Storm 588ad010c0
fix(mcp): stop persisting URL-sourced ResourceLink blocks and heal bricked threads (#6606)
* fix(agents): sanitize persisted URL content blocks before model calls

Threads whose checkpoints carry URL-sourced file blocks (written before
the MCP conversion-layer fix) fail every model call at serialization: the
Chat Completions translator rejects any file block carrying a url, and the
error handler answers each later turn with a non-retriable fallback. Add a
read-time sanitizer that rewrites those blocks in the model-bound request
view only, so poisoned threads heal on their next turn with no migration
and no user action.

- ModelContentCompatibilityMiddleware wraps the model call (sync and
  async) and rewrites ToolMessage list content: URL-sourced file blocks
  become "[Resource ({mime or unknown type}) available at {url}]" text
  blocks, and image blocks whose scheme is not http/https/data get the
  same placeholder. Fetchable image URLs, base64 payloads, text, and
  non-ToolMessage messages pass through. The rewrite is order-preserving,
  idempotent, and never writes state or mutates checkpoints, so artifact
  capture and other state readers keep seeing the original blocks.
- Register on all three chains that replay checkpointed ToolMessages:
  build_middlewares (lead; outer of the MODEL_PHYSICAL extension anchor so
  its final-request guarantee holds), the SDK factory
  _assemble_from_features (new step 13a; docstring updated and its stale
  omission of TokenBudgetMiddleware fixed), and
  build_subagent_runtime_middlewares (after DurableContext/summarization,
  before the date/coalescer tail).
- Subagent coverage verified by tracing every subagent agent-creation
  site: executor.py _create_agent is the only caller of
  build_subagent_runtime_middlewares and serves both the task tool and the
  durable batch worker (SubagentRuntime itself only carries dependencies),
  and a wiring test now asserts the middleware is present in that
  builder's output; the lead and factory chains gained the same wiring
  assertions.
- Update the chain-order contract tests for the new slot: full-chain
  order, loop-detection adjacency, custom loop-detection tail positions,
  and the subagent chain count (22 -> 23).

* fix(mcp): stop emitting URL-sourced file blocks from ResourceLink results

MCP ResourceLink conversion produced a URL-sourced file content block for
every non-image link, which LangChain's Chat Completions translator rejects
at serialization time. Once such a block was checkpointed in the
ToolMessage, every subsequent turn of the thread failed at model-call time,
permanently bricking the conversation.

- Downgrade every ResourceLink that is not an http(s) image to a short text
  placeholder carrying the resource name, MIME type, and the
  already-virtualized URL, so host paths never leak and the model still
  learns a resource was produced and where it lives.
- Preserve each downgraded link as structured data in the tool-message
  artifact under resource_links (merged with structured_content when
  present) for artifact capture and future MCP Apps rendering.
- Keep http(s) image links as image blocks; embedded base64 payloads, text
  path rewriting, and the error-to-ToolException path are unchanged.
- Re-contract the file-migration tests to the new behavior and document
  the conversion contract in the MCP AGENTS.md.

* docs(middlewares): add ModelContentCompatibilityMiddleware to the chain inventory

Insert the read-time sanitizer at its actual lead-chain position (after the
token-budget guard, before the custom-middleware injection point) and renumber
the tail entries 34-39 to 35-40.

* fix(agents): rewrite file blocks on url key presence, not truthiness

langchain-core's OpenAI translator raises for ANY file block carrying a
url key — an empty string or None included — so the read-time sanitizer
must not let such blocks through just because the value is falsy. A
persisted block with url="" or url=None would still brick every later
model call in the thread.

- Gate the file-block rewrite on "url" in block instead of a truthiness
  check; a non-empty string URL keeps the
  "[Resource (mime) available at url]" placeholder, while an empty or
  None URL gets a location-less "[Resource (mime)]" placeholder, so no
  unusable location is advertised to the model.
- Pin both shapes with new middleware tests (url="" and url=None file
  blocks are both rewritten to text). The image branch is unchanged: an
  empty-image case fails provider-side with a 400, not a bricked thread.

* fix(mcp): keep data URIs out of model text and resource_links

A data: scheme ResourceLink fell into the generic placeholder branch,
inlining megabytes of base64 into the model-visible text and into
resource_links, which is checkpointed state — against the repo policy
that data:/blob: URIs never enter state.

- Special-case data: links in _convert_call_tool_result: the
  model-visible placeholder becomes "[Resource: name (mime) embedded
  inline]" and the raw URI is not added to resource_links at all, so the
  payload can neither bloat the context window nor persist in the
  checkpoint.
- Pin the behavior with a conversion test asserting both the placeholder
  wording and the absence of the payload/URI from every emitted block and
  the artifact.
- Add the missing passthrough pin for an HTTPS:// uppercase-scheme image
  link: scheme matching is case-insensitive, so the link stays an image
  block (the block's URL validation normalizes the scheme to lowercase).

* fix(tools): consume resource_links in extract_artifacts_from_result

The MCP conversion layer preserves downgraded ResourceLinks as
{"name", "uri", "mime_type"} entries under the tool message
artifact's resource_links key, but the artifact extractor only read
structured_content — a result whose only artifact signal was
resource_links produced no entries and the file silently vanished from
the artifacts panel.

- Add a fourth extraction path: each resource_links entry becomes a file
  artifact entry, reusing _is_referenceable_url like the
  structured-content and content-block paths, so data:/blob: and other
  unresolvable URIs stay rejected per existing policy. The entry is named
  after the link when a name is present, falling back to the URI's final
  segment; a string mime_type is carried through.
- Integration-test a result whose only signal is resource_links, plus the
  referenceability gate (data:, ui://, and absolute-path URIs in one
  artifact).

* docs(mcp): update the ResourceLink conversion contract bullet

Mention the new artifact-registry consumer and the data: special case so
the bullet stays accurate: uppercase http(s) schemes match
case-insensitively, data: URIs get the embedded-inline placeholder and
are dropped from resource_links, and extract_artifacts_from_result turns
resource_links into registry entries through the shared
referenceability gate.

* refactor(tools): add the canonical resource placeholder formatter

Both the MCP conversion layer and the read-time
ModelContentCompatibilityMiddleware downgrade model-incompatible resource
references to a text placeholder, but each built its own literal. Extract
the single formatter they will share so a thread healed at read time shows
the model the same placeholder shape a fresh conversion produces; the name
segment is optional because persisted content blocks carry no resource name.

* fix(mcp): keep host paths out of ResourceLink placeholder text

Review follow-up on the ResourceLink conversion contract. The placeholder
embedded the resolved URL unconditionally, so a link outside the user-data
tree (or converted without thread context) leaked a raw host path — a
file:// URI or bare filesystem path — into model-visible text, violating
US-16. Compute the resolved URL's scheme and withhold the location segment
when it spells out a host filesystem location (empty scheme, file, or a
single-letter Windows drive scheme); virtual paths and remote schemes keep
their location. The unresolved URI still lands in the artifact channel,
which the model never sees.

- add _model_visible_link_location gate and route the generic placeholder
  through it, re-contracting the outside-user-data and no-context tests to
  the location-less shape and pinning the Windows-drive case
- treat blob: like data: as non-referenceable inline input: drop its raw
  URI from checkpointed resource_links and emit the location-less
  placeholder instead of the mismatched 'embedded inline' wording, and fix
  the comment that claimed blob: was already excluded
- replace every inline placeholder f-string in the ResourceLink branch
  with the shared resource_placeholder_text formatter so the conversion
  layer and the read-time middleware emit byte-identical shapes; data:
  links now render in the canonical location-less form
- sync the ResourceLink conversion contract bullet in mcp/AGENTS.md and
  the _convert_call_tool_result docstring with the host-path suppression
  rule and blob: handling

* fix(agents): sanitize URL content blocks on any message role

Address the second-pass review of the request sanitizer with two
changes that share the same code path.

- Adopt the canonical resource_placeholder_text formatter from
  deerflow.tools.resource_placeholder instead of the module-local
  placeholder helpers, so the read-time rewrite and the MCP conversion
  layer emit byte-identical placeholder text from one definition.
- Widen the rewrite from ToolMessage-only to every request message with
  list-form content. User uploads are verified to produce base64 blocks,
  but imported or cross-client history can carry a URL-sourced file
  block on a HumanMessage or AIMessage, and the Chat Completions
  serializer rejects such a block regardless of the role carrying it.
  The rewrite stays request-view-only: state and checkpoints are never
  mutated, and base64/file-id blocks and string content pass through
  untouched on any role.

* docs(agents): state the ModelContentCompatibility placement contract

The comment above the registration claimed the sanitizer sits just
before Clarification. In the lead chain it is actually followed by the
custom/extension injection point and the whole terminal tail
(terminal-response, finish-reason, and the always-last
ClarificationMiddleware). Describe the real contract: after every
built-in content transform, before extension injection and the
terminal tail.

* docs(middlewares): clarify provenance stamps for request-view-only rewrites

The message-provenance rule read as if every rewrite needs a
provenance_kwargs stamp. Add one line noting the exception: rewrites
that only modify the model-bound request view and never enter state
need no stamps, citing InputSanitizationMiddleware,
DanglingToolCallMiddleware, and ModelContentCompatibilityMiddleware as
precedents.

* fix(agents): keep host paths and data URIs out of healed placeholders

The read-time ModelContentCompatibilityMiddleware rewrote URL-sourced
file blocks and non-fetchable image blocks into placeholders that
inlined the block's URL verbatim. Pre-fix checkpoints — exactly the
threads this middleware exists to heal — can carry a file:// URI, a bare
or Windows host path (links that never resolved to virtual paths), or a
data: URI embedding megabytes of base64, so healing leaked deployment
filesystem layout into prompts (US-16) and could inject the whole inline
payload into model-visible text.

The conversion layer already suppresses those forms via
_model_visible_link_location. Move that gate into the shared
deerflow.tools.resource_placeholder module as model_visible_location
(now also collapsing data:/blob: URIs) and route both middleware
branches through it, so both layers apply identical suppression rules
with one definition. Conversion behavior is unchanged: its data:/blob:
branch short-circuits before the gate, and the gate covers those schemes
for defense in depth.

- resource_placeholder.py gains model_visible_location alongside the
  shared formatter; mcp/tools.py drops its private copy and imports it.
- The middleware's file and image branches pass the URL through the gate
  before building the placeholder; module docstring documents the rules.
- Tests: gate unit tests (virtual/remote visible; file://, bare/Windows
  host paths, data:/blob: withheld) and middleware regression tests
  pinning that a pre-fix data: payload, file:// URI, and Windows drive
  path heal to location-less placeholders.
- AGENTS.md bullets in mcp/ and middlewares/ state the shared gate.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(agents): downgrade malformed image URLs instead of raising in the sanitizer

The read-time ModelContentCompatibilityMiddleware gated persisted image
blocks on urlparse(url).scheme, but urlparse raises ValueError on
structurally invalid URLs — a bad IPv6 literal, invalid netloc
characters — instead of returning an unusable scheme. Pre-fix
checkpoints and imported history can carry exactly those URLs, and the
block stays in the checkpoint, so every later model call in the thread
raised again: the sanitizer re-bricked the very threads it exists to
heal, only with a framework-side exception instead of the langchain
serialization error.

Catch ValueError and treat the URL as non-fetchable, so the block
degrades into the same text placeholder as any other unresolvable
scheme (the shared model_visible_location gate already swallows
ValueError, so the location segment is withheld as well).

- wrap the image branch's urlparse call in try/except ValueError and
  fall back to an empty scheme, keeping http/https/data pass-through
  behavior unchanged for well-formed URLs
- add a regression test pinning that an image block with a bad IPv6
  literal heals to the location-less placeholder without raising

Co-Authored-By: Codex <noreply@openai.com>

* fix(tools): dedupe artifact refs across extraction sources

One downgraded ResourceLink produced two registry entries: the typed
resource_links channel added an entry for the URI, and the free-text
scan over the conversion layer's placeholder text — which embeds the
same virtual path or remote URL — matched it again. The two handles
pointed at one resource, spent double of the render budget, and showed
the model two handles for a single artifact.

extract_artifacts_from_result now tracks seen real_refs across all
sources and keeps only the first entry per ref. Extraction order makes
the typed sources (structured content, resource_links, content blocks)
win over the free-text scan, so the surviving entry keeps the link's
display name and mime type.

- route all six entry-producing sites through a local _add_unique
  helper keyed on real_ref; per-source behavior is unchanged
- document the cross-source dedup in the function docstring
- add a regression test covering a virtual-path and a remote-URL
  placeholder together with their resource_links entries

Co-Authored-By: Codex <noreply@openai.com>

* docs(mcp): state the intentional data: image downgrade asymmetry

The conversion layer downgrades image/* data: ResourceLinks to
location-less text placeholders, while the read-time middleware lets
persisted data: image blocks pass through to the model. The two
contracts looked contradictory but are deliberately layered: the
conversion layer keeps new inline payloads out of checkpointed state,
and the middleware only preserves blocks already occupying one.

- mcp/AGENTS.md's ResourceLink conversion contract and the conversion
  comment in mcp/tools.py now state the image/* data: downgrade and
  why it differs from the read-time pass-through
- middlewares/AGENTS.md's ModelContentCompatibilityMiddleware entry
  states the symmetric read-time rule
- pin the behavior with an image-mime data: ResourceLink conversion
  test (location-less placeholder, nothing in the artifact channel)

Co-Authored-By: Codex <noreply@openai.com>

* docs(backend): compact AGENTS.md guidance to fit the chain byte budget

The branch's new contract bullets pushed the middlewares and mcp
effective AGENTS.md chains past the 98304-byte AG002 hard limit (the
sandbox/subagents chains on main were already over it). Compact the
guidance without dropping contracts:

- middlewares item 34 points at the MCP ResourceLink conversion
  contract and the module docstring instead of restating both
- the mcp ResourceLink conversion contract bullet is tightened
- backend/AGENTS.md merges the File Upload and Context Summarization
  bullet sprawl, folds the stray ATX test note into the upload outline
  rule, drops the Nginx routing block the root guide already covers,
  merges the duplicate MCP-task pointer bullet, compacts Vision
  Support, and scopes the Project Structure tree to the backend
  subtree (the root guide maps the full repo)

Co-Authored-By: Codex <noreply@openai.com>

* fix(agents): gate the file-URL downgrade on provider support and neutralize placeholder metadata

Two review findings on the read-time sanitizer:

- The file-block downgrade ran for every provider, but only Chat
  Completions rejects URL-sourced file blocks: the OpenAI Responses API
  (input_file file_url) and Anthropic (document url source) accept
  http(s) document URLs, so a persisted block created for those
  providers lost its document from the model request. Keep the block
  when the selected model serializes http(s) file URLs natively; every
  other URL shape (non-http schemes, empty/None, malformed) still
  degrades to the placeholder.
- The placeholder interpolated persisted MIME/location metadata
  verbatim, but the middleware runs after the input/tool-result
  sanitization passes and historical URL blocks never went through them
  (non-text content is left untouched), so values carrying
  <system-reminder>-style tags or user-input boundary markers reached
  the model raw. Route the interpolated metadata through the shared
  neutralize_untrusted_tags guard in both the file and image branches.

Tests: provider gating (Responses/Anthropic preserve, Chat Completions
still downgrades, non-http and malformed URLs downgrade even for
capable providers) and metadata neutralization (injection tags
HTML-escaped, boundary tokens neutralized, file and image branches).

Co-Authored-By: Codex <noreply@openai.com>

* fix(tools): require a directory boundary before exposing virtual locations

model_visible_location admitted any URL starting with the virtual
prefix, so a sibling like /mnt/user-data-backups/ops/private/report.pdf
was treated as a virtual path and its host location reached
model-visible placeholder text — defeating the US-16 host-path
suppression the gate exists for. Require the exact virtual root or a
slash-delimited descendant; siblings now collapse to the location-less
placeholder like any other host path. Both the file and image
downgrade branches share the gate, and the conversion layer applies
the same rules to fresh results.

Regressions: gate unit tests (exact root and descendants stay visible;
/mnt/user-data-backups and /mnt/user-database siblings withheld) and
middleware tests pinning the location-less placeholder for both
branches.

Co-Authored-By: Codex <noreply@openai.com>

* docs(agents): scope the placeholder artifact-visibility claim to the conversion layer

The module docstring claimed the healed placeholder keeps the location
visible to the artifact free-text scan and that the link survives in
the structured artifact channel — true for the conversion layer, whose
placeholders are checkpointed, but not on the healing path: the request
view never reaches artifact capture, and no resource_links entry is
created for a downgraded block. Spell out what actually happens here:
a referenceable original block (http(s) URL or absolute host path) is
still captured, from the capture-time scan of the state block rather
than the placeholder, while a non-referenceable one (file://, data:,
blob:) yields no entry and survives only in the untouched checkpoint.

Co-Authored-By: Codex <noreply@openai.com>

* docs(mcp): clarify healing and artifact preservation contracts

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-10-10 21:23:27 +08:00

548 lines
25 KiB
Python

"""Pure-argument factory for DeerFlow agents.
``create_deerflow_agent`` accepts plain Python arguments — it does not load
YAML or install process-global runtime dependencies. It is the SDK-level entry
point sitting between the raw
``langchain.agents.create_agent`` primitive and the config-driven
``make_lead_agent`` application factory.
Direct callers that need an isolated native-subagent capacity or a durable
batch worker pass a caller-owned ``SubagentRuntime`` explicitly. When omitted,
subagent tools retain their application-compatible process-global fallback.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from langchain.agents import create_agent
from langchain.agents.middleware import AgentMiddleware
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware
from deerflow.agents.middlewares.dangling_tool_call_middleware import DanglingToolCallMiddleware
from deerflow.agents.middlewares.tool_error_handling_middleware import ToolErrorHandlingMiddleware
from deerflow.agents.thread_state import adapt_state_schema_for_mode, get_thread_state_schema, normalize_middleware_state_schemas
from deerflow.config.database_config import CheckpointChannelMode
from deerflow.tools.builtins import ask_clarification_tool
if TYPE_CHECKING:
from langchain_core.language_models import BaseChatModel
from langchain_core.tools import BaseTool
from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.graph.state import CompiledStateGraph
from deerflow.config.memory_config import MemoryConfig
from deerflow.config.pii_redaction_config import PiiRedactionConfig
from deerflow.subagents.runtime import SubagentRuntime
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# TodoMiddleware prompts (minimal SDK version)
# ---------------------------------------------------------------------------
_TODO_SYSTEM_PROMPT = """
<todo_list_system>
You have access to the `write_todos` tool to help you manage and track complex multi-step objectives.
**CRITICAL RULES:**
- Mark todos as completed IMMEDIATELY after finishing each step - do NOT batch completions
- Keep EXACTLY ONE task as `in_progress` at any time (unless tasks can run in parallel)
- Update the todo list in REAL-TIME as you work - this gives users visibility into your progress
- DO NOT use this tool for simple tasks (< 3 steps) - just complete them directly
</todo_list_system>
"""
_TODO_TOOL_DESCRIPTION = "Use this tool to create and manage a structured task list for complex work sessions. Only use for complex tasks (3+ steps)."
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def create_deerflow_agent(
model: BaseChatModel,
tools: list[BaseTool] | None = None,
*,
system_prompt: str | None = None,
middleware: list[AgentMiddleware] | None = None,
features: RuntimeFeatures | None = None,
extra_middleware: list[AgentMiddleware] | None = None,
plan_mode: bool = False,
state_schema: type | None = None,
checkpoint_channel_mode: CheckpointChannelMode = "full",
checkpoint_snapshot_frequency: int | None = None,
checkpointer: BaseCheckpointSaver | None = None,
name: str = "default",
subagent_runtime: SubagentRuntime | None = None,
pii_redaction_config: PiiRedactionConfig | None = None,
) -> CompiledStateGraph:
"""Create a DeerFlow agent from plain Python arguments.
The factory assembly itself reads no config files. Pass ``subagent_runtime``
when direct SDK-created graphs must share an explicit native-subagent
capacity or caller-managed durable batch worker.
Parameters
----------
model:
Chat model instance.
tools:
User-provided tools. Feature-injected tools are appended automatically.
system_prompt:
System message. ``None`` uses a minimal default.
middleware:
**Full takeover** — if provided, this exact list is used.
Cannot be combined with *features* or *extra_middleware*.
features:
Declarative feature flags. Cannot be combined with *middleware*.
extra_middleware:
Additional middlewares inserted into the auto-assembled chain via
``@Next``/``@Prev`` positioning. Cannot be used with *middleware*.
plan_mode:
Enable TodoMiddleware for task tracking.
state_schema:
LangGraph state type. Defaults to ``ThreadState``.
checkpoint_channel_mode:
Checkpoint representation for accumulating channels. Defaults to the
full-state compatibility schema. ``"delta"`` requires the guarded
persistence paths (mode markers + compatibility gate) and is therefore
rejected when combined with *checkpointer* in this factory; without a
checkpointer the graph is ephemeral and delta is allowed.
checkpoint_snapshot_frequency:
DeltaChannel snapshot cadence for ``"delta"`` mode. ``None`` uses the
process-frozen value, falling back to the config default. Ignored in
``"full"`` mode.
checkpointer:
Optional persistence backend.
name:
Agent name (passed to middleware that cares, e.g. ``MemoryMiddleware``).
subagent_runtime:
Explicit process runtime shared by direct SDK-created graphs. Required
only when the caller needs non-default native-subagent capacity or a
caller-managed durable batch worker without Gateway/DeerFlowClient
startup. Requires ``features.subagent`` to be enabled.
pii_redaction_config:
Optional PII redaction policy (#3190). ``None`` leaves redaction off;
when enabled, memory-queue and durable-context redaction apply to the
assembled middlewares. A ``middleware=`` takeover bypasses the
assembly that would apply it.
Raises
------
ValueError
If both *middleware* and *features*/*extra_middleware* are provided.
"""
if middleware is not None and features is not None:
raise ValueError("Cannot specify both 'middleware' and 'features'. Use one or the other.")
if checkpoint_channel_mode == "delta" and checkpointer is not None:
raise ValueError(
"create_deerflow_agent does not support checkpoint_channel_mode='delta' with a checkpointer: "
"persisted graphs built here bypass checkpoint mode marker injection and the fail-closed "
"compatibility gate (see deerflow.runtime.checkpoint_mode), so a mixed-mode store would "
"silently corrupt thread state. Use the guarded application paths (make_lead_agent or "
"DeerFlowClient) for delta persistence; delta without a checkpointer is ephemeral and allowed."
)
if middleware is not None and extra_middleware:
raise ValueError("Cannot use 'extra_middleware' with 'middleware' (full takeover).")
if subagent_runtime is not None and (middleware is not None or features is None or features.subagent is False):
raise ValueError("subagent_runtime requires features.subagent to be enabled; it cannot be used with middleware full takeover")
if subagent_runtime is not None and subagent_runtime.batch_config is not None and subagent_runtime.batch_submitter is None:
raise RuntimeError("The explicit durable batch worker is not running; await subagent_runtime.start() or enter it with 'async with' before calling create_deerflow_agent")
if extra_middleware:
for mw in extra_middleware:
if not isinstance(mw, AgentMiddleware):
raise TypeError(f"extra_middleware items must be AgentMiddleware instances, got {type(mw).__name__}")
effective_tools: list[BaseTool] = list(tools or [])
effective_state = get_thread_state_schema(checkpoint_channel_mode, checkpoint_snapshot_frequency) if state_schema is None else adapt_state_schema_for_mode(state_schema, checkpoint_channel_mode, checkpoint_snapshot_frequency)
if middleware is not None:
effective_middleware = list(middleware)
else:
feat = features or RuntimeFeatures()
effective_middleware, extra_tools = _assemble_from_features(
feat,
name=name,
plan_mode=plan_mode,
extra_middleware=extra_middleware or [],
subagent_runtime=subagent_runtime,
pii_redaction_config=pii_redaction_config,
)
# Deduplicate by tool name — user-provided tools take priority.
existing_names = {t.name for t in effective_tools}
for t in extra_tools:
if t.name not in existing_names:
effective_tools.append(t)
existing_names.add(t.name)
effective_middleware = normalize_middleware_state_schemas(
effective_middleware,
checkpoint_channel_mode,
checkpoint_snapshot_frequency,
)
return create_agent(
model=model,
tools=effective_tools or None,
middleware=effective_middleware,
system_prompt=system_prompt,
state_schema=effective_state,
checkpointer=checkpointer,
name=name,
)
# ---------------------------------------------------------------------------
# Internal: feature-driven middleware assembly
# ---------------------------------------------------------------------------
def _assemble_from_features(
feat: RuntimeFeatures,
*,
name: str = "default",
plan_mode: bool = False,
extra_middleware: list[AgentMiddleware] | None = None,
subagent_runtime: SubagentRuntime | None = None,
pii_redaction_config: PiiRedactionConfig | None = None,
) -> tuple[list[AgentMiddleware], list[BaseTool]]:
"""Build an ordered middleware chain + extra tools from *feat*.
Middleware order matches ``make_lead_agent`` (18 middlewares):
0-2. Sandbox infrastructure (ThreadData → Uploads → Sandbox)
3. DanglingToolCallMiddleware (always)
4. GuardrailMiddleware (guardrail feature)
5. ToolErrorHandlingMiddleware (always)
5a. DurableContextMiddleware (always)
5b. SystemMessageCoalescingMiddleware (always)
6. SummarizationMiddleware (summarization feature)
7. TodoMiddleware (plan_mode parameter)
8. TitleMiddleware (auto_title feature)
9. MemoryMiddleware (memory feature)
10. ViewImageMiddleware (vision feature)
11. SubagentLimitMiddleware (subagent feature)
12. LoopDetectionMiddleware (loop_detection feature)
13. TokenBudgetMiddleware (token_budget feature)
13a. ModelContentCompatibilityMiddleware (always)
14. ClarificationMiddleware (always last)
Two-phase ordering:
1. Built-in chain — fixed sequential append.
2. Extra middleware — inserted via @Next/@Prev.
Each feature value is handled as:
- ``False``: skip
- ``True``: create the built-in default middleware (not available for
``summarization`` and ``guardrail`` — these require a custom instance)
- ``AgentMiddleware`` instance: use directly (custom replacement)
"""
chain: list[AgentMiddleware] = []
extra_tools: list[BaseTool] = []
# --- [0-2] Sandbox infrastructure ---
if feat.sandbox is not False:
if isinstance(feat.sandbox, AgentMiddleware):
chain.append(feat.sandbox)
else:
from deerflow.agents.middlewares.thread_data_middleware import ThreadDataMiddleware
from deerflow.agents.middlewares.uploads_middleware import UploadsMiddleware
from deerflow.sandbox.middleware import SandboxMiddleware
chain.append(ThreadDataMiddleware(lazy_init=True))
chain.append(UploadsMiddleware())
chain.append(SandboxMiddleware(lazy_init=True))
# --- [3] DanglingToolCall (always) ---
chain.append(DanglingToolCallMiddleware())
# --- [4] Guardrail ---
if feat.guardrail is not False:
if isinstance(feat.guardrail, AgentMiddleware):
chain.append(feat.guardrail)
else:
raise ValueError("guardrail=True requires a custom AgentMiddleware instance (no built-in GuardrailMiddleware yet)")
# --- [5] ToolErrorHandling (always) ---
chain.append(ToolErrorHandlingMiddleware())
# --- [5a] DurableContext (always) ---
# Summarization moves compacted history into ``summary_text``, and
# SubagentLimitMiddleware counts the run's delegations from the
# ``delegations`` ledger. This middleware writes that ledger and projects
# both into model requests. It sits ahead of summarization, as in
# make_lead_agent, so delegations are captured before they are compacted.
from deerflow.agents.middlewares.durable_context_middleware import DurableContextMiddleware
from deerflow.agents.middlewares.system_message_coalescing_middleware import SystemMessageCoalescingMiddleware
if pii_redaction_config is not None and pii_redaction_config.enabled:
from deerflow.agents.middlewares.pii_redaction_middleware import PiiRedactionMiddleware
chain.append(PiiRedactionMiddleware(pii_redaction_config))
chain.append(DurableContextMiddleware(pii_redaction_config=pii_redaction_config))
# DurableContext adds its authority contract as a second SystemMessage; strict backends
# (vLLM, SGLang, Qwen, Anthropic) reject that, so merge them into one leading message.
chain.append(SystemMessageCoalescingMiddleware())
# --- [6] Summarization ---
if feat.summarization is not False:
if isinstance(feat.summarization, AgentMiddleware):
chain.append(feat.summarization)
else:
raise ValueError("summarization=True requires a custom AgentMiddleware instance (SummarizationMiddleware needs a model argument)")
# --- [7] TodoMiddleware (plan_mode) ---
if plan_mode:
from deerflow.agents.middlewares.todo_middleware import TodoMiddleware
chain.append(TodoMiddleware(system_prompt=_TODO_SYSTEM_PROMPT, tool_description=_TODO_TOOL_DESCRIPTION))
# --- [8] Auto Title ---
if feat.auto_title is not False:
if isinstance(feat.auto_title, AgentMiddleware):
chain.append(feat.auto_title)
else:
from deerflow.agents.middlewares.title_middleware import TitleMiddleware
chain.append(TitleMiddleware())
# --- [9] Memory ---
if feat.memory is not False:
if isinstance(feat.memory, AgentMiddleware):
chain.append(feat.memory)
else:
from deerflow.config.memory_config import get_memory_config, should_use_memory_tools
memory_cfg: MemoryConfig = feat.memory_config or get_memory_config()
if should_use_memory_tools(memory_cfg):
from deerflow.agents.memory.manager import backend_requires_passive_writes_in_tool_mode
from deerflow.agents.memory.tools import get_memory_tools
existing_names = {tool.name for tool in extra_tools}
for memory_tool in get_memory_tools():
if memory_tool.name in existing_names:
logger.warning("Memory tool name %r already exists and was skipped.", memory_tool.name)
continue
extra_tools.append(memory_tool)
existing_names.add(memory_tool.name)
if backend_requires_passive_writes_in_tool_mode(memory_cfg.manager_class):
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
chain.append(
MemoryMiddleware(
agent_name=name,
memory_config=memory_cfg,
pii_redaction_config=pii_redaction_config,
)
)
else:
if memory_cfg.mode == "tool" and not memory_cfg.enabled:
logger.warning("memory.mode is 'tool' but memory.enabled is false; memory tools will not be registered.")
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
chain.append(
MemoryMiddleware(
agent_name=name,
memory_config=memory_cfg,
pii_redaction_config=pii_redaction_config,
)
)
# --- [10] Vision ---
if feat.vision is not False:
if isinstance(feat.vision, AgentMiddleware):
chain.append(feat.vision)
else:
from deerflow.agents.middlewares.view_image_middleware import ViewImageMiddleware
chain.append(ViewImageMiddleware())
if feat.sandbox is not False:
from deerflow.tools.builtins import view_image_tool
extra_tools.append(view_image_tool)
# --- [11] Subagent ---
if feat.subagent is not False:
if isinstance(feat.subagent, AgentMiddleware):
chain.append(feat.subagent)
else:
from deerflow.agents.middlewares.subagent_limit_middleware import SubagentLimitMiddleware
from deerflow.config.subagents_config import DEFAULT_MAX_TOTAL_SUBAGENTS_PER_RUN
from deerflow.subagents.capacity import configured_subagent_max_running
max_concurrent = subagent_runtime.config.max_running if subagent_runtime is not None else configured_subagent_max_running()
max_total = subagent_runtime.max_total_per_run if subagent_runtime is not None else DEFAULT_MAX_TOTAL_SUBAGENTS_PER_RUN
chain.append(
SubagentLimitMiddleware(
max_concurrent=max_concurrent,
max_total=max_total,
)
)
from deerflow.tools.builtins import task_tool
if subagent_runtime is None:
extra_tools.append(task_tool)
else:
from deerflow.tools.builtins.task_tool import bind_task_tool
extra_tools.append(
bind_task_tool(
subagent_runtime.execution_capacity,
app_config=subagent_runtime.app_config,
)
)
if subagent_runtime is not None and subagent_runtime.batch_submitter is not None:
from deerflow.tools.builtins.batch_task_tool import bind_batch_tools
extra_tools.extend(
bind_batch_tools(
submitter_provider=lambda: subagent_runtime.batch_submitter,
app_config=subagent_runtime.app_config,
)
)
elif subagent_runtime is None:
from deerflow.subagents.batch_runtime import is_subagent_batch_runtime_available
if is_subagent_batch_runtime_available():
from deerflow.tools.builtins import batch_status, batch_task, cancel_batch, read_batch_result
extra_tools.extend((batch_task, batch_status, cancel_batch, read_batch_result))
# --- [12] LoopDetection ---
if feat.loop_detection is not False:
if isinstance(feat.loop_detection, AgentMiddleware):
chain.append(feat.loop_detection)
else:
from deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware
from deerflow.config.loop_detection_config import LoopDetectionConfig
chain.append(LoopDetectionMiddleware.from_config(LoopDetectionConfig()))
# --- [13] TokenBudget ---
if feat.token_budget is not False:
if isinstance(feat.token_budget, AgentMiddleware):
chain.append(feat.token_budget)
else:
from deerflow.agents.middlewares.token_budget_middleware import TokenBudgetMiddleware
from deerflow.config.token_budget_config import TokenBudgetConfig
# ``enabled`` defaults to False for config.yaml; ``token_budget=True`` is the opt-in.
chain.append(TokenBudgetMiddleware.from_config(TokenBudgetConfig(enabled=True)))
# --- [13a] ModelContentCompatibility (always) ---
# Read-time sanitizer: rewrites URL-sourced file/image blocks in list-form
# message content into text placeholders in the request view only, so
# threads poisoned before the conversion-layer fix heal on the next model
# call. Placement contract: after every built-in content transform so it
# sees the near-final request, and before the custom/extension injection
# point (_insert_extra) and the terminal tail — in the lead chain it is
# followed by configured extensions, terminal-response and finish-reason
# middlewares, and the always-last ClarificationMiddleware.
from deerflow.agents.middlewares.model_content_compatibility_middleware import ModelContentCompatibilityMiddleware
chain.append(ModelContentCompatibilityMiddleware())
# --- [14] Clarification (always last among built-ins) ---
chain.append(ClarificationMiddleware())
extra_tools.append(ask_clarification_tool)
# --- Insert extra_middleware via @Next/@Prev ---
if extra_middleware:
_insert_extra(chain, extra_middleware)
# Invariant: ClarificationMiddleware must always be last.
# @Next(ClarificationMiddleware) could push it off the tail.
clar_idx = next(i for i, m in enumerate(chain) if isinstance(m, ClarificationMiddleware))
if clar_idx != len(chain) - 1:
chain.append(chain.pop(clar_idx))
return chain, extra_tools
# ---------------------------------------------------------------------------
# Internal: extra middleware insertion with @Next/@Prev
# ---------------------------------------------------------------------------
def _insert_extra(chain: list[AgentMiddleware], extras: list[AgentMiddleware]) -> None:
"""Insert extra middlewares into *chain* using ``@Next``/``@Prev`` anchors.
Algorithm:
1. Validate: no middleware has both @Next and @Prev.
2. Conflict detection: two extras targeting same anchor (same or opposite direction) → error.
3. Insert unanchored extras before ClarificationMiddleware.
4. Insert anchored extras iteratively (supports cross-external anchoring).
5. If an anchor cannot be resolved after all rounds → error.
"""
next_targets: dict[type, type] = {}
prev_targets: dict[type, type] = {}
anchored: list[tuple[AgentMiddleware, str, type]] = []
unanchored: list[AgentMiddleware] = []
for mw in extras:
next_anchor = getattr(type(mw), "_next_anchor", None)
prev_anchor = getattr(type(mw), "_prev_anchor", None)
if next_anchor and prev_anchor:
raise ValueError(f"{type(mw).__name__} cannot have both @Next and @Prev")
if next_anchor:
if next_anchor in next_targets:
raise ValueError(f"Conflict: {type(mw).__name__} and {next_targets[next_anchor].__name__} both @Next({next_anchor.__name__})")
if next_anchor in prev_targets:
raise ValueError(f"Conflict: {type(mw).__name__} @Next({next_anchor.__name__}) and {prev_targets[next_anchor].__name__} @Prev({next_anchor.__name__}) — use cross-anchoring between extras instead")
next_targets[next_anchor] = type(mw)
anchored.append((mw, "next", next_anchor))
elif prev_anchor:
if prev_anchor in prev_targets:
raise ValueError(f"Conflict: {type(mw).__name__} and {prev_targets[prev_anchor].__name__} both @Prev({prev_anchor.__name__})")
if prev_anchor in next_targets:
raise ValueError(f"Conflict: {type(mw).__name__} @Prev({prev_anchor.__name__}) and {next_targets[prev_anchor].__name__} @Next({prev_anchor.__name__}) — use cross-anchoring between extras instead")
prev_targets[prev_anchor] = type(mw)
anchored.append((mw, "prev", prev_anchor))
else:
unanchored.append(mw)
# Unanchored → before ClarificationMiddleware
clarification_idx = next(i for i, m in enumerate(chain) if isinstance(m, ClarificationMiddleware))
for mw in unanchored:
chain.insert(clarification_idx, mw)
clarification_idx += 1
# Anchored → iterative insertion (supports external-to-external anchoring)
pending = list(anchored)
max_rounds = len(pending) + 1
for _ in range(max_rounds):
if not pending:
break
remaining = []
for mw, direction, anchor in pending:
idx = next(
(i for i, m in enumerate(chain) if isinstance(m, anchor)),
None,
)
if idx is None:
remaining.append((mw, direction, anchor))
continue
if direction == "next":
chain.insert(idx + 1, mw)
else:
chain.insert(idx, mw)
if len(remaining) == len(pending):
names = [type(m).__name__ for m, _, _ in remaining]
anchor_types = {a for _, _, a in remaining}
remaining_types = {type(m) for m, _, _ in remaining}
circular = anchor_types & remaining_types
if circular:
raise ValueError(f"Circular dependency among extra middlewares: {', '.join(t.__name__ for t in circular)}")
raise ValueError(f"Cannot resolve positions for {', '.join(names)} — anchors {', '.join(a.__name__ for _, _, a in remaining)} not found in chain")
pending = remaining