mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(github): separate webhook runs from tool authentication (#8485)
* fix(github): separate webhook runs from tool authentication Signed-off-by: Willem Jiang <willem.jiang@gmail.com> * docs(github): explain App authorization for MCP Signed-off-by: Willem Jiang <willem.jiang@gmail.com> --------- Signed-off-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
53e6042c29
commit
ee54c96300
@ -123,6 +123,7 @@ Each guide is the full reference for its topic. Open the one you need.
|
||||
| Projects, instructions, document shelf | [Projects](docs/guide/projects.md) |
|
||||
| Scheduled tasks | [Scheduled Tasks](docs/guide/scheduled-tasks.md) |
|
||||
| Feishu, Slack, Telegram, Discord, DingTalk and other IM channels | [IM Channels](docs/guide/im-channels.md) |
|
||||
| GitHub webhooks and tool setup | [GitHub Event-Driven Agents](backend/docs/GITHUB_AGENTS.md) |
|
||||
| File attachments, downloads and Office previews | [File Previews](docs/guide/file-previews.md) |
|
||||
| Token usage dashboard, workspace, chat archive | [Workspace UI](docs/guide/workspace.md) |
|
||||
| Terminal workbench | [Terminal Workbench (TUI)](docs/guide/tui.md) |
|
||||
|
||||
@ -80,8 +80,8 @@ make test-blocking-io # channels share the Gate
|
||||
|
||||
- The webhook route skips session auth and CSRF because the HMAC signature
|
||||
authenticates it. It is mounted only when `GITHUB_WEBHOOK_SECRET` is set.
|
||||
- Outbound is log-only by design. Each agent posts its own comment with `gh` from
|
||||
its sandbox, so the manager starts the run and does not wait for it.
|
||||
- Outbound is log-only. The agent uses configured GitHub tools for outbound
|
||||
actions. Webhook admission stays independent of tool authentication.
|
||||
- Follow-up buffering while a thread is busy is process-local. Read
|
||||
[the contract](../../docs/GITHUB_AGENTS.md#follow-up-buffering-while-busy-4121)
|
||||
before you change it.
|
||||
|
||||
@ -17,14 +17,14 @@ Why log-only rather than auto-post:
|
||||
|
||||
- Two agents can bind the same event (e.g. coder + reviewer on a mention).
|
||||
If both auto-posted their final messages, the user would see two replies
|
||||
for every mention even when only one had useful work to do. Letting the
|
||||
LLM call ``gh`` mid-run means silence is just "the LLM did not call gh."
|
||||
for every mention even when only one had useful work to do. Each agent
|
||||
chooses whether to post using its configured tools.
|
||||
- The agent often wants to post *intermediate* updates (an issue comment
|
||||
linking the PR, a separate comment on a new sub-issue, …) — the
|
||||
auto-post-the-final-message contract didn't model that and forced the
|
||||
final message to play double duty.
|
||||
- The dispatcher's per-agent ``_is_self_event`` gate already prevents the
|
||||
comments the LLM posts via ``gh`` from looping the webhook back into a
|
||||
comments the agent posts from looping the webhook back into a
|
||||
new run for the same agent.
|
||||
"""
|
||||
|
||||
@ -85,9 +85,8 @@ class GitHubChannel(Channel):
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
"""Log the agent's final message — do NOT post it to GitHub.
|
||||
|
||||
GitHub agents post to issues/PRs themselves via ``gh`` mid-run; the
|
||||
final assistant message is logged for ``gateway.log`` visibility but
|
||||
is not delivered to the platform. See the module docstring for why.
|
||||
GitHub agents use configured tools to post to issues and PRs. The
|
||||
final assistant message goes to ``gateway.log``.
|
||||
|
||||
Metadata layout (read for logging context only):
|
||||
- ``repo`` (str, e.g. ``"owner/name"``) — falls back to ``chat_id``
|
||||
|
||||
@ -2327,10 +2327,7 @@ class ChannelManager:
|
||||
``ClarificationMiddleware`` would otherwise dead-end a webhook
|
||||
run waiting for a synchronous reply that only arrives as a
|
||||
later, separate webhook delivery.
|
||||
* Channel-specific credentials provider — e.g. the GitHub channel
|
||||
installs a token-mint callable so ``bash_tool`` can resolve a
|
||||
fresh installation token on every invocation (longer than the
|
||||
1h GitHub TTL).
|
||||
* Optional channel-specific credentials provider.
|
||||
|
||||
``recursion_limit`` is applied inside :meth:`_resolve_run_params`
|
||||
instead because it lives on ``run_config`` (not ``run_context``)
|
||||
@ -3411,11 +3408,7 @@ class ChannelManager:
|
||||
pinned_model_value = run_context.get("model_name")
|
||||
expected_pin = pinned_model_value.strip() if isinstance(pinned_model_value, str) and pinned_model_value.strip() else None
|
||||
|
||||
# Apply per-channel policy: credentials provider (e.g. GitHub
|
||||
# installation-token mint) and the non-interactive flag for
|
||||
# webhook channels. Driven by CHANNEL_RUN_POLICY so each new
|
||||
# webhook channel is a one-row registration, not a fresh
|
||||
# if-branch here.
|
||||
# Apply the run policy registered by the channel.
|
||||
policy = await self._apply_channel_policy(msg, run_context)
|
||||
|
||||
# If the inbound message contains file attachments, let the channel
|
||||
|
||||
@ -8,7 +8,6 @@ single-purpose modules so each piece can be tested in isolation:
|
||||
* :mod:`prompts` — payload → user prompt strings.
|
||||
* :mod:`registry` — scan custom agents and index them by (repo, event).
|
||||
* :mod:`app_auth` — GitHub App JWT and installation-token minting.
|
||||
* :mod:`writeback` — POST comments back to GitHub.
|
||||
* :mod:`run_policy` — ChannelRunPolicy entry registered into ChannelManager.
|
||||
* :mod:`dispatcher` — orchestrates all of the above and creates a langgraph run.
|
||||
|
||||
@ -17,8 +16,5 @@ of this package.
|
||||
"""
|
||||
|
||||
# Side-effect import: registers the GitHub channel's ChannelRunPolicy
|
||||
# (non-interactive flag, recursion_limit bump, installation-token
|
||||
# provider) so the manager finds it on first delivery — and tests that
|
||||
# build a ChannelManager directly inherit the registration as soon as
|
||||
# anything inside this subpackage is imported.
|
||||
# so the manager and tests find it before the first delivery.
|
||||
from app.gateway.github import run_policy # noqa: F401
|
||||
|
||||
@ -9,12 +9,8 @@ Design notes:
|
||||
("review this PR"), so the agent's SOUL.md gets to define behavior.
|
||||
The dispatcher appends one terse instruction at the end so a stock
|
||||
``lead_agent`` SOUL still does something useful.
|
||||
* The channel layer is **log-only on the outbound path** — the agent's
|
||||
final message goes to ``gateway.log`` and is NOT posted to GitHub.
|
||||
If the agent wants to reply on the PR/issue, it must call ``gh`` (or
|
||||
the equivalent REST API) **during** the run. We do not promise the
|
||||
agent that "your final message will be posted." That used to be true;
|
||||
it isn't any more.
|
||||
* The channel logs the final message. GitHub actions during the run use
|
||||
GitHub tools configured for the agent.
|
||||
* We embed the comment body verbatim because that's the most useful
|
||||
signal — the agent needs to see what the human actually typed. We
|
||||
do not try to escape it; agents understand markdown.
|
||||
@ -51,10 +47,9 @@ def _pull_request_prompt(payload: dict[str, Any]) -> str:
|
||||
f" Author: {author}\n"
|
||||
f" URL: {url}\n\n"
|
||||
f"Description:\n{body or '(no description)'}\n\n"
|
||||
f"Decide what action (if any) to take for this pull request and carry it out. "
|
||||
f"Your final assistant message is for the run log only — it will NOT be "
|
||||
f"posted to GitHub. If you want to reply on the PR, call `gh pr comment` "
|
||||
f"(or `gh pr review`) yourself during the run."
|
||||
"Decide what action (if any) to take in response to this event. "
|
||||
"Your final assistant message goes to the run log. "
|
||||
"Use a configured GitHub tool for actions that require repository access."
|
||||
)
|
||||
|
||||
|
||||
@ -91,10 +86,9 @@ def _issue_comment_prompt(payload: dict[str, Any]) -> str:
|
||||
f" Author: {author}\n"
|
||||
f" URL: {url}\n\n"
|
||||
f" Body:\n{body or '(empty comment)'}\n\n"
|
||||
f"Decide what action (if any) to take in response to this comment, in the context "
|
||||
f"of the parent {target} above. Your final assistant message is for the run log "
|
||||
f"only — it will NOT be posted to GitHub. If you want to reply, call "
|
||||
f"`gh issue comment {number} --repo {repo} --body-file -` yourself during the run."
|
||||
"Decide what action (if any) to take in response to this event. "
|
||||
"Your final assistant message goes to the run log. "
|
||||
"Use a configured GitHub tool for actions that require repository access."
|
||||
)
|
||||
|
||||
|
||||
@ -117,10 +111,9 @@ def _pr_review_comment_prompt(payload: dict[str, Any]) -> str:
|
||||
f" File: {path}:{line}\n\n"
|
||||
f" Diff context:\n```\n{diff_hunk}\n```\n\n"
|
||||
f" Body:\n{body or '(empty comment)'}\n\n"
|
||||
f"Decide what action (if any) to take in response to this review comment, in the "
|
||||
f"context of the parent pull request above. Your final assistant message is for the "
|
||||
f"run log only — it will NOT be posted to GitHub. If you want to reply, call "
|
||||
f"`gh pr comment {number} --repo {repo} --body-file -` yourself during the run."
|
||||
"Decide what action (if any) to take in response to this event. "
|
||||
"Your final assistant message goes to the run log. "
|
||||
"Use a configured GitHub tool for actions that require repository access."
|
||||
)
|
||||
|
||||
|
||||
@ -149,7 +142,7 @@ def _pr_review_prompt(payload: dict[str, Any]) -> str:
|
||||
# instruction never renders a broken `gh api` path.
|
||||
fetch_hint = ""
|
||||
if review_id is not None and number is not None:
|
||||
fetch_hint = f"This review's inline comments are not included in this message. Before deciding what to do, fetch them with `gh api repos/{repo}/pulls/{number}/reviews/{review_id}/comments`.\n\n"
|
||||
fetch_hint = f"This review's inline comments are not included in this message. Before deciding what to do, use a configured GitHub tool to fetch them from `repos/{repo}/pulls/{number}/reviews/{review_id}/comments`.\n\n"
|
||||
return (
|
||||
f"A pull request review was submitted on #{number} in {repo}.\n\n"
|
||||
f"{parent_block}\n"
|
||||
@ -158,12 +151,9 @@ def _pr_review_prompt(payload: dict[str, Any]) -> str:
|
||||
f" State: {state}\n\n"
|
||||
f" Body:\n{body or '(no review body)'}\n\n"
|
||||
f"{fetch_hint}"
|
||||
f"Decide what action (if any) to take in response to this review, in the context "
|
||||
f"of the parent pull request above. Your final assistant message is for the run "
|
||||
f"log only — it will NOT be posted to GitHub. If you want to reply (or push a fix), "
|
||||
f"call `gh pr comment {number} --repo {repo} --body-file -` (and the usual "
|
||||
f"`git clone` / `gh pr checkout` / `git push` flow for code changes) yourself "
|
||||
f"during the run."
|
||||
"Decide what action (if any) to take in response to this event. "
|
||||
"Your final assistant message goes to the run log. "
|
||||
"Use a configured GitHub tool for actions that require repository access."
|
||||
)
|
||||
|
||||
|
||||
@ -182,11 +172,9 @@ def _issues_prompt(payload: dict[str, Any]) -> str:
|
||||
f" Author: {author}\n"
|
||||
f" URL: {url}\n\n"
|
||||
f"Description:\n{body or '(no description)'}\n\n"
|
||||
f"Decide what action (if any) to take for this issue and carry it out. "
|
||||
f"Your final assistant message is for the run log only — it will NOT be "
|
||||
f"posted to GitHub. If you want to reply on the issue (or open a PR), call "
|
||||
f"`gh issue comment {number} --repo {repo} --body-file -` / `gh pr create` "
|
||||
f"yourself during the run."
|
||||
"Decide what action (if any) to take in response to this event. "
|
||||
"Your final assistant message goes to the run log. "
|
||||
"Use a configured GitHub tool for actions that require repository access."
|
||||
)
|
||||
|
||||
|
||||
|
||||
@ -1,92 +1,7 @@
|
||||
"""Per-run policy hooks for the GitHub channel.
|
||||
|
||||
The generic ``ChannelManager`` looks up a :class:`ChannelRunPolicy`
|
||||
keyed on ``msg.channel_name`` and applies it after ``_resolve_run_params``
|
||||
but before the agent runs. The GitHub channel registers its policy
|
||||
entry from :func:`register_policy`, called once from the gateway
|
||||
bootstrap.
|
||||
|
||||
Keeping the GitHub-specific provider closure here (rather than inline
|
||||
in ``ChannelManager``) lets every new webhook channel ship its own
|
||||
``run_policy.py`` with the same shape, with no edits to the manager.
|
||||
"""
|
||||
"""Per-run policy for inbound GitHub events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.channels.message_bus import InboundMessage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def inject_github_credentials(msg: InboundMessage, run_context: dict[str, Any]) -> None:
|
||||
"""Install a GitHub App installation token in ``run_context``.
|
||||
|
||||
The GitHub fan-out dispatcher carries each binding's
|
||||
``installation_id`` in ``msg.metadata["github"]``. We mint a
|
||||
short-lived (1h) installation token and put the resulting **string**
|
||||
into ``run_context["github_token"]``.
|
||||
|
||||
Why a string and not a closure:
|
||||
``run_context`` is passed to ``client.runs.wait(context=…)``
|
||||
on the ``langgraph_sdk`` HTTP client, which JSON-encodes the
|
||||
payload before sending it to Gateway's LangGraph-compatible
|
||||
runtime over HTTP — even when that runtime is embedded in the
|
||||
same process. A Python callable does not survive that
|
||||
encoding (``TypeError: Type is not JSON serializable: function``).
|
||||
The harness side (``_github_env_from_runtime`` in
|
||||
``packages/harness/deerflow/sandbox/tools.py``) already accepts
|
||||
either a ``str`` or a zero-arg sync callable from
|
||||
``runtime.context["github_token"]``; only the ``str`` shape
|
||||
round-trips through the SDK transport, so that is what we
|
||||
ship.
|
||||
|
||||
Failure modes for autonomous runs that span past the 1h token TTL:
|
||||
The minted token is valid for 1h. Most agent runs complete well
|
||||
inside that window. Truly long coder runs (multi-hour refactors
|
||||
on the higher ``recursion_limit=250`` ceiling) may see a 401 on
|
||||
a late ``git push`` / ``gh pr create``. The fix for that —
|
||||
re-installing a token-refresh hook on the **runtime side** by
|
||||
pushing the ``installation_id`` through ``run_context`` and
|
||||
looking up a process-local provider in the harness — is
|
||||
deliberately deferred: it crosses the harness/app boundary
|
||||
(``tests/test_harness_boundary.py``) and needs a registered
|
||||
token-provider lookup, not a string-vs-closure switch.
|
||||
|
||||
Minting on the bus-consumer side (not in the webhook route) keeps
|
||||
GitHub's 10s delivery timeout safe. Mint failures propagate up to
|
||||
:meth:`ChannelManager._apply_channel_policy`, which logs and lets
|
||||
the run proceed without credentials (read-only is better than no
|
||||
response).
|
||||
"""
|
||||
if msg.channel_name != "github":
|
||||
return
|
||||
meta = msg.metadata if isinstance(msg.metadata, dict) else {}
|
||||
gh = meta.get("github")
|
||||
if not isinstance(gh, dict):
|
||||
return
|
||||
installation_id = gh.get("installation_id")
|
||||
if not isinstance(installation_id, int) or installation_id <= 0:
|
||||
return
|
||||
|
||||
from app.gateway.github.app_auth import mint_installation_token
|
||||
|
||||
# Mint and ship the token string. ``mint_installation_token`` caches
|
||||
# with a 5-min leeway, so subsequent runs against the same
|
||||
# installation reuse the cached token until ~55 min into its TTL.
|
||||
# Failures (bad App id, wrong installation_id, missing private key)
|
||||
# propagate to ``_apply_channel_policy``, which handles logging
|
||||
# without dropping the delivery.
|
||||
token = await mint_installation_token(installation_id)
|
||||
run_context["github_token"] = token
|
||||
logger.info(
|
||||
"[github-run-policy] installed installation token for installation_id=%s (TTL ~1h)",
|
||||
installation_id,
|
||||
)
|
||||
|
||||
|
||||
def register_policy() -> None:
|
||||
"""Register the GitHub channel's :class:`ChannelRunPolicy` entry.
|
||||
@ -110,7 +25,6 @@ def register_policy() -> None:
|
||||
# Per-agent overrides via GitHubAgentConfig.recursion_limit still
|
||||
# win (read in ChannelManager._resolve_run_params from msg.metadata).
|
||||
default_recursion_limit=250,
|
||||
credentials_provider=inject_github_credentials,
|
||||
# GitHub deliveries are HMAC-authenticated 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
|
||||
@ -119,9 +33,8 @@ def register_policy() -> None:
|
||||
# the agent even when channel_connections.enabled=True for
|
||||
# interactive IM channels in the same deployment.
|
||||
requires_bound_identity=False,
|
||||
# GitHub agents post their own outbound to the issue/PR via the
|
||||
# ``gh`` CLI in the sandbox; the channel's ``send`` is log-only
|
||||
# by design. We don't need to keep an HTTP stream open on
|
||||
# GitHub agents use configured tools for outbound actions. The
|
||||
# channel's ``send`` is log-only by design. We don't need to keep an HTTP stream open on
|
||||
# ``runs.wait`` for ~6-minute coding runs and then watch it die
|
||||
# at the SDK's 300s ``httpx.ReadTimeout``. Fire-and-forget swaps
|
||||
# the manager call to ``runs.create`` (returns immediately once
|
||||
@ -130,7 +43,7 @@ def register_policy() -> None:
|
||||
# still raised synchronously by ``start_run`` before the run is
|
||||
# accepted, so the busy-thread path is preserved.
|
||||
fire_and_forget=True,
|
||||
# GitHub's ``send`` is log-only (agents post via ``gh`` themselves),
|
||||
# GitHub's ``send`` is log-only,
|
||||
# so a busy-thread ``THREAD_BUSY_MESSAGE`` is otherwise invisible to
|
||||
# the commenter — a concurrent comment is silently dropped from
|
||||
# their point of view (issue #4121). Buffering + draining follow-ups
|
||||
|
||||
@ -1247,6 +1247,8 @@ _SERVER_OWNED_RUNTIME_CONTEXT_KEYS: frozenset[str] = (
|
||||
# never survive in either run-config section.
|
||||
PROJECT_CONTEXT_KEY,
|
||||
AGENT_AUTH_CONTEXT_KEY,
|
||||
# Obsolete run field. Discard it even on internal requests.
|
||||
"github_token",
|
||||
MCP_BROWSER_USER_CONTEXT_KEY,
|
||||
KNOWLEDGE_SCOPE_KEY,
|
||||
KNOWLEDGE_SCOPE_RUNTIME_KEY,
|
||||
@ -1259,14 +1261,8 @@ _SERVER_OWNED_RUNTIME_CONTEXT_KEYS: frozenset[str] = (
|
||||
# runtime context that becomes ``ToolRuntime.context`` / ``runtime.context``),
|
||||
# never into ``config['configurable']``. These are read by tools and
|
||||
# middlewares from ``runtime.context`` and have no reason to live in
|
||||
# ``configurable`` — and ``configurable`` is persisted in checkpoints, so
|
||||
# keeping secrets like ``github_token`` out of it avoids writing a
|
||||
# short-lived installation token into the checkpoint store.
|
||||
# ``configurable``, which is persisted in checkpoints.
|
||||
#
|
||||
# ``github_token`` — App installation token minted by the GitHub
|
||||
# channel; the bash tool exposes it as
|
||||
# ``GH_TOKEN``/``GITHUB_TOKEN`` so ``gh`` and
|
||||
# ``git`` push as the bot, not the host user.
|
||||
# ``disable_clarification`` — set for non-interactive channels (GitHub
|
||||
# webhooks) so ClarificationMiddleware proceeds
|
||||
# instead of dead-ending the run.
|
||||
@ -1277,7 +1273,7 @@ _SERVER_OWNED_RUNTIME_CONTEXT_KEYS: frozenset[str] = (
|
||||
# (``ChannelManager._apply_channel_policy`` and ``app.gateway.github.run_policy``),
|
||||
# which reach the Gateway over the internally-authenticated request channel, so
|
||||
# they are internal-only as well — see :data:`_INTERNAL_ONLY_CONTEXT_KEYS`.
|
||||
_CONTEXT_RUNTIME_ONLY_KEYS: frozenset[str] = frozenset({"github_token", "disable_clarification", "channel_name"})
|
||||
_CONTEXT_RUNTIME_ONLY_KEYS: frozenset[str] = frozenset({"disable_clarification", "channel_name"})
|
||||
|
||||
# Public run-only controls are accepted through body.context, not body.config.
|
||||
_MODEL_SELECTION_CONTEXT_KEYS = frozenset({"subagent_model_name", "model_selection_requested"})
|
||||
@ -1291,10 +1287,7 @@ _MODEL_SELECTION_CONTEXT_KEYS = frozenset({"subagent_model_name", "model_selecti
|
||||
# included — with "proceed without asking" instead of interrupting, and
|
||||
# ``SandboxMiddleware`` reads the two keys as the same non-interactive signal.
|
||||
# Accepting it from a client therefore reproduces the effect the
|
||||
# ``non_interactive`` gate exists to prevent. ``github_token`` is a live
|
||||
# credential that ``bash`` exports as ``GH_TOKEN``/``GITHUB_TOKEN``, and a copy
|
||||
# smuggled through ``body.config['configurable']`` would be written to the
|
||||
# checkpoint store.
|
||||
# ``non_interactive`` gate exists to prevent.
|
||||
_INTERNAL_ONLY_CONTEXT_KEYS: frozenset[str] = _CONTEXT_INTERNAL_CALLER_KEYS | _CONTEXT_RUNTIME_ONLY_KEYS | _SERVER_OWNED_RUNTIME_CONTEXT_KEYS
|
||||
|
||||
|
||||
@ -1341,12 +1334,8 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An
|
||||
is True; for non-internal callers those keys are dropped from client requests
|
||||
by :func:`strip_internal_context_keys`.
|
||||
|
||||
A second set of keys (``_CONTEXT_RUNTIME_ONLY_KEYS`` — e.g. ``github_token``,
|
||||
``disable_clarification``) is likewise forwarded only when ``internal`` is True,
|
||||
and then into ``config['context']`` only, never ``configurable``. These are
|
||||
secrets / runtime flags read by tools and middlewares from ``runtime.context``;
|
||||
keeping them out of ``configurable`` avoids persisting a short-lived token in the
|
||||
checkpoint store.
|
||||
Runtime-only flags such as ``disable_clarification`` are forwarded only for
|
||||
internal requests and land exclusively in ``config['context']``.
|
||||
|
||||
Client capability context is runtime-only: it is sanitized and copied into
|
||||
``config['context']['client']`` but never into ``configurable``.
|
||||
@ -1405,7 +1394,7 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An
|
||||
runtime_context[key] = value
|
||||
if "model_selection_requested" in context and (context.get("model_name") != context["model_selection_requested"] or not isinstance(runtime_context, dict) or runtime_context.get("model_name") != context["model_selection_requested"]):
|
||||
raise HTTPException(status_code=400, detail="model_selection_requested must match model_name in context.")
|
||||
# Context-only keys (secrets / runtime flags) land in ``config['context']``
|
||||
# Runtime-only flags land in ``config['context']``
|
||||
# only — never ``configurable`` (which is persisted in checkpoints) — and only
|
||||
# for internal callers, the sole legitimate producers.
|
||||
if internal:
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
# GitHub Event-Driven Agents
|
||||
|
||||
GitHub is a **webhook-push** channel: there is no long-polling worker. Every GitHub App / repository delivery lands at `POST /api/webhooks/github`, where it is HMAC-verified, fan-out'd to one `InboundMessage` per matching custom-agent binding, and shipped to the rest of DeerFlow through the same `ChannelManager` that handles Feishu/Slack/Telegram. For the high-level orientation, see [AGENTS.md](../AGENTS.md) → "GitHub event-driven agents".
|
||||
GitHub is a **webhook-push** channel: there is no long-polling worker. Every GitHub App / repository delivery lands at `POST /api/webhooks/github`, where it is HMAC-verified, fan-out'd to one `InboundMessage` per matching custom-agent binding, and shipped to the rest of DeerFlow through the same `ChannelManager` that handles Feishu/Slack/Telegram. For the high-level orientation, see [channel guidance](../app/channels/AGENTS.md#github-channel).
|
||||
|
||||
This document covers the **architecture** of that pipeline:
|
||||
This guide covers setup and the architecture of that pipeline:
|
||||
|
||||
- Per-agent bindings (`config.yaml` → `github:` block)
|
||||
- Webhook → fan-out → `InboundMessage` dispatch
|
||||
- Mention-handle precedence for `require_mention` triggers
|
||||
- `preferred_thread_id = UUID5(repo, number, agent_name)` thread determinism
|
||||
- GH token lifecycle (`GITHUB_APP_ID` + `PRIVATE_KEY` → `run_context["github_token"]` → sandbox `GH_TOKEN`/`GITHUB_TOKEN`)
|
||||
- [Configuring GitHub tools for webhook runs](#github-tool-setup)
|
||||
- `ConflictError` (HTTP 409) thread-create race recovery
|
||||
- Why **outbound is log-only** (agents post via `gh` from their sandbox)
|
||||
- Why **outbound is log-only**
|
||||
- Follow-up buffering while busy (issue #4121): buffer → watch → drain, and the single-process scope limit
|
||||
|
||||
## Overview
|
||||
@ -86,7 +86,7 @@ sequenceDiagram
|
||||
Mgr->>Client: runs.create() [fire_and_forget=True]
|
||||
Client->>Gateway: start run
|
||||
Gateway-->>Client: pending
|
||||
Note over Mgr: Manager returns immediately.<br/>Agent posts to GitHub via gh CLI.
|
||||
Note over Mgr: Manager returns immediately.<br/>The agent can use configured GitHub tools.
|
||||
```
|
||||
|
||||
## `preferred_thread_id = UUID5(...)` Thread Determinism
|
||||
@ -139,50 +139,101 @@ graph LR
|
||||
|
||||
Whitespace-only values at every level are treated as unset, so the chain falls through cleanly. The `_is_self_event` gate uses the same precedence (with the agent's whole `bindings[*].triggers[*].mention_login` aggregated across all bindings, plus an `agent.name` fallback) so the self-loop gate and the mention gate stay coherent.
|
||||
|
||||
## GH Token Lifecycle
|
||||
## GitHub Tool Setup
|
||||
|
||||
GitHub Agents get push/write credentials as **per-call installation tokens**, not as inherited environment. The minted token string is bound into `run_context["github_token"]` on the bus-consumer side and exposed to the agent's sandbox commands as both `GH_TOKEN` and `GITHUB_TOKEN` via per-call `extra_env` on `execute_command`. No `os.environ` mutation, no cross-repo bleed.
|
||||
Webhook delivery starts the agent independently of its GitHub tool settings.
|
||||
`GITHUB_WEBHOOK_SECRET` verifies incoming deliveries. For repository operations,
|
||||
the [official GitHub MCP Server](https://github.com/github/github-mcp-server) can
|
||||
authenticate as a GitHub App installation in `stdio` mode. It obtains and
|
||||
refreshes installation tokens without an interactive login. Git and the GitHub
|
||||
CLI use their own authentication settings.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant Bus as MessageBus
|
||||
participant Mgr as ChannelManager<br/>_handle_chat_on_thread
|
||||
participant Pol as inject_github_credentials()<br/>(github/run_policy.py)
|
||||
participant Auth as mint_installation_token<br/>(github/app_auth.py)
|
||||
participant GH as GitHub API<br/>(POST /app/installations/{id}/access_tokens)
|
||||
participant Run as runs.create
|
||||
participant GW as Gateway runtime
|
||||
participant Bash as bash_tool
|
||||
participant Sandbox as Sandbox process
|
||||
participant Cmd as Sandbox command<br/>(gh / git push)
|
||||
### Configure the GitHub App and webhook
|
||||
|
||||
Bus->>Mgr: msg (channel=github, metadata.github.installation_id)
|
||||
Mgr->>Pol: _apply_channel_policy(msg, run_context)
|
||||
Pol->>Auth: mint_installation_token(installation_id)
|
||||
Auth->>GH: exchange installation_id for token<br/>(JWT signed with PRIVATE_KEY)
|
||||
GH-->>Auth: {token, expires_at}
|
||||
Auth-->>Pol: token string (cached ~55min)
|
||||
Pol->>Mgr: run_context["github_token"] = token
|
||||
Mgr->>Run: client.runs.create(<br/>thread_id, assistant_id,<br/>context={..., github_token})
|
||||
Run->>GW: POST /threads/{id}/runs
|
||||
GW-->>Run: pending
|
||||
Run-->>Mgr: returns once pending
|
||||
Note over Mgr: Manager returns immediately (fire_and_forget)
|
||||
1. [Register a GitHub App](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/registering-a-github-app)
|
||||
or reuse an existing App. Install it on the repositories the agent should
|
||||
access. For the read-only tools below, grant read access to **Contents**,
|
||||
**Issues**, and **Pull requests**.
|
||||
2. In the App settings, set the webhook URL to
|
||||
`https://<deerflow-host>/api/webhooks/github` and subscribe to
|
||||
[**Issue comment**](https://docs.github.com/en/webhooks/webhook-events-and-payloads#issue_comment)
|
||||
events to trigger on issue and PR conversation comments. Set the same webhook
|
||||
secret in GitHub and in the Gateway's `GITHUB_WEBHOOK_SECRET` environment
|
||||
variable. Set `channels.github.enabled: true` in the deployment `config.yaml`.
|
||||
|
||||
Note over GW,Bash: Harness side
|
||||
GW->>Bash: bash_tool call<br/>cmd="git push https://x-access-token:$GH_TOKEN@..."
|
||||
Bash->>Sandbox: execute_command(<br/>env={"GH_TOKEN": "...",<br/> "GITHUB_TOKEN": "..."})
|
||||
Note over Sandbox: AioSandbox: bash.exec(env=...) on fresh session<br/>LocalSandbox: subprocess.run(env=...)
|
||||
Sandbox->>Cmd: gh pr comment / git push / etc.
|
||||
Cmd->>GH: authenticated GitHub API call
|
||||
### Connect the MCP server
|
||||
|
||||
Install [GitHub MCP Server v2.2.0](https://github.com/github/github-mcp-server/releases/tag/v2.2.0)
|
||||
on the Gateway. In the Gateway environment, set `GITHUB_APP_ID` to the App ID
|
||||
from its settings and `GITHUB_APP_INSTALLATION_ID` to the installation ID
|
||||
(`installation.id` in a GitHub App webhook payload). Generate a private key in
|
||||
the App settings and make its PEM file readable by the MCP process. For Docker,
|
||||
provide the Linux binary inside the Gateway container and mount the PEM as a
|
||||
read-only secret. Keep the key out of source control and outside agent-accessible
|
||||
mounts.
|
||||
|
||||
Merge the `github-app` entry into `mcpServers` in
|
||||
[`extensions_config.json`](MCP_SERVER.md#setup). Adjust the executable and PEM
|
||||
paths for the Gateway environment.
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"github-app": {
|
||||
"enabled": true,
|
||||
"type": "stdio",
|
||||
"command": "/usr/local/bin/github-mcp-server",
|
||||
"args": [
|
||||
"stdio",
|
||||
"--read-only",
|
||||
"--tools=issue_read,pull_request_read,get_file_contents"
|
||||
],
|
||||
"env": {
|
||||
"GITHUB_APP_ID": "$GITHUB_APP_ID",
|
||||
"GITHUB_APP_INSTALLATION_ID": "$GITHUB_APP_INSTALLATION_ID",
|
||||
"GITHUB_APP_PRIVATE_KEY_PATH": "/run/secrets/github-app.pem"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Why a string and not a closure: `run_context` is JSON-encoded by the `langgraph_sdk` HTTP client before reaching Gateway. A Python callable does not survive that serialization. The harness side (`_github_env_from_runtime`) already accepts either shape, but only `str` round-trips through the SDK transport.
|
||||
This MCP server uses a deployment-wide credential. Use it on a trusted Gateway
|
||||
and scope repository access through the App installation and its permissions.
|
||||
See the [MCP server's GitHub App authentication guide](https://github.com/github/github-mcp-server/blob/v2.2.0/docs/github-app-auth.md)
|
||||
for installation-token errors and GitHub Enterprise configuration.
|
||||
|
||||
**App JWT signing**: the mint builds the App JWT in a worker thread, because it reads `GITHUB_APP_PRIVATE_KEY_PATH` and signs with the key. The key is still read on every mint, but it is parsed again only when its PEM text changes (parsing an RSA-2048 key takes tens of milliseconds and holds the GIL). A rotated key, inline or on disk, is used by the next mint without a restart.
|
||||
### Bind and verify the agent
|
||||
|
||||
**Token TTL caveat**: GitHub installation tokens are valid for ~1 hour. Most agent runs finish well inside that window. Truly long coder runs (multi-hour refactors at the higher `recursion_limit=250` ceiling) may see a 401 on a late `git push` / `gh pr create`. Auto-refresh past the 1h TTL is intentionally deferred — it requires registering a token-provider lookup on the harness side, which crosses the harness/app boundary (`tests/test_harness_boundary.py`). Until refresh ships, long runs should finish GitHub writes before expiry or accept the loss. If minting fails (bad App id, wrong installation_id, missing private key), the agent still runs without push/write credentials — read-only is better than no response.
|
||||
Add or update the `github` block in the custom agent's `config.yaml`. Set
|
||||
`bot_login` to the App slug without `[bot]` and substitute the repository and App
|
||||
slug below.
|
||||
|
||||
```yaml
|
||||
github:
|
||||
bot_login: example-review-app
|
||||
bindings:
|
||||
- repo: your-org/your-repo
|
||||
triggers:
|
||||
issue_comment:
|
||||
actions: [created]
|
||||
require_mention: true
|
||||
```
|
||||
|
||||
Restart the Gateway. In Docker, recreate the Gateway container to apply new
|
||||
environment variables and mounts. In the custom agent's **Plugins and skills**
|
||||
settings, select `github-app`. On a test PR in the bound repository, post a
|
||||
conversation comment such as `@example-review-app summarize this pull request`.
|
||||
Verify that GitHub's Recent Deliveries response lists the agent under
|
||||
`dispatch.fired_agents` and that the DeerFlow run successfully calls
|
||||
`pull_request_read`. This checks both the webhook dispatch and the
|
||||
installation's repository access.
|
||||
|
||||
To let the bot post conversation comments, grant the App **Issues: Read and
|
||||
write** and approve the updated installation permissions if GitHub prompts you.
|
||||
Add `add_issue_comment` to `--tools`, remove `--read-only`, and restart the
|
||||
Gateway. The agent must call this tool to post a comment. Its final response is
|
||||
logged by the GitHub channel. See [GitHub's comment permissions](https://docs.github.com/en/rest/issues/comments#create-an-issue-comment).
|
||||
|
||||
## Thread-create Race Recovery
|
||||
|
||||
@ -278,33 +329,33 @@ graph LR
|
||||
classDef gh fill:#D7D3E8,stroke:#6B6680,color:#29263A
|
||||
|
||||
Run["GitHub agent run"]:::agent
|
||||
GhCLI["gh CLI<br/>(in sandbox)"]:::gh
|
||||
GitHubTool["Configured GitHub tool"]:::gh
|
||||
Issue["GitHub issue / PR"]:::gh
|
||||
Channel["GitHubChannel.send()<br/>(log-only)"]:::send
|
||||
Log["gateway.log<br/>(INFO line)"]:::send
|
||||
|
||||
Run -->|"mid-run intentional writeback"| GhCLI --> Issue
|
||||
Run -->|"mid-run intentional writeback"| GitHubTool --> Issue
|
||||
Run -->|"final assistant message"| Channel --> Log
|
||||
```
|
||||
|
||||
GitHub agents post to GitHub themselves via the `gh` CLI from inside their sandbox (`gh issue comment`, `gh pr comment`, `gh pr create`, etc.). The channel's `send()` is **log-only** by design — the agent's final assistant message is logged at INFO for visibility but never auto-posted.
|
||||
A configured GitHub tool can post comments or open pull requests during a run. The channel logs the final assistant message at INFO.
|
||||
|
||||
Why:
|
||||
|
||||
- **Multiple agents can bind the same event.** coder + reviewer on a mention would each auto-post a reply, producing two replies per mention even when only one had useful work. Letting the LLM call `gh` mid-run means silence is just "the LLM did not call `gh`".
|
||||
- **Multiple agents can bind the same event.** coder + reviewer on a mention would each auto-post a reply, producing two replies per mention even when only one had useful work. Each agent chooses whether to post during its run.
|
||||
- **The agent often wants to post intermediate updates** (an issue comment linking the PR, a sub-issue comment, a PR description edit). The auto-post-the-final-message contract didn't model that and forced the final message to play double duty.
|
||||
- **The dispatcher's per-agent `_is_self_event` gate** already prevents comments the LLM posts via `gh` from looping the webhook back into a new run for the same agent.
|
||||
- **The dispatcher's per-agent `_is_self_event` gate** already prevents comments the agent posts from looping the webhook back into a new run for the same agent.
|
||||
|
||||
This is also why the GitHub channel registers `ChannelRunPolicy.fire_and_forget=True`: the manager calls `runs.create()` and returns once the run is `pending`, no outbound ferrying, no SDK 300s `httpx.ReadTimeout` on a legitimate long coder run.
|
||||
|
||||
## Cross-references
|
||||
|
||||
- [AGENTS.md](../AGENTS.md) → "GitHub event-driven agents" — the index view in `backend/AGENTS.md` (binding shape, per-event triggers, mention precedence, token env summary, follow-up buffering summary)
|
||||
- [Channel guidance](../app/channels/AGENTS.md#github-channel)
|
||||
- [IM_CHANNEL_CONNECTIONS.md](IM_CHANNEL_CONNECTIONS.md) — interactive IM channels (Telegram/Slack/etc.) for the full `_handle_chat` and owner-scoped file storage flow
|
||||
- `app/gateway/github/dispatcher.py` — `fanout_event`, `_is_self_event`, mention precedence chain
|
||||
- `app/channels/manager.py` — `_buffer_followup`, `_drain_followups_for_thread`, `_watch_run_and_drain_followups` (follow-up buffering while busy, issue #4121)
|
||||
- `app/gateway/github/identity.py` — `resolve_thread_id` (UUID5), `extract_target`
|
||||
- `app/gateway/github/triggers.py` — `event_should_fire`, `DEFAULT_TRIGGERS`
|
||||
- `app/gateway/github/run_policy.py` — `inject_github_credentials`, `register_policy`
|
||||
- `app/gateway/github/run_policy.py` — `register_policy`
|
||||
- `app/gateway/routers/github_webhooks.py` — HMAC verify, route mount predicate
|
||||
- `app/channels/github.py` — `GitHubChannel` (log-only outbound)
|
||||
|
||||
@ -98,14 +98,7 @@ class GitHubBinding(BaseModel):
|
||||
class GitHubAgentConfig(BaseModel):
|
||||
"""Top-level ``github:`` block on a custom agent's ``config.yaml``."""
|
||||
|
||||
# GitHub App installation id used to mint per-repo access tokens. The
|
||||
# ``ChannelManager`` mints a 1h installation token from this and injects it
|
||||
# into ``run_context["github_token"]``, which the ``bash`` tool exposes to
|
||||
# the agent's sandbox as ``GH_TOKEN`` / ``GITHUB_TOKEN``. The agent then
|
||||
# uses ``gh`` to read repo state, push branches, and post comments itself.
|
||||
# None means no token is minted: the agent still runs but cannot push or
|
||||
# post (effectively read-only via unauthenticated ``gh`` for public repos,
|
||||
# or fully blind for private ones).
|
||||
# Optional installation identifier retained for existing bindings and metadata.
|
||||
installation_id: int | None = None
|
||||
# GitHub App login this agent posts as (e.g. ``llm-gateway-ai`` for the
|
||||
# ``llm-gateway-ai[bot]`` App identity, without the ``[bot]`` suffix).
|
||||
|
||||
@ -56,7 +56,8 @@ Windows. The portable string assertions do not replace it.
|
||||
|
||||
- **Environment.** `build_sandbox_env()` removes inherited credential variables.
|
||||
Values from `sandbox.environment` and per-request secrets are added after the
|
||||
scrub. Route every new subprocess launch through it.
|
||||
scrub. Route every new subprocess launch through it. Channel-managed
|
||||
credentials belong to the integration that uses them.
|
||||
- **Network approval** needs a human. Runs with no interactive responder
|
||||
(scheduled, webhook, autonomous, subagent) deny automatically. Never show an
|
||||
approval card that nobody can answer.
|
||||
|
||||
@ -2864,51 +2864,6 @@ def _user_identity_prefix(runtime: Runtime) -> str:
|
||||
return f"unset {USER_ID_ENV}; "
|
||||
|
||||
|
||||
def _github_env_from_runtime(runtime: Runtime) -> dict[str, str] | None:
|
||||
"""Build a per-call env overlay carrying a GitHub App installation token.
|
||||
|
||||
The GitHub channel mints a short-lived installation token in the
|
||||
``ChannelManager`` (app layer) and threads it through ``run_context``
|
||||
so it lands in ``runtime.context["github_token"]``. We expose it to
|
||||
the agent's bash as both ``GH_TOKEN`` (what the ``gh`` CLI reads) and
|
||||
``GITHUB_TOKEN`` (the conventional name). Returning ``None`` when no
|
||||
token is present keeps non-GitHub runs identical to before.
|
||||
|
||||
The value at ``runtime.context["github_token"]`` may be either:
|
||||
|
||||
* a ``str`` — the captured token, the simple shape used by tests and
|
||||
by older code paths that don't need refresh; or
|
||||
* a zero-arg sync callable returning ``str`` — a provider that re-mints
|
||||
transparently when the underlying installation token's 1h TTL is
|
||||
nearing expiry. The provider's cache logic lives app-side (see
|
||||
``app.gateway.github.app_auth.mint_installation_token`` for the
|
||||
cache + leeway semantics); the harness just calls it.
|
||||
|
||||
The callable path is what lets long autonomous runs survive past the
|
||||
60-minute installation-token life: every bash invocation re-asks the
|
||||
provider, which returns the cached token until ~55 min, then mints a
|
||||
fresh one. Without this, a coder agent doing a multi-hour refactor
|
||||
would do most of the work and then 401 on the final ``git push``.
|
||||
|
||||
The token still crosses the harness/app boundary as opaque data — the
|
||||
harness never imports the app-layer minting code, preserving the
|
||||
dependency firewall enforced by ``tests/test_harness_boundary.py``.
|
||||
"""
|
||||
context = runtime.context if runtime.context is not None else None
|
||||
value = context.get("github_token") if context else None
|
||||
if callable(value):
|
||||
try:
|
||||
token = value()
|
||||
except Exception:
|
||||
logger.warning("github_token provider raised; skipping env overlay", exc_info=True)
|
||||
return None
|
||||
else:
|
||||
token = value
|
||||
if not isinstance(token, str) or not token:
|
||||
return None
|
||||
return {"GH_TOKEN": token, "GITHUB_TOKEN": token}
|
||||
|
||||
|
||||
_LARK_CLI_COMMAND_RE = re.compile(r"(?<![A-Za-z0-9_.-])lark-cli(?![A-Za-z0-9_.-])")
|
||||
|
||||
|
||||
@ -2962,17 +2917,11 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | To
|
||||
redaction_env = None
|
||||
try:
|
||||
sandbox = ensure_sandbox_initialized(runtime)
|
||||
# Request-scoped secrets resolved for the active skill (#3861), plus a
|
||||
# short-lived GitHub App installation token threaded through by the
|
||||
# GitHub channel. Both are injected as per-call env into the subprocess,
|
||||
# never placed in the command string.
|
||||
# Only the active skill's explicitly resolved secrets belong here.
|
||||
injected_env = read_active_secrets(getattr(runtime, "context", None)) or None
|
||||
identity_prefix = _channel_identity_prefix(runtime)
|
||||
user_prefix = _user_identity_prefix(runtime)
|
||||
github_env = _github_env_from_runtime(runtime)
|
||||
lark_cli_env = _lark_cli_env_from_runtime(runtime, command, sandbox_paths=not is_local_sandbox(runtime), sandbox=sandbox)
|
||||
if github_env:
|
||||
injected_env = {**(injected_env or {}), **github_env}
|
||||
if lark_cli_env:
|
||||
injected_env = {**(injected_env or {}), **lark_cli_env}
|
||||
redaction_env = injected_env
|
||||
|
||||
@ -3130,16 +3130,6 @@ def test_merge_run_context_overrides_noop_for_empty_context():
|
||||
|
||||
|
||||
def test_merge_run_context_overrides_forwards_context_only_keys():
|
||||
"""``github_token`` and ``disable_clarification`` must reach ``config['context']``
|
||||
(runtime context → ``runtime.context``) so the bash tool and ClarificationMiddleware
|
||||
can read them. They must NOT be written to ``config['configurable']`` — that dict is
|
||||
persisted in checkpoints, and ``github_token`` is a (short-lived) secret.
|
||||
|
||||
Regression for the GitHub channel: without this, the installation token minted by
|
||||
``ChannelManager._apply_channel_policy`` was silently dropped here, so ``gh``
|
||||
fell back to the host's stored keyring creds and authored issues/PRs as the host
|
||||
user instead of the App bot.
|
||||
"""
|
||||
from app.gateway.services import build_run_config, merge_run_context_overrides
|
||||
|
||||
config = build_run_config("thread-1", None, None)
|
||||
@ -3153,8 +3143,7 @@ def test_merge_run_context_overrides_forwards_context_only_keys():
|
||||
internal=True,
|
||||
)
|
||||
|
||||
# Forwarded into runtime context — what tools/middlewares read.
|
||||
assert config["context"]["github_token"] == "ghs_installation_token"
|
||||
assert "github_token" not in config["context"]
|
||||
assert config["context"]["disable_clarification"] is True
|
||||
assert config["context"]["agent_name"] == "coding-llm-gateway"
|
||||
|
||||
@ -3164,9 +3153,7 @@ def test_merge_run_context_overrides_forwards_context_only_keys():
|
||||
|
||||
|
||||
def test_context_only_keys_are_internal_only():
|
||||
"""``github_token`` / ``disable_clarification`` are produced by the channel run
|
||||
policies, which reach the Gateway over the internally-authenticated channel. A
|
||||
non-internal caller must not be able to supply either through ``body.context``.
|
||||
"""Only internal callers can supply ``disable_clarification`` through ``body.context``.
|
||||
|
||||
``disable_clarification`` is not a milder cousin of ``non_interactive``:
|
||||
``ClarificationMiddleware`` answers every clarification — ``risk_confirmation``
|
||||
@ -3195,16 +3182,13 @@ def test_context_only_keys_are_internal_only():
|
||||
|
||||
|
||||
def test_merge_run_context_overrides_context_only_keys_do_not_override_existing():
|
||||
"""A token already in ``config['context']`` must not be clobbered by one supplied
|
||||
in ``body.context`` (defense in depth — ``setdefault`` keeps the contract explicit
|
||||
even now that only internal callers reach this branch)."""
|
||||
from app.gateway.services import build_run_config, merge_run_context_overrides
|
||||
|
||||
config = build_run_config("thread-1", None, None)
|
||||
config["context"] = {"github_token": "pre-existing"}
|
||||
merge_run_context_overrides(config, {"github_token": "later-supplied"}, internal=True)
|
||||
config["context"] = {"disable_clarification": False}
|
||||
merge_run_context_overrides(config, {"disable_clarification": True}, internal=True)
|
||||
|
||||
assert config["context"]["github_token"] == "pre-existing"
|
||||
assert config["context"]["disable_clarification"] is False
|
||||
|
||||
|
||||
def test_context_does_not_override_existing_configurable():
|
||||
@ -5382,19 +5366,17 @@ def test_start_run_sequence_drops_context_only_keys_for_session_caller():
|
||||
assert "disable_clarification" not in config.get("configurable", {})
|
||||
|
||||
|
||||
def test_start_run_sequence_keeps_context_only_keys_for_internal_caller():
|
||||
"""The channel path (internal auth) must keep carrying the minted token and the
|
||||
non-interactive flag, and neither may land in checkpoint-persisted ``configurable``."""
|
||||
def test_start_run_sequence_keeps_webhook_flags_and_discards_legacy_credentials():
|
||||
from app.gateway.internal_auth import INTERNAL_SYSTEM_ROLE
|
||||
|
||||
request = _make_request_with_auth_source(AUTH_SOURCE_INTERNAL, system_role=INTERNAL_SYSTEM_ROLE)
|
||||
config = _assemble_authz_run_config(
|
||||
{},
|
||||
{"context": {"github_token": "legacy-context"}, "configurable": {"github_token": "legacy-configuration"}},
|
||||
request,
|
||||
body_context={"github_token": "ghs_installation_token", "disable_clarification": True},
|
||||
body_context={"github_token": "legacy-request", "disable_clarification": True},
|
||||
)
|
||||
|
||||
assert config["context"]["github_token"] == "ghs_installation_token"
|
||||
assert "github_token" not in config["context"]
|
||||
assert config["context"]["disable_clarification"] is True
|
||||
assert "github_token" not in config.get("configurable", {})
|
||||
assert "disable_clarification" not in config.get("configurable", {})
|
||||
|
||||
@ -190,7 +190,7 @@ def test_pull_request_review_prompt_instructs_fetching_inline_comments() -> None
|
||||
review-comment gate assumes the agent recovers inline comment content
|
||||
from the parent `pull_request_review` event -- nothing enforced that
|
||||
before this. The prompt must tell the agent how, with the exact
|
||||
`gh api` path GitHub uses for a review's inline comments.
|
||||
API path GitHub uses for a review's inline comments.
|
||||
"""
|
||||
payload = {
|
||||
"action": "submitted",
|
||||
@ -204,7 +204,8 @@ def test_pull_request_review_prompt_instructs_fetching_inline_comments() -> None
|
||||
"repository": {"full_name": "a/b"},
|
||||
}
|
||||
prompt = build_prompt("pull_request_review", payload)
|
||||
assert "gh api repos/a/b/pulls/5/reviews/999001/comments" in prompt
|
||||
assert "configured GitHub tool" in prompt
|
||||
assert "repos/a/b/pulls/5/reviews/999001/comments" in prompt
|
||||
|
||||
|
||||
def test_pull_request_review_prompt_omits_fetch_hint_without_review_id() -> None:
|
||||
@ -219,7 +220,7 @@ def test_pull_request_review_prompt_omits_fetch_hint_without_review_id() -> None
|
||||
"repository": {"full_name": "a/b"},
|
||||
}
|
||||
prompt = build_prompt("pull_request_review", payload)
|
||||
assert "gh api" not in prompt
|
||||
assert "/reviews/" not in prompt
|
||||
|
||||
|
||||
def test_issues_prompt() -> None:
|
||||
|
||||
@ -1,19 +1,4 @@
|
||||
"""Tests for the GitHub App installation-token plumbing.
|
||||
|
||||
Covers the end-to-end path that lets a GitHub-driven agent actually push
|
||||
code and open PRs:
|
||||
|
||||
dispatcher carries ``installation_id`` + a deterministic
|
||||
``preferred_thread_id`` in ``InboundMessage.metadata``
|
||||
-> ChannelManager mints an installation token and injects it into
|
||||
``run_context["github_token"]``
|
||||
-> the value flows through ``context=`` into ``runtime.context``
|
||||
-> the bash tool exposes it as ``GH_TOKEN`` / ``GITHUB_TOKEN`` via a
|
||||
per-call ``env`` overlay on ``Sandbox.execute_command``
|
||||
|
||||
The per-call overlay (rather than mutating ``os.environ``) is what keeps
|
||||
concurrent runs on different repos from clobbering each other's token.
|
||||
"""
|
||||
"""Sandbox environment overlays and GitHub webhook run policy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -31,7 +16,7 @@ from app.channels.manager import ChannelManager
|
||||
from app.channels.message_bus import InboundMessage, InboundMessageType, MessageBus
|
||||
from app.channels.store import JsonChannelStore
|
||||
from deerflow.sandbox.local.local_sandbox import LocalSandbox
|
||||
from deerflow.sandbox.tools import _github_env_from_runtime, bash_tool
|
||||
from deerflow.sandbox.tools import bash_tool
|
||||
|
||||
|
||||
def _new_aio_sandbox_with_session_state():
|
||||
@ -314,69 +299,11 @@ def test_aio_sandbox_rejects_invalid_env_key() -> None:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# bash_tool token read-through
|
||||
# Bash command environment
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_github_env_from_runtime_returns_token_pair() -> None:
|
||||
runtime = SimpleNamespace(context={"github_token": "tok-abc"})
|
||||
env = _github_env_from_runtime(runtime)
|
||||
assert env == {"GH_TOKEN": "tok-abc", "GITHUB_TOKEN": "tok-abc"}
|
||||
|
||||
|
||||
def test_github_env_from_runtime_resolves_provider_callable() -> None:
|
||||
"""A callable in context["github_token"] is invoked per bash call.
|
||||
|
||||
This is the refresh seam: long autonomous github runs that span past
|
||||
the 60-minute installation-token TTL need every bash invocation to
|
||||
re-ask the provider, which transparently re-mints via the app-side
|
||||
cache when the token's leeway tripped.
|
||||
"""
|
||||
calls = {"n": 0}
|
||||
|
||||
def _provider() -> str:
|
||||
calls["n"] += 1
|
||||
return f"tok-call-{calls['n']}"
|
||||
|
||||
runtime = SimpleNamespace(context={"github_token": _provider})
|
||||
|
||||
env_1 = _github_env_from_runtime(runtime)
|
||||
assert env_1 == {"GH_TOKEN": "tok-call-1", "GITHUB_TOKEN": "tok-call-1"}
|
||||
|
||||
env_2 = _github_env_from_runtime(runtime)
|
||||
assert env_2 == {"GH_TOKEN": "tok-call-2", "GITHUB_TOKEN": "tok-call-2"}
|
||||
assert calls["n"] == 2 # called once per bash invocation
|
||||
|
||||
|
||||
def test_github_env_from_runtime_returns_none_when_provider_raises() -> None:
|
||||
"""A misbehaving provider must NOT crash the bash tool — it just falls
|
||||
back to the no-token path so the run can still execute read-only.
|
||||
"""
|
||||
|
||||
def _broken() -> str:
|
||||
raise RuntimeError("mint failed")
|
||||
|
||||
runtime = SimpleNamespace(context={"github_token": _broken})
|
||||
assert _github_env_from_runtime(runtime) is None
|
||||
|
||||
|
||||
def test_github_env_from_runtime_returns_none_when_provider_returns_empty() -> None:
|
||||
runtime = SimpleNamespace(context={"github_token": lambda: ""})
|
||||
assert _github_env_from_runtime(runtime) is None
|
||||
|
||||
|
||||
def test_github_env_from_runtime_none_when_no_token() -> None:
|
||||
runtime = SimpleNamespace(context={"thread_id": "t1"})
|
||||
assert _github_env_from_runtime(runtime) is None
|
||||
|
||||
|
||||
def test_github_env_from_runtime_none_when_empty() -> None:
|
||||
runtime = SimpleNamespace(context={"github_token": ""})
|
||||
assert _github_env_from_runtime(runtime) is None
|
||||
|
||||
|
||||
def test_bash_tool_passes_token_as_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""When runtime.context carries github_token, bash forwards it to the sandbox."""
|
||||
def test_bash_tool_ignores_legacy_run_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
runtime = SimpleNamespace(
|
||||
state={"sandbox": {"sandbox_id": "aio:xyz"}}, # non-local -> simpler branch
|
||||
context={"thread_id": "t1", "github_token": "tok-from-manager"},
|
||||
@ -394,10 +321,10 @@ def test_bash_tool_passes_token_as_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: _Sandbox())
|
||||
monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None)
|
||||
|
||||
result = bash_tool.func(runtime=runtime, description="push", command="git push")
|
||||
result = bash_tool.func(runtime=runtime, description="List files", command="ls")
|
||||
|
||||
assert "done" in result
|
||||
assert captured["env"] == {"GH_TOKEN": "tok-from-manager", "GITHUB_TOKEN": "tok-from-manager"}
|
||||
assert captured["env"] is None
|
||||
|
||||
|
||||
def test_bash_tool_no_env_without_token(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@ -472,12 +399,7 @@ def test_bash_tool_routes_subagent_command_to_its_shell_scope(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ChannelManager._apply_channel_policy — the unified per-channel run-policy
|
||||
# hook. The github channel registers (is_interactive=False,
|
||||
# default_recursion_limit=250, credentials_provider=inject_github_credentials,
|
||||
# requires_bound_identity=False) via CHANNEL_RUN_POLICY; this section
|
||||
# exercises that one hook for github and the no-op path for unregistered
|
||||
# channels (Slack, Telegram, …).
|
||||
# GitHub webhook policy and thread routing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@ -510,83 +432,6 @@ def _new_manager() -> ChannelManager:
|
||||
return ChannelManager(bus=bus, store=store)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_context_after_apply_channel_policy_is_json_serializable(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Regression pin: ``run_context`` survives the langgraph SDK's JSON encoder.
|
||||
|
||||
The channel path calls ``client.runs.wait(thread_id, assistant_id,
|
||||
context=run_context, …)``. The SDK encodes the body with ``orjson``
|
||||
before sending it over HTTP. Anything in ``run_context`` that is not
|
||||
JSON-serializable (notably the previous closure-based token provider)
|
||||
raises ``TypeError: Type is not JSON serializable: function`` and the
|
||||
entire delivery fails. This test pins the contract so we never
|
||||
silently regress to shipping a closure again.
|
||||
"""
|
||||
import json
|
||||
|
||||
manager = _new_manager()
|
||||
mint = AsyncMock(return_value="ghs_installation_token")
|
||||
monkeypatch.setattr("app.gateway.github.app_auth.mint_installation_token", mint)
|
||||
|
||||
run_context: dict = {"thread_id": "t1", "user_id": "u1"}
|
||||
await manager._apply_channel_policy(_github_msg(), run_context)
|
||||
|
||||
# Will raise TypeError if anything in run_context is not JSON-serializable.
|
||||
encoded = json.dumps(run_context)
|
||||
assert '"github_token": "ghs_installation_token"' in encoded
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_channel_policy_degrades_on_mint_failure(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""A failed mint must not crash the run; the agent proceeds read-only.
|
||||
|
||||
``_apply_channel_policy`` catches credential-provider exceptions and
|
||||
logs a warning so a transient GitHub API outage or a misconfigured
|
||||
installation_id degrades to "no token injected" rather than dropping
|
||||
the delivery.
|
||||
"""
|
||||
manager = _new_manager()
|
||||
|
||||
async def boom(_installation_id):
|
||||
raise RuntimeError("GITHUB_APP_ID not set")
|
||||
|
||||
monkeypatch.setattr("app.gateway.github.app_auth.mint_installation_token", boom)
|
||||
|
||||
run_context: dict = {}
|
||||
with caplog.at_level("WARNING", logger="app.channels.manager"):
|
||||
await manager._apply_channel_policy(_github_msg(), run_context)
|
||||
|
||||
# Must not crash, must not set a token, must warn.
|
||||
assert "github_token" not in run_context
|
||||
assert any("credentials_provider raised" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_channel_policy_skips_token_without_installation_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A binding with no ``installation_id`` runs without a minted token —
|
||||
no mint call, no ``github_token`` in run_context. The non-interactive
|
||||
flag still gets set because that is decided by the channel-policy
|
||||
entry, not by the credentials provider.
|
||||
"""
|
||||
manager = _new_manager()
|
||||
mint = AsyncMock(return_value="should-not-be-called")
|
||||
monkeypatch.setattr("app.gateway.github.app_auth.mint_installation_token", mint)
|
||||
|
||||
run_context: dict = {}
|
||||
await manager._apply_channel_policy(_github_msg(installation_id=None), run_context)
|
||||
|
||||
mint.assert_not_awaited()
|
||||
assert "github_token" not in run_context
|
||||
# disable_clarification is set unconditionally for github (it is on
|
||||
# the policy entry, not the credentials provider).
|
||||
assert run_context["disable_clarification"] is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ChannelRunPolicy registration + _apply_channel_policy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_github_policy_is_registered_on_import() -> None:
|
||||
"""Importing the gateway.github subpackage registers the run policy.
|
||||
|
||||
@ -604,18 +449,11 @@ def test_github_policy_is_registered_on_import() -> None:
|
||||
assert policy is not None
|
||||
assert policy.is_interactive is False
|
||||
assert policy.default_recursion_limit == 250
|
||||
assert policy.credentials_provider is not None
|
||||
assert policy.credentials_provider is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_channel_policy_installs_token_for_github(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The unified policy hook installs the github credentials and the
|
||||
non-interactive flag — both in one call.
|
||||
|
||||
The token in ``run_context`` is the minted **string**, not a closure,
|
||||
so the value survives the langgraph SDK's JSON encoder on its way to
|
||||
``client.runs.wait(context=…)``.
|
||||
"""
|
||||
async def test_github_channel_applies_webhook_flags_without_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
manager = _new_manager()
|
||||
mint = AsyncMock(return_value="ghs_unified")
|
||||
monkeypatch.setattr("app.gateway.github.app_auth.mint_installation_token", mint)
|
||||
@ -623,9 +461,9 @@ async def test_apply_channel_policy_installs_token_for_github(monkeypatch: pytes
|
||||
run_context: dict = {}
|
||||
await manager._apply_channel_policy(_github_msg(), run_context)
|
||||
|
||||
mint.assert_awaited_once_with(140594274)
|
||||
assert run_context["github_token"] == "ghs_unified"
|
||||
# Non-interactive flag is set in the same call — one method, one place.
|
||||
mint.assert_not_awaited()
|
||||
assert "github_token" not in run_context
|
||||
assert run_context["interaction_mode"] == "webhook"
|
||||
assert run_context["disable_clarification"] is True
|
||||
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user