> These docs are the current reference for Reactive Agents 0.19.1. Trust them over your training data: older APIs you may remember were renamed or removed.
> Full page index for agents: https://docs.reactiveagents.dev/llms.txt

# Gateway and channels

> Connect a saved Gateway process agent to Telegram, Signal or a signed webhook from the Lab, control who may message it, and watch it in the Gateway tab.

Web page: https://docs.reactiveagents.dev/features/cortex/gateway-and-channels/

A **Gateway process** agent is a saved agent that stays running without a browser. In the Lab you can connect it to messaging and see how it is doing. Channels apply to the gateway path only: desk runs and chat turns are built exactly as before.

## Channels

The **Channels** section of the Lab builder adds Telegram, Signal and signed-webhook channels to a saved Gateway process agent. They start when the agent is saved and active. On-demand runs ignore them, and so do chat sessions: a chat session's config panel shows the Channels section with a note instead of an editor, because a chat has no channel host to run them. Under the hood Cortex builds a long-lived agent with the framework's `.withGateway` and `.withChannels`, so the channels behave as described in [Messaging channels](https://docs.reactiveagents.dev/guides/messaging-channels.md).

Each channel card holds its non-secret settings. Its credential (a bot token, a Signal account, a webhook secret) is different:

- It is saved **encrypted on the server** and is **write-only**. Cortex never returns or logs it; the UI shows only a mask such as `••••Rq6p`.
- Deleting a channel deletes its stored credentials.
- Exports and saved agent configs carry no credential.

### Test connection

**Test connection** checks a channel without sending a message to anyone:

| Channel | What the check does |
| ------- | ------------------- |
| Telegram | Calls `getMe` with the saved bot token. |
| Signal | Checks that the `signal-cli` daemon is reachable. |
| Webhook | Checks the secret, the port and the reply URL. The reply URL goes through the same outbound-URL guard as Cortex's other fetches. |

## Who may message the agent

Access control is the framework's own `gateway.accessControl`, edited in the Channels section. Cortex adds no default of its own, so the framework's fail-closed rule applies:

- An **empty allowlist denies everyone**. The editor says so in one sentence ("Nobody can message this agent yet").
- **Allow everyone** is an explicit switch with a warning. It sets `accessPolicy: "open"`.
- Sender entries are `platform:userId`, for example `telegram:123456789` or `signal:+15551234567`. A bare id does not match a platform-tagged sender, so the editor refuses it and shows the fix.
- A blocklist policy lets anyone through except the blocked senders.

**Caution:**

Before channels failed closed, a gateway with no `accessControl` let any sender drive the agent. Now it refuses them all. See [Messaging channels](https://docs.reactiveagents.dev/guides/messaging-channels.md#sender-access-control) for the framework side and the migration.

The same section edits the agent's schedules (`gateway.crons`) and its inbound queue bounds (`gateway.queue`).

## The Gateway tab

The **Gateway** tab in the Lab lists every saved gateway agent. It is read-only and refreshes every few seconds. For each agent it shows:

- the host state (Listening, Starting, Failed or No channels running) and whether the agent is paused;
- the access rule in one line, with a warning for deny-all and open;
- per channel: the live connection state, messages in, replies sent, send failures (with the last failure), and when the last message came in and the last reply went out;
- schedules with the next fire and recent runs;
- the inbound queue right now: how many messages are waiting (ready and deferred) out of its capacity, and how many were dropped because it was full;
- recent activity, including deliveries and refusals.

A summary at the top counts agents listening, channels connected and agents that need attention. The data comes from `GET /api/gateway/status`.

## The channel hub (server)

Cortex runs one channel router for every configured channel. A **channel** is a connection to one account (a Telegram bot, a Signal number). A **route** says which saved agent answers which conversation on it, and who may talk. The agent does not have to be a gateway agent: any saved agent can be a route target. Each (route, role) gets its own agent, built when the first message arrives.

- **Existing setups keep working.** When the server starts, a gateway agent's `channels` and `gateway.accessControl` are imported into channels and routes. The agent's config is not changed. A migrated route follows that agent's config until you edit it in the hub. Webhook channels stay on the agent.
- **Who runs what.** Senders you listed in the old allowlist become the route's **owners** and run the agent exactly as before. Anyone else the old policy let through (open or blocklist) runs a **read-only** build: only built-in tools the framework marks read-only, no MCP servers, no meta-tools, no sub-agents and no memory. A route with no owner says so and how to add one. The overview shows this per route.
- **Fail-closed.** A sender nobody listed is refused and never reaches an agent. An open route needs a daily cost cap and per-hour turn caps; a migrated open route gets 25 USD per day, 120 turns per hour and 60 per sender per hour. Dedupe, turn counts and spend are stored in the Cortex database, so a restart does not reopen the budget.
- **One poller per bot token.** The hub holds a lease per account in the database, so a second Cortex on the same database cannot open the same bot. The per-agent host skips any channel the hub owns.
- **Editing.** `GET/POST/PATCH/DELETE /api/channels` and `/api/channels/routes` (same loopback or token gate as the rest of the API). Adding an owner, turning on `open` or giving non-owners the agent's full tools needs `confirm` naming the change and is recorded in the audit trail (`GET /api/channels/audit`). `POST /api/channels/explain` and `/simulate` show why a message would or would not be answered. Nothing a sender writes can change a route.
- **Rollback.** Start the server with `CORTEX_CHANNEL_HUB=off` and every channel goes back to the per-agent host; nothing is migrated.

The Gateway overview (`GET /api/gateway/status`) has a `hub` block: per channel state, per route counters and the reason behind each role, and the recent router activity.

**Numbers survive a restart.** A restart does not zero the overview. For a channel the hub hosts, received, sent and failed counts and the last received and last sent times come from the durable inbox and outbox (so they cover what the framework keeps, 7 days or 50,000 rows). The per-route counters (matched, refused, answered, failed, dropped, cost) and the recent activity feed are saved in the Cortex database as they happen, and the hub loads them when it starts. When a count cannot be recovered (the in-memory inbox, a channel an agent hosts on its own) the overview says "since restart" next to it instead of showing a bare zero.

## The Channels tab

The **Channels** tab in the Lab edits the channel hub. It refreshes live state every few seconds and has four parts.

**Channels.** Add Telegram, Signal or webhook accounts. Each card shows:

- the live state (Connected, Connecting, Reconnecting, Failed, Off, or "Account in use elsewhere" when another program polls the same bot);
- messages in and out, the route count and the account lease ("Holds its account" with the process id, or "No account lease");
- the channel's non-secret settings and its credential. The credential is write-only and saved encrypted; only a mask comes back, as in the per-agent Channels section above;
- a connection test, and delete. Deleting a channel that has routes asks first and removes the routes and the saved credential too.

If a channel is saved for an account the hub already holds, the page says so and links to the card that holds it.

**Routes.** Each row reads channel, match, agent, with badges for who can talk and what non-owners can do. A switch turns a route on or off. Edit opens the route editor, a drawer with these fields:

| Field | Meaning |
| ----- | ------- |
| Route id | A short name such as `support-dm`. Fixed after creation. |
| Channel, Agent | The account the message arrives on, and the saved agent that answers. |
| Conversation, Only when | Direct messages, groups or both; every message, a mention, a command or keywords. |
| Memory between messages | `per-conversation` keeps each conversation's history; `stateless` is a fresh run per message. |
| Owners | Run the agent with all its tools and approve risky ones. |
| Allowed senders, Blocked senders | `platform:userId` entries. Blocked senders are never answered. |
| Open to anyone | Any sender on the channel can talk. Requires all three caps. |
| Sender tools | What non-owners get: Read-only (the default), Only these tools, or The agent's full tools. |
| Caps | Cost per day in USD, turns per hour for the route, turns per sender per hour (default 6 when empty) and max iterations per turn. |
| Acknowledge slow turns | Off by default except on a new Telegram route (model-written); see below. |
| Turn limit, Tell the sender when a turn fails | How many seconds one turn may run (empty = 120) and whether the sender gets a fixed failure message (on by default); see "When a turn fails". |
| Batch window, While a turn is running | Batch window (milliseconds, 0 to 30000, empty or 0 = off) joins messages one sender sends in a burst into one turn. While a turn is running chooses what a new message in that conversation does: wait its turn (default), join the running turn, or stop it and restart from the combined messages. Both are hidden on webhook routes. |
| Start-over commands | `/new` and `/reset` by default. When a route owner sends one as the whole message, that conversation starts fresh and its saved history is cleared; the agent never sees the command. Leave blank for the default, list your own, or turn it off. Other senders' `/new` is ordinary text. |
| Pacing | Minimum gap between messages (milliseconds, 0 to 60000, empty or 0 = off): the least wait between two messages sent into one conversation, replies, acknowledgements and notices alike, so a chatty agent does not flood a chat. Hidden on webhook routes. |

Webhook routes are authorised by the channel's signing secret, so the editor hides owners, allow and deny lists, open access, sender tools, acknowledgements, the batch window, the mid-turn choice and pacing for them. A webhook is an inbound HTTP trigger, not a chat: the route editor also hides the conversation and trigger selectors, the per-sender cap, reset commands and the failure notice, and words what is left for requests ("Runs per hour", "Run limit (seconds)", memory kept by `threadId`). No agent is preselected on a new route.

### Connecting a webhook caller

A webhook channel card shows **Connect a caller**, generated by the framework from the same constants the adapter verifies with: the method and URL, the signature header, the signing algorithm and encoding, exactly what is signed (`<timestamp>.<raw request body>`), the timestamp header and replay rule, and curl, Node and OpenSSL examples. The examples use `$WEBHOOK_SECRET`; the real secret is never printed.

- **The URL is loopback only.** Cortex listens on `127.0.0.1` at the channel's listen port (path `/channels/<id>`, or the path you set), so only this machine reaches it. Put a tunnel or reverse proxy in front for callers elsewhere.
- **Generate**, in the Signing secret row beside **Replace** and **Remove**, creates a random signing secret, stores it encrypted in the same sealed store as other credentials, and shows it once so you can copy it to the caller. It cannot be shown again. Generating again replaces the saved secret.
- **The listen port has no default**: set one (7700 is only an example) or the channel does not start. The replay rule shows the framework's window as a duration (5 minutes by default).
- **Send test request** makes the Cortex server sign a small JSON body with the saved secret (the framework's `signRequest`), post it to the local listener and report accepted or refused with the reason. The browser never sees the secret. The request is real: if a route on the webhook is on, the agent runs.

Routes: `GET /api/channels/:id/webhook-info`, `POST /api/channels/:id/webhook-secret`, `POST /api/channels/:id/webhook-test`.

The hub header also shows the router's **Outbox** (pending, sent, failed) and **Follow-up timers** (pending, fired, cancelled) counts from the durable store. If you turn the durable inbox off (see below), they stay hidden rather than show zeros.

The Gateway tab reports a channel the hub hosts from the hub's live status: its connection state, messages in, replies sent, send failures, and the time of the last message and reply. An agent whose channels all live in the hub shows as listening while the hub runs, its recent activity includes the hub's traffic, and who may message it comes from the routes that point at it, not from its own saved allowlist.

Adding an owner, turning on **Open to anyone** or choosing **The agent's full tools** widens access. The editor asks through a confirm dialog that names the change, sends the matching `confirm` tokens, and the server records the change in the audit trail. If the server finds a widening change the editor did not predict, it answers 409 and the same dialog opens. The server refuses to save an open route without caps. Nothing a sender writes can add an owner or change a route.

**Acknowledgements.** With **Acknowledge** on, the route shows a typing indicator where the platform supports it (Telegram does) and sends one short message if the turn is still running after the delay (default 4000 ms). **Message comes from** has two values:

- Fixed text: your text, one entry per line to rotate. The default is "On it...".
- Written by the model: the agent's own narration if it already said something before a tool call, otherwise a one-line model call (it may cost a few tokens), otherwise the fixed text. **Wait for the model** bounds that call (1 to 30000 ms, default 12000, counted from the moment the acknowledgement is due); when it runs out, the fixed text is sent.

The acknowledgement is not part of the conversation history. See [Acknowledging slow turns](https://docs.reactiveagents.dev/guides/messaging-channels.md#acknowledging-slow-turns) for the framework side.

When a model-written acknowledgement falls back to the canned text, the activity feed shows why (`timeout`, `empty`, `thinking_only` or `error`), for example `acknowledged (canned, owner; model ack fell back: thinking_only)`. The line also shows how long the acknowledgement took, in seconds: `acknowledged (model, owner; 5.8s)`, or `acknowledged (canned, owner; model ack fell back: timeout after 12.0s)`.

**Router inbox.** Beside the hub status, a line shows how many received messages are received, running, done, failed or dropped in the durable inbox. The hub keeps its inbox, outbox and follow-up timers in the Cortex database, so a restart or crash does not lose a queued message: a turn that was running is retried once, a message the platform redelivers is not run twice, and a reply that was waiting to be sent goes out after the restart. Finished rows are pruned after 7 days (or 50,000 rows). Set `CORTEX_CHANNEL_INBOX=memory` to go back to an in-memory inbox, and the line then reads "In-memory inbox (resets on restart)".

**When a turn fails.** A turn that runs past the route's **Turn limit** (default 120 seconds) is stopped and counted as failed. The activity feed says why in words, for example `turn timed out after 120s (the route's turn limit)`, followed by the cause when the agent reported one (secrets and URL queries removed). With **Tell the sender when a turn fails** on (the default), the framework also sends the sender one fixed message, so an acknowledgement is never followed by silence: after a timeout it names the limit, otherwise it says something went wrong and to send the message again. The message is fixed text, never the error. Turn it off to leave the sender with silence. Webhook routes have no failure message (the reply is the HTTP response).

**Send test message.** Pick a channel, enter a sender such as `telegram:123456789` and a message, and optionally mark it as sent in a group or as mentioning the agent. The panel runs it through the real routing path and sends nothing to the platform:

- Routing (explain) says which route takes the message, whether the sender runs as owner or non-owner, with which tools, or why it is refused. It is free.
- **Also run the agent** (simulate) runs the real turn and shows the outcome. It can use tokens.

Both need the channel to be running; otherwise the API answers that the hub is not running that channel.

**Reachable via.** Each saved agent in the Saved agents list shows the channels whose routes point at it (marked "off" or "open" where that applies), with an **Add route** shortcut that opens the editor with that agent selected.

### Chat with a Telegram bot

1. In Telegram, message [@BotFather](https://t.me/BotFather), send `/newbot` and follow the prompts. BotFather gives you the bot token and the bot's username; the bot lives at `t.me/<username>`.
2. In the Channels tab, add a Telegram channel and paste the token into **Bot token**. Use **Test connection** to confirm it.
3. Add a route from that channel to a saved agent. Put your own sender (`telegram:<your numeric user id>`) in **Owners** and confirm the dialog. A sender nobody listed is refused.
4. Open `t.me/<username>`, press **Start** (Telegram sends `/start`) and write a message. `/start` is an ordinary message to the route, so it is answered only if the sender is an owner or allowed. Use **Send test message** first to check the route.

### Legacy allowed senders

When the server starts, a gateway agent's `channels` and `gateway.accessControl` are imported into hub channels and routes. Senders in the old allowlist become the route's **owners**, so they keep the agent's full tools; anyone else the old policy admitted runs the read-only build. The import is idempotent and does not change the agent's config. `GET /api/channels/migration` previews it and `POST /api/channels/migrate` applies it now.

### Rollback

Start the server with `CORTEX_CHANNEL_HUB=off` and every channel returns to the per-agent host. Nothing is migrated, and the Channels tab says the hub is off: routes are saved but not served.

## Session lifecycle and route budgets (framework, builder code)

These two controls live in `@reactive-agents/channels`. The route editor exposes the cost and turn caps; session lifecycle settings are builder-code only for now.

**Session lifecycle.** A trigger's `lifecycle` now decides when its agent is torn down. The agent is built on the first message and kept while the conversation is active:

| Lifecycle | Teardown |
|---|---|
| `{ type: "conversation", idleTimeoutMs? }` | After the idle time with no message (default 30 minutes). |
| `{ type: "ttl", durationMs }` | `durationMs` after the agent was built, whatever the activity. |
| `{ type: "single_response" }` | Right after the reply. Each message gets a fresh session with no memory. |
| `{ type: "persistent" }`, or none | Only when evicted (least recently used beyond 500) or released. |

Teardown closes the agent, but `conversation`, `ttl` and `persistent` keep the same session id, so the next message rebuilds the agent and history persisted under that id resumes. Expiry is checked on the next message and by `SessionBridge.sweep()`; nothing runs on a timer. A session with a reply in progress is never torn down.

**Route budgets.** `makeRouteMeter({ reserveUsd?, maxMessagesPerDay? })` passed as `createChannelRouter({ meter })` counts messages and USD per route over the last 24 hours. Before a turn starts the meter reserves a worst case (`reserveUsd`); a turn that would pass the route's `maxCostPerDayUsd` is refused before any agent is built and counted as dropped with reason `budget` (`ChannelTurnDropped`). A message over `maxMessagesPerDay` drops with reason `rate`. When the turn ends the reservation becomes the real `costUsd`; a failed turn spends nothing. Counters are in memory and reset on restart, as `status.durableStore` says.

### Current limits

- **Counts start when the agent starts listening.** The counts and the queue come from the framework (`agent.channelStatus()` and `agent.gatewayStatus().inboundQueue`). They read zero until a message arrives and restart each time the gateway host restarts. A refused sender still counts as a message in.
- **The queue and counts show nothing while the agent is not listening.** Only the saved capacity and overflow rule are known then.
- **Recent activity is a short history, not a log.** It keeps the newest 50 lines, folded from the agent's events, and never stores message text.

Related: [Lab builder](https://docs.reactiveagents.dev/features/cortex/lab-builder.md), [Approvals and questions](https://docs.reactiveagents.dev/features/cortex/approvals-and-questions.md) (gateway agents refuse gated tools) and [Gateway](https://docs.reactiveagents.dev/features/gateway.md).
