// 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.

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": [ ... ]
}

Two fields up here are easy to confuse:

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:

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:

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:

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:

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:

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.

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.


Related rules