mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-10-26 13:16:24 +00:00
* feat(agents): persist tool artifacts as resolvable handles (#4676) MCP and sandbox tools return file paths, URLs, and task ids that are lost when context compaction summarizes the conversation. This adds a per-thread artifact handle registry so the model can reference artifacts by short deterministic handles (art_xxxxxxxx) that survive compaction and resolve to real references at the tool-call boundary. - ThreadState.tool_artifacts: reducer channel capped at 100 entries, same-handle latest-wins, survives summarization compaction - artifact_registry: deterministic handle derivation from (thread_id, tool_call_id, call_index); extraction precedence structured_content -> file/image blocks -> conservative text scan; HTML-escaped model-context rendering with char budget - ArtifactCaptureMiddleware: before_model hook captures lightweight metadata (never content) and tracks handle consumption - ArtifactResolutionMiddleware: rewrites handles in tool-call args to real references before execution; unknown handles untouched - DurableContextMiddleware: projects the registry into the hidden durable-context data block ([available]/[consumed] status) - config: new tool_artifacts section (all switches default on) - frontend: artifact badges on tool-call steps keyed by tool_call_id Fixes #4676 * fix(agents): harden artifact registry after review (#4676) Review findings on #4929: - capture/consumption updates emitted in the same before_model call are now concatenated instead of dict-merged; dict-merging clobbered the shared tool_artifacts key and permanently dropped fresh captures - handles embed a per-result ordinal so multiple references inside one tool result never collide (two paths in one text block previously collapsed into one handle) - structured_content extraction pulls concrete refs from known keys (file/path/url/task_id/..., string or list-of-string values) instead of storing a truncated JSON preview, falls back to an untruncated whole-object data entry, and no longer skips file/image content blocks - plain-string tool results (e.g. bash/write_file output) are scanned for sandbox paths / remote URLs too, gated by detect_refs_in_text - wire max_entries through configure_tool_artifact_max_entries at assembly (clamped 10..1000) and gate detect_refs_in_text scans - resolution requires both enabled and resolve_handles_in_args, matching its docs - add real ToolCallRequest.override coverage and the spec 14.4 integration cycle (capture -> inject -> resolve -> consumption) * fix(agents): address second-round artifact registry review (#4676) Follow-up findings on #4929: - drop generic `output`/`outputs` from structured ref keys: prose under those keys no longer becomes a bogus file entry (falls back to the whole-object data entry; path-shaped refs are still caught by the free-text scan) - strip closing quotes, brackets, and backticks from detected refs so markdown- and JSON-wrapped paths resolve to clean real references - remove the process-wide cap setter: the reducer enforces only an absolute ceiling (1000) and ArtifactCaptureMiddleware applies the configured max_entries per agent when emitting updates, so agents with different configs in one process never share or flap a cap - skip extraction for tool messages whose tool_call_id already has registry entries and memoize known-empty results (bounded FIFO), so steady-state capture cost drops to the new message tail instead of a full-history rescan per model call - correct the inverted ordering claim: capture is position-independent in the wrap chain because it is a before_model hook reading state messages; fixed the assembly comment, AGENTS.md item 15, and the ordering test docstring CI parity verified locally: ruff check + format --check, full offline suite, blocking-io suite, collect-only, uv lock --check, check_agent_guidance, frontend format/lint/typecheck/build/tests. * fix(agents): sliding-window cap and URI gates for artifact registry (#4676) Third-round review findings on #4929: - max_entries is now a sliding retention window: fresh captures are always registered, and when the projection exceeds the configured cap the middleware appends a trailing {"op": "trim_to", "keep": N} directive that the reducer applies by evicting the oldest entries. The previous remaining-budget emission froze the registry at the cap, permanently dropping post-compaction artifacts — the exact failure mode #4676 targets — and silently disabled the round-2 rescan optimizations at the point threads grew longest - _track_consumption memoizes settled tool-call args in a bounded FIFO alongside the existing empty-result memo, so historical AIMessage args are not regex-rescanned every model call - file/image content-block URLs must be http(s) or path-shaped; data:/blob: URIs (MCP embedded resources carrying base64 payloads) can no longer enter thread state, tool args, or crowd out the render budget; protocol-relative //host forms are rejected as well - structured-content ref values go through the same URI-shape gate as content blocks, closing the embedded-payload hole via known keys such as url/urls - tool_artifacts.enabled now gates the whole middleware including consumption tracking via an early return in before_model Docs updated to describe the sliding window, URI gates, enabled scope, and both bounded memos. * fix(agents): final evictions and pending-aware consumption for artifact registry (#4676) Fourth-round review findings on #4929: - the sliding window interacted with the seen_call_ids skip to resurrect evicted entries every round: once an entry was trimmed, its tool_call_id left the seen set while its ToolMessage stayed in context, so the next model call re-extracted it, re-registered it as newest, and evicted something else — a never-converging rotation. The empty-result memo is now a unified _processed_results memo that records every extraction regardless of outcome, making evictions final; steady state over a saturated thread is quiescent (pinned by a multi-round test asserting no updates and zero extractions) - the consumption scan built its handle map from pre-capture state, so a call referencing a handle captured in the same before_model call missed, got settled as quiet, and its consumption mark was lost forever. _track_consumption now receives the pending capture entries and resolves against state + pending; a call settles as quiet only after every referenced handle resolved, so transient misses retry next round instead of permanently suppressing the mark AGENTS.md entry 15 updated to describe both memos and the eviction-is-final semantics. * fix(artifacts): address occurrence identity, PII and URL review findings * fix(artifacts): enforce resolved policy checks and bounded registry handling --------- Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
171 lines
7.4 KiB
Python
171 lines
7.4 KiB
Python
"""Tests for declarative middleware ordering constraints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from deerflow.extensions.isolation import IsolatedMiddleware
|
|
from deerflow.extensions.ordering import OrderingConstraint, assert_ordering
|
|
|
|
|
|
class _Outer:
|
|
pass
|
|
|
|
|
|
class _Inner:
|
|
pass
|
|
|
|
|
|
class _Unrelated:
|
|
pass
|
|
|
|
|
|
_CONSTRAINTS = (OrderingConstraint(outer=_Outer, inner=_Inner, reason="outer must wrap inner"),)
|
|
|
|
|
|
def test_correct_order_passes():
|
|
assert_ordering([_Outer(), _Inner()], {}, _CONSTRAINTS)
|
|
|
|
|
|
def test_reversed_order_raises():
|
|
with pytest.raises(RuntimeError, match="outer must wrap inner"):
|
|
assert_ordering([_Inner(), _Outer()], {}, _CONSTRAINTS)
|
|
|
|
|
|
def test_missing_participant_is_not_a_violation():
|
|
"""The stack is conditionally built; an absent middleware means the
|
|
constraint simply does not apply."""
|
|
assert_ordering([_Outer(), _Unrelated()], {}, _CONSTRAINTS)
|
|
assert_ordering([_Unrelated()], {}, _CONSTRAINTS)
|
|
|
|
|
|
def test_violation_message_names_the_responsible_extension():
|
|
"""Without attribution, an operator cannot tell which extension to remove."""
|
|
stack = [_Inner(), _Outer()]
|
|
provenance = {0: "bad_ext:install"}
|
|
with pytest.raises(RuntimeError) as excinfo:
|
|
assert_ordering(stack, provenance, _CONSTRAINTS)
|
|
assert "bad_ext:install" in str(excinfo.value)
|
|
|
|
|
|
def test_violation_without_extensions_says_core():
|
|
stack = [_Inner(), _Outer()]
|
|
with pytest.raises(RuntimeError) as excinfo:
|
|
assert_ordering(stack, {}, _CONSTRAINTS)
|
|
assert "core" in str(excinfo.value).lower()
|
|
|
|
|
|
def test_violation_does_not_blame_an_uninvolved_extension():
|
|
"""Only the two positions in the violating pair can be responsible. A
|
|
provenance entry for some other index — an extension that contributed
|
|
elsewhere in the stack but is not part of this constraint — must not be
|
|
named, even though it is the only entry in `provenance`."""
|
|
stack = [_Inner(), _Outer(), _Unrelated()]
|
|
provenance = {2: "innocent_ext:install"}
|
|
with pytest.raises(RuntimeError) as excinfo:
|
|
assert_ordering(stack, provenance, _CONSTRAINTS)
|
|
message = str(excinfo.value)
|
|
assert "innocent_ext:install" not in message
|
|
assert "core" in message.lower()
|
|
|
|
|
|
def test_reversed_order_raises_when_a_participant_is_wrapped():
|
|
"""Extension-contributed middlewares are wrapped in IsolatedMiddleware before
|
|
they reach the merged stack. If _index_of matched only the wrapper's own
|
|
type, a wrapped participant would read as absent and the constraint would
|
|
silently stop being enforced instead of raising — the worst possible failure
|
|
mode for a safety check."""
|
|
stack = [IsolatedMiddleware(_Inner(), "bad_ext:install", lambda d: None), _Outer()]
|
|
with pytest.raises(RuntimeError, match="outer must wrap inner"):
|
|
assert_ordering(stack, {}, _CONSTRAINTS)
|
|
|
|
|
|
def test_every_duplicate_participant_must_satisfy_the_constraint():
|
|
"""A valid first pair must not hide a later contributed violation."""
|
|
stack = [_Outer(), _Inner(), _Outer()]
|
|
|
|
with pytest.raises(RuntimeError) as exc_info:
|
|
assert_ordering(stack, {2: "late:install"}, _CONSTRAINTS)
|
|
|
|
assert "late:install" in str(exc_info.value)
|
|
|
|
|
|
def test_core_constraints_are_declared():
|
|
from deerflow.agents.middlewares.skill_tool_policy_middleware import SkillToolPolicyMiddleware
|
|
from deerflow.agents.middlewares.tool_error_handling_middleware import ToolErrorHandlingMiddleware
|
|
from deerflow.agents.middlewares.tool_progress_middleware import ToolProgressMiddleware
|
|
from deerflow.agents.middlewares.tool_promotion_audit_middleware import DeferredToolPromotionAuditMiddleware
|
|
from deerflow.extensions.ordering import core_ordering_constraints
|
|
|
|
core_ordering_constraints.cache_clear() # Prior wiring tests temporarily replace middleware modules.
|
|
pairs = {(c.outer, c.inner) for c in core_ordering_constraints()}
|
|
assert (ToolProgressMiddleware, ToolErrorHandlingMiddleware) in pairs
|
|
assert (DeferredToolPromotionAuditMiddleware, SkillToolPolicyMiddleware) in pairs
|
|
|
|
from deerflow.agents.middlewares.artifact_resolution_middleware import ArtifactResolutionMiddleware
|
|
from deerflow.agents.middlewares.read_before_write_middleware import ReadBeforeWriteMiddleware
|
|
from deerflow.agents.middlewares.sandbox_audit_middleware import SandboxAuditMiddleware
|
|
from deerflow.agents.middlewares.tool_receipt_middleware import ToolReceiptMiddleware
|
|
from deerflow.guardrails.middleware import GuardrailMiddleware
|
|
|
|
for policy in (GuardrailMiddleware, SandboxAuditMiddleware, ReadBeforeWriteMiddleware, ToolProgressMiddleware):
|
|
assert (ArtifactResolutionMiddleware, policy) in pairs
|
|
assert (ToolReceiptMiddleware, ArtifactResolutionMiddleware) in pairs
|
|
core_ordering_constraints.cache_clear()
|
|
|
|
|
|
def test_core_constraints_are_a_plain_tuple():
|
|
"""Deferred resolution must not be paid for with an object that reports one
|
|
thing when iterated and another when measured.
|
|
|
|
The predecessor was a ``tuple`` subclass whose backing storage stayed empty
|
|
(a tuple cannot fill its own storage after construction), so ``len`` was 0,
|
|
``bool`` was False, ``in`` was always False and it compared unequal to the
|
|
very tuples tests substitute for it — while iteration yielded the real
|
|
constraints.
|
|
"""
|
|
from deerflow.extensions.ordering import core_ordering_constraints
|
|
|
|
constraints = core_ordering_constraints()
|
|
iterated = list(constraints)
|
|
|
|
assert type(constraints) is tuple
|
|
assert len(constraints) == len(iterated)
|
|
assert bool(constraints) is bool(iterated)
|
|
assert constraints == tuple(iterated)
|
|
assert all(constraint in constraints for constraint in iterated)
|
|
assert constraints[0] is iterated[0]
|
|
assert list(reversed(constraints)) == list(reversed(iterated))
|
|
|
|
|
|
def test_resolution_stays_deferred_until_first_use():
|
|
"""Importing this module must not drag in the middleware layer.
|
|
|
|
``extensions/`` is the layer the middleware layer calls into, so resolving
|
|
the table at import time would give it a backward dependency on the layer
|
|
it exists to serve — an import cycle waiting for the first middleware that
|
|
imports anything under ``extensions/`` at module level. Resolution belongs
|
|
at ``assert_ordering`` time, which already runs inside the middleware
|
|
builder.
|
|
"""
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
backend_root = Path(__file__).resolve().parents[1]
|
|
env = {**os.environ, "PYTHONPATH": os.pathsep.join([str(backend_root), str(backend_root / "packages" / "harness"), os.environ.get("PYTHONPATH", "")])}
|
|
probe = (
|
|
"import sys\n"
|
|
"from deerflow.extensions import ordering\n"
|
|
"targets = ('deerflow.agents.middlewares.tool_progress_middleware', 'deerflow.agents.middlewares.tool_error_handling_middleware')\n"
|
|
"print('after_import', [t for t in targets if t in sys.modules])\n"
|
|
"ordering.core_ordering_constraints()\n"
|
|
"print('after_call', sorted(t for t in targets if t in sys.modules))\n"
|
|
)
|
|
result = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, env=env)
|
|
|
|
assert result.returncode == 0, result.stderr
|
|
assert "after_import []" in result.stdout, "importing extensions.ordering must not load the middleware layer"
|
|
assert "after_call ['deerflow.agents.middlewares.tool_error_handling_middleware', 'deerflow.agents.middlewares.tool_progress_middleware']" in result.stdout
|