# HTTP API reference

`lucidd` exposes three HTTP surfaces on loopback (`127.0.0.1:11434` by default for CLI; `127.0.0.1:11435` for LUCID Desktop's managed sidecar):

1. **Ollama-compatible inference API (`/api/*`)** — loopback-only, unauthenticated for compatibility with existing Ollama clients (including Open WebUI and OpenCode).
2. **OpenAI-compatible inference API (`/v1/chat/completions`, `/v1/models`)** — loopback-only, sharing the exact same routing, fair queue, signed-manifest, and Ed25519 receipt-verification pipeline for coding agents like Pi and OpenCode.
3. **LUCID private control API (`/api/lucid/*`)** — loopback-only, requires `Authorization: Bearer <64-hex-token>` (verified in constant time) and returns `Cache-Control: no-store`.

> [!TIP]
> Looking for ready-to-paste client configs instead of wire schemas? See [Connect Open WebUI, Pi and OpenCode](apps-and-agents.md).

## Global transport and security guards

- **Loopback bind enforcement:** `lucidd` refuses non-loopback `LUCIDD_HOST` values at startup (only `127.0.0.1` and `::1` are permitted).
- **DNS-rebinding `Host` guard:** Missing, duplicated, or non-loopback `Host` headers (or URI authorities) return `403 Forbidden`. Allowed hosts: `localhost`, `127.0.0.1`, `[::1]` (with optional `:port`). On the Ollama/OpenAI inference surfaces (never on `/api/lucid/*`), `host.docker.internal` is also permitted so containerized clients such as Docker Open WebUI work cleanly.
- **Loopback CORS:** Allows `http`/`https` origins on `localhost`/`127.0.0.1`/`::1`/`[::1]`, methods `GET`/`POST`, request headers `Content-Type`, `Authorization`, `x-lucid-local-only`, and exposes `x-phase-worker`, `x-lucid-routed-via`, `x-lucid-route-explanation`, `x-lucid-receipt-verified`, `x-lucid-trust-label`, `x-phase-receipt`.
- **Body & input bounds:** Default HTTP request body cap is **`4 MiB`** (`4,194,304` bytes); combined local prompt + tool input is capped at **`1.5 MiB`** (`1,572,864` bytes). Requests routed to a remote peer over `/phase/job-relay/2.0.0` enforce the **`256 KiB`** P2P relay manifest cap and return a clean `400 Bad Request` before dialing if oversized. Tighter per-route caps for `/api/lucid/*` are listed below.
- **Whole-request deadline:** HTTP/relay manifest TTL and Desktop chat client timeout are `10 minutes` (fitting up to `120s` queue wait + `180s` first-token prefill + decode, while staying within the `15-minute` remote manifest ceiling).

## Custom HTTP headers and trust labels

### Request headers

| Header | Values | Effect |
|---|---|---|
| `X-Lucid-Local-Only` | `1`, `true`, `yes`, `on` (case-insensitive) | Refuses remote peer routing **and** refuses RPC-offloaded (`trusted-circle-sharded`) execution (`503`). Under automatic Slice Quorum, enforced per model: models whose active plan fits 100% locally still run locally; models whose active plan uses helpers are refused. |
| `Authorization` | `Bearer <64-hex-token>` | Required on all `/api/lucid/*` control endpoints (`401` on failure). |

### Response headers, HTTP trailers, and terminal fields

| Header / Field | Where Sent | Values & Meaning |
|---|---|---|
| `X-Lucid-Routed-Via` | Response header | `"local"`, `"peer"`, or `"trusted-circle-sharded"` (omitted on refusal; never leaks a peer ID). |
| `X-Lucid-Route-Explanation` | Response header | Sanitized ASCII routing summary (≤192 B; alphanumeric runs >32 chars redacted to `[redacted]`). |
| `X-Lucid-Receipt-Verified` | Response header & terminal NDJSON (`x_lucid_receipt_verified`) | `"pending"` on initial peer stream headers; final verdict `"true"`, `"false"`, or `"unverifiable"` (omitted on local path). |
| `X-Lucid-Trust-Label` | Initial header, HTTP trailer (`Trailer: x-lucid-trust-label`), & terminal NDJSON (`x_lucid_trust_label`) | One of the five canonical `TrustLabel` values below. |
| `Retry-After` | `503 Service Unavailable` busy & quorum responses | `"5"` (seconds) when the Prompt Queue or caller share is full, or when a sliced model's quorum is not met (`cluster quorum not met: ...`). |
| `X-Phase-Worker` | Streaming `/api/chat` & `/api/generate` | `"lucidd"`. |
| `X-Phase-Receipt` | Non-streaming `/api/chat`, `/api/generate`, `/api/embed`, `/api/embeddings` | Base64-encoded 32-byte `output_commitment`. |
| `x_phase_commitment` | Terminal NDJSON on streaming `/api/chat` & `/api/generate` | 64-hex SHA-256 streaming output commitment. |
| `x_lucid_status` | Empty-content NDJSON progress frame on `/api/chat` & `/api/generate` | Advisory queue/progress metadata (`{phase: "queued"\|"dispatched", position?, depth?, message}`). |

### The five `X-Lucid-Trust-Label` values

1. `local` — executed locally on this machine without RPC offload.
2. `remote-pending` — initial header on a streaming peer job before terminal receipt verification completes.
3. `remote-receipt-verified` — terminal Ed25519 `SignedReceipt` verified against manifest hash, delivering `PeerId`, and replayed chunk commitment.
4. `remote-spot-checked` — receipt verified **and** a deterministic redundant spot-check peer agreed on the commitment.
5. `trusted-circle-sharded` — executed across opted-in Tier-1 Trusted-Circle GPUs (RPC offload or `/api/lucid/cluster/execute`).

## Prompt queue and busy responses

Both `/api/*` and `/v1/*` share one fair FIFO **`SlotQueue`** (`1` active GPU slot by default; depth `16` total with `4` local-reserved slots, `2` per remote peer, and `120s` wait cap):

- **While waiting (Ollama NDJSON):** `lucidd` emits empty-content keepalive frames carrying `x_lucid_status` (for example, `{"done": false, "message": {"role": "assistant", "content": ""}, "x_lucid_status": {"phase": "queued", "position": 2, "depth": 3, "message": "Waiting for an open slot (position 2 of 3)"}}`). Standard Ollama clients ignore empty deltas cleanly while LUCID Desktop renders live queue status.
- **While waiting (OpenAI SSE):** `lucidd` emits SSE comment heartbeats (`: ...`) so coding agents and HTTP proxies keep the stream alive until the slot opens.
- **When full or timed out:** Returns `503 Service Unavailable` with `Retry-After: 5` (formatted in OpenAI's `{"error": {...}}` envelope on `/v1/*`).

## Ollama-compatible endpoints

| Method & Path | Request Shape & Limits | Response Shape |
|---|---|---|
| `GET /` | None | `200 text/plain`: `"lucidd ready: see /api/version"` |
| `GET /api/version` | None | `200`: `{"version": "<crate-version>"}` |
| `GET /api/tags` | None (serves startup cache immediately without blocking on DHT; omits local models whose Slice Quorum is not ready) | `200`: `{"models": [{name, model, modified_at, size (integer; 0 if unavailable), digest ("sha256:<cid>"), details: {format?, family, families, parameter_size, quantization_level}, x_lucid_access? ("authorized"\|"access_not_confirmed")}]}` |
| `POST /api/show` | `{model?, name?}` | `200`: `{details, capabilities (includes "tools" for llama.cpp models), model_info: {"phase.model_cid", "phase.backend", "phase.context_length", "phase.max_concurrent", "phase.advertised_at", "phase.valid_until", "phase.verification"?, "phase.size_bytes"?, "phase.installed_at"?}}`. `404` unknown, `409` ambiguous alias. |
| `GET /api/ps` | None | `200`: `{"models": [{name, model, digest?}]}`. Reports only live, health-verified models; omits unknown `size`/`size_vram`/`expires_at`. |
| `POST /api/chat` | `{model, messages?: [{role, content? (nullable), tool_calls?, tool_call_id?, tool_name?, thinking?}], stream? (default true), tools?, tool_choice?, think?, options?}` (`deny_unknown_fields`). Rejects (`400`) `keep_alive`, `format`, `images`, invalid roles (only `system\|user\|assistant\|tool`), or oversized input (> `1.5 MiB` local / > `256 KiB` peer relay). | Streaming (`application/x-ndjson`): delta lines `{model, created_at, message: {role:"assistant", content}, done: false}`, optional empty-content `x_lucid_status` queue frames, and terminal line `{..., message: {..., tool_calls? (JSON-object arguments, id, function.index)}, done: true, done_reason ("stop" for normal & tool turns), total_duration, prompt_eval_count, eval_count, eval_duration, x_lucid_receipt_verified?, x_phase_commitment?, x_lucid_trust_label?}` + trailer. Tool calls are released **only** after terminal receipt + contract verification passes. |
| `POST /api/generate` | `{model, prompt?, stream? (default true), options?}` (token-only; no tools). Rejects (`400`) `system`, `keep_alive`, `raw`, `suffix`, `images`, `template`, or oversized input. | Same streaming/non-streaming contract as `/api/chat`, with `"response"` and `"context": []`. |
| `POST /api/embed` | `{model, input?: string \| string[]}`. Rejects (`400`) `truncate`, `dimensions`, `keep_alive`, `options`, >128 inputs, >262,144 total chars. Non-streaming only. | `200`: `{"model", "embeddings": [[f32, ...], ...]}` + `X-Phase-Receipt`. |
| `POST /api/embeddings` | `{model, prompt?}`. Non-streaming only. | `200`: `{"model", "embedding": [f32, ...]}` + `X-Phase-Receipt`. |
| `POST /api/pull` | `{model?, name?, stream? (default true), cid? (64-hex), publisher? (PeerId)}` | Imports local `<model_dir>/<name>.gguf` if present & unpinned, else verified P2P pull. Streaming NDJSON emits `resolving`, `selecting_provider`, `downloading`, `verifying`, `installing`, `registering`, `success`/`error`. |

### Allowed `options` on `/api/chat` and `/api/generate`

Only the following keys are permitted inside `options` (unknown keys return `400 Bad Request`):

- `num_predict` (`1..=8192`, default `4096`, clamped by `policy.toml` `max_tokens_ceiling`)
- `temperature`, `top_p`, `top_k`, `min_p`, `seed`, `stop`, `repeat_penalty` / `repetition_penalty`, `presence_penalty`, `frequency_penalty`

## OpenAI-compatible endpoints (`/v1/*`)

Built for coding agents (`Pi 1.6.1`, `OpenCode 2.4.2`, SDK clients) over the exact same signed-manifest, fair-queue, and receipt-verification pipeline. Unknown fields are rejected fail-closed (`400 Bad Request`) using the OpenAI `{"error": {"message", "type", "param", "code"}}` envelope.

| Method & Path | Request Shape & Limits | Response Shape |
|---|---|---|
| `GET /v1/models` | None (same catalog as `/api/tags`; omits local models whose Slice Quorum is not ready) | `200`: `{"object": "list", "data": [{"id", "object": "model", "created", "owned_by"}]}` |
| `POST /v1/chat/completions` | `{model, messages: [{role ("system"\|"developer"\|"user"\|"assistant"\|"tool"), content (string, null, or text parts), name?, tool_calls?, tool_call_id?}], stream? (default false), stream_options?: {include_usage?}, store? (false ok; true rejected 400), max_tokens?, max_completion_tokens?, temperature?, top_p?, top_k?, min_p?, repeat_penalty?, presence_penalty?, frequency_penalty?, seed?, stop?, tools?, tool_choice?, parallel_tool_calls?, n? (must be 1), user?}` | Non-streaming (`stream: false`): `chat.completion` JSON with `choices[0].message.tool_calls` (JSON-**string** `arguments`), `finish_reason: "stop" \| "tool_calls" \| "length"`, and real `llama.cpp` `usage` (`prompt_tokens`, `completion_tokens`, `total_tokens`). Streaming (`stream: true`): `text/event-stream` (`data: {...}\n\n` ... `data: [DONE]\n\n`) with SSE queue heartbeats, optional final usage chunk (`stream_options.include_usage: true`), and `X-Lucid-Trust-Label` HTTP trailer. |

### Shared tool-calling bounds and receipt gate

Enforced identically at the HTTP edge, in inbound P2P relay admission, and in `llama-cpp`:

- **Bounds:** max `64` tools, `[A-Za-z0-9_.-]{1,128}` function names, `4 KiB` descriptions, `16 KiB` / depth-`16` object schemas (`64 KiB` total), `32` calls per message/turn, `128`-byte call IDs, `32 KiB` arguments per call (`128 KiB` per turn).
- **Receipt + contract gate:** Tool calls are buffered and released **only** after a valid `SignedReceipt` matches the manifest, signer/delivering `PeerId`, and replayed chunks, and satisfies `ToolCallPolicy` (`tool_choice`, declared function names, unique non-empty IDs, and `parallel_tool_calls: false` one-call cap).
- **Backend compatibility:** Tool requests route exclusively to `llama.cpp` models; `mlx` and `echo` fail closed with `400 Bad Request`.

## LUCID private control endpoints (`/api/lucid/*`)

All routes below require `Authorization: Bearer <token>`, enforce strict loopback `Host` (`host.docker.internal` is NOT allowed), and return `Cache-Control: no-store`. Request structs enforce `deny_unknown_fields`.

### Status, discovery, telemetry, and models

| Method & Path | Cap | Request | Response |
|---|---|---|---|
| `GET /api/lucid/status` | — | None | `{state ("connected"\|"connecting"\|"offline"), peer_count, active_path, model_count, enrollment: {state, message}, onboarding_completed, providing_enabled, cluster_enabled, providing_models, paused_reason, policy}` |
| `GET /api/lucid/peers` | — | None | `{peer_count, active_path, nat, peers: [{peer_id, path, authorized}]}` |
| `GET /api/lucid/telemetry` | — | None | Strictly metadata-only live Activity Monitor snapshot (never includes prompts, replies, PeerIds, or IPs): `{timestamp_ms, active_requests, recent_requests (max 16), queue (SlotQueue counters), cluster: {cluster_enabled, active_rpc_offload, tensor_split, local_backend, local_slice_pct, local_slices (u32 \| null), quorum ({required, online, state} \| null), resident_models, helpers: [{label ("Helper 1"..), slice_pct, slices? (u32 when quorum active), path, active_tunnels, tx_bytes, rx_bytes}]}}` |
| `GET /api/lucid/probe` | — | None | `SystemProbe` (`{hardware, existing_inference, runtime, discovered_models, onboarding_completed, providing_enabled}`) |
| `POST /api/lucid/probe/refresh` | `1 KiB` | Empty | Fresh `SystemProbe` |
| `GET /api/lucid/models` | — | None | `{models: [{id, name, cid, source ("local"\|"ollama"\|"lmstudio"\|"network"), size_bytes, quantization, peer_count, on_device, available_locally, providing, can_request, fits_hardware, local_path}], model_dirs, providing_enabled, onboarding_completed}` |
| `GET /api/lucid/runtime` | — | None | `{hardware, runtime}` (pinned `llama.cpp b12651` status) |

### Permission-gated mutations and settings

#### `POST /api/lucid/provide`
- **Cap:** `4 KiB` · **Gate:** requires `confirm_permission: true` when `enable: true` (else `428 Precondition Required`).
- **Request:** `{model_name, enable, confirm_permission?, make_available_locally?, local_path?}`
- **Response:** `{providing_enabled, approved_provide_models, imported_cid, runtime_ready, restart_required}`

#### `POST /api/lucid/pull`
- **Cap:** `4 KiB`
- **Request:** `{model, cid?, publisher?}`
- **Response:** `200`: `{status: "installed", model_id, cid, size_bytes}` (`503` if content plane disabled, `502` on transfer failure).

#### `POST /api/lucid/folders`
- **Cap:** `4 KiB`
- **Request:** `{action: "add" | "remove", path}` (runs `validate_model_dir` on add)
- **Response:** `{model_dirs, probe}`

#### `POST /api/lucid/settings`
- **Cap:** `4 KiB` (read current values via `GET /api/lucid/status` and `GET /api/lucid/cluster`)
- **Request:** `{onboarding_completed?, manual_pause?, auto_pause_on_battery?, thermal_limit_c?: f32 | null (40..=105), serve_model_content?, cluster_enabled?, cluster_rpc_peers?, cluster_tensor_split?: string | null, cluster_helper_budget_bytes?: u64 | null, cluster_auto_split?: bool, cluster_slice_overrides?: {"<64-hex-cid>": 2..=16}}`
  - **Nullable clears:** Omitting `cluster_tensor_split` or `cluster_helper_budget_bytes` leaves the current value unchanged. Passing `cluster_tensor_split: null` (or `""`) clears a manual split; setting a non-empty manual split turns `cluster_auto_split` off, while setting `cluster_auto_split: true` clears `cluster_tensor_split`. Passing `cluster_helper_budget_bytes: null` or `0` returns the helper to `Auto` (measured safe budget minus `1 GiB`); otherwise validated in `1 GiB..=1 TiB`.
  - **Live vs restart:** `cluster_helper_budget_bytes` and `cluster_slice_overrides` (max `64` entries) apply live; changing `cluster_enabled`, `cluster_rpc_peers`, `cluster_tensor_split`, or `cluster_auto_split` sets `restart_required: true`.
- **Response:** `{onboarding_completed, serve_model_content, cluster_enabled, cluster_rpc_peers, cluster_tensor_split, cluster_helper_budget_bytes, cluster_auto_split, cluster_slice_overrides, restart_required, policy: {manual_pause, auto_pause_on_battery, thermal_limit_c}}`

#### `POST /api/lucid/runtime/setup`
- **Cap:** `4 KiB` · **Gate:** requires `confirm_permission: true` (else `428`).
- **Request:** `{action: "pin_detected" | "download_pinned", confirm_permission?}`
- **Response:** `{detail, runtime}` (serialized via `runtime_lock`; persists `llama_server_binary` and `llama_server_sha256` to `node.toml`).

### Circle enrollment and invitations

#### `POST /api/lucid/invitations`
- **Cap:** `1 KiB`
- **Request:** `{ttl_seconds? (default 900, range 1..=3600)}`
- **Response:** `201 Created`: `{invitation ("lucid://join/..."), expires_at, grant_expires_at}` (`409 Conflict` if node has neither local models nor `shard_stage_bridge_port`).

#### `POST /api/lucid/enroll`
- **Cap:** `16 KiB`
- **Request:** `{invitation}`
- **Response:** `202 Accepted`: `{state, message}` (`400` on invalid/expired link).

### Tier-1 Trusted-Circle cluster endpoints

#### `GET /api/lucid/cluster`
- **Response:** `{cluster_enabled, cluster_rpc_peers, cluster_tensor_split, cluster_helper_budget_bytes, cluster_auto_split, cluster_slice_overrides, quorum: [{model, model_cid, ctx_size, required_slices, online_slices, state ("waiting"|"ready"|"loading"|"blocked"), reason, slice_bytes, local_slices, helpers: [{label ("Helper 1"..), slices, backend, status ("online"|"stale"|"refused"|"update_required")}]}], active_rpc_offload, shard_stage_bridge_configured, trust_tier: "trusted-circle", trust_label: "trusted-circle-sharded", untrusted_sharding_allowed: false, local_node, connected_peers, models}`

#### `POST /api/lucid/cluster/rebalance`
- **Cap:** `1 KiB` · **Gate:** returns `409 Conflict` when automatic Slice Quorum planning is not active on this node (e.g. `cluster_enabled = false`, manual `cluster_tensor_split`, or CLI RPC flags override `node.toml`).
- **Request:** Empty
- **Response:** Immediately polls eligible helpers, repacks every sliced model onto the best current plan (waiting up to `20s`), and returns the updated `GET /api/lucid/cluster` JSON payload.

#### `POST /api/lucid/cluster/plan`
- **Cap:** `16 KiB` · **Gate:** rejects non-`trusted-circle` tiers and unverified `model_path` with `403 Forbidden`.
- **Request:** `{model_name, model_path?, model_cid_hex?, total_layers?, size_bytes?, trust_tier?, peers: [PeerShardCapacity]}`
- **Response:** `{verified: true, required_memory_bytes, signed_plan}`

#### `POST /api/lucid/cluster/execute`
- **Cap:** `4 MiB` · **Gate:** requires live `cluster_enabled == true` and `trust_tier == "trusted-circle"` (else `403`).
- **Request:** `{job_id?, signed_plan, input_base64, per_stage_timeout_ms? (default 30000, clamped 500..=60000)}`
- **Response:** `{verified: true, trust_label, job_id, output_base64, verification, receipts}` + `X-Lucid-Trust-Label: trusted-circle-sharded`.

## Phase Artifact Server HTTP API (`phase-artifact-server`)

Standalone content-addressed HTTP/1.1 & HTTP/2 server (plaintext, unauthenticated; designed for LAN/trusted artifact distribution and Phase Boot):

| Route | Purpose |
|---|---|
| `GET /`, `/health`, `/status` | Service health and store summary |
| `GET /manifest.json` | Store manifest |
| `GET /blobs/:prefix/:filename` | Immutable content-addressed blob with `Range: bytes=start-end` / `206 Partial Content` and `X-Artifact-Hash` |
| `GET /:channel/:arch/manifest.json`, `/:channel/:arch/:artifact` | Channel/architecture Phase Boot images with HTTP `Range` support |
