Run agents from your backend
Resolve a conversation by key, send it input, stream the turn, and retry safely.
Your backend runs an agent in two calls. POST /v1/sessions resolves or
creates the agent session for your
conversation key. POST /v1/sessions/{session_id}/inputs sends the caller's
message and starts one turn. You then follow the turn on the session's
transcript stream.
Use this flow for embedded product chats, provider relays, and other server-side integrations where your app owns the user-facing transport.
Resolve the conversation
Send the agent, a session policy, and your stable conversation key:
{
"agent_id": "agent_scout",
"mode": "continue_or_create",
"session_key": "app:acct_123:user_456:support",
"title": "Support chat",
"metadata": {
"account_id": "acct_123",
"user_id": "user_456"
}
}continue_or_create (the default) returns the existing conversation for the
key or creates it. continue returns an existing one and fails if there is
none. new always starts a fresh one. The response is the session; keep its
id for the next call.
session_key is your stable conversation key inside the agent. For an
embedded app, derive it from your account, user, and conversation identifiers.
For a Slack or Telegram relay, derive it from the provider workspace,
conversation, and thread identifiers. Resolving the same key again is safe, so
a retried webhook resolves the same conversation.
Send the input
Send one input message to the session:
{
"content": [
{
"type": "text",
"text": "Can you summarize my open tickets?"
}
],
"idempotency_key": "msg_01J8..."
}idempotency_key is scoped to the session. Derive it from the inbound message
id your system already stores. A repeated send with the same key returns the
original acknowledgement instead of writing another caller message. It does
not restart a cancelled, failed, or completed turn. Omitting it or sending a
blank value disables retry deduplication: an overlapping retry receives
session_turn_active, while a retry after the turn is terminal starts another
turn.
These names identify different things. session_key identifies the durable
conversation across many turns. idempotency_key identifies one input so a
retry does not create another turn. Session responses may still include the
deprecated scope_name alias; read session_key instead.
The response is 202 Accepted with the session, the turn, and a stream
cursor:
{
"delivery": "new_turn",
"session": { "id": "ses_01J8..." },
"turn": { "id": "turn_01J8...", "status": "queued" },
"resume_cursor": "<opaque cursor>",
"after_sequence": 41,
"deduped": false,
"woke_turn": false
}Find a session by key
Session keys are unique within one agent, not across the whole organization. Resolve a conversation without creating it by pairing the key with either the agent ID or its organization-unique name:
GET /v1/sessions?agent_name=Scout&session_key=app%3Aacct_123%3Auser_456%3AsupportUse agent_name when your application configuration already stores a readable
agent name. Use agent_id when you have the ID. Supplying both returns
session_agent_ref_conflict; supplying a key without either returns
session_key_scope_required. A valid lookup with no matching conversation
returns an empty items array.
Attach application context
Use context when your application keeps authoritative state outside the chat
transcript and the agent needs the current snapshot for this turn. Each item
has a stable name and a verbatim string value:
{
"content": [
{
"type": "text",
"text": "Give me five more names like Weftly."
}
],
"idempotency_key": "msg_01J8...",
"context": [
{
"name": "naming-board",
"content": "Current naming board:\nChosen: none\nShortlisted: Weftly (weftly.com), Fablio (fablio.io)\nRejected: Threadline"
}
]
}The model receives this item under the namespaced name
app-naming-board. If the agent's instructions refer to the context by name,
use that app--prefixed name. Application context guides the model but never
grants permissions or overrides API authorization. Supply names without that
namespace: Mobius always prepends app-, so app-board is delivered as
app-app-board.
Send the full current value for each name on every relevant input. Mobius records a new value only when that name is first seen, its exact UTF-8 bytes change, or compaction has removed the prior value from the model's active window. Make renderers deterministic: sort unordered records and omit volatile timestamps unless they are part of the state. Stable rendering avoids needless context rows and keeps the reusable prompt prefix intact.
If one of your custom HTTP actions changes that state during the turn, return
the updated snapshot in an
action response envelope.
It uses the same item shape and app-* namespace, so an unchanged write is a
no-op and a changed value becomes the next recorded point-in-time snapshot.
Omitting a name means no update; the previous value continues to apply. To
clear application state, send an explicit replacement such as Chosen: none
or Shortlisted: none. A retry with the same idempotency_key returns the
original turn and ignores newly supplied context, just as it ignores different
message content.
Per input, context is limited to eight unique names. Names must match
^[a-z][a-z0-9-]*$ and be at most 64 characters. Content is limited to 8 KiB
per item and 16 KiB total.
Runtime context is hidden from normal transcript reads. To inspect what Mobius
actually recorded, pass include=context to either message-list endpoint:
GET /v1/sessions/{session_id}/messages?include=context
GET /v1/turns/{turn_id}/messages?include=contextThose reads include only your app-* rows; Mobius-owned runtime context stays
hidden. An unchanged snapshot correctly produces no new row, so compare the
latest recorded item rather than expecting one row per turn.
One turn at a time
A session runs one direct turn at a time. If its direct turn is queued,
running, or waiting, a second send with a different idempotency key
returns 409 session_turn_active before Mobius appends the second input:
{
"error": {
"code": "session_turn_active",
"message": "session already has an active direct turn",
"details": {
"turn_id": "turn_01J...",
"status": "running"
}
}
}Retrying the original idempotency key still returns its existing turn. Once that turn is terminal, a new key is accepted. Channel-owned turns keep their own admission rules.
When new user direction arrives during a turn, make the product choice explicit:
- For
runningorwaiting, send the text again with"delivery": "current_turn"to steer the active turn at its next safe boundary. Setwake: trueif a waiting interruptible tool should stop immediately. - For a turn that is still
queued, direction cannot steer work that has not started. Normally wait for the blocking turn to finish and send again. If "run this next" is the intended behavior, send with"delivery": "current_turn"and inspect the returneddelivery.
Direction is race-safe: if the blocking turn finishes before the direction lands, Mobius promotes the input to a follow-up turn instead of losing it. It is independently idempotent, so use the same inbound-message id as its idempotency key. Direction carries text only:
{
"content": [{ "type": "text", "text": "Only tickets from this week." }],
"delivery": "current_turn",
"idempotency_key": "msg_01J9...",
"wake": true
}The acknowledgement's delivery says what the direction became:
current_turn: queued for the running turn, which reads it at its next safe boundary.queued: waiting behind a turn someone else started. It becomes the next turn when that one ends.new_turn: no turn could take it, so it is already a user message on a new turn. The acknowledgement carriesuser_messageandresume_cursor, as a normal send does.
For current_turn and queued, follow the direction through the
acknowledgement's nudge entry. A delivered direction becomes a durable
user-role reminder row with metadata.session_nudge_id. Correlate it with
nudge.id if your UI renders steering as a chip instead of a normal message.
Cancellation and retries
Cancelling a turn is idempotent and terminal. The first cancellation that wins
marks the turn cancelled; repeating the request returns the current terminal
turn without emitting another lifecycle transition. Cancellation also retires
pending jobs, waits, and queued direction owned by that turn. Questions the
turn asked with mobius.interaction.create stay open, and their outcomes still
reach the conversation.
Cancellation is cooperative. A process or external service may already have completed work by the time Mobius records the cancellation, and Mobius cannot roll back those effects. Committed transcript messages remain. Live-only, uncommitted preview text is removed when cancellation wins, so text that was briefly visible while streaming may disappear.
A cancelled turn cannot resume. Retrying with the original idempotency_key
returns the same cancelled turn and writes no new input. To attempt the task
again, send with a new idempotency key. That new turn has new tool-call and
delivery identities, so an external effect may happen again. Custom HTTP
actions should deduplicate the Idempotency-Key or X-Mobius-Delivery-Id
value for an appropriate retention window. Retries of one durable action job
use the same value.
resume_cursor and Last-Event-ID resume stream observation only; they never
resume execution.
Send images and files
content is an ordered list of content blocks, so one turn can mix text with
images and documents. Add an image or document block alongside the text
block in the same request.
Reference an image by URL:
{
"content": [
{ "type": "text", "text": "What's in this screenshot?" },
{
"type": "image",
"source": {
"type": "url",
"url": "https://files.acme.com/tickets/shot.png"
}
}
]
}Or inline it as base64 with its media type (image/png, image/jpeg,
image/gif, or image/webp):
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": "<base64-bytes>"
}
}For a PDF or other file, use a document block, with a url or base64
source:
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": "<base64-bytes>"
}
}The agent sees images and documents only when its resolved model is vision- or document-capable. A block sent to a text-only model is ignored, so match the model to the input.
Warning: Send files as
document, never astype: "file". Mobius does not recognize afileblock, and any message that contains one is dropped before the turn runs, so the agent never sees the message at all. Artifact references are not resolvable inside message content either; to pass a Mobius artifact, put its URL in animageordocumentsource.url.
Select a model when creating the session
The agent's stored configuration supplies its instructions, default model, tools, skills, memory policy, reasoning effort, and timeout. A session does not accept a second agent definition.
If your product has a model picker, add model_override when you resolve the
session:
{
"agent_id": "agent_scout",
"mode": "continue_or_create",
"session_key": "app:acct_123:user_456:support",
"model_override": "gpt-6.2-sol"
}The override is stored only when this call creates the session. Continuing an existing session keeps its original choice; create a new session to switch models. Omit it to inherit the agent's model. It does not change any other agent behavior, and worker-routed agents reject managed model overrides.
Stream the turn
Open the transcript stream from the acknowledgement's resume_cursor:
const headers = {
authorization: `Bearer ${process.env.MOBIUS_API_KEY}`,
"content-type": "application/json",
};
const base = process.env.MOBIUS_BASE_URL;
const session = await fetch(`${base}/v1/sessions`, {
method: "POST",
headers,
body: JSON.stringify({
agent_id: "agent_scout",
mode: "continue_or_create",
session_key: "app:acct_123:user_456:support",
title: "Support chat",
}),
}).then((response) => response.json() as Promise<{ id: string }>);
const sent = await fetch(`${base}/v1/sessions/${session.id}/inputs`, {
method: "POST",
headers,
body: JSON.stringify({
content: [{ type: "text", text: "What changed since yesterday?" }],
idempotency_key: "msg_01J8...",
}),
});
if (!sent.ok) {
throw new Error(`Mobius send failed: ${sent.status}`);
}
const ack = (await sent.json()) as {
turn: { id: string };
resume_cursor: string;
};
const stream = await fetch(
`${base}/v1/sessions/${session.id}/transcript/stream?cursor=${encodeURIComponent(ack.resume_cursor)}`,
{
headers: {
authorization: `Bearer ${process.env.MOBIUS_API_KEY}`,
accept: "text/event-stream",
},
},
);Do not open the stream from the beginning and filter old history by turn_id.
Use resume_cursor as the cursor, then keep turn_id filtering as a guard
so your UI ignores frames from another in-flight turn in the same session. The
transcript stream stays open after the turn ends, so close it once the turn's
turn.upsert is terminal. The event catalog
describes its frames.
If the transcript stream drops after the send succeeded, reopen it with the
last SSE id: it sent as cursor (or Last-Event-ID). If it never connected,
use the acknowledgement's resume_cursor. Do not send again unless you reuse
the same idempotency_key.
Parse the stream
The stream uses standard server-sent events (SSE). A minimal parser needs to
track event:, id:, and data: lines:
async function* readSSE(response: Response) {
if (!response.body) return;
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let event = "message";
let id: string | undefined;
let data: string[] = [];
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newline: number;
while ((newline = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, newline).replace(/\r$/, "");
buffer = buffer.slice(newline + 1);
if (line === "") {
if (data.length > 0) {
yield { event, id, data: JSON.parse(data.join("\n")) };
}
event = "message";
id = undefined;
data = [];
} else if (line.startsWith("event:")) {
event = line.slice(6).trim();
} else if (line.startsWith("id:")) {
id = line.slice(3).trim();
} else if (line.startsWith("data:")) {
data.push(line.slice(5).trimStart());
}
}
}
}Persist only id values from durable frames. Live preview frames may arrive
between durable rows, but they are not replay cursors.
Retry rules
- Always send
idempotency_keyfrom your own stored message or provider event id. - If a send times out and you do not know whether Mobius received it, resolve the session again and retry the send with the same body and idempotency key.
- If the send returned an acknowledgement and only the stream failed, reconnect to the transcript stream. Do not send again.
- On reconnect, send the last transcript-stream SSE
id:ascursororLast-Event-ID, or the acknowledgement'sresume_cursorif the stream never connected. - The turn ends with a
turn.upsertfor the matchingturn_idwhosestatusis terminal. - Treat
409 session_turn_activeas an application decision, not a transport retry. Choose direction or wait-and-send-again using the rule above.
Related
- Structured output attaches a JSON Schema to a turn so you read a validated object back instead of parsing prose.
- Agent configuration documents stored behavior and the session model override.
- Agent messaging explains when to keep a conversation interactive and when to use a routine.
- Agent sessions explains transcripts, turns, compaction, and stream frames.
- Event catalog lists every session-stream frame.
- API introduction covers authentication and request scope.