Dex Agent Framework
查看 MarkdownThese rules apply to sessions on the Dex Agent Framework, the agent loop of the Dex Agents packages. Rules that every harness shares, such as Steer and Stop, are on Agent SDK adapters.
Step graph
Each model call is one RunModel Step, and each tool call is its own Step:
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 explains each Step. Crashes and tool call outcomes and Workers and timeouts give their retries, timeouts, and failure routes.
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 gives the threshold,
the retention limits, and how to keep the whole transcript.
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
gives the full rules.
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. No model call or Worker holds the wait.
Steer or Stop interrupts a durable_wait. A queued message does not.
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.
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.
A tool's effect decides whether it waits for approval, as
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.
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.
Live events
Text, reasoning summaries, tool activity, approvals, and plan updates arrive on
the session's AgentEvents Stream. 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 shows both
routes, and Serve sessions from a web app
shows the TypeScript chat route.
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.
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)
例子: examples/python/dex_examples/products/ai-agent/http_routes.py
const issueSessionToken = (sessionId: string) => createHmac("sha256", sessionKey).update(sessionId).digest("hex");
const authorizeSession = (request: Request, sessionId: string): string => {
const expected = Buffer.from(issueSessionToken(sessionId));
const presented = Buffer.from(request.header(sessionTokenHeaderName) ?? "");
if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) {
throw new HttpError(403, "this browser has no token for the AI Agent session");
}
return sessionId;
};
const sessionIdOf = (request: Request) => authorizeSession(request, String(request.params.id));
router.use("/", express.static(fileURLToPath(new URL("./ui/", import.meta.url))));
router.get("/settings", (_request, response) => {
response.json({ model: models[0], models });
});
router.post("/sessions", async (request, response) => {
const model = requireBody(request).model ?? models[0];
if (typeof model !== "string" || !models.includes(model)) {
throw new HttpError(400, "model must be one of the models in /settings");
}
// The server picks the session ID, and settings carry only the model name the Worker resolves.
const sessionId = `ai-agent-${randomUUID()}`;
const start = { initialMessage: null, sessionSettings: { model } };
await client.startFlow(flow, sessionId, start, { timeoutMs: 30 * DAY_MS });
response.json({ session_id: sessionId, session_token: issueSessionToken(sessionId) });
});
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.
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
with the Flow type AIAgentSession and the permission ai-agent.operate.
Limits
- Each model call and each tool call adds a Step round trip; see Latency and cost.
- A session grows toward the server limits in Limits for long sessions.
- A new call can repeat a single-attempt tool's effect; see New calls can repeat an effect.