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.
# Gemfile
gem "replybrain-client", path: "vendor/replybrain-client"
Bundler requires it; outside Bundler, require "replybrain/client".
Configuration
# 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
# 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
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" => "<ISO 8601>" }). account: is a method name or a lambda. Without a block, the model's support_context is served. See Facts.
Capabilities
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 <argument>_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:
ReplyBrain::Client.release_effect!("invoice.resend", "invoice.resend:981:1") # only after confirming nothing happened
The production store's table:
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
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 Capabilities.
Posting events
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 Events.
The /v1 client
Responses are records you read like a hash or an object (kase[:title], kase.title).
kase = ReplyBrain::Client.cases.create(email: "[email protected]", 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" }])
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
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).