AI Messages
Messages within a session. Sending a user message triggers an AI run that generates the assistant response.
Chat Flow Walkthrough
- Fetch existing messages for the session (
GET /ai/sessions/:sessionId/messages) to display the conversation history or pagination cursor. - Send a new user message (
POST /ai/sessions/:sessionId/messages) and capture both theuserMessageand theassistantMessage.runId. - Stream the assistant output via
GET /ai/sessions/:sessionId/messages/:messageId/stream(or the run stream) and appendmessage.deltaevents to the UI as they arrive. - If the user interrupts the assistant, call
POST /ai/sessions/:sessionId/messages/:assistantMessageId/stopto finalize the partial content and showstatus: stopped. - If the assistant pauses on a question card (
clarification.required), render it and submit the answers or skip it. See AI Question Cards.
The JavaScript walkthrough uses eventsource v4 (npm install eventsource@4).
import { EventSource } from "eventsource";
const startChat = async (sessionId) => {
const history = await fetch(
`https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages`,
{ headers: { Authorization: `Bearer ${TOKEN}` } }
);
console.log("Existing messages:", (await history.json()).data);
const reply = await fetch(
`https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages`,
{
method: "POST",
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ content: "Show me a recap of today's tasks." }),
}
);
const {
assistantMessage: { id: assistantId },
} = (await reply.json()).data;
const stream = new EventSource(
`https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages/${assistantId}/stream`,
{
fetch: (input, init) => fetch(input, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${TOKEN}` },
}),
},
);
stream.addEventListener("message.delta", (event) => {
const { payload } = JSON.parse(event.data);
console.log("Delta:", payload.delta);
});
["run.settlement.completed", "run.failed", "run.error", "run.cancelled", "run.degraded"]
.forEach((type) => stream.addEventListener(type, () => stream.close()));
};Automatic recovery during provider interruptions
If a model times out or its provider is temporarily unavailable or rate limited, the conversation can continue on another eligible model. The account's provider permissions, model capabilities and execution budget still apply.
If every eligible route is unavailable, the task waits with its progress saved. Temporary provider interruptions are retried automatically. Completed tool results and the original objective remain available to the continuation, including conversations addressed to an agent. Execution limits and permanent refusals retain their own bounded recovery behavior.
The run.paused event carries status: "waiting_user" and recovery: { mode: "automatic", retryAt } for this automatic wait. retryAt is an ISO timestamp for the next scheduled attempt, not a guaranteed completion time. Message history exposes the same recovery object while the run is waiting, so a page reload can restore the waiting indicator. Human approval and clarification waits do not carry this automatic-recovery marker.
Display an automatic retry indicator instead of continuing to show stale thinking text. On run.resumed, follow resumeRunId and messageId to the continuation; the user does not need to submit another message. The continuation eventually produces its own final message and settlement events.
Long messages and model capacity
A message has no character limit of its own. Three limits apply instead, and each fails in a different place.
| Limit | Checked | What you see |
|---|---|---|
| Request body size | Before anything is created | 413 with payload_too_large in the standard error envelope. No message and no run exist. Shorten the text and send it again. |
| The context budget of the model route for your plan | When you send the message, before a run exists | 403 with prompt_context_limit_exceeded. The message Requested route exceeds the <n> token context budget gives the budget. Shorten the message. |
| The model's context window | After the message is accepted, when the run starts | POST succeeds as usual and returns the run. The run then moves to a model with a larger window, or fails with financial_execution_input_exceeds_capacity. |
When the message is larger than the model's window
A message that was accepted can still be larger than the context window of the model chosen for it. The run is refused before any model is called, and the refused step is not charged. Work completed before the refusal is billed as usual.
- You did not set
modelorprovider. The run moves to a model your plan can use that has a larger context window, and carries on. The stream emitsrun.model.switchedwithreason: "financial_execution_input_exceeds_capacity", and you are billed for the replacement model as for any other run. If no such model is available, the run fails as below. - You set
modelorprovideron the request. Your choice is kept, so the run fails. Send a shorter message, or leave the model unpinned.
A refused run is terminal. It ends with the stream event run.failed, which carries the code and the sizes behind it:
{
"runId": "00000000-0000-4000-8000-000000000001",
"messageId": "00000000-0000-4000-8000-000000000002",
"code": "financial_execution_input_exceeds_capacity",
"capacity": {
"requiredInputTokens": 78464,
"contextWindowTokens": 65536,
"modelId": "00000000-0000-4000-8000-000000000003"
}
}code is the field to branch on. capacity appears only with this code: requiredInputTokens is a safe upper bound for the request in tokens, contextWindowTokens is the window of the model that was too small, and modelId names that model. Compare the two numbers to see how much shorter the message must be.
A client that reconnects after the stream closed reads the same outcome from the message list: the assistant message has status: "failed" and errorCode: "financial_execution_input_exceeds_capacity". Its content holds a short explanation for people; do not parse it.
Endpoints
| Method | Path | Description | Auth |
|---|---|---|---|
| GET | /ai/sessions/:sessionId/messages | List messages (cursor/page paginated) | JWT + Entitlement |
| POST | /ai/sessions/:sessionId/messages | Send a message (triggers AI run) | JWT + Entitlement |
| GET | /ai/sessions/:sessionId/messages/:messageId/stream | SSE message stream | JWT + Entitlement |
| POST | /ai/sessions/:sessionId/messages/:assistantMessageId/stop | Stop generation | JWT + Entitlement |
| POST | /ai/clarifications/:clarificationId/answer | Answer a question card (details) | JWT + Entitlement |
| POST | /ai/clarifications/:clarificationId/skip | Skip a question card (details) | JWT + Entitlement |
GET /ai/sessions/:sessionId/messages
Description
List the newest messages first, in fixed pages of 10. Use meta.nextCursor to load older messages. A limit parameter does not change the page size.
Authentication: JWT Bearer token + active AI entitlement required.
Request
- Headers:
Authorization: Bearer <token> - Path params:
sessionId
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
cursor | string | No | Message ID from meta.nextCursor; returns older messages |
offset | number | No | Offset for page-based pagination |
page | number | No | One-based page fallback; ignored when cursor is set |
chainyId | string (uuid) | No | Filter by Project. Returns 404 if the session is not associated with this Project. |
Response
Response Example
{
"data": [
{
"id": "cm5msg001",
"role": "user",
"content": "How can I improve my vocabulary retention rate?",
"createdAt": "2026-03-17T10:05:00.000Z"
},
{
"id": "cm5msg002",
"role": "assistant",
"content": "Spaced repetition is one of the most effective techniques...",
"status": "completed",
"toolCalls": [
{
"id": "tc_abc123",
"toolKey": "memory.search",
"input": { "query": "vocabulary retention" },
"status": "completed",
"output": { "total": 2 },
"error": null,
"executionMs": 64
}
],
"suggestions": [
{
"suggestion": "Can you turn that into a 7-day vocabulary executable workflow?",
"priority": 1
},
{
"suggestion": "What should I do when I keep forgetting the same words?",
"priority": 2
}
],
"tokensUsed": 850,
"createdAt": "2026-03-17T10:05:00.000Z"
}
],
"meta": {
"limit": 10,
"offset": 0,
"page": 1,
"hasMore": false,
"hasNextPage": false
}
}Response Fields
meta.nextCursor, when present, is the message ID to pass as cursor for older messages. It is omitted on the last page. No total count is returned. With a cursor, offset and page are omitted. An empty history page currently returns 404 rather than an empty data array.
| Field | Type | Description |
|---|---|---|
id | string | Message ID |
role | string | user or assistant |
content | string | null | Message content (null while generating) |
status | string | Assistant messages: running, completed, stopped, failed. A reply paused on a question card is waiting_user, and superseded once its card is answered and the conversation has continued in a new reply. |
suggestions | object[] | Follow-up suggestion cards returned separately from the assistant markdown. Empty when disabled, unavailable, or not generated. |
errorCode | string | Present only when status is failed: the typed reason, for example financial_execution_input_exceeds_capacity (see Long messages and model capacity). Branch on it, not on content. |
runId | string | null | ID of the AI run that produced this message. Use this to attach a stream listener on page reload. Present on all assistant messages once the run is created. |
clarifications | object[] | Question cards the assistant asked in this message, with their answers once given. Empty when there are none. See AI Question Cards. |
toolCalls | object[] | null | For Chao sessions: list of tool calls made during this message. See Tool Call Fields below. |
modelId | string | null | ID of the model that generated the response |
modelName | string | null | Display name of the model |
providerKey | string | null | Provider identifier (e.g. "anthropic", "openai") |
createdAt | string | ISO 8601 |
Tool Call Fields
Each entry in toolCalls represents one tool invoked by Chao during this message:
| Field | Type | Description |
|---|---|---|
id | string | Tool call ID (matches SSE callId, toolCallId, or stepId) |
toolKey | string | Tool name (e.g. "bits.create", "chainies.list") |
input | object | Arguments Chao passed to the tool |
status | string | pending, executing, completed, failed, degraded, rejected, or skipped |
output | object | null | Tool result (present when status is completed) |
error | string | null | Error message (present when status is failed) |
executionMs | number | null | Execution duration in milliseconds |
toolCalls is persisted and returned on every history request. On page reload, reconstruct tool cards from this field and re-attach a stream listener when the assistant message still has an active runId.
Normalize live SSE payloads into the same card shape:
| Normalized field | Preferred lookup |
|---|---|
toolKey | payload.toolKey ?? payload.key |
callId | payload.callId ?? payload.toolCallId ?? envelope.stepId |
input | payload.input ?? payload.args |
output | payload.data ?? payload.output |
When payload.activity exists, render card title, detail, status, and subject from that object.
Code Examples
Use the id from Create a Session's response (data.id) as $SESSION_ID. For the Project filter, use the id from Create Project as $CHAINY_ID.
curl "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages" \
-H "Authorization: Bearer $TOKEN"# Filter by project:
curl "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages?chainyId=$CHAINY_ID" \
-H "Authorization: Bearer $TOKEN"POST /ai/sessions/:sessionId/messages
Description
Send a user message to a session, which triggers an AI run to generate the assistant response.
Authentication: JWT Bearer token + active AI entitlement required.
Request
- Headers:
Authorization: Bearer <token>,Content-Type: application/json - Path params:
sessionId
Request Body
| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
content | string | Yes | Non-empty | Message content. There is no character limit of its own: the request body size limit bounds the request, and the model's context budget bounds what a run can read. See Long messages and model capacity. This applies to every caller, including the seed message returned by feature endpoints such as POST /productivity/priority-analysis/runs. |
model | string | No | Active model key | Override the model for this message |
effortMode | string | No | "basic", "thinking", or "pro" | High-level model tier preference. basic uses a standard model, thinking selects a thinking-capable model, pro selects the highest-capability tier. Overrides the session-level effortMode if both are set. Exact model selection remains a backend hint. |
provider | string | No | Lowercase identifier (e.g. openai) | AI provider key. Requires a paid plan with the corresponding provider entitlement. |
capabilityKey | string | No | ai.search.web, ai.research.deep, ai.image.generate, ai.video.generate, ai.audio.generate | Explicit Chao capability to execute deterministically. When set, the matching capability-specific parameters are accepted (see Capability Parameters). |
attachmentIds | string[] | No | Valid file IDs (UUID v4) | Array of file IDs to attach |
memoryIds | string[] | No | Valid memory IDs (UUID v4) | Optional memory items to pin into the run |
idempotencyKey | string | No | — | Client-side dedupe key for retries |
parameters | object | No | Capability-specific params | Long-term contract for capability-specific parameters. See Capability Parameters. |
structuredBlocks | object[] | No | Mention/media blocks | Structured user-side blocks such as agent mentions or media references |
renderCapability | object | No | { surface, renders } | What your client can draw. Include "question_form" in renders to let the assistant ask choice questions as cards. See AI Question Cards. |
Capability-specific fields (such as durationSeconds, aspectRatio, generateAudio, etc.) may also be sent at the top level for backward compatibility. See the section below.
Capability Parameters
When capabilityKey is set, the message endpoint accepts the parameters that capability declares. Two equivalent request shapes are supported:
- Top-level fields (current client compatibility):json
{ "content": "lo-fi beat with a deep bass line", "capabilityKey": "ai.audio.generate", "durationSeconds": 20, "bpm": 90, "styleTokens": ["lo-fi", "chill"] } - Nested
parametersobject (long-term contract, recommended for new code):jsonWhen both forms are present, nested values win on collision.{ "content": "lo-fi beat with a deep bass line", "capabilityKey": "ai.audio.generate", "parameters": { "durationSeconds": 20, "bpm": 90, "styleTokens": ["lo-fi", "chill"] } }
Accepted parameters per capability:
| capabilityKey | Accepted parameters |
|---|---|
ai.audio.generate | durationSeconds (5–30), bpm (40–220), styleTokens (string[], ≤16 items, ≤64 chars each). See Audio Generation. |
ai.image.generate | aspectRatio (W:H), quality (standard|hd|auto), numImages / numberOfImages (alias for count, 1–4), seed (int), negativePrompt (≤4000 chars), size (1024x1024|1792x1024|1024x1792), style (vivid|natural), resolution, provider, model, activeImageId. See Generative Media. |
ai.video.generate | aspectRatio (16:9|9:16|1:1|4:3|3:4|21:9), duration (1–60, accepts numeric strings), resolution (480p|720p|1080p|4k), size (WxH), generateAudio (boolean), negativePrompt, seed (int), styleTokens, inputImageUrl, inputVideoUrl, referenceImages[], referenceVideos[], provider (kling|veo|sora), model. See Video Generation. |
ai.search.web | maxResults (1–20) |
ai.research.deep | depth (standard|deep) |
Capability fields belonging to a different capability than the one selected are rejected with a precise error (bpm is only valid for ai.audio.generate). Truly unknown fields are also rejected with unknown property X. Plain chat (no capabilityKey) keeps the original DTO contract — extra fields are still rejected.
Response
Response Example
{
"data": {
"sessionId": "$SESSION_ID",
"userMessage": {
"id": "cm5msg001",
"role": "user",
"content": "How can I improve my vocabulary retention rate? I keep forgetting words after a few days.",
"createdAt": "2026-03-17T10:05:00.000Z"
},
"assistantMessage": {
"id": "cm5msg002",
"role": "assistant",
"content": "",
"suggestions": [],
"createdAt": "2026-03-17T10:05:00.000Z"
},
"run": {
"id": "cm5run003",
"status": "queued"
}
}
}The assistant message shell is returned immediately with suggestions: []. Suggestions are generated together with the assistant reply and are delivered via history reads and the message.suggestions SSE event in the same tick as message.completed.
Response Fields
| Field | Type | Description |
|---|---|---|
userMessage.id | string | User message ID |
userMessage.role | string | Always user |
userMessage.content | string | Message content |
userMessage.createdAt | string | ISO 8601 |
assistantMessage.id | string | Assistant message ID |
assistantMessage.role | string | Always assistant |
assistantMessage.content | string | Empty string while generating |
assistantMessage.suggestions | object[] | Always [] in the immediate POST response shell |
run.id | string | Associated AI run ID |
run.status | string | Initial run status, usually queued |
Pending question card
While the assistant is waiting for an answer to a question card, the session accepts no new message. The request is refused with 409 and clarification_answer_required, and error.details names the clarificationId and runId to answer, skip or stop. See AI Question Cards.
Error Example
{
"error": {
"code": "bad_request",
"message": "bpm is only valid for ai.audio.generate; unknown property foo",
"details": {
"fields": [
{ "field": "bpm", "message": "bpm is only valid for ai.audio.generate", "capabilityKey": "ai.audio.generate" },
{ "field": "foo", "message": "unknown property foo" }
]
}
},
"meta": { "requestId": "<request-id>" }
}Code Examples
Use the id from Create a Session's response (data.id) as $SESSION_ID.
curl -X POST https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"content": "How can I improve my vocabulary retention rate? I keep forgetting words after a few days."
}'GET /ai/sessions/:sessionId/messages/:messageId/stream
Description
Connect to a Server-Sent Events stream to receive incremental content as an assistant message is generated.
Authentication: JWT Bearer token + active AI entitlement required.
Request
- Headers:
Authorization: Bearer <token>,Accept: text/event-stream - Path params:
sessionId,messageId
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
park | string | No | Set to 1 to let the server close the connection while the reply waits on a question card. The stream then ends with a stream.parked event that says when to connect again. Without it the connection stays open while the card is pending. See Waiting without an open connection. |
Response
Response Example
event: message.delta
data: {"eventId":1,"type":"message.delta","runId":"cm5run003","payload":{"delta":"Spaced repetition is one of the most "}}
event: message.delta
data: {"eventId":2,"type":"message.delta","runId":"cm5run003","payload":{"delta":"effective techniques for long-term retention. "}}
event: message.delta
data: {"eventId":3,"type":"message.delta","runId":"cm5run003","payload":{"delta":"Here are some strategies tailored to your chain..."}}
event: message.completed
data: {"eventId":4,"type":"message.completed","runId":"cm5run003","payload":{"messageId":"cm5msg002","content":"Spaced repetition is one of the most effective techniques for long-term retention. Here are some strategies tailored to your chain..."}}Response Fields
| Field | Type | Description |
|---|---|---|
event | string | SSE event type such as message.delta, message.completed, tool.started, tool.completed, run.error |
data.payload.delta | string | Incremental content token(s) for message.delta |
data.payload.content | string | Full assistant content for message.completed |
data.payload.messageId | string | Assistant message ID when present |
Code Examples
Use $SESSION_ID from Create a Session's response (data.id), and use the id from Send a Message's response (data.assistantMessage.id) as $MESSAGE_ID.
curl -N "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages/$MESSAGE_ID/stream" \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: text/event-stream"POST /ai/sessions/:sessionId/messages/:assistantMessageId/stop
Description
Stop an in-progress assistant message generation.
Authentication: JWT Bearer token + active AI entitlement required.
Request
- Headers:
Authorization: Bearer <token> - Path params:
sessionId,assistantMessageId
Response
Response Example
{
"data": {
"id": "cm5msg002",
"status": "stopped",
"content": "Spaced repetition is one of the most effective techniques for long-term retention. ",
"stoppedAt": "2026-03-17T10:05:05.000Z"
}
}Response Fields
| Field | Type | Description |
|---|---|---|
id | string | Message ID |
status | string | Always stopped |
content | string | Partial content generated before stopping |
stoppedAt | string | ISO 8601 timestamp of stop |
Code Examples
Use $SESSION_ID from Create a Session's response (data.id), and use the id from Send a Message's response (data.assistantMessage.id) as $ASSISTANT_MESSAGE_ID.
curl -X POST https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages/$ASSISTANT_MESSAGE_ID/stop \
-H "Authorization: Bearer $TOKEN"