---
title: "Dex Agent Framework"
description: "How a Dex Agent Framework session runs as Steps, and the rules for its context, queued messages, questions, durable waits, plans, MCP tools, live events, session access, the example's configuration, and its limits."
canonical_url: "https://docs.superdurable.io/reference/agents/dex-agent-framework/"
source: "docs/reference/agents/dex-agent-framework.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

Code on this page is in Python. Other languages: [TypeScript](https://docs.superdurable.io/reference/agents/dex-agent-framework.typescript.md)

<a id="dex-agent-framework"></a>

# Dex Agent Framework

These rules apply to sessions on the
[Dex Agent Framework](https://docs.superdurable.io/build-ai-agents/dex-agent-framework.md), the agent loop of
the Dex Agents packages. Rules that every harness shares, such as
[Steer and Stop](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#steer-and-cancel-turn), are on
[Agent SDK adapters](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md).

<a id="step-graph"></a>

## Step graph

Each model call is one `RunModel` Step, and each tool call is its own Step:

```text
StartAgentSession -> AwaitUserMessage, or RunModel with an initial message
AwaitUserMessage -> RunModel
RunModel -> final answer -> AwaitUserMessage
RunModel -> retries exhausted or non-retryable error -> RecordTurnFailure -> AwaitUserMessage
RunModel -> CompactContext -> RunModel
RunModel -> tool calls -> AwaitToolApproval -> CallTool or CallSingleAttemptTool
                          CallTool or CallSingleAttemptTool
                          AwaitQuestionAnswer      for ask_user
                          AwaitTimer               for durable_wait
                          ResumeTurn -> RunModel, or ApplyTurnControl when steered
a wait in a turn -> steer or cancel_turn -> ApplyTurnControl
ApplyTurnControl -> RunModel with the steered messages, else AwaitUserMessage
```

The view is simplified. [Your agent SDK's terms in Dex](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#term-map)
explains each Step. [Crashes and tool call outcomes](https://docs.superdurable.io/reference/agents/failures.md)
and [Workers and timeouts](https://docs.superdurable.io/reference/agents/workers.md) give their retries,
timeouts, and failure routes.

<a id="durable-context"></a>

## Durable context

Dex builds every model input from the session's stored messages, so the agent
needs no provider conversation API. The session stores each user message,
model output item, and tool result. Model output items go back to the provider
unchanged, including encrypted reasoning items and thinking signatures.

When the model input nears the context window, a `CompactContext` Step
summarizes older messages before the next model call. Retention can then
remove older summarized messages; large active data and recent messages still
count toward the session's state limit.
[Compaction](https://docs.superdurable.io/reference/agents/session-limits.md#compaction) gives the threshold,
the retention limits, and how to keep the whole transcript.

<a id="queued-messages-and-steer"></a>

## Queued messages and Steer

A message sent during a turn waits in the durable `QueuedUserMessages` queue.
The example page shows **Steer** and **Delete** for it. **Steer** ends the turn
at its next safe Step boundary and starts a new one with the message. **Stop**
(`cancel_turn`) ends the turn with no new one. Neither stops a tool call that
has started; [Steer and Stop](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#steer-and-cancel-turn)
gives the full rules.

<a id="questions-and-durable-waits"></a>

## Questions and durable waits

The `ask_user` built-in tool asks the user a question and waits in
`AwaitQuestionAnswer`. The answer becomes the tool's result in the same turn.

The `durable_wait` built-in tool waits in `AwaitTimer` on a
[Timer](https://docs.superdurable.io/concepts/primitives/timer.md). No model call or Worker holds the wait.
**Steer** or **Stop** interrupts a `durable_wait`. A queued message does not.

<a id="durable-plans"></a>

## Plans

Turn on **Plan mode** for a message to get a plan instead of actions. A
planning turn can call only the `write_todos` built-in tool, which writes the
`AgentPlan` Attribute. The user reviews the draft, and **Execute plan** calls
`execute_plan` to run it with every tool.

`write_todos` replaces the `AgentPlan` Attribute and advances its revision.
`execute_plan` takes the revision the user reviewed and refuses a stale one. A
plan that stops with unfinished tasks stays active and can be continued. While
a plan is active, every turn can call every tool; only a draft plan limits a
turn to `write_todos`.

<a id="mcp-tools-and-approvals"></a>

## MCP tools and approvals

The Worker loads trusted stdio or Streamable HTTP MCP servers from local
configuration and offers their tools through `McpToolSource`. Each MCP call
runs in its own tool Step and carries an idempotency key, so the server can
drop a repeat of the same call. A new call has a new key; see
[New calls can repeat an effect](https://docs.superdurable.io/reference/agents/failures.md#tool-runs-twice).

A tool's effect decides whether it waits for approval, as
[Require approval](https://docs.superdurable.io/reference/agents/approvals.md#require-approval) describes.
When a server's annotations are trusted, its read-only hint makes a tool a read
and its idempotent hint makes it an idempotent write, so neither waits by
default. Every other tool gets the session's default effect, unclassified
unless you change it, and waits in `AwaitToolApproval`. An explicit tool policy
wins over the hints.

`McpToolSource` leaves a server that cannot be listed out of that model call
and tries it again on the next one, so the agent keeps answering when every
server is down. With `resource_and_prompt_tools_enabled`
(`resourceAndPromptToolsEnabled` in TypeScript), it also offers three read
tools that list and read a server's resources and prompts.

<a id="model-per-session"></a>

## Model per session

The allowed models, the system prompt, the context window, and the MCP servers
are Worker configuration. Each session picks one allowed model when it starts.
Its settings hold only the model name, which the Worker maps to a model
client, so no credential or server command comes from a browser or Flow input.

<a id="live-events"></a>

## Live events

Text, reasoning summaries, tool activity, approvals, and plan updates arrive on
the session's `AgentEvents` [Stream](https://docs.superdurable.io/concepts/primitives/stream.md). The Python
example serves it as Server-Sent Events. The TypeScript example serves it as an
AI SDK UI message stream for `useChat`. The page reads the conversation from
the session snapshot and the live text from the Stream.
[Read the stream](https://docs.superdurable.io/reference/agents/event-stream.md#read-the-stream) shows both
routes, and [Serve sessions from a web app](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#web-handler)
shows the TypeScript chat route.

<a id="session-access"></a>

## Session access

A session ID appears in the page URL, so the example treats it as public.
**POST /sessions** checks the requested model against the models the Worker
allows, picks a new session ID, and returns a token: an HMAC-SHA256 of the
session ID under `DEX_AGENT_SESSION_KEY`. Every route that names a session
checks the **X-Agent-Session-Token** header before it calls Dex, and answers
403 when it is missing or wrong.

**Python**

```python
    def authorize_session(session_id: str) -> str:
        # Every route that names a session checks its token before any Dex call.
        expected = sign_session_id(app_state.config.agent_session_key, session_id)
        if not hmac.compare_digest(request.headers.get(SESSION_TOKEN_HEADER, ""), expected):
            raise Forbidden("this browser has no token for the AI Agent session")
        return session_id

    # ...

    @blueprint.post("/sessions")
    async def start_session() -> Response:
        body = await request.get_json(silent=True)
        if not isinstance(body, dict):
            raise BadRequest("the request body must be a JSON object")
        model = body.get("model", app_state.config.agent_models[0])
        if model not in app_state.config.agent_models:
            raise BadRequest("model must be one of the models in /settings")
        # The server picks the session ID, so a caller cannot claim an existing session.
        session_id = f"ai-agent-{uuid.uuid4()}"
        # Settings carry only the model name; the Worker resolves it, and keys stay on the Worker.
        await sessions().start_session(session_id, session_settings={"model": model})
        session_token = sign_session_id(app_state.config.agent_session_key, session_id)
        return jsonify(session_id=session_id, session_token=session_token)
```

Example: [examples/python/dex_examples/products/ai-agent/http_routes.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/ai-agent/http_routes.py)

The page keeps each token in local storage, so a copied URL grants no access.
The Python page reads the event stream with **fetch**, because `EventSource`
cannot send a header. The TypeScript page passes the header to the `useChat`
transport, so its reconnects send it too. The routes send no CORS headers.
Without `DEX_AGENT_SESSION_KEY`, a restart picks a new random key and ends
access to older sessions, so give every replica the same key. A real
application replaces the token with its own sign-in and checks that the user
may use the session.

<a id="example-configuration"></a>

## Example configuration

The default demo model needs no credential. It reads slash commands such as
`/ask`, `/choose`, `/wait`, and `/tool`, so you can try every feature without a
key. In TypeScript, the demo models are `mock/dex` and `mock/dex-mini`, and
`/model` names the session's model.

To use real models, set these variables and restart the Worker:

| Variable                   | Meaning                                                                                                         |
| -------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `DEX_AGENT_MODEL`          | The default model. In Python, a LiteLLM model name. In TypeScript, an AI SDK model such as `openai/gpt-5-mini`. |
| `DEX_AGENT_MODELS`         | More models a session may pick, separated by commas.                                                            |
| `DEX_AGENT_SYSTEM_PROMPT`  | The system prompt.                                                                                              |
| `DEX_AGENT_CONTEXT_TOKENS` | The context window that compaction works against.                                                               |
| `DEX_AGENT_MCP_CONFIG`     | The MCP server configuration file.                                                                              |
| `DEX_AGENT_SESSION_KEY`    | The key that signs session tokens.                                                                              |

Put each provider key in the Worker's environment, such as `examples/.env` for
Python. It never enters Flow state.

The example page has its own approval buttons. To approve in Dex Web instead,
follow [Approve in Dex Web](https://docs.superdurable.io/reference/agents/approvals.md#approve-in-dex-web)
with the Flow type **AIAgentSession** and the permission `ai-agent.operate`.

<a id="limits"></a>

## Limits

- Each model call and each tool call adds a Step round trip; see
  [Latency and cost](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#latency-and-cost).
- A session grows toward the server limits in
  [Limits for long sessions](https://docs.superdurable.io/reference/agents/session-limits.md).
- A new call can repeat a single-attempt tool's effect; see
  [New calls can repeat an effect](https://docs.superdurable.io/reference/agents/failures.md#tool-runs-twice).
