Skip to content

AI Run Lifecycle ​

A Run represents a single execution of an AI feature, agent, or workflow. Runs follow a defined state machine and can be monitored in real time via Server-Sent Events (SSE).

Creating a Run ​

Start a run by calling the feature execution endpoint with at least one user message:

http
POST /api/v1/ai/features/:featureKey/runs
Authorization: Bearer <accessToken>
Idempotency-Key: create-run-abc123-1
Content-Type: application/json

{
  "messages": [
    { "role": "user", "content": "Analyze my weekly progress" }
  ]
}

The response identifies the request and, when a run was created, its runId. A newly accepted asynchronous run can report running in result.finishReason:

json
{
  "requestId": "00000000-0000-4000-8000-000000000002",
  "runId": "00000000-0000-4000-8000-000000000001",
  "result": { "finishReason": "running", "text": "" }
}

Use runId for subsequent run and stream requests. The response is not a run detail object; fetch the run separately for its current status.

Run States ​

A run commonly moves from queued through starting and running to a terminal status. Some runs pause for a tool or user, and cancellation has intermediate states.

StateDescription
queuedCreated and awaiting execution.
startingExecution is being prepared.
runningExecution is in progress; partial results may stream via SSE.
waiting_toolWaiting for a tool to finish.
waiting_userWaiting for user input or approval.
cancel_requestedA cancellation request has been recorded.
cancellingCancellation is in progress.
cancelledCancelled without a partial result.
partially_completedStopped after producing a partial result.
supersededReplaced by a continuation run.
completedFinished successfully.
failedFinished with an error.

For a current state, query the run or listen for run.status.changed events. Retrying creates a new run instead of changing a terminal run's state.

Real-Time Streaming (SSE) ​

Monitor a run's progress in real time by subscribing to its Server-Sent Events stream:

http
GET /api/v1/ai/runs/:runId/stream
Authorization: Bearer <accessToken>
Accept: text/event-stream

Feature runs send the completed response and a terminal settlement event. The identifiers below are synthetic UUIDs; use the IDs returned by your requests:

event: message.completed
data: {"eventId":1,"type":"message.completed","runId":"00000000-0000-4000-8000-000000000001","payload":{"content":"Based on your activity this week, choose one achievable next step.","deliveryState":"committed"}}

event: run.settlement.completed
data: {"eventId":2,"type":"run.settlement.completed","runId":"00000000-0000-4000-8000-000000000001","payload":{"status":"completed"}}

Event Types ​

EventDescription
run.status.changedThe run transitioned to a new state.
message.deltaA partial result from the AI model — always clean user-facing text, never raw reasoning.
message.completedThe final assistant message is available.
cot.stepA sanitized visible-reasoning step for an eligible Chao session. It preserves the session's think → tool → think order without exposing a private model transcript.
tool.*Chao tool-card, progress, approval, and result events.
run.error / run.failedAn error occurred during execution.
run.settlement.completedThe run is fully settled and terminal.

Client Implementation ​

Use fetch when a browser client must send an Authorization header. The native browser EventSource constructor does not accept custom headers. Set runId to the ID returned by run creation and TOKEN to your bearer token:

javascript
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(); }
}

Parse frames by their event: and data: fields to handle message.delta, run.settlement.completed, and run.error separately.

Agent-style Runs ​

Chao runs use a multi-step agent loop. A single user message can drive several iterations of planning, tool calls, and answer composition before producing the final assistant response. Multiple tool.started / tool.completed events may fire for one user message, followed by a single message.completed once the answer is verified.

If your client wants a structured, typed view of the agent's progress, subscribe to the agent.* event family alongside the existing message.* and tool.* events.

EventPayloadWhen
agent.phase.changed{ phase, iteration }Each high-level phase transition (planning, tool selection, observation, verification, finalization).
agent.verify.started{ iteration }The agent is checking its draft answer before sending it.
agent.verify.passed{ iteration, attempts }The verifier accepted the answer.
agent.verify.failed{ iteration, attempt, refinementReason }The verifier rejected the draft and the agent will refine.
agent.budget.exhausted{ reason }The agent reached its reasoning-step limit. The final message is a partial result.

phase values your client may want to render: plan_or_reason, tool_request, execute_tool, observe_tool_result, verify, message_draft, needs_approval, ask_clarification, final. Ignore any other phase value; it should not produce visible UI.

The platform guarantees message.completed always carries a non-empty content field, even if the agent budget was exhausted — in that case agent.budget.exhausted fires before message.completed and the content explains the partial result.

Clients that ignore agent.* events continue to work exactly as before.

Cancelling a Run ​

Request cancellation of a run that has not reached a terminal state:

http
POST /api/v1/ai/runs/:runId/cancel
Authorization: Bearer <accessToken>

Response:

json
{
  "cancelled": true
}

Account owners and admins can cancel any run in the workspace the request acts in; other members can cancel only runs they started. A member who has been removed from the account or suspended cannot cancel any run there, including runs they started. A runId that does not exist, or a run in another account or workspace that you did not start, is refused with 403; every other refusal returns { "cancelled": false }, the same answer as for a run that has already finished. See Cancel a run.

Cancellation is best-effort. Tokens already streamed are not retracted and may still be billed.

Retrying a Run ​

Create a new run using the feature key of an existing run that belongs to your account and workspace. Supply new user messages and an Idempotency-Key header so repeating the HTTP request does not create another paid run:

http
POST /api/v1/ai/runs/:runId/retry
Authorization: Bearer <accessToken>
Idempotency-Key: retry-run-abc123-1
Content-Type: application/json

{
  "messages": [
    { "role": "user", "content": "Analyze my weekly progress again" }
  ]
}

The response uses the same execution envelope as run creation:

json
{
  "requestId": "00000000-0000-4000-8000-000000000004",
  "runId": "00000000-0000-4000-8000-000000000005",
  "result": { "finishReason": "running", "text": "" }
}

The source run remains unchanged. Retry is not limited to runs with failed status, but the source must be accessible to the caller and eligible as a feature run.

Provider Resilience ​

When the selected model is temporarily unavailable, a run may be completed by an alternative model instead of failing. When a model switch occurs, the SSE stream emits a run.model.switched event:

json
{
  "event": "run.model.switched",
  "data": {
    "runId": "00000000-0000-4000-8000-000000000001",
    "fromProvider": "<previous-provider>",
    "toProvider": "<current-provider>",
    "reason": "unavailable"
  }
}

Credits are charged for whichever model ultimately handled the request. Whether a switch is available depends on your plan.

Saved Provider Preference ​

Save a default provider in your account preferences so you don't need to specify it on every message:

http
PATCH /api/v1/preferences
Authorization: Bearer <accessToken>
Content-Type: application/json

{ "preferredAiProvider": "openai" }

Valid values: google, openai, anthropic, mistral. Your plan must include access to the chosen provider. If your subscription changes or expires, the saved preference is silently ignored and requests fall back to your plan's default — no errors occur.

Per-message provider always takes precedence over the saved preference.

Credit Consumption ​

Each run consumes credits from your wallet. Credit use depends on the work performed and the final settlement. If a run fails due to a platform error (not a user error), credits may be refunded automatically. Check the wallet documentation for details on credit balance and usage.

Built with purpose. chainabit.com