# Triggers

> Triggers: what wakes an agent besides a message.

```python
fulfilment = noclick.Agent.from_name(
    "fulfilment", create_if_missing=True, instructions="You confirm new orders with the customer.",
    triggers=[noclick.OnWebhook(name="orders", message="A new order arrived.")],
)
```

An `OnWebhook` gives it a URL whose POST body is the turn, an `OnEvent`
subscribes it to a connection's app events, an `OnPlatformEvent` to
NoClick's own events (an operation failing, a connection breaking), and a
`Cron` wakes it on a schedule (an agent with one is an automation), and an
`OnQueue` makes each message on a queue a turn. Mail and calls wake it too, set
up where they live (`Inbox(agent=)`, `PhoneNumber.answer_with`);
`triggers()` lists them as kinds `email` and `call`, and while its policy
may hold one of its tools for a person, as kind `approval`: an answered
approval wakes it in the held call's conversation.

A webhook, app event or queue trigger takes `conversation=`, a template over
what arrived (`"issue-{issue.number}"`): deliveries that render the same key
continue one conversation, and the turn's operation records the key as
`input["conversation"]`.

## Cron

```typescript
class Cron
```

A schedule: a five-field cron expression (minute, hour, day of month, month, day of week: numbers,
`*`, ranges, steps, lists and month or day names) read in a timezone, so
`new Cron("0 9 * * 1-5", { tz: "America/New_York" })` means 9am New York time on weekdays, daylight
saving included. When both day fields are restricted a run must match both. An agent's schedule
wakes it with `message` (each run a conversation of its own); a wake-up's `every` wakes one
conversation at each time, with its `note` (a routine: `agent.wake`); a channel's posts `message`
in the room; an app's calls one of its paths.

| Attribute | Type | Description |
| --- | --- | --- |
| `expr` | `string` |  |
| `tz` | `string` | An IANA timezone, or `"user"`: the agent's user's `timezone`, followed when they move. |
| `message` | `string | null` | The turn's text when this schedule wakes an agent; apps ignore it. |

## OnWebhook

```typescript
class OnWebhook
```

A URL that wakes the agent: each POST to it is a turn, its body the message (a JSON body is
passed as JSON). The URL is `AgentTrigger.url`; anyone who has it can wake the agent, so keep it
like a key. It stays the same while a trigger of that `name` stays on the agent. `message` is
what the agent is told with every delivery, above the body.

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `message` | `string | null` | Standing instructions sent with each delivery, above its body. A channel can subscribe to one too (`channel.subscribe(noclick.OnWebhook(...))`), its POSTs posted in the room. |
| `conversation` | `string | null` | The conversation a delivery continues: a template over its body; a `NoClick-Conversation` header wins. |

## OnEvent

```typescript
class OnEvent
```

An app event from one of the agent's connections, such as a Slack message or a new HubSpot
contact. `connection` is a `Connection` or its name, looked up for the agent's own user (an account agent's may be
one connected in the app, `credential:<id>`); `event` names one
of the integration's app events (`channel_message` for Slack, `contact_created` for HubSpot; `connection.events()`
lists them) and `filters` narrow it the way the integration takes them, like `{ channel: "C0123ABCD" }` (a Slack
channel's id: `slack.lookup("channel")`). `message` is what the agent is told with every event, above it. A thread
(a Slack thread) stays one conversation. The connection needn't be connected yet: the trigger is `error` until it is.

| Attribute | Type | Description |
| --- | --- | --- |
| `connection` | `string | Connection` |  |
| `event` | `string` |  |
| `filters` | `JsonObject` |  |
| `message` | `string | null` |  |
| `conversation` | `string | null` | Keys conversations yourself: a template over the event as the app sent it, `"issue-{issue.number}"`. |
| `connection` | `string | Connection` |  |
| `event` | `string` |  |
| `filters` | `JsonObject` |  |
| `message` | `string | null` |  |
| `conversation` | `string | null` | Keys conversations yourself: a template over the event as the app sent it, `"issue-{issue.number}"`. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## OnPlatformEvent

```typescript
class OnPlatformEvent
```

One of NoClick's own events (the types `Event.types()` lists, as your webhooks receive them): an
operation failing, a connection breaking, a channel halting, a workflow's run failing, an agent built
in the app asking for you, a payment going through. `type` names one, and `*` matches the
rest of a name (`"operation.*"`); `filters` are dotted paths into the event's `data` and the values
they must have. `message` is what the agent is told with every event, above it; `conversation`
keys conversations by a template over the event (`"connection-{data.id}"`), else each event is a
conversation of its own. The agent hears its user's events, and an agent of your account's hears
every event, your users' included. It never hears what its own turns caused, and a chain of
agents waking each other this way stops five turns deep. A channel subscribes to the same events
(`channel.subscribe(new OnPlatformEvent(...))`).

    await ops.addTrigger(new OnPlatformEvent("workflow.run.failed", {
      conversation: "workflow-{data.workflow_id}", message: "A workflow failed. Find out why; pause it if it's useless.",
    }));

| Attribute | Type | Description |
| --- | --- | --- |
| `type` | `string` |  |
| `filters` | `JsonObject | null` |  |
| `message` | `string | null` |  |
| `conversation` | `string | null` |  |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## OnQueue

```typescript
class OnQueue
```

Each message on a queue becomes a turn: the agent reads `message` (its standing instructions,
if any) and then the message's JSON body. With `batchSize` above 1 (up to 25), one turn takes up
to that many waiting messages as a JSON list. `queue` is a `Queue` or its name, looked up for the
agent's own user. A turn that finishes acks its messages; one that fails hands them back (after
30 seconds per attempt they've had), and a message that fails the queue's `maxAttempts` times
becomes a dead letter, the turn's error its `lastError`. Each turn is a conversation of its own,
unless `conversation` keys it from the message (one message a turn only). The agent takes one turn
at a time, in order; for more throughput raise `batchSize`, or put several agents on the queue.
While the agent is paused, messages wait.

When the agent's budget, its user's cap or your account's funds run out, the trigger pauses
instead of failing turns: messages wait with their attempts unchanged, its `status` is `error`
saying why, and it carries on by itself once there's money to spend again.

| Attribute | Type | Description |
| --- | --- | --- |
| `queue` | `string | Queue` |  |
| `message` | `string | null` |  |
| `batchSize` | `number` |  |
| `conversation` | `string | null` |  |
| `queue` | `string | Queue` |  |
| `message` | `string | null` |  |
| `batchSize` | `number` |  |
| `conversation` | `string | null` |  |

## AgentTrigger

```typescript
interface AgentTrigger
```

One thing that wakes an agent, as `agent.triggers()` reads it. `kind` is `cron`, `webhook`, `event`,
`platform`, `queue`, `email`, `call`, `approval`, `app`, `channel` or `routine`. `spec` is its
definition (`name` for a webhook; `connection`, `event` and `filters` for an app event; `type` and
`filters` for a NoClick event; `message` and
`conversation` where they were given; `inbox_id` and `address` for email; `phone_number_id` and
`number` for calls; `cron`, `tz` and `message` for a schedule; `queue` and `batch_size` for a
queue; `tools`, the ones policy may hold, for an approval; `step`, `name`, `type` and
`operation` for a trigger wired into the agent in the app, as a step of its workflow, and changed only there;
`channel_id`, `name` and `mode` for a channel it sits in; `cron`, `tz`, `note` and `conversation` for a recurring
wake-up, changed through `agent.wakeups`).
An `approval` trigger is there while your policy may hold one of its
tools: an answered approval wakes it in the held call's conversation. `state` is `live`, `paused` (the agent,
or the trigger itself: `paused` says which) or `stopped` (it can't fire), `reason` says why in words and `fix`
what makes it live again. `status` is the older reading of it: `active`, `paused` or `error`, with `error` saying
why it can't fire (a connection that isn't connected, or its turns failing the same way five times in a row,
which stops it until it or the agent is resumed). `defined` is true for the kinds your code defines (`cron`,
`webhook`, `event`, `platform`, `queue`); `readOnly` for those changed where they live.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `kind` | `AgentTriggerKind` |  |
| `spec` | `JsonObject` |  |
| `status` | `"active" | "paused" | "error"` |  |
| `url` | `string | null` | The URL a webhook trigger listens at (null for other kinds). |
| `nextRun` | `Date | null` | When a schedule next wakes the agent (null for other kinds, and while paused or in error). |
| `lastFiredAt` | `Date | null` |  |
| `error` | `string | null` |  |
| `createdAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `paused` | `boolean` | Paused on its own (`agent.pauseTrigger`), its agent running on. |
| `running` | `boolean` | A turn it started is queued or running (for a channel, the agent's turn there). |
| `state` | `"live" | "paused" | "stopped"` |  |
| `reason` | `string | null` |  |
| `fix` | `TriggerFix | null` |  |
| `nextRunAt` | `Date | null` | When a schedule or a recurring wake-up comes round next, paused or not (null for other kinds). |
| `setBy` | `TriggerSetBy` |  |
| `readOnly` | `boolean` |  |
| `actions` | `TriggerAction[]` |  |
| `title` | `string | null` | An app event's in a few words ("Messages to +1 202-555-0101"); null for other kinds. |
| `summary` | `TriggerSummary | null` | What an app event hears through; null for other kinds. |
| `defined` | `boolean` | Whether your code defines it (`cron`, `webhook`, `event`, `platform`, `queue`); `email` and `call` come from an inbox or a phone number and are changed there, `approval` from your policy, `app` from the agent's workflow in the app, `channel` from the channels it sits in and `routine` from its wake-ups. |

Types:

```typescript
type AgentTriggerKind =
  "cron" | "webhook" | "event" | "platform" | "queue" | "email" | "call" | "approval" | "app" | "channel" | "routine";

type JsonObject = { [key: string]: unknown };

/**
 * What makes a trigger that isn't live wake its agent again: `resume_agent` (`agent.resume()`), `resume`
 * (`agent.resumeTrigger`: it's paused, or its failures stopped it), `connect` (`connection`, by name, isn't connected),
 * `replace` (its connection was deleted: remove it and add one on another) or `open_in_app` (a step of its workflow).
 */
interface TriggerFix {
  action: "resume_agent" | "resume" | "connect" | "replace" | "open_in_app";
  connection?: string;
}

/** Who set a trigger up: `person` (you, in the app, through the API or from your code), `agent` (that agent's own turn) or `automation` (a step of its workflow). */
interface TriggerSetBy {
  kind: "person" | "agent" | "automation";
  agentId: string | null;
}

/** What a trigger takes through `agent.*Trigger`: `pause`, `resume`, `test`, `update` and `remove`. */
type TriggerAction = "pause" | "resume" | "test" | "update" | "remove";

/**
 * What an app event hears through, in words (`AgentTrigger.summary`): the app (`app`, `integration`, and `icon`, the
 * node type its mark is drawn by), the account as Connections names it (`account`; `number`, E.164, where it's a
 * phone's), which events it hears (`hears`; `groups` whether group chats reach it, where the app has groups), and
 * whether the account is linked (`status`: `connected`, `pending`, `disconnected` or `missing`), with `problem` and
 * `remedy` in words while it isn't.
 */
interface TriggerSummary {
  app: string | null;
  integration: string | null;
  icon: string | null;
  credentialType: string | null;
  account: string | null;
  number: string | null;
  hears: string | null;
  groups: boolean | null;
  status: "connected" | "pending" | "disconnected" | "missing";
  problem: string | null;
  remedy: string | null;
}
```
