# Developer API

[Guide index](../v1.md) · [API reference](api-reference.md) · [For AI agents](agents.md)

Everything an API key can do: chat for your own app or website, and managing your company (resources, rules, users, channels and the rest) the way the panel does.

## Base URL

Your region's API: **`https://api.eu.determesh.com`** for the EU region. A key works only in the region it was issued in.

## API keys

Issued on the panel's **Channels** page (see [Panel: Channels](panel-channels.md)). Each key has:

- the **key** (`dmk_...`), sent with every request;
- its **signing secret** (`dms_...`), used to sign requests and never sent;
- optionally a **webhook** with its own **webhook signing secret** (`dmw_...`), used to verify what we send you;
- **sections and folders**, fixed when issued:

| Section | What it opens |
|---|---|
| **Chat** | `POST /v1/messages` and `GET /v1/threads/...`: your users' messages and replies. Not limited by folder. |
| Company settings | Name, summary, settings, AI choice, your SMTP. |
| Channels | Telegram bots, mailboxes, channel restrictions. |
| API keys and webhook | Issuing and revoking keys, webhooks and their deliveries. |
| Resources | The resource tree, methods, documents, notes, code, databases, webhooks into resources, verification groups. |
| Access rules | The rules. |
| Identities | Users, attributes, blocks, the "what they can reach" preview. |
| Threads and emails | Reading and deleting conversations; sending and listing emails. |
| Requests | Messages for resources and their replies. |
| Audit log | Reading and clearing the audit log. |
| Billing | Reading the balance, usage, plans and ledger. |
| Spending cap | Setting the cap. |
| Sub users | Managing sub users. |

**Folders** (each with everything under it, Read only or Manage) limit what a key reaches in Resources and Access rules: read to look, manage to change. A key gets only what its issuer holds. Never by key: payments, a login's own email, password and authenticator, and deleting the company.

Keep keys and secrets on your server, never in a browser or mobile app.

## Signing a request

Every request carries four headers:

| Header | Value |
|---|---|
| `X-Determesh-Key` | The key, `dmk_...` |
| `X-Determesh-Timestamp` | Unix time in **seconds** |
| `X-Determesh-Nonce` | A random string, up to 128 characters, never reused |
| `X-Determesh-Signature` | Lowercase hex HMAC-SHA256, keyed with the signing secret (`dms_...`) |

The string to sign is: the timestamp, the nonce, the HTTP method in upper case, and the path with its query string, **each followed by a newline**, then the **raw body bytes** (nothing for a GET).

```
1762981234\n
3f9a2c...\n
POST\n
/v1/messages\n
{"userId":"u-1042","text":"What is my leave balance?"}
```

### Python

```python
import hashlib, hmac, json, secrets, time, urllib.request

KEY, SECRET = "dmk_...", "dms_..."
BASE = "https://api.eu.determesh.com"

def call(method, path, body=None):
    raw = json.dumps(body).encode() if body is not None else b""
    ts, nonce = str(int(time.time())), secrets.token_hex(16)
    sig = hmac.new(SECRET.encode(), f"{ts}\n{nonce}\n{method}\n{path}\n".encode() + raw, hashlib.sha256).hexdigest()
    req = urllib.request.Request(BASE + path, data=raw or None, method=method, headers={
        "Content-Type": "application/json", "X-Determesh-Key": KEY, "X-Determesh-Timestamp": ts,
        "X-Determesh-Nonce": nonce, "X-Determesh-Signature": sig})
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read() or b"null")

print(call("POST", "/v1/messages", {"userId": "u-1042", "text": "What is my leave balance?"}))
```

### Node.js

```js
import crypto from "node:crypto";

const KEY = "dmk_...", SECRET = "dms_...", BASE = "https://api.eu.determesh.com";

async function call(method, path, body) {
  const raw = body === undefined ? "" : JSON.stringify(body);
  const ts = Math.floor(Date.now() / 1000).toString();
  const nonce = crypto.randomBytes(16).toString("hex");
  const sig = crypto.createHmac("sha256", SECRET)
    .update(`${ts}\n${nonce}\n${method}\n${path}\n`).update(raw).digest("hex");
  const res = await fetch(BASE + path, {
    method, body: raw || undefined,
    headers: { "Content-Type": "application/json", "X-Determesh-Key": KEY, "X-Determesh-Timestamp": ts,
               "X-Determesh-Nonce": nonce, "X-Determesh-Signature": sig },
  });
  return res.status === 204 ? null : res.json();
}
```

Sign the exact bytes you send. A request older than 5 minutes, a reused nonce, or a wrong signature is refused.

## Chat

### Sending a message

`POST /v1/messages`

```json
{ "userId": "u-1042", "text": "What is my leave balance?", "threadId": "optional, to continue a thread", "longRunning": false }
```

- `userId`: **your own** ID for the user, up to 200 characters. It is trusted: your backend vouches for who the user is. The same `userId` is the same identity every time.
- `text`: up to 20,000 characters.
- `threadId`: leave out to open a new conversation; give it to continue one.
- `longRunning` (optional): `true` for a conversation the user keeps coming back to, like a chat. When such a thread has grown large and gone quiet, Determesh summarises it just before the AI provider's cache of it expires, so the user's next message costs less. Left out, a new thread is short-lived (most API threads are one task) and an existing one keeps what it had.

Answers **202** at once with `messageId`, `threadId` and `receivedAt`. The reply comes later, by webhook, and can also be read from the thread. A reply can take from a few seconds to a few minutes when the work is long. If the user sends another message before the reply, the assistant takes it into the work already under way and one reply answers both; if the reply was already being written, it is sent and the newer message gets its own reply after it.

### Receiving replies by webhook

Set a webhook on the key (Channels page, or `PUT /v1/companies/{companyId}/api-keys/{keyId}/webhook`). For every reply or progress update on that key's conversations we `POST` to your URL:

```json
{
  "deliveryId": "…",
  "event": "message.created",
  "time": "2026-11-12T10:15:30Z",
  "apiKey": { "id": "…", "label": "shop backend", "summary": "…" },
  "threadId": "…",
  "chatId": "…",
  "userId": "u-1042",
  "seq": 2,
  "response": "You have 12 days of annual leave left.",
  "files": [ { "fileId": "…", "name": "payslip-oct.pdf", "contentType": "application/pdf", "sizeBytes": 48211,
               "url": "/v1/threads/{threadId}/files/{fileId}" } ]
}
```

- `seq` numbers the user's messages and replies 1, 2, 3 within the thread.
- `files` appears when the assistant handed over files; download each from its `url`, signed like any call. A file the report maker made for the user (a PDF report, a spreadsheet) can be downloaded until the company's download-link hours after it was made (6 by default); fetch it when the webhook arrives.
- Headers: `X-Determesh-Delivery` (use it to ignore a repeat), `X-Determesh-Event`, `X-Determesh-Timestamp`, `X-Determesh-Nonce`, `X-Determesh-Signature`.

**Verify every delivery:** compute lowercase hex HMAC-SHA256, keyed with the **webhook signing secret** (`dmw_...`), over the timestamp, the nonce, `POST`, and the path of your webhook URL with its query string, each followed by a newline, then the raw body. Compare in constant time, and reject a timestamp more than 5 minutes off.

**Answer 2xx within 10 seconds** (do the work afterwards). Redirects are not followed. Failed deliveries are retried with growing gaps (up to 5 days apart) for up to 15 days; while your endpoint is down, later deliveries wait behind the oldest, and all go as soon as one gets through, oldest first. A dropped delivery never loses a reply: it stays in the thread.

Other events, if the key subscribes: `email.sent`, `email.failed`, `email.bounced` (with `emailId`, `to`, `resourceId`, `threadId`, `status`, `error`), `upload.processing` and `upload.ready`. `GET /v1/companies/{companyId}/webhook/events` lists them; `GET .../webhook/deliveries` shows each delivery and your server's answer.

### Reading threads

- `GET /v1/threads?userId=u-1042&page=0&size=20`: the user's threads, newest activity first, with status `idle`, `working` or `failed`.
- `GET /v1/threads/{threadId}/messages?afterSeq=0&limit=50`: the user's messages and the replies, oldest first, numbered by `seq`. Pass `nextAfterSeq` back to page on. Use it to catch up on anything a webhook missed, or instead of a webhook (polling).
- `GET /v1/threads/{threadId}/files/{fileId}`: a file handed over in that thread.

Only your own company's threads; anything else is 404.

## Managing your company by API

With the sections above, a key does what the panel pages do. The [API reference](api-reference.md) lists every endpoint by section. Some things to know:

- Paths are `/v1/companies/{companyId}/...`; `{companyId}` must be your own company's id. `GET /v1/companies/{companyId}` returns your company; `GET /v1/auth/me` is panel-only, so find the id once in the panel's address bar (`/c/<companyId>/...`) or from a previous answer.
- **Uploading a document:** `PUT .../resources/{folderId}/documents?name=handbook.pdf&read=true&share=false` with the file as the raw body and its type as `Content-Type`, up to 1 GB. Sign it like any request (the signature covers the file's bytes). A file resource takes `PUT .../resources/{resourceId}/file?name=...`.
- **Code:** `PUT .../resources/{resourceId}/code` with the script as the raw body.
- Saving a database connection, a mailbox or your SMTP logs in first; a wrong login is refused with the server's reason.
- Rule changes on a folder that keeps notes need a decision for the notes (`notes.decision`: `MIRROR`, `SEPARATE` or `LEAVE`), or the API answers `400 notes_decision_required`.
- Changes are recorded in the audit log as made by the key.

## Errors

Errors are JSON: `{"code": "machine_readable_code", "message": "A sentence for a person"}`.

| Status | Meaning |
|---|---|
| 400 | The request is not valid; `code` and `message` say why. |
| 401 | Missing or wrong signature, unknown or revoked key, timestamp out of range, or a reused nonce. No body. |
| 403 | The caller's address is not on the company's IP allowlist (no body), or the key lacks the section (`section_not_granted`). |
| 404 | Not found, or not yours, or outside the key's folders. |
| 409 | A conflict, such as `setup_incomplete` (no fallback set yet) or a thread still busy. |
| 413 | The body is over 1 MB (uploads excepted). No body. |
| 429 | More than 120 calls a minute on this key. No body. Wait and retry. |
| 503 | Messages are not being taken: `billing_no_plan`, `billing_trial_ended`, `billing_out_of_credit`, `billing_cap_reached`, or `maintenance` during a release (retry shortly). |

## Limits

120 signed calls per key per minute; 1 MB per request body (uploads up to 1 GB); message text up to 20,000 characters. More in [Limits](limits.md).
