Execution
A REST query starts at HTTP ingress and continues until model and tool execution ends.
sequenceDiagram participant C as Client participant R as REST participant S as SessionAgents participant A as Agent graph participant M as Model participant T as Tools C->>R: POST /api/v1/runs R->>S: Get or create handle by thread S->>A: Compiled graph R->>C: RUN_STARTED A->>M: Model loop M-->>A: Tool calls or text A->>T: Files, shell, plugins, or MCP T-->>A: Tool results A-->>R: Graph ends R->>C: MESSAGES_SNAPSHOT R->>C: RUN_FINISHED
Session handles
SessionAgents caches Agents by (threadId, input binding), up to 32 of them. The lock covers the preparation stage only; active streams each hold their own graph reference and are unaffected by the lock.
Extension changes are checked before a new turn. Failed candidate assembly returns HTTP 500 while preserving the previous cache. See extension lifecycle for refresh and publication stages.
The semantic client is created once in the REST process lifespan, shared with all handles, and closed on process exit.
Checkpoints use AsyncSqliteSaver at <stateDir>/checkpoints.sqlite. A file lock allows only one backend for a given stateDir.
In an embedded SDK host, one Agent can reuse model and semantic-service clients while assembling separate session graphs and file backends by thread_id. The first invocation determines that session's output directory; resumption retains the binding so files referenced by historical messages remain readable. See SDK task outputs.
Graph contents
Without dataagent.entry, build_graph calls create_deep_agent. Product middleware is added in this order:
- Root Agent
TodoListMiddleware; absent from subagents. - Model-call limit, raising an error when exceeded.
- Tool-call limit, raising an error when exceeded.
- Tool-loop detection when enabled.
- Compiled Hooks.
ToolErrorMiddleware: onlyToolExceptionbecomes correctable text.- Revision-aware Skill middleware when a revision is available.
Core additionally assembles filesystem, subagent, summarization, and tool-call patching middleware, plus other layers required by the profile. Product configuration, plugins, and subagents extend the lifecycle through Hooks.
The default model client is ChatOpenAI, using timeout_seconds and max_retries for timeout and retries. Standard subagents inherit the parent model by default and support model-alias and temperature overrides. Compiled subagents obtain models through factory services. See subagents for declarations.
Session filesystems use real paths, and shell timeout follows timeout_seconds. See security boundaries for file access and process permissions, and context and prompts for offloading long messages and tool results.
Entry graph
When dataagent.entry is set, the graph is not a Deep Agents root. It is a MessagesState graph with this shape:
START → <entry> → ENDIts sole node is the Runnable returned by the compiled subagent factory. The plugin's own StateGraph remains inside that Runnable; the host does not call the plugin's graph builder. The compile name and node name both use the entry name. with_config applies the same recursion_limit as core, 9999, and a LocalLangChainTracer attached to the session directory. The root trace uses the entry name.
The entry node does not set emit-messages or emit-tool-calls. Its factory receives the original model cached in AgentContext, without changing disable_streaming. Text tokens, tool calls, and reasoning reach the frontend as model chunks. The node's returned reply remains in the final MESSAGES_SNAPSHOT. STEP_STARTED and STEP_FINISHED are still emitted.
The session outputs/ directory still reaches the factory, and result files belong to that session. dataagent.hooks, call limits, and input_workspaces remain in configuration but are not installed into this graph and do not cause an error merely by being present. See entry mode. An invalid entry does not fail /healthz; its entry field still reports the configured value. Names are checked before plugin factories. The first /api/v1/runs request returns HTTP 409 for an invalid entry.
Turn boundaries
REST wraps the whole upstream iteration in asyncio.timeout(timeout_seconds) — retries and their wait time included. Inbound A2A applies its deadline only to Agent ainvoke, excluding queuing, session preparation, and checkpoint saving; see A2A. SDK ainvoke has no host-wide deadline; callers impose one themselves.
The graph's own limit overrides AG-UI's default recursion_limit=25; only the graph-configured value is forwarded.
If a graph stops with unfinished nodes, the service returns RUN_ERROR. On failure or cancellation, cleanup records the checkpoint containing messages saved by this turn in the session index. The next turn prefers that indexed position, falling back to the latest thread state if none exists. Recovery is not task re-execution or idempotent replay.
Human feedback execution and recovery
Human feedback integration describes stages, answers, and resume actions. In the standard root graph, the plugin compiler gathers enabled policies, then HITLMiddleware implements interruption and recovery.
- Durable prepare tasks handle matching policies in declaration order at each stage, saving questions, parameters, original tool calls, and policy versions in checkpoints. SQLite recovery reuses prepared results. Policies at the same stage run sequentially; later resume methods can observe earlier explicit state updates. Recovery fails if a pending policy disappears or its stage or version changes.
- Tools cache completed results through durable execute tasks, so resuming from
after_toolreuses the result. A process exit during tool execution can still cause a retry; external side effects must be idempotent. Middleware preserves reducer increments in before-tool, tool, and after-tool order, submitting one tool message corresponding to the original call. HITL-managed tools support ordinary tool results andCommand(update=dict)for the current graph. - Private
hitl_historymerges by interaction ID. A host retaining the checkpoint can inspect it throughgraph.aget_state(config).source="external"means the answer arrived through a resume entry point.
Regression tests cover SQLite reconstruction and parallel interruptions, resume actions at different stages, reducer update order, and HTTP / A2A recovery.
Repetition and loop detection
Detection uses local rules only, adds no model calls, and does not change model streaming settings. It lives in dataagent/extensions/loop_detection.py beside extensions/tracing.py and depends only on public LangChain APIs. The two detectors are installed in different places:
- Tool loops are checked by
LoopDetectionMiddleware.build_native_middleware()inassembly/graph.pyinstalls it for the main Agent and standard subagents after call limits and before plugin Hooks. Middleware has exact turn boundaries, and model spans have already ended when a loop is detected, avoiding unclosed trace records. - Text repetition is checked by
LoopDetectionCallback, installed withwith_config(callbacks=...)during graph assembly. LangChain propagates it into internal model and subagent calls. Only streaming callbacks can stop degraded decoding before the full reply has been consumed, so this detection remains callback-based.
Rules:
- Streaming text: the detector inspects 50-character fragments within the latest 5,000 characters.
- It stops when a fragment appears densely ten times and the intervening content repeats as well.
- Text and provider-exposed reasoning are counted separately. Tool-argument JSON is excluded.
- Fenced code and naturally repetitive Markdown structural lines — tables, lists, headings, quotations, separators — are skipped, to avoid false positives on normal output.
- Only confirmed block markers qualify. Bold, emphasis, and inline-code prefixes do not exempt prose.
- Fences follow CommonMark line-start, matching-character, and length rules. Backtick fence info strings cannot contain backticks, and closing lines permit only spaces or tabs after the fence.
- LF, CRLF, and CR endings are supported, including endings split across chunks.
- Non-streaming replies check every content block per channel; channels already checked while streaming are not checked twice. Non-streaming models can only be checked after they have replied.
- Tool loops: one assistant reply counts as one step, and the latest 25 steps of the current turn are considered. Execution stops when a sequence of 1–5 steps repeats five consecutive times with identical tool names, normalized arguments, results, and statuses.
- Parallel calls belong to one step and do not inflate the count.
- Results match their owning reply; reused call IDs and parallel outputs cannot mix.
- Changed results let execution continue. Polling tools can be listed in
ignored_tools.
- Tool-loop retry: the first detection in a turn does not terminate it. Middleware appends a user message whose
nameisloop_detection, telling the model that identical calls have repeated five times with identical results and asking it to try a different approach or answer from existing information. Execution then continues.- Earlier steps stop counting; only another full loop after the message terminates the turn, so each turn allows at most one retry.
- The message stays in the conversation history.
- Retry model calls count toward
model_calls_per_agentandserver.run_timeout_seconds.
before_agent records the turn start for each invocation. Messages inserted mid-turn by other middleware, such as summaries, scoring reconsideration, or media references, do not reset detection; a new user request does. Text repetition or a second tool loop raises dataagent.LoopDetectedError through the SDK and emits REST RUN_ERROR with code LOOP_DETECTED. It does not automatically replay tasks or completed tools. Inspect completed steps before sending a new request. Exceptions contain no original text or arguments. Changing detector configuration requires restarting or recreating the SDK instance.
Model calls initiated by middleware itself, such as context summarization or Rubric grading, are not Agent output and do not participate in text detection.
These heuristic protections have explicit coverage boundaries:
- With
dataagent.entry, a compiled entry owns its graph and bypassesbuild_native_middleware. It therefore has text repetition detection only, with no tool-loop detection or retry. The entry owns its internal limits, and Server execution still usesserver.run_timeout_seconds. Even when its implementation catches an exception and returns an ordinary reply, as NL2SQL can,build_entry_graph()rethrows anyLoopDetectedErrorrecorded by that invocation after the entry returns. - Compiled subagents delegated through
taskalso have only text repetition detection. They use the same exception-propagation guard: converting a loop exception to an ordinary internal reply does not prevent the host from raisingLoopDetectedError, ending the turn without another parent-model call. - Without a plugin-declared
general-purpose, the core-generated general subagent does not inherit custom middleware. It therefore has no tool-loop detection, only text repetition detection. Declaregeneral-purposeexplicitly in a plugin when you need it. - Text repetition is not retried. JSON-retry entry points in NL2SQL nodes and UDN scenario packs propagate
LoopDetectedErrorrather than treating it as a format error. Detection in a validator or selector stops the remaining workflow and produces no final CSV. HTTP interfaces always stream, so repeated text has already reached the frontend; AG-UI has no event that invalidates emitted text. Model SDK retries for transient errors such as 429, 5xx, timeout, and disconnection followmodels.<id>.max_retries— no extra middleware retry is added. - Exempting Markdown structural lines allows repetition consisting entirely of identical table rows or list items to escape text detection. This deliberate tradeoff avoids rejecting normal tables. Tool-loop detection,
model_calls_per_agent, andtool_calls_per_agentprovide additional limits. - After summarization rewrites history, the recorded turn start can exceed its new length. Detection then covers less content and can miss a loop, but does not count a previous turn as part of the current one.
- Plugin model calls that suppress callbacks are outside coverage, as is private reasoning unavailable to the runtime. Closing the client stream does not guarantee the provider immediately stops computing; token, call-count, and timeout limits remain necessary.
enabled: false disables both detectors for tasks intentionally producing extensive repeated text or repeated tool calls.
The algorithm references Gemini CLI LoopDetectionService and is independently implemented using DataAgent's native middleware, callback, and error-handling model.
See configuration fields for settings and examples.