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

# Triggers

> Give other services a webhook URL whose rules turn their events into messages for your agents' sessions.

A trigger is a webhook endpoint of your project. Any service can post JSON events to its URL, and its rules decide which events become which messages, in which agent's session. An event-driven agent needs no server of yours in between: paddock receives the event, records it, finds or creates the session, and sends the message.

```mermaid theme={null}
sequenceDiagram
  participant Sender as Sender (any service)
  participant Trigger as trigger.paddock.build
  participant Session as Agent's session
  Sender->>Trigger: POST /trg_... { JSON event }
  Note over Trigger: verify, deduplicate, run every rule
  Trigger-->>Sender: 202 { deliveryId }
  Trigger->>Session: find or create the session by its key, send the rendered message
```

## Create a trigger

```go Go theme={null}
trigger, err := client.Triggers.Create(ctx, paddock.TriggerCreate{
	Name:         "GitHub acme/web",
	Verification: &paddock.VerificationCreate{Header: "X-Hub-Signature-256", Prefix: "sha256="},
	Secret:       os.Getenv("GITHUB_WEBHOOK_SECRET"),
	Dedupe:       paddock.Ptr(`headers["x-github-delivery"]`),
	Rules: []paddock.RuleCreate{{
		Name:    "review",
		AgentID: agent.ID,
		Filter: paddock.Ptr(`headers["x-github-event"] == "pull_request"
  && body.action in ["opened", "synchronize", "reopened"]
  && !body.pull_request.draft`),
		Session: paddock.SessionChoiceKey("{{body.repository.full_name}}#{{body.pull_request.number}}"),
		Message: "Review pull request {{body.pull_request.html_url}}, head {{body.pull_request.head.sha}}.",
	}},
})
if err != nil {
	return err
}
fmt.Println(trigger.URL) // https://trigger.paddock.build/trg_...
```

```python Python theme={null}
import os

trigger = client.triggers.create(
    {
        "name": "GitHub acme/web",
        "verification": {"header": "X-Hub-Signature-256", "prefix": "sha256="},
        "secret": os.environ["GITHUB_WEBHOOK_SECRET"],
        "dedupe": 'headers["x-github-delivery"]',
        "rules": [
            {
                "name": "review",
                "agentId": agent.id,
                "filter": 'headers["x-github-event"] == "pull_request"'
                ' && body.action in ["opened", "synchronize", "reopened"]'
                " && !body.pull_request.draft",
                "session": {
                    "mode": "key",
                    "key": "{{body.repository.full_name}}#{{body.pull_request.number}}",
                },
                "message": "Review pull request {{body.pull_request.html_url}}, head {{body.pull_request.head.sha}}.",
            }
        ],
    }
)
print(trigger.url)  # https://trigger.paddock.build/trg_...
```

```ts TypeScript theme={null}
const trigger = await paddock.triggers.create({
  name: "GitHub acme/web",
  verification: { header: "X-Hub-Signature-256", prefix: "sha256=" },
  secret: process.env.GITHUB_WEBHOOK_SECRET,
  dedupe: 'headers["x-github-delivery"]',
  rules: [
    {
      name: "review",
      agentId: agent.id,
      filter: `headers["x-github-event"] == "pull_request"
  && body.action in ["opened", "synchronize", "reopened"]
  && !body.pull_request.draft`,
      session: { mode: "key", key: "{{body.repository.full_name}}#{{body.pull_request.number}}" },
      message: "Review pull request {{body.pull_request.html_url}}, head {{body.pull_request.head.sha}}.",
    },
  ],
});
console.log(trigger.url); // https://trigger.paddock.build/trg_...
```

Give the sender `trigger.url` and, if the trigger verifies signatures, the same secret. The Python SDK takes requests as dictionaries spelled as the API spells them (`agentId`), or as the models in `paddock.types`.

| Field | Meaning |
| - | - |
| `name` | For people, 1 to 200 characters |
| `verification` | `{ header, prefix }` to require an HMAC-SHA256 signature; omitted, no signature is checked |
| `secret` | 16 to 256 printable characters; generated when omitted |
| `dedupe` | A CEL expression yielding the sender's delivery ID; omitted, the SHA-256 of the body |
| `rules` | Up to 50 rules, in order |

The trigger's ID, `trg_...`, is the last segment of its URL. The URL is unguessable; a trigger without verification accepts every request to it.

## Rules

Each rule picks the events it wants and sends each as a message to a session of one agent. **Every enabled rule that matches an event fires**, independently of the others: each has its own outcome, session, and message, and their order only decides the order they run in.

| Field | Meaning |
| - | - |
| `name` | Lowercase letters, digits, and `-`, 1 to 64 characters, unique in the trigger |
| `enabled` | Default `true`; a disabled rule is kept but never runs |
| `filter` | A [CEL](#filters) expression; omitted, the rule matches every event |
| `agentId` | The agent to deliver to, an existing agent of the project |
| `session` | `{ mode: "key", key }` to reuse the session of a rendered key, or `{ mode: "new" }` for a new session per event |
| `sessionSettings` | `cwd`, `systemPrompt`, and `metadata` for sessions the rule creates; literal values, never rendered from the event |
| `message` | The message, a [template](#templates) rendered from the event |

### Sessions by key

With `mode: "key"`, the rule renders its `key` template from the event, then reuses the agent's session whose `triggerKey` metadata equals that key, or creates one with the rule's session settings and that key. So every event about one pull request lands in one conversation, and the agent answers with its earlier work in context. Two rules that render the same key for the same agent reach the same session, each with its own message.

With `mode: "new"`, every event gets a new session.

Find a rule's sessions with a metadata filter:

```go Go theme={null}
for s, err := range client.Sessions.List(ctx, paddock.ProjectSessionList{
	Metadata: map[string]string{"triggerKey": "acme/web#42"},
}) {
	if err != nil {
		return err
	}
	fmt.Println(s.ID)
}
```

```python Python theme={null}
for s in client.sessions.list(metadata={"triggerKey": "acme/web#42"}):
    print(s.id)
```

```ts TypeScript theme={null}
for await (const s of paddock.sessions.list({ metadata: { triggerKey: "acme/web#42" } })) {
  console.log(s.id);
}
```

## Filters

A filter is a [CEL](https://cel.dev) expression over three variables, built from the request as the sender sent it:

| Variable | Type | Holds |
| - | - | - |
| `body` | `dyn` | The body parsed as JSON |
| `headers` | `map(string, string)` | Every header, its name in lowercase; repeated values joined with `", "` |
| `query` | `map(string, string)` | Every query parameter; repeated values joined with `,` |

```cel theme={null}
headers["x-github-event"] == "issue_comment"
  && body.action == "created"
  && has(body.issue.pull_request)
  && body.comment.body.lowerAscii().contains("@reviewer")
```

* The expression must yield a boolean: `true` matches, `false` ends the rule's outcome as `filtered`.
* Reading a key that is not there is an error. Test first with `has(body.x)` or `"x-github-event" in headers`. `&&` and `||` absorb an error when the other side decides the result, so a check that fails first protects the checks after it.
* Available: comparisons, `in`, `has()`, `size()`, `contains`, `startsWith`, `endsWith`, `matches`, the macros `exists`, `all`, `map`, and `filter`, and cel-go's string extensions (`lowerAscii`, `upperAscii`, `trim`, `split`, `join`, `replace`, `substring`, `indexOf`, `format`, and more) and list extensions (`slice`, `flatten`, `distinct`, `sort`, `hasAny`, `hasAll`, and more).
* At most 4 KiB. Every evaluation is bounded in cost and time.
* An evaluation that fails ends the rule's outcome as `failed` with `filter_error`; it is never retried.

Every filter and the dedupe expression are compiled when you create or update the trigger; a mistake is `400` with the field, such as `rules[review].filter`, and CEL's message with its position.

## Templates

A rule's `message` and its session `key` are templates: plain text with `{{path}}` placeholders that place values from the same three variables.

```text theme={null}
Pull request {{ body.repository.full_name }}#{{ body.pull_request.number }} was {{ body.action }}.
First label: {{ body.pull_request.labels.0.name }}
Event: {{ headers.x-github-event }}, literal braces: \{{ not a placeholder }}
```

| Rule | Meaning |
| - | - |
| Path | `body`, `headers`, or `query`, then segments separated by `.`: an object key, a header name, or an array index from 0. Spaces around the path are ignored |
| Values | A string as it is; a number as it appears in the body; `true` and `false` as words; an object or array as compact JSON; `null` as nothing |
| Missing values | In the message, a path that leads nowhere places nothing. In the session key it fails the rule's outcome with `template_error`, so two events never share a session by accident |
| Escaping | `\{{` places a literal `{{`. Nothing else is escaped: the message is plain text |
| No expressions | A placeholder holds only a path. Put logic in the filter |
| Size | The rendered message 1 byte to 100 KB, so an empty message fails too; the rendered key 1 to 500 bytes. Outside that, the outcome fails with `template_error` |

## Verify signatures

With `verification`, paddock computes the HMAC-SHA256 of the raw body with the trigger's secret, writes it as lowercase hexadecimal after `prefix`, and compares it with the header's value. The header name is matched in any case. A missing or wrong signature is answered `401` and recorded as a rejected delivery.

| Sender | `header` | `prefix` |
| - | - | - |
| GitHub | `X-Hub-Signature-256` | `sha256=` |
| A sender that sends the bare hex digest | Its header | `""` |

The secret is returned only by its own operations. Rotating it replaces it at once: requests signed with the old secret fail from then on, so give the sender the new one.

```go Go theme={null}
secret, err := trigger.Secret.Get(ctx)
if err != nil {
	return err
}
rotated, err := trigger.Secret.Rotate(ctx, paddock.SecretRotate{}) // or SecretRotate{Secret: "..."}
```

```python Python theme={null}
secret = trigger.secret.get().secret
rotated = trigger.secret.rotate().secret  # or rotate(secret="...")
```

```ts TypeScript theme={null}
const { secret } = await trigger.secret.get();
const rotated = await trigger.secret.rotate(); // or rotate({ secret: "..." })
```

## Deduplication

Senders redeliver events after a timeout. Every accepted request gets a dedupe key: the SHA-256 of the `dedupe` expression's value, such as GitHub's `X-GitHub-Delivery` header, or of the raw body when the trigger has none, or the expression fails or yields anything but a non-empty string. A request whose key matches a delivery the trigger already has is answered `200 { deliveryId, duplicate: true }` and does nothing. Deliveries are kept until the trigger is deleted, so a duplicate is recognized however late it comes.

## Test rules on a sample event

`triggers.test` runs a draft trigger's rules on a sample event exactly as a real request would, after the signature: the dedupe expression, then each enabled rule's filter and both templates. It stores nothing and sends nothing, and the trigger need not exist.

```go Go theme={null}
result, err := client.Triggers.Test(ctx, paddock.TriggerTestRequest{
	Trigger: draft, // a paddock.TriggerCreate
	Event: paddock.TestEvent{
		Headers: map[string]string{"x-github-event": "pull_request"},
		Body: map[string]any{
			"action":       "opened",
			"repository":   map[string]any{"full_name": "acme/web"},
			"pull_request": map[string]any{"number": 42, "draft": false},
		},
	},
})
if err != nil {
	return err
}
for _, r := range result.Rules {
	// Matched is nil when the rule is disabled or its filter failed. SessionKey is nil
	// unless the rule matched and both templates rendered; for mode "new" it reads
	// "dlv_…/<rule>".
	if r.Matched == nil || !*r.Matched || r.SessionKey == nil {
		fmt.Println(r.Rule, "no session", r.Error)
		continue
	}
	fmt.Println(r.Rule, *r.SessionKey, r.Missing)
}
```

```python Python theme={null}
result = client.triggers.test(
    trigger=draft,  # the same dictionary or model triggers.create takes
    event={
        "headers": {"x-github-event": "pull_request"},
        "body": {
            "action": "opened",
            "repository": {"full_name": "acme/web"},
            "pull_request": {"number": 42, "draft": False},
        },
    },
)
for r in result.rules:
    print(r.rule, r.matched, r.session_key, r.missing)
```

```ts TypeScript theme={null}
const result = await paddock.triggers.test({
  trigger: draft, // the same object triggers.create takes
  event: {
    headers: { "x-github-event": "pull_request" },
    body: { action: "opened", repository: { full_name: "acme/web" }, pull_request: { number: 42, draft: false } },
  },
});
for (const r of result.rules) console.log(r.rule, r.matched, r.sessionKey, r.missing);
```

Each rule's result says whether it is enabled, whether it matched, its first error with the code a real outcome would record, the rendered session key and message, and `missing`, the message paths that led nowhere. The console's rule editor runs this on every edit; see [Console](https://docs.paddock.build/platform/console.md).

## Deliveries

Every request to an existing trigger is a **delivery**. paddock records it durably and answers before doing anything else, then delivers it in the background. A sender waits only for the record, so a slow agent wake never times it out.

| Delivery `status` | Meaning |
| - | - |
| `pending` | At least one rule's outcome is not final yet |
| `done` | Every outcome is final |
| `rejected` | The request was refused before any rule ran: `bad_signature` or `invalid_body` |

Each delivery has one outcome per rule that was enabled when it arrived:

| Outcome `status` | Meaning |
| - | - |
| `pending` | Matched and waiting to be delivered, or waiting behind an earlier delivery for the same key (`waitingFor`) |
| `filtered` | The filter was false |
| `delivered` | The message was sent: `sessionId`, `sessionCreated`, `messageId`, and `seq` say where |
| `failed` | It ended with an error: `filter_error`, `template_error`, `agent_not_found`, `unavailable`, or `internal` |

```go Go theme={null}
for d, err := range trigger.Deliveries.List(ctx, paddock.DeliveryList{Status: "done"}) {
	if err != nil {
		return err
	}
	for _, o := range d.Outcomes {
		fmt.Println(d.ID, o.Rule, o.Status)
	}
}
```

```python Python theme={null}
for d in trigger.deliveries.list(status="done"):
    for o in d.outcomes:
        print(d.id, o.rule, o.status)
```

```ts TypeScript theme={null}
for await (const d of trigger.deliveries.list({ status: "done" })) {
  for (const o of d.outcomes) console.log(d.id, o.rule, o.status);
}
```

`deliveries.get(id)` adds the request as the sender sent it: its headers, query, and body. Deliveries are listed newest first and kept, with their requests, until the trigger is deleted.

### What a delivery promises

* **Exactly one message per rule.** A rule's message is appended in the same transaction that marks its outcome delivered, so a delivery retried after a crash never sends a message twice.
* **Fixed on receipt.** Filters and templates run when the request arrives, so editing or disabling a rule later never changes what a recorded delivery sends.
* **In order per session key.** Deliveries for one agent and one session key are delivered in the order they arrived; a later one waits until the earlier ones are final. Other keys are not held back.
* **Bounded retries.** A failure that may pass, such as a service briefly unavailable, is retried up to 5 attempts in total, 30 seconds, 2 minutes, 8 minutes, and 32 minutes apart; then the outcome fails with its last error. A failure that would repeat, such as `agent_not_found`, fails at once. A delivery stuck in retries holds back later deliveries for its key for at most about 43 minutes.

Once a message is delivered it is the session's like any message you send, and a turn that fails is retried by the agent.

### Replay

Replay delivers a recorded request again, for real, as a new delivery that runs the rules as they are now. Deduplication never drops it, and the signature is not checked again. A rule in `key` mode reaches the same session the first delivery reached, if it still exists. A rejected delivery cannot be replayed (`409 conflict`).

```go Go theme={null}
replayed, err := trigger.Deliveries.Replay(ctx, "dlv_01h455vb4pex5vsknk084sn02q")
```

```python Python theme={null}
replayed = trigger.deliveries.replay("dlv_01h455vb4pex5vsknk084sn02q")
```

```ts TypeScript theme={null}
const replayed = await trigger.deliveries.replay("dlv_01h455vb4pex5vsknk084sn02q");
```

## Update and delete

`triggers.update(id, spec)` replaces the name, the verification, the dedupe expression, and the whole list of rules, so send the whole trigger every time, without its secret; a field you leave out is cleared. The ID, the URL, and the secret stay. Deleting a trigger makes its URL answer `404` at once and removes its deliveries; the sessions its rules created stay.

```go Go theme={null}
// draft is the paddock.TriggerCreate the trigger was created from.
_, err := client.Triggers.Update(ctx, trigger.ID, paddock.TriggerUpdate{
	Name:         "GitHub acme/web (production)",
	Verification: draft.Verification,
	Dedupe:       draft.Dedupe,
	Rules:        draft.Rules,
})
if err != nil {
	return err
}
err = client.Triggers.Delete(ctx, trigger.ID)
```

```python Python theme={null}
# draft is the dictionary the trigger was created from.
spec = {key: value for key, value in draft.items() if key != "secret"}
client.triggers.update(trigger.id, {**spec, "name": "GitHub acme/web (production)"})
client.triggers.delete(trigger.id)
```

```ts TypeScript theme={null}
// draft is the object the trigger was created from.
const { secret, ...spec } = draft;
await paddock.triggers.update(trigger.id, { ...spec, name: "GitHub acme/web (production)" });
await paddock.triggers.delete(trigger.id);
```

The webhook endpoint's answers are on [Trigger webhook](https://docs.paddock.build/api-reference/webhook.md). For a complete setup, see the [pull request reviewer](https://docs.paddock.build/examples/pr-reviewer.md).


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