mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-26 16:07:53 +00:00
* feat(channels): add GitHub event-driven agents (#3754) Add a webhook-driven GitHub channel with fail-closed webhook routing, deterministic per-agent PR/issue threads, mention-gated trigger fan-out, GitHub App token injection for sandboxed gh/git commands, and backend/AGENTS.md documentation. * fix(llm-middleware): classify bare IndexError as transient Upstream chat providers occasionally return 200 OK with an empty generations list (observed against Volces "coding" on ark.cn-beijing.volces.com). When that happens, langchain_core.language_models.chat_models.ainvoke raises ``IndexError: list index out of range`` at ``llm_result.generations[0][0].message`` and kills the run. Treat a bare IndexError reaching the middleware as a transient upstream-payload glitch and route it through the existing retry/backoff path instead of failing the whole agent run. The retry budget and backoff schedule are unchanged. Adds three regression tests covering the classifier and both the recover-on-retry and exhausted-retries paths. * fix(runtime): ignore stale LLM fallback markers from prior runs When a run on a thread ends with the LLM-error-handling middleware emitting a `deerflow_error_fallback`-marked AIMessage (e.g. after the IndexError empty-generations classification fix lands), that message is persisted to the thread's checkpoint as part of the messages channel. LangGraph replays the full message history in `stream_mode="values"` chunks, so every subsequent run on the same thread re-streams the stale fallback marker — and the worker's chunk scanner faithfully picks it up, flipping `RunStatus.success` to `RunStatus.error` for runs that themselves had no LLM failure at all. Snapshot the set of pre-existing message ids from the pre-run checkpoint and thread it through `_extract_llm_error_fallback_message` / `_try_extract_from_message` as a filter. Markers on history messages are ignored; markers on fresh messages produced during this run still trip the error path. Falls back to an empty set when the checkpointer is absent or the snapshot can't be captured, preserving the prior behavior on first-run / no-state paths. Adds unit tests for the new filter (helper-level and `_collect_pre_existing_message_ids`) plus an integration test exercising the full `run_agent` path with a stale history checkpointer. * fix(channels): make github channel fire-and-forget to avoid httpx.ReadTimeout on long runs GitHub agent runs (clone -> edit -> test -> push -> PR) routinely exceed the langgraph_sdk default 300s read deadline. The manager's runs.wait call kept an HTTP stream open for the entire run lifetime, so the long run blew up with httpx.ReadTimeout and the outer except branch then released the dedupe key and emitted a false 'internal error' outbound. The GitHub channel's outbound send is log-only by design: agents post to the issue/PR via the gh CLI in the sandbox when they choose to comment or create a PR. There is nothing for the manager to ferry back, so the long-poll was pure overhead. This change adds ChannelRunPolicy.fire_and_forget (default False) and sets it True for the github channel. When fire_and_forget is True, _handle_chat dispatches via client.runs.create (short POST, returns once the run is pending) instead of client.runs.wait, and skips the response-extraction + outbound-publish block. ConflictError on a busy thread still trips the standard THREAD_BUSY_MESSAGE path so behavior on the busy case is preserved for any future non-github fire-and-forget channel. Other (non-github) channels are unchanged: their policy defaults fire_and_forget=False and they continue to dispatch via runs.wait. Adds 6 regression tests in tests/test_channels.py::TestGithubFireAndForget: - Default ChannelRunPolicy.fire_and_forget is False. - The github policy registers fire_and_forget=True. - github inbound calls runs.create, not runs.wait, with the right kwargs. - github inbound publishes no outbound on success. - ConflictError from runs.create still emits THREAD_BUSY_MESSAGE. - Non-github channels (slack) still dispatch via runs.wait. * test(lead-agent): accept user_id kwarg in skill-policy test stubs The two GitHub-channel tests added in #3754 stubbed _load_enabled_skills_for_tool_policy with a lambda that only accepted `available_skills` and `app_config`, but the real function (and its call site in agent.py) also passes `user_id`. This raised TypeError on every run, failing backend-unit-tests. Add `user_id=None` to match the three sibling stubs in the same file. * refactor(gateway): disambiguate context-key set names The two frozensets _INTERNAL_ONLY_CONTEXT_KEYS and _CONTEXT_ONLY_KEYS shared a confusable "CONTEXT_ONLY" token in different orders, and the first broke the _CONTEXT_<X>_KEYS pattern of its sibling _CONTEXT_CONFIGURABLE_KEYS. Rename to make the distinct axes explicit: _CONTEXT_INTERNAL_CALLER_KEYS - WHO: internal callers (scheduler) only _CONTEXT_RUNTIME_ONLY_KEYS - WHERE: runtime context only, never configurable Pure rename, no behavior change.
94 lines
4.6 KiB
Python
94 lines
4.6 KiB
Python
"""Per-channel run policy registry.
|
|
|
|
Holds the global ``CHANNEL_RUN_POLICY`` map and its :class:`ChannelRunPolicy`
|
|
descriptor. Split into its own module so channels can register their own
|
|
policy entries (typically as a side-effect of importing their package)
|
|
without creating a circular dependency on :mod:`app.channels.manager`.
|
|
|
|
The dispatch path in :class:`app.channels.manager.ChannelManager` looks
|
|
up policy entries by ``msg.channel_name`` and applies them after
|
|
``_resolve_run_params``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Awaitable, Callable
|
|
from dataclasses import dataclass
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
if TYPE_CHECKING:
|
|
from app.channels.message_bus import InboundMessage
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ChannelRunPolicy:
|
|
"""Per-channel knobs applied by :meth:`ChannelManager._apply_channel_policy`.
|
|
|
|
Webhook-driven channels (GitHub today; others later) need four
|
|
things the generic interactive-chat path does not: a higher
|
|
``recursion_limit`` for autonomous long runs, suppression of
|
|
``ask_clarification`` (no human is synchronously present), a
|
|
credentials provider that mints platform tokens for the agent, and
|
|
an opt-out from the per-sender bound-identity gate (authenticity is
|
|
enforced at the webhook route by HMAC, and there is no equivalent
|
|
of a per-user ``/connect`` handshake to perform).
|
|
|
|
Declaring all four on one dataclass keeps the channel's run
|
|
behavior in a single discoverable place and turns "add a new
|
|
webhook channel" into a one-row registration instead of touching
|
|
multiple separate methods on the manager.
|
|
|
|
Attributes:
|
|
is_interactive: When False, the manager sets
|
|
``run_context["disable_clarification"] = True`` so
|
|
``ClarificationMiddleware`` returns a "proceed with best
|
|
judgment" ToolMessage instead of interrupting via
|
|
``Command(goto=END)``. Defaults to True (the safe default
|
|
for an IM channel).
|
|
default_recursion_limit: When set, the manager raises
|
|
``run_config["recursion_limit"]`` to ``max(existing,
|
|
limit)``. None leaves the global default (100) untouched —
|
|
interactive chat turns don't need 250 super-steps.
|
|
credentials_provider: Optional async hook that mutates
|
|
``run_context`` with platform-specific credentials. Called
|
|
after ``_resolve_run_params``. Exceptions are caught and
|
|
logged so a credential failure degrades gracefully (agent
|
|
runs read-only) instead of dropping the delivery.
|
|
requires_bound_identity: When False, the manager skips the
|
|
per-sender bound-identity gate (``_get_bound_identity_rejection``)
|
|
for this channel even when ``channel_connections.enabled`` is
|
|
on. Webhook-authenticated channels (GitHub) have no
|
|
per-sender ``/connect`` handshake — authenticity is enforced
|
|
by HMAC at the webhook route, and the binding from "sender"
|
|
to DeerFlow user is encoded in the agent's ``config.yaml``
|
|
ownership, not in the channel-connections table. Defaults to
|
|
True (the safe default for an interactive IM channel).
|
|
fire_and_forget: When True, the manager schedules the run with
|
|
``runs.create`` (returns immediately once the run is
|
|
``pending``) instead of ``runs.wait`` (which keeps an HTTP
|
|
stream open for the entire run lifetime). Channels that do
|
|
their own outbound during the run — e.g. GitHub, where the
|
|
agent posts to the issue/PR via the ``gh`` CLI in its
|
|
sandbox — don't need the manager to ferry a final state
|
|
back. Eliminates the SDK's 300s ``httpx.ReadTimeout`` on
|
|
runs that legitimately take more than 5 minutes, and the
|
|
false "internal error" outbound that follows when it
|
|
fires. Defaults to False (the safe default for an
|
|
interactive IM channel that depends on the manager to
|
|
publish the agent's reply).
|
|
"""
|
|
|
|
is_interactive: bool = True
|
|
default_recursion_limit: int | None = None
|
|
credentials_provider: Callable[[InboundMessage, dict[str, Any]], Awaitable[None]] | None = None
|
|
requires_bound_identity: bool = True
|
|
fire_and_forget: bool = False
|
|
|
|
|
|
# Channel name → policy. Channels absent from this map fall through to
|
|
# the policy default (an interactive IM channel with no credential
|
|
# plumbing) — which is what every IM channel had before GitHub. Webhook
|
|
# channels register their entry at package-import time (see
|
|
# ``app.gateway.github.run_policy``).
|
|
CHANNEL_RUN_POLICY: dict[str, ChannelRunPolicy] = {}
|