SSE Streaming
AI run results are streamed in real time via Server-Sent Events (SSE). Connect to a run's stream endpoint to receive incremental tokens, tool progress, workflow steps, and terminal events as they occur.
Stream Endpoints
| Method | Path | Description | Auth |
|---|---|---|---|
| GET | /ai/runs/:runId/stream | Stream events for a feature run | JWT + Entitlement |
| GET | /ai/sessions/:sessionId/messages/:messageId/stream | Stream events for a chat message | JWT + Entitlement |
Connecting to a Stream
Open an SSE connection with a GET request and the Accept: text/event-stream header. Use fetch in browsers when you need an Authorization header; native EventSource does not support custom headers.
Use runId from the POST /ai/features/:featureKey/runs response as $RUN_ID.
// Use fetch to send the required Authorization header.
const runId = process.env.RUN_ID; // from POST /ai/features/:featureKey/runs response.runId
const streamController = new AbortController(); // Call abort() to stop viewing.
const response = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}/stream`, {
signal: AbortSignal.any([streamController.signal, AbortSignal.timeout(60_000)]),
headers: { Authorization: `Bearer ${TOKEN}`, Accept: "text/event-stream" },
});
if (!response.ok || !response.body) throw new Error("Could not open run stream");
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value, { stream: true })); // raw SSE frames
}
} finally {
try { await reader.cancel(); } finally { reader.releaseLock(); }
}import requests, os
run_id = os.environ["RUN_ID"] # from POST /ai/features/:featureKey/runs response["runId"]
with requests.get(
f"{BASE_URL}/ai/runs/{run_id}/stream",
headers={"Authorization": f"Bearer {TOKEN}"},
stream=True,
) as response:
response.raise_for_status()
for line in response.iter_lines(decode_unicode=True):
if line.startswith("data: "):
import json
event = json.loads(line[6:])
if "type" in event: # The connection preamble has no typed payload.
print(event["type"], event["payload"])Event Frame Format
Each event is sent as a standard SSE frame:
id: 1
retry: 3000
event: message.delta
data: {"eventId":1,"type":"message.delta","runId":"00000000-0000-4000-8000-000000000001","timestamp":"2026-03-17T14:00:00.123Z","payload":{"delta":"Hello"}}| Field | Description |
|---|---|
id | Monotonically increasing event ID (use for reconnection) |
retry | Reconnection interval in milliseconds (3000ms) |
event | Event type name |
data | JSON envelope with full event details |
Data Envelope Fields
| Field | Type | Description |
|---|---|---|
eventId | number | Sequential event counter for this run |
type | string | Event type (see table below) |
runId | string | The AI run UUID |
stepId | string | undefined | Step ID (for workflow/tool events) |
timestamp | string | ISO 8601 event timestamp |
payload | object | Event-specific data |
Event Types
30+ event types organized by category:
Connection
| Event Type | Description | Terminal |
|---|---|---|
stream.connected | Emitted once per connection after headers flush. Carries { runId }. Not buffered — will not appear in event replay. | No |
stream.parked | Sent only to a stream opened with ?park=1, when the run is waiting on a question card. The server then closes the connection. Not buffered — will not appear in event replay. See Question Cards. | No |
Capability Routing
| Event Type | Description | Terminal |
|---|---|---|
capability.resolved | The requested AI capability was routed to an executable path | No |
Run Lifecycle
| Event Type | Description | Terminal |
|---|---|---|
run.started | Run processing has begun | No |
run.status.changed | Run status transition | No |
run.model.switched | Active model changed (model unavailable or provider failover) | No |
run.cancel_requested | Cancellation was requested | No |
run.cancelling | Cancellation in progress | No |
run.cancelled | Run cancelled successfully | Yes |
run.failed | Run failed with an error | Yes |
run.error | Runtime/timeout error | Yes |
run.model.switched Payload
{
"eventId": 3,
"type": "run.model.switched",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2026-04-15T12:00:00.300Z",
"payload": {
"runId": "550e8400-e29b-41d4-a716-446655440000",
"fromModelKey": "gemini-2.0-flash",
"fromProvider": "google",
"toModelKey": "gemini-2.5-flash",
"toProvider": "google",
"reason": "model_not_found"
}
}reason is a machine-readable code, for example model_not_found or rate_limited. financial_execution_input_exceeds_capacity means the message was larger than the previous model's context window and the run moved to a model with a larger one; see Long messages and model capacity.
This event is informational — the run continues uninterrupted with the new model. Clients may surface it as a status indicator but do not need to take any action.
run.failed Payload
run.failed is terminal. Branch on payload.code; the assistant message content is explanatory text for people.
{
"eventId": 9,
"type": "run.failed",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2026-04-15T12:00:02.000Z",
"payload": {
"runId": "550e8400-e29b-41d4-a716-446655440000",
"messageId": "00000000-0000-4000-8000-000000000002",
"code": "financial_execution_input_exceeds_capacity",
"capacity": {
"requiredInputTokens": 78464,
"contextWindowTokens": 65536,
"modelId": "00000000-0000-4000-8000-000000000003"
},
"activity": {
"activityType": "workflow",
"origin": "execution",
"label": "The run could not be completed",
"renderHint": "status_card",
"status": "failed"
}
}
}capacity is present only for financial_execution_input_exceeds_capacity, a message too large for the model's context window. Other codes carry their own optional fields; ignore fields you do not recognize.
Message Streaming
| Event Type | Description | Terminal |
|---|---|---|
message.delta | Incremental token content (partial response) | No |
message.block.state.changed | A text block becomes retained progress or an unverified candidate, or is retracted | No |
message.retracted | Deprecated: repeats a retracted block transition for older clients | No |
message.completed | Full message has been assembled | No |
message.suggestions | Follow-up suggestion cards for the completed assistant message | No |
message.partially_completed | Partial completion (e.g., mid-cancel) | No |
Text preceding a tool call remains a progress step. If an answer needs verification or a missing tool call, its block becomes a candidate: retain it as a clearly labelled, unverified draft while the run continues. Neither transition ends the run.
A block that must be withdrawn arrives as message.block.state.changed with state: "retracted" and a reason code. Replace only the named blockId with a withdrawal notice; keep the other steps and tool activity. The run continues, and message history keeps the entry with state: "retracted" and empty text.
{
"eventId": 6,
"type": "message.block.state.changed",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2026-11-13T12:00:01.537Z",
"payload": {
"runId": "550e8400-e29b-41d4-a716-446655440000",
"messageId": "00000000-0000-4000-8000-000000000002",
"blockId": "00000000-0000-4000-8000-000000000008",
"state": "retracted",
"reason": "invalid_tool_protocol"
}
}Deprecated since 2026-11-13: message.retracted carries the same messageId, blockId and reason without state. It is still sent immediately after the message.block.state.changed frame for clients that predate the retracted state. Handle the retracted state and treat a message.retracted frame for a block you already withdrew as a no-op. It will be removed only after the minimum supported versions of the Chainabit CLI and mobile app handle the retracted state; this page will announce the removal date first.
Message history exposes turnLayout version 2 with ordered entries for retained text, tool references, approved thinking summaries and the final answer. content remains the final answer, not a concatenation of drafts. For an active message, render its saved steps and resume after eventCursor using Last-Event-ID. Older version 1 layouts remain readable. Show Stop from the active message/run status, including after a page reload, rather than from whether an SSE connection is open.
message.suggestions Payload
{
"eventId": 11,
"type": "message.suggestions",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2026-04-15T12:00:01.000Z",
"payload": {
"messageId": "00000000-0000-4000-8000-000000000006",
"suggestions": [
{
"suggestion": "Can you make that more practical for this week?",
"priority": 1
},
{
"suggestion": "What would the first 10 minutes look like?",
"priority": 2
}
]
}
}message.suggestions is emitted immediately after message.completed (in the same tick) and before run.settlement.completed. Suggestion chips are generated together with the assistant reply, so they arrive as soon as the reply is finalized. Clients should render these cards outside the assistant markdown so copying the answer does not include suggestion text.
Tool Calls
Tool events occur when Chao calls built-in tools (calendar lookups, task queries, projects/chains operations, memory, and write operations like creating or completing tasks) during a conversation. Multiple tools may be called in parallel within a single turn.
| Event Type | Description | Terminal |
|---|---|---|
tool.started | Tool call initiated | No |
tool.progress | Tool execution progress | No |
tool.completed | Tool call finished successfully | No |
tool.failed | Tool call failed (non-terminal — Chao handles errors gracefully) | No |
tool.degraded | Tool or capability returned a graceful fallback state | No |
tool.started Payload
{
"eventId": 4,
"type": "tool.started",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"stepId": "00000000-0000-4000-8000-000000000007",
"timestamp": "2026-04-12T10:00:01.100Z",
"payload": {
"toolKey": "calendar.today",
"callId": "00000000-0000-4000-8000-000000000007",
"input": {},
"activity": {
"activityType": "tool_read",
"origin": "chao",
"label": "Reading calendar",
"detail": "Starting tool execution.",
"renderHint": "tool_card",
"status": "active",
"subjectType": "calendar",
"subjectId": "00000000-0000-4000-8000-000000000007"
}
}
}tool.completed Payload
{
"eventId": 5,
"type": "tool.completed",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"stepId": "00000000-0000-4000-8000-000000000007",
"timestamp": "2026-04-12T10:00:01.160Z",
"payload": {
"toolKey": "calendar.today",
"callId": "00000000-0000-4000-8000-000000000007",
"executionMs": 58,
"success": true,
"data": { "items": [] },
"activity": {
"activityType": "tool_read",
"origin": "chao",
"label": "Calendar complete",
"detail": "Tool execution completed.",
"renderHint": "tool_card",
"status": "completed",
"subjectType": "calendar",
"subjectId": "00000000-0000-4000-8000-000000000007"
}
}
}tool.failed Payload
{
"eventId": 5,
"type": "tool.failed",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"stepId": "00000000-0000-4000-8000-000000000007",
"timestamp": "2026-04-12T10:00:06.105Z",
"payload": {
"toolKey": "bits.get",
"callId": "00000000-0000-4000-8000-000000000007",
"executionMs": 5001,
"success": false,
"error": "Tool execution timed out",
"activity": {
"activityType": "tool_read",
"origin": "chao",
"label": "Tool failed",
"detail": "Tool execution timed out",
"renderHint": "tool_card",
"status": "failed",
"subjectType": "bits",
"subjectId": "00000000-0000-4000-8000-000000000007"
}
}
}tool.failed is not a terminal event. Chao receives the error result and continues generating a response.
Treat payload.data as tool observation output. It can help render a card, but Chao's assistant message remains the user-facing synthesis.
Tool card normalization
Frontend and mobile clients should normalize tool-like payloads before rendering:
| 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 cards from activityType, origin, label, detail, renderHint, status, subjectType, and subjectId.
activityType tells a client what kind of step it is showing. For a tool step it is tool_read when the tool only looks something up, tool_write when it changes something (it creates, updates, moves, deletes, or generates) or when Chainabit cannot tell which, because a tool it does not recognize is treated as one that changes something, and approval while the call waits for the user and when that wait resolves or expires. The values thinking, workflow, and artifact describe steps that are not tool calls. Treat any value you do not recognize as a generic step.
Approval Gates
When Chao needs to perform a write or destructive action in a session with mode: "approval" (the default), it pauses and waits for the user to approve or reject the tool call. Three events manage this flow:
| Event Type | Description | Terminal |
|---|---|---|
tool.approval_required | Chao requires user approval before executing a write/destructive tool | No |
tool.approval_response | User approved or rejected the pending tool call | No |
tool.approval_timeout | Approval window expired (120 s by default); tool was not executed | No |
tool.approval_required Payload
{
"eventId": 6,
"type": "tool.approval_required",
"runId": "550e8400-e29b-41d4-a716-446655440000",
"stepId": "00000000-0000-4000-8000-000000000007",
"timestamp": "2026-04-12T10:00:01.500Z",
"payload": {
"runId": "550e8400-e29b-41d4-a716-446655440000",
"toolCallId": "00000000-0000-4000-8000-000000000007",
"toolKey": "bits.create",
"input": { "title": "Review Q2 metrics", "priority": "high" },
"approvalWindowMs": 120000,
"approval": {
"contractVersion": 1,
"state": "pending",
"digest": "EXAMPLE_DIGEST",
"nonce": "EXAMPLE_NONCE",
"expiresAt": "2026-04-12T10:02:01.500Z",
"approvalWindowMs": 120000,
"preview": null
},
"activity": {
"activityType": "approval",
"origin": "chao",
"label": "Approval needed",
"detail": "Review this action before Chao runs it.",
"renderHint": "status_card",
"status": "pending",
"subjectType": "bits",
"subjectId": "00000000-0000-4000-8000-000000000007"
}
}
}payload.approval is present on the content audience. Its digest and nonce are what you echo in the approve request, and expiresAt is the server clock for any countdown. preview is built by the server from the exact arguments that will run, or null when the tool declares no preview (show a generic card). It is shown as null above; for an external write such as sending an email it looks like this:
{
"kind": "email_send",
"operation": "gmail.send_email",
"connectorKey": "gmail",
"connectionId": "00000000-0000-4000-8000-000000000009",
"fields": [
{ "id": "to", "kind": "list", "value": ["person@example.com"], "truncated": false },
{ "id": "subject", "kind": "text", "value": "Hello", "truncated": false },
{ "id": "body", "kind": "multiline", "value": "Hi...", "truncated": true, "total": 5120 }
],
"implications": ["email_sent_immediately", "email_cannot_be_unsent"]
}No display sentences cross the wire; translate operation, field id and implications in your own catalogue. Render fields in the order given. preview.kind is one of email_send, email_draft, calendar_event_create, calendar_event_update, calendar_event_delete, drive_file_create, drive_file_share, generic_external_write, chain_create, chain_grant. The last two describe Chainabit's own operations (connectorKey is chainabit, connectionId is null): creating a Chain with its title, instructions and schedule, and allowing a Chain to use read-only tools. Field kind is text (up to 300 characters), multiline (up to 2,000), list (up to 25 items, value is string[]) or enum (a closed token such as a share role). When truncated is true, total is the original length (characters, or items for a list); show that the value is shown in part.
Approval outcome events
tool.approval_response carries approved, state and, when the call will not run, a typed code:
state | code | Meaning |
|---|---|---|
approved | none | The decision was recorded. |
rejected | approval_denied | The user rejected; optional reason is the user's text. |
cancelled | approval_cancelled | The run was stopped while approval was pending. |
rejected | approval_digest_mismatch | The operation changed after the approval was requested. |
tool.approval_timeout carries state: "expired", code: "approval_expired" and expiresAt. A call refused at execution time can also surface approval_replay_refused or approval_unavailable. A client never infers a terminal approval state from silence.
Submit the user's decision with one of these endpoints:
| Decision | Endpoint | Body |
|---|---|---|
| Approve | POST /ai/runs/:runId/tools/:toolCallId/approve | { "digest": string, "nonce": string } (required) |
| Reject | POST /ai/runs/:runId/tools/:toolCallId/reject | { "reason"?: string, "digest"?: string, "nonce"?: string } |
Approval is bound to the exact operation. Echo payload.approval.digest and payload.approval.nonce from tool.approval_required in the approve body. The server refuses to execute if the operation differs from the one that was approved. The nonce is single-use. Approve and reject do not use an Idempotency-Key. On reject, digest and nonce are optional and verified only when present.
Both routes need the same access to the run as the run itself. A successful response is { "data": { "resolved": true, "state": "approved" | "rejected", "replayed": boolean } }. replayed: true means an identical decision was already recorded (double click, second tab) and is also a success.
Approval states: pending, approved, rejected, expired, cancelled, consumed. rejected, expired, cancelled and consumed are terminal and never reopen. A retry is a new approval with a new toolCallId, digest and nonce.
| Result | HTTP | error.code |
|---|---|---|
Missing or malformed digest or nonce | 400 | approval_digest_required |
| Unknown request, or retention elapsed | 404 | approval_not_found |
digest differs from the stored one | 409 | approval_digest_mismatch |
nonce differs from the stored one | 409 | approval_nonce_mismatch |
| Cancelled (the run was stopped) | 409 | approval_cancelled |
| Already rejected or consumed | 409 | approval_already_decided |
| Approval window elapsed | 410 | approval_expired |
Errors use the standard envelope with error.details.state set to the current approval state. Branch on error.code, not on message.
After approval is recorded, Chao resumes and emits tool.approval_response, then tool.started and tool.completed or tool.failed. Approved means the decision was recorded; the tool runs only if the server can still consume the approval with a matching digest. If the call is rejected, expires, is cancelled or is refused, the tool does not run and Chao continues and explains the result.
Stopping the run with POST /ai/runs/:runId/cancel cancels a pending approval: the approval moves to cancelled, tool.approval_response carries code: "approval_cancelled", and the run ends with its terminal event. Nothing executes.
Clients should disable both buttons after the first click until the response arrives. On approval_expired, show an expired state with no actions except asking again; do not re-enable the old card. Clear streaming and Stop state on any terminal run event.
Question Cards
When the assistant pauses on a question card, these events describe it. By default the connection stays open while the card is pending. A stream opened with ?park=1 is closed by the server instead; see Waiting without an open connection.
| Event Type | Description | Terminal |
|---|---|---|
clarification.required | The assistant is waiting for answers to a card | No |
clarification.answered | The card was answered; carries the validated answers | No |
clarification.skipped | The user skipped the card. Not a cancellation: clarification.superseded follows with the continuation | No |
clarification.superseded | The paused reply was replaced by a continuation. Follow messageId and resumeRunId | Yes for this message's stream |
run.cancelled | The user stopped the paused reply instead of answering | Yes |
run.failed | The card expired unanswered. payload.code is clarification_expired | Yes |
clarification.required Payload
{
"eventId": 10,
"type": "clarification.required",
"runId": "00000000-0000-4000-8000-000000000001",
"timestamp": "2026-04-12T10:00:00.000Z",
"payload": {
"runId": "00000000-0000-4000-8000-000000000001",
"messageId": "00000000-0000-4000-8000-000000000021",
"clarificationId": "00000000-0000-4000-8000-000000000022",
"status": "waiting_user_input",
"reason": "Round 1 of 3",
"title": "Vocabulary quiz",
"schemaVersion": 1,
"questions": [
{
"id": "q1",
"question": "What does “acquiesce” mean?",
"inputType": "radio",
"required": true,
"allowCustomAnswer": false,
"options": [
{ "id": "a", "label": "To refuse strongly", "recommended": false },
{ "id": "b", "label": "To accept reluctantly", "recommended": false }
]
}
],
"expiresAt": "2026-04-13T10:00:00.000Z"
},
"v": 1
}The payload fields are described in AI Question Cards.
clarification.answered, clarification.skipped and clarification.superseded Payloads
{
"eventId": 11,
"type": "clarification.answered",
"runId": "00000000-0000-4000-8000-000000000001",
"payload": {
"runId": "00000000-0000-4000-8000-000000000001",
"clarificationId": "00000000-0000-4000-8000-000000000022",
"status": "answered",
"answers": [
{ "questionId": "q1", "inputType": "radio", "selectedOptionIds": ["b"], "customText": null }
]
},
"v": 1
}{
"eventId": 11,
"type": "clarification.skipped",
"runId": "00000000-0000-4000-8000-000000000001",
"payload": {
"runId": "00000000-0000-4000-8000-000000000001",
"clarificationId": "00000000-0000-4000-8000-000000000022",
"status": "skipped"
},
"v": 1
}{
"eventId": 12,
"type": "clarification.superseded",
"runId": "00000000-0000-4000-8000-000000000001",
"payload": {
"runId": "00000000-0000-4000-8000-000000000001",
"messageId": "00000000-0000-4000-8000-000000000023",
"clarificationId": "00000000-0000-4000-8000-000000000022",
"resumeRunId": "00000000-0000-4000-8000-000000000024",
"answerMessage": {
"id": "00000000-0000-4000-8000-000000000025",
"content": "1. What does “acquiesce” mean? → To accept reluctantly",
"createdAt": "2026-04-12T10:00:01.000Z"
}
},
"v": 1
}A card is either answered or skipped, so a stream carries clarification.answered or clarification.skipped, never both. messageId is the new assistant message that continues the conversation, and answerMessage is the user message the answers became. Every client watching the paused reply, not only the one that submitted the answers, receives these events, so a second tab or device updates without polling. Attach to the new message's stream to read the continuation.
If the user stops the paused reply instead, the stream ends with run.cancelled and the card's history status is cancelled. If the card expires unanswered, the stream ends with run.failed and payload.code clarification_expired, and the card's history status is expired.
Waiting without an open connection
A card can stay pending for up to 24 hours, and only keep-alive comments are sent while it waits. To avoid holding a connection open for that time, add ?park=1 to the chat message stream or to the run stream. Shortly after clarification.required is delivered, the server sends stream.parked and closes the connection. A later connection to the same stream while the card is still pending receives the replay, or nothing when Last-Event-ID is already past the card, and then stream.parked again.
retry: 15000
event: stream.parked
data: {"runId":"00000000-0000-4000-8000-000000000001","status":"waiting_user","reason":"clarification_required","clarificationId":"00000000-0000-4000-8000-000000000022","expiresAt":"2026-04-13T10:00:00.000Z","retryAfterMs":15000}| Field | Type | Description |
|---|---|---|
runId | string | The paused run. |
status | string | Always waiting_user. |
reason | string | Always clarification_required. |
clarificationId | string | The pending card. |
expiresAt | string | When the card expires (ISO 8601). |
retryAfterMs | number | How long to wait before connecting again. The same value is sent as the SSE retry: field. It grows the longer the card has been waiting, from about 15 seconds to about 5 minutes, but never much past expiresAt, so the first connection after expiry learns the outcome. |
stream.parked is not a terminal event: the reply is still waiting, so keep showing the card. Do not reconnect before retryAfterMs. After the user answers or skips, attach to the resume.messageId the response names; you do not need to reconnect to the paused reply. Once the card has expired, a new connection is no longer parked: it stays open until the run ends with run.failed.
Without ?park=1 the connection stays open while the card is pending.
Reasoning and Activity Summaries
Public clients should show safe activity summaries, not raw private Chain-of-Thought. Tool, approval, planning, and capability events may include payload.activity; use that object for status cards and timelines.
| Event Type | Description | Terminal |
|---|---|---|
tool.progress | Tool progress/activity update | No |
tool.approval_required | Approval activity card | No |
plan.step_added | Planned action summary | No |
capability.resolved | Capability routing summary | No |
Eligible sessions can also emit approved visible-reasoning summaries through cot.* events. Render them only when the disclosure contract permits it; see Visible reasoning. They are distinct from tool-card activity and never expose raw provider thinking deltas.
Workflow Steps
| Event Type | Description | Terminal |
|---|---|---|
workflow.step.started | Workflow step began | No |
workflow.step.completed | Workflow step finished | No |
workflow.step.failed | Workflow step failed | No |
workflow.completed | Entire workflow finished | Yes |
Settlement
| Event Type | Description | Terminal |
|---|---|---|
run.settlement.completed | Settlement done, run fully finished | Yes |
Terminal events cause the stream to close automatically after a short grace period.
Closing the client connection only detaches that viewer; it does not cancel the underlying run. Use the documented stop or cancel endpoint when the run itself must end.
Reconnection with Last-Event-ID
If the connection drops, reconnect using the Last-Event-ID header to resume from where you left off:
The server replays events after the supplied Last-Event-ID before switching to live delivery. Events are retained for replay for 15 minutes.
JavaScript Reconnection Example
This example allows five connection attempts and a 60-second total deadline. Pass an AbortController signal to stop viewing; this does not cancel the run. Permanent HTTP errors and oversized frames stop immediately.
async function connectStream(runId, { lastEventId = null, signal } = {}) {
const streamSignal = signal
? AbortSignal.any([signal, AbortSignal.timeout(60_000)])
: AbortSignal.timeout(60_000);
const terminalEvents = new Set([
"run.settlement.completed", "run.failed", "run.cancelled", "run.error",
"run.degraded", "workflow.completed",
]);
const maxFrameBytes = 2 * 1024 * 1024;
const encoder = new TextEncoder();
for (let attempt = 0; attempt < 5; attempt++) {
streamSignal.throwIfAborted();
const headers = { Authorization: `Bearer ${TOKEN}`, Accept: "text/event-stream" };
if (lastEventId !== null) headers["Last-Event-ID"] = String(lastEventId);
let reader;
try {
const response = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${encodeURIComponent(runId)}/stream`, {
headers, signal: streamSignal,
});
if (!response.ok) {
await response.body?.cancel();
if ([408, 429].includes(response.status) || response.status >= 500) {
throw new TypeError(`Temporary stream error: ${response.status}`);
}
throw new Error(`Stream request refused: ${response.status}`);
}
if (!response.body) throw new Error("Stream response has no body");
reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) {
if (encoder.encode(buffer.slice(0, end)).byteLength > maxFrameBytes) throw new Error("Stream frame is too large");
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
let event = "message";
let id;
const data = [];
for (const line of frame.split("\n")) {
if (line.startsWith(":")) continue;
const colon = line.indexOf(":");
const field = colon === -1 ? line : line.slice(0, colon);
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
if (field === "event") event = value;
if (field === "id" && !value.includes("\0")) id = value;
if (field === "data") data.push(value);
}
if (id !== undefined) lastEventId = id || null;
if (data.length) {
console.log(event, data.join("\n")); // Handle the event in your application.
if (terminalEvents.has(event)) return;
}
}
if (encoder.encode(buffer).byteLength > maxFrameBytes) throw new Error("Stream frame is too large");
}
} catch (error) {
streamSignal.throwIfAborted();
if (!(error instanceof TypeError)) throw error;
console.error("Stream disconnected:", error.message);
} finally {
if (reader) {
try { await reader.cancel(); } finally { reader.releaseLock(); }
}
}
if (attempt === 4) throw new Error("Stream reconnect limit reached");
await new Promise((resolve, reject) => {
const abort = () => { clearTimeout(timer); reject(streamSignal.reason); };
const timer = setTimeout(() => {
streamSignal.removeEventListener("abort", abort);
resolve();
}, 3000);
streamSignal.addEventListener("abort", abort, { once: true });
if (streamSignal.aborted) abort();
});
}
}Retry Behavior
The connection preamble contains retry: 3000, which tells compliant SSE clients when to reconnect. The fetch example above manages reconnection itself and sends the latest event ID in Last-Event-ID to replay missed events.
Error Events
The run.error event signals a runtime error during streaming:
| Payload Field | Type | Description |
|---|---|---|
error | string | Human-readable error message |
code | string | Error code — see table below |
| Code | Meaning |
|---|---|
execution_error | General error during LLM execution |
provider_error | Unhandled upstream provider failure |
empty_response | Provider returned no text and no tool calls. Eligible recovery attempts are bounded; this terminal error means recovery did not produce a result. |
run.error is a terminal event -- the stream closes after it is sent.
Stream Timeout
An SSE connection has a bounded lease (30 minutes by default). Lease expiry closes the connection without failing or cancelling the run. EOF is not terminal run evidence: reconcile with message history, and reconnect with Last-Event-ID if the run is still active. Recovery and execution have separate bounded budgets; their terminal status, not the connection lease, determines whether work has ended.
Connection Lifecycle
Simple run (no tool calls):
Client Server
│ │
│──── GET /ai/runs/:id/stream ────────►│
│ │ Set headers (text/event-stream)
│◄──── event: stream.connected ────────│
│◄──── (replay missed events) ─────────│
│ │
│◄──── event: message.delta ───────────│ (real-time events)
│◄──── event: message.delta ───────────│
│◄──── event: message.completed ───────│
│◄──── event: run.settlement.completed─│ (terminal)
│ │
│──── connection closed ───────────────│Chao run with auto tool calls:
Client Server
│ │
│──── GET /ai/runs/:id/stream ────────►│
│◄──── event: stream.connected ────────│
│◄──── event: run.started ─────────────│
│◄──── event: tool.started ────────────│ (card opens with activity)
│◄──── event: tool.progress ───────────│ (optional status update)
│◄──── event: tool.completed ──────────│
│◄──── event: message.delta ───────────│ (LLM writes response)
│◄──── event: message.completed ───────│
│◄──── event: run.settlement.completed─│ (terminal)
│ │
│──── connection closed ───────────────│Chao run with approval gate (default mode):
Client Server
│ │
│──── GET /ai/runs/:id/stream ────────►│
│◄──── event: stream.connected ────────│
│◄──── event: run.started ─────────────│
│◄──── event: tool.approval_required ──│ (run pauses)
│ │
│──── POST /ai/runs/:id/tools/:toolCallId/approve ─►│
│◄──── event: tool.approval_response ──│
│◄──── event: tool.started ────────────│
│◄──── event: tool.completed ──────────│
│◄──── event: message.delta ───────────│
│◄──── event: message.completed ───────│
│◄──── event: run.settlement.completed─│ (terminal)
│ │
│──── connection closed ───────────────│Keep-Alive
A heartbeat comment (: keep-alive) is sent every 15 seconds to prevent proxy timeouts.
Response Headers
| Header | Value |
|---|---|
Content-Type | text/event-stream; charset=utf-8 |
Cache-Control | no-cache, no-transform |
Connection | keep-alive |
X-Accel-Buffering | no |