Nan Gao 13f0a7f263
feat(extensions): let an out-of-tree extension observe what the agent did (#4863)
* feat(extensions): let an out-of-tree extension observe what the agent did

DeerFlow's extension system can contribute middleware, services and routes,
but an extension cannot answer basic questions about a run without reaching
into host internals. Several of the facts it would need are destroyed by the
operations that produce them:

  * The middleware chain injects and rewrites a lot of context — date
    reminders, recalled memory, compaction summaries, durable-context data,
    image payloads, activated skill bodies. Downstream, none of it is
    attributable: at the model-call boundary an injected HumanMessage is
    indistinguishable from the user's own, and anything wanting to tell them
    apart has to pattern-match prompt wording, which breaks on the next copy
    edit.

  * Two runs of "the same agent" are only comparable if the chain enforced the
    same limits, prompts and thresholds. Recovering that from outside means
    reading private attributes and guessing which of them change behaviour — a
    guess that rots silently as middlewares gain fields.

  * The lead-agent factory resolves a model after runtime overrides, renders a
    prompt, filters tools through authorization and composes a stack, all
    inside one synchronous call, and none of it survives: a middleware sees its
    neighbours but not the prompt, the run worker sees a graph but not what
    went into it.

  * Summarization is destructive by design. N messages leave the context and
    one summary enters it; afterwards only the summary exists, so "which
    messages became this?" is not reconstructible.

This adds seven neutral facilities so those facts are recorded where they are
still true, and releases the contract package as 0.2.0.

Message provenance
  Producers stamp `deerflow_content_kind` / `deerflow_producer_kind` onto the
  messages they inject or rewrite. Stamping is unconditional — a fact whose
  presence depends on whether an observer is installed is not a fact — and the
  keys are server-owned, so provenance cannot be forged from a request.

Middleware self-description
  Twelve middlewares declare their own behaviour-affecting parameters through
  a duck-typed `release_policy_parameters()`. Long text is hashed rather than
  embedded: a declaration is an identity, not a copy of the prompt.

Agent assembly descriptor
  `assemble_lead_agent()` returns the graph plus a descriptor whose fingerprint
  answers "did anything about this agent change between these two runs?".
  `make_lead_agent()` keeps its graph-only signature — it is the LangGraph
  Server ABI declared in langgraph.json. Tools and skills are sorted before
  hashing because their assembly order is incidental; middlewares are not,
  because stack order decides what wraps what. Host build identity is reported
  but excluded from the fingerprint, so a redeploy does not invalidate every
  agent's identity.

Context compaction observation
  Summarization emits the content hashes of the messages it is about to remove
  joined to the summary that replaced them. Content is the only identity
  available at that seam: the summary does not become a message, and what later
  projects it into a request renders it bounded and escaped rather than
  verbatim.

Neutral policy, transform and MCP-source facts
  Guardrail decisions are published to runtime context under a `__`-prefixed
  key; result-rewriting middlewares append a declared, ordered transform trail;
  MCP tools carry their credential-free logical origin.

Extension route identity
  Contributed routes are session-authenticated and cannot opt out, but
  "logged in" and "administrator" are different questions. Extensions get a
  neutral projection of the caller rather than the host's auth context, and
  `require_admin` fails closed when identity cannot be determined.

Extension-owned tables
  An extension that persists data owns its own MetaData and migration chain, so
  its tables are absent from Base.metadata and `alembic revision --autogenerate`
  proposes dropping them. Extensions declare a table prefix, which is rejected
  at registration if it would shadow a host table.

The contract package stays dependency-free and imports no host code; every new
Protocol method has a default so later additions remain additive. The loader's
pre-1.0 rule requires an exact major.minor match, so extensions written against
0.1 are now refused at startup with an actionable install hint rather than
loading into a host that implements a different surface.

uv.lock records the contract package's new version, so `uv sync --locked` still
resolves on a fresh checkout.

* fix(backend): sort gateway service imports
2026-08-23 09:57:12 +08:00

96 lines
3.3 KiB
Python

"""Who produced a message, declared by the producer.
DeerFlow's middleware chain injects and rewrites messages: a date reminder, a
recalled-memory block, a compaction summary, a durable-context data block, an
image payload, an activated skill body. By the time any of those reach the
model-call boundary, the component that produced them is no longer recoverable
from the message itself — an observer would have to infer it from wording,
which breaks the moment a prompt is reworded.
The producing middleware therefore stamps the fact. Keys live here, in the
contract package, rather than in the host: an extension pinned to this contract
version must be able to rely on the facility existing, and only a shared
declaration makes that checkable.
Values are plain strings, not enum members, so an unknown producer from a newer
host degrades to an unrecognised string rather than an import error.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
MESSAGE_CONTENT_KIND_KEY = "deerflow_content_kind"
MESSAGE_PRODUCER_KIND_KEY = "deerflow_producer_kind"
MESSAGE_PRODUCER_ENTITY_ID_KEY = "deerflow_producer_entity_id"
#: Every key this contract owns. The host treats all of them as server-owned and
#: strips caller-supplied values from untrusted input.
PROVENANCE_KEYS: frozenset[str] = frozenset(
{
MESSAGE_CONTENT_KIND_KEY,
MESSAGE_PRODUCER_KIND_KEY,
MESSAGE_PRODUCER_ENTITY_ID_KEY,
}
)
class ContentKind(StrEnum):
"""What a stamped message *is*, independent of which component made it."""
MIDDLEWARE_INJECTION = "middleware_injection"
MEMORY = "memory"
DURABLE_CONTEXT = "durable_context"
SKILL_BODY = "skill_body"
IMAGE_PAYLOAD = "image_payload"
@dataclass(frozen=True)
class MessageProvenance:
content_kind: str
producer_kind: str
producer_entity_id: str | None = None
def provenance_kwargs(
content_kind: str,
producer_kind: str,
*,
producer_entity_id: str | None = None,
) -> dict[str, str]:
"""Build the ``additional_kwargs`` fragment a producer merges into its message.
Optional fields are omitted rather than written as ``None`` so a stamped
message carries no keys whose value says nothing.
"""
kwargs = {
MESSAGE_CONTENT_KIND_KEY: str(content_kind),
MESSAGE_PRODUCER_KIND_KEY: str(producer_kind),
}
if producer_entity_id is not None:
kwargs[MESSAGE_PRODUCER_ENTITY_ID_KEY] = str(producer_entity_id)
return kwargs
def read_provenance(message: object) -> MessageProvenance | None:
"""Return the stamp, or ``None`` when absent or malformed.
Both required fields must be present strings; a partial or wrongly-typed
stamp is treated as absent rather than as a half-truth an observer would
then record as fact.
"""
kwargs = getattr(message, "additional_kwargs", None)
if not isinstance(kwargs, dict):
return None
content_kind = kwargs.get(MESSAGE_CONTENT_KIND_KEY)
producer_kind = kwargs.get(MESSAGE_PRODUCER_KIND_KEY)
if not isinstance(content_kind, str) or not isinstance(producer_kind, str):
return None
entity_id = kwargs.get(MESSAGE_PRODUCER_ENTITY_ID_KEY)
return MessageProvenance(
content_kind=content_kind,
producer_kind=producer_kind,
producer_entity_id=entity_id if isinstance(entity_id, str) else None,
)