# Webhooks

Webhooks let Flow push events to your systems, so agents can run push-style instead of polling. Examples: start an agent when a task becomes ready, notify Slack when an agent asks a question, merge when a run is approved.

## Set one up

1. **Settings → Webhooks** (workspace admins).
2. Enter the URL and pick the events. A webhook covers the whole workspace; use `project.key` in the payload to filter.
3. Copy the **signing secret** (reveal it on the webhook), and use it to verify deliveries.

Each webhook shows its latest delivery: the event, the HTTP status and how long ago it was sent.

## Events for agent work

| Event | Fires when | Typical reaction |
| --- | --- | --- |
| `agent.work_available` | There's work for specific agents: assigned with auto-start, newly ready, changes requested, plan approved, question answered, given back. `data.agents` lists them; `data.reason` says why | Start those agents ([auto-start](auto-start.md)) |
| `task.ready` | A task is switched to "Ready for agents" | Start an agent to claim it |
| `lease.claimed` | An agent claims a task | Bookkeeping |
| `lease.expired` | An agent stopped sending heartbeats | Restart or replace that agent. `data.removed_from_queue` is true after the second expiry in a row |
| `run.submitted` | An agent submits a run | Nothing, or tell the reviewer (`data.reviewer`) |
| `review.approved` | A run is approved (by a human or the review agent) | Merge, deploy, start dependent work |
| `review.changes_requested` | A reviewer asks for changes | Start the same agent again: the feedback comes with its next claim |
| `question.asked` | An agent asks a human | Notify the person (`data.for`) in Slack or email |
| `question.answered` | A human answers | Resume the agent |

General events are also available: `task.created`, `task.updated`, `task.status_changed`, `task.assigned`, `comment.added`, `sprint.started`, `sprint.completed`.

## Payload

Each delivery is a `POST` with a JSON body:

```json
{
  "event": "review.changes_requested",
  "occurred_at": "2026-10-04T16:20:11.512Z",
  "workspace": "your-workspace",
  "project": { "id": "…", "key": "PAY", "name": "Payments" },
  "actor": { "id": "…", "name": "Reviewer Name", "type": "human" },
  "data": {
    "task": { "identifier": "PAY-12", "number": 12, "title": "Add a refunds endpoint", "status": { "name": "To Do", "category": "todo" }, "…": "…" },
    "run": { "id": "…", "attempt": 1, "agent": { "id": "…", "name": "dev-agent", "type": "agent" } },
    "review": { "decision": "changes_requested", "feedback": { "comment": "Partial refunds fail", "unticked": [ { "id": "…", "text": "Partial refunds are supported" } ] } }
  }
}
```

`actor.type` is `human` or `agent`. `data` depends on the event, and always includes the `task` for task events.

## Verify the signature

Each delivery has these headers:

- `X-Hivantis-Event`: the event name
- `X-Hivantis-Signature`: `sha256=` followed by the HMAC-SHA256 of the **raw body**, keyed with the signing secret
- `X-Hivantis-Timestamp`: when the request was sent, in Unix seconds
- `X-Hivantis-Signature-Timed`: `sha256=` followed by the HMAC-SHA256 of `<timestamp>.<raw body>`, keyed with the signing secret
- `X-Hivantis-Delivery`: an id for this delivery, the same on every retry of it

```python
import hashlib, hmac

def verify(raw_body: bytes, header: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header)
```

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

const verify = (rawBody, header, secret) => {
  const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  return header.length === expected.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(header));
};
```

Verify against the raw bytes you received, before parsing the JSON.

### Rejecting replayed requests

Anyone who captures a delivery could send it again later, and its `X-Hivantis-Signature` would still check out.
To refuse old copies, verify `X-Hivantis-Signature-Timed` instead and turn away requests whose timestamp is more
than five minutes old. To handle each delivery once, remember the `X-Hivantis-Delivery` ids you've processed.

```python
import hashlib, hmac, time

def verify_fresh(raw_body: bytes, timestamp: str, header: str, secret: str, tolerance: int = 300) -> bool:
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance:
        return False
    expected = "sha256=" + hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header)
```

## Delivery

- Sent after the change is saved, so a rolled-back change never fires an event.
- 10-second timeout. Any 2xx counts as delivered. Network failures are retried 3 times, 30 seconds apart.
- URLs that resolve to private or loopback addresses are refused, unless the server allows them (development).
- Redirects aren't followed: a 3xx answer is recorded as the response. Point the webhook at the final URL.
- Respond quickly and do slow work (like starting an agent) in the background.

## Recipe: start an agent when a task is ready

A small receiver that starts Claude Code with the Flow MCP server for each `task.ready`:

```python
# pip install flask
import hashlib, hmac, os, subprocess
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["FLOW_WEBHOOK_SECRET"]

@app.post("/flow")
def flow():
    sig = request.headers.get("X-Hivantis-Signature", "")
    expected = "sha256=" + hmac.new(SECRET.encode(), request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        abort(401)
    event = request.get_json()
    if event["event"] == "agent.work_available":
        # The agent claims whatever is next; Flow decides the order. Needs `claude mcp add hivantis-flow …` done once.
        subprocess.Popen(["claude", "-p", f"Claim the next task in Flow project {event['project']['key']} and do it."],
                         cwd=os.environ["REPO_DIR"])
    return "", 204
```

Headless `claude -p` runs can't stop to ask for permission. Give them what they need with `--allowedTools` or `--permission-mode`, and a spend cap with `--max-budget-usd`; see the Claude Code docs.

The same idea works in GitHub Actions (with a `repository_dispatch` trigger), n8n, Zapier or a serverless function.
