// TL;DR
A chat session is delivered as one self-contained JSON document. It carries everything the UI needs to render in one round-trip: session shell, participants (humans and agents alike), all messages, reactions, tags, attachments. The choices that shape it for agentic-AI workloads: agents-as-users, JSON-Schema action payloads that close the loop from prompt to structured result, the Actor pattern for "who did this," soft delete with a sweeper, and polling instead of WebSockets. Each one earns its place; this article is the why.
// Audience
This article assumes you know what JSON is and have used a REST API before. It does not assume you know JSON Schema, denormalisation as a deliberate design choice, or the trade-offs between polling and push. Each of those is explained where it comes up.
Why a chat protocol needs a shape
A modern chat session isn't just text. It's a conversation between humans, AI agents, and sometimes other systems, all writing into the same timeline. The agent might present a form, the user fills it in, the result feeds back into the agent's next decision — and that loop can repeat several times before the work is done. That's what we mean by an Agentic-AI loop: prompt → response → structured action → result → next prompt.
For this loop to work cleanly, the protocol has to make every step legible to both sides. The agent has to be able to say "fill out this form" without the client knowing how to render that specific form. The user's reply has to be linked back to the prompt that asked for it, so the agent (or a later reader) can follow the chain. And every event in the loop has to live in the same timeline — not split across separate logs.
The shape below is one way to do that.
The Agentic-AI loop. Each step is a typed message in the same messages[] array — replayable, auditable, ordered.
One big document, not five small ones
Coming from REST, you'd expect /sessions, /messages, /participants, /reactions as separate endpoints. We don't do that here. The reason is round-trip cost: a chat UI typically wants to show the whole session at once — who's in the room, what was said, what reactions were placed, what's still attached. Fetching that as five separate calls means five latencies stacked on top of each other, and five places for the client to get out of sync.
So loadSession(sessionId) returns one JSON. That JSON is denormalised — meaning we pre-flatten data the client would otherwise have to look up itself. We'll come back to denormalisation in a moment because it's a recurring pattern.
The shell
The top level of a session response looks like this:
{
"sessionId": "c372f77c-28df-4516-bdde-2e29cf192139",
"userId": "20a716d8-...", // who STARTED the session
"activeResponderUserId": "a1b2c3d4-...", // who's currently expected to reply
"startedAt": "2026-03-25T11:35:41Z",
"status": "active", // or "closed"
"deletedAt": null, // soft delete
"context": { ... }, // summary + entities
"participants": [ ... ],
"tags": [ ... ],
"attachments": [ ... ],
"reactions": [ ... ],
"messages": [ ... ]
}
ChatSession // one self-contained document ├── sessionId "c372f77c-..." // GUID ├── userId "20a716d8-..." // who STARTED the session (immutable) ├── activeResponderUserId "a1b2c3d4-..." // who's expected to reply now ├── startedAt · status · deletedAt // shell metadata │ ├── context // summary + entities │ ├── summary: "Employee asking about vacation policy" │ └── entities: [{ type, id, label }, ...] │ ├── participants[] // humans + agents (one user table) │ ├── { userId, isAgent, role, status, historyVisibleFrom, addedBy, ... } │ └── ... │ ├── messages[] // chronological — the loop lives here │ ├── { type: "text", role: "user", content } ← step 1 │ ├── { type: "text", role: "assistant", actions[] } ← step 2 (JSON Schema) │ ├── { type: "action_result", role: "user", actionResult } ← step 3 │ ├── { type: "handoff", role: "system", handoff } ← agent → agent │ └── ... │ ├── tags[] // searchable labels ├── reactions[] // emoji on messages └── attachments[] // files
Two fields up here are easy to confuse:
userIdis the starter. Historical fact. It never changes — even if the starter leaves the session, this field stays as a record of who began the conversation.activeResponderUserIdis whoever is currently expected to reply. It moves around as the session is handed off between participants — including handoffs between agents, which is common in multi-agent loops.
If userId could change, "who started this thread" would silently rewrite itself, which is exactly the kind of small inconsistency that becomes a debugging nightmare months later. So it doesn't.
Participants — and the agent-as-user trick
A participant is a user who's been added to the session. Here's one:
{
"id": "p002",
"userId": "9f8e7d6c-...",
"displayName": "HR Assistant",
"isAgent": true,
"role": "member", // owner | member | observer
"status": "left", // pending | active | left | declined
"joinedAt": "2026-03-25T11:35:41Z",
"leftAt": "2026-03-25T11:37:37Z",
"historyVisibleFrom": "2026-03-25T11:35:41Z",
"addedBy": { "type": "system", "value": "system" },
"lastReadAt": "2026-03-25T11:37:37Z"
}
The design choice that matters: AI agents are not a separate type. They're regular user records with isAgent = true. There's no separate "agent table" — there's one user table.
Why does this matter for agentic-AI workloads? Because as soon as agents become a separate entity, every join, every permission check, every UI view has to handle two cases. By making agents users, all the existing user logic just works — access control, audit, login flow. Multi-agent handoffs (one agent passes to another) become identical to human-to-human handoffs from the protocol's point of view. The isAgent flag is denormalised into the participant payload so the UI can show an "agent" badge on the avatar without a second lookup.
The other fields tell you about lifecycle:
statusis a state machine: a participant moves throughpending(invited, hasn't accepted) →active(in the room) →left(gone, but might still see history) →declined(turned the invitation down). Useful when an agent is added asynchronously and may not have been "online" yet.historyVisibleFromcontrols how far back this participant can see. Newcomers usually only see from when they joined; the owner sees everything (null). For a fresh agent joining mid-loop, this prevents it from being flooded with prior context unless that's intended.lastReadAtis a fast unread-count optimisation — instead of joining against every message-read row, the client just compares this timestamp to the latest message.
Denormalisation — what and why
You'll see displayName and isAgent on every participant. Those values live on the user table in the database — but here they sit on the participant. That's denormalisation: keeping a cached copy of one piece of data in two places.
// What it BUYS us
- Client renders the chat without a separate "fetch user list" call.
- Historic records show what was rendered at the time, even if the user later changes their name.
- Faster paint of the first message bubble.
// What it COSTS us
- If a user renames themselves, old participant records still show the old name.
- If a user becomes / stops being an agent, old records show the previous flag.
- Two places to keep in mind when thinking about consistency.
For chat history, the trade is worth it. A self-contained record of "what the room looked like" is more useful than a perfectly normalised view that re-renders on every name change.
Messages — types and shapes
Messages are listed in chronological order under messages. Each one has a type field:
text— a normal text message (the most common kind).handoff— a structural event: control of the session passed from one user to another. In agentic loops, this is how one agent passes a sub-task to another.action_result— a user filled out a form, picked an option, or completed an action that an agent had presented. This is the closing half of an agentic loop.
A plain text message:
{
"id": "85c76002-...",
"role": "user", // user | assistant | system
"type": "text",
"userId": "20a716d8-...",
"content": "Hello, I'd like to know about my vacation days.",
"replyTo": null,
"timestamp": "2026-03-25T11:35:48Z",
"metadata": null
}
role exists separately from userId because the same user can post both as themselves and as a system event. The client uses role to pick the bubble style (left, right, centred); userId identifies who actually authored it. For an agent, role: "assistant" tells the UI to render it on the agent side; userId identifies which agent.
Actions — declarative UI inside a message (the agentic loop opens)
This is where the protocol gets interesting and where the agentic loop comes alive. An agent can send a message that contains UI instructions:
{
"type": "text",
"content": "You have 12 days left. Want to apply now?",
"actions": [
{
"type": "open_form",
"target": "modal",
"payload": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"title": "Vacation request",
"properties": {
"startDate": { "type": "string", "format": "date", "title": "Start" },
"endDate": { "type": "string", "format": "date", "title": "End" }
},
"required": ["startDate", "endDate"],
"x-formId": "vacation_request"
},
"id": "a1",
"version": 1
}
]
}
The payload inside the action is a JSON Schema — the same standard often used for API validation. We use it for forms because:
- It's a known standard with libraries in every language. We don't invent a custom form-DSL just for chat.
- The client can render it generically: a string with
format=datebecomes a date picker; anenumbecomes a dropdown; arequiredarray becomes red asterisks. - Validation rules ride along (
required,minLength,pattern) — so the client validates locally, and the server validates the same schema before accepting the result. The agent that generated the schema can validate the result with the same library before acting on it.
The agent doesn't write UI code to draw a form. It emits a schema. The client decides how to render it. The same form definition works on web, mobile, or any future client without anyone copy-pasting UI code. This is critical for agentic AI: the agent should reason about what to ask and let the protocol handle how it's rendered.
The x-formId field is a JSON Schema convention for custom extensions (anything starting with x-). We use it to identify which form was submitted, so the receiver can route the result correctly.
Action results — the agentic loop closes
When the user fills out the form and submits, a new message of type action_result is added to the session:
{
"type": "action_result",
"userId": "20a716d8-...",
"replyTo": "199b9709-...",
"actionResult": {
"actionId": "a1",
"actionType": "open_form",
"sourceMessageId": "199b9709-...",
"status": "completed",
"data": {
"formId": "vacation_request",
"startDate": "2026-05-01",
"endDate": "2026-05-10"
}
}
}
Notice it's a regular message — it lives in the same messages array, ordered by timestamp. It refers back to the message that prompted it via sourceMessageId. The actionId ties it to a specific action (one message can have multiple actions; the result identifies which one was completed).
The agent now has a structured input it can act on: validated against the same schema it sent out, addressed to a known actionId, with a clear chain of provenance back to the prompting message. The next agent step can read the result, take an action (call a tool, post a follow-up, hand off to another agent), and continue the loop. Multiple actions in the same message let the agent give the user a choice (form / decline / postpone), and the result tells the agent which path was taken.
Why a message and not a separate "results" array? Because in the chat log, a form submission is something the user did at a particular moment, and the agent (or a later reader) wants to see it in chronological order alongside what was said. Separate-array would split the timeline into two logs that have to be merged on every render — and would lose the natural ordering that agent reasoning depends on.
The Actor pattern — who did this
Several fields document "who did this" — who added a participant, who locked a tag, who uploaded a file. Some actions are done by users; some by the system itself (a cron job, a migration, an automated trigger, an agent runtime).
In the database, this is stored as two columns and a CHECK constraint that says exactly one must be set:
SomeBy_UserId CHAR(36) NULL, SomeBy_System VARCHAR(50) NULL, CHECK ( (SomeBy_UserId IS NOT NULL AND SomeBy_System IS NULL) OR (SomeBy_UserId IS NULL AND SomeBy_System IS NOT NULL) )
In the JSON, both possibilities collapse into a single Actor object:
// Done by a user (human or agent — both are users) "addedBy": { "type": "user", "userId": "20a716d8-..." } // Done by the system (automation with no user identity) "addedBy": { "type": "system", "value": "system" } // Optional — null if not applicable "addedBy": null
Why bother with the CHECK constraint? Because without it, both columns could be set, and nobody knows which one to trust. By forcing exactly one, the data is unambiguous. Allowed values for type=system include "system", "admin", "cron", and similar — extensible at the application layer. This matters in agentic systems where some actions are taken by an agent runtime acting on behalf of no specific user (e.g. autonomous cleanup, scheduled summarisation).
Soft delete
deletedAt is a nullable timestamp. When a session is "deleted," it isn't removed from the database — deletedAt is set to the current time. A scheduled job later hard-deletes records that have been soft-deleted past a retention threshold.
Why? Because hard delete is irreversible. Soft delete gives a recovery window. The cost is that read paths must filter WHERE DeletedAt IS NULL for "active" records — easy to forget, but a very small price to pay for not losing data to a misclick or an over-eager agent.
Polling, not push
The reference implementation uses REST + polling rather than WebSocket / Server-Sent Events / SignalR. The client polls a REST endpoint every few seconds for changes. This is unusual — modern chat usually means push.
The reasons:
- Hosting reality. Many environments (shared hosting, corporate proxies, restrictive firewalls) don't reliably support long-lived WebSocket connections. Polling works on every host, every reverse proxy, every firewall.
- Reconnect simplicity. With polling, "reconnect" is just "send the next GET." No state machine for connection lifecycle, no special handling of zombie sockets, no reconnect-storm protection beyond a simple backoff.
- Battery on mobile. Aggressive polling backoff and pause-when-backgrounded is well-trodden territory. WebSocket battery management is harder.
- Agent loops aren't real-time. An agent thinking, calling a tool, and emitting a follow-up takes seconds anyway. A 2–3 second poll cadence isn't the bottleneck.
The downside is latency: with a 3-second poll interval, a new message can be 3 seconds old before the client sees it. For chat between humans and AI agents — not an instant-messaging app between humans typing in real time — that's acceptable. The protocol is shaped so that switching to push later doesn't require redesigning the JSON; events just arrive faster.
What the JSON does not contain
By design, you won't find:
- Permission logic. The backend decides what each user can see before serialising. If a participant doesn't have permission to see a message, it's filtered out of
messagesentirely. The client never sees the boundary. This matters when an agent is observing on behalf of a tenant: the agent only sees what it's allowed to. - Internal database IDs. Foreign-key constraints, audit row numbers, change-tracking metadata — these stay on the server.
- Validation rules for things the client shouldn't enforce. The agent might know a form-result requires a manager's approval. The client doesn't need to know — it sends the result and the backend (or the next agent step) rejects or accepts.
The principle: the JSON is what the client needs to render and act. Anything else stays behind.
Why the whole shape adds up
Every choice in the JSON serves the same goal: the client and the agent can render and reason about a complete session from one document, with no extra lookups, and act on it through clearly typed messages and actions.
- Denormalisation buys speed.
- Agents-as-users buys uniformity in permission checks and cross-agent handoffs.
- JSON-Schema action payloads buy generic form rendering and a closed agentic loop with structured results.
- The Actor pattern buys clarity about who did what, including system-initiated actions.
- Soft delete buys reversibility.
- Polling buys deployment simplicity, and matches the natural cadence of agent reasoning.
If a future version moves to push-based transport, the JSON shape doesn't have to change. Subscriptions just deliver events typed as additions and updates to the same shapes. The protocol survives the transport. And because every step in the loop — prompt, response, action, result, handoff — lives on the same timeline, an agent reading the session can replay reasoning forwards or backwards without joining across data sources.