Source: https://docs.cumuluslabs.io/triggers-and-webhooks
Content version: 5fcfc672

# Triggers and webhooks

After a service call, your application may need the outcome, and another agent may need to prepare follow-up. Use a **webhook** to deliver the call’s events to your application. Use a **trigger** to start a cloud agent after an event or on a schedule.

Configure them on the draft and publish to activate them. The [after-call workflow](/docs/after-call-operations) shows how these pieces fit together.

## Webhooks {#webhooks}

Subscribe to the events your application needs: `run.admitted`, `run.ended`, `recording.updated` or `analysis.updated`. For example, use `run.ended` to update a service request and `analysis.updated` to read the completed analysis.

Create a signing secret, add your HTTPS endpoint with `notification.put`, then publish the draft.

**Add a webhook**

```
# 1. Create the signing secret (admin key). Keep the value: your receiver needs it.
PUT /api/v1/secrets/crm-webhook      { "kind": "webhook_signing", "value": "<a long random string>" }
#    → { "id": "crm-webhook", "current_version": "<version>", … }

# 2. Add the webhook to the agent's draft, then publish.
PATCH /api/v1/agents/{agent_id}/draft
{ "draft_id": "…", "expected_revision": 7, "edits": [
  { "type": "notification.put", "notification": {
      "id": "crm", "url": "https://hooks.example.com/talos", "format": "semantic.v1",
      "secret_ref": { "id": "crm-webhook", "version": "<version>" },
      "events": ["run.ended", "analysis.updated"] } } ] }
```

### Delivery {#delivery}

Use `run.ended` when you need the final run state. Recording and analysis can finish later, so listen for their update events when you need those outputs, then read the relevant endpoint to check its state.

The body is the event exactly as the run's event stream carries it (format `semantic.v1`).

**What your endpoint receives**

```
POST https://hooks.example.com/talos
content-type: application/json
x-talos-event-id: 3f6c…            # the event's id; the same on every retry
idempotency-key: 3f6c…             # the same value: deduplicate on it
x-talos-signature: t=1790380800,v1=5d41402abc4b2a76b9719d911017c592…

{ "event_id": "3f6c…", "type": "run.ended", "sequence": 14, "run": { "run_id": "…", … }, "data": { "outcome": { … }, … }, … }
```

*   Return `2xx` after saving the event. Delivery has a 20-second budget: a non-`2xx` response is recorded as failed, and a lost response as uncertain. An attempted delivery is not automatically sent again, so use the Runs API to recover a missed event or output.
*   For a delivery problem, inspect `GET /api/v1/runs/{run_id}/effects`, then read the run or artifact you need. Processing the same event twice must not create a duplicate update in your application.
*   Your receiver should durably deduplicate by `event_id` (also `idempotency-key`) and accept distinct events out of order. Do not discard a later-arriving recording event because an analysis event had a higher sequence. Run completion, recording readiness and analysis readiness are independent.
*   Test runs (`"test": true`) are never delivered.

### Verify the signature {#verify}

`x-talos-signature` is `t=<unix seconds>,v1=<hex HMAC-SHA256>` of `<t>.<raw body>` with your signing secret. Compute it over the raw bytes you received (before parsing the JSON), compare in constant time, and reject old timestamps; five minutes is a reasonable window.

<!-- code-tabs: Verify a webhook -->

**Verify a webhook · typescript**

```typescript
import { verifyTalosWebhook } from "@cumulus/sdk";

// rawBody contains the exact received bytes, before JSON parsing.
const valid = await verifyTalosWebhook(rawBody, signatureHeader, signingSecret);
if (!valid) throw new Error("Invalid or stale Talos webhook signature");
```

**Verify a webhook · python**

```python
import hashlib
import hmac
import re
import time

def verify_talos_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
    """True when the body was signed with your webhook signing secret within the last five minutes."""
    parts = dict(part.split("=", 1) for part in signature_header.split(",") if "=" in part)
    # t is unix seconds; v1 is exactly 64 lowercase hex characters.
    if not re.fullmatch(r"\d{1,12}", parts.get("t", "")) or not re.fullmatch(r"[0-9a-f]{64}", parts.get("v1", "")):
        return False
    if abs(time.time() - int(parts["t"])) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{parts['t']}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])
```

<!-- /code-tabs -->

Publications pin a secret version. After rotating it with `PUT /api/v1/secrets/{secret_id}`, update the draft’s `secret_ref` and publish again.

## Triggers {#triggers}

A trigger starts a `background` cloud run of the agent it belongs to:

*   **schedule**: a five-field cron expression in a time zone, with a fixed `input`.
*   **event**: when a run matching `source` (an agent, a channel, dispositions) emits `run.ended` or `analysis.updated`. `input_mapping` copies selected fields from the completed run into the new task's input. For example, `"previous_run_id":"/run_id"` copies the source run ID.

**Draft edits**

```
# Every weekday at 9:00 in New York, start a background run with this input.
{ "type": "trigger.put", "trigger": {
    "kind": "schedule", "id": "morning-sweep", "cron": "0 9 * * 1-5", "timezone": "America/New_York",
    "input": { "queue": "service_follow_up" } } }

# When a phone run of another agent ends as voicemail, start a run of this agent with fields from that event.
{ "type": "trigger.put", "trigger": {
    "kind": "event", "id": "after-voicemail", "event_type": "run.ended",
    "source": { "agent_id": "<caller agent id>", "channel": "phone", "dispositions": ["voicemail_left"] },
    "input_mapping": { "previous_run_id": "/run_id" } } }
```

*   Only the head's triggers are active. Publishing with `"live": false` does not register them; promoting that version does, and replaces the previous head's triggers.
*   Publishing a trigger checks that you may start those runs; if not, `403 policy_denied`.
*   Test runs never fire event triggers. Remove a trigger with `trigger.remove` and publish.

## Secrets {#secrets}

Secrets hold the values agents must not carry in their definition: webhook signing keys, HTTP action credentials and SIP passwords (kinds `webhook_signing`, `http_auth`, `sip_auth`). Values are write-only: reads return names and versions, never values. Each `PUT` adds a version; drafts reference a secret as `{ id, version }`. Writing and deleting secrets takes an admin key. See [Phone](/docs/phone) for trunk credentials.

| Operation | MCP tool | Key role | Purpose |
| --- | --- | --- | --- |
| [`GET /api/v1/secrets`](https://docs.cumuluslabs.io/reference/secrets.list) | `secrets_list` | viewer | List secret names, kinds and versions. Secret values are never returned. |
| [`PUT /api/v1/secrets/{secret_id}`](https://docs.cumuluslabs.io/reference/secrets.put) | `secrets_put` | admin | Create a secret or add a version. Keep the returned version for references in agents and trunks; the response does not return the value. |
| [`DELETE /api/v1/secrets/{secret_id}`](https://docs.cumuluslabs.io/reference/secrets.delete) | `secrets_delete` | admin | Delete a secret and all its versions. |
