# Events

**At the end of this page your server verifies every event hlix sends, handles each one once and recovers from a failed delivery.** hlix sends an HTTPS `POST` with a JSON body to the event URL saved for each mode (Test and Live).

## How events work

When an agent connection changes or a request finishes, hlix records one fixed event payload and delivers it to your mode's event URL. You verify the signature before reading the JSON, deduplicate on the event ID and return any `2xx` status within 10 seconds.

## Before you start

- An event URL saved on the app ([Set the event URL](/partners/portal/#set-the-event-url)).
- The app's event secret for that mode (`hes_...`). Test and Live have separate secrets.

## Event types

| Type | When hlix sends it |
| --- | --- |
| `agent.connected` | An agent owner (your seller or freelancer who owns hlix agents) connected an agent to your app. |
| `agent.updated` | A connected agent's name or service line changed. |
| `agent.disconnected` | A connection ended (unchecked in Connect, disconnected in the agent owner's hlix account, agent switched off, owner left the Workspace or your app called `DELETE`). |
| `request.started` | A request you sent was handed to the agent's project. |
| `request.delivered` | The agent finished a request and its delivery is ready to read. Sent once per request. |
| `test.ping` | Triggered manually by **Send a test event** in the portal. Never retried. |

## The payload

Every event uses the same JSON envelope:

```json
{
  "id": "evt_6a1c0d94e2b84f7f9a5d2c0b7e31f4aa",
  "type": "request.delivered",
  "createdAt": "2026-11-26T09:14:03.512Z",
  "appId": "app_01j9x7k9m2p4r6t8v0w2y4z6ab",
  "mode": "test",
  "data": {
    "requestId": "a41e8c3f-7b2d-4f09-9d6a-5c2e8b1a4f70",
    "connectionId": "6f1c4b2e-9a8d-4c11-8e2f-3b7a1d5e9c02",
    "status": "done"
  }
}
```

`createdAt` is an ISO 8601 UTC timestamp. `data` contains only IDs and fields the agent owner agreed to share—never an email address or a Workspace name.

| Event types | `data` fields |
| --- | --- |
| `agent.connected`, `agent.updated`, `agent.disconnected` | `connectionId`, `agentId`, `name`, `service` |
| `request.started`, `request.delivered` | `requestId`, `connectionId`, `status` (`"received"` on `request.started`, `"done"` on `request.delivered`) |
| `test.ping` | `message` |

## The headers

| Header | Value |
| --- | --- |
| `hlix-event-id` | The event's `id`. Identical across every retry. |
| `hlix-event-type` | The event's `type`. |
| `hlix-timestamp` | Unix timestamp in **seconds** when this delivery attempt was signed. |
| `hlix-signature` | `v1=` followed by the 64-character lowercase hex HMAC-SHA256 of `<hlix-timestamp>.<raw body>`, keyed with the mode's event secret. |

## Verify an event

hlix signs every event so you know it came from hlix and was not altered in transit. Check the signature before parsing the JSON body.

1. **Read the raw body.** Keep the exact bytes you received. Parsing JSON and serializing it again can change whitespace or key order and break the signature.
2. **Read two headers.** Read `hlix-timestamp` (Unix seconds) and `hlix-signature` (`v1=<hex>`). Reject the request if either is missing.
3. **Check the timestamp.** Parse `hlix-timestamp` safely—reject non-numeric values—and refuse events older or newer than 5 minutes (300 seconds) from your clock to block replay attacks.
4. **Compute the signature.** Compute HMAC-SHA256 over `<hlix-timestamp>.<raw body>` using your mode's event secret (`hes_...`), format as lowercase hex and prefix with `v1=`.
5. **Compare in constant time.** Use your language's constant-time compare function, never `==`. If it does not match, answer `400` and stop.

**Node.js (`events.ts` with Express):**

```ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import express from 'express'

const EVENT_SECRET = process.env.PARTNER_EVENT_SECRET! // starts with hes_
const TOLERANCE_SECONDS = 300

export function isFromHlix(
  rawBody: Buffer,
  timestamp: string | undefined,
  signature: string | undefined,
  secret = EVENT_SECRET,
  nowSeconds = Date.now() / 1000,
): boolean {
  if (!timestamp || !signature) return false

  const sentAt = Number(timestamp)
  if (!Number.isFinite(sentAt)) return false
  if (Math.abs(nowSeconds - sentAt) > TOLERANCE_SECONDS) return false

  const signed = Buffer.concat([Buffer.from(`${timestamp}.`), rawBody])
  const expected = Buffer.from('v1=' + createHmac('sha256', secret).update(signed).digest('hex'))
  const received = Buffer.from(signature)

  return expected.length === received.length && timingSafeEqual(expected, received)
}

const handled = new Set<string>() // replace with your database in production

const app = express()

// Register express.raw BEFORE express.json() so rawBody holds the exact received bytes.
app.post('/hlix/events', express.raw({ type: 'application/json' }), (req, res) => {
  const rawBody = req.body as Buffer
  if (!isFromHlix(rawBody, req.header('hlix-timestamp'), req.header('hlix-signature'))) {
    res.sendStatus(400)
    return
  }

  let event: { id: string; type: string; data: Record<string, unknown> }
  try {
    event = JSON.parse(rawBody.toString('utf8'))
  } catch {
    res.sendStatus(400)
    return
  }

  if (!handled.has(event.id)) {
    handled.add(event.id)
    // Queue slow work (reading deliveries, downloading files) after you answer.
  }
  res.sendStatus(200)
})

app.listen(3000)
```

**Python (`events.py` with Flask):**

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

EVENT_SECRET = os.environ["PARTNER_EVENT_SECRET"]  # starts with hes_
TOLERANCE_SECONDS = 300

app = Flask(__name__)
handled: set[str] = set()  # replace with your database in production

def is_from_hlix(
    raw_body: bytes,
    timestamp: str | None,
    signature: str | None,
    secret: str = EVENT_SECRET,
    now_seconds: float | None = None,
) -> bool:
    if not timestamp or not signature:
        return False
    try:
        sent_at = float(timestamp)
    except ValueError:
        return False
    now = time.time() if now_seconds is None else now_seconds
    if abs(now - sent_at) > TOLERANCE_SECONDS:
        return False

    signed = timestamp.encode() + b"." + raw_body
    expected = "v1=" + hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

@app.post("/hlix/events")
def events():
    raw_body = request.get_data()  # raw bytes before JSON parsing
    if not is_from_hlix(raw_body, request.headers.get("hlix-timestamp"), request.headers.get("hlix-signature")):
        return "", 400

    try:
        event = json.loads(raw_body)
    except json.JSONDecodeError:
        return "", 400

    if event["id"] not in handled:
        handled.add(event["id"])
        # Queue slow work (reading deliveries, downloading files) after you answer.
    return "", 200
```

### Test vector

Verify your signature function offline before pointing hlix at your server. With `nowSeconds = 1790000000`:

| Input | Value |
| --- | --- |
| Event secret | `hes_example_secret` |
| `hlix-timestamp` | `1790000000` |
| Raw body | `{"id":"evt_example","type":"test.ping","createdAt":"2026-11-26T09:14:03.512Z","appId":"app_example","mode":"test","data":{"message":"hello"}}` |
| Expected `hlix-signature` | `v1=711cc9b687f5a8de805df5480ac04cad35e56bfb1bebc25fd10d31c96fa5a7a4` |

## Answer the event

- Return any `2xx` HTTP status within **10 seconds**.
- Do not answer with a `3xx` redirect: hlix does not follow redirects and counts them as failures.
- hlix ignores your response body. Queue slow work (fetching deliveries, downloading files, notifying buyers) in a background job after responding `200`.

## Retries and duplicates

If a delivery attempt fails or times out, hlix retries up to 6 more times (7 attempts total), counting each delay from the previous failed attempt:

| Attempt | Wait after previous failure |
| --- | --- |
| 1 | Immediate |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 6 hours |
| 7 | 12 hours |

No attempt starts more than **24 hours** after the event was created. After the final failure or 24-hour cap, the event becomes `expired` (shown as **Gave up** in the portal).

- **Same ID on every retry.** Every attempt sends the exact same `id`, `hlix-event-id` and body.
- **Deduplicate in your database.** Record each handled event ID before or alongside processing, and return `200` for any ID you already handled.
- **Do not assume ordering.** A retry of an earlier event can arrive after a later event.

If your event endpoint was offline for more than 24 hours, run a catch-up job that lists connections (`GET /v1/api/partner-app/connections`) and reads any open requests (`GET /v1/api/partner-app/requests/{id}`) to reconcile state.

## Test your endpoint

On the app page in the [partner portal](https://partner.hlix.ai), save your event URL and select **Send a test event**. hlix posts a signed `test.ping` and shows the HTTP status and response time immediately:

```json
{
  "id": "evt_8b2d9e41c7a34f5a8e1d6b9c0f2a3e4d",
  "type": "test.ping",
  "createdAt": "2026-11-26T09:14:03.512Z",
  "appId": "app_01j9x7k9m2p4r6t8v0w2y4z6ab",
  "mode": "test",
  "data": {
    "message": "This is a test event from hlix."
  }
}
```

**Screenshot:** The Event URL panel after Send a test event: the result reads 200 OK in 186 ms next to the button.

From **Events** in the portal, you can also select **Send again now** on any event to replay it immediately with the same `id` and body without changing its automatic retry schedule.

## If events do not arrive

Check the **Events** log in the portal. When an event cannot be delivered, hlix records a failure category (never your server's response body):

| Category | Cause | Fix |
| --- | --- | --- |
| `no_event_url` | No event URL was saved for this mode (shown as **Not sent**). | Save an event URL on the app page, then select **Send now** on missed events. |
| `blocked_address` | The event URL resolves to a private, link-local or non-allowed local address. | Use a public HTTPS address (Test mode also allows exact `localhost`, `127.0.0.1` and `[::1]`). |
| `timeout` | Your server did not answer within 10 seconds. | Answer `200` immediately and move file downloads or API calls to a background job. |
| `refused` | The TCP or TLS connection failed. | Confirm your server is listening on the configured host and port with valid TLS. |
| `redirect` | Your server answered with a `3xx` redirect. | Save the final destination URL (check trailing slashes and `www.`) so no redirect occurs. |
| `http_4xx` | Your server returned a `4xx` status—most often `400` from signature verification. | Check that you verify the raw bytes before JSON parsing and use the matching mode's `hes_` secret. |
| `http_5xx` | Your server threw an unhandled error. | Inspect your server logs, fix the handler and replay the event from the portal. |
| `internal` | hlix could not read the signing secret for this delivery. | Replay the event from the portal or contact `support@hlix.ai` with the event ID. |

**Rotate with care:** When you select **Make a new one** on an event secret, the old secret stops signing immediately. Prepare your server deployment first, rotate, deploy the new secret and send a test event to confirm `200 OK`.

## Next steps

[Test and live](/partners/test-and-live/)
  [Errors and troubleshooting](/partners/errors/)
  [Partner API](/api/reference/partner/)