---
title: "Events and webhooks"
description: "Messages, questions, custom events and signed deliveries."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.cloudraker.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Events and webhooks

An agent talks back only through tools. Each tool call becomes one event. You read the events on a stream, page through them, or receive them as webhooks. You never get raw harness logs.

## Event envelope

```json
{
  "id": "evt_01K7Q…",
  "seq": 12,
  "type": "event.label_suggested",
  "ts": "2026-10-15T14:02:19.412Z",
  "run_id": "run_01K7…",
  "agent": "linear-triage",
  "turn": 1,
  "deployment": "a1b2c3d",
  "metadata": { "ticket": "EGR-123" },
  "data": { "label": "bug" }
}
```

| Field        | Rule                                                                                      |
| ------------ | ----------------------------------------------------------------------------------------- |
| `id`         | Unique per org. The same on stream replay and on every webhook retry. De-duplicate on it. |
| `seq`        | From 1, strictly increasing per run, no gaps. Sort on it.                                 |
| `type`       | A built-in type below, or `event.{name}` for a custom event.                              |
| `ts`         | Server time.                                                                              |
| `turn`       | The turn that produced the event.                                                         |
| `deployment` | The commit SHA the run is pinned to.                                                      |
| `metadata`   | The `metadata` of the run request.                                                        |
| `data`       | The tool payload, validated before the event gets its `seq`.                              |

## Built-in tools

| Tool            | Event           | `data`                                                                              |
| --------------- | --------------- | ----------------------------------------------------------------------------------- |
| `message`       | `message`       | `{ id, text }`. Markdown. Many per run. `id` is the message id of the step.         |
| `ask`           | `question`      | `{ question_id, text, choices?, input_schema? }`. `turns` mode only. Ends the turn. |
| `file`          | `file`          | `{ file_id, name, content_type, bytes, url }`. Read [Files](https://docs.cloudraker.com/run/guides/files).     |
| `done`          | `run.completed` | The final result. Validated against `output_schema` when set.                       |
| `data.*` writes | `data.changed`  | Schema, record id and operation. Reads emit nothing.                                |
| `handoff`       | `handoff`       | `{ to, reason }`. Conversation runs only. The run then ends with `run.cancelled` by `handoff`. |
| `switch_language` | `language`    | `{ lang }`. Conversation runs only.                                                 |

The model sees tool names with `_` in place of `.`, for example `data_query`. Events and these pages keep the dotted names.

## Lifecycle events

| Type             | `data`                                                                                   |
| ---------------- | ---------------------------------------------------------------------------------------- |
| `run.started`    | `{ deployment, model?, mode }`. A machine run has no `model`.                           |
| `run.progress`   | `{ text }`. A short step. A tool step adds `tool`, `call_id` and `state`. Read [Tool steps](#tool-steps). |
| `turn.started`   | `{ turn, input? }`. `input` echoes a text input or a text answer, up to 4000 characters. |
| `turn.completed` | `{ turn, reason }`. `reason` is `question`, `yield` or `children` (the run waits for its child runs). |
| `run.completed`  | `{ result, usage }`                                                                      |
| `run.failed`     | `{ code, message, usage }`. Never a stack trace.                                         |
| `run.cancelled`  | `{ by }`. `api`, `console`, `system`, `slack`, `teams`, `parent` (the parent run ended), `handoff` (a [handoff](https://docs.cloudraker.com/run/guides/front-doors#handoff) to another agent) or `conversation` (the conversation ended). |
| `run.expired`    | `{ idle_ttl }`                                                                           |

## Tool steps

Every run sends a tool step for each tool call of the agent: a knowledge search, a document read, a Structured Memory query, an MCP tool, a delegation, a custom event and more. You can show the person what the agent does while it works.

A tool step is a `run.progress` event with these fields:

| Field     | Value                                                                       |
| --------- | --------------------------------------------------------------------------- |
| `text`    | A short business phrase, for example `Searching knowledge for fever in children`. |
| `tool`    | The tool name, for example `knowledge_search` or `emit_triage`.             |
| `call_id` | The id of the tool call. The two events of one call have the same `call_id`. |
| `state`   | `running` before the call, then `done` or `failed` after it.                |

```json
{ "type": "run.progress", "data": { "text": "Searching knowledge for fever in children", "tool": "knowledge_search", "call_id": "toolu_01", "state": "running" } }
{ "type": "run.progress", "data": { "text": "Searched knowledge for fever in children", "tool": "knowledge_search", "call_id": "toolu_01", "state": "done" } }
```

Show one line per `call_id`, and replace its text when the `done` or `failed` event arrives. A `run.progress` without `call_id` is a plain progress line. The tools `message`, `done` and `ask` send no tool step: their own events show them. An `emit_<name>` call sends its `event.<name>` between its two steps.

You do not need `work_session` for tool steps. A [conversation](https://docs.cloudraker.com/run/guides/conversations) turns tool steps into `activity` items for the web chat, the console, Slack and Teams.

## Agents that work together

A run with an `agents:` key can give tasks to other agents (child runs) and send messages to the live runs of its run tree. Texts in these events are cut at 600 characters.

| Type                     | On           | `data`                                                                  |
| ------------------------ | ------------ | ----------------------------------------------------------------------- |
| `child.started`          | The parent   | `{ child_run_id, agent, title, task, call_id }`                         |
| `child.reported`         | The parent   | `{ child_run_id, agent, title, status, summary, credits? }`             |
| `agent_message.sent`     | The sender   | `{ message_id, to_run_id, to_agent, text, expect_reply }`               |
| `agent_message.received` | The receiver | `{ message_id, from_run_id, from_agent, from_title, text }`             |

`child.reported` statuses: `completed`, `failed`, `cancelled`, `expired`, `answered` (the first turn of a `turns` child ended, and the child stays available for messages) and `question`.

`run.failed` codes: `model_error`, `timeout`, `step_limit`, `secret_missing`, `egress_denied`, `connector_unavailable`, `code_error`, `output_schema`, `concurrency_limited`.

## Run states

`queued` → `running` → `waiting` (turns only) → `running` → … → `completed`, `failed`, `cancelled` or `expired`.

A terminal run never resumes. It keeps its events and result until retention. After retention, the events answer `410 run_purged`, and `GET /_run/{id}` answers the run stub with its usage.

## Stream and replay

`POST /{agent}`, `POST /_run/{id}` and `GET /_run/{id}` stream when the request sends `Accept: text/event-stream`. Each SSE frame sets `id: <seq>`, `event: <type>` and `data: <envelope>`. A terminal event closes the stream.

```bash
curl -N "https://$ORG.cloudraker.run/_run/$RUN_ID" \
  -H "Authorization: Bearer $RUN_TOKEN" \
  -H "Accept: text/event-stream" \
  -H "Last-Event-ID: 12"
```

Without `Last-Event-ID`, the stream replays from `seq` 1. A replay works after a disconnect, a crash or days later, until retention. To page instead of stream:

```bash
curl -s "https://$ORG.cloudraker.run/_run/$RUN_ID/events?after_seq=0&limit=200" \
  -H "Authorization: Bearer $RUN_TOKEN"
```

`limit` is 200 by default and 1000 at most. A run allows 10 open streams.

## Turn-based runs

A `mode: turns` agent ends each turn in `waiting`. Send the next turn on `POST /_run/{id}`:

```bash
curl -N -X POST "https://$ORG.cloudraker.run/_run/$RUN_ID" \
  -H "Authorization: Bearer $RUN_TOKEN" \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{ "answer": { "question_id": "q_1", "value": "Montreal" } }'
```

| Topic              | Rule                                                                                                      |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| Body               | `input`, `answer`, or both. Also `files` and `secrets`.                                                   |
| Answer             | `answer.question_id` must match the open `question` event, or `422 question_mismatch`.                    |
| One turn at a time | A second turn while one runs answers `409 run_busy`.                                                      |
| Idle TTL           | A `waiting` run expires after `idle_ttl` (default 24 h). A later turn answers `410 run_expired`.          |
| Zeroshot           | `POST /_run/{id}` on a `zeroshot` run answers `409 run_not_turn_based`.                                   |
| State              | History, files, grants, `metadata`, the pinned SHA and the pinned model persist. Override secrets do not. |

Cancel a run with `DELETE /_run/{id}` (scope `cancel`).

## Idempotency

Send `Idempotency-Key` (1 to 255 characters) on `POST /{agent}` and `POST /_run/{id}`. The gateway keeps the key 24 hours per org. A retry with the same key and body returns the first answer. The same key with a different body answers `422 idempotency_mismatch`.

## Custom events

Declare events in a leaf `agent.yml`. Each one becomes a tool `emit_{name}`:

```yaml agent.yml
events:
  label_suggested:
    description: Suggest one label for the ticket.
    schema:
      type: object
      required: [label]
      properties: { label: { type: string } }
```

The caller gets `event.label_suggested` with a validated `data`. A payload that fails the schema goes back to the agent as a tool error, and no event is emitted. We define the shape. You write the handler.

## Webhooks

`webhooks:` in the leaf `agent.yml` sends matching events to your server. An open stream does not stop webhook delivery.

```yaml agent.yml
webhooks:
  - url: https://ops.example.com/hooks/agents
    events: [run.completed, run.failed, event.label_suggested]
```

You do not set a secret. CloudRaker signs each delivery with a JWT of your organization.

> **Warning**
>
> `signing_secret` is deprecated. A hook that still has it gets the old HMAC `x-cr-signature: t=...,v1=...` and the JWT in `x-cr-signature-jwt`. Lint shows a warning. Remove `signing_secret` when your receiver verifies the JWT.

| Topic               | Rule                                                                                                                                                                         |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| One event, one POST | No batching. The body is the envelope. `content-type: application/json`.                                                                                                     |
| Headers             | `x-cr-signature`, `x-cr-event-id`, `x-cr-event-type`, `x-cr-run-id`, `x-cr-delivery-attempt`, `user-agent: CloudRaker-Run/1.0`.                                              |
| Success             | Any 2xx within 10 seconds.                                                                                                                                                   |
| Retries             | 6 attempts: at once, then 10 s, 1 min, 10 min, 1 h and 6 h, with 10 percent jitter. The event `id` stays the same.                                                           |
| Dead letter         | After the last attempt, the delivery is `dead`. The console **Webhooks** screen shows it and can retry it. A URL that the signer refuses is `dead` at once (`sign_refused`). |
| Order               | At least once, not in order. Sort by `seq`.                                                                                                                                  |
| Targets             | HTTPS only. Private addresses are refused. A host under `cloudraker.run` and a URL of more than 512 characters are refused. Redirects are not followed.                      |
| History             | `GET /_run/{id}/deliveries` lists one row per attempt. It needs a `crk_` key with the `read` scope.                                                                          |

## Verify the signature

The `x-cr-signature` header holds a JWT, signed with RS256. Each attempt has a new JWT with a lifetime of 5 minutes. Verify the JWT with the public keys of your organization:

```text
https://{org}.cloudraker.run/.well-known/jwks.json
```

| Claim               | Value                                                                  |
| ------------------- | ---------------------------------------------------------------------- |
| `iss`               | `https://{org}.cloudraker.run`                                         |
| `sub`               | `webhook`                                                              |
| `aud`               | The exact `url` of the `webhooks:` entry.                              |
| `jti`               | The event `id`. The same on every retry.                               |
| `type`              | The event type.                                                        |
| `run_id`            | The run.                                                               |
| `body_sha256`       | The SHA-256 of the raw body, as 64 lowercase hex characters.           |
| `iat`, `nbf`, `exp` | The issue time, the start time and the end time. `exp` is `iat` + 300. |

1. Read the raw body bytes. Do not parse and re-serialize the JSON first.
2. Verify the JWT signature with the key that has the `kid` of the JWT. Allow RS256 only.
3. Check `iss`, `aud` and `exp`.
4. Compute the SHA-256 of the raw body and compare it with `body_sha256`.
5. De-duplicate on `jti` (the event `id`).

```ts title="TypeScript (jose)"
import { createHash } from 'node:crypto'
import { createRemoteJWKSet, jwtVerify } from 'jose'

const ISSUER = `https://${process.env.RUN_ORG}.cloudraker.run`
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`))

export async function verifyRunWebhook(rawBody: Buffer, token: string, endpointUrl: string) {
  // jwtVerify checks the signature, iss, aud, exp and nbf.
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: endpointUrl,
    algorithms: ['RS256'],
  })
  const digest = createHash('sha256').update(rawBody).digest('hex')
  if (digest !== payload.body_sha256) throw new Error('The body hash does not match.')
  return payload
}

// Hono example
app.post('/hooks/agents', async (c) => {
  const rawBody = Buffer.from(await c.req.arrayBuffer())
  const token = c.req.header('x-cr-signature') ?? ''
  try {
    await verifyRunWebhook(rawBody, token, 'https://ops.example.com/hooks/agents')
  } catch {
    return c.text('bad signature', 401)
  }
  const event = JSON.parse(rawBody.toString('utf8'))
  // De-duplicate on event.id, then handle event.type.
  return c.body(null, 204)
})
```

```python title="Python (PyJWT)"
import hashlib
import os

import jwt
from jwt import PyJWKClient

ISSUER = f"https://{os.environ['RUN_ORG']}.cloudraker.run"
JWKS = PyJWKClient(f"{ISSUER}/.well-known/jwks.json")


def verify_run_webhook(raw_body: bytes, token: str, endpoint_url: str) -> dict:
    # jwt.decode checks the signature, iss, aud, exp and nbf.
    signing_key = JWKS.get_signing_key_from_jwt(token).key
    claims = jwt.decode(
        token,
        signing_key,
        algorithms=["RS256"],
        issuer=ISSUER,
        audience=endpoint_url,
        options={"require": ["iss", "aud", "exp", "jti", "body_sha256"]},
    )
    if hashlib.sha256(raw_body).hexdigest() != claims["body_sha256"]:
        raise ValueError("The body hash does not match.")
    return claims


# Flask example
@app.post("/hooks/agents")
def hook():
    try:
        verify_run_webhook(
            request.get_data(),
            request.headers.get("x-cr-signature", ""),
            "https://ops.example.com/hooks/agents",
        )
    except (jwt.PyJWTError, ValueError):
        return "bad signature", 401
    event = request.get_json()
    # De-duplicate on event["id"], then handle event["type"].
    return "", 204
```

> **Warning**
>
> Do not use the event to authorize a side effect without the signature check. The `metadata` of an
> event comes from the caller of the run.

Source: https://docs.cloudraker.com/run/guides/events-and-webhooks/index.mdx
