# LumanexAI API Reference

Integrate LumanexAI into your own application, website, or backend. The API gives an authenticated user access to AI chat with streaming, document retrieval (RAG), presentation generation, an optional code assistant, and supporting utilities — all acting **on behalf of the user**, with the user's own access token.

This reference is written for developers building legitimate integrations. Every call is authenticated with a per-user token, and every operation is scoped to that user's own data.

---

## 1. Overview

| Area | Typical integration use |
|------|--------------------------|
| **Auth** | Login, session, optional passkey (WebAuthn) |
| **Chat** | Sessions, messages, SSE streaming, attachments, regeneration variants, projects |
| **Memory** | Read/write the user's persistent memory (where enabled by the plan) |
| **Documents (RAG)** | Upload documents for personal/group retrieval |
| **Presentations** | Generate and download presentations |
| **Code Assistant** | Inspect and edit code workspaces (where enabled for the user) |
| **Code Execution** | Run Python / JavaScript / Bash in a sandbox and capture output |
| **OpenAI-compatible API** | Stateless chat completions with native tool calling, JSON Schema output, SSE streaming and inline documents; models; embeddings; transcriptions — reachable with an **API key** |

Integrate **only** the endpoints described in this guide, always with the **user's token**. Internal and administrative endpoints are out of scope and not documented here.

If your product exposes LumanexAI to other people, read §18 (compliance, transparency and integrator responsibilities): roles, the notice you owe your end users, content marking, acceptable use and reporting.

---

## 2. Base URL

All paths in this document are **relative** to the base URL:

```
https://app.lumanex.it/ai
```

For example, the full login endpoint is `POST https://app.lumanex.it/ai/auth/login`.

If you have been provided with a dedicated environment or URL, use that base instead — the path structure is identical.

---

## 3. Authentication

### 3.1 Model

After login, the server returns an opaque **session token**. Every subsequent request carries it in the `Authorization` header:

```http
Authorization: Bearer YOUR_TOKEN
```

Store the token securely (encrypted storage on mobile, an httpOnly cookie if you run your own backend). Never place it in a query string or an unencrypted log.

### 3.2 Login

| | |
|---|---|
| **Method / path** | `POST /auth/login` |
| **Auth** | None |
| **Content-Type** | `application/json` |

**Body:**

```json
{
  "username": "user",
  "password": "pass"
}
```

**Response (200):**

```json
{
  "token": "YOUR_TOKEN",
  "user": {
    "id": 1,
    "username": "user",
    "name": "Jane Doe",
    "role": "user",
    "allowed_apps": ["chat", "dataset"]
  }
}
```

`allowed_apps` lists the product areas enabled for that user. Use it to show or hide features in your UI.

The `username` field accepts the account username only and is matched
case-insensitively. The email address is used for registration and account
recovery, not to sign in.

### 3.3 Create an account

| | |
|---|---|
| **Method / path** | `POST /auth/register` |
| **Auth** | None |
| **Content-Type** | `application/json` |

Creates a standard user account through self-service registration. The new account is assigned the base set of apps available on its plan.

> **Email verification required.** Self-service registration creates the account in a **pending** state: a confirmation link is emailed to the address provided (valid for **72 hours**) and **the account cannot sign in until it is confirmed**. Pending accounts not confirmed within 72 hours are **deleted automatically**. The `email` must therefore be a real, reachable mailbox.

**Body:**

```json
{
  "name": "Jane Doe",
  "username": "jane.doe",
  "email": "jane@example.com",
  "password": "secret123"
}
```

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `name` | string | Yes | Display name. Leading/trailing whitespace is trimmed. |
| `username` | string | Yes | Normalized to lowercase. Allowed characters: `a-z`, `0-9`, `.`, `_`, `-`. |
| `email` | string | Yes | A real mailbox: the confirmation link is sent here. Normalized to lowercase. |
| `password` | string | Yes | Minimum 6 characters. |

**Response (201):**

```json
{
  "ok": true,
  "pending": true,
  "message": "Account created. Check your email and confirm your address (link valid for 72 hours) to sign in."
}
```

`pending: true` means email confirmation is required before login. Registration does **not** return a session token.

**Recommended flow:**

1. `POST /auth/register` with the account details.
2. Tell the user to check their inbox and open the confirmation link.
3. The link (`GET /auth/verify?token=…`) activates the account.
4. `POST /auth/login` to obtain the `token` and user payload. Before confirmation, login returns `403`.
5. If `user.first_login` is `true`, show any onboarding, then call `POST /auth/first-login-seen` with the bearer token.

**Common errors:**

| Code | Example body | When |
|------|--------------|------|
| `400` | `{"error":"Name, username and password are required."}` | A required field is missing. |
| `400` | `{"error":"Password must be at least 6 characters."}` | Password too short. |
| `400` | `{"error":"Invalid username."}` | Username contains disallowed characters. |
| `403` | `{"error":"Account not confirmed yet…"}` | Login attempted before email confirmation. |
| `409` | `{"error":"Username already in use."}` | The username is taken by a confirmed account. |
| `429` | `{"error":"Too many registrations…"}` | Per-IP registration rate limit. |

### 3.4 Confirm first login

| | |
|---|---|
| **Method / path** | `POST /auth/first-login-seen` |
| **Auth** | Bearer required |

Marks the first-login onboarding as seen for the authenticated user. Newly registered users start with `first_login: true`.

**Response (200):** `{ "ok": true }`

### 3.5 Current session

| | |
|---|---|
| **Method / path** | `GET /auth/me` |
| **Auth** | Bearer required |

Returns the user profile **without sensitive data** — useful to validate a token and read the profile.

### 3.6 Logout

| | |
|---|---|
| **Method / path** | `POST /auth/logout` |
| **Auth** | Bearer |

Invalidates the server-side session where supported.

### 3.7 Passkeys (WebAuthn)

A standard multi-step WebAuthn flow is available:

- `GET /auth/passkey/status`
- `POST /auth/passkey/lookup`
- `POST /auth/passkey/register/options` then `POST /auth/passkey/register/verify`
- `POST /auth/passkey/auth/options` then `POST /auth/passkey/auth/verify`
- `DELETE /auth/passkeys`
- `DELETE /auth/passkeys/{credential_id}`

Implement the client side with your browser/SDK WebAuthn helpers; payloads follow the FIDO2 protocol.

### 3.8 Sign in with LumanexAI (OAuth 2.0 / OpenID Connect)

LumanexAI can act as an **identity provider** for your own applications, exactly like "Sign in with Google/GitHub/Apple": users sign in (or register) once on LumanexAI, then enter your app with one click — and your app can call the LumanexAI APIs **on their behalf**, without ever handling their password.

The supported flow is **Authorization Code + PKCE (S256)**. PKCE is mandatory for `public` clients (SPA / mobile) and recommended for `confidential` clients (server-side backends with a `client_secret`).

**Endpoints:**

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/.well-known/openid-configuration` | OIDC discovery document (issuer, endpoints, algorithms) |
| `GET` | `/.well-known/jwks.json` | Public RS256 keys to verify `id_token`s |
| `GET` | `/oauth/authorize` | Starts the flow: login/consent UI, redirects back with a `code` |
| `POST` | `/oauth/token` | Exchanges the code for tokens; refreshes tokens (form-urlencoded) |
| `GET` | `/oauth/userinfo` | OIDC claims for the user (Bearer access token) |
| `GET` / `PUT` | `/oauth/mascot` | Read (`lumanex.mascot`) and update (`lumanex.mascot.write`) the user mascot (`m1.*`) |
| `POST` | `/oauth/revoke` | Revokes an access or refresh token (RFC 7009) |
| `POST` | `/oauth/introspect` | Token status — confidential clients only (RFC 7662) |
| `GET` | `/oauth/logout` | RP-Initiated Logout: ends the LumanexAI SSO session (account switch / federated logout) |

#### 3.8.1 Registering your app

OAuth clients are provisioned by your LumanexAI administrator. Provide:

- **App name** (shown on the consent screen).
- **Client type** — `public` (SPA/mobile, no secret, PKCE required) or `confidential` (backend; you receive a `client_secret` **once** at creation — store it securely, only a hash is kept server-side).
- **Redirect URIs** — HTTPS (or `http://localhost` for development, or a mobile app scheme). Matching at authorize time is **exact**: unregistered URIs are rejected.
- **Allowed scopes** (see below) and whether the app is **trusted** (first-party apps skip the consent screen; third-party apps show it once, the consent is then remembered).
- **`initiate_login_uri`** (optional) — where to send a user back after they register from your app's authorize page and confirm their email. See §3.8.7.

#### 3.8.2 Scopes

| Scope | Grants |
|-------|--------|
| `openid` | Stable `sub` identifier + `id_token`; enables `/oauth/userinfo` |
| `profile` | `name`, `preferred_username` (+ access to `GET /auth/me`) |
| `email` | `email`, `email_verified` |
| `lumanex.mascot` | `mascot`, `mascot_custom`, `mascot_updated_at` in `/oauth/userinfo`, `id_token` and `GET /oauth/mascot` |
| `lumanex.mascot.write` | Includes read access and enables `PUT` / `POST /oauth/mascot` (`{"mascot": "m1....", "only_if_unset": false}`, rate-limited to 20/min and 60/h per user) |
| `lumanex.chat` | Chat API (`/chat/*`, code/chart execution), downloads of the files the assistant publishes (`/doc_download/*`), `/v1/chat/completions`, `/v1/models`, `/v1/embeddings` (text and image/audio/video inputs) |
| `lumanex.memory` | Memory API (`/memory/*`) |
| `lumanex.documents` | Documents API / RAG (`/docs*`) |
| `lumanex.presentations` | Presentations API (`/presentazioni/*`) |
| `lumanex.code` | Code Assistant API (`/code/*`), every Code Agent route of a chat (`/chat/sessions/{sid}/code-agent/*`: runs, events, resume, cancel, rollback, queue), the answers to a waiting command (`/chat/sessions/{sid}/ssh-agent-auth`), runbooks (`/one-click-fix`, `/execute-runbook`), the command ledger (`/agent-trace`), the synced local folder (`/chat/local-ws/*`), the bus between chats (`/chat/intersession/*`, `/chat/sessions/{sid}/intersession*`) and Code turns asked on `/chat/sessions/{sid}/message` (`X-Chat-Code-Agent` / `X-Chat-WS` headers or a workspace pack in the message: without this scope `403` `insufficient_scope`, `required_scope: "lumanex.code"`) |

OAuth access tokens only reach the endpoints covered by the granted scopes (server-side allowlist). Everything else — account settings, administration, and any endpoint not listed above — stays reserved to first-party sessions and answers `401` to an OAuth token.

Some actions stay with the user even inside a granted scope; an OAuth token or an API key gets `403` with the code shown: approving a web confirmation or giving login values (`third_party_approval_refused`: a third party can only refuse, `{"approved": false}`), the chat's browser panel `/chat/sessions/{sid}/web/browser/*` (`browser_first_party_only`), rewriting a waiting command with `edited_action` (`edited_action_first_party_only`), turning on the `unrestricted` Code mode (`unrestricted_first_party_only`; an `X-Chat-Code-Agent-Mode: unrestricted` header is ignored), creating, changing, duplicating a server profile or forgetting its host key (`POST /code/ssh`, `PUT /code/ssh/{id}`, `/duplicate`, `/reset-host-key`: `ssh_profile_first_party_only`), the message queue `/chat/sessions/{sid}/chat-queue/*` (`chat_queue_first_party_only`; when too many turns are running a third party gets the plain `429`, without the «queue» offer).

#### 3.8.3 Integration example (server-side web app)

**1) Redirect the user to the authorize URL** (generate and store `state` and the PKCE `code_verifier` in the user's session first):

```
https://app.lumanex.it/ai/oauth/authorize
  ?client_id=lxc_abc123
  &redirect_uri=https%3A%2F%2Fyourapp.example.com%2Fauth%2Flumanex%2Fcallback
  &response_type=code
  &scope=openid%20profile%20email%20lumanex.chat
  &state=RANDOM_STATE
  &nonce=RANDOM_NONCE
  &code_challenge=BASE64URL(SHA256(code_verifier))
  &code_challenge_method=S256
```

The user signs in on LumanexAI with username and password or with a passkey (in any browser with WebAuthn, also the passkey on their phone via QR code — useful on devices that cannot save credentials, such as a car or a TV), or is recognized via SSO; registers there if needed (email confirmation included), approves the scopes, and lands back on your `redirect_uri` with `?code=...&state=...`.

**2) In your callback, validate `state`, then exchange the code:**

```bash
curl -X POST https://app.lumanex.it/ai/oauth/token \
  -u "lxc_abc123:YOUR_CLIENT_SECRET" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=THE_CODE" \
  -d "redirect_uri=https://yourapp.example.com/auth/lumanex/callback" \
  -d "code_verifier=THE_CODE_VERIFIER"
```

**Response (200):**

```json
{
  "access_token": "lxoa_...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "openid profile email lumanex.chat",
  "refresh_token": "lxor_...",
  "id_token": "eyJhbGciOiJSUzI1NiIs..."
}
```

Verify the `id_token` (RS256) against `/.well-known/jwks.json`, checking `iss`, `aud` (your `client_id`), `exp` and `nonce`. Claims include `sub` (stable user id), `email`, `email_verified`, `name`, `preferred_username`.

**3) Call the APIs with the access token** — same as a normal session token:

```bash
curl -X POST https://app.lumanex.it/ai/chat/sessions \
  -H "Authorization: Bearer lxoa_..."
```

**4) Refresh** (rotation: **every** refresh returns a new `refresh_token`; discard the old one — reusing a rotated token revokes the whole grant as a security measure, except during the 30 seconds after the rotation, see below):

```bash
curl -X POST https://app.lumanex.it/ai/oauth/token \
  -u "lxc_abc123:YOUR_CLIENT_SECRET" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=lxor_..."
```

**5) Disconnect** (e.g. the user unlinks your app):

```bash
curl -X POST https://app.lumanex.it/ai/oauth/revoke \
  -u "lxc_abc123:YOUR_CLIENT_SECRET" \
  -d "token=lxor_..."
```

For a **SPA / mobile app** (`public` client) the flow is identical without `-u`: pass your `client_id` in the body and PKCE acts as the client authentication. `/oauth/token`, `/oauth/revoke`, `/oauth/userinfo` and the `/.well-known/*` documents are callable cross-origin (CORS enabled, no cookies involved).

#### 3.8.4 Forcing re-authentication and switching account

By default, if the user already has an active LumanexAI session in their browser, the authorize endpoint recognizes them via SSO and can return to your app without a fresh login. When your app offers a **"switch account"** or **"log in as someone else"** action, ask LumanexAI **not** to reuse that session with the OIDC `prompt` and `max_age` parameters on the authorize URL:

| Parameter | Effect |
|-----------|--------|
| `prompt=login` | Always shows the login screen; the already signed-in user is **never** auto-authorized. |
| `prompt=select_account` | Shows the login screen so the user can choose / enter a different account. |
| `prompt=consent` | Re-displays the consent screen even for trusted apps and already-granted scopes. |
| `prompt=none` | No UI at all: silently returns a `code` if possible, otherwise `login_required` / `consent_required`. Not combinable with the values above. |
| `max_age=<seconds>` | Requires the user's authentication to be at most N seconds old, otherwise re-auth is forced. `max_age=0` always forces a fresh login. |

The `id_token` carries `auth_time` (epoch seconds of the actual authentication), so your app can independently verify `max_age` compliance. The values honored by the server are advertised in discovery as `prompt_values_supported: ["login", "select_account", "consent", "none"]`.

**Federated logout (`end_session_endpoint`).** To clear the LumanexAI SSO session before switching accounts — so the next authorize really starts from a blank login screen — send the user to:

```
https://app.lumanex.it/ai/oauth/logout
  ?client_id=lxc_abc123
  &post_logout_redirect_uri=https%3A%2F%2Fyourapp.example.com%2Fafter-logout
  &state=RANDOM_STATE
```

This ends the LumanexAI browser session and, if `post_logout_redirect_uri` is a **registered** redirect URI of your client, redirects back there with your `state` (unregistered URIs are ignored — a "signed out" page is shown instead). `id_token_hint` is accepted as an alternative to `client_id`. Note this clears only the LumanexAI SSO session; it does **not** revoke your app's tokens — call `/oauth/revoke` for that.

#### 3.8.5 OAuth error responses

Errors follow RFC 6749: `{"error": "...", "error_description": "..."}`.

| `error` | Meaning |
|---------|---------|
| `invalid_request` | Missing/malformed parameter (e.g. missing `state` or PKCE challenge) |
| `invalid_client` | Unknown/disabled `client_id` or wrong `client_secret` (HTTP 401) |
| `invalid_grant` | Code invalid/expired/already used, PKCE verification failed, refresh token revoked or reused |
| `unsupported_grant_type` | Only `authorization_code` and `refresh_token` are supported |
| `invalid_scope` | Scope unknown or not allowed for your client |
| `access_denied` | The user denied consent (or the account is not eligible) |
| `login_required` | `prompt=none` was requested but interactive login is needed (no SSO session, or re-auth forced by `prompt=login`/`select_account`/`max_age`) |
| `consent_required` | `prompt=none` was requested but the consent screen is needed (missing grant or `prompt=consent`) |
| `slow_down` | Rate limit hit on authorize/token (HTTP 429) |

Authorize errors with an **unregistered** `redirect_uri` never redirect: an error page is shown instead (anti open-redirect).

#### 3.8.6 Security notes

- `state` is required and must be validated by your app at the callback (CSRF protection).
- PKCE S256 is required for public clients; the `plain` method is not supported.
- Authorization codes are single-use and expire after ~2 minutes.
- Access tokens are opaque (`lxoa_`, ~1 hour); refresh tokens (`lxor_`, ~30 days) rotate on every use with reuse detection. A 30-second grace window (`OAUTH_REFRESH_REUSE_GRACE_S`, 0 = off) tolerates two refreshes in flight with the same token, or a retry after a lost response: each gets a new valid token set and the grant is not revoked. Still serialize refreshes per user and store the **last** pair you received.
- Never place tokens in URLs or logs; token responses are served with `Cache-Control: no-store`. OAuth access tokens are only accepted from the `Authorization` header.
- Token exchange happens server-to-server (or via PKCE): the user's LumanexAI password never transits through your app.

#### 3.8.7 Returning to your app right after registration (`initiate_login_uri`)

If a user doesn't have a LumanexAI account yet and registers from the "Register" form embedded in your app's `/oauth/authorize` page, LumanexAI by default:

1. emails them a confirmation link (`/auth/verify?token=…`, single-use, valid 72 hours);
2. when they open it, confirms the account **and opens the LumanexAI session right there** — the same as if they had just logged in, no password re-entry.

Without further configuration the user is then left on a plain "account confirmed" page on LumanexAI. If you'd rather they land **straight back in your app, already signed in**, set `initiate_login_uri` on your client:

```bash
curl -X PUT https://app.lumanex.it/ai/admin/oauth/clients/YOUR_CLIENT_ID \
  -H "Authorization: Bearer ADMIN_TOKEN" -H "Content-Type: application/json" \
  -d '{"initiate_login_uri": "https://yourapp.example.com/?lx_entra=1"}'
```

With this set, opening the confirmation email link **redirects (302) the user to that URL**, with the LumanexAI session already active in the browser (an httpOnly, `SameSite=Lax` cookie, sent on a top-level navigation even across origins).

**What your app should do on that URL:** start a fresh `GET /oauth/authorize?...` (new `state`, new PKCE pair). Don't try to resurrect the original authorize request that sent the user to registration — its `state` has typically expired by then (email delivery + confirmation usually take longer than the validity window most apps give their own `state`). With the LumanexAI session already open, the new `/oauth/authorize` call is **instant**: if your client is trusted, or the user already granted consent before, it returns a fresh `code` immediately with no screen at all; otherwise the user sees the consent screen once (no password).

**Security rules:** `initiate_login_uri` is configured **only** on the registered client by an admin — it is never accepted as a URL parameter on authorize, nor embedded in the confirmation email. A `client_id` sent to `POST /auth/register` that doesn't resolve to an active OAuth client is silently ignored (no error, unchanged behavior).

If your app has **its own registration form** instead of using the one embedded in LumanexAI's `/oauth/authorize` page, and calls `POST /auth/register` directly, include the same `client_id` in the body to get the same behavior:

```json
{ "name": "...", "username": "...", "email": "...", "password": "...",
  "client_id": "lxc_abc123" }
```

**Optional — `prompt=create`:** if your app already knows the user has no account (e.g. they tapped "Create account" rather than "Sign in"), append `&prompt=create` to the `/oauth/authorize` URL: the page opens directly on the registration form instead of login. Has no effect if the user already has a valid LumanexAI session — the SSO fast-path still applies in that case.

### 3.9 API keys (server-to-server)

For a backend integration — a management system, a bot, a scheduled job — use an **API key** instead of storing a username and password and refreshing a session token. A key belongs to one account, works on every **`/v1/*`** endpoint (§13.1) and, with the **scopes** chosen when it is created, also on the session APIs those scopes cover. It is sent exactly like a token:

```http
Authorization: Bearer lxk_…
```

- Create keys from **Settings → API keys** in the app, or with the endpoints below (they require a normal session token: a key cannot create or revoke keys).
- An account can hold several keys (up to 20), each with its own name: give one to every environment or customer and revoke it on its own, without changing the password.
- The value is shown **once**, when the key is created; the server keeps only a hash. Store it like a password.
- Keys do **not** expire. On `/v1/chat/completions` and `/v1/models` a revoked key answers `401` with `error.code: "revoked_api_key"`, an unknown one `401` with `"invalid_api_key"` (OpenAI error format).
- Keys are accepted **only in the `Authorization` header** (never in `?token=` or a cookie).
- Usage, quotas and token consumption are counted on the account that owns the key.

**Scopes.** Without scopes (the default, and every key created before scopes existed) a key works only on `/v1/*`. Scopes only ADD endpoints: they never restrict `/v1/*` (OpenAI-compatible chat, embeddings, audio), which every key can always use. When you create a key you can enable any of these scopes; each one opens the same endpoints an OAuth token with that scope reaches:

| Scope | Opens |
|-------|-------|
| `lumanex.chat` | chat sessions (`/chat/sessions`, the SSE message stream with web search and approvals, `DELETE /chat/sessions/{id}`), `/exec-code`, `/exec-chart`, `/doc_download` |
| `lumanex.memory` | `/memory/*` |
| `lumanex.documents` | `/docs/*`, `/verbali/*`, `/jobs/*`, `/transcribe` |
| `lumanex.presentations` | `/presentazioni/*` |
| `lumanex.code` | the Code Assistant (`/code/*`), every Code Agent route of a chat (`/chat/sessions/{sid}/code-agent/*`, `/ssh-agent-auth`, `/one-click-fix`, `/execute-runbook`, `/agent-trace`), the synced local folder (`/chat/local-ws/*`), the bus between chats (`/chat/intersession/*`) and Code turns in a chat session (`X-Chat-Code-Agent` / `X-Chat-WS` or a workspace pack on `/chat/sessions/{sid}/message`; with a key, also `lumanex.chat` is needed). It can act on the SSH servers linked to the account: enable it only if you need it. SSH file upload/download stays unavailable to keys |

Scopes are fixed when the key is created: to change them, create a new key and revoke the old one. Settings (including creating, listing and revoking keys and reading their usage), admin, terminal and account endpoints are **never** reachable with a key, whatever its scopes. Features reserved to the user's own session (e.g. steering a running turn, reminders, public share and review links, approving a web confirmation, the browser panel, editing a waiting command, server profiles; see §3.8.2) answer `403` to a key exactly as they do to an OAuth token. A revoked key stops working from the next request.

**Errors with a key** on every endpoint except the OpenAI-format ones above (JSON body `{"error": "<message>", "code": "<code>"}`):

| Status | `code` | Meaning |
|--------|--------|---------|
| `401` | `api_key_revoked` | the key was revoked: create a new one |
| `401` | `api_key_invalid` | unknown or malformed key |
| `403` | `insufficient_scope` | the key is valid but lacks the scope this endpoint needs; `required_scope` names it (e.g. `"lumanex.chat"`) |
| `403` | `api_key_not_allowed` | this endpoint is never available to a key (settings, admin, account, SSH file transfer, …) |
| `403` | `account_suspended` | the account that owns the key is suspended |
| `429` | as with a session | the account's usage limits |

A `401` also carries `WWW-Authenticate: Bearer realm="LumanexAI", error="invalid_token"`; an `insufficient_scope` `403` carries `WWW-Authenticate: Bearer realm="LumanexAI", error="insufficient_scope", scope="…"`.

| Method | Path | Use |
|--------|------|-----|
| `GET` | `/settings/api-keys` | List keys: `id`, `name`, `hint` (last 4 characters), `created_at`, `last_used_at`, `scopes` and `scope_labels` — never the value; `selectable_scopes` lists the scopes a new key can get |
| `POST` | `/settings/api-keys` | Body `{"name": "Back office — production", "scopes": ["lumanex.chat"]}` (`scopes` optional: omitted or `[]` = `/v1/*` only) → `201` with `id`, `name`, `scopes` and **`key`** (the only time it is returned) |
| `DELETE` | `/settings/api-keys/{id}` | Revoke: effective from the next request |

```bash
curl -sS -X POST "$BASE/settings/api-keys" \
  -H "Authorization: Bearer $SESSION_TOKEN" -H "Content-Type: application/json" \
  -d '{"name":"Back office — production","scopes":["lumanex.chat"]}'
```

```json
{ "id": "key_3f9c2a1b7d4e5f60", "name": "Back office — production", "hint": "Q2xw",
  "created_at": "2026-09-25T18:40:12Z", "last_used_at": null,
  "scopes": ["lumanex.chat"],
  "scope_labels": [{"scope": "lumanex.chat", "label": "Use AI Chat on your behalf"}],
  "key": "lxk_…" }
```

Errors: `400` with `reason: "name"` (empty name), `reason: "scope"` (a scope that is unknown or not available to keys, e.g. `openid`; `allowed_scopes` lists the valid ones) or `reason: "limit"` (too many keys), `404` for an unknown `id` on revoke.

---

## 4. Conventions

### 4.1 Headers

| Scenario | Header |
|----------|--------|
| JSON API | `Content-Type: application/json`, `Accept: application/json` |
| Authentication | `Authorization: Bearer YOUR_TOKEN` (session/OAuth token, or an API key on `/v1/*` and on the endpoints its scopes open — §3.9) |
| File upload | `Content-Type: multipart/form-data` (set automatically by your multipart client) |
| Deny web access for one chat request | `X-Chat-Web-Policy: denied` (see §7.9) |

### 4.2 CORS

The service exposes a permissive CORS policy:

- `Access-Control-Allow-Origin: *`
- `Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS`
- `Access-Control-Allow-Headers: Content-Type, Accept, Authorization`

For browser apps that send `Authorization`, make sure your HTTP client handles the `OPTIONS` preflight.

### 4.3 Dates and IDs

- Identifiers (`job_id`, `sid`, `doc_id`, `mid`, …) are server-issued strings. Do **not** assume a fixed format beyond what you receive.
- Timestamps are generally ISO 8601. When in doubt, treat them as opaque display strings.

---

## 5. Errors and status codes

### 5.1 Error body

A common shape:

```json
{ "error": "human-readable message" }
```

Some errors carry a more structured payload. In production, show a generic message to the user and log the detail server-side.

**Exception — OpenAI-compatible endpoints** (`/v1/chat/completions`, `/v1/models`): errors use the OpenAI object shape, so the official OpenAI SDKs raise their usual exceptions. The LumanexAI limit fields are kept inside it:

```json
{ "error": { "message": "…", "type": "invalid_request_error", "code": null, "param": "messages" } }
```

### 5.2 HTTP status codes

| Code | Meaning |
|------|---------|
| `200` | OK |
| `201` | Created |
| `202` | Accepted (asynchronous job started) |
| `400` | Bad request (parameters, body, or disallowed sandbox code) |
| `401` | Unauthenticated, or token missing/invalid |
| `403` | Authenticated but not authorized (role or disabled app) |
| `404` | Resource not found |
| `409` | State conflict on the resource |
| `429` | Usage limit / rate limiting |
| `500` | Internal error |
| `502` / `504` | Upstream error or timeout (e.g. AI backend) |
| `503` | AI engine temporarily unavailable or busy — retryable, honour `Retry-After` when present |

**Recommended handling:** on `401`, re-authenticate; on `429`, `502`, `503`, `504`, use exponential backoff with a maximum retry count. When a `429` carries `Retry-After`, wait at least that long; a `429` whose type is `quota_exceeded` (§13.5.8) will not clear before the stated reset time, so do not retry it in a loop.

---

## 6. Streaming (Server-Sent Events)

### 6.1 Streaming endpoints

| Flow | Method / path | Response content-type |
|------|---------------|------------------------|
| Chat | `POST /chat/sessions/{sid}/message` | `text/event-stream; charset=utf-8` |
| Code Assistant | `POST /chat/sessions/{sid}/message` with `X-Chat-Code-Agent: 1` | `text/event-stream; charset=utf-8` |
| OpenAI-compatible chat | `POST /v1/chat/completions` with `"stream": true` | `text/event-stream; charset=utf-8` — OpenAI chunk format, see §13.5.5 |

### 6.2 Event format

Each SSE event is:

1. One or more `data: <payload>` lines.
2. A blank separator line.

**End of stream:** an event with payload `data: [DONE]`.

### 6.3 Chat payloads

The stream interleaves text tokens with JSON status events. Handle the types you recognize and ignore unknown ones for forward compatibility.

| Type | Example | Notes |
|------|---------|-------|
| Text token | `{ "token": "..." }` | Append in order to build the reply. |
| Status / phase | `{ "status": "..." }` | Progress signal; may be a JSON-encoded string. |
| Error | `{ "error": "..." }` | Show and stop, or recover. |
| File published | `{ "sandbox_event": { "type": "artifact.published", "id": "a_05e6eceb3b", "name": "report.xlsx", "size": 6269, "url": "/doc_download/....xlsx", "ext": "xlsx" } }` | A file the assistant created or edited (Word, Excel, PDF, CSV, presentations, images). `url` is relative to the base URL. The same entries are persisted in the message's `artifacts` (§6.4). |
| Document ready | `{ "doc_ready": { "url": "/doc_download/....docx", "filename": "output.docx" } }` | Older delivery event, still sent by some flows: handle both. `url` is relative to the base URL. |
| Choice prompt | `{ "choice_prompt": { "message": "...", "options": [...] } }` | Requires UI selection. |
| Corrected reply | `{ "corrected_response": "..." }` | Replaces the displayed text instead of appending. At the end of a reply that used web sources it carries the final text with numbered citations and the sources list (§7.9). |
| Agent activity | `{ "sandbox_event": { "type": "web.search.started", ... } }` | What the assistant is really doing (web searches, pages opened, browser actions, files). Informational; see §7.9 for the web events and `approval.requested`. |

### 6.4 After the stream

After `[DONE]`, call `GET /chat/sessions/{sid}` to reconcile messages, metadata, and persisted state.

Files produced during the reply are listed on the assistant message:

```json
"artifacts": [
  { "id": "a_05e6eceb3b", "name": "ordine.xlsx", "size": 6269, "type": "xlsx",
    "url": "/doc_download/49c5c9f4-2083-410a-89a0-cf0fa2e000e2.xlsx", "sha256": "05e6ec..." }
]
```

Download a file with `GET {url}` and the user's token. With an OAuth token the `lumanex.chat` scope is required, and the token goes in the `Authorization: Bearer …` header (never in the query string).

#### Documents (Word, Excel, PDF, CSV)

Ask for a document in plain language, as in the app: *"write the procedure as a Word document"*, *"fill in the attached Excel with formulas"*, *"find current prices and make me an Excel with the sources"*. There is no separate document endpoint or mode. The assistant builds the file, checks it (structure, rendering, formulas) and publishes it, with its other tools at hand: web research (§7.9), attached files and code execution. An attached file it edits keeps its formatting, styles and content outside the requested change. When the user asks for text only, no file is produced.

---

## 7. Chat API

### 7.1 Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/chat/sessions` | Create a session (optional `title`, `project_id`) |
| `GET` | `/chat/sessions?limit=100&offset=0` | Paginated slim session list (`items`, `next_offset`, `has_more`, `total`; max 100). Without query parameters returns a backward-compatible array capped at 100. |
| `GET` | `/chat/sessions/{sid}` | Session detail with `messages` |
| `DELETE` | `/chat/sessions/{sid}` | Delete a session |
| `POST` | `/chat/sessions/{sid}/message` | Send a message — returns **SSE** |
| `POST` | `/chat/sessions/{sid}/web/approvals/{id}` | Answer a confirmation requested during a reply (§7.9) |
| `POST` | `/chat/sessions/{sid}/web/credentials/{id}` | Provide login values for the assistant's browser without exposing them to the model (§7.9) |
| `DELETE` | `/chat/sessions/{sid}/messages/{mid}` | Delete a message |
| `POST` | `/chat/sessions/{sid}/messages/{mid}/feedback` | Submit feedback on a message |
| `GET` | `/chat/sessions/{sid}/messages/{mid}/variants` | List variants of an AI message |
| `POST` | `/chat/sessions/{sid}/messages/{mid}/switch-variant` | Activate a specific variant |
| `PUT` | `/chat/sessions/{sid}/pin` | Pin/unpin a session (`pinned: bool`) |
| `PUT` | `/chat/sessions/{sid}/project` | Assign or remove a session from a project |
| `GET` | `/chat/sessions/{sid}/export` | Export a session (JSON / MD / DOCX via `?format=`) |
| `GET` | `/chat/search?q=...` | Bounded full-text search across the 100 most recent sessions |
| `GET` | `/chat/projects` | List the user's projects |
| `POST` | `/chat/projects` | Create a project |
| `GET` | `/chat/projects/{pid}` | Project detail + associated chats |
| `PUT` | `/chat/projects/{pid}` | Update name/color/description/instructions |
| `DELETE` | `/chat/projects/{pid}` | Delete a project (chats are unlinked, not deleted) |

### 7.2 Create a session

**`POST /chat/sessions`**

```json
{
  "title": "Customer support",
  "project_id": "4f6f29da-c648-4bd5-9620-c8b6c3426826"
}
```

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `title` | string (≤80) | No | Defaults to a generic title. Trimmed and truncated server-side. |
| `project_id` | string (UUID) | No | If set, links the chat to that project immediately. `404` if the project does not exist or is not yours. |

**Response:** the session object (`id`, `title`, `messages`, `project_id`, runtime metadata).

### 7.3 Send a message

**`POST /chat/sessions/{sid}/message`**

**JSON mode:**

```json
{ "content": "Explain this report" }
```

**`multipart/form-data` mode:**

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `content` | text | Yes | The user message. |
| `files` | file, repeatable | No | Images, PDF, DOCX, etc. |
| `regenerate_from_msg_id` | text | No | ID of the AI message to regenerate; creates a new variant (see §7.5). |
| `think` | `"1"` / `"true"` | No | Enables **Pro mode** (extended reasoning). Takes precedence over the `X-Chat-Think` header. See §7.6. |

#### Optional headers

All headers below accept `1`, `true`, `yes`, `on` to enable (anything else or missing = off). They work in both JSON and multipart mode.

| Header | Effect | Reference |
|--------|--------|-----------|
| `X-Chat-Think` | Enables **Pro mode** (extended reasoning). In multipart, the `think` field wins. | §7.6 |
| `X-Chat-Web-Policy` | `denied` removes the web tools for this reply (no search, no page fetch, no browser). It can only restrict: without it the account's web setting applies. | §7.9 |
| `X-Chat-Code-Agent` | Enables the code assistant for this request (file analysis/editing, allow-listed commands). Requires the code module to be enabled for the user. | §11 |
| `X-Chat-Code-Agent-Mode` | Safety policy for a single request: `readonly`, `assisted`, `autonomous`, `unrestricted` (the last only with `X-Chat-Code-Agent-Confirmed: unrestricted`). Overrides the session default. Invalid value is ignored. | §11.4 |
| `X-Chat-WS` | Marks that the turn uses a remote workspace over SSH. | §11.3 |
| `X-Chat-WS-Meta` | JSON metadata for the SSH workspace (`ssh_config_id` and `workspace`). Recommended whenever `X-Chat-WS: 1`. | §11.3 |

**Example (Pro mode, current information):** no header is needed for web access — the assistant searches and reads online when the question needs it (§7.9).

```bash
curl -X POST "$BASE/chat/sessions/$SID/message" \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-Chat-Think: 1" \
  -H "Content-Type: application/json" \
  -d '{"content":"Summarize the latest central-bank rate decisions"}'
```

**Example (upload + Pro mode):**

```bash
curl -X POST "$BASE/chat/sessions/$SID/message" \
  -H "Authorization: Bearer $TOKEN" \
  -F "content=Explain this PDF" \
  -F "think=1" \
  -F "files=@/path/to/report.pdf"
```

**Response:** an SSE stream (see §6). In Pro mode the stream may include reasoning events — see §7.6.

### 7.4 Message feedback

**`POST /chat/sessions/{sid}/messages/{mid}/feedback`**

```json
{
  "rating": "up",
  "reason": "very helpful"
}
```

Typical `rating` values: `up`, `down`, `removed`.

### 7.5 Conversation branching (regeneration variants)

When you regenerate a message by passing `regenerate_from_msg_id`, the system creates a **new variant** instead of overwriting the previous one. Both variants stay available and navigable.

#### Variant fields on AI messages

Messages returned by `GET /chat/sessions/{sid}` may include:

| Field | Type | Description |
|-------|------|-------------|
| `variant_group` | string | Variant group ID, shared by all messages in the group. |
| `variant_index` | integer (0-based) | Position of this message in the group. |
| `variant_total` | integer | Total number of variants in the group. |

Messages without `variant_group` are single replies.

#### List variants

**`GET /chat/sessions/{sid}/messages/{mid}/variants`**

Returns all variants of the group the message belongs to.

**Response (200):**

```json
{
  "variants": [
    { "id": "msg-abc", "content": "First generated reply...", "created_at": "2025-09-01T10:00:00Z", "active": false },
    { "id": "msg-def", "content": "Second (regenerated) reply...", "created_at": "2025-09-01T10:05:00Z", "active": true }
  ]
}
```

If the message belongs to no group, a single-element list is returned (`active: true`).

#### Activate a variant

**`POST /chat/sessions/{sid}/messages/{mid}/switch-variant`**

Makes the variant identified by `mid` active within its group; the others are hidden. No body required.

**Response (200):**

```json
{
  "ok": true,
  "message": { "id": "msg-def", "content": "Second (regenerated) reply...", "created_at": "2025-09-01T10:05:00Z" }
}
```

**Recommended UI flow:**

1. After `[DONE]`, refetch the session (`GET /chat/sessions/{sid}`).
2. For each AI message with `variant_total > 1`, show a `‹ N / total ›` navigator.
3. On click, resolve the target `mid` from `GET .../variants`.
4. Call `POST .../switch-variant` with the target `mid`.
5. Update the bubble with `message.content`.

### 7.6 Pro mode (reasoning toggle)

**Pro mode** enables the model's extended reasoning ("thinking"). Use it for questions that need structured analysis, problem solving, or multi-step reasoning. In Fast mode (default) the model answers immediately; in Pro mode it reasons first, then produces the final answer.

#### Activation

Pro mode is set **per request**, not per session:

| Channel | How | Precedence |
|---------|-----|------------|
| HTTP header | `X-Chat-Think: 1` | Low |
| Multipart field | `think=1` (inside the form-data) | **High** (wins over the header) |

#### What changes in the stream

In Pro mode the stream may include reasoning events alongside the normal content chunks. The raw internal reasoning is **never sent to the client**: you may receive a "thinking" signal and, optionally, a sanitized high-level summary.

Additional `data:` payloads you may observe:

```json
{"type":"thinking_started"}
{"type":"chunk","content":"..."}
{"type":"thinking_summary","points":["weighs two options","picks A because..."]}
```

Your client may:

- ignore `thinking_*` events — behaves exactly like Fast mode;
- render a "thinking…" indicator between `thinking_started` and the first content chunk;
- optionally show `thinking_summary` in a collapsible panel.

#### Considerations

- **Latency**: Pro mode adds from a few seconds to ~1–2 min for complex requests. Don't enable it by default — let the user choose.
- **Cost**: Pro mode uses more output tokens (reasoning + answer). If the user's plan has a token quota, account for it.

### 7.7 Skills

Removed on 2026-11-18. `GET /chat/skills`, `GET /chat/skills/{id}/body` and `POST /chat/sessions/{sid}/skill` no longer exist and answer `404` like any unknown route. A session saved earlier may still carry an `active_skill` field: it is ignored and no longer returned.

### 7.8 Chat projects (grouping sessions)

**Projects** group multiple sessions under a common container. Each session belongs to **0 or 1** project at a time; unassigned sessions stay in the flat chronological list.

Projects are **per-user**: not shared across accounts. Deleting a project does **not** delete its chats — they are simply unlinked (`project_id → null`).

#### Data model

```json
{
  "id": "4f6f29da-c648-4bd5-9620-c8b6c3426826",
  "name": "Thesis",
  "description": "Chapter 3 - Analysis",
  "instructions": "Formal tone; reply in English",
  "color": "#16a34a",
  "icon": null,
  "created_at": "2026-05-24T16:02:08Z",
  "updated_at": "2026-05-24T16:02:23Z",
  "chat_count": 5
}
```

The `instructions` field is a project-level note you can show the user as a reminder of the project context.

#### `GET /chat/projects`

Lists the user's projects, ordered by `updated_at` descending.

```json
{
  "projects": [
    {
      "id": "4f6f29da-c648-4bd5-9620-c8b6c3426826",
      "name": "Thesis",
      "description": "Chapter 3 - Analysis",
      "instructions": "Formal tone; reply in English",
      "color": "#16a34a",
      "icon": null,
      "created_at": "2026-05-24T16:02:08Z",
      "updated_at": "2026-05-24T16:02:23Z",
      "chat_count": 5
    }
  ]
}
```

#### `POST /chat/projects`

Creates a project.

| Field | Type | Required | Constraints |
|-------|------|----------|-------------|
| `name` | string | **Yes** | trimmed, ≤80 chars, non-empty |
| `description` | string | No | ≤500 chars |
| `instructions` | string | No | ≤4000 chars |
| `color` | string | No | HEX `#RRGGBB` — e.g. `#6366f1`; invalid value returns `400` |
| `icon` | string | No | ≤32 chars (emoji or keyword) |

```json
{
  "name": "Backend refactor",
  "description": "Framework migration",
  "instructions": "Always answer with Python examples.",
  "color": "#6366f1"
}
```

**Response (201):** the full project object (`id` generated, `chat_count: 0`).

#### `GET /chat/projects/{pid}`

Project detail **with the list of associated chats** (minimal metadata, no messages).

```json
{
  "id": "4f6f29da-...",
  "name": "Thesis",
  "color": "#16a34a",
  "chats": [
    {
      "id": "83fe593f-4d6b-4149-9bb2-8e69c66c9766",
      "title": "Chapter 3 - intro",
      "created_at": "...",
      "updated_at": "...",
      "pinned": null,
      "project_id": "4f6f29da-..."
    }
  ],
  "chat_count": 1
}
```

`404` if the project does not exist or is not yours.

#### `PUT /chat/projects/{pid}`

**Partial** update: only the fields present in the body change. Accepts the same fields as `POST`. To clear an optional field, send an empty string.

```json
{ "name": "Thesis 2026", "color": "#16a34a" }
```

#### `DELETE /chat/projects/{pid}`

Deletes the project. Associated chats are **not** deleted — they are unlinked (`project_id → null`) and return to the main list.

**Response (200):** `{ "ok": true }`

#### `PUT /chat/sessions/{sid}/project`

Assigns a chat to a project, or removes it (`project_id: null`).

```json
{ "project_id": "4f6f29da-c648-4bd5-9620-c8b6c3426826" }
```

**Response (200):**

```json
{
  "ok": true,
  "session_id": "72a8eff5-60a6-4be0-aa18-7e9e823aee00",
  "project_id": "4f6f29da-c648-4bd5-9620-c8b6c3426826",
  "previous_project_id": null
}
```

#### Typical integration pattern

1. On open, call `GET /chat/sessions` and `GET /chat/projects` in parallel.
2. Group chats client-side by `project_id`, using the project list as definitions.
3. Chats with `project_id == null` go in the flat chronological list.
4. To create a chat inside a project, pass `project_id` to `POST /chat/sessions`.
5. To move an existing chat, `PUT /chat/sessions/{sid}/project` with the new `project_id` (or `null`).

---

### 7.9 Web access (search, reading, browser)

There is no web mode to switch on. The assistant has web tools and decides by itself when a question needs them: current or changing information, news, prices and catalogues, documentation that is updated, a specific site, a link you give, or an explicit request to search or verify online. Rewriting, translating, calculations and questions about your own files do not use the web.

- **Search** finds sources, **reading** opens a page, PDF, Office document, CSV/JSON/feed or a link from the message, **the browser** is used only for pages that need JavaScript or interaction (forms, configurators, logins).
- **Privacy setting** (`web_access` in §13.2): `automatic`, `ask` or `disabled`. Administrators can restrict it further.
- **Per request:** `X-Chat-Web-Policy: denied` removes the web tools for that reply.
- **Personal data:** search queries and addresses the assistant opens never carry personal or secret data taken from your files or memory (tax codes, IBAN, card numbers, credentials, private document text); such a request is refused before it leaves the server.
- **Actions with consequences** in the browser (submitting, buying, sending, deleting, publishing, uploading) always need a confirmation from you. Web content is treated as untrusted evidence, never as instructions.

**Activity events.** While the reply is generated the stream carries `sandbox_event` payloads, for example:

| `type` | Payload fields |
|--------|----------------|
| `web.search.started` / `web.search.completed` | `query`, `vertical`, `domains` / `results`, `refs` |
| `web.open.started` / `web.open.completed` | `url`, `domain` / `ref`, `title`, `chars` |
| `web.find`, `web.follow` | `ref`, `query` / `link` |
| `browser.navigated`, `browser.clicked`, `browser.downloaded` | `url`, `title`, `name` |
| `web.source.added` | `ref`, `url`, `title`, `domain` |
| `web.blocked`, `web.error` | `kind` / `code` |
| `approval.requested` | `id`, `kind`, `title`, `detail`, `deadline_at`, `fields` (only for `credentials`) |
| `approval.resolved` | `id`, `status` (`approved`, `denied`, `timeout`, `cancelled`) |

**Confirmations.** When the stream emits `approval.requested`, show `title` and `detail` and answer before `deadline_at`. With an OAuth token or an API key the answer can only be a refusal (`{"approved": false}`): approving, or sending login values for `credentials`, answers `403` `third_party_approval_refused` and stays with the user in LumanexAI.

```bash
curl -X POST "$BASE/chat/sessions/$SID/web/approvals/$APPROVAL_ID" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"approved": true}'
```

For `kind: "credentials"` (a login the assistant needs in the browser) send the values for the listed field refs to `POST /chat/sessions/{sid}/web/credentials/{id}` as `{"values": {"e3": "user", "e4": "password"}}`, or `{"approved": false}` to decline. The values go straight to the browser session and are never visible to the model, stored or logged. Responses: `200 {"ok": true}`; `409` if the request is no longer pending or expired; `404` if unknown.

**Citations.** A reply built on web sources cites them as `[1]`, `[2]` and ends with a **Fonti** / **Sources** list whose links point only to resources the assistant actually found. The persisted assistant message also has `web_citations`: `[{ "n": 1, "ref": "S3", "url": "...", "title": "...", "domain": "...", "published_at": "..." }]`. Documents built from web research carry their sources inside the file too.

**Code assistant.** The code assistant (§11) has web search and page reading too (no browser), for what lies outside the workspace: current documentation, changelogs, unfamiliar error messages. It uses them only when needed and gives the URLs of the sources in its answer. The same `web_access` setting applies: `automatic` allows them, `ask` raises a run approval (answered with `POST /chat/sessions/{sid}/ssh-agent-auth`, action `kind: "web_access"`), `disabled` removes them. `X-Chat-Web-Policy: denied` removes them for that request.

## 8. Memory API

Persistent memory lets the assistant remember facts about the user across sessions. The chat can save facts automatically when the user explicitly asks (e.g. *"remember this"*).

### 8.1 Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/memory` | List memory entries |
| `POST` | `/memory/add` | Add an entry manually |
| `DELETE` | `/memory` | Delete all of the user's memory |
| `DELETE` | `/memory/{mid}` | Delete a single entry |

### 8.2 Add an entry

**`POST /memory/add`**

```json
{
  "content": "Prefers concise answers",
  "category": "preference",
  "importance": 6,
  "source": "manual"
}
```

**Allowed categories:** `identity`, `preference`, `technical`, `project`, `context`

`importance` is a 1–10 scale; values may be clamped server-side to the valid range for each category.

### 8.3 Importance guidance

| Value | Typical use |
|-------|-------------|
| `9–10` | Strong identity facts (name, role) explicitly stated by the user |
| `7–8` | Stable confirmed preferences (language, style, usual tools) |
| `5–6` | Project context or minor preferences |
| `< 5` | Short-term context |

---

## 9. Documents API (RAG)

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/docs` | List documents |
| `POST` | `/docs` | Upload (multipart) |
| `GET` | `/docs/{doc_id}/status` | Indexing / processing status |
| `DELETE` | `/docs/{doc_id}` | Remove |

**Indicative limits (confirm current values with your provider):**

- up to **30 files** per batch
- up to **10 GB** per file
- typical extensions: `pdf`, `docx`, `doc`, `pptx`, `txt`, `csv`

**Recommended flow:** upload → read `doc_id` → poll `GET /docs/{doc_id}/status` until the status indicates processing is complete.

---

## 10. Presentations API

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/presentazioni/genera` | Start generation |
| `POST` | `/presentazioni/refine/{job_id}` | Refine an existing job |
| `GET` | `/presentazioni/jobs` | List jobs |
| `GET` | `/presentazioni/status/{job_id}` | Status |
| `GET` | `/presentazioni/download/{job_id}` | Download the generated file |
| `GET` | `/presentazioni/preview/{job_id}` | Preview (HTML/JSON) |

**Example `POST /presentazioni/genera`:**

```json
{
  "topic": "AI business plan",
  "num_slides": 12,
  "template": "minimal",
  "lingua": "en",
  "tono": "professional",
  "use_web": true
}
```

---

## 11. Code Assistant API (optional)

Available when the code module is enabled for the user. The assistant can work on a local workspace or on a **remote workspace over SSH** that the user registers in their own profile. SSH configurations are **per-user**: a token only sees and edits servers registered by the same account, and secrets are never returned in plaintext.

### 11.1 Workspace and files

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/code/workspace` | Local workspace inventory |
| `GET` | `/code/workspace?ssh={cid}&ws=/var/www/app` | Remote workspace inventory over SSH |
| `GET` | `/code/files` | List the workspace root |
| `GET` | `/code/files/{path}` | List a directory or read a file |
| `GET` | `/code/files/{path}?ssh={cid}&ws=/var/www/app` | List/read inside the SSH workspace |
| `PUT` | `/code/files/{path}` | Write a file in the local workspace |
| `DELETE` | `/code/files/{path}` | Delete a local file |

The `ssh` and `ws` parameters select the SSH configuration and the remote root. Paths are resolved inside `ws`; requests outside the workspace are rejected.

**Read a remote workspace:**

```bash
curl -sS "$BASE/code/workspace?ssh=$CID&ws=/var/www/app" \
  -H "Authorization: Bearer $TOKEN"
```

**Indicative response:**

```json
{
  "root": "/var/www/app",
  "tree": {
    "path": ".",
    "entries": [
      { "name": "index.html", "type": "file" },
      { "name": "css", "type": "dir" }
    ]
  },
  "project": {
    "type": "nodejs",
    "language": "JavaScript/TypeScript",
    "package_manager": "npm",
    "test_cmd": "npm test"
  }
}
```

### 11.2 SSH servers in the user profile

These endpoints manage the SSH servers saved in the user's profile. Responses never return secrets — only flags such as `has_key_text` and `has_password`.

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/code/ssh` | List the user's saved SSH configurations |
| `POST` | `/code/ssh` | Add an SSH server |
| `PUT` | `/code/ssh/{cid}` | Update host, credentials, or default workspace |
| `DELETE` | `/code/ssh/{cid}` | Remove a configuration |
| `POST` | `/code/ssh/{cid}/test` | Test the saved connection |
| `POST` | `/code/ssh/try-test` | Test credentials without saving |
| `GET` | `/code/ssh/{cid}/browse?path=/...` | Browse remote directories to pick a workspace |
| `POST` | `/code/ssh/try-browse` | Browse remote directories without saving |

**`POST /code/ssh`:**

```json
{
  "name": "Production server",
  "host": "203.0.113.10",
  "port": 22,
  "username": "deploy",
  "auth_type": "key_text",
  "key_text": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----",
  "workspace_path": "/var/www/app"
}
```

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `name` | string | Yes | Display label. |
| `host` | string | Yes | Remote hostname or IP. |
| `port` | number | No | Default `22`. |
| `username` | string | Yes | Remote SSH user. |
| `auth_type` | string | No | One of `key_text`, `password`, `key_path`. Default `key_path`. |
| `key_text` | string | When `auth_type=key_text` | Pasted private key; used as a temporary file with `0600` permissions. |
| `password` | string | When `auth_type=password` | Password authentication. |
| `key_path` | string | When `auth_type=key_path` | Reference to a private key already available to the service. |
| `workspace_path` | string | No | Default remote root, e.g. `/var/www/app`; defaults to `/`. |

**Response (201):**

```json
{
  "id": "fcaf1bbf-19d1-4366-821a-a148b324053c",
  "name": "Production server",
  "host": "203.0.113.10",
  "port": 22,
  "username": "deploy",
  "auth_type": "key_text",
  "workspace_path": "/var/www/app",
  "has_key_text": true,
  "has_password": false
}
```

`PUT /code/ssh/{cid}` accepts the same updatable fields. When `auth_type` changes, credentials inconsistent with the new type are cleared to avoid ambiguous configurations.

**Test before saving:**

```bash
curl -sS -X POST "$BASE/code/ssh/try-test" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"host":"203.0.113.10","username":"deploy","auth_type":"key_text","key_text":"-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----"}'
```

### 11.3 Using an SSH workspace in chat

To use a remote workspace inside a conversation, send the chat message with:

- `X-Chat-Code-Agent: 1` to enable the code assistant.
- `X-Chat-WS: 1` to mark that the turn uses an SSH workspace.
- `X-Chat-WS-Meta` with at least `ssh_config_id` and `workspace`.
- optionally `X-Chat-Code-Agent-Mode` for the turn's safety policy (`readonly`, `assisted`, `autonomous`, `unrestricted`; see §11.4).

```bash
curl -N -X POST "$BASE/chat/sessions/$SID/message" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "X-Chat-Code-Agent: 1" \
  -H "X-Chat-WS: 1" \
  -H 'X-Chat-WS-Meta: {"ssh_config_id":"fcaf1bbf-19d1-4366-821a-a148b324053c","workspace":"/var/www/app"}' \
  -H "X-Chat-Code-Agent-Mode: assisted" \
  -d '{"content":"Review the site and propose a cleaner layout"}'
```

When the code assistant is active, the turn runs in Pro mode automatically. If a request produces an action that the safety mode submits for approval (in `assisted` mode, sensitive changes; §11.4), or the user's web setting is `ask` and the assistant wants to consult the web (§7.9), the SSE stream emits an approval request. Show it to the user and respond with:

**`POST /chat/sessions/{sid}/ssh-agent-auth`** (with an OAuth token or an API key: `lumanex.code` scope; `edited_action` is refused with `403` `edited_action_first_party_only`, and a `409` `approval_not_pending` does not list the open step ids)

```json
{
  "run_id": "5e6851fc-c6658da05c7c",
  "step_id": "step-2208f008a6b3",
  "approved": true,
  "reason": "approved by the user"
}
```

**Response:**

```json
{ "ok": true, "run_id": "5e6851fc-c6658da05c7c", "phase": "executing", "approved": true }
```

To monitor persistent code-assistant runs (with an OAuth token or an API key these routes need the `lumanex.code` scope):

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/chat/sessions/{sid}/code-agent/runs/{rid}` | Run status |
| `GET` | `/chat/sessions/{sid}/code-agent/runs/{rid}/events?since_seq=0` | Incremental event log |
| `POST` | `/chat/sessions/{sid}/code-agent/runs/{rid}/resume` | Resume a run |
| `POST` | `/chat/sessions/{sid}/code-agent/runs/{rid}/cancel` | Cancel a run |

#### Run statuses

The run detail (`GET /chat/sessions/{sid}/code-agent/runs/{rid}`) carries `status`. These are the only values the code assistant produces: `phase` is the coarser grouping of the same status (it appears, for example, in the `ssh-agent-auth` response above) and the labels are the words the app shows the user.

| `status` | Terminal | `phase` | Label (it / en) | Meaning |
|------|------|------|------|------|
| `queued` | no | `executing` | In coda / Queued | Accepted and waiting to start (for example, another run holds the workspace). |
| `running` | no | `executing` | In esecuzione / Running | The agent is working. |
| `waiting_approval` | no | `paused_for_approval` | In attesa di conferma / Waiting for confirmation | An action needs the user's approval (`POST /chat/sessions/{sid}/ssh-agent-auth`); the run stays alive. |
| `completed_with_changes` | yes | `succeeded` | Completato / Completed | The task is done and the agent changed files or the system. The checks it ran are in the run's final card; they do not change the status. |
| `completed_no_changes` | yes | `succeeded` | Completato, nessuna modifica / Completed, no changes | The agent finished without changing any file (an answer, an analysis, nothing to do). |
| `blocked` | yes | `inconclusive` | Bloccato / Blocked | The agent could not continue: an approval was refused or expired without an answer, or something it needed was missing. |
| `budget_exhausted` | yes | `inconclusive` | Limite della run raggiunto / Run limit reached | The run reached one of its own limits before finishing; `stop_reason` says which (for example `wall_clock`). |
| `provider_error` | yes | `failed` | Errore del modello / Model error | The model engine failed and the run could not recover. |
| `crashed` | yes | `failed` | Errore interno / Internal error | An internal error of the agent. |
| `cancelled` | yes | `cancelled` | Annullato / Cancelled | The user stopped the run (`POST /chat/sessions/{sid}/code-agent/runs/{rid}/cancel` or the Stop control). Nothing else produces it. |
| `rolled_back` | yes | `rolled_back` | Modifiche ripristinate / Changes rolled back | The run's changes were restored from the pre-change checkpoint. |

Runs that finished before 27 October 2026 may still carry `completed_verified` or `completed_unverified`: these historical values mean `completed_with_changes` (terminal, `phase` `succeeded`, label Completato / Completed) and the app shows them as such. New runs never produce them.

Rules that follow from the table:

- **Exit codes do not decide the status.** When the agent runs a command, the exit code is the result of that step: the agent reads it and decides what to do next. The run status describes the agent's outcome, not the last process it ran: a command that exits with `1` can belong to a `completed_with_changes` run (a test that failed and was then fixed), and a run whose commands all exit with `0` can still end `blocked` or `budget_exhausted`. Never map exit code `0` to a completed status and a non-zero exit code to `cancelled`.
- **`cancelled` has one cause**: the user stopped the run. Failures are `provider_error` or `crashed`, limits are `budget_exhausted`, a missing approval is `blocked`.
- **There is no `invariata` / `unchanged` status.** A run that finished without changing any file ends `completed_no_changes`.

#### Checkpoints and rollback

When a run modifies remote files, the system creates a pre-change checkpoint.

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/code/ssh/checkpoints/{sid}` | List the session's checkpoints |
| `POST` | `/code/ssh/checkpoints/{sid}/{chk_id}/restore` | Restore a checkpoint on the remote workspace |

**Restore body:**

```json
{
  "ssh_config_id": "fcaf1bbf-19d1-4366-821a-a148b324053c",
  "workspace": "/var/www/app"
}
```

**Response:**

```json
{
  "ok": true,
  "message": "restore complete",
  "details": { "restored": ["index.html", "css/style.css"], "failed": [] }
}
```

### 11.4 Safety modes

The code assistant operates in one of **four safety modes**, controlling what it can do without asking and what requires the user's explicit approval. Every tool call goes through a policy engine that answers **allow**, **ask** (human approval) or **deny**; the agent loop cannot bypass it.

| Mode (API value) | App label | What it can do | Asks for approval on |
|------|------|------|------|
| `readonly` | Read-only | Reads, searches and runs checks that change nothing | Nothing: anything that would change something is **refused** |
| `assisted` | Assisted | Edits files in the workspace and runs ordinary commands | Database writes, deletions, installations, services, network commands that send or publish (push, upload, ssh, cloud CLIs), privileged commands, execution on remote hosts, folders outside the workspace, sensitive files, destructive or critical commands |
| `autonomous` | Autonomous | Works on the task without interruptions, including remote servers and system configuration | Destructive or critical host commands, and deleting sensitive files |
| `unrestricted` | No confirmations | Like `autonomous`, and never asks | Nothing (explicit confirmation required, see below) |

In **every** mode, `unrestricted` included, commands that would destroy the host or its disks are refused. `autonomous` grants permission to execute, not permission to widen the user's task.

#### Policy summary

| Action | readonly | assisted | autonomous | unrestricted |
|--------|:---:|:---:|:---:|:---:|
| Read, list and search files | Yes | Yes | Yes | Yes |
| Web search and page reading | per `web_access` | per `web_access` | per `web_access` | per `web_access` |
| Read-only commands, tests, network requests that only read | Yes | Yes | Yes | Yes |
| Create, edit, move files in the workspace | No | Yes | Yes | Yes |
| Write sensitive files (`.env`, `.pem` and `.key` keys, SSH private keys, `.git`, `.ssh` and `.gnupg` folders, …) | No | approve | Yes | Yes |
| Delete files | No | approve | Yes | Yes |
| Delete sensitive files | No | approve | approve | Yes |
| Work in other project folders outside the workspace | No | approve | Yes | Yes |
| Commands with effects: installations, services, network that sends or publishes, privileged commands, database writes, remote hosts | No | approve | Yes | Yes |
| Destructive or critical commands (`rm -r`, `git reset --hard`, `git push --force`, `DROP TABLE`, `shutdown`, `reboot`, `curl \| sh`, stopping `sshd`, firewall reset, …) | No | approve | approve | Yes |
| Commands that would destroy the host or its disks (`mkfs`, `dd` to a disk, `rm -rf /`, fork bomb, …) | No | No | No | No |

System folders and a whole home directory can never be added to a run: access is refused in every mode. Web access always follows the user's `web_access` setting (`automatic`, `ask`, `disabled`), whatever the mode (§7.9).

When the policy answers "ask", the SSE stream emits an approval request (`ssh_agent_auth`) that your client answers with `POST /chat/sessions/{sid}/ssh-agent-auth` (§11.3).

#### Removed modes

The former `guided` and `emergency` modes, listed in earlier versions of this reference, **no longer exist** and are not valid values.

- `POST /chat/sessions/{sid}/code-agent` with those values returns `400`.
- The `X-Chat-Code-Agent-Mode` header with those values is ignored (the next level of precedence applies).
- A value stored on a session under those names is treated as unset: the default applies.

#### Set the mode at session level

**`POST /chat/sessions/{sid}/code-agent`**

```json
{ "enabled": true, "mode": "assisted" }
```

All fields are optional; omitted fields leave the corresponding state unchanged.

| Field | Type | Notes |
|-------|------|-------|
| `enabled` | bool | Session opt-in for the code assistant. |
| `mode` | string | One of `readonly`, `assisted`, `autonomous`, `unrestricted`. |
| `confirm_unrestricted` | bool | Must be `true` to switch to `unrestricted` (unless the session already has it). Only from the user's own session: an OAuth token or an API key gets `403` `unrestricted_first_party_only`. |

**Response (200):** `{ "ok": true, "enabled": true, "mode": "assisted" }`. When the session has no stored mode, `mode` reports the default (see Precedence below).

**Errors:**

- `400` `{"error": "Mode non valido. Ammessi: assisted, autonomous, readonly, unrestricted"}`
- `400` `{"code": "confirmation_required", "error": "..."}`: `unrestricted` requested without `confirm_unrestricted: true`.
- `400` invalid JSON, `401` unauthenticated, `404` session not found.

#### Per-request override

The `X-Chat-Code-Agent-Mode` header overrides the persisted mode for a single request. Precedence (first wins):

1. The `X-Chat-Code-Agent-Mode` header (if valid).
2. The mode set on the session.
3. The default: `autonomous` when mutations are enabled for the environment, otherwise `readonly`.

Unrecognized header values are silently ignored, falling back to the next level.

`unrestricted` never comes from a header alone: the request must also carry `X-Chat-Code-Agent-Confirmed: unrestricted` (your client sends it after showing the user a confirmation), or the session must already have `unrestricted` saved. Without confirmation the header is ignored. With an OAuth token or an API key the header is always ignored: the turn keeps the session's mode, which only the user can set to `unrestricted`.

#### Recommended flow

- **Interactive UI** → `assisted`. Every action the policy submits for approval raises an approval event you answer via `POST /chat/sessions/{sid}/ssh-agent-auth`.
- **Automated batch** → `autonomous` per session, optionally `readonly` on diagnostic-only requests. Destructive or critical commands still ask for approval: design the task so it does not need them.
- **Monitoring / automatic diagnosis** → `readonly`. An automatic fix on a server you are responsible for needs `autonomous`, with the same residual approvals.
- **Audit / investigation** → `readonly`, no risk of altering state.
- `unrestricted` is discouraged in unattended integrations: it removes every approval and the user must confirm it explicitly.

### 11.5 Automation runs

Automations are the scheduled tasks the user creates in the app. A run is a chat turn or a code-assistant run on a workspace (§11.3), optionally followed by the actions the user configured (e-mail, HTTP). **Bearer** required.

**`GET /automations/{aid}/runs`** lists the runs of automation `aid`. Each run carries:

- `status`: one of the values in the table below.
- `code_outcome`: only when the run executed the code assistant and that run reached a terminal status; it is the raw code-assistant `status` (§11.3, "Run statuses").
- `error_code`: set on some `cancelled` runs (see below).

| `status` | Label (it / en) | When |
|------|------|------|
| `queued` | In coda / Queued | The run record was created and waits to start. |
| `running` | In esecuzione / Running | The turn or the code-assistant run is in progress. |
| `waiting_approval` | In attesa di approvazione / Awaiting approval | The turn finished and a configured action waits for the user's approval. |
| `paused` | In attesa di approvazione / Waiting for approval | The code-assistant run is `waiting_approval`; the automation resumes when the user answers from the run detail. |
| `ok` | Completata / Completed | The turn produced its answer, or the code-assistant run ended in a `completed_*` status (mapping below). With `code_outcome` `completed_no_changes` the app shows Completata with the note "nessun file modificato" / "no files changed". |
| `empty` | Vuota / Empty | The chat turn produced no answer. |
| `timeout` | Timeout / Timeout | The turn or the code-assistant run exceeded the automation's time budget (a code run still alive at the deadline is cancelled cooperatively; one that stopped by itself for `wall_clock` is mapped here, see below). |
| `error` | Errore / Error | The turn failed, or the code-assistant run ended `blocked`, `budget_exhausted`, `provider_error`, `crashed`, `rolled_back` or in an unknown status. |
| `budget_exceeded` | Oltre budget / Over budget | The automation's token budget was exhausted before or after the model call, or the code-assistant run was stopped because the automation's action limit was exceeded. |
| `partial_success` | Successo parziale / Partial success | The turn succeeded; among the required follow-up actions some completed and some failed. |
| `action_failed` | Azione fallita / Action failed | The turn succeeded; no required follow-up action completed, or the actions raised an error. |
| `approval_expired` | Approvazione scaduta / Approval expired | The code-assistant run closed as `blocked` or `cancelled` after an approval expired without an answer. Informative, like `cancelled`: it does not count as a consecutive error. |
| `cancelled` | Annullata / Cancelled | One of the four causes below. |
| `preview` | Anteprima valida / Preview valid | Outcome of a preview run that produced a valid result. |
| `preview_invalid` | Anteprima non valida / Preview invalid | Outcome of a preview run whose result failed validation. |

**Mapping from the code-assistant status (`code_outcome`) to the automation `status`.** Three rules apply first:

1. `blocked` or `cancelled` with an approval that expired without an answer (an entry of `approvals` with `outcome` `timeout`) becomes `approval_expired`.
2. `budget_exhausted` with `stop_reason` `wall_clock` becomes `timeout`: the automation's time ran out and the agent stopped by itself.
3. `completed_no_changes` whose final answer only repeats the output of a command of the run that exited with a non-zero code (not a check, not timed out or cancelled), with no file changed, becomes `cancelled` with `error_code` `stopped_by_task`: the run stopped at the precondition of its own task (for instance a script that printed a `NIENTE DA FARE` line and the agent answered with that line alone). `code_outcome` stays `completed_no_changes`.

Otherwise:

| Code-assistant `status` | Automation `status` |
|------|------|
| `completed_with_changes` | `ok` (so do the historical `completed_verified` and `completed_unverified`) |
| `completed_no_changes` | `ok` (Completata, "nessun file modificato"), or `cancelled` with `error_code` `stopped_by_task` under rule 3 |
| `cancelled` | `cancelled` |
| `blocked` | `error` |
| `budget_exhausted` | `error` |
| `provider_error` | `error` |
| `crashed` | `error` |
| `rolled_back` | `error` |
| any other value | `error` |

**`cancelled` has exactly four causes:**

- the user interrupted the run (also while it was waiting for the workspace);
- the workspace was busy: `error_code` `workspace_busy`, the run never started and touched nothing (`skip` describes the run that held the folder);
- the same scheduled slot had already been claimed by another worker: `error_code` `duplicate_due_slot`, `duration_ms` `0`;
- the run stopped at the precondition of its own task (rule 3 above): `error_code` `stopped_by_task`, `code_outcome` `completed_no_changes`, the agent's final answer is the refusing line of its own script. The app shows Annullata with the note "non partita: fermata dallo script" / "not started: stopped by its script". Like every `cancelled`, it does not count as a consecutive error.

As for code-assistant runs, no automation status is derived from the exit code of a process the agent ran by itself: `stopped_by_task` also needs the agent's final answer to be nothing but that command's output, with no file changed. There is no `invariata` / `unchanged` automation status either: a code run that changed nothing is `ok` with `code_outcome` `completed_no_changes`.

---

## 12. Corrections API

Lets the user submit and manage structured corrections/feedback about the product. **Bearer** required.

| Method | Path |
|--------|------|
| `GET` | `/corrections` |
| `POST` | `/corrections` |
| `DELETE` | `/corrections` |
| `DELETE` | `/corrections/{cid}` |

For the `POST /corrections` body schema, use the schema supplied with your service.

---

## 13. User settings & utilities

### 13.1 Direct endpoints

| Method | Path | Use |
|--------|------|-----|
| `POST` | `/v1/audio/transcriptions` | Dedicated audio transcription (OpenAI-compatible) |
| `POST` | `/v1/embeddings` | Semantic vectors for meaning-based search over text, images, audio and video (OpenAI-compatible) |
| `POST` | `/v1/chat/completions` | Stateless chat with native tool calling (OpenAI-compatible) — §13.5 |
| `GET` | `/v1/models` | Available chat model (OpenAI-compatible) — §13.6 |

Every `/v1/*` endpoint accepts a session token, an OAuth token with the listed scope, or an **API key** (§3.9).
| `POST` | `/feedback` | General application feedback |

#### `POST /v1/audio/transcriptions`

Transcribes one audio/video file without going through the chat. **Bearer** required (OAuth scope `lumanex.documents`). Multipart form:

| Field | Required | Description |
|-------|----------|-------------|
| `file` | yes | audio/video (`mp3`, `wav`, `m4a`, `mp4`, `ogg`, `flac`, `webm`, …), up to 200 MB |
| `language` | no | ISO code (`it`, `en`, …): forces the spoken language and skips detection |
| `language_hint` | no | the language you work in: prior for auto-detection and expected script of the result (default: the user's UI language) |
| `response_format` | no | `json` (default), `text`, `verbose_json`, `srt`, `vtt` |
| `cache` | no | `0` to bypass the cached result for an identical file (or header `X-Audio-No-Cache: 1`) |

The response opens immediately and, for `json`/`verbose_json`/`text`, sends a space every few seconds while the engine works (whitespace is valid before a JSON value), so a client read timeout never fires on a transcription that is succeeding. `verbose_json` returns:

```json
{
  "task": "transcribe",
  "language": "it",
  "duration": 523.7,
  "text": "…",
  "words": 751,
  "segments": [{"id": 0, "start": 0.0, "end": 13.0, "text": "…"}],
  "coverage": {"complete": false, "transcript_end_sec": 506.6,
               "uncovered": [{"start": 253.4, "end": 280.9, "duration": 27.5, "reason": "no_speech_recognised"}]},
  "warnings": [],
  "language_detection": {"chosen": "it", "source": "auto-detected", "avg_p": 0.91, "windows": []},
  "model": "large-v3-turbo-q8_0",
  "processing_sec": 40.0
}
```

`coverage.uncovered` lists stretches where the engine measured audible sound but recognised no speech: a declared gap, never a silent hole. An engine failure after the response has opened arrives as `{"error": "…"}` in the body (for `text`/`srt`/`vtt`: an `ERROR: …` line).

```bash
curl -sS https://app.lumanex.it/ai/v1/audio/transcriptions \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@lecture_01.m4a" -F "language=it" -F "response_format=verbose_json"
```

### 13.2 User settings — `/settings/user`

Manage the authenticated user's profile and preferences.

**`GET /settings/user`** — read preferences:

```json
{
  "name": "Jane Doe",
  "email": "jane@example.com",
  "theme": "dark",
  "language": "en",
  "web_access": "automatic",
  "notifications_enabled": true
}
```

Allowed values: `theme` is one of `dark`, `light`, `auto`; `language` is one of `it`, `en`.

**`PUT /settings/user`** — update preferences. All fields are optional; send only what changes.

```json
{
  "name": "Jane Doe",
  "theme": "light",
  "language": "en",
  "web_access": "ask",
  "current_password": "old_pw",
  "new_password": "new_pw"
}
```

| Field | Type | Notes |
|-------|------|-------|
| `name` | string (≤100) | |
| `email` | string (≤200, lowercased) | |
| `theme` | string | One of `dark`, `light`, `auto` |
| `language` | string | One of `it`, `en` |
| `web_access` | string | `automatic` (default: the assistant uses the web when needed), `ask` (confirmation before the first web access of each reply), `disabled` (no web). See §7.9 |
| `notifications_enabled` | bool | |
| `current_password` | string | **Required** when changing the password |
| `new_password` | string (≥6) | New password |

**Response (200):** `{ "ok": true }`

**Errors:** `400` for an incorrect current password, a too-short new password, or invalid JSON; `401` unauthenticated.

### 13.3 Custom instructions — `/settings/instructions`

Retrieves the user's persistent custom instructions, which are automatically prepended to each chat.

**`GET /settings/instructions`**

```json
{
  "instructions": "Always answer in formal English, avoid emoji.",
  "updated_at": "2026-04-20T10:30:00Z"
}
```

---

### 13.4 Embeddings — `POST /v1/embeddings`

Turns texts, images, audio or video into numeric vectors for meaning-based search (client-side RAG, deduplication, clustering). Request and response follow the **OpenAI shape**; authentication is the same Bearer token as the rest of the API (OAuth scope `lumanex.chat`).

> **Model change on 2026-10-25.** Since 25 October 2026 the model is `embeddinggemma-2` (previously `qwen3-embedding:0.6b`, 1024 dimensions). **Vectors computed with the previous model are not comparable with the new ones** (even the size differs): comparing them gives meaningless results, not an error. Re-embed your whole index with the new model and tag every vector with `model_id`.

```bash
curl -sS https://app.lumanex.it/ai/v1/embeddings \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model":"embeddinggemma-2","input_type":"document","input":["first quote","second quote"]}'
```

The user's question, against the same index (`input_type: "query"`):

```bash
curl -sS https://app.lumanex.it/ai/v1/embeddings \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"input_type":"query","input":"who signed the contract?"}'
```

| Field | Required | Description |
|-------|----------|-------------|
| `input` | yes | a single string, an object, or an array of strings and/or objects (batch) |
| `input_type` | no | `query` for questions, `document` (default) for the texts you index; `none` = no prefix; other prompt names of the model are forwarded |
| `model` | no | when present it must be the served model; any other name returns `400` |
| `encoding_format` | no | `float` (default) or `base64` (little-endian float32) |
| `dimensions` | no | Matryoshka reduction: `768` (default), `512`, `256` or `128`; other values return `400` |

**`query` or `document`.** The model is asymmetric: the server adds a different prefix to questions and to documents. Index your texts with `document` and embed the user's question with `query`; always compare a `query` with `document`s. To compare two texts of the same kind (deduplication, clustering) use the same `input_type` for both. Do not add prefixes yourself: the server does it.

**Object items and multimodal inputs.** Each element of `input` can be an object with the keys `text`, `title`, `image`, `audio`, `video`; each object yields **one** vector.

- `{"text": "...", "title": "Lease agreement"}`: the document title goes into the vector (useful with `input_type: "document"`).
- `image`, `audio`, `video`: the file as **base64** or as a **data URL** (`data:image/png;base64,...`); the data URL type must match the key. **`http(s)://` URLs are refused** with `400`: the server does not download files on the client's behalf.
- A media item can also carry a `text` (caption): the vector represents both. An object with neither `text` nor media returns `400`.

```json
{
  "input_type": "document",
  "input": [
    {"text": "Second floor plan", "image": "data:image/png;base64,iVBORw0KGgo..."},
    {"audio": "UklGRiQAAABXQVZF..."}
  ]
}
```

Response:

```json
{
  "object": "list",
  "model": "embeddinggemma-2",
  "model_id": "google/embeddinggemma-2",
  "data": [
    {"object": "embedding", "index": 0, "embedding": [0.0123, -0.0456, "…"]},
    {"object": "embedding", "index": 1, "embedding": ["…"]}
  ],
  "usage": {"prompt_tokens": 37, "total_tokens": 37}
}
```

The served model is **`embeddinggemma-2`** (`model_id`: `google/embeddinggemma-2`), multilingual, with text, images, audio and video in the same space; **768 dimensions** unless `dimensions` says otherwise (512/256/128: smaller, slightly less precise vectors); **8,192-token** window per element, prefix included — a longer text returns `400` with the engine's message. Vectors come out **L2-normalised**: the dot product *is* cosine similarity. Store `model_id` next to every vector you keep — vectors from different models are not comparable, so a change of `model_id` means the index must be rebuilt (it happened on 2026-10-25, from `Qwen/Qwen3-Embedding-0.6B` to `google/embeddinggemma-2`).

Limits: at most **64 items** per call (`400` with `max_inputs`) and **24,000 characters** of text per item (`text` + `title`; media do not count) (`400` with `index` and `max_chars` — an over-long text is refused, never silently truncated, because a truncated vector is a mistake you only discover once the index is built). A media file over the byte limit (20 MB after decoding), invalid base64 or an `http(s)://` URL returns `400` with `index`. More than **120 calls per minute** returns `429` with `limit_key: "embeddings_per_minute"` and a **`retry_after`** value in seconds; more than **5,000 calls per day** returns `429` with `limit_key: "embeddings_per_day"`; too many parallel requests also return `429`, and an unavailable engine a retryable `503`. These limits belong to this endpoint: embedding calls do **not** consume the plan's chat quotas, and are not blocked when those run out. Only the per-user concurrency cap is shared with chat, because it protects the same GPU. A batch counts as **one** call whatever its size, so group your texts.

### 13.5 Chat completions — `POST /v1/chat/completions`

An **OpenAI-compatible** chat endpoint for integrations that run their own agent loop: send the whole conversation and the tools on every call, receive either text or tool calls. Point the official OpenAI SDK (or any compatible client) at the base URL and it works without code changes:

```python
from openai import OpenAI
client = OpenAI(base_url="https://app.lumanex.it/ai/v1", api_key="lxk_…")
```

Unlike `/chat/sessions/{sid}/message` (§7.3), this endpoint is **stateless**: no session to create, nothing added to the account's chat history, no memory, RAG, skills or web access — only the messages you send. Authentication: API key (§3.9), session token, or OAuth scope `lumanex.chat`. The account needs the Chat app.

#### 13.5.1 Request

| Field | Required | Description |
|-------|----------|-------------|
| `messages` | yes | Array of `system` / `developer` (treated as `system`) / `user` / `assistant` / `tool` messages |
| `model` | no | `lumanexai` (see `GET /v1/models`). Any other name returns `400` with `code: "model_not_found"` |
| `tools` | no | Up to **128** tools in OpenAI format: `{"type": "function", "function": {"name", "description", "parameters"}}` — `parameters` is a JSON Schema object; names use letters, digits, `_`, `-` (max 64) |
| `tool_choice` | no | `auto` (default with tools), `none`, `required`, or `{"type": "function", "function": {"name": "…"}}` |
| `parallel_tool_calls` | no | `false` to ask for at most one call per turn (default: several calls allowed) |
| `response_format` | no | `{"type": "json_object"}` or `{"type": "json_schema", "json_schema": {"name", "schema", "strict"}}` — §13.5.4 |
| `max_tokens` / `max_completion_tokens` | no | Output ceiling, honoured exactly; capped at **16,384** (also the value used when omitted) |
| `temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `seed`, `stop` | no | Standard sampling parameters (`stop`: up to 4 strings) |
| `reasoning_effort` | no | `none` / `minimal` (default: answer directly), `low`, `medium`, `high`: the model reasons before answering. Reasoning tokens count as output (`usage.completion_tokens_details.reasoning_tokens`) and are never returned |
| `stream`, `stream_options.include_usage` | no | SSE streaming — §13.5.5 |
| `n` | no | Only `1` |

Unknown OpenAI fields (`user`, `metadata`, `store`, …) are ignored.

#### 13.5.2 Tool calling

```bash
curl -sS https://app.lumanex.it/ai/v1/chat/completions \
  -H "Authorization: Bearer $LUMANEX_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "model": "lumanexai",
    "messages": [
      {"role": "system", "content": "You are the back-office assistant. Use the tools for data."},
      {"role": "user", "content": "Who has not paid, and how much are my monthly mortgage instalments?"}
    ],
    "tools": [
      {"type": "function", "function": {"name": "getOverdueInvoices",
        "description": "Overdue unpaid invoices", "parameters": {"type": "object", "properties": {}}}},
      {"type": "function", "function": {"name": "getMortgageSummary",
        "description": "Mortgages: instalments and outstanding debt", "parameters": {"type": "object", "properties": {}}}}
    ],
    "tool_choice": "auto"
  }'
```

The model may ask for **several tools in the same turn**:

```json
{
  "id": "chatcmpl-…", "object": "chat.completion", "created": 1790359324, "model": "lumanexai",
  "choices": [{
    "index": 0, "finish_reason": "tool_calls", "logprobs": null,
    "message": {
      "role": "assistant", "content": null, "refusal": null,
      "tool_calls": [
        {"id": "call_c9ed…", "type": "function", "function": {"name": "getOverdueInvoices", "arguments": "{}"}},
        {"id": "call_113f…", "type": "function", "function": {"name": "getMortgageSummary", "arguments": "{}"}}
      ]
    }
  }],
  "usage": {"prompt_tokens": 362, "completion_tokens": 34, "total_tokens": 396,
            "prompt_tokens_details": {"cached_tokens": 320},
            "completion_tokens_details": {"reasoning_tokens": 0}}
}
```

`function.arguments` is always a JSON **string**. Run the tools on your side, then send the next turn with the assistant message unchanged followed by one `tool` message per call:

```json
{"role": "tool", "tool_call_id": "call_c9ed…", "content": "[{\"tenant\": \"M. Rossi\", \"amount\": 650}]"}
```

The loop ends when a response comes back with `finish_reason: "stop"` and the answer in `message.content`. `content` may also carry a short text next to the tool calls.

#### 13.5.3 Response

`choices[0].message` holds `content` (string, or `null` when the turn is only tool calls) and optionally `tool_calls`. `finish_reason` is `stop`, `length` (the `max_tokens` ceiling was reached — the text is cut there) or `tool_calls`. `usage` is present on every response; `prompt_tokens_details.cached_tokens` says how much of the prompt was served from the prefix cache (§13.5.7).

Every successful response, JSON or SSE, also carries the headers `X-AI-Generated: true` and `X-AI-System: LumanexAI`, which mark the content as AI-generated. The body format is unchanged. What they mean for your integration: §18.3.

#### 13.5.4 Guaranteed JSON

With `response_format.type = "json_schema"` the output is produced under **grammar-constrained decoding**: it is always valid JSON that conforms to the schema — no Markdown fences, no text around it, no repair needed.

```json
"response_format": {"type": "json_schema", "json_schema": {
  "name": "bill", "strict": true,
  "schema": {"type": "object", "additionalProperties": false,
             "required": ["supplier", "amount", "due_date"],
             "properties": {"supplier": {"type": "string"}, "amount": {"type": "number"},
                            "due_date": {"type": "string"}}}}}
```

`{"type": "json_object"}` guarantees a JSON object without a schema. Keep `max_tokens` large enough for the whole object: a response cut by `length` is incomplete JSON.

#### 13.5.5 Streaming

With `"stream": true` the response is SSE in the **OpenAI chunk format** (compatible with the official SDKs): `data: {"object": "chat.completion.chunk", "choices": [{"delta": …}]}` events, tool calls streamed as `delta.tool_calls` pieces (the first piece of each call carries `id` and `function.name`, the next ones `function.arguments` fragments to concatenate by `index`), terminated by `data: [DONE]`. With `"stream_options": {"include_usage": true}` the last chunk before `[DONE]` has `choices: []` and the `usage` object. Lines starting with `:` are keep-alive comments (sent while the model reasons) and must be ignored — standard SSE clients already do.

#### 13.5.6 Documents and images in the message

`user` messages accept content parts:

| Part | Shape | Notes |
|------|-------|-------|
| Text | `{"type": "text", "text": "…"}` | |
| Image | `{"type": "image_url", "image_url": {"url": "data:image/png;base64,…"}}` | **Inline data URLs only**; remote `http(s)` URLs are refused with `400` |
| File | `{"type": "file", "file": {"filename": "bill.pdf", "file_data": "data:application/pdf;base64,…"}}` | PDF, Word, Excel, PowerPoint, CSV, text and more. A scanned PDF without a text layer is read page by page as images (first **20** pages). `file_id` is not supported |

Documents and tools work in the **same call**: read a bill and register its due date in one loop. Request body limit: **48 MB** (base64 included).

#### 13.5.7 Performance

The model is always loaded: there is no cold start after a pause. Prompts that begin with the **same prefix** as a recent call — system prompt, then the tool catalogue — are served from a prefix cache: keep that part byte-identical and in front, put what changes (the conversation, the new question) after it. Measured on a ~11,000-token system prompt + 70-tool catalogue: first output in ~7.5 s on the first call, **~0.8 s** on the next one (`cached_tokens: 11136`). `reasoning_effort` above `none` adds the reasoning time before the first visible token.

#### 13.5.8 Limits, quota headers and 429

This endpoint has its **own quotas**, counted in calls and tokens — it does **not** consume the plan's chat quotas (chats per day) and is not blocked when those run out. Default values (they may differ by plan — confirm with your provider):

| Quota | Default | `limit_key` |
|-------|---------|-------------|
| Requests per minute | 60 | `chat_completions_per_minute` |
| Requests per day | 5,000 | `chat_completions_per_day` |
| Tokens per day (prompt + completion) | 20,000,000 | `chat_completions_tokens_per_day` |
| Parallel requests | shared with chat (per-user cap) | `concurrent_requests` |
| Plan token windows, where the plan sets them | — | `session_token_limit`, `weekly_token_limit` |

Daily quotas reset at **00:00 (Europe/Rome)**. Every response — errors included — reports what is left:

| Header | Meaning |
|--------|---------|
| `x-ratelimit-limit-requests` / `x-ratelimit-remaining-requests` / `x-ratelimit-reset-requests` | Daily requests (reset as a duration, e.g. `5h3m20s`) |
| `x-ratelimit-limit-tokens` / `x-ratelimit-remaining-tokens` / `x-ratelimit-reset-tokens` | Daily tokens (remaining as of this response) |
| `x-ratelimit-limit-requests-minute` / `x-ratelimit-remaining-requests-minute` / `x-ratelimit-reset-requests-minute` | Per-minute window |

A `429` says **which kind** of limit it is, in `error.type`, with `Retry-After` (seconds):

- `rate_limit` — too frequent (per-minute window or too many parallel requests): wait `Retry-After` and retry.
- `quota_exceeded` — the daily quota (or the plan's token window) is used up until the time in the message: do not retry before then.

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 18342
x-ratelimit-remaining-requests: 0

{"error": {"type": "quota_exceeded", "code": "chat_completions_per_day",
  "limit_key": "chat_completions_per_day", "limit": 5000, "retry_after": 18342,
  "message": "Quota giornaliera di richieste esaurita: si azzera alle 00:00 del 26/09/2026.", "param": null}}
```

A request counts toward the daily quota as soon as it is accepted; its tokens are added when it completes. The token check happens before a call, so the last call of the day can go slightly over the token quota.

#### 13.5.9 Data retention

Calls to this endpoint create **no chat session and no history** in the account: after any number of API calls the account's chat list is unchanged. The service keeps only the request and token counters and a technical log line (account, key id, token counts, duration) — never the content of the messages, the tools or the answers. The exact list of what is kept is in §18.6.

#### 13.5.10 Errors

| Status | `error.type` | When |
|--------|--------------|------|
| `400` | `invalid_request_error` | Invalid body, message, tool, `tool_choice`, `response_format` or parameter (`param` names the field), unknown model, prompt too long for the context window, unreadable file |
| `401` | `authentication_error` | Missing/invalid token or key (`invalid_api_key`), revoked key (`revoked_api_key`) |
| `403` | `permission_error` | Account without the Chat app, or suspended |
| `413` | `invalid_request_error` | Body over 48 MB |
| `429` | `rate_limit` / `quota_exceeded` | §13.5.8 |
| `503` | `server_error` | Engine busy or unavailable — retry after `Retry-After` |

### 13.6 Models — `GET /v1/models`

Lists the chat model available on `/v1/chat/completions` (OpenAI shape). `GET /v1/models/{id}` returns one entry, or `404` for an unknown id.

```json
{"object": "list", "data": [{"id": "lumanexai", "object": "model", "created": 1767225600, "owned_by": "lumanexai"}]}
```

---

## 14. Code execution

### 14.1 Charts — `POST /exec-chart`

Generates a chart from Python/matplotlib code. **Bearer** required.

**Body:**

```json
{ "code": "import matplotlib.pyplot as plt\nplt.plot([1,2,3],[4,5,6])" }
```

**Response (200):**

```json
{ "image": "data:image/png;base64,..." }
```

**Error (400 / 200 with `error`):**

```json
{ "error": "error description" }
```

**Service unavailable (503):**

```json
{ "error": "Chart execution is temporarily unavailable." }
```

**Constraints:**

- `code` size ≤ **15,000 characters** (otherwise `400`).
- Code runs in an isolated sandbox. System and network modules (`os`, `sys`, `subprocess`, `socket`, `urllib`, `requests`, …) and dynamic-eval calls are disabled; disallowed code returns `400`.
- Execution timeout: 30 seconds. Exceeding it returns an `error`.

### 14.2 General sandbox — `POST /exec-code`

Runs code in an isolated environment and captures stdout, stderr, images, and produced files. **Bearer** required.

**Supported languages:** `python`, `javascript` (alias `nodejs`), `bash` (alias `sh`)

**Body:**

```json
{
  "code": "print('hello world')",
  "language": "python"
}
```

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `code` | string | Yes | Maximum size: 30 KB |
| `language` | string | No | Default: `python` |

**Response (200):**

```json
{
  "ok": true,
  "exit_code": 0,
  "stdout": "hello world\n",
  "stderr": "",
  "elapsed_ms": 312,
  "images": ["data:image/png;base64,..."],
  "files": [{ "name": "output.csv", "content": "col1,col2\n1,2\n" }]
}
```

| Field | Type | Description |
|-------|------|-------------|
| `ok` | bool | `true` if it ran without timeout, `false` if interrupted |
| `exit_code` | int | Process exit code; `0` = success, `-1` = timeout |
| `stdout` | string | Standard output (truncated at 20,000 chars) |
| `stderr` | string | Errors/warnings (truncated at 20,000 chars) |
| `elapsed_ms` | int | Execution time in milliseconds |
| `images` | array of strings | Data URIs of produced images (`png`, `jpg`, `svg`, `gif`) |
| `files` | array of objects | Text files produced: `{ "name", "content" }` (max 5,000 chars per file) |

**Timeout response (200):**

```json
{
  "ok": false,
  "exit_code": -1,
  "stdout": "",
  "stderr": "Timeout: execution stopped after 15s.",
  "elapsed_ms": 15000,
  "images": [],
  "files": []
}
```

**Errors (400):**

```json
{ "error": "Language 'ruby' not supported. Available: bash, js, py" }
```

**Notes:**

- Maximum timeout is **15 seconds** per execution.
- Network operations and risky system modules are blocked server-side.
- Code runs in an isolated temporary directory that is removed afterwards.
- For Python, `matplotlib` is available with a non-interactive backend; saved images are returned in `images`.

---

## 15. Best practices

### Token and session

- Centralize obtaining and refreshing the token.
- On `401`, guide the user to login without infinite retry loops.
- Never store passwords or tokens in plaintext on disk or in logs.
- For server-to-server integrations use an API key (§3.9) per environment instead of a stored password; revoke it when it leaks or the environment is retired.

### Retry

- Backoff with jitter on `429` (`rate_limit`), `502`, `503`, `504`; honour `Retry-After`.
- Don't retry a `429` of type `quota_exceeded` before its reset: read `x-ratelimit-remaining-*` to slow down before you get there.
- Avoid unlimited automatic retries on `400`, `403`, `404`.

### SSE

- Use a client read timeout; handle network disconnections.
- After `[DONE]`, reconcile with a `GET` of the session.
- Be idempotent in the UI so chunks are not duplicated.
- Handle `corrected_response`: replace the current bubble text instead of appending.

### Upload

- Validate extension and size before sending.
- Show progress; for very large files consider a step-based UX (dataset vs chat).

### Chat variants

- Don't assume the last message `mid` stays stable after a regeneration — refetch the session after `[DONE]`.
- Use `variant_total` to decide whether to show the variant navigator (hide it when absent or `≤ 1`).

### Sandbox

- Don't run unvalidated user input through `/exec-code`; validate code in your app first.
- Handle the `ok: false` (timeout) case explicitly.

### Observability

- Track latency for login, first SSE token, and job completion.
- Classify errors as `4xx` vs `5xx` vs stream errors.

---

## 16. Quick examples

### 16.1 Login

```bash
curl -sS -X POST "https://app.lumanex.it/ai/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"user","password":"pass"}'
```

Save `token` from the JSON response.

### 16.2 Create an account

```bash
curl -sS -X POST "https://app.lumanex.it/ai/auth/register" \
  -H "Content-Type: application/json" \
  -d '{"name":"Jane Doe","username":"jane.doe","email":"jane@example.com","password":"secret123"}'
```

After `201`, log in with `POST /auth/login`.

### 16.3 Create a chat session and send a message

1. `POST /auth/login` → `token`
2. `POST /chat/sessions` with `Authorization: Bearer YOUR_TOKEN` → `sid`
3. `POST /chat/sessions/{sid}/message` with the same header, JSON or multipart body → consume SSE until `[DONE]`
4. `GET /chat/sessions/{sid}` for the updated state

### 16.4 Upload a RAG document and poll

1. `POST /docs` multipart with the file
2. Read `doc_id` from the response
3. Repeat `GET /docs/{doc_id}/status` until processing is complete

### 16.5 Navigate variants (regeneration)

```js
// 1. Regenerate
await fetch(`/chat/sessions/${sid}/message`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}` },
  body: JSON.stringify({ content: "", regenerate_from_msg_id: mid }),
});
// ... consume SSE until [DONE] ...

// 2. Fetch available variants
const { variants } = await fetch(
  `/chat/sessions/${sid}/messages/${newMid}/variants`,
  { headers: { Authorization: `Bearer ${token}` } }
).then(r => r.json());

// 3. Activate the desired variant
await fetch(`/chat/sessions/${sid}/messages/${targetMid}/switch-variant`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}` },
});
```

### 16.6 Run Python code

```bash
curl -sS -X POST "https://app.lumanex.it/ai/exec-code" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"code":"for i in range(3):\n    print(i**2)","language":"python"}'
```

**Expected response:**

```json
{
  "ok": true,
  "exit_code": 0,
  "stdout": "0\n1\n4\n",
  "stderr": "",
  "elapsed_ms": 180,
  "images": [],
  "files": []
}
```

### 16.7 Create a project and move a chat into it

```bash
# 1. Create the project
PID=$(curl -sS -X POST "$BASE/chat/projects" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Thesis","description":"Chapter 3 - Analysis","color":"#6366f1"}' | jq -r '.id')

# 2. Create a chat directly inside the project
SID_NEW=$(curl -sS -X POST "$BASE/chat/sessions" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"title\":\"Chapter 3 - intro\",\"project_id\":\"$PID\"}" | jq -r '.id')

# 3. Move an existing chat into the project
curl -sS -X PUT "$BASE/chat/sessions/$EXISTING_SID/project" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"project_id\":\"$PID\"}"

# 4. List the project's chats
curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/chat/projects/$PID" \
  | jq '.chats[] | {id, title, updated_at}'
```


### 16.8 Tool-calling loop with the OpenAI SDK

```python
import json
from openai import OpenAI

client = OpenAI(base_url="https://app.lumanex.it/ai/v1", api_key="lxk_…")
tools = [{"type": "function", "function": {
    "name": "getOverdueInvoices", "description": "Overdue unpaid invoices",
    "parameters": {"type": "object", "properties": {}}}}]
messages = [{"role": "system", "content": "Use the tools for data."},
            {"role": "user", "content": "Who has not paid?"}]

while True:
    resp = client.chat.completions.create(model="lumanexai", messages=messages,
                                          tools=tools, temperature=0.2, max_tokens=800)
    msg = resp.choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg.model_dump(exclude_none=True))
    for call in msg.tool_calls:
        result = my_backend(call.function.name, json.loads(call.function.arguments))
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
```

---

## 17. Integration checklist

- [ ] End-to-end authentication and `401` handling
- [ ] Chat session lifecycle (create / list / detail / delete)
- [ ] SSE parser handling `error`, `doc_ready`, `sandbox_event` (`artifact.published`, `approval.requested`), `choice_prompt`, `corrected_response`
- [ ] Chat attachment upload (multipart)
- [ ] Message feedback (optional but recommended)
- [ ] Variant navigation: `GET .../variants` + `POST .../switch-variant`
- [ ] Show `variant_total` to toggle the variant navigator
- [ ] Chat projects: list projects + group chats client-side by `project_id`
- [ ] Centralized error handler and safe user messages
- [ ] Retry / backoff policy
- [ ] Documents: upload + status polling
- [ ] Code execution: timeout (`ok: false`) handling, base64 image render, file download
- [ ] Presentations if included in your contract
- [ ] Client-side logging and metrics without sensitive data
- [ ] OpenAI-compatible API: one API key per environment, `429` handling by `error.type` (`rate_limit` vs `quota_exceeded`), `x-ratelimit-remaining-*` monitoring
- [ ] Tool loop: assistant message resent unchanged + one `tool` message per `tool_call_id`
- [ ] Compliance (§18): a visible notice for end users that they are interacting with an AI, in voice and chat channels too, and the AI never presented as a person
- [ ] Compliance (§18): `X-AI-Generated` header read and kept, markings and metadata of synthetic content not removed, deepfakes and texts on matters of public interest labelled
- [ ] Compliance (§18): system prompt and safety measures towards your users defined by you (`/v1/chat/completions` adds only LumanexAI's fixed system block, §18.4); DPA (§18.1) in force; service not exposed to minors without the safeguards required by law

---

## 18. Compliance, transparency and integrator responsibilities

This section is for anyone who integrates LumanexAI into a product or service used by other people (customers, end users, employees). It is a developer guide: **it does not replace the contractual documents and is not legal advice**. If they differ, the legal documents prevail.

### 18.1 Roles and documents

- **Lumanex S.r.l.** is the **provider** of the AI system "LumanexAI" under Regulation (EU) 2024/1689 (the AI Act).
- **The integrator** that uses the system in its own application is normally the **deployer**: it answers to its own end users for the obligations described in §18.2 to §18.5.
- **Personal data.** For the personal data of your end users that reaches LumanexAI through the API, Lumanex normally acts as **processor** (Article 28 GDPR) and you as controller: the Data Processing Agreement applies ([DPA](https://app.lumanex.it/ai/legal/dpa)). For the data of your own account (registration, API keys, usage counters) Lumanex is the controller, as described in the privacy notice.

Reference documents:

| Document | Where |
|----------|-------|
| Terms and conditions for the supply of Lumanex services (contractual base; clause 17 covers AI services), in Italian | [https://www.c1vhosting.it/agreements/2026/termini_e_condizioni.pdf](https://www.c1vhosting.it/agreements/2026/termini_e_condizioni.pdf) |
| Privacy notice (base; section 10 covers AI), in Italian | [https://www.c1vhosting.it/agreements/2026/informativa_privacy.pdf](https://www.c1vhosting.it/agreements/2026/informativa_privacy.pdf) |
| Service-specific terms for LumanexAI | [https://app.lumanex.it/ai/legal/terms-ai](https://app.lumanex.it/ai/legal/terms-ai) |
| Service-specific privacy notice for LumanexAI | [https://app.lumanex.it/ai/legal/privacy-ai](https://app.lumanex.it/ai/legal/privacy-ai) |
| API terms | [https://app.lumanex.it/ai/legal/api-terms](https://app.lumanex.it/ai/legal/api-terms) |
| Acceptable use policy | [https://app.lumanex.it/ai/legal/aup](https://app.lumanex.it/ai/legal/aup) |
| Data Processing Agreement (Article 28 GDPR) | [https://app.lumanex.it/ai/legal/dpa](https://app.lumanex.it/ai/legal/dpa) |
| AI transparency | [https://app.lumanex.it/ai/legal/ai-transparency](https://app.lumanex.it/ai/legal/ai-transparency) |
| Recipients and sub-processors | [https://app.lumanex.it/ai/legal/subprocessors](https://app.lumanex.it/ai/legal/subprocessors) |

The LumanexAI-specific documents supplement the base documents for the use of the AI service and do not replace them.

### 18.2 Tell end users they are interacting with an AI (Article 50(1))

People interacting with an AI system must know it, unless it is obvious from the circumstances and the context of use (Article 50(1) of the AI Act, applicable from 2 August 2026). The API has no interface towards your users: **you give that information**, in your application.

- **Web and mobile front ends.** A visible, permanent indication next to the conversation (for example "You are talking to an AI-based assistant"), in the user's language, shown before or at the start of the interaction. Writing it in the terms of use is not enough.
- **Voice channels.** A spoken notice at the start of the call or voice message; if the voice is synthetic, say so.
- **Chat, messaging, email and automatic tickets.** The indication in the first message or in every automatically generated reply.
- **Do not present the AI as a person.** No name, photo, avatar or phrasing that suggests a human operator, and no instruction in the system prompt to deny being an AI. Anyone who asks whether they are talking to a person gets a truthful answer.
- **Possible errors.** Answers can be inaccurate: say so in the interface and provide human verification when the outcome matters.

### 18.3 Marking synthetic content (Article 50(2), (4) and (5))

**Response headers.** Every successful response of `POST /v1/chat/completions`, JSON or SSE, carries:

```http
X-AI-Generated: true
X-AI-System: LumanexAI
```

- When streaming, the headers are sent with the response head, before the first chunk.
- They are not present on errors (4xx and 5xx) nor on `GET /v1/models`, which carry no generated text.
- The body does not change: it stays in the OpenAI format, with no extra fields. The headers are HTTP metadata: read them in your backend.
- The headers mark the response; they do not travel with the text once you extract it. If you store, forward or publish the content, you are the one who keeps and shows the indication that it is AI-generated.

**Do not remove markings.** If content you receive or produce with LumanexAI carries markings or metadata identifying it as AI-generated (for example the metadata embedded in images and in the properties of documents generated by LumanexAI features), do not remove them, alter them, or circumvent them with conversions or re-exports that strip them.

**Label when required (Article 50(4)).**

- **Deepfakes.** Generated or manipulated images, audio or video that resemble real people, objects, places or events and could appear authentic must be clearly disclosed as artificial or manipulated.
- **Texts on matters of public interest.** AI-generated or manipulated text published to inform the public on matters of public interest must be labelled as such, unless it has undergone human review or editorial control and a natural or legal person holds editorial responsibility for it.

The indication must be clear and distinguishable, at the latest at the first interaction or exposure (Article 50(5)).

### 18.4 What `/v1/chat/completions` adds and what it does not

The route is **stateless**: it adds no memory, RAG, skills, web access or verticals ("law firm", "medical"). It does prepend to your messages, in the same system message, **LumanexAI's fixed system block**, the same one the chat applies to every conversation: priority of instructions, confidentiality and resistance to manipulation attempts (jailbreak), identity (the assistant presents itself as LumanexAI and does not disclose the underlying model), factual accuracy and assistant behaviour. Your `system` and `developer` instructions follow it and define role and task within those rules. Tools, `response_format` and parameters stay yours (§13.5). The block **does not count** against your tokens: `usage`, the daily quotas and the plan budgets include only the tokens of your messages and of the reply (the block is about 3,600 tokens, served from the prefix cache after the first call).

It follows that **you are responsible** for:

- your system prompt: role, limits, language, what the assistant must not do (LumanexAI's block does not replace it);
- the safety measures towards your users: validation and filtering of input and output where the context requires it, protection against manipulation attempts, usage limits, content moderation;
- human oversight for decisions that affect people, and verification of answers before acting on them;
- any use in a medical, legal or financial setting: the notices and constraints of the verticals exist only in the LumanexAI app, not on this route.

### 18.5 Acceptable use, minors and suspension

Use is governed by the [Acceptable use policy](https://app.lumanex.it/ai/legal/aup) and the [API terms](https://app.lumanex.it/ai/legal/api-terms). Among others, the following are prohibited (the complete, binding list is in those documents):

- the practices banned by Article 5 of the AI Act, including deceptive manipulation, exploitation of vulnerabilities, social scoring, biometric surveillance and identification that is not permitted, and emotion recognition in the workplace and at school;
- creating child sexual abuse material (CSAM) and sexualizing minors;
- creating intimate or demeaning images of real people without their consent (intimate deepfakes);
- fraud, phishing, impersonation, disinformation meant to deceive, and any other unlawful activity;
- decisions taken solely by automated means with legal or similarly significant effects on people, in particular in the high-risk areas of Annex III (employment, credit, education, access to essential services, law enforcement, justice), without effective human oversight. LumanexAI is not intended for these uses.

**Minors.** The service is reserved for people aged 14 and over; no access is provided for children under 14 (Article 4 of Italian Law 132/2025). Registration in the LumanexAI app blocks anyone who declares they are under 14, but calls made with an API key do not go through that check: if your application can be used by children under 14, **do not expose the service to them without the safeguards required by law**.

**Suspension.** In case of violation of the acceptable use policy or of the API terms, or for security reasons, Lumanex may suspend the account or revoke keys. A suspended account receives `403` with `code: "account_suspended"`; a revoked key receives `401` with `code: "revoked_api_key"`.

### 18.6 Data and logs

Calls to `/v1/chat/completions` **create no session and no history**. The service does not record the content of messages, tools, files or answers. What remains is only:

- the request and token counters of the day per account (they expire after about 25 hours) and the token consumption of the account (app `api`), with an activity event that carries the counts only;
- the date of the key's last use, updated at most once a minute;
- one technical log line per call: account and key identifiers, streaming yes or no, number of tools and of tool calls, finish reason, prompt tokens (of which cached) and completion tokens, duration; if the engine returns an error, the line may include the engine's error message (at most 300 characters);
- an event when a request exceeds a quota (limit key and value);
- the access logs of the network infrastructure, holding connection metadata only (IP address, route, outcome), kept for 14 days.

Inference runs on infrastructure managed by Lumanex: the content of requests is not sent to external AI model providers. The list of recipients and sub-processors is at [Recipients and sub-processors](https://app.lumanex.it/ai/legal/subprocessors).

Because the service does not record the content of these calls, it **cannot return it afterwards**: if you need traceability and audit of conversations, record them yourself, in compliance with personal data law and with the notice you give your users.

### 18.7 Reporting abuse and serious incidents

To report an abuse or a serious incident related to the use of LumanexAI (a compromised API key, use for prohibited purposes, output that caused or risks causing harm to people, a personal data breach):

- email: **dpo@c1vhosting.it**
- certified email (PEC), when a communication with legal value is needed: **lumanex@pec.it**

Include date and time (with time zone), the key `id` (never the value), the route and what happened. **Do not send the value of a key or unnecessary personal content.** If a key is compromised, revoke it immediately with `DELETE /settings/api-keys/{id}` (§3.9): the effect is immediate.

Also provide, in your application, a channel through which your users can report problems with the AI's answers and, for the personal data of which you are the controller, exercise their rights.

---

*Need help integrating? Visit [lumanex.it](https://www.lumanex.it) or reach out to your LumanexAI contact. API limits, quotas, and environments may vary by plan — confirm current values with your provider.*
