> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oasm.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Run lifecycle

> What happens between sending a message and the last streamed token: conversation ownership, model resolution, system context assembly, the step loop and its continuation, streaming and resume, stopping, persistence and usage accounting

A **run** is one answer of the agent to one user message. It can last a second (a lookup in Ask mode) or an hour (an Agent-mode task with subagents). This page follows a run from the HTTP request to the last saved byte.

```mermaid theme={null}
sequenceDiagram
    participant C as Console
    participant API as Core API
    participant DB as PostgreSQL
    participant R as Redis
    participant M as LLM provider

    C->>API: POST /agents/messages/stream
    API->>DB: find or create conversation (owner check)
    API->>DB: save user message, load history
    API->>API: resolve model, check tool support
    API->>DB: assistant placeholder (status = streaming)
    API->>API: build system context and tool set
    loop steps (≤ max steps), continuation while plan steps remain
        API->>M: stream step
        M-->>API: text, reasoning, tool calls
        API->>API: permission → guard → approval → execute tool
        API-->>C: SSE chunks
        API->>R: append chunk to replay buffer
    end
    API->>DB: parts, tool calls, stats, metadata
    API-->>C: done
```

## The conversation

The console generates the conversation id itself, so the first message can stream before any round-trip. The core API then:

* **reuses** the conversation when the id exists and belongs to the caller,
* **creates** it with that id when it does not exist yet,
* **refuses with 404** when the id exists but belongs to another member — a client can never take over, or even detect, someone else's conversation.

Every read and write of conversations, messages, subagents and the plan filters on the workspace **and** the creator. A conversation started inside a [project](https://docs.oasm.io/ai-studio/project-chats.md) is additionally locked to that project, and every project-aware tool uses it. Sending a chat message needs only `agent.read`; what the agent can then do is decided per tool.

## The model

LLM connections belong to a **member**, not to the workspace: each member connects their own providers in [AI Studio](https://docs.oasm.io/ai-studio/connect-a-model.md), and the API key is stored encrypted under the workspace key. A run uses:

1. the provider and model picked in the composer for this message, if any,
2. otherwise the conversation's connection,
3. otherwise the member's default model.

Providers are reached through the [AI SDK](https://ai-sdk.dev/): OpenAI, Anthropic, Google Gemini, DeepSeek, OpenRouter, Vercel AI Gateway and other routers, plus any OpenAI-compatible endpoint. For providers that serve models without tool calling, the core API checks tool support **before** the stream starts, so the user gets a clear error instead of a run that silently cannot act.

The model's **context window**, prices and supported reasoning efforts come from a bundled snapshot of the [models.dev](https://models.dev/) catalog, unless the member overrides the window on the connection. Unknown models fall back to 128k tokens.

## The system context

The system context is assembled fresh for every run, in a fixed order — stable parts first, changing parts last — so providers that cache prompt prefixes can reuse most of it:

| Order | Part | Source |
| - | - | - |
| 1 | Mode prompt | `ASK` or `AGENT` |
| 2 | Shared system prompt | Platform rules, tool usage, mention syntax |
| 3 | User instruction | The member's own [instruction](https://docs.oasm.io/ai-studio/settings/instruction.md) |
| 4 | Project context | The project's name and instruction, when the chat is locked to one |
| 5 | Skills and subagents | The list of available skills and, in Agent mode, available subagents |
| 6 | Conversation summary | Written by compaction when the history grew too long |
| 7 | Long-term memory | Only when the member turned memory on |
| 8 | Short-term memory | Facts the agent saved in this conversation |
| 9 | Plan and goal | The current plan and its status, Agent mode only |
| 10 | Current time | Always last |

The history sent with it is pruned to the token budget, and summarized when it is too long. See [Context and memory](https://docs.oasm.io/architecture/ai-agent/context-and-memory.md).

## The step loop

A run is a loop of **steps**. In each step the model receives the context, the history and the tool definitions, and returns text, reasoning and tool calls. Each tool call goes through the [permission check, guard and approval gate](https://docs.oasm.io/architecture/ai-agent/safety.md), executes, and its result is fed into the next step.

* **Step limit.** A run stops after 50 steps by default; the member's settings or the agent definition can change it. On the last allowed step the model gets no tools, so it must write an answer from what it has and say what is unfinished, instead of ending on a dangling tool call.
* **Continuation.** In Agent mode, a model that hits the limit while plan steps are still pending is not left mid-plan: the loop opens another iteration, with its own assistant message, as long as steps remain and the context budget allows, up to a hard ceiling of 50 iterations. Before each iteration, the context is compacted if it has grown past its budget.
* **Subagent results.** Results of subagents that finish while the run is going are handed to the model before its next step, so it never has to poll for them. Results that arrive after the run ended are delivered with the next message.
* **Safety nets.** If the model forgets to close the last plan step after answering, the run closes it. If the run fails, steps left in progress are reset to pending, so a retry picks them up instead of skipping them.

### Timeouts

A provider that accepts a request and never answers would otherwise hang the run, so each step must produce its first output within 120 seconds. After that, chunks may be at most 30 seconds apart — or, when a call may be waiting for the user's approval, the length of the approval window.

## Streaming

The response is a Server-Sent Events stream of AI SDK UI message chunks — text, reasoning, tool input and output — plus platform-specific `data-*` parts the console renders:

| Part | Purpose |
| - | - |
| `data-conversation-created` | The conversation now exists (first message) |
| `data-todos-updated` | The plan or a step's status changed |
| `data-approval-required` / `data-approval-resolved` / `data-approval-mode-changed` | An approval card appears, is answered, or the run's approval mode switches |
| `data-subagents-updated` | A subagent was queued, started, finished or cancelled |
| `data-remote-execute-output` | Live output of a shell command on a worker |
| `data-browser-screenshot` | The page after a browser command |
| `data-conversation-stats` | Tokens, cost and context usage after the run |

### A run outlives its request

Closing the tab does not stop the agent. The core API keeps draining the stream after the client disconnects, and every chunk is also appended to a **replay buffer** in Redis. A client that reloads, or opens the conversation on another device, calls the resume endpoint: it replays the buffered chunks from the start of the run, then tails new ones live over Redis pub/sub until the run ends. The database stays the source of truth; the buffer only carries the answer still being streamed, and expires minutes after the run ends.

Only two things stop a run: the **Stop** button (which also cancels the conversation's pending and running subagents) or a new run started on the same conversation.

## Persistence

The assistant message is created as a placeholder marked `streaming` before the first token, and finalized as completed, stopped or failed — so a crash never leaves a message that claims to still be running. It stores:

* **parts** in their real order — reasoning, tool calls and text interleaved as they happened,
* **tool calls** in their own table, with arguments, result, duration and any policy that refused them,
* **stats** — input, output, reasoning and cached tokens, time to first token, and estimated cost.

The conversation keeps running totals and the model it last used, which back the context meter in the composer and the [Usage](https://docs.oasm.io/ai-studio/usage.md) page. The first exchange of a conversation also generates its **title** and, in Agent mode, a one-line **goal** pinned above the plan; neither can fail the run.

## Related

> [card] [Context and memory](https://docs.oasm.io/architecture/ai-agent/context-and-memory.md)
>
> What the model sees, and how it is kept within the window

> [card] [Guard and approvals](https://docs.oasm.io/architecture/ai-agent/safety.md)
>
> What happens to every tool call before it runs

> [card] [Chat](https://docs.oasm.io/ai-studio/chat.md)
>
> The composer, modes and answers from the user's side


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.