Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


title: Outbox Approval Protocol tags: [pubsub, approval, discord, email]

Outbox Approval Protocol

Outbox services can hold an outbound message for human approval before sending it. The agent never sends directly; it writes to an outbox stream, and a broker service decides whether to forward the message, optionally gating it behind a human reaction.

Source: pkgs/bridge/base.py (OutboxService), pkgs/bridge/outcomes.py (how each decision settles), pkgs/bridge/approval_client.py (the gate client), with per-platform implementations in pkgs/discord/ and pkgs/email/.

See also Security Model.

Transport

Messages move over Redis Streams. Each bridge {name} has an inbox stream ({name}:inbox) and an outbox stream ({name}:outbox). OutboxService reads its outbox via a consumer group ({name}-outbox / worker {name}-worker) and acknowledges each entry after handling it.

Two approval planes

A host keeps its decisions on one of two planes:

  • The operator gate, when services.cowboy.approvals.enable is set. Every bridge is given COWBOY_APPROVAL_SOCKET and asks the cowboy-approvals service over it to create, read, claim and settle a request. Requests live in approval-gate:v1:*, which no bridge credential can read or write. The bridge’s gate policy sets the window and the methods that may answer: a security key, and a Discord reaction or an email reply only where the policy names that transport. See the gate’s README.
  • The Redis plane, otherwise. The decision is a plain approval:{uuid} hash in the message Redis, and a reaction or reply from a listed approver answers it.

Both planes use the same park-and-poll loop in OutboxService, and both read a decision into one outcome, so each outcome settles the entry, and reads to the agent, the same way whichever plane decided it (see Outcomes).

Flow on the Redis plane

When approval_required is set, an outbound message is held and routed through a notification channel:

  1. The agent writes a message to its outbox — {agent}:{source}:outbox under the per-agent ACL (the flat {source}:outbox on a shared Redis).
  2. OutboxService.process_one() sees approval_required and the message has no approval_id, so it parks the entry (_resume_or_start_approval):
    • creates approval:{uuid} with status=pending, source, channel_id, a content_preview (first 200 chars), created_at and expires_at
    • writes a notification to the configured notify outbox ({approval_notify}:outbox) carrying the approval_id
    • returns without acking, so the rest of the stream keeps moving
  3. The notify service (e.g. Discord) sends the notification. Because the message carries an approval_id and the send returns an external_id, the base loop records the mapping in approval:{source}_map (external id → approval id).
  4. A human reacts to the notification.
  5. The notify service’s ingest handler calls OutboxService.resolve_approval(), which looks up the approval id from the map and, if the record is still pending and inside its window, sets status to approved or rejected plus the approver. A late answer — a record already decided, past expires_at, or already settled and deleted — is ignored; the map entry is dropped either way.
  6. The original outbox service checks its parked entries once per loop (poll_awaiting, via check_approval, which reads the deadline before the decision); it sends the message on approved, or acks it and tells the agent on its inbox that the operator declined it (rejected) or that it was rejected automatically (expired).

Email answers with a reply to the notification from an allowed sender. The first non-blank line must be exactly one decision word (approve, approved, yes, ok, lgtm, or reject, rejected, no, deny, denied), with at most one trailing . or !. A reply such as “ok but not before Friday” is not a decision and reaches the agent as a message. The bridge trusts the From: header without checking DKIM, SPF or DMARC; see threat model N-17.

Flow under the operator gate

  1. The agent writes a message to its outbox, as above.
  2. process_one() parks the entry. It asks the gate to create a request for the prepared operation, and the gate answers with the existing request when it already has one for that entry. While the request is pending, and this process has not announced it yet, the bridge writes a notification carrying the request id to {approval_notify}:outbox. The card says which methods the policy accepts and when the request expires.
  3. The notify service posts the card and tells the gate the message id it got (delivery). It does this only for a notification on its own flat stream, never for one on an agent’s stream.
  4. An operator answers with a security key (cowboy-approvals review or decide), or, where the policy allows it, by reacting to or replying to the card. For a reaction or a reply the notify service’s ingest calls OutboxService.resolve_approval(), which passes it to the gate (transport_decision). The gate records it only if the request’s policy accepts that transport, the answering identity maps to one of the policy’s operators, and the request is still pending.
  5. poll_awaiting() reads the request once per loop. On approved it checks that the prepared operation still matches the approved one, claims the request (a request can be claimed once), sends, and reports the outcome to the gate as succeeded or failed. Any other outcome settles as the Outcomes table says.

The Redis plane’s record

approval:{uuid} = {
  status:          pending | approved | rejected
  source:          email | discord | ...
  channel_id:      destination (email address, channel id, ...)
  content_preview: first 200 chars of the message body
  pinned:          the bridge's private preparation notes for this prompt
  created_at:      unix timestamp
  expires_at:      unix timestamp; past it the record reads as expired.
                   `never` for a timeout of -1: the request has no deadline
  approver:        who resolved it (set on resolution)
  external_id:     the prompt message that was answered (set on resolution)
}
pending --+-- approve --> approved --> send
          +-- reject  --> rejected --> drop, notify the agent
          +-- timeout --> expired  --> drop, notify the agent

expired is never written: it is what check_approval answers for a record past expires_at, whatever its status field says, and for a missing record. An expires_at that is missing or unreadable also reads as expired; never does not, and that record waits until it is decided. poll_awaiting deletes the approval hash when it settles the entry.

Outcomes

Each plane’s answer is read into one outcome, and each outcome has one row in pkgs/bridge/outcomes.py that says what becomes of the entry and what the agent is told on its inbox.

OutcomeRedis planeOperator gateThe entryThe agent is told
pendingstatus=pending, inside the windowpendingstays parkednothing yet
approvedstatus=approved, inside the windowapproved, not yet claimedsent (under the gate, claimed first)nothing: it was sent
rejectedstatus=rejected, inside the windowrejectedacknowledgedrejected: the operator declined it; do not resubmit without addressing the reason
expiredpast expires_at, or no recordpast the policy’s windowacknowledgedexpired: rejected automatically; the operator may not be monitoring approvals; resubmit only if it must be done
supersededneverthe bridge’s gate configuration changed, or the key or identity behind the grant was revoked, before it was claimedacknowledgedsuperseded: rejected automatically; resubmit only if it must be done
retiredneveronly the request’s reference outlived retentionacknowledgedexpired: the same as an expired request
interruptedneverthis bridge holds the claim, and an attempt under it may have runrecorded as uncertainit could not be confirmed; inspect before resubmitting
claim usedneverthe claim was already used and its outcome reportedrecorded as uncertainit could not be confirmed; inspect before resubmitting

A refusal reaches the agent as Your request was NOT delivered (<label>). followed by the row’s notice, then a preview of the entry:

  • declined by an operator: “The operator declined it. Nothing ran. Do not resubmit without addressing the reason.”
  • expired or retired: “Rejected automatically: this isn’t available. The operator may not be monitoring approvals. If you must do this, resubmit the tool call.”
  • superseded under the gate: “Rejected automatically: this isn’t available. If you must do this, resubmit the tool call.”

Nothing ran in any of these cases. The automatic rejection is only what the agent is told: the records still read expired and superseded, so an operator or an audit can tell a request nobody answered from one an operator declined.

The outbox’s own supersession is a different case. Once a newer entry for the same operation has been filed, the older one is dropped rather than run, and the agent is told Your request was NOT delivered (superseded). Superseded by <entry>., naming the entry that replaced it.

This bridge holding the claim with every attempt under it ended cleanly (a send the transport refused) reads as approved: it is retried under the same claim, without a second decision.

An answer that arrives after its request was decided, expired, superseded or settled is ignored on both planes. resolve_approval() still reports that the message answered a prompt, so it never reaches the agent as a message either.

Delivery, retry and uncertainty

An entry stays unacknowledged until it is settled. Recovery re-claims one idle for 30 seconds on each pass, once a minute. How the entry is settled depends on how its last attempt ended:

  • The send failed. send() returned an error. Recovery retries the entry up to OUTBOX_MAX_DELIVERIES attempts (five by default). After the last attempt the entry goes to {source}:dead and is acknowledged, and the agent is told on its inbox. Under the approval gate the retries reuse the claim the first attempt took, and a dead-lettered claim is recorded as failed. The Redis plane deletes a decision once it has been read, so each retry is gated again.
  • The send partly succeeded. The email bridge’s SMTP server accepted the message for some recipients and refused the rest. The entry is not retried, because the recipients that accepted it would get it twice. It is acknowledged, the agent is told which recipients were refused, and a gate claim is recorded as failed with the same detail.
  • The attempt may have run. Either the process stopped during the send or the bridge could not confirm completion. The entry is not retried. It is recorded on {stream}:uncertain, the gate request is marked uncertain, and the agent is told the request could not be confirmed.
  • Handling the entry raised an error. The error counts as a failed attempt for that entry only, with the same bounded retries and dead letter. Other entries keep moving.
  • The bridge refused the entry. For example, runas refuses a re-claimed entry once its declared unit has changed. The requester is told why, the entry is acknowledged, and a request or prompt it already had is settled: an unclaimed gate request reads superseded, a claimed one is given its outcome, and the prompt is marked withdrawn.
  • The gate retired the request. The entry is acknowledged, and the agent is told it was rejected automatically, as for an expired request.

Acknowledging an entry does not delete it. At the end of each recovery pass the bridge trims settled entries older than OUTBOX_RETAIN_S seconds (seven days by default) from each outbox stream it reads. The cut never passes the oldest entry any consumer group has pending or not yet read, so an unsettled entry is never trimmed. A refusal recorded against a trimmed entry is forgotten with it.

Redis keys

On the Redis plane:

approval:{uuid}         # HASH — approval state
approval:{source}_map   # HASH — external message id -> approval id

The requesting service writes and polls approval:{uuid}. The notify service owns approval:{source}_map. Bridges share only the key format — Discord and email do not know about each other.

Under the operator gate a bridge holds none of these. The gate keeps its requests, deliveries and decisions under approval-gate:v1:*, which only the cowboy-approvals service can reach. Enabling the gate removes every bridge’s access to the approval:* hashes, so an old record cannot authorize anything.

Implementation

The park-and-poll flow (process_one(), poll_awaiting()), the static resolve_approval(), and the recording of which message carried which prompt all live in the shared OutboxService, for both planes. A per-platform bridge only needs to:

  1. Return SendResult(ok=True, external_id=...) from its send().
  2. Call OutboxService.resolve_approval(pubsub, source, external_id, status, approver) from its ingest handler when a reaction or reply arrives, with status set to approved or rejected. It returns true whenever the message answered a prompt, whether or not the answer was honoured, so the ingest can keep a late answer from reaching the agent as a message.

systemd services

Each bridge {name} runs cowboy-{name}-outbox, plus cowboy-{name}-ingest and cowboy-{name}-ping when its package has those entry points. The rebuild, effects and runas bridges have only an outbox; hermes and howdy have no ingest, because their outbox owns the connection in both directions.

Configuration

Approval is configured per bridge under services.cowboy.bridges.<name>.approval (and equivalently on services.cowboy.pubsub.sources.<name>.approval):

services.cowboy.bridges.discord.approval = {
  required = false;       # hold outbound messages for manual approval
  notify = "discord";     # which outbox to send approval notifications to
  notify_channel = "";    # channel id within that outbox
  timeout = 3600;         # seconds before an unanswered request expires
};

If required is true, notify_channel must be set. Under the operator gate (services.cowboy.approvals), the bridge’s gate policy sets the window and the methods that may answer, and the bridge’s timeout is not read. The rebuild-request and effects-request records report the terms in force: approval.timeout_seconds and approval.via are the policy’s timeout and methods under the gate, and the bridge’s timeout and notify otherwise.

A bridge’s timeout and a gate policy’s (services.cowboy.approvals.policies.<name>.timeout) mean the same thing, and both default to 3600:

  • A positive number is the seconds a request waits for a decision. At that deadline it expires: the entry is acknowledged and the agent is told the request was rejected automatically.
  • -1 means the request never expires. It has no deadline, and waits until an operator decides it or it is superseded, however long that takes. The Redis plane records expires_at as never, the gate records expires as null, a card that would give the deadline says it does not expire, and the request tools report timeout_seconds as null. A parked request holds one of the bridge’s parking slots for as long as it waits. The gate keeps a request with a deadline until seven days after that deadline, and one without until seven days after it first finds it settled (see the gate’s README).
  • 0 means every request expires as it is created, so each one is refused unanswered and nothing is sent.

Anything below -1 fails evaluation, and a bridge or the gate refuses it when it loads a configuration written by hand.

The Redis ACL enforcement option keeps the agent restricted to stream commands so it cannot touch the approval hashes directly.

Two bridges use this protocol for something other than a message. rebuild gates a system rebuild, and effects gates a declared action on the world (a git push, for instance) — see Gated Effects. For effects, approval.required is read-only true: there is no unapproved mode, and the approval is bound to a specific commit sha rather than to the request text, so what the operator approved is what runs, byte for byte.

Adding a new approval channel

To approve via something other than Discord:

  1. Have the new service’s outbox return external_id from send().
  2. Have its ingest call OutboxService.resolve_approval(...).
  3. Set approval.notify = "<service>" on the bridge that needs approval.

Under the operator gate the new service’s answers decide only when the requesting bridge’s policy lists <service> in its methods and services.cowboy.approvals.transportIdentities.<service> maps the answering identity to one of the policy’s operators. Without both, the card is still posted, but an answer left on it decides nothing.

No changes to OutboxService or the requesting service are required.