# ReplyBrain Docs > Customer support that reads your product, drafts the reply, and lets a person approve it. (https://replybrain.com) ## Documentation - [ReplyBrain Documentation](/) - [Email in 15 Minutes](/getting-started-email/) - [Your App in 15 Minutes](/getting-started-your-app/) - [Check It Works](/getting-started-check-it-works/) - [Cases, Conversations and Messages](/concepts-cases-and-conversations/) - [Drafts and Publications](/concepts-drafts-and-publications/) - [Holding Replies and Follow-ups](/concepts-holding-replies-and-follow-ups/) - [Disclosure and Authority](/concepts-disclosure-and-authority/) - [Knowledge: Answers and Playbook](/concepts-knowledge/) - [Facts and Account Scope](/concepts-facts-and-account-scope/) - [The Ticket Holder](/concepts-ticket-holder/) - [Events](/guides-events/) - [Facts](/guides-facts/) - [Capabilities](/guides-capabilities/) - [Mailboxes](/guides-mailboxes/) - [Security](/guides-security/) - [Caveats, Pitfalls and Tips](/guides-caveats-pitfalls-and-tips/) - [MCP server](/guides-mcp/) - [Ruby (replybrain-client)](/sdks-ruby/) - [API Overview](/api-reference-overview/) - [Errors](/api-reference-errors/) - [Idempotency, Revisions and Pagination](/api-reference-conventions/) - [Connection Events](/api-reference-connection-events/) - [Endpoints](/api-reference-endpoints/) --- ## Full Content ## ReplyBrain Documentation ReplyBrain answers your customers with your product's own truth. It takes in your support conversations, reads what your product knows about the customer who wrote, drafts a reply, and proposes it to a person on your team, who approves and sends it. **Drafts only, by default.** Nothing reaches a customer until a person sends it. More autonomy is a decision you make later, channel by channel. ## How it works
  1. A customer writes
  2. One case
  3. Context
  4. A draft
  5. A person sends it
1. **A message arrives.** Mail to your support address, forwarded to a mailbox ReplyBrain manages, or an event your own app posts when a customer writes in its help desk. 2. **It becomes a case.** One case per customer problem, with its conversations and messages. 3. **ReplyBrain gathers context.** Your approved answers and playbook, and, when the case is bound to the customer's account, the facts your app serves about them (their plan, their recent orders, the state of their export…). 4. **It drafts.** A reply that solves the problem when it can; otherwise a fast, personal holding reply, with the follow-up it promises tracked until it is kept. 5. **A person decides.** The draft waits in the ReplyBrain console (mail) or in your own help desk (your app). Your teammate edits, sends, or discards it. ## Where to start | You want to… | Start here | |---|---| | Answer the mail that reaches `support@your-domain` | [[getting-started/email|Email in 15 minutes]] | | Connect your own app's help desk and customer facts | [[getting-started/your-app|Your app in 15 minutes]] | | Confirm the first message flows end to end | [[getting-started/check-it-works|Check it works]] | | Understand cases, drafts, disclosure and facts | [[concepts/cases-and-conversations|Concepts]] | | Know what bites people in their first week | [[guides/caveats-pitfalls-and-tips|Caveats, pitfalls and tips]] | | Call the API | [[api-reference/overview|API overview]] and the [interactive reference](/api/) | > [!NOTE] > Questions, or something here that does not match what you see? Write to [support@replybrain.com](mailto:support@replybrain.com). --- ## Email in 15 Minutes Your customers keep writing to the address they know (say `support@example.com`). Mail to it reaches a mailbox ReplyBrain manages; every thread becomes a case; drafts wait in the ReplyBrain console for a person to send. Replies leave as your address once your domain is verified for sending. ## What you need - The support address, and access to where its mail is handled today (your mail provider's forwarding or routing, or the admin console of a Google Group). - A ReplyBrain organization, and its owner's email. ## Step 1. Ask for the mailbox (2 minutes) Mailboxes are set up by ReplyBrain for you today. Write to [support@replybrain.com](mailto:support@replybrain.com) with: - the support address (`support@example.com`), and any other address the same product receives mail at (`hello@example.com`): those become **aliases** of the one mailbox, so a thread stays one case whichever address it reached; - whether the address is a plain mailbox or alias (**direct**) or a **Google Group**; - the product's name. You get back the mailbox's **ingress address**, one per address, of this form: ``` support=example.com@in.replybrain.com ``` > [!NOTE] > One managed mailbox per product, and one managed product per organization for now. A second product's mail needs its own organization until mail routes by product. ## Step 2. Send the mail to the ingress address (5 minutes) Pick the one that matches how your address works today. **Direct (a mailbox or an alias).** In your mail provider, forward or route every message for `support@example.com` to `support=example.com@in.replybrain.com`. Keep a copy in your own inbox if you like; ReplyBrain does not need it. **A Google Group.** In the Google Workspace admin console: 1. Allow external members for the group (*Groups → the group → Settings → External members*). Without it the ingress address cannot be added. 2. Add `support=example.com@in.replybrain.com` as a **member** of the group, with *Each email* delivery. 3. Tell ReplyBrain it is a Google Group (Step 1). Group mail is then read correctly: the real writer is taken from the group's headers, and posts by your own teammates are recognised as theirs, not as customers'. See [[guides/mailboxes|Mailboxes]] for every detail, including threading. > [!WARNING] > **Wait about two minutes after the mailbox is set up before your first test.** A new route takes a moment to apply everywhere, and a mail sent before it can bounce. ## Step 3. Send replies as your address (5 minutes, optional at first) Until your domain is verified for sending, replies leave from ReplyBrain's own address with `Reply-To: support@example.com`. To send **as** `support@example.com`, add the three DKIM `CNAME` records ReplyBrain gives you to your domain's DNS. SPF changes are optional: DKIM alignment satisfies DMARC. ## Step 4. Decide draft-only for email (1 minute) ReplyBrain drafts only once your organization's owner has decided how the assistant's words are disclosed on the channel. For a draft-only start the decision is `none`: the assistant's words are only ever drafts a person sends, so nothing is disclosed to a customer yet. ReplyBrain records it with the owner's email and checks that the assistant may draft and that the owner may send replies. See [[concepts/disclosure-and-authority|Disclosure and authority]]. ## Step 5. Send a test mail (2 minutes) From an address that is **not** one of your teammates' (a personal address is fine), write to `support@example.com`: ``` Subject: Can't find my invoice Hi, I'm Ada. Where can I download last month's invoice? Thanks! ``` Then follow [[getting-started/check-it-works|Check it works]]. > [!TIP] > Answer from the ReplyBrain console. A reply you send from your own mail client is invisible to ReplyBrain unless you CC the support address on it, so the case would still look unanswered. --- ## Your App in 15 Minutes Your app keeps its own help desk. It tells ReplyBrain when a customer writes (a signed **event**), answers questions about that customer (**facts**), and receives the drafted reply as a **draft** in its own desk, where your teammate sends it. This page uses the Ruby gem `replybrain-client`, mounted in a Rails app. Any stack can implement the same HTTP contract: see [[api-reference/connection-events|Connection events]] and [[guides/capabilities|Capabilities]]. ## Step 1. Ask for the connection (2 minutes) Connections are set up by ReplyBrain for you today. Write to [support@replybrain.com](mailto:support@replybrain.com) with your app's public HTTPS base URL (`https://app.example.com`). You receive four values **once**: | Value | What it is | |---|---| | `connection_id` | Your app's connection. Every signature is bound to it. | | `key_id` and secret (`rbsec_…`) | The secret both sides sign with: ReplyBrain its calls to your app, your app its events. | | API key (`rb_sk_live_…`) | A secret key bounded to this connection, scope `connections.read`. | > [!DANGER] > They are shown once. Put them straight into your encrypted credentials; never in a repository, a log or a chat. ## Step 2. Install the gem (2 minutes) The gem is not on rubygems.org. Today it is vendored: copy the `replybrain-client` source you received into your app, then: ```ruby # Gemfile gem "replybrain-client", path: "vendor/replybrain-client" ``` ```bash bundle install ``` It has no runtime dependencies; Rails is optional but this page assumes it. ## Step 3. Configure and mount (3 minutes) ```ruby # config/initializers/replybrain.rb ReplyBrain::Client.configure do |c| creds = Rails.application.credentials.replybrain c.api_key = creds[:api_key] c.connection_id = creds[:connection_id] c.base_url = "https://replybrain.com/v1" c.signing_secrets = { creds[:key_id] => creds[:secret] } # current first; add the previous one while rotating c.effects = ReplyBrain::Client::Effects::ActiveRecordStore.new c.account_topic = "user" # the facts topic for a customer's whole account c.record_topics = %w[order] # records that topic lists, which a message may be about end ``` ```ruby # config/routes.rb mount ReplyBrain::Client::Engine => "/replybrain" ``` The effects store needs one table: ```ruby create_table :replybrain_effects, id: false do |t| t.string :key, null: false, primary_key: true t.text :value, null: false t.timestamps end ``` ReplyBrain calls your app at `https://app.example.com/replybrain/…`, always a signed `POST`. Anything unsigned is refused with `401`. ## Step 4. Serve facts (2 minutes) Tell ReplyBrain what a customer's account and records look like. Only what your block returns leaves your app. ```ruby class User < ApplicationRecord replybrain_facts(:user, account: :id) do |user| { plan: user.plan_name, plan_status_label: user.plan_status.humanize, # a label people read, not a code orders: { recent: user.orders.recent.limit(5).map { |o| { id: o.id, reference: o.number, status_label: o.status.humanize } } } } end end class Order < ApplicationRecord replybrain_facts(:order, account: :user_id) { |order| { reference: order.number, status_label: order.status.humanize, eta: order.eta } } end ``` `account:` names who owns the record; a request for another account's record answers exactly like a missing one. See [[guides/facts|Facts]]. ## Step 5. Post events (3 minutes) When a message is added to a conversation in your desk (by the customer or by your team), post an event. Do it from a job enqueued after the database commits, never inline: ```ruby class ReplyBrainEventJob < ApplicationJob def perform(message) ticket = message.ticket ReplyBrain::Client.connection.post_event( source_event_id: "message:#{message.id}", source_object: { type: "ticket", id: ticket.reference }, occurred_at: message.created_at.utc.iso8601, kind: "conversation.message_added", message: { id: message.id.to_s, body_text: message.body, visibility: "customer", channel: "in_app", direction: message.from_customer? ? "inbound" : "outbound", author: message.from_customer? ? "requester" : "agent", author_name: (message.author.first_name unless message.from_customer?) }, requester: { ref: "user:#{ticket.user.id}", account_scope: ticket.user.id.to_s, name: ticket.user.first_name, email: ticket.user.email }, assignee: ticket.assignee ? { name: ticket.assignee.name, email: ticket.assignee.email } : {} ) end end ``` > [!WARNING] > Always send `message.channel` and `message.visibility`. Without `channel` the conversation is filed under `api`, and drafts are refused there until a disclosure decision exists for `api`. Without `visibility: "customer"` the message counts as internal and is never answered. See [[guides/events|Events]]. ## Step 6. Receive drafts, and let them be taken back (2 minutes) Two pieces in `app/capabilities/` (the engine loads that folder): ```ruby # app/capabilities/help_desk_source.rb: drafts arrive here class HelpDeskSource < ReplyBrain::Client::Source publish do |message| next refused(:not_draft_only) unless message.draft? # draft-only: never send ticket = Ticket.find_by!(reference: message.conversation_ref.delete_prefix("ticket:")) draft = ticket.drafts.find_or_create_by!(effect_key: message.effect_key) { |d| d.body = message.body } drafted(draft.id) end # A publish that timed out: does a draft exist for this key? state is pending, sent, # withdrawn, rejected, superseded or expired; message_id once a person sent it. lookup do |effect_key| Draft.find_by(effect_key:)&.then { |d| { draft_id: d.id.to_s, state: d.state, message_id: d.message_id&.to_s }.compact } end end ``` ```ruby # app/capabilities/message_withdraw.rb: without it, your app is sent no draft at all class MessageWithdraw < ReplyBrain::Client::Capability manifest "message.withdraw", version: 1, effect: :communication argument :publication_id argument :reason perform do |draft_id: nil, effect_key:| draft = Draft.find_by(id: draft_id) next succeeded(outcome: "not_pending") unless draft next succeeded(outcome: "already_sent", message_id: draft.message_id.to_s) if draft.sent? draft.withdraw!(idempotency_key: effect_key) succeeded(outcome: "withdrawn") end reconcile { |draft_id: nil| Draft.find_by(id: draft_id)&.withdrawn? ? effected(outcome: "withdrawn") : not_effected } verifier do |draft_id: nil| draft = Draft.find_by(id: draft_id) or next pending observe(source: "draft:#{draft.id}", revision: draft.updated_at) { draft.withdrawn? } end end ``` `conversation_ref` is `":"` of your events. The full contract, and the optional `support.open_tickets`, `identity.lookup` and `conversation.close`, are in [[guides/capabilities|Capabilities]]. ## Step 7. Register and go draft-only (1 minute) Deploy, then tell ReplyBrain it can: 1. read your app's **manifest** (your fact topics and capabilities); 2. **register** `message.withdraw` (and any of the optional operations you serve); 3. record the **draft-only** decision for the channel your events carry (`in_app` above): disclosure `none`, the assistant drafts, the owner sends. Then follow [[getting-started/check-it-works|Check it works]]. --- ## Check It Works Send one synthetic message and follow it through. Use made-up customers only (`ada@example.com`, account `acme`), never a real one. ## 1. The message arrived | Channel | What you should see | |---|---| | Email | A new case in the ReplyBrain console inbox within a few seconds, with the mail as its first message. | | Your app | `POST /v1/connections/{id}/events` answered `202` with `"state": "recorded"`. A second post of the same `source_event_id` answers `"state": "duplicate"`. | For your app, read the connection's status with its API key: ```bash curl -s https://replybrain.com/v1/connections/$CONNECTION_ID/status \ -H "Authorization: Bearer $REPLYBRAIN_API_KEY" ``` ```json { "object": "connection_status", "id": "9a8b7c6d-0000-4000-8000-000000000002", "kind": "product_api", "system": "host", "sync": "fresh", "grants": "valid", "credential_expires_at": null, "write": "drafts_only", "operations": { "publish": { "conditional_publish": false, "discloses": false, "enforces_valid_until": false, "revision_tokens": false, "visibility_control": false, "attachments": false, "idempotency_window": 0 } }, "links": { "self": "/v1/connections/9a8b7c6d-0000-4000-8000-000000000002/status" } } ``` `write: drafts_only` is what a draft-only app shows. `grants: expiring` means the connection's credential expires within 14 days; `revoked` means nothing can be signed. ## 2. The case is on the right channel Open the case in the console. Its conversation's channel must be the one you decided draft-only for (`email`, or the `message.channel` your events send, such as `in_app`). > [!WARNING] > A case on channel `api` means your events carry no `message.channel`. Drafts there are refused until a disclosure decision exists for `api`. Fix the events (send `channel`), or decide draft-only for `api` too. ## 3. A draft was placed - **Email:** the draft waits on the case in the console. - **Your app:** your `HelpDeskSource#publish` ran with `mode: "draft"` and answered `drafted(…)`; the draft sits in your own desk. If no draft came, the case says why in the console. The usual causes: | Reason | Fix | |---|---| | No disclosure decision for the channel | Decide draft-only for that channel (`none`). | | `withdraw_unsupported` | Serve `message.withdraw` and have it registered. Until then your app is sent no assistant draft. | | The message is internal | Send `message.visibility: "customer"`. | | A holding reply instead of an answer | Expected when the case needs a person, facts are missing, or research is still running. See [[concepts/holding-replies-and-follow-ups|Holding replies]]. | | Not support (a test, an automated notice) | Expected: no draft for mail that is not a support request. | ## 4. A person sends it Send the draft from where it waits (the console, or your desk). For your app, post the outbound message as an event (`direction: "outbound"`, `author: "agent"`, `author_name`), so the case knows the customer was answered. ## 5. Facts were read (your app) On a case bound to the customer's account, the console shows the facts read from your app. If none were read, check [[concepts/facts-and-account-scope|Facts and account scope]]: the case must be bound to an account before any of that customer's facts are used. --- ## Cases, Conversations and Messages ## Case A **case** is one customer problem. It holds one or more conversations, the customer's needs, what was promised to them, and who on your team holds it. A case belongs to one product of your organization. ## Conversation A **conversation** is where the case is being talked about, on one channel: `email`, `in_app`, `whatsapp`, `sms`, `phone` or `api`. Its channel is fixed when the conversation is first seen. Every conversation is one of two kinds: | Kind | Where it lives | How messages arrive | Where replies go | |---|---|---|---| | **Managed** | ReplyBrain's own desk | Mail to your managed mailbox, or `POST /v1/cases` | Sent from the ReplyBrain console | | **Connected** | Your app's help desk | Signed events from your app | Drafts placed in your desk, sent by your team there | A connected conversation is identified by the `source_object` of your events (`{ type: "ticket", id: "SUP-1042" }`): every event with the same type and id belongs to the same conversation. Your app stays the source of truth for it; ReplyBrain keeps a projection. ## Message A **message** has a direction (`inbound` from the customer, `outbound` from your team), a visibility (`customer` or `internal`), a body, and when it happened. Only customer-visible inbound messages are answered. ## Need A **need** is what the customer wants, written down with the message it came from. Its state moves from `identified` through `planned` and `in_work` to `satisfied`, `declined` or `unknown`; the last three are a person's decision. ## Requester The **requester** is the customer a conversation is with. In mail, the sender. In your app, the `requester` your events name, by your own id for them (`ref`). A signed event proves the event came from your app; it does not prove who the customer is. See [[concepts/facts-and-account-scope|Facts and account scope]]. --- ## Drafts and Publications ## Draft A **draft** is a reply ReplyBrain wrote for a case: its words, its channel, and every claim it makes tied to what backs it (an approved answer, a fact your app served). A draft that states something nothing backs is refused before anyone sees it. ## Publication A **publication** is one attempt to put a draft in front of the customer. It has its own id (`publication_id`) and an `effect_key`, the same on every retry, so a reply is never placed twice. - **Managed (mail).** A person approves the draft in the console and it is sent from your mailbox. - **Connected (your app).** ReplyBrain calls your app's `message.publish` with `mode: "draft"`: your app stores it as a draft in its desk and answers `drafted()`. A person on your team sends it there. `mode: "publish"` (your app sends it at once) is only ever used for an app that declares it can check the conversation's turn and send atomically, and the assistant's own words go that way only to an app that also renders their disclosure. By default, your app only ever receives drafts. ## Taking a draft back A draft can lose its backing after it was placed: the answer it quotes is withdrawn, or the facts it states expire. ReplyBrain then asks your app to take it back through `message.withdraw`. That is why an app that does not serve `message.withdraw` is sent **no** assistant draft at all: the case asks a person in ReplyBrain instead. A teammate's own words are unaffected. ## valid_until A draft that states the customer's own facts holds only as long as those facts. An app that declares it enforces it receives `valid_until` with each such draft and refuses to send it after that time; ReplyBrain also withdraws a draft still unsent at its `valid_until`. An app that does not declare it is sent no draft resting on the customer's facts; drafts that rest only on your approved answers still go. ## Reconciliation When a call to your app times out, ReplyBrain never sends it again blindly. It asks your app's lookup whether a draft or a message exists for that `effect_key`, and records what really happened. --- ## Holding Replies and Follow-ups Solving the problem in one reply is the goal. When that is not possible right now, the customer still hears from you fast. ## Holding reply When a case cannot be solved at once (it needs a person, a fact is missing, research is still running), ReplyBrain drafts a **holding reply**: short, in your product's voice, about their problem in their words. It answers whatever part can be answered now, says you are looking into it and will get back to them, and promises no date and no outcome. It never gives an internal reason ("our AI couldn't verify…"). A holding reply goes through the same checks as any draft and, by default, waits for a person like any draft. No holding reply is drafted for a refund demand, a legal or security threat, abuse or a grave escalation (a person writes the first word), for mail that is not a support request, or when your team already answered after the customer's last message. ## Follow-up Sending a holding reply records the follow-up it promised as an owed **commitment**: who owns it, the sentence that promised it, and a review time. If the review time passes and nobody answered, the case comes back as owed. The commitment is kept by the real answer, never by another acknowledgement, and a case with an open follow-up is never wrapped up. ## Settings, per product | Setting | Default | Meaning | |---|---|---| | Holding replies | on | Draft a holding reply when the case cannot be solved now. | | Hold after | 15 minutes | How long research may run before a holding reply is drafted instead of waiting for the full answer. | | Follow up within | 1 business day | The review time of the follow-up a holding reply promises. | Who owns the follow-up: the teammate who accepted the case, else the person who holds the ticket in your app (see [[concepts/ticket-holder|The ticket holder]]), else the product's escalation owner. --- ## Disclosure and Authority ## Authority levels Everything ReplyBrain may do is capped at a level, per product and per kind of effect: | Level | Means | |---|---| | `observe` | Read only. | | `draft` | Propose: a draft for a person to send, a planned action for a person to approve. | | `reply` | Send replies to the customer. | | `resolve` | Carry out the remedy itself. | The assistant starts at `draft`. A teammate sends replies when their membership allows it (permission to publish replies). Actions with money, identity or deployment effects never go beyond `draft` for the assistant without an explicit grant, and every action a capability registers is approved by a person. ## Disclosure Before the assistant drafts on a channel of a product, your organization's owner decides how its words are disclosed there. The decision is recorded per product and channel: | Decision | What the customer sees | |---|---| | `none` | Nothing, because the assistant's words are only ever **drafts a person sends**. This is the draft-only start. | | `signature` | Each of the assistant's messages is signed as an AI assistant. | | `notice` | A line saying an AI assistant is answering, before its first message in the conversation. Never on email on its own. | | `signature_and_notice` | Both. | On email, any decision other than `none` means the assistant's mails are signed with its disclosed name and carry the header `X-ReplyBrain-AI-Generated: yes`. > [!WARNING] > **No decision, no drafts.** A channel without a disclosure decision gets no assistant draft (the case says "proposal not authorized"). The decision is per channel, so it must be the channel your messages really arrive on. A connected app that sends no `message.channel` lands on `api`, not `in_app`. ## A connected app and disclosure ReplyBrain cannot see how your app renders a message. The assistant's words are sent for your app to deliver itself (`mode: "publish"`) only when your connection declares the disclosure contract, which means your app renders the `disclosure_mode` it receives in the conversation the customer reads (and on email, signs with the disclosed name and adds the header), or refuses with `disclosure_unsupported`. Without that declaration your app only ever receives drafts. ## Moving beyond drafts More autonomy is an explicit decision by your organization's administrator, channel by channel, once a channel has earned it. A low-risk holding reply that promises only a follow-up is the natural first candidate. --- ## Knowledge: Answers and Playbook Facts say what is true about one customer. Knowledge says what is true about your product, and how your team handles a kind of ticket. ## Answers An **answer** is a standalone statement your team approved, written to be quoted: one value with its conditions inside ("Exports usually finish within an hour; very large workspaces can take longer."), with language variants. Answers live in one Answers document per product. A draft may state something about your product only when an approved answer backs it, and every draft records which answers it used. When an answer is withdrawn or replaced, every draft that quoted it is stopped, including drafts already placed in your app (that is what `message.withdraw` is for). > [!TIP] > Write answers in the words a customer reads, never an internal code. "Your export is queued", not "status 3". ## Playbook A **playbook** is your team's insider know-how for a product, written as entries: ```markdown ## Refund requested after the trial key: trial-refund when: plan.status = trial_ended cues: refund, charged, money back ### Know What is really going on with these tickets; never said to the customer. ### Do What the reply and the team do. ### Never What the reply never says and the team never does. ### Say The team's approved words for these tickets, one per line. ``` An entry with `when` conditions applies when they hold on the customer's account facts; one without applies when one of its `cues` is in the message. `Know` guides the drafting and the plan but never reaches the reply. An entry may also `forbid` capabilities: they are never proposed while it applies. When the playbook changes, open cases are thought over again. ## Reference documents Help pages and docs are searchable by your team on the case page, and are where new answers come from. They do not back a claim in a draft by themselves: a person promotes a passage into an answer. --- ## Facts and Account Scope **Facts** are what your app says about one customer and their records, read live when a draft is written: their plan, their recent orders, the state of an export. Your app serves them from its own models; only what your serializer returns ever leaves it. ## account_scope Every fact request carries an `account_scope`: your app's own id for the customer's account. Your app answers only for records that account owns, and a record of another account answers exactly like a missing one (`404 not_found`), so nothing leaks, not even that it exists. The `account_scope` always comes from ReplyBrain's own records (a verified binding, or the key's bounds), never from what a customer or a caller typed. In the API, you name an account by its ReplyBrain `account_id`; `account_ref` and an `account_scope` inside a resource reference are refused. ## Binding a case to an account A signed event proves where it came from, not who the customer is. So a case reads a customer's facts only once it is **bound** to their account, by one of: - **A verified session.** Your app adds `requester.session` to an inbound message event when its server verified the customer's signed-in session as they posted it. - **A signed-in desk.** ReplyBrain is told your in-app desk accepts messages only from signed-in customers, so every in-app message binds its case. - **A confirmed identity (mail).** Your app's `identity.lookup` names which customer holds the sender's address; a teammate confirms it per case. Two accounts on one case are a person's to tell apart; nothing is guessed. ## Topics Your app declares an **account topic** (default `user`) and **record topics** (`order`, `invoice`, …). For a draft, ReplyBrain reads the account topic with the `account_scope` as its id, then up to three records the customer's message cites, found in the account's lists: the items of a `recent` list under a key naming the topic (`orders: { recent: [...] }` → `order`), or of a `_candidates` list. Each listed item has an `id`, and may have a `reference` (the number customers see). ## Freshness Every answer carries your app's `observed_at`. A fact holds for one hour from it, and is read again right before a draft is placed: a changed value or no answer stops the draft (`stale_facts`), and a new one is written. See [[guides/facts|the facts guide]] for the code. --- ## The Ticket Holder Your app's help desk knows who holds each ticket. Every event can say so with `assignee`: ```json "assignee": { "name": "Grace", "email": "grace@example.com" } ``` - `{ "name", "email" }`: who holds the ticket **now**, a teammate, never a customer. - `{}`: nobody holds it. - No `assignee` key: the event says nothing about it, and the holder stays as it was. ReplyBrain keeps the holder on the conversation as the newest event said it (an older event never overwrites a newer one). The inbox row shows "Assigned to Grace", and the case says who holds it in your product. When the holder is a member of your ReplyBrain organization, the follow-ups a holding reply promises go to them, and the reminder of drafts waiting is mailed to them for their own tickets. A holder who is not a member is shown by name, and their follow-ups go to the product's escalation owner. Add them as a member if they answer support. > [!TIP] > Send `assignee` on **every** event, including `{}` when nobody holds the ticket, and send a `conversation.assigned` event when the holder changes without a message. To bring existing open tickets up to date, post one such event per open ticket with a fresh `source_event_id`. --- ## Events Your app tells ReplyBrain what happens in its help desk by posting **events** to `POST https://replybrain.com/v1/connections/{connection_id}/events`, signed with the connection's secret (see [[api-reference/connection-events|Connection events]] for the signature). With the gem: ```ruby ReplyBrain::Client.connection.post_event(event_hash) # signed for you ``` ## A complete event ```json { "source_event_id": "message:88", "source_object": { "type": "ticket", "id": "SUP-1042" }, "source_revision": "14", "occurred_at": "2026-11-12T09:30:00Z", "kind": "conversation.message_added", "message": { "id": "88", "visibility": "customer", "direction": "inbound", "channel": "in_app", "author": "requester", "body_text": "My export has been stuck since this morning." }, "requester": { "ref": "user:42", "account_scope": "42", "name": "Ada", "email": "ada@example.com", "avatar_url": "https://example.com/avatars/42.jpg" }, "assignee": {} } ``` ## Fields | Field | Required | Meaning | |---|---|---| | `source_event_id` | yes (or `source_revision`) | Unique per event. The deduplication key. | | `source_object` | yes | `{ type, id }` of the conversation. Every event with the same pair is the same conversation. | | `source_revision` | no | Your revision of the conversation. Without `source_event_id`, the identity is `type:id:revision:kind`. | | `occurred_at` | yes | ISO 8601, when it happened in your app. | | `kind` | yes | `conversation.message_added`, `conversation.opened`, `conversation.reopened`, `conversation.closed`, `conversation.assigned`. | | `message.id` | recommended | Your id for the message (else `source_event_id` is used). | | `message.visibility` | **yes, in practice** | `customer` or `internal`. **Missing means internal**, and internal messages are never answered. | | `message.direction` | no | `inbound` (default) or `outbound`. | | `message.channel` | **yes, in practice** | `email`, `in_app`, `whatsapp`, `sms`, `phone` or `api`. Fixed when the conversation is first seen. Missing (or unknown) means `api`. | | `message.body_text` | yes for a message | Plain text. | | `message.author` | no | `requester` or `agent`. | | `message.author_name` | no | On an outbound `agent` message, the teammate's name as the customer reads it (up to 60 characters). The console's thread shows it as who sent that reply. | | `message.author_email` | no | On an outbound `agent` message, the address that teammate signs in with. When it is a member of your ReplyBrain team's, the reply is that member's: the thread shows their name and avatar there. Anyone else's is ignored. | | `requester.ref` | yes for a requester | Your stable id for the customer. Without it, the rest of `requester` is ignored. | | `requester.account_scope` | no | Your id for their account: what facts requests carry back. | | `requester.name`, `email`, `phone` | no | Your word about them. An email is kept unverified and is never written to; a phone is used only in E.164 (`+34600000000`). | | `requester.avatar_url` | no | Where you keep their picture: an `https` address, up to 2,048 characters. The console draws it beside their name; ReplyBrain stores the address, never the image, and the AI agent never reads it. Kept as you said it last: an event without it removes the picture. | | `requester.session` | no | `{ verified: true, method, provenance, verified_at, expires_at }`, only on an inbound message your server verified the signed-in customer posted. Binds the case to the account. | | `assignee` | no | `{ name, email }` of the teammate holding the ticket, `{}` for nobody. See [[concepts/ticket-holder|The ticket holder]]. | | `caused_by_action_id` | no | When the event echoes ReplyBrain's own work: the `publication_id` (or action id) it sent you. | Bodies over 256 KB are refused. A body without `source_object`, `kind` or a valid `occurred_at`, or without any identity, is `400` and nothing is recorded. ## Idempotency: one event, once Events are recorded once per (connection, `source_event_id`). Posting the same id again answers `202` with `"state": "duplicate"` and **changes nothing**, even if the body is different. > [!WARNING] > To correct something you already sent (a wrong channel, a missing assignee), post a **new** event with a **new** `source_event_id`. Re-posting the old id with a fixed body is silently ignored. And a conversation's channel is fixed when it is first seen: a later event cannot move it. Use ids derived from your own records (`message:88`, `assigned:SUP-1042:2026-11-12T09:31:00Z`), so a retry after a timeout sends the same id and is harmless. ## Ordering Post from a job enqueued **after** your transaction commits, one per event, and retry it on failure. Events may arrive out of order: open/closed status and the holder follow `occurred_at`, so an older event never overwrites what a newer one said. A backstop sweep that re-posts recent events (same ids) repairs anything a crashed job missed. ## What an event triggers - Every event updates the conversation's open/closed status (from its `kind`) and its holder (from `assignee`). - A `customer`-visible message is linked to its case. - A new **inbound** message is taken in: it may be drafted, routed to a person, or both. Outbound messages, your echoes of ReplyBrain's own drafts and backfilled history are recorded and nothing more. ## Backfill If your app defines `backfill` on its source, ReplyBrain can replay history after a cursor: `POST /replybrain/events/backfill` with `{ "after": "" }`, answered with `{ "events": [ ... ] }`, each event body with its own `cursor`. Backfilled events are recorded with no effect: no drafts, no needs. ```ruby class HelpDeskSource < ReplyBrain::Client::Source backfill do |after| HelpDeskEvent.after(after).limit(100).map { |e| e.to_replybrain.merge(cursor: e.id.to_s) } end end ``` --- ## Facts Facts are served by your app at `POST /replybrain/facts/`, signed by ReplyBrain. Read [[concepts/facts-and-account-scope|Facts and account scope]] first for when they are read. ## The request and the answer ```json { "ref": { "type": "order", "id": "4521", "account_scope": "42" }, "purpose": "support", "query": { "around": "2026-11-12T09:30:00Z" } } ``` ```json { "facts": { "reference": "A-4521", "status_label": "Shipped", "eta": "2026-11-14" }, "revision": "2026-11-12T08:01:13.000000Z", "observed_at": "2026-11-12T09:30:02.114000Z", "ref": { "type": "order", "id": "4521" } } ``` | Answer | Meaning | |---|---| | `200` with `facts` and `observed_at` | Read. Both are required; without them the answer is unreadable. | | `404` `not_found` | You serve the topic, but the record is not there, or not this account's. | | `404` `unsupported` (or `405`, `501`) | You serve no such topic. | The gem answers all of this for you. ## The account topic The account topic (default `user`) is read with the `account_scope` as its id, so declare it on the model whose id **is** your account scope: ```ruby class User < ApplicationRecord replybrain_facts(:user, account: :id) do |user, _account_scope, query| around = query["around"]&.then { Time.iso8601(_1) } { name: user.first_name, plan_label: user.plan.display_name, exports: { recent: user.exports.near(around).limit(5).map { |e| { id: e.id, reference: e.number, state_label: e.state.humanize } } } } end end ``` `query["around"]` is when the customer wrote, so a list can hold the records of those days (the order they mention from last month), not only the newest. ## Record topics Records the customer's message may be about: declare them in `c.record_topics` and serve each one. ReplyBrain finds them in the account topic's lists, `: { recent: [...] }` or `_candidates: [...]`, each item with an `id` and optionally the `reference` customers quote. It reads up to three cited records per draft. ```ruby class Export < ApplicationRecord replybrain_facts(:export, account: :user_id) do |export| { reference: export.number, state_label: export.state.humanize, finished_at: export.finished_at } end end # Not an Active Record model: ReplyBrain::Client.facts(:shipment, find: ->(id) { Shipments.lookup(id) }, account: :customer_id) { |s| { carrier: s.carrier } } ``` ## Rules that keep drafts right > [!WARNING] > **Declare `account:` on every topic.** Without it, every account-scoped request answers `not_found`: the gem fails closed. With it, a record of another account answers exactly like a missing one. > [!TIP] > **Labels, not codes.** A draft repeats what your facts say. Send `status_label: "Waiting for payment"` beside (or instead of) `status: 3`; a customer must never read an internal code. > [!TIP] > **Keep it minimal.** Return what a support reply needs, nothing else: no password hashes, tokens, full card numbers, internal notes or other customers' data. Everything you return may be quoted to this customer. - Each answer holds for one hour from its `observed_at`, and is read again right before a draft is placed. Make the read fast: all of a draft's reads share a budget of about ten seconds. - `revision` is the record's `updated_at`; a change between the first read and the placement stops the draft and a new one is written. - Every topic listed in the manifest must be served, or the manifest is refused. --- ## Capabilities Every call ReplyBrain makes to your app is a signed `POST` under your mount (`/replybrain`). The gem routes them; this page lists what each one is sent and must answer. | Operation | Path | Required? | |---|---|---| | `message.publish` | `capabilities/message.publish` | Yes, to receive drafts. | | `message.withdraw` | `capabilities/message.withdraw` | **Yes**: without it your app is sent no assistant draft. | | `support.open_tickets` | `capabilities/support.open_tickets` | No. Lists open tickets, so a backlog can be drafted. | | `identity.lookup` | `capabilities/identity.lookup` | No. Says which customer wrote a mail. | | `conversation.close` | `capabilities/conversation.close` | No. Without it a case of your app is never wrapped up by ReplyBrain. | | facts | `facts/` | For drafts that use the customer's facts. See [[guides/facts|Facts]]. | | manifest | `manifest` | Served by the engine. | Except `message.publish` and facts, each operation is used only after ReplyBrain **registers** it for your connection: tell us which ones you serve. ## message.publish Defined with a `ReplyBrain::Client::Source` subclass. Sent (with `Idempotency-Key: `): ```json { "capability": "message.publish", "version": 1, "publication_id": "c0ffee00-0000-4000-8000-000000000003", "effect_key": "publish:c0ffee00", "mode": "draft", "arguments": { "body": "Hi Ada, your export finished at 10:02; you can download it from Settings → Exports.", "channel": "in_app", "conversation_ref": "ticket:SUP-1042", "recipients": [], "expected_source_revision": null, "origin": "assistant", "disclosure_mode": "none", "approval_id": null, "policy_id": null } } ``` Answer `drafted()`, `accepted(message_id: …)` (sent; only in `publish` mode) or `refused()`. A `valid_until` argument comes only if your connection declared it enforces it: store it, and refuse to send the draft after it. `origin` is `assistant` or `member` (a teammate's words, `disclosure_mode` null). The gem's `Source::Message` exposes `body`, `recipients`, `channel`, `conversation_ref`, `expected_source_revision`, `disclosure_mode`, `approval_id`, `policy_id`, `publication_id`, `effect_key`, `mode`, `draft?` and `publish?`. For `origin` or `valid_until`, read the raw arguments: `payload["arguments"]["valid_until"]`. Its `lookup` (at `capabilities/message.publish/reconcile`) answers whether something exists for an `effect_key`: a Hash (`{ draft_id:, state:, message_id: }`) or `nil`. `state` is one of `pending`, `sent`, `withdrawn`, `rejected`, `superseded`, `expired`; `sent` counts only with its `message_id`. ## message.withdraw ```json { "capability": "message.withdraw", "version": 1, "effect_key": "withdraw:c0ffee00", "arguments": { "publication_id": "c0ffee00-0000-4000-8000-000000000003", "draft_id": "981", "reason": "evidence_withdrawn" } } ``` `draft_id` is the id you answered `drafted` with (absent if the withdrawal arrives before the draft). `reason` is a code such as `evidence_withdrawn`, `evidence_superseded`, `grant_revoked`. Answer `succeeded(outcome: …)`: | `outcome` | When | |---|---| | `withdrawn` | The draft was removed. | | `prevented` | No draft yet: remember the publication so its later placement is refused. | | `not_pending` | Nothing left to take back. | | `already_sent` | A person sent it first; add `message_id`. A person is then asked to correct what the customer was told. | Take the same lock a person's send takes, so a withdrawal and a send never both win. A `failed(…)` answer or a 4xx (other than 408, 425, 429) is treated as a bug and never retried. See [[getting-started/your-app|the quickstart]] for a full class. ## support.open_tickets Read-only (`effect :read`), always answered fresh: ```ruby class SupportOpenTickets < ReplyBrain::Client::Capability manifest "support.open_tickets", version: 1, effect: :read perform do tickets = Ticket.open.order(:created_at).limit(500).map do |t| { conversation_ref: "ticket:#{t.reference}", latest_message_id: t.messages.last&.id&.to_s, opened_at: t.created_at.utc.iso8601, awaiting: t.awaiting, requester: { ref: "user:#{t.user_id}", account_scope: t.user_id.to_s } } end succeeded(tickets:, truncated: Ticket.open.count > 500) end end ``` `conversation_ref` must be exactly `":"` of your events. ## identity.lookup Read-only. Sent `{ "arguments": { "email": "ada@example.com", "phones": ["+34600000000"], "name": "Ada" } }` (`phones` and `name` only when the mail mentions them). Answer the one customer who holds that confirmed address, or nobody: ```ruby class IdentityLookup < ReplyBrain::Client::Capability manifest "identity.lookup", version: 1, effect: :read argument :email perform do |email:| next failed("invalid_email") unless email.to_s.include?("@") user = User.where(email: email.downcase).where.not(confirmed_at: nil).first user ? succeeded(ref: "user:#{user.id}", account_scope: user.id.to_s, name: user.first_name, matched_by: "email") : succeeded(ref: nil, account_scope: nil) end end ``` `ref` must be the same `requester.ref` your events use. The answer is a candidate a teammate confirms, never proof. ## conversation.close Sent `{ "arguments": { "conversation_ref", "expected_last_message_id", "closing_publication_id", "silent": "true" | "false" } }`. Close only if the conversation's last message is still `expected_last_message_id` (under the same lock an inbound reply takes), and answer `succeeded(outcome: "closed")`, or `failed("")`. ## Your own actions Anything else your app can do for a customer (extend a trial, resend an invoice) is a capability ReplyBrain may propose in a plan, for a person to approve. Describe it so it is proposed at the right time: ```ruby class ExtendTrial < ReplyBrain::Client::Capability manifest "trial.extend", version: 1, effect: :billing describe "Extend a customer's trial by a few days", use_when: "the customer could not try the product during the trial for a reason on our side", never_when: "the trial was already extended", risk: :low, outcome: { en: "I've extended your trial by %{days} days." } argument :user, resource: :user argument :days, type: :integer, description: "How many days" perform { |user:, days:, effect_key:| Trials.extend!(user, days:, idempotency_key: effect_key) ? succeeded : failed("not_eligible") } reconcile { |user:, effect_key:| Trials.extension(user, key: effect_key) ? effected : not_effected } verifier do |user:, effect_key:| ext = Trials.extension(user, key: effect_key) or next pending observe(source: "trial_extension:#{ext.id}", revision: ext.updated_at) { ext.applied? } end end ``` > [!WARNING] > A capability that changes something must declare `reconcile` and `verifier`, or it does not load. `perform` must pass `effect_key` to your own idempotency, and must check again that the action is still allowed when it runs: an approval may be hours old. Changing a capability's arguments or effect needs a new `version`; then ask for your manifest to be read again. --- ## Mailboxes A managed mailbox answers the mail sent to your support address. Each address gets an **ingress address** that ReplyBrain receives at: ``` support@example.com -> support=example.com@in.replybrain.com hello@example.com -> hello=example.com@in.replybrain.com (an alias) ``` ## Direct Your address is a mailbox or an alias at your mail provider. Forward or route all of its mail to the ingress address. That is all: the sender of each mail is its writer. ## Google Group Your address is a Google Workspace group delivering to your team. Keep it: add the ingress address as one more member. 1. In the Admin console, allow **external members** for the group. Without this, the ingress address cannot be added. 2. Add `support=example.com@in.replybrain.com` as a member, delivery *Each email*. 3. Tell ReplyBrain the mailbox is a Google Group, so the group's own headers are read: the writer is the original sender, not the group, even when Google rewrites the From to "Ada via Support". Google sends the new member a "you have been added" notice; it is recognised as automatic and opens no case. ### Your teammates' own mail to the group On a group mailbox, a post by a teammate who is a ReplyBrain member allowed to answer support is their reply on the customer's thread (or their outreach to a customer), never a customer's message, and is never mailed again. It counts as theirs only when the group's signature chain proves it. Anything less (forged headers, mail straight to the ingress address) becomes an internal note on the case, and a person is asked. Make every team address that writes to the group a member with permission to answer support. ## Threading Replies carry a `Reply-To` with a signed thread token (`support+@example.com`), so the customer's answer lands on the same case. Some providers, Google Groups among them, refuse unknown `+suffixes`. > [!WARNING] > Before going live on a Google Group, send one mail to `support+test@example.com`. If it does not reach the group's members, ask for reply tokens to be **off** for the mailbox: replies then carry your plain address and thread by their `Message-ID`s. ## Sending as your address Replies approved in the console leave **as** `support@example.com` once your domain is verified for sending: add the three DKIM `CNAME` records you are given. Until then they leave from ReplyBrain's address with `Reply-To` your address. Every reply is also copied (BCC) to your support address, so your team sees both sides in its own mail. ## Replies sent from your own mail client > [!WARNING] > A reply a teammate sends from Gmail or another client is invisible to ReplyBrain: the case still looks unanswered and may be drafted again. Reply from the console. If you must reply from your client on a Google Group mailbox, CC the support address, so the copy reaches the case as your reply. ## Attachments Text-bearing attachments of a mail are read and given to the draft: plain text, Markdown, PDF and `.docx`, up to three files of 2 MB each. Images (a screenshot) are read too. Other files are named on the case but not read. ## Aliases Every other address the same product receives mail at is an **alias** of its one mailbox, with its own ingress address. A thread stays one case whichever address it reached, and replies leave from the mailbox's own address. ## Before the first real mail - Wait about two minutes after a new mailbox or alias is set up before you send to it: a mail sent earlier can bounce. - Send the first test from an address that is not a teammate's. - Check the case lands on channel `email`, and that the draft-only decision exists for `email`. --- ## Security ## Signatures, both ways One secret per connection signs everything between ReplyBrain and your app: every call ReplyBrain makes to your mount, and every event your app posts. Scheme `v2`: ``` ReplyBrain-Signature: t=,v2= ReplyBrain-Key-Id: key_1 signed string = "v2\n" + t + "\n" + METHOD + "\n" + path + "\n" + connection_id + "\n" + raw body ``` - `METHOD` is upper case (`POST`). `path` is the absolute request path as sent, your mount included (`/replybrain/capabilities/message.withdraw`, `/v1/connections//events`), with `?query` when there is one. - The `connection_id` is the audience: a request signed for one connection verifies on no other, and a request signed for one path (a `verify`) cannot be replayed on another (a `perform`). - A signature older or newer than **five minutes** is refused: keep your server's clock in sync. - Old `v1` signatures (timestamp and body only) are refused. The gem signs and verifies for you (`ReplyBrain::Client::Signature.sign` / `.verify!` for anything by hand). See [[api-reference/connection-events|Connection events]] for a worked example. ## Rotating the secret with two keys A connection holds its current key and, during a rotation, the previous one; both verify, the current one signs. 1. You receive a new key (`key_2`) and its secret. 2. Deploy your app with **both**, the new one first: ```ruby c.signing_secrets = { "key_2" => creds[:secret_2], "key_1" => creds[:secret_1] } ``` The first key signs your events; both verify ReplyBrain's calls. 3. ReplyBrain starts signing with `key_2`. 4. Once nothing signed with `key_1` is in flight (more than five minutes later), the old key is retired: remove it from your credentials and deploy. A credential may carry an expiry; the connection's status reports `grants: expiring` within 14 days of it, and `revoked` once nothing can be signed. ## API keys `/v1` takes organization-owned **secret** keys only (`rb_sk_live_…`), as `Authorization: Bearer`. Browser sessions and other key types are refused. - **Scopes** per resource family: `cases.read`, `cases.write`, … A write needs `.write`. Actions with money, identity, deployment or work-tracker effects also need `actions.`. - **Bounds**: a key may be limited to some products, connections, accounts or cases. Everything outside answers `404`, as if it did not exist. - A decision made with a key (approving an action, deciding a need) is recorded as the decision of the member who created it. If that person leaves the organization, the key stops working. - Your app's own key is bounded to its connection with `connections.read`; its events need no key at all. Keep secret keys on servers only, never in a browser or a mobile app. ## What leaves your app Only what you choose to send: - **Events**: the message text, its direction and channel, and the `requester` and `assignee` fields you fill in. - **Facts**: exactly what your serializers return, only for the account in scope. - **Capability answers**: the refs you return. > [!TIP] > Send the minimum a support reply needs. Prefer your own opaque ids for `ref` and `account_scope`, send labels people read instead of internal codes, and leave out anything you would not show the customer: tokens, password hashes, full payment details, internal notes, other customers' data. An email or name in `requester` is kept as your word about the customer, never treated as proof of who they are, and ReplyBrain never writes to an address it learned that way: a connected case's replies go back through your app. --- ## Caveats, Pitfalls and Tips Every item here happened to someone. Each one says what you see, and what to do. ## Your app's events > [!WARNING] > **No `message.channel`: drafts refused.** A conversation whose events carry no `channel` is filed under `api`. Drafts are refused there ("proposal not authorized") until a disclosure decision exists for `api`, even though you decided draft-only for `in_app`. Send `"channel": "in_app"` from the first event. For conversations already on `api`, decide draft-only for `api` too: a conversation's channel never changes. > [!WARNING] > **No `message.visibility`: never answered.** A message without `visibility` counts as internal. Send `"visibility": "customer"` on every message the customer sees. > [!WARNING] > **Re-posting an event changes nothing.** Events are deduplicated by `source_event_id`: the same id again answers `duplicate`, whatever the body says. To correct state (a holder, a status), post a new event with a new id. > [!TIP] > **Say who holds the ticket, every time.** Send `assignee` (`{ name, email }`, or `{}` for nobody) on every event, so follow-ups and reminders reach the right teammate. See [[concepts/ticket-holder|The ticket holder]]. > [!TIP] > **Name your teammates.** On outbound messages send `author: "agent"` and `author_name`, so the case shows who answered. > [!TIP] > **Post after commit.** Enqueue the event job after your transaction commits; a job that runs first may post an event about a row that rolls back. ## Drafts into your app > [!WARNING] > **No `message.withdraw`, no drafts.** Until your app serves `message.withdraw` **and** it is registered, ReplyBrain sends it no assistant draft at all; the case asks a person instead. > [!NOTE] > **`valid_until`.** Drafts that state the customer's own facts reach your app only if it declared it enforces `valid_until`, refusing to send a draft after it. Drafts resting only on approved answers are unaffected. > [!NOTE] > **In-app attachments are not read yet.** Files a customer attaches in your app's desk do not reach ReplyBrain. Mail attachments are read (text, Markdown, PDF, `.docx`, images). ## Facts > [!WARNING] > **No `account:`, no facts.** A topic served without `account:` answers every account-scoped request `not_found`. > [!TIP] > **Labels, not codes.** A draft says what your facts say. Serve `status_label: "Refund sent"` so no customer ever reads `status: 7`. > [!NOTE] > **No binding, no facts.** A case uses a customer's facts only once it is bound to their account: a verified session in the event, a desk that only takes signed-in customers, or an identity a teammate confirmed. Until then drafts use your approved answers only. ## Mailboxes > [!WARNING] > **Wait two minutes.** After a new mailbox or alias is set up, wait about two minutes before the first test mail. A mail sent earlier can bounce. > [!WARNING] > **Google Groups.** Allow external members, then add the ingress address as a member. Test a `+suffix` address before going live; if the group refuses it, ask for reply tokens to be turned off. > [!WARNING] > **Replies from Gmail are invisible.** A reply sent from your own mail client never reaches the case unless the support address is CC'd. Reply from the console. > [!TIP] > **Test from a stranger's address.** On a group mailbox your teammates' own mail is read as theirs, not a customer's. Send tests from an address that is not a teammate's. ## Signatures and keys > [!WARNING] > **Clock drift fails signatures.** A signature outside five minutes is refused (`401`). Keep NTP on. > [!WARNING] > **Sign the exact bytes and path.** Sign the raw body you send (not a re-serialized copy) and the path as sent, mount prefix included, plus any query string. > [!TIP] > **Rotate with two keys.** Deploy the new and the old secret together, new first; retire the old one only after the switch. See [[guides/security|Security]]. ## The API > [!TIP] > **Reuse the `Idempotency-Key` on retries.** A new key is a new command. A `5xx` or a timeout after a write means the effect may have happened: read the resource, or reconcile, before sending again. > [!NOTE] > **`202` is not done.** It means recorded. Poll the `Location` or read the event stream. > [!NOTE] > **Context queries take `account_id`.** Name the account by its ReplyBrain id; `account_ref` and `account_scope` in a reference are refused (`400`). --- ## MCP server ReplyBrain's MCP server lets your AI agent set up ReplyBrain with you: it reads these docs, checks what your organization has set up, and does each step after you say yes. No tool ever sends a message to a customer. Endpoint (Streamable HTTP): `https://replybrain.com/mcp` ## Connect - **Claude Code**: `claude mcp add --transport http replybrain https://replybrain.com/mcp`, then `/mcp` to sign in. - **Claude (web and desktop)**: Settings → Connectors → Add custom connector, paste the endpoint, sign in. - **Cursor**: add `{"mcpServers": {"replybrain": {"url": "https://replybrain.com/mcp"}}}` to `.cursor/mcp.json`, approve the sign-in. - **ChatGPT**: turn on developer mode, then Settings → Apps & Connectors → Create; paste the endpoint, choose OAuth, sign in. The first time, you sign in to ReplyBrain and choose **one** of your organizations. Revoke a client any time in Settings → Connected apps. ## What it can do Start with "What's left to set up?". The agent calls `get_setup_status` and walks the checklist: create the product, connect your support mailbox (with the forwarding or Google Group steps), decide drafts only per channel, import your approved answers and your playbook, set the reply voice, register what your app serves, and send a test message to watch the assistant draft. | Tool | Who | |---|---| | `get_setup_status`, `list_cases`, `get_case`, `search_docs`, `get_doc`, `get_openapi` | any member | | `create_product`, `set_voice`, `import_answers`, `import_playbook`, `connect_mailbox`, `decide_draft_only`, `register_capability`, `discover`, `send_test_message` | owners and admins | ## Access and limits - Every tool runs as you, in the organization you chose, with your permissions there. - Cases are shown by id, state, channel and counts: never what anyone wrote, nor who the customer is. - No tool returns a credential. Connecting your own app's host is done with ReplyBrain's team. - 60 tool calls a minute and 2,000 a day per connected client. - Access tokens last an hour and refresh on their own; revoking in Settings ends access at once. --- ## Ruby (replybrain-client) `replybrain-client` is the host side of ReplyBrain for Ruby apps. It serves what ReplyBrain calls (facts, capabilities, your help desk as a source), signs and verifies every request, and wraps the whole `/v1` API with automatic idempotency keys, `If-Match`, pagination and typed errors. It needs Ruby 3.3 or later and has no runtime dependencies; Rails is optional. ## Installation The gem is not published on rubygems.org. Today it is **vendored**: copy the source you received into your app and point Bundler at it. ```ruby # Gemfile gem "replybrain-client", path: "vendor/replybrain-client" ``` Bundler requires it; outside Bundler, `require "replybrain/client"`. ## Configuration ```ruby # config/initializers/replybrain.rb ReplyBrain::Client.configure do |c| c.api_key = ENV["REPLYBRAIN_API_KEY"] # an organization secret key, rb_sk_live_… c.base_url = "https://replybrain.com/v1" # with /v1 c.connection_id = ENV["REPLYBRAIN_CONNECTION_ID"] # the audience of every signature; required to serve c.signing_secrets = { "key_1" => ENV["REPLYBRAIN_SECRET"] } # current first; both verify while rotating c.effects = ReplyBrain::Client::Effects::ActiveRecordStore.new # default MemoryStore: development only c.account_topic = "user" # default "user" c.record_topics = %w[order] # default [] c.currency = "USD" # for money arguments sent without one c.max_retries = 2 # with the same Idempotency-Key c.open_timeout = 5 c.read_timeout = 30 end ``` | Setting | Default | Notes | |---|---|---| | `api_key` | `ENV["REPLYBRAIN_API_KEY"]` | For `/v1` calls. | | `base_url` | `ENV["REPLYBRAIN_BASE_URL"]` | **Set it** to `https://replybrain.com/v1`. | | `connection_id` | `ENV["REPLYBRAIN_CONNECTION_ID"]` | Without it the engine serves nothing. | | `signing_secrets` | `{}` | `{ key_id => secret }`, current first. Without it the engine answers `503`. | | `effects` | `MemoryStore` | Use `ActiveRecordStore` in production (one table, below). `Rails.cache` stores are refused. | | `account_topic`, `record_topics` | `"user"`, `[]` | Published in the manifest; every listed topic must be served. | ## Mounting ```ruby # config/routes.rb mount ReplyBrain::Client::Engine => "/replybrain" ``` The engine loads `app/capabilities/` (also in development) and refuses to boot with an effectful capability that cannot be reconciled or verified. Outside Rails, `run ReplyBrain::Client.app` is a plain Rack app. ## Facts ```ruby class User < ApplicationRecord replybrain_facts(:user, account: :id) { |user| { name: user.first_name, plan_label: user.plan.display_name } } end class Order < ApplicationRecord replybrain_facts(:order, account: :user_id) { |order, account_scope, query| { reference: order.number, status_label: order.status.humanize } } end ReplyBrain::Client.facts(:shipment, find: ->(id) { Shipments.lookup(id) }, account: :customer_id) { |s| { carrier: s.carrier } } ``` The block may take one to three arguments: the record, the `account_scope`, and the `query` (`{ "around" => "" }`). `account:` is a method name or a lambda. Without a block, the model's `support_context` is served. See [[guides/facts|Facts]]. ## Capabilities ```ruby class ResendInvoice < ReplyBrain::Client::Capability manifest "invoice.resend", version: 1, effect: :communication # served at capabilities/invoice.resend describe "Email an invoice to the account's billing address again", risk: :low argument :invoice, resource: :invoice # "981" arrives, the record is handed to you perform { |invoice:, effect_key:| Mailer.resend(invoice, idempotency_key: effect_key) && succeeded(sent_to: invoice.billing_email) } reconcile { |invoice:, effect_key:| Mailer.sent?(invoice, key: effect_key) ? effected : not_effected } cancel { |invoice:, effect_key:| Mailer.cancel(invoice, key: effect_key) ? cancelled : already_effected } verifier do |invoice:, effect_key:| delivery = Mailer.delivery(invoice, key: effect_key) or next pending observe(source: "delivery:#{delivery.id}", revision: delivery.updated_at) { delivery.delivered? } end end ``` | Piece | Answers | |---|---| | `perform` | `succeeded(**refs)` (or a Hash), `failed("reason")` (or `false`), `accepted(**refs)` for work still running. An exception is a `500`: the effect may have happened. | | `reconcile` | `effected(**refs)` (or a Hash), `not_effected` (or `nil`), `unknown`. | | `cancel` | `cancelled`, `already_effected`. No block: cancelling is unsupported. | | `verifier` | `observe(source:, revision:) { true \| false }` or `pending`. The block must return literally `true` or `false`. | Arguments: `argument :reason` (a string as sent), `argument :invoice, resource: :invoice` (found through `replybrain_facts(:invoice)`, or a lambda), `argument :amount, money: true` (`amount_cents` and `currency` arrive, a `Money` is handed to you), `argument :days, type: :integer, description: "…"` (`:string`, `:integer`, `:boolean`). `effect :read` marks a capability that changes nothing; it needs neither `reconcile` nor `verifier`. Every other one must declare both. Blocks receive only the keywords they ask for: the declared arguments (resolved), every raw argument, `effect_key`, `action_id`, `attempt_id`, `scope`, `predicate`. A resource that is not found fails the call with `_not_found` and nothing runs. **Effects happen once.** The gem reserves each `effect_key` before `perform` runs: a retry after success replays the answer; a retry while the first is still running answers `accepted`. A started perform is never released by time; only a definitive reconcile, a cancel, or you: ```ruby ReplyBrain::Client.release_effect!("invoice.resend", "invoice.resend:981:1") # only after confirming nothing happened ``` The production store's table: ```ruby create_table :replybrain_effects, id: false do |t| t.string :key, null: false, primary_key: true t.text :value, null: false t.timestamps end ``` ## Your help desk as a source ```ruby class HelpDeskSource < ReplyBrain::Client::Source publish { |message| message.draft? ? drafted(Draft.place!(message).id) : refused(:not_draft_only) } lookup { |effect_key| Draft.find_by(effect_key:)&.then { { draft_id: _1.id.to_s, state: _1.state } } } observe { |ref| t = Ticket.find_by!(reference: ref); { state: t.state, revision: t.revision, participants: t.participant_ids, visibility: "customer" } } backfill { |after| HelpDeskEvent.after(after).limit(100).map(&:to_replybrain) } # each with its "cursor" end ``` `message` exposes `body`, `recipients`, `channel`, `conversation_ref`, `expected_source_revision`, `disclosure_mode`, `approval_id`, `policy_id`, `publication_id`, `effect_key`, `mode`, `draft?`, `publish?`. A missing block answers `501`, which ReplyBrain reads as "this app does not offer that". See [[guides/capabilities|Capabilities]]. ## Posting events ```ruby ReplyBrain::Client.connection.post_event(source_event_id: "message:88", source_object: { type: "ticket", id: "SUP-1042" }, occurred_at: Time.now.utc.iso8601, kind: "conversation.message_added", message: { id: "88", visibility: "customer", channel: "in_app", body_text: "Hi!" }, requester: { ref: "user:42", account_scope: "42" }) ReplyBrain::Client.connection.status ``` Signed with the first signing secret, never with the API key. See [[guides/events|Events]]. ## The /v1 client Responses are records you read like a hash or an object (`kase[:title]`, `kase.title`). ```ruby kase = ReplyBrain::Client.cases.create(email: "ada@example.com", message: "I was charged twice", title: "Double charge") kase.created? # true: 201 opened; false: 200 added to her open case ReplyBrain::Client.cases.each { |c| puts c.title } # follows next_cursor for you kase = ReplyBrain::Client.cases.find(kase.id) # remembers the ETag… ReplyBrain::Client.cases.update(kase, title: "Refund") # …and sends it as If-Match ReplyBrain::Client.messages.list(kase).to_a ReplyBrain::Client.messages.create(kase, "It happened again") need = ReplyBrain::Client.needs.create(kase, message_ref_id: "…", desired_outcome: "refund") ReplyBrain::Client.needs.update(need, state: "satisfied") run = ReplyBrain::Client.runs.create(need_id: need.id, planner: "caller") ReplyBrain::Client.plans.create(run, base_revision: 0, steps: [{ key: "resend", capability: "invoice.resend", version: 1, arguments: { invoice: "981" } }]) action = ReplyBrain::Client.actions.find("…") ReplyBrain::Client.actions.approve(action) # bound to action.revision and arguments_digest ReplyBrain::Client.actions.dispatch(action) promise = ReplyBrain::Client.commitments.create(case_id: kase.id, kind: "follow_up", wording: "We'll email you when it's done", review_at: 2.days.from_now) ReplyBrain::Client.commitments.withdraw(promise) ReplyBrain::Client.context_queries.create(query: "Why hasn't order 4521 shipped?", account_id: "…", resource_refs: [{ connection_id: "…", type: "order", id: "4521" }]) ``` > [!WARNING] > Name the account of a context query with `account_id`. `account_ref`, and `account_scope` inside a resource ref, are refused by the API with `400`. ### The event stream ```ruby begin stream = ReplyBrain::Client.events.list(after: checkpoint) stream.each { |event| handle(event) unless seen?(event.id) } checkpoint = stream.cursor rescue ReplyBrain::Client::CursorExpired => expired resync_from_current_state! checkpoint = expired.snapshot_cursor retry end ``` ### Retries and errors Every `POST` and `PATCH` carries an `Idempotency-Key` (yours via `idempotency_key:`, or a fresh one), reused on every retry after a network error, a `5xx` or a `429`. Errors are `ReplyBrain::Client::Error` subclasses with `code`, `status`, `request_id`, `retryable?` and `details`: `InvalidRequest`, `Unauthenticated`, `PolicyDenied`, `NotFound`, `Conflict` (`ApprovalRequired`, `CapabilityUnavailable`, `AuthorityMismatch`, `IdempotencyConflict`, `InvalidState`), `CursorExpired`, `StaleRevision`, `PreconditionRequired`, `RateLimited` (`retry_after`), and `OutcomeUnknown` (`ServerError`, `ConnectionError`): **the effect may have happened**; read or reconcile before sending again. A second organization: `ReplyBrain::Client::API.new(api_key: "…")` has the same families. ## Testing The engine is a Rack app (`ReplyBrain::Client.app`): drive it with `rack-test`, signing each request with `ReplyBrain::Client::Signature.sign(secret:, key_id:, body:, method: "POST", path:, audience: connection_id)`. --- ## API Overview The `/v1` API lets your servers read and work on your organization's cases: open managed cases, read transcripts, record needs, run and approve work, track commitments, and follow everything through an event stream. The complete contract is the [interactive reference](/api/), generated from [`openapi.json`](/openapi.json) (OpenAPI 3.1). ## Base URL ``` https://replybrain.com/v1 ``` JSON over HTTPS. Timestamps are UTC ISO 8601; ids are opaque strings. ## Authentication ```bash curl https://replybrain.com/v1/cases \ -H "Authorization: Bearer $REPLYBRAIN_API_KEY" ``` Only organization-owned **secret** keys (`rb_sk_live_…`) are accepted. Browser sessions, cookies, query-string tokens and other key types are refused (`403 policy_denied`). A missing, wrong or revoked key is `401 unauthenticated`. Keep secret keys on servers. The one exception is `POST /v1/connections/{id}/events`, which your app signs with its connection secret and sends with no key: see [[api-reference/connection-events|Connection events]]. ## Scopes Each key carries scopes named after resource families. Reads need `.read`, writes `.write`: | Family | Scopes | |---|---| | Cases and their messages | `cases.read`, `cases.write` | | Needs | `needs.read`, `needs.write` | | Runs and plans | `runs.read`, `runs.write` | | Actions | `actions.read`, `actions.write`; plus `actions.financial`, `actions.identity`, `actions.deployment`, `actions.work` for those effects | | Approvals | `approvals.write` | | Commitments | `commitments.read`, `commitments.write` | | Capabilities | `capabilities.read` | | Connections | `connections.read` | | Context queries | `context.read` (also for creating one) | | Events | `events.read` | | Waits | `waits.read` | A missing scope is `403 policy_denied` with `details.required_scope`. ## Bounds A key may be bounded to some products, connections, accounts or cases. Anything outside its bounds answers `404 not_found`, exactly like something that does not exist. ## Who a decision belongs to Approving or rejecting an action and deciding a need are human decisions: they are recorded as made by the member who created the key, and checked against that member's permissions. A key whose creator is no longer a member of the organization is refused. ## Rate limits 600 requests per minute per key. Above that: `429 rate_limited` with `Retry-After` (seconds until the next minute). ## Conventions | Convention | Page | |---|---| | Error shape and codes | [[api-reference/errors|Errors]] | | Idempotency keys, `202`, ETags and `If-Match`, pagination | [[api-reference/conventions|Idempotency, revisions and pagination]] | | Every endpoint at a glance | [[api-reference/endpoints|Endpoints]] | --- ## Errors Every error has the same shape: ```json { "error": { "code": "stale_revision", "message": "The resource changed. Read it again before retrying.", "request_id": "6c1f0e8e-0000-4000-8000-000000000004", "retryable": false, "details": { "current_etag": "\"3f1c…\"" } } } ``` Branch on `code`, never on `message`. Quote `request_id` when you write to [support@replybrain.com](mailto:support@replybrain.com). | Status | `code` | Meaning, and what to do | |---|---|---| | 400 | `invalid_request` | A missing or malformed field, a bad `limit`, a value the endpoint refuses. Fix the request. | | 401 | `unauthenticated` | No key, a wrong or revoked one; on the events endpoint, a missing or wrong signature. | | 403 | `policy_denied` | A missing scope (`details.required_scope`), a key that is not an organization secret key, a creator who left, or an authority that refuses the decision. | | 404 | `not_found` | Does not exist, or is outside this key's organization or bounds. | | 409 | `approval_required` | The action needs a valid approval of its current revision (`details.action_revision`, `details.arguments_digest`). | | 409 | `capability_unavailable` | Not possible for this resource: a connected case changed here, an outbound message on a managed case. | | 409 | `authority_mismatch` | The policy changed since the approver reviewed it (`details.current_policy_revision`). | | 409 | `idempotency_conflict` | The `Idempotency-Key` was used for another request, or a concurrent request with it was recorded. Read the resource, or use a new key for a new request. | | 409 | `invalid_state` | The record's state refuses the change (a run that already ended, a dispatched action). | | 409 | `send_in_progress` | A reply about this commitment is being sent. Retry shortly (`retryable: true`). | | 410 | `cursor_expired` | The cursor expired or belongs to another key or route. Lists: start again without a cursor. Events: see [[api-reference/conventions|conventions]]. | | 412 | `stale_revision` | The resource changed since you read it (`details.current_etag`). Read it again. | | 413 | `invalid_request` | An event body over 256 KB. | | 422 | `reason_required` | Withdrawing a `work` commitment needs `commitment.reason`. | | 422 | `unattributed` | A `work` commitment's change needs a key a member created. | | 428 | `precondition_required` | A `PATCH` without `If-Match`. | | 429 | `rate_limited` | Wait `Retry-After` seconds (`retryable: true`). | | 5xx | (none guaranteed) | The write may have happened. Read the resource, or reconcile, before sending again with the same `Idempotency-Key`. | > [!WARNING] > A timeout or a `5xx` after a write is **not** proof that nothing happened. Retry with the **same** `Idempotency-Key`: you get the recorded result if it did happen. A new key is a new command. --- ## Idempotency, Revisions and Pagination ## Idempotency-Key on every write Every `POST` and `PATCH` (except the signed events endpoint) needs an `Idempotency-Key` header, 1 to 255 characters, unique per logical write and the **same on every retry** of it. ```bash curl -X POST https://replybrain.com/v1/cases \ -H "Authorization: Bearer $REPLYBRAIN_API_KEY" \ -H "Idempotency-Key: open-case:ada:2026-11-12" \ -H "Content-Type: application/json" \ -d '{"requester":{"email":"ada@example.com"},"message":{"body_text":"I was charged twice."}}' ``` - The same key with the same request, at any time later: the recorded resource as it is now, with `Idempotent-Replayed: true`. The write is not repeated. - The same key with a different request: `409 idempotency_conflict`. - No key: `400 invalid_request`. ReplyBrain keeps each (organization, key) record for the life of the organization. ## 202 Accepted Some writes answer `202`: a context query, a run, a cancelled run, an action dispatch or reconcile, and the events endpoint. It means **recorded**, never sent or done. Poll the `Location` header's resource, or read the event stream. ## ETag and If-Match Cases, needs and commitments carry an `ETag`. A `PATCH` must send it back: ```bash curl -X PATCH https://replybrain.com/v1/cases/$CASE_ID \ -H "Authorization: Bearer $REPLYBRAIN_API_KEY" \ -H "Idempotency-Key: rename:$CASE_ID:1" \ -H "If-Match: \"3f1c…\"" \ -H "Content-Type: application/json" \ -d '{"case":{"title":"Double charge"}}' ``` No `If-Match`: `428 precondition_required`. A different one: `412 stale_revision` with `details.current_etag`. Read again, then decide. Approving an action is bound the same way, by its `action_revision` and `arguments_digest` in the body. ## Pagination Lists (`/cases`, `/cases/{id}/messages`, `/capabilities`, `/waits`) answer: ```json { "data": [ … ], "next_cursor": "eyJfcmFpbHMi…" } ``` - `limit`: 1 to 100, default 50. - Pass `next_cursor` back as `cursor`. `null` means the last page. - Order is stable (by creation; messages by when they happened). A cursor is bound to the key and the route and lasts one hour; after that, `410 cursor_expired`: start again without one. ## The event stream `GET /v1/events` is different: its cursor parameter is `after`, `limit` defaults to 100, and `next_cursor` is **always** present, because the stream does not end. Read until a page is empty, store the cursor, and come back later with `after=`. Deduplicate by event `id`. | Query | Starts at | |---|---| | (none) | The start of the retained stream. | | `from=now` | Only what happens from now on. | | `after=` | Right after the page that gave the cursor. | | `run_id=` | Only that run, its plans and their actions. | An event cursor lasts seven days. An expired one answers `410 cursor_expired` with `details.snapshot_cursor`, taken at that moment: read the current state of what you track, then resume from the snapshot cursor, deduplicating by `id`. Nothing that happened in between is lost. ```json { "id": "…", "type": "need.identified", "occurred_at": "2026-11-12T09:30:04Z", "object": { "type": "…", "id": "…" }, "revision": 1, "causation_id": "…", "correlation_id": "…", "data": { } } ``` --- ## Connection Events ``` POST https://replybrain.com/v1/connections/{connection_id}/events ``` Your app posts its help desk's events here. No API key: the request is **signed** with the connection's secret. The body is described field by field in [[guides/events|Events]]. ## Signing ``` ReplyBrain-Signature: t=,v2= ReplyBrain-Key-Id: Content-Type: application/json signed string = "v2" \n t \n "POST" \n path \n connection_id \n raw body ``` - `path` is the request path exactly as sent: `/v1/connections//events`, plus `?query` if you add one. - `raw body` is the exact bytes you send. Serialize once, sign those bytes, send those bytes. - The timestamp must be within five minutes of ReplyBrain's clock. - The key id must be the connection's current or previous key. ### Ruby, by hand ```ruby require "openssl" require "json" require "net/http" body = JSON.generate(event) path = "/v1/connections/#{connection_id}/events" t = Time.now.to_i signature = OpenSSL::HMAC.hexdigest("SHA256", secret, ["v2", t, "POST", path, connection_id, body].join("\n")) request = Net::HTTP::Post.new(path, "Content-Type" => "application/json", "ReplyBrain-Signature" => "t=#{t},v2=#{signature}", "ReplyBrain-Key-Id" => key_id) request.body = body uri = URI("https://replybrain.com") Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) } ``` With the gem it is one line: `ReplyBrain::Client.connection.post_event(event)`. ### Node ```js import crypto from "node:crypto"; const body = JSON.stringify(event); const path = `/v1/connections/${connectionId}/events`; const t = Math.floor(Date.now() / 1000); const v2 = crypto.createHmac("sha256", secret).update(["v2", t, "POST", path, connectionId, body].join("\n")).digest("hex"); await fetch(`https://replybrain.com${path}`, { method: "POST", headers: { "Content-Type": "application/json", "ReplyBrain-Signature": `t=${t},v2=${v2}`, "ReplyBrain-Key-Id": keyId }, body, }); ``` ## Answers | Status | Body | Meaning | |---|---|---| | `202` | `{ "object": "source_event", "id", "connection_id", "source_event_id", "state": "recorded" }` | Recorded. Drafting happens afterwards. | | `202` | the same, `"state": "duplicate"` | This `source_event_id` was already recorded. Nothing changed. | | `400` | `invalid_request` | Not JSON, or the event has no `source_object`, `kind`, valid `occurred_at` or identity (`details.reason`). | | `401` | `unauthenticated` | The signature is missing, expired, signed with an unknown key, or does not match. | | `404` | `not_found` | No such connection. | | `413` | `invalid_request` | The body is over 256 KB. | > [!TIP] > Treat any `202` as done, and retry anything else with the **same** body and `source_event_id` (re-signed with a fresh timestamp). Because events are deduplicated by `source_event_id`, a retry that already landed answers `duplicate`. ## The calls ReplyBrain makes to your app They are signed the same way, with your mount in the path (`/replybrain/facts/order`) and your `connection_id` as the audience. Your app must verify every one and refuse anything else with `401`. The [interactive reference](/api/) lists them as webhooks; [[guides/capabilities|Capabilities]] explains each. --- ## Endpoints All paths are under `https://replybrain.com/v1`. Request and response bodies, examples and every status are in the [interactive reference](/api/) ([`openapi.json`](/openapi.json)). | Method and path | Scope | Success | What it does | |---|---|---|---| | `POST /context-queries` | `context.read` | 202 | Ask for scoped evidence about a customer, without a case. | | `GET /context-queries/{id}` | `context.read` | 200 | Poll it; `result` holds evidence and what was missing. | | `GET /cases` | `cases.read` | 200 | List cases (paginated). | | `POST /cases` | `cases.write` | 201 / 200 | Open a managed case (`200`: added to the requester's open case). | | `GET /cases/{id}` | `cases.read` | 200 | Read a case (`ETag`). | | `PATCH /cases/{id}` | `cases.write` | 200 | Rename a managed case (`If-Match`). | | `GET /cases/{id}/messages` | `cases.read` | 200 | The transcript (paginated). | | `POST /cases/{id}/messages` | `cases.write` | 201 | The customer's next inbound message on a managed case. | | `POST /cases/{case_id}/needs` | `needs.write` | 201 | Record a need from one of the case's messages. | | `GET /needs/{id}` | `needs.read` | 200 | Read a need (`ETag`). | | `PATCH /needs/{id}` | `needs.write` | 200 | Reword it, or decide it: `satisfied`, `declined`, `unknown` (`If-Match`). | | `POST /connections/{id}/events` | signature | 202 | Your app's signed events. See [[api-reference/connection-events|Connection events]]. | | `GET /connections/{id}/status` | `connections.read` | 200 | Sync health, credential state, declared operations. | | `POST /runs` | `runs.write` | 202 | Start a run for one need. | | `GET /runs/{id}` | `runs.read` | 200 | Poll a run. | | `POST /runs/{id}/cancel` | `runs.write` | 202 | Cancel it; undispatched actions are cancelled. | | `POST /runs/{id}/plans` | `runs.write` | 201 | Submit your own plan (`planner: caller`). | | `GET /runs/{id}/plans/{revision}` | `runs.read` | 200 | Read a plan revision. | | `GET /capabilities` | `capabilities.read` | 200 | Registered capabilities (paginated). | | `GET /capabilities/{name}/versions/{version}` | `capabilities.read` | 200 | One capability version, with its argument schema. | | `GET /actions/{id}` | `actions.read` | 200 | Read an action. | | `POST /actions/{id}/approvals` | `approvals.write` | 201 / 200 | Approve (`201`, the approval) or reject (`200`, the cancelled action). | | `POST /actions/{id}/dispatch` | `actions.write` | 202 | Dispatch an approved action. | | `POST /actions/{id}/cancel` | `actions.write` | 200 | Cancel an action not yet dispatched. | | `POST /actions/{id}/reconcile` | `actions.write` | 202 | Find out what happened to an `outcome_unknown` action. | | `POST /commitments` | `commitments.write` | 201 | Record a proposed commitment. | | `GET /commitments/{id}` | `commitments.read` | 200 | Read a commitment (`ETag`). | | `PATCH /commitments/{id}` | `commitments.write` | 200 | Reword, reschedule or withdraw it (`If-Match`). | | `GET /events` | `events.read` | 200 | The event stream, with cursor replay. | | `GET /waits` | `waits.read` | 200 | What waits for a person (paginated). | | `GET /waits/{id}` | `waits.read` | 200 | One wait. | > [!NOTE] > These are the endpoints that exist today. There is no endpoint yet for outbound webhooks, customer sessions, hand-offs, usage or offboarding; follow the event stream instead of webhooks. ---