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

# Webhooks

> Start agent runs from GitHub, Linear, Slack, and other systems that send webhooks.

An agent runs in a Restate handler, so systems that send webhooks, such as GitHub, Linear, and Slack, can start agent runs.
In [Restate Cloud](https://docs.restate.dev/cloud/getting-started.md), an [incoming webhook](https://docs.restate.dev/services/invocation/webhooks.md) forwards each delivery to a service handler. Incoming webhooks are in preview, and aren't available in Restate BYOC.

The example on this page triages GitHub issues. An agent answers each new issue and each new comment as a comment on the issue, and keeps a conversation per issue:

1. A webhook handler verifies the delivery's signature, sends the event to the issue's agent, and returns.
2. A Virtual Object, keyed by the issue, runs the agent with the issue's conversation and posts the answer.

## Receive the webhook

The webhook handler is a service handler that accepts GitHub's `issues` and `issue_comment` events:

```typescript {"CODE_LOAD::harness/src/webhooks.ts#webhook"}  theme={null}
type GitHubEvent = {
  action: string;
  repository: {full_name: string};
  issue: {number: number; title: string; body: string | null};
  comment?: {body: string};
  sender: {login: string; type: string};
};

export const gitHubWebhook = restate.service({
  name: "GitHubWebhook",
  handlers: {
    // Receive the unmodified body as raw bytes, to verify its signature
    receive: restate.serdes({input: restate.serde.binary, output: restate.serde.empty}, function* (body) {
      const headers = restate.handlerRequest().headers;
      const expected =
        "sha256=" + createHmac("sha256", process.env.GITHUB_WEBHOOK_SECRET!).update(body).digest("hex");
      if (!signatureMatches(expected, headers.get("x-hub-signature-256"))) {
        throw new TerminalError("Invalid signature", {errorCode: 401});
      }

      const name = headers.get("x-github-event");
      const event: GitHubEvent = JSON.parse(new TextDecoder().decode(body));
      // Skip events from bots, such as the comments that the agent posts through its GitHub App
      if (event.sender.type === "Bot") return;
      let message: string;
      if (name === "issues" && event.action === "opened") {
        message = `${event.sender.login} opened: ${event.issue.title}\n\n${event.issue.body ?? ""}`;
      } else if (name === "issue_comment" && event.action === "created") {
        message = `${event.sender.login} commented: ${event.comment!.body}`;
      } else {
        return;
      }

      // Send the event to the issue's agent, and return without waiting for the run
      const thread = `${event.repository.full_name}#${event.issue.number}`;
      yield* restate.sendClient(gitHubThread, thread).onEvent(
        message,
        rpc.sendOpts({idempotencyKey: `github:${headers.get("x-github-delivery")}`}),
      );
    }),
  },
  options: {handlers: {receive: {accept: "*/*"}}},
});

// Compares the signatures in constant time
function signatureMatches(expected: string, received: string | undefined) {
  if (received === undefined) return false;
  const a = Buffer.from(expected);
  const b = Buffer.from(received);
  return a.length === b.length && timingSafeEqual(a, b);
}
```

* **Verify the signature.** The handler receives the unmodified body as raw bytes, computes its HMAC with the webhook's secret, and compares the result with the `x-hub-signature-256` header. A terminal error with code `401` rejects the delivery: Restate doesn't retry the invocation, and in sync mode GitHub receives `401`. See [Write the handler](https://docs.restate.dev/services/invocation/webhooks.md#write-the-handler).
* **Return immediately.** Senders wait only a few seconds for a response, for example 10 seconds for GitHub, while an agent run can take minutes. The handler sends the event to the agent and doesn't wait for the run.
* **Deduplicate deliveries.** The idempotency key from the `x-github-delivery` header makes Restate start one run per delivery, also when you redeliver the event from GitHub.
* **Skip bot events.** The handler ignores deliveries whose sender is a bot. This includes the agent's own comments when it posts them through a GitHub App: each of its comments is an `issue_comment` event too, which would otherwise start another run.

## Run the agent per issue

The Virtual Object runs the agent for one issue, and posts the answer as a comment:

```typescript {"CODE_LOAD::harness/src/webhooks.ts#agent"}  theme={null}
const triager = agent({
  model,
  instructions: "Triage GitHub issues: ask for missing details, and suggest labels.",
});

export const gitHubThread = restate.object({
  name: "GitHubThread",
  handlers: {
    *onEvent(message: string) {
      // The key is the thread, such as "owner/repo#123"
      const thread = restate.handlerRequest().key!;
      const result = yield* triager.run(message, {conversation: new Conversation()});
      if (result.status !== "completed") throw new TerminalError(`Triage ${result.status}`);
      yield* restate.run(() => postComment(thread, result.output), {name: "Post comment"});
    },
  },
  // Keep idempotency keys as long as GitHub allows manual redelivery
  options: {
    idempotencyRetention: {days: 3},
    state: {preload: ["conversation/meta", "conversation/summary"]},
  },
});
```

* **One run at a time per issue.** Restate runs one exclusive handler per key, so the events of an issue run in the order they arrive, and different issues run in parallel.
* **A conversation per issue.** The agent answers a comment with the issue and its earlier answers in its history. See [Sessions](https://docs.restate.dev/harness/sessions.md).
* **A journaled comment.** `restate.run` journals the result of posting the comment, so a replay doesn't post it again.
* **Idempotency retention.** Restate keeps the idempotency keys of `onEvent` for 3 days, as long as GitHub allows you to redeliver an event. A redelivery within these 3 days doesn't start another run, also when the earlier run failed.

An event for an issue whose run is still in progress waits until the run ends. To deliver the event to the running run instead, send it to a shared handler that steers the run. See [Steering and interruption](https://docs.restate.dev/harness/steering.md).

## Connect GitHub

1. Register the deployment that contains `GitHubWebhook` and `GitHubThread`, and set `GITHUB_WEBHOOK_SECRET` in its environment.
2. In Restate Cloud, [create an incoming webhook](https://docs.restate.dev/services/invocation/webhooks.md#create-a-webhook) for `GitHubWebhook/receive`. Either delivery mode works: GitHub accepts any `2xx` response, and the handler returns well within GitHub's 10 seconds. In sync mode, GitHub's delivery log shows rejected deliveries.
3. In your repository settings, add a webhook with the webhook URL, the content type `application/json`, and the same secret. Select the **Issues** and **Issue comments** events. GitHub also sends **Issue comments** events for comments on pull requests, so the agent answers those too. See [Configure webhook senders](https://docs.restate.dev/services/invocation/webhooks.md#github).

To test locally, send signed deliveries to the Restate ingress at `http://localhost:8080/restate/call/GitHubWebhook/receive`.

## Other senders

The handlers for other senders follow the same steps, with the sender's signature scheme and delivery ID:

| Sender | Signature | Delivery ID | Delivery mode |
| - | - | - | - |
| GitHub | `x-hub-signature-256` header | `x-github-delivery` header | Sync or async |
| Linear | `linear-signature` header, and `webhookTimestamp` in the body | `linear-delivery` header | Sync, because Linear treats any status other than `200` as a failure |
| Slack | `x-slack-signature` and `x-slack-request-timestamp` headers | `event_id` in the body of Events API requests | Sync, because Slack expects the URL verification challenge and slash command replies in the response |

Reject Linear and Slack deliveries whose timestamp is too old. See [Configure webhook senders](https://docs.restate.dev/services/invocation/webhooks.md#configure-webhook-senders) for the verification code of each sender.
The [incoming webhooks example](https://github.com/restatedev/examples/tree/main/typescript/integrations/webhooks) has handlers for GitHub, Linear, and Slack that forward events to Virtual Objects, and a script that sends signed sample deliveries. To add an agent, replace the logic in the example's Virtual Objects with an agent run, as in `GitHubThread` on this page.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.