Build a conversation integration with a coding agent
A copyable implementation brief, typed API contracts, receiver code and acceptance checks for your coding agent.
Give your coding agent the brief below and this page's Markdown version. It contains the implementation contract without requiring the agent to run shell commands or extract schemas from an interactive API explorer. Use your application's existing backend, database, authentication and job processing.
The integration mirrors existing AgentBrains conversations into your application. Operators can take over an active web chat, reply and resume the AI. Customers continue using the existing AgentBrains chat channel. These endpoints do not create conversations, accept customer turns from your application, or start AI generation on demand. Operator commands support active web chats; email history and events can be read, but operator commands cannot send email. Version 1 message events and structured history do not include attachment metadata.
Copy this brief to your coding agent
Implement the AgentBrains conversation integration in this repository.
Read these contracts before editing:
https://docs.agent-brains.com/integrations/coding-agent.mdx
https://docs.agent-brains.com/integrations/api/webhooks/events.mdx
Inspect the current backend, authentication, database, jobs and chat model.
Reuse them. Keep the AgentBrains API key and webhook signing secrets on the
server, in the existing secret configuration. Do not ask for secrets in prompts
or include them in source code, logs, browser bundles or screenshots.
Implement an authenticated server-side API client, an HTTPS webhook receiver,
durable event deduplication and a mapping between AgentBrains conversations
and our chats. Synchronize structured history without losing concurrent events.
Add takeover, operator replies and resume to the existing operator workflow.
Authorize these actions against our own users and workspace membership.
Use the exact plural /messages endpoint for operator replies. Persist each
client_message_id and payload before sending. Reuse them after a lost response.
Verify raw-body HMAC before parsing JSON. Acknowledge only after durable storage.
Handle duplicates, out-of-order events, version conflicts and ambiguous delivery.
Do not forward incoming events back as new outbound messages.
Use the acceptance checks in this guide. Start with a dedicated test employee,
an employee-filtered subscription and a fresh ordinary web chat. Do not alter
the employee's agent-execution webhook or register a replacement AI agent.
Deliver the implementation, required database migrations, automated checks,
configuration names and a short setup/runbook. Identify any missing CRM-specific
chat/contact mapping or credential configuration; do not invent identifiers.
Run live checks only against the workspace and employee authorized by the owner.
Report which checks ran and any remaining integration gaps.Inputs to obtain from the owner
| Input | Purpose |
|---|---|
| AgentBrains API origin | Production is https://api.agent-brains.com. Use the owner's origin for another environment. |
| API key, supplied through server secret configuration | Requires webhooks:manage, conversations:read and conversations:write. Existing keys gain no additional scopes automatically. |
Expected workspace ID (tenant_id) | Bind authenticated webhook events to the configured workspace. |
| Test employee ID | Use the employee's ID, not a campaign ID. Restrict the initial subscription to this employee. |
| Public HTTPS receiver URL | Must have a valid certificate and respond directly. Private addresses and redirects are unsupported. |
| Existing chat/contact mapping | Decide how conversation_id and recipient_id map into the application's existing records. |
| A fresh web chat with the test employee | Send synthetic text in an ordinary chat. Conversations created as synthetic QA tests are excluded from external webhook delivery. |
Create the API key in System Integration → API Keys. A chat widget's expert-api-key is a separate credential; it is not the public integration API key. It is needed only if your test harness opens the customer chat through that existing channel. Obtain that channel's setup from the owner rather than inventing an undocumented public endpoint.
The three integration scopes cover the operations below. Legacy employee lookup and GET /conversations currently require the separate knowledge-base scope. For historical discovery, either obtain known conversation IDs from the owner or request that additional permission explicitly. New conversations can be discovered from incoming events.
HTTP contract
Authenticate server-to-server requests with x-api-key. The workspace is derived from that key; never put tenant_id into request bodies. Alternative authentication headers are documented in the API introduction.
All operations below use JSON. Unknown body and query fields are rejected. Resource IDs in these paths are 24 hexadecimal characters; obtain them from AgentBrains. Treat IDs as identifiers, not timestamps or sortable business keys.
| Method and path | Scope | Body or query | Success body |
|---|---|---|---|
POST /webhooks | webhooks:manage | WebhookCreate | 201 WebhookCreated |
GET /webhooks | webhooks:manage | cursor?, limit? | 200 Page<Webhook> |
GET /webhooks/{id} | webhooks:manage | None | 200 Webhook |
PATCH /webhooks/{id} | webhooks:manage | WebhookPatch | 200 Webhook |
DELETE /webhooks/{id} | webhooks:manage | None | 204, no body |
GET /webhooks/{id}/deliveries | webhooks:manage | cursor?, limit? | 200 Page<Delivery> |
POST /webhooks/{id}/deliveries/{deliveryId}/retry | webhooks:manage | None | 202 Delivery |
GET /conversations/{id} | conversations:read | None | 200 Conversation |
GET /conversations/{id}/messages | conversations:read | cursor?, limit? | 200 Page<Message> |
PATCH /conversations/{id}/control | conversations:write | ControlRequest | 200 Conversation |
POST /conversations/{id}/messages | conversations:write | OperatorMessageRequest | 202 Message |
Use the per-operation API reference for field descriptions and schemas. The types below describe the same integration inputs and outputs. Validate external JSON at runtime with your application's existing validation library; TypeScript annotations alone do not validate it. Timestamp strings are RFC 3339 UTC values.
type EventType = "message.created" | "conversation.control_changed";
type Mode = "ai" | "human";
type Sender = {
type: "customer" | "ai" | "human" | "system" | "unknown";
external_id?: string;
};
type Page<T> = { items: T[]; next_cursor: string | null };
type WebhookCreate = {
url: string;
events: EventType[];
employee_ids?: string[] | null;
enabled?: boolean;
};
type WebhookPatch = Partial<WebhookCreate>;
type Webhook = {
id: string;
url: string;
events: EventType[];
employee_ids: string[] | null;
enabled: boolean;
created_at: string;
};
type WebhookCreated = Webhook & { signing_secret: string };
type Delivery = {
id: string;
event_id: string;
status: "pending" | "delivered" | "failed" | "cancelled";
attempts: number;
last_http_status: number | null;
last_error: string | null;
next_attempt_at: string | null;
};
type Conversation = {
id: string;
employee_id: string;
recipient_id: string;
channel: "web-chat" | "email";
mode: Mode;
control_version: number;
};
type Message = {
id: string;
conversation_id: string;
body: string;
direction: "incoming" | "outgoing";
sender: Sender;
created_at: string;
sequence: number | null;
client_message_id?: string;
delivery_status: "pending" | "sent" | "failed" | "unknown";
};
type ControlRequest = { mode: Mode; expected_version: number };
type OperatorMessageRequest = {
body: string;
client_message_id: string;
operator_id?: string;
};
type ApiError = { error: { code: string; message: string } };Apply these constraints at runtime:
url: public HTTPS, at most 2,048 characters.events: one or two distinct supported values.employee_ids: omit or usenullfor all employees; otherwise use 1–100 distinct IDs from this workspace, each nonempty and at most 255 characters. PATCH withnullclears the filter.enableddefaults totrueonly on creation; PATCH changes only supplied fields and must contain at least one field.limit: integer 1–100, default 50.cursor: nonempty opaque string, at most 1,024 characters. Pass it usingURLSearchParams; stop atnext_cursor: null. Never construct a cursor or reuse a history cursor for another conversation.expected_version: nonnegative safe integer read fromcontrol_version. An actual transition increments the version. Repeating the current mode returns the current state without another transition, even if the supplied version is stale.- Operator
body: nonblank, at most 20,000 characters.client_message_id: nonblank, at most 255 characters, stable per logical command in a conversation. Optionaloperator_id: nonblank, at most 255 characters, derived from an authorized operator in your application.
Implement in this order
1. Add the server API client
Reuse your existing HTTP client, timeouts and runtime schemas. This Node.js example shows the transport behavior with native fetch; adapt it to your backend. It returns unknown so the caller must validate the operation's response. It deliberately leaves retry decisions to the operation that knows whether a write is safe to repeat.
export class AgentBrainsHttpError extends Error {
constructor(readonly status: number, readonly payload: unknown) {
super(`AgentBrains HTTP ${status}`);
}
}
export async function agentBrainsRequest(
path: string,
init: RequestInit = {},
): Promise<unknown> {
const key = process.env.AGENTBRAINS_API_KEY;
if (!key) throw new Error("AGENTBRAINS_API_KEY is required");
const headers = new Headers(init.headers);
headers.set("x-api-key", key);
headers.set("Accept", "application/json");
if (init.body !== undefined) headers.set("Content-Type", "application/json");
const response = await fetch(`https://api.agent-brains.com${path}`, {
...init,
headers,
redirect: "error",
signal: init.signal ?? AbortSignal.timeout(25_000),
});
if (response.status === 204) return undefined;
const payload: unknown = await response.json();
if (!response.ok) throw new AgentBrainsHttpError(response.status, payload);
return payload;
}Build paths from the documented routes and URL-encoded IDs. Keep the API origin under server configuration, never under an end user's control. Authorize application users before calling this client: possessing a conversation ID does not grant an operator permission to control it.
2. Provision the receiver and create one subscription
Create a receiver path tied to a server-side integration connection. Look up that connection's signing secret by the route, not by an unverified JSON tenant_id.
Create the subscription once with this JSON body, replacing the receiver URL and employee ID with configured values:
{
"url": "https://your-app.example/integrations/agentbrains/your-connection/events",
"events": ["message.created", "conversation.control_changed"],
"employee_ids": ["507f1f77bcf86cd799439011"]
}Persist the returned webhook id and signing_secret securely. The signing secret is a literal UTF-8 string and is returned only on creation. While provisioning is incomplete, the receiver should return 503 so events can be retried. Never acknowledge events before you can authenticate and store them.
Reuse the saved subscription on restart. If creation times out, inspect GET /webhooks before retrying: creation has no idempotency key and a blind retry can create duplicates. A listed subscription does not reveal its signing secret. If the response was lost before you saved the secret, identify the subscription you created, delete it and recreate it deliberately. Do not delete subscriptions owned by another integration.
Subscription activation starts new events only. Updating the URL, filters or enabled state cancels outstanding deliveries and establishes a new activation point; it is not a way to replay missed events. Keep the subscription stable while reconciling history. Revoking the API key does not disable an existing subscription; disable or delete the subscription separately.
3. Verify raw bytes and accept events durably
Configure this endpoint to receive the raw body before JSON middleware parses it. Re-serializing parsed JSON changes the signed bytes. This Node.js function checks the attempt timestamp and HMAC without adding a dependency:
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyAgentBrainsSignature(
rawBody: Buffer,
timestamp: string,
signature: string,
signingSecret: string,
nowSeconds = Math.floor(Date.now() / 1000),
): boolean {
if (!/^\d{1,12}$/.test(timestamp)) return false;
if (Math.abs(nowSeconds - Number(timestamp)) > 300) return false;
if (!/^v1=[a-f0-9]{64}$/i.test(signature)) return false;
const expected = createHmac("sha256", signingSecret)
.update(timestamp)
.update(".")
.update(rawBody)
.digest();
const received = Buffer.from(signature.slice(3), "hex");
return timingSafeEqual(expected, received);
}Read X-AgentBrains-Timestamp and X-AgentBrains-Signature case-insensitively from the HTTP headers. Use the literal secret as the HMAC key; do not hex-decode it.
After verification, parse and validate the complete event union. Require version: 1, body id equal to X-AgentBrains-Event-Id, the expected workspace binding, and the configured employee filter. Enforce a body-size limit appropriate to your application's accepted message sizes; reject invalid signatures before processing message text.
In one database transaction, insert an inbox record with a unique (connection_id, event.id) key and store the event for asynchronous processing. Commit, then return 204. An already stored identical event can also return 204. If durable storage is unavailable, return 503. Do not acknowledge after only adding the event to an in-memory queue. A worker should resume unprocessed inbox records after restart and retry its local work independently of HTTP delivery.
The receiver has a five-second delivery deadline. Keep CRM writes, history fetching and other slow processing outside the HTTP handler. AgentBrains retries network errors, 408, 429 and 5xx for up to 24 hours. Other non-retryable responses end that delivery; 410 disables the subscription. Delivery and event records are retained for seven days after reaching a terminal state. Timestamps and signatures change on retry; event IDs and bodies remain stable.
4. Merge events and structured history
Use a durable mapping from (connection_id, conversation_id) to your application's chat and from recipient_id to the contact where that mapping is known. Do not guess contact identity from message text.
For each discovered conversation:
- Keep accepting webhook events durably before starting the history fetch.
- Read
GET /conversations/{id}and every page ofGET /conversations/{id}/messages. - Upsert history messages by
(connection_id, conversation_id, Message.id). - Merge buffered and later
message.createdevents usingdata.message_idas the same message key. - Apply
conversation.control_changedonly when itscontrol_versionis newer than the locally stored control version. Re-read current state before a control command.
Deduplication of events and deduplication of messages solve different problems: history and a webhook can describe the same message with different top-level IDs. Include the connection in local keys to prevent cross-workspace mixing. Handle all sender types explicitly; outgoing alone does not mean AI. Older history records can have sequence: null and sender.type: unknown.
Events can arrive out of order. Use sequence within each conversation, shared by message and control events; it is not a global or gap-free message counter. Do not discard a previously unseen event merely because its sequence is below the highest received sequence. Preserve late messages and prevent older control events or history snapshots from overwriting newer state. Subscription filters and activation can also leave gaps; do not wait forever for consecutive numbers. Reconcile missed message history after an outage or subscription change.
Your chat is a projection of AgentBrains history. Display incoming message events without calling the operator endpoint in response. Match an operator API response and its later webhook by message ID, and use client_message_id to reconcile a locally pending operator command. This prevents echo loops and duplicate chat entries.
5. Take over, send and resume
Read the current conversation, then PATCH its /control path with {"mode":"human","expected_version":CURRENT_VERSION}. Use the returned mode and version. Operator actions require an active web chat. On stale_control_version, fetch state again and let the current operator intent determine the next action; do not blindly overwrite another operator's change.
Before POSTing to /conversations/{id}/messages, persist a logical command with its payload and a unique client_message_id. Generate the ID once, for example from a durable local command ID. The body is:
{
"body": "Hello, a member of our team is here to help.",
"client_message_id": "your-durable-command-id",
"operator_id": "your-authorized-operator-id"
}A lost response or request timeout does not prove the message was rejected. Repeat the same ID, body and operator identity to recover the original result. The ID is unique per conversation. Different text or operator identity with the same ID returns 409 idempotency_conflict. Never generate a new ID automatically to work around a conflict or uncertain delivery.
202 means accepted. delivery_status: sent means handed to the chat channel; it does not mean read by the customer. pending is awaiting dispatch. failed and unknown need reconciliation with history and the application's command record; an ambiguous unknown is not automatically resent. A message.created event also reports persistence, not customer delivery, and has no delivery_status field. Fetch the structured message history to inspect that field.
Resume with {"mode":"ai","expected_version":LATEST_VERSION}. New customer turns can generate AI replies again. Human-mode turns are not replayed automatically. Takeover invalidates older AI generations, including after resume, but does not cancel external tools or side effects already running inside an agent.
Do not use the legacy singular POST /conversations/{id}/message for operator replies: it lacks this command's handoff and idempotency contract.
6. Handle failures by operation
| Response or failure | Action |
|---|---|
400 | Correct input or runtime validation. Do not retry the unchanged request. |
401 / 403 | Check the key, environment and required scope. Do not fall back to a broader credential silently. |
404 | Resource is absent or unavailable in the key's workspace. |
409 | Inspect error.code: refresh stale control state; use bounded retries for conversation_busy; require human mode before sending; surface unsupported conversations and idempotency conflicts. |
503, network failure or client timeout | Retry safe reads with bounded backoff. For operator writes, preserve the persisted command ID and payload. For control writes, reconcile current state. For subscription creation, inspect existing subscriptions before creating again. |
Use GET /webhooks/{id}/deliveries for sanitized status and attempt counts. Manually retry only a retained failed delivery while the subscription is enabled with the same configuration. POST /webhooks/{id}/deliveries/{deliveryId}/retry returns 202; then inspect that same delivery until terminal. delivery_unavailable means it cannot be retried in the current state. A webhook retry repeats an event notification; it does not resend the operator's message to the customer.
Acceptance checks
Leave automated checks for signature verification, durable deduplication, ordering, command retries and authorization in the integration's repository. Run this live scenario with the owner's dedicated employee and a fresh ordinary chat:
- A customer turn and AI reply appear once in the application, with the correct sender types. Verify signatures and compare message IDs against paginated history.
- Take over with the returned version. A customer turn still reaches history and webhook; the AI does not reply while in human mode. A repeated takeover creates no second transition; a stale conflicting version returns 409.
- Send one operator reply. Confirm it appears in the customer's actual chat. Repeat the same command sequentially and concurrently: one stored message, one customer delivery, the same returned ID. Change the payload with that ID: expect 409.
- Make the test receiver return 503 once, then 204. Verify automatic retry, the same event ID and identical raw body. Return 400 for another event, restore the receiver, use manual retry and verify successful delivery.
- Resume using the latest version, send a new customer turn and confirm a new AI reply. Verify the integration does not echo events back into the chat.
- Inject duplicate and reordered events into your receiver/worker checks, including an older control event after a newer one. Restart your integration worker with an accepted but unprocessed event and confirm processing resumes without duplicate messages.
- Reject invalid and expired signatures, another workspace's event binding and unauthorized local operator actions. Test insufficient API scopes using a separate restricted key; do not change the live key to perform this check.
- Delete only the temporary subscription, end the test chat through its normal channel, and stop the temporary HTTPS tunnel. Preserve a result summary without credentials or customer message text.
The public scenario was smoke-tested with a dedicated production chat and an HTTPS test receiver on 2026-11-04: customer and AI events, history, takeover, operator idempotency, automatic/manual webhook retries and resume passed. That run does not verify your application's receiver or worker; run these checks against your implementation.