Compare commits

..

2 Commits

Author SHA1 Message Date
Willem Jiang
573968a78d release: v2.2.0-rc0 2026-10-29 20:53:45 +08:00
Willem Jiang
c133f5e0da chore(release): keep deerflow-harness in the version-source lockstep
bump_version.sh now also rewrites backend/packages/harness/pyproject.toml
(deerflow-harness is a workspace member, so `uv lock` moves its
backend/uv.lock entry too), and verify_versions.sh gates on it in both
tag and mutual-equality modes. RELEASING.md and AGENTS.md describe the
five version sources.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-29 14:48:16 +08:00
1954 changed files with 74339 additions and 237875 deletions

View File

@ -97,14 +97,14 @@ smoke-test/
2. **Check frontend service** - Visit `http://localhost:2026` and verify that the page loads 2. **Check frontend service** - Visit `http://localhost:2026` and verify that the page loads
3. **Check API Gateway** - Verify the `http://localhost:2026/health` endpoint 3. **Check API Gateway** - Verify the `http://localhost:2026/health` endpoint
4. **Check LangGraph-compatible API** - Verify the `/api/langgraph/*` route exposed by Gateway 4. **Check LangGraph-compatible API** - Verify the `/api/langgraph/*` route exposed by Gateway
5. **Frontend route smoke check** - Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh` to verify key routes under `/workspace`. When authentication is enabled, first finish setup and supply credentials for an existing test account as described below. 5. **Frontend route smoke check** - Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh` to verify key routes under `/workspace`. The script auto-detects whether authentication is enabled and, if so, registers / logs in a smoke-test user so the real pages are verified rather than the login redirect.
**Docker mode health check** (when using Docker): **Docker mode health check** (when using Docker):
1. **Check container status** - Run `docker ps` and confirm that all containers are running 1. **Check container status** - Run `docker ps` and confirm that all containers are running
2. **Check frontend service** - Visit `http://localhost:2026` and verify that the page loads 2. **Check frontend service** - Visit `http://localhost:2026` and verify that the page loads
3. **Check API Gateway** - Verify the `http://localhost:2026/health` endpoint 3. **Check API Gateway** - Verify the `http://localhost:2026/health` endpoint
4. **Check LangGraph-compatible API** - Verify the `/api/langgraph/*` route exposed by Gateway 4. **Check LangGraph-compatible API** - Verify the `/api/langgraph/*` route exposed by Gateway
5. **Frontend route smoke check** - Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh` to verify key routes under `/workspace`. When authentication is enabled, first finish setup and supply credentials for an existing test account as described below. 5. **Frontend route smoke check** - Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh` to verify key routes under `/workspace`. The script auto-detects whether authentication is enabled and, if so, registers / logs in a smoke-test user so the real pages are verified rather than the login redirect.
### Optional Functional Verification ### Optional Functional Verification
@ -136,7 +136,7 @@ smoke-test/
The following warnings can appear during smoke testing and do not block a successful result: The following warnings can appear during smoke testing and do not block a successful result:
- Feishu/Lark SSL errors in Gateway logs (certificate verification failure) can be ignored if that channel is not enabled - Feishu/Lark SSL errors in Gateway logs (certificate verification failure) can be ignored if that channel is not enabled
- Warnings in Gateway logs about missing methods in the custom checkpointer, such as `adelete_for_runs` or `aprune`, do not affect the core functionality - Warnings in Gateway logs about missing methods in the custom checkpointer, such as `adelete_for_runs` or `aprune`, do not affect the core functionality
- With authentication enabled, set `SMOKE_TEST_EMAIL` and `SMOKE_TEST_PASSWORD` for an existing test account with a local DeerFlow password and workspace access. The script uses local sign-in and removes its temporary cookie jar on exit. With authentication disabled, it checks the routes anonymously. - The `frontend_check.sh` script automatically handles authentication. When auth is enabled it registers / logs in a smoke-test user (`smoke-test@deerflow.dev` by default) to verify the real `/workspace/*` pages. The registration may produce a log entry from the auth provider, which is expected and harmless.
## Key Tools ## Key Tools

View File

@ -368,8 +368,12 @@ curl http://localhost:2026/health
**Steps**: **Steps**:
1. Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh`. 1. Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh`.
2. The script auto-detects whether authentication (`DEER_FLOW_AUTH_DISABLED`) is enabled. 2. The script auto-detects whether authentication (`DEER_FLOW_AUTH_DISABLED`) is enabled.
3. When auth is on, finish setup before running the check. Set `SMOKE_TEST_EMAIL` and `SMOKE_TEST_PASSWORD` for an existing test account with a local DeerFlow password and workspace access. The script signs in and uses a temporary cookie jar that it removes on exit. 3. When auth is on, the script registers / logs in a smoke-test user (`smoke-test@deerflow.dev` by default) and passes the session cookie so the real `/workspace/*` pages are verified — not the login redirect.
4. When auth is off, the script checks the routes anonymously. 4. When auth is off, the routes are checked anonymously as before.
**Customisation**:
- `SMOKE_TEST_EMAIL` — email for the test account (default: `smoke-test@deerflow.dev`).
- `SMOKE_TEST_PASSWORD` — password for the test account (default: `SmokeTest123!`).
--- ---
@ -430,8 +434,12 @@ curl http://localhost:2026/health
**Steps**: **Steps**:
1. Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh`. 1. Run `bash .agent/skills/smoke-test/scripts/frontend_check.sh`.
2. The script auto-detects whether authentication (`DEER_FLOW_AUTH_DISABLED`) is enabled. 2. The script auto-detects whether authentication (`DEER_FLOW_AUTH_DISABLED`) is enabled.
3. When auth is on, finish setup before running the check. Set `SMOKE_TEST_EMAIL` and `SMOKE_TEST_PASSWORD` for an existing test account with a local DeerFlow password and workspace access. The script signs in and uses a temporary cookie jar that it removes on exit. 3. When auth is on, the script registers / logs in a smoke-test user (`smoke-test@deerflow.dev` by default) and passes the session cookie so the real `/workspace/*` pages are verified — not the login redirect.
4. When auth is off, the script checks the routes anonymously. 4. When auth is off, the routes are checked anonymously as before.
**Customisation**:
- `SMOKE_TEST_EMAIL` — email for the test account (default: `smoke-test@deerflow.dev`).
- `SMOKE_TEST_PASSWORD` — password for the test account (default: `SmokeTest123!`).
--- ---

View File

@ -9,68 +9,97 @@ echo ""
BASE_URL="${BASE_URL:-http://localhost:2026}" BASE_URL="${BASE_URL:-http://localhost:2026}"
DOC_PATH="${DOC_PATH:-/en/docs}" DOC_PATH="${DOC_PATH:-/en/docs}"
# On auth-enabled deployments, verify protected routes with a session for an # When the gateway has authentication enabled (DEER_FLOW_AUTH_DISABLED != 1),
# existing account. Account provisioning belongs to the operator. # protected /workspace/* routes redirect anonymous requests to /login.
COOKIE_JAR="" # We detect auth, register / log in a smoke-test user, and pass the session
trap 'if [ -n "$COOKIE_JAR" ]; then rm -f -- "$COOKIE_JAR"; fi' EXIT # cookie to all curl calls so the real pages are verified, not the login form.
trap 'exit 130' INT SMOKE_TEST_EMAIL="${SMOKE_TEST_EMAIL:-smoke-test@deerflow.dev}"
trap 'exit 143' TERM SMOKE_TEST_PASSWORD="${SMOKE_TEST_PASSWORD:-SmokeTest123!}"
COOKIE_JAR=$(mktemp /tmp/deerflow-smoke-cookies.XXXXXX)
curl_get() { trap 'rm -f "$COOKIE_JAR"' EXIT
if [ -n "$COOKIE_JAR" ]; then CURL_AUTH_OPTS=""
# curl treats a cookie argument containing '=' as literal cookie data.
curl -q --cookie - "$@" < "$COOKIE_JAR"
else
curl -q "$@"
fi
}
authenticate() { authenticate() {
local auth_check # Make sure the service is reachable before detecting auth
if ! auth_check=$(curl -q -s -o /dev/null -w "%{http_code}" "${BASE_URL}/api/models"); then local health
echo "✗ Cannot reach ${BASE_URL} — is the service running?" >&2 health=$(curl -s -o /dev/null -w "%{http_code}" "${BASE_URL}/" 2>/dev/null)
if [ "$health" = "000" ]; then
echo "✗ Cannot reach ${BASE_URL} — is the service running?"
return 1 return 1
fi fi
case "$auth_check" in
200) # A protected endpoint returns 401 when auth is on
local auth_check
auth_check=$(curl -s -o /dev/null -w "%{http_code}" "${BASE_URL}/api/models" 2>/dev/null)
if [ "$auth_check" != "401" ]; then
echo "ℹ Auth is disabled — no login needed" echo "ℹ Auth is disabled — no login needed"
return 0 return 0
;;
401) ;;
*)
echo "✗ Could not check authentication (HTTP $auth_check)" >&2
return 1
;;
esac
if [ -z "${SMOKE_TEST_EMAIL:-}" ] || [ -z "${SMOKE_TEST_PASSWORD:-}" ]; then
echo "✗ Set SMOKE_TEST_EMAIL and SMOKE_TEST_PASSWORD for an existing test account." >&2
return 1
fi
if ! COOKIE_JAR=$(mktemp "${TMPDIR:-/tmp}/deerflow-smoke-cookies.XXXXXX"); then
echo "✗ Could not create a temporary cookie jar" >&2
return 1
fi fi
echo "🔐 Auth is enabled — signing in to the existing test account..." echo "🔐 Auth is enabled — setting up smoke test session..."
# Check whether the system needs first-boot initialization
local needs_setup
needs_setup=$(curl -s "${BASE_URL}/api/v1/auth/setup-status" \
| grep -o '"needs_setup":[^,}]*' | grep -o 'true\|false')
if [ "$needs_setup" = "true" ]; then
echo " Initializing system with smoke test admin..."
local init_code
init_code=$(curl -s -o /dev/null -w "%{http_code}" \
-X POST "${BASE_URL}/api/v1/auth/initialize" \
-H "Content-Type: application/json" \
-d "{\"email\":\"${SMOKE_TEST_EMAIL}\",\"password\":\"${SMOKE_TEST_PASSWORD}\"}" \
-c "$COOKIE_JAR" 2>/dev/null)
if [ "$init_code" != "201" ]; then
echo "✗ Initialize failed (HTTP $init_code)"
return 1
fi
echo "✓ Admin initialized & logged in"
elif [ -z "$needs_setup" ]; then
echo "⚠ Could not determine setup status — skipping initialize, trying register/login"
else
# Register first — on success (201) it also auto-logs-in via the cookie.
# This avoids a wasted login attempt that counts toward rate-limiting.
local auth_code
auth_code=$(curl -s -o /dev/null -w "%{http_code}" \
-X POST "${BASE_URL}/api/v1/auth/register" \
-H "Content-Type: application/json" \
-d "{\"email\":\"${SMOKE_TEST_EMAIL}\",\"password\":\"${SMOKE_TEST_PASSWORD}\"}" \
-c "$COOKIE_JAR" 2>/dev/null)
if [ "$auth_code" = "201" ]; then
echo "✓ Registered as ${SMOKE_TEST_EMAIL}"
else
# User already exists — clear stale cookies from register attempt, then log in
: > "$COOKIE_JAR"
local login_code local login_code
if ! login_code=$(printf '%s' "$SMOKE_TEST_PASSWORD" | curl -q -s -o /dev/null -w "%{http_code}" \ login_code=$(curl -s -o /dev/null -w "%{http_code}" \
"${BASE_URL}/api/v1/auth/login/local" \ -X POST "${BASE_URL}/api/v1/auth/login/local" \
--data-urlencode "username=${SMOKE_TEST_EMAIL}" \ --data-urlencode "username=${SMOKE_TEST_EMAIL}" \
--data-urlencode 'password@-' \ --data-urlencode "password=${SMOKE_TEST_PASSWORD}" \
--data-urlencode 'remember_me=false' \ -c "$COOKIE_JAR" 2>/dev/null)
-c "$COOKIE_JAR") || [ "$login_code" != "200" ]; then if [ "$login_code" != "200" ]; then
echo "✗ Login failed (HTTP ${login_code:-unavailable}). Check the existing test account and finish setup first." >&2 echo "✗ Login failed (HTTP $login_code)"
return 1 return 1
fi fi
echo "✓ Logged in as ${SMOKE_TEST_EMAIL}"
fi
fi
# Verify the session cookie works across all branches
local me_code local me_code
if ! me_code=$(curl_get -s -o /dev/null -w "%{http_code}" "${BASE_URL}/api/v1/auth/me") || [ "$me_code" != "200" ]; then me_code=$(curl -s -o /dev/null -w "%{http_code}" \
echo "✗ Auth failed — session cookie not accepted (HTTP ${me_code:-unavailable})" >&2 -b "$COOKIE_JAR" "${BASE_URL}/api/v1/auth/me" 2>/dev/null)
return 1
if [ "$me_code" = "200" ]; then
echo "✓ Session verified for ${SMOKE_TEST_EMAIL}"
CURL_AUTH_OPTS="-b $COOKIE_JAR"
return 0
fi fi
echo "✓ Session verified" echo "✗ Auth failed — session cookie not accepted (HTTP $me_code)"
echo " Set SMOKE_TEST_EMAIL / SMOKE_TEST_PASSWORD or check the existing account"
return 1
} }
all_passed=true all_passed=true
@ -81,7 +110,7 @@ check_status() {
local expected_re="$3" local expected_re="$3"
local status local status
status="$(curl_get -s -o /dev/null -w "%{http_code}" -L "$url")" status="$(curl -s -o /dev/null -w "%{http_code}" -L ${CURL_AUTH_OPTS} "$url")"
if echo "$status" | grep -Eq "$expected_re"; then if echo "$status" | grep -Eq "$expected_re"; then
echo "✓ $name ($url) -> $status" echo "✓ $name ($url) -> $status"
else else
@ -96,7 +125,7 @@ check_final_url() {
local expected_path_re="$3" local expected_path_re="$3"
local effective local effective
effective="$(curl_get -s -o /dev/null -w "%{url_effective}" -L "$url")" effective="$(curl -s -o /dev/null -w "%{url_effective}" -L ${CURL_AUTH_OPTS} "$url")"
if echo "$effective" | grep -Eq "$expected_path_re"; then if echo "$effective" | grep -Eq "$expected_path_re"; then
echo "✓ $name redirect target -> $effective" echo "✓ $name redirect target -> $effective"
else else

View File

@ -62,9 +62,6 @@ docker/
skills/ skills/
frontend/.next frontend/.next
frontend/node_modules frontend/node_modules
# Frontend unit tests can import fixtures outside frontend/ (for example, examples/),
# so exclude them from the frontend-only Docker build context.
frontend/tests
backend/.venv backend/.venv
backend/htmlcov backend/htmlcov
backend/.coverage backend/.coverage
@ -76,23 +73,6 @@ backend/.coverage
# root that the build client cannot read. # root that the build client cannot read.
**/.deer-flow/ **/.deer-flow/
backend/sandbox/ backend/sandbox/
# Local configuration holds model API keys, MCP credentials, frontend secrets and
# local HTTPS keys (frontend/*.pem, the frontend .gitignore's mkcert pair).
# Compose and Helm supply it at runtime. The config resolvers still read the legacy
# backend/ copies, and `COPY backend ./backend` / `COPY frontend ./frontend` would
# otherwise bake them into every image layer built from this checkout.
config.yaml
config.yaml.bak
extensions_config.json
mcp_config.json
backend/config.yaml
backend/config.yaml.bak
backend/extensions_config.json
backend/mcp_config.json
**/.env*.local
frontend/*.pem
*.md *.md
!README.md !README.md
!frontend/README.md !frontend/README.md
@ -104,17 +84,3 @@ frontend/*.pem
!backend/extensions/ !backend/extensions/
!backend/extensions/sources/ !backend/extensions/sources/
!backend/extensions/sources/** !backend/extensions/sources/**
# The re-inclusion above wins over every earlier rule, so the files the extension
# manager refuses to snapshot (deerflow/extensions/manager.py) are excluded again
# here. A snapshot the manager wrote never contains them; one edited by hand
# must not carry credentials into the image either.
backend/extensions/sources/**/.env
backend/extensions/sources/**/.env.*
backend/extensions/sources/**/.npmrc
backend/extensions/sources/**/.pypirc
backend/extensions/sources/**/credentials.json
backend/extensions/sources/**/*.key
backend/extensions/sources/**/*.pem
backend/extensions/sources/**/*.p12
backend/extensions/sources/**/*.pfx

View File

@ -1,40 +1,37 @@
# Serper API Key (Google Search) - https://serper.dev # Serper API Key (Google Search) - https://serper.dev
# SERPER_API_KEY=your-serper-api-key SERPER_API_KEY=your-serper-api-key
# Optional operator-controlled Serper-compatible API base URL, without /search or /images. # Optional operator-controlled Serper-compatible API base URL, without /search or /images.
# The configured API key is sent in X-API-KEY to this host; use a trusted provider. # The configured API key is sent in X-API-KEY to this host; use a trusted provider.
SERPER_BASE_URL=https://google.serper.dev SERPER_BASE_URL=https://google.serper.dev
# Exa API Key - https://exa.ai # Exa API Key - https://exa.ai
# EXA_API_KEY=your-exa-api-key EXA_API_KEY=your-exa-api-key
# Optional operator-controlled Exa-compatible API base URL for the Exa web_search and web_fetch tools. # Optional operator-controlled Exa-compatible API base URL for the Exa web_search and web_fetch tools.
# The configured API key is sent in x-api-key to this host; use a trusted provider. # The configured API key is sent in x-api-key to this host; use a trusted provider.
EXA_BASE_URL=https://api.exa.ai EXA_BASE_URL=https://api.exa.ai
# Serply API Key (Google Search, News and Scholar) - https://serply.io # Serply API Key (Google Search, News and Scholar) - https://serply.io
# SERPLY_API_KEY=your-serply-api-key SERPLY_API_KEY=your-serply-api-key
# TAVILY API Key # TAVILY API Key
# TAVILY_API_KEY=your-tavily-api-key TAVILY_API_KEY=your-tavily-api-key
# Optional Webz.io News Search key (select Webz in make setup) # Optional Webz.io News Search key (select Webz in make setup)
# WEBZ_API_KEY=your-webz-api-key # WEBZ_API_KEY=your-webz-api-key
# Jina API Key (optional; the Jina Reader web_fetch works without one at a lower rate limit) # Jina API Key
# JINA_API_KEY=your-jina-api-key JINA_API_KEY=your-jina-api-key
# InfoQuest API Key # InfoQuest API Key
# INFOQUEST_API_KEY=your-infoquest-api-key INFOQUEST_API_KEY=your-infoquest-api-key
# Sofya API Key (web search and fetch) - https://sofya.co # Sofya API Key (web search and fetch) - https://sofya.co
# SOFYA_API_KEY=your-sofya-api-key SOFYA_API_KEY=your-sofya-api-key
# SpecStream API Key (web search and fetch) - https://specstream.ai
# SPECSTREAM_API_KEY=your-specstream-api-key
# Unbrowse API Key (web fetch) - https://unbrowse.ai/app # Unbrowse API Key (web fetch) - https://unbrowse.ai/app
# UNBROWSE_API_KEY=your-unbrowse-api-key UNBROWSE_API_KEY=your-unbrowse-api-key
# Browser CORS allowlist for split-origin or port-forwarded deployments (comma-separated exact origins). # Browser CORS allowlist for split-origin or port-forwarded deployments (comma-separated exact origins).
# Leave unset when using the unified nginx endpoint, e.g. http://localhost:2026. # Leave unset when using the unified nginx endpoint, e.g. http://localhost:2026.
@ -68,9 +65,6 @@ EXA_BASE_URL=https://api.exa.ai
# Optional: # Optional:
# FIRECRAWL_API_KEY=your-firecrawl-api-key # FIRECRAWL_API_KEY=your-firecrawl-api-key
# BytePlus Agent Plan (Personal & Enterprise): one key for LLM + Seedream images/slides + Seedance 2.5 video
# Subscribe at https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow
# BYTEPLUS_AGENTPLAN_API_KEY=your-byteplus-agentplan-api-key
# VOLCENGINE_API_KEY=your-volcengine-api-key # VOLCENGINE_API_KEY=your-volcengine-api-key
# OPENAI_API_KEY=your-openai-api-key # OPENAI_API_KEY=your-openai-api-key
# OPENVIKING_API_KEY=your-openviking-user-api-key # OPENVIKING_API_KEY=your-openviking-user-api-key
@ -78,12 +72,7 @@ EXA_BASE_URL=https://api.exa.ai
# DEEPSEEK_API_KEY=your-deepseek-api-key # DEEPSEEK_API_KEY=your-deepseek-api-key
# NOVITA_API_KEY=your-novita-api-key # OpenAI-compatible, see https://novita.ai # NOVITA_API_KEY=your-novita-api-key # OpenAI-compatible, see https://novita.ai
# MINIMAX_API_KEY=your-minimax-api-key # OpenAI-compatible, see https://platform.minimax.io # MINIMAX_API_KEY=your-minimax-api-key # OpenAI-compatible, see https://platform.minimax.io
# MiniMax API host (choose by region):
# China: https://api.minimaxi.com (default)
# International: https://api.minimax.io
# MINIMAX_API_HOST=https://api.minimax.io
# OPPER_API_KEY=your-opper-api-key # OpenAI-compatible, see https://opper.ai # OPPER_API_KEY=your-opper-api-key # OpenAI-compatible, see https://opper.ai
# NVIDIA_API_KEY=your-nvidia-api-key # OpenAI-compatible, see https://integrate.api.nvidia.com
# OpenAI-compatible Images API (used by the image-generation skill) # OpenAI-compatible Images API (used by the image-generation skill)
# IMAGE_GENERATION_PROVIDER=openai # openai-compatible is also accepted # IMAGE_GENERATION_PROVIDER=openai # openai-compatible is also accepted
# IMAGE_GENERATION_API_KEY=your-image-generation-api-key # IMAGE_GENERATION_API_KEY=your-image-generation-api-key
@ -96,18 +85,6 @@ EXA_BASE_URL=https://api.exa.ai
# E2B cloud sandbox API key — required only when using E2BSandboxProvider. # E2B cloud sandbox API key — required only when using E2BSandboxProvider.
# Sign up at https://e2b.dev/dashboard # Sign up at https://e2b.dev/dashboard
# E2B_API_KEY=your-e2b-api-key # E2B_API_KEY=your-e2b-api-key
# boxd API key, required only when using BoxdSandboxProvider.
# Create one in the boxd console: https://boxd.sh?ref=deer-flow
# BOXD_API_KEY=your-boxd-api-key
# BytePlus veFaaS cloud sandbox credentials — required only when using VeFaaSSandboxProvider.
# Learn more: https://www.byteplus.com/en/product/vefaas?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow
# BYTEPLUS_ACCESS_KEY_ID=your-byteplus-access-key-id
# BYTEPLUS_SECRET_ACCESS_KEY=your-byteplus-secret-access-key
# BYTEPLUS_VEFAAS_SANDBOX_APP_ID=your-vefaas-sandbox-app-id
# BYTEPLUS_VEFAAS_SANDBOX_BASE_URL=https://sandbox.example.com
# FEISHU_APP_ID=your-feishu-app-id # FEISHU_APP_ID=your-feishu-app-id
# FEISHU_APP_SECRET=your-feishu-app-secret # FEISHU_APP_SECRET=your-feishu-app-secret

View File

@ -46,23 +46,13 @@ Fixes #
<!-- Skip (delete) this section if this PR is not a bug fix. <!-- Skip (delete) this section if this PR is not a bug fix.
Fold regression cases into the owning module's existing suite instead of Bugs should be encoded as a failing test that goes red before the fix.
creating a new test file per fix.
Confirm: Confirm:
- Existing suite + test case that reproduces the bug: - Test path that reproduces the bug:
- Did it go red on `main` and green on this branch? (yes / no) - Did it go red on `main` and green on this branch? (yes / no)
- If a red test wasn't cheap to write, explain why and what you did instead. --> - If a red test wasn't cheap to write, explain why and what you did instead. -->
## Test footprint
<!-- Keep CI shards within budget: add cases to the module's behavioral suite
and delete or update superseded tests in the same PR. -->
- **Net test line delta** (`+<added> / -<removed>` across test files):
- **Merged or pruned old tests?** (`yes` — list consolidated/deleted test paths, or `no` — explain why net growth is needed):
## Validation ## Validation
<!-- What you actually ran. Run at least the checks for the area you changed: <!-- What you actually ran. Run at least the checks for the area you changed:

View File

@ -1,86 +0,0 @@
name: Backend Benchmark Tests
# Offline benchmark script suites (`backend/tests/test_bench_*.py`) carry the
# `benchmark` marker. Core backend shards exclude them so benchmark harness
# tests do not inflate unrelated PRs; this workflow runs them whenever benchmark
# scripts, benchmark tests, or shared test infrastructure change.
#
# `test_benchmark_ci.py` keeps the marker registration, Makefile targets, and
# trigger paths in sync.
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
paths:
- 'backend/scripts/benchmark/**'
- 'backend/tests/conftest.py'
- 'backend/tests/support/**'
- 'backend/tests/test_bench_*.py'
- 'backend/tests/test_benchmark_ci.py'
- 'backend/pyproject.toml'
- 'backend/uv.lock'
- 'backend/Makefile'
- '.github/workflows/backend-benchmark-tests.yml'
push:
branches: [main, "*-dev"]
paths:
- 'backend/scripts/benchmark/**'
- 'backend/tests/conftest.py'
- 'backend/tests/support/**'
- 'backend/tests/test_bench_*.py'
- 'backend/tests/test_benchmark_ci.py'
- 'backend/pyproject.toml'
- 'backend/uv.lock'
- 'backend/Makefile'
- '.github/workflows/backend-benchmark-tests.yml'
permissions:
contents: read
concurrency:
group: backend-benchmark-tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
backend-benchmark-tests:
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
runs-on: ubuntu-latest
timeout-minutes: 10
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: deerflow
POSTGRES_PASSWORD: deerflow
POSTGRES_DB: deerflow_test
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
TEST_POSTGRES_URI: postgresql://deerflow:deerflow@localhost:5432/deerflow_test?sslmode=disable
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- uses: astral-sh/setup-uv@v7
with:
# Must match backend/Dockerfile's UV_IMAGE tag; pinned by backend/tests/test_ci_uv_version_pin.py
version: "0.11.1"
- name: Install backend dependencies
working-directory: backend
run: uv sync --group dev --extra postgres
- name: Run offline benchmark script tests
working-directory: backend
run: make test-benchmark

View File

@ -14,32 +14,11 @@ permissions:
contents: read contents: read
jobs: jobs:
changes:
# Path scoping lives in scripts/ci_changed_scopes.py so every workflow reads
# one rule set. It fails open: pushes and CI config changes run every scope.
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
backend: ${{ steps.scopes.outputs.backend }}
frontend: ${{ steps.scopes.outputs.frontend }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# The PR merge commit and its first parent, the base branch tip.
fetch-depth: 2
- name: Detect changed scopes
id: scopes
run: python3 scripts/ci_changed_scopes.py --event "${{ github.event_name }}" >> "$GITHUB_OUTPUT"
default-install-collection: default-install-collection:
# The main job installs --extra postgres; this job proves the documented # The main job installs --extra postgres; this job proves the documented
# contributor path (uv sync --group dev, no extras) still collects the # contributor path (uv sync --group dev, no extras) still collects the
# whole suite, so optional-dependency imports must stay lazy. # whole suite, so optional-dependency imports must stay lazy.
needs: changes if: github.event.pull_request.draft == false
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
@ -67,8 +46,7 @@ jobs:
run: uv run pytest --collect-only -q run: uv run pytest --collect-only -q
backend-unit-tests: backend-unit-tests:
needs: changes if: github.event.pull_request.draft == false
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 15 timeout-minutes: 15
strategy: strategy:
@ -79,7 +57,7 @@ jobs:
# its peers. # its peers.
fail-fast: false fail-fast: false
matrix: matrix:
shard: [1, 2, 3, 4, 5, 6] shard: [1, 2, 3, 4]
services: services:
postgres: postgres:
@ -127,7 +105,7 @@ jobs:
working-directory: backend working-directory: backend
run: uv sync --group dev --extra postgres run: uv sync --group dev --extra postgres
- name: Run unit tests of backend (shard ${{ matrix.shard }} of ${{ strategy.job-total }}) - name: Run unit tests of backend (shard ${{ matrix.shard }} of 4)
working-directory: backend working-directory: backend
env: env:
# Expose the job's Postgres service to the cross-pod dedupe integration # Expose the job's Postgres service to the cross-pod dedupe integration
@ -136,6 +114,4 @@ jobs:
# exercised in CI. # exercised in CI.
DEERFLOW_TEST_WORKFLOW_POSTGRES: ${{ env.TEST_POSTGRES_URI }} DEERFLOW_TEST_WORKFLOW_POSTGRES: ${{ env.TEST_POSTGRES_URI }}
DEDUPE_TEST_POSTGRES_URL: ${{ env.TEST_POSTGRES_URI }} DEDUPE_TEST_POSTGRES_URL: ${{ env.TEST_POSTGRES_URI }}
# Exercise the bundled chart with its own PostgreSQL image and disposable volumes. run: make test-shard SPLITS=4 GROUP=${{ matrix.shard }}
DEERFLOW_TEST_HELM_POSTGRES: "1"
run: make test-shard SPLITS=${{ strategy.job-total }} GROUP=${{ matrix.shard }}

View File

@ -1,141 +0,0 @@
name: Bundled Extension Tests
# Bundled extension examples own their behavior suites, which carry the
# `bundled_extension` marker. The core backend shards exclude them so an
# optional example cannot fail an unrelated core PR; this workflow runs them
# whenever an example, the extension contract, the host they load into or the
# bundled tests change.
#
# The filter is deliberately bounded: the marked modules import `deerflow.*`
# (packages) and `app.gateway.*`, so only the Gateway subtree is listed rather
# than all of `backend/app`. Test files are listed one by one instead of
# `backend/tests/**`, and `test_bundled_extension_ci.py` fails when a module
# carries the marker without appearing here, so this list cannot drift.
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
paths:
- 'examples/deerflow-extension-*/**'
- 'backend/packages/**'
- 'backend/app/gateway/**'
- 'backend/tests/conftest.py'
- 'backend/extension_test_fixtures/agent_teams_gateway.py'
- 'backend/tests/support/**'
- 'backend/tests/test_agent_teams_plugin.py'
- 'backend/tests/test_agent_teams_postgres_store.py'
- 'backend/tests/test_agent_teams_postgres_flow.py'
- 'backend/tests/test_agent_teams_storage_config.py'
- 'backend/tests/test_agent_teams_storage_lifecycle.py'
- 'backend/tests/blocking_io/test_agent_teams_storage_offloop.py'
- 'backend/tests/test_bookmark_plugin.py'
- 'backend/tests/test_bundled_extension_ci.py'
- 'backend/tests/test_jev_classify_extension.py'
- 'backend/tests/test_jev_context_extension.py'
- 'backend/tests/test_jev_result_screening_extension.py'
- 'backend/tests/test_jev_screening_pipeline.py'
- 'backend/tests/test_jev_screening_policy.py'
- 'backend/tests/test_knowledge_center_extension.py'
- 'backend/tests/test_knowledge_management_extension.py'
- 'backend/tests/test_knowledge_platform_extension.py'
- 'backend/tests/test_lightrag_relations_extension.py'
- 'backend/tests/test_report_sections_extension.py'
- 'backend/tests/test_retrieval_plugin_artifacts.py'
- 'backend/tests/test_run_postmortem_extension.py'
- 'backend/tests/test_weknora_extension.py'
- 'backend/tests/test_workflow_plugin.py'
- 'backend/pyproject.toml'
- 'backend/uv.lock'
- 'backend/Makefile'
- '.github/workflows/bundled-extension-tests.yml'
push:
branches: [main, "*-dev"]
paths:
- 'examples/deerflow-extension-*/**'
- 'backend/packages/**'
- 'backend/app/gateway/**'
- 'backend/tests/conftest.py'
- 'backend/extension_test_fixtures/agent_teams_gateway.py'
- 'backend/tests/support/**'
- 'backend/tests/test_agent_teams_plugin.py'
- 'backend/tests/test_agent_teams_postgres_store.py'
- 'backend/tests/test_agent_teams_postgres_flow.py'
- 'backend/tests/test_agent_teams_storage_config.py'
- 'backend/tests/test_agent_teams_storage_lifecycle.py'
- 'backend/tests/blocking_io/test_agent_teams_storage_offloop.py'
- 'backend/tests/test_bookmark_plugin.py'
- 'backend/tests/test_bundled_extension_ci.py'
- 'backend/tests/test_jev_classify_extension.py'
- 'backend/tests/test_jev_context_extension.py'
- 'backend/tests/test_jev_result_screening_extension.py'
- 'backend/tests/test_jev_screening_pipeline.py'
- 'backend/tests/test_jev_screening_policy.py'
- 'backend/tests/test_knowledge_center_extension.py'
- 'backend/tests/test_knowledge_management_extension.py'
- 'backend/tests/test_knowledge_platform_extension.py'
- 'backend/tests/test_lightrag_relations_extension.py'
- 'backend/tests/test_report_sections_extension.py'
- 'backend/tests/test_retrieval_plugin_artifacts.py'
- 'backend/tests/test_run_postmortem_extension.py'
- 'backend/tests/test_weknora_extension.py'
- 'backend/tests/test_workflow_plugin.py'
- 'backend/pyproject.toml'
- 'backend/uv.lock'
- 'backend/Makefile'
- '.github/workflows/bundled-extension-tests.yml'
permissions:
contents: read
concurrency:
group: bundled-extension-tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
bundled-extension-tests:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
timeout-minutes: 10
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: deerflow
POSTGRES_PASSWORD: test-only-password
POSTGRES_DB: deerflow_test
ports:
- '127.0.0.1:5432:5432'
options: >-
--health-cmd "pg_isready -U deerflow -d deerflow_test"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- uses: astral-sh/setup-uv@v7
with:
# Must match backend/Dockerfile's UV_IMAGE tag; pinned by backend/tests/test_ci_uv_version_pin.py
version: "0.11.1"
- name: Install backend dependencies
working-directory: backend
run: uv sync --group dev --extra postgres
- name: Run bundled extension behavior tests
working-directory: backend
env:
TEST_POSTGRES_URI: postgresql://deerflow:test-only-password@127.0.0.1:5432/deerflow_test
UV_NO_SYNC: '1'
run: make test-bundled-extensions
- name: Check team storage event-loop isolation
working-directory: backend
env:
UV_NO_SYNC: '1'
run: uv run pytest tests/blocking_io/test_agent_teams_storage_offloop.py -q

View File

@ -14,7 +14,6 @@ on:
- 'backend/pyproject.toml' - 'backend/pyproject.toml'
- 'backend/uv.lock' - 'backend/uv.lock'
- 'examples/deerflow-extension-bookmarks/**' - 'examples/deerflow-extension-bookmarks/**'
- 'examples/deerflow-extension-office-preview/**'
- '.github/workflows/e2e-tests.yml' - '.github/workflows/e2e-tests.yml'
pull_request: pull_request:
types: [opened, synchronize, reopened, ready_for_review] types: [opened, synchronize, reopened, ready_for_review]
@ -29,7 +28,6 @@ on:
- 'backend/pyproject.toml' - 'backend/pyproject.toml'
- 'backend/uv.lock' - 'backend/uv.lock'
- 'examples/deerflow-extension-bookmarks/**' - 'examples/deerflow-extension-bookmarks/**'
- 'examples/deerflow-extension-office-preview/**'
- '.github/workflows/e2e-tests.yml' - '.github/workflows/e2e-tests.yml'
concurrency: concurrency:
@ -43,15 +41,6 @@ jobs:
e2e-tests: e2e-tests:
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }} if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Keep the image version aligned with frontend/pnpm-lock.yaml. Browsers and
# OS libraries are installed together, without per-shard CDN downloads.
container:
image: mcr.microsoft.com/playwright:v1.62.1-noble
options: --ipc=host
env:
# The host tool cache can contain Python built for a newer OpenSSL than
# this image. uv's standalone Python carries compatible runtime libraries.
UV_PYTHON_PREFERENCE: only-managed
timeout-minutes: 25 timeout-minutes: 25
strategy: strategy:
fail-fast: false fail-fast: false
@ -62,20 +51,21 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v6 uses: actions/checkout@v6
# The bookmark browser test starts the real Python action/router fixture.
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: '3.12'
- name: Install uv - name: Install uv
uses: astral-sh/setup-uv@v7 uses: astral-sh/setup-uv@v7
with: with:
# Keep aligned with backend/Dockerfile and other backend workflows. # Keep aligned with backend/Dockerfile and other backend workflows.
version: "0.11.1" version: "0.11.1"
- name: Install container-compatible Python
run: uv python install 3.12
- name: Install backend dependencies (bookmark plugin gateway) - name: Install backend dependencies (bookmark plugin gateway)
working-directory: backend working-directory: backend
run: | run: uv sync --locked
uv sync --locked
uv run --no-sync python -c 'import ssl, sqlite3'
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v4
@ -92,20 +82,9 @@ jobs:
working-directory: frontend working-directory: frontend
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
# Playwright collects the resource suite before selecting a shard. Its - name: Install Playwright Chromium
# synthetic Office fixtures use JSZip from the extension's locked install.
- name: Install Office preview test dependencies
working-directory: examples/deerflow-extension-office-preview
run: npm ci --ignore-scripts --no-audit --no-fund
- name: Verify Playwright Chromium
working-directory: frontend working-directory: frontend
id: chromium run: npx playwright install chromium --with-deps
run: >-
node --input-type=module -e
'import { chromium } from "@playwright/test";
const browser = await chromium.launch();
await browser.close();'
- name: Run E2E tests - name: Run E2E tests
working-directory: frontend working-directory: frontend
@ -121,7 +100,7 @@ jobs:
- name: Run auth recovery E2E tests - name: Run auth recovery E2E tests
# Keep auth coverage unsharded and run it even if the first shard fails. # Keep auth coverage unsharded and run it even if the first shard fails.
if: ${{ !cancelled() && matrix.shard == 1 && steps.chromium.outcome == 'success' }} if: ${{ !cancelled() && matrix.shard == 1 }}
working-directory: frontend working-directory: frontend
run: >- run: >-
pnpm exec playwright test -c playwright.auth.config.ts pnpm exec playwright test -c playwright.auth.config.ts

View File

@ -14,29 +14,8 @@ permissions:
contents: read contents: read
jobs: jobs:
changes:
# Path scoping lives in scripts/ci_changed_scopes.py so every workflow reads
# one rule set. It fails open: pushes and CI config changes run every scope.
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
backend: ${{ steps.scopes.outputs.backend }}
frontend: ${{ steps.scopes.outputs.frontend }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# The PR merge commit and its first parent, the base branch tip.
fetch-depth: 2
- name: Detect changed scopes
id: scopes
run: python3 scripts/ci_changed_scopes.py --event "${{ github.event_name }}" >> "$GITHUB_OUTPUT"
frontend-unit-tests: frontend-unit-tests:
needs: changes if: github.event.pull_request.draft == false
if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 15 timeout-minutes: 15

View File

@ -6,33 +6,10 @@ on:
pull_request: pull_request:
branches: [ '*' ] branches: [ '*' ]
concurrency:
group: lint-check-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: permissions:
contents: read contents: read
jobs: jobs:
changes:
# Path scoping lives in scripts/ci_changed_scopes.py so every workflow reads
# one rule set. It fails open: pushes and CI config changes run every scope.
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
backend: ${{ steps.scopes.outputs.backend }}
frontend: ${{ steps.scopes.outputs.frontend }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# The PR merge commit and its first parent, the base branch tip.
fetch-depth: 2
- name: Detect changed scopes
id: scopes
run: python3 scripts/ci_changed_scopes.py --event "${{ github.event_name }}" >> "$GITHUB_OUTPUT"
agent-guidance: agent-guidance:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@ -61,17 +38,6 @@ jobs:
--after "${{ github.sha }}" --after "${{ github.sha }}"
--github-annotations --github-annotations
frontend-scope-reads:
# Not gated on a scope: the PR that makes frontend code read a new path
# outside the frontend scope may only run frontend jobs.
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v6
- name: Check frontend reads stay inside the frontend scope
run: python3 scripts/ci_changed_scopes.py --check-frontend-reads
label-declarations: label-declarations:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@ -86,8 +52,6 @@ jobs:
run: python scripts/check_label_declarations.py run: python scripts/check_label_declarations.py
lint-backend: lint-backend:
needs: changes
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
@ -117,8 +81,6 @@ jobs:
run: make lint run: make lint
lint-frontend: lint-frontend:
needs: changes
if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6

View File

@ -71,27 +71,21 @@ jobs:
name: Layer 2 — full-stack render (no API key) name: Layer 2 — full-stack render (no API key)
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Match the locked Playwright runtime so the image supplies its browsers.
container:
image: mcr.microsoft.com/playwright:v1.62.1-noble
options: --ipc=host
env:
UV_PYTHON_PREFERENCE: only-managed
timeout-minutes: 25 timeout-minutes: 25
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: "3.12"
- name: Install uv - name: Install uv
uses: astral-sh/setup-uv@v7 uses: astral-sh/setup-uv@v7
with: with:
# Must match backend/Dockerfile's UV_IMAGE tag; pinned by backend/tests/test_ci_uv_version_pin.py # Must match backend/Dockerfile's UV_IMAGE tag; pinned by backend/tests/test_ci_uv_version_pin.py
version: "0.11.1" version: "0.11.1"
- name: Install container-compatible Python
run: uv python install 3.12
- name: Install backend dependencies (replay gateway) - name: Install backend dependencies (replay gateway)
working-directory: backend working-directory: backend
run: | run: uv sync --group dev
uv sync --group dev
uv run --no-sync python -c 'import ssl, sqlite3'
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
@ -103,13 +97,9 @@ jobs:
- name: Install frontend dependencies - name: Install frontend dependencies
working-directory: frontend working-directory: frontend
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
- name: Verify Playwright Chromium - name: Install Playwright Chromium
working-directory: frontend working-directory: frontend
run: >- run: npx playwright install chromium --with-deps
node --input-type=module -e
'import { chromium } from "@playwright/test";
const browser = await chromium.launch();
await browser.close();'
- name: Full-stack replay render (DOM assertions are the gate) - name: Full-stack replay render (DOM assertions are the gate)
working-directory: frontend working-directory: frontend
run: pnpm exec playwright test -c playwright.real-backend.config.ts run: pnpm exec playwright test -c playwright.real-backend.config.ts

View File

@ -29,7 +29,7 @@ permissions:
jobs: jobs:
sandbox-image-smoke: sandbox-image-smoke:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 45 timeout-minutes: 25
env: env:
SANDBOX_SMOKE_IMAGE_REF: ${{ vars.SANDBOX_SMOKE_IMAGE || 'enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest' }} SANDBOX_SMOKE_IMAGE_REF: ${{ vars.SANDBOX_SMOKE_IMAGE || 'enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest' }}
FOWNER_SMOKE_IMAGE_REF: ${{ vars.SANDBOX_FOWNER_SMOKE_IMAGE || 'enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:1.11.0' }} FOWNER_SMOKE_IMAGE_REF: ${{ vars.SANDBOX_FOWNER_SMOKE_IMAGE || 'enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:1.11.0' }}
@ -38,16 +38,7 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v6 uses: actions/checkout@v6
- name: Free disk space for sandbox images
# This job only needs Python and Docker, not the runner's mobile/.NET/Haskell SDKs.
run: |
df -h /
sudo rm -rf /usr/local/lib/android /usr/share/dotnet /usr/local/.ghcup /opt/ghc
docker image prune --all --force
df -h /
- name: Resolve immutable image references for this run - name: Resolve immutable image references for this run
timeout-minutes: 30
# Pull on the runner's platform, then pass only immutable repo@sha256 # Pull on the runner's platform, then pass only immutable repo@sha256
# references to pytest. This keeps both the baseline and the 1.11.0 # references to pytest. This keeps both the baseline and the 1.11.0
# regression run reproducible even if either source tag moves later. # regression run reproducible even if either source tag moves later.
@ -85,6 +76,5 @@ jobs:
run: uv sync --group dev run: uv sync --group dev
- name: Run the live real-image smoke tests - name: Run the live real-image smoke tests
timeout-minutes: 10
working-directory: backend working-directory: backend
run: uv run pytest -m live tests/test_aio_sandbox_local_backend.py -v run: uv run pytest -m live tests/test_aio_sandbox_local_backend.py -v

View File

@ -67,7 +67,7 @@ jobs:
working-directory: backend working-directory: backend
run: | run: |
# Fail instead of silently skipping data-analysis tests on missing extras. # Fail instead of silently skipping data-analysis tests on missing extras.
uv run --locked python -c "import duckdb, openpyxl, pandas, requests, xlrd" uv run --locked python -c "import duckdb, openpyxl, requests"
uv run --locked python -m pytest ../tests/skills -q -rs uv run --locked python -m pytest ../tests/skills -q -rs
skill-review: skill-review:

View File

@ -55,23 +55,12 @@ jobs:
// ---- area: replaces .github/labeler.yml (path -> area) ---- // ---- area: replaces .github/labeler.yml (path -> area) ----
const AREA_RULES = [ const AREA_RULES = [
['area:frontend', [/^frontend\//]], ['area:frontend', [/^frontend\//]],
// Cover both backend packages. Keep the harness exclusions aligned ['area:backend', [/^backend\/app\//, /^backend\/packages\/harness\/deerflow\/(runtime|persistence|config|tools|guardrails|tracing|models|utils|uploads)\//]],
// with the dedicated tree rules below; the offline replay checks this.
['area:backend', [
/^backend\/app\//,
/^backend\/packages\/harness\/(?!deerflow\/(?:agents|subagents|reflection|sandbox|skills|mcp)\/)/,
/^backend\/packages\/extension-api\//,
]],
['area:agents', [/^backend\/packages\/harness\/deerflow\/(agents|subagents|reflection)\//, /(^|\/)langgraph\.json$/, /^backend\/.*\/prompts\//]], ['area:agents', [/^backend\/packages\/harness\/deerflow\/(agents|subagents|reflection)\//, /(^|\/)langgraph\.json$/, /^backend\/.*\/prompts\//]],
['area:sandbox', [/^docker\//, /^backend\/packages\/harness\/deerflow\/sandbox\//, /(^|\/)Dockerfile$/]], ['area:sandbox', [/^docker\//, /^backend\/packages\/harness\/deerflow\/sandbox\//, /(^|\/)Dockerfile$/]],
['area:skills', [/^skills\//, /^backend\/packages\/harness\/deerflow\/skills\//, /^frontend\/src\/core\/skills\//]], ['area:skills', [/^skills\//, /^backend\/packages\/harness\/deerflow\/skills\//, /^frontend\/src\/core\/skills\//]],
['area:mcp', [/^backend\/packages\/harness\/deerflow\/mcp\//, /^frontend\/src\/core\/mcp\//]], ['area:mcp', [/^backend\/packages\/harness\/deerflow\/mcp\//, /^frontend\/src\/core\/mcp\//]],
// deploy/ holds the Helm chart, which is release/deploy tooling like ['area:ci', [/^\.github\//, /^scripts\//]],
// scripts/: bump_version.sh rewrites its versions, verify_versions.sh
// and the chart workflow gate its rendering. Without this entry a PR
// that touches only deploy/ (plus its backend/tests/test_helm_*.py)
// matches no rule at all and arrives with no area label.
['area:ci', [/^\.github\//, /^scripts\//, /^deploy\/helm\//]],
['area:docs', [/^docs\//, /\.mdx?$/]], ['area:docs', [/^docs\//, /\.mdx?$/]],
['area:deps', [/(^|\/)(pyproject\.toml|uv\.lock|package\.json|pnpm-lock\.yaml)$/]], ['area:deps', [/(^|\/)(pyproject\.toml|uv\.lock|package\.json|pnpm-lock\.yaml)$/]],
]; ];

327
AGENTS.md
View File

@ -1,124 +1,251 @@
# DeerFlow # AGENTS.md
DeerFlow is an agent harness: a LangGraph-based backend with thread-isolated Guidance source; `CLAUDE.md` imports `@AGENTS.md`.
sandboxes, memory, subagents, skills and MCP tools, and a Next.js frontend. IM Module guides:
channels connect through the Gateway. `CLAUDE.md` imports this file; edit
guidance here, not in the shim.
## How guidance is organized - **[backend/AGENTS.md](backend/AGENTS.md)** — backend depth: harness/app split, agent &
middleware chain, sandbox, MCP, skills, memory, IM channels, persistence/migrations,
config system, test layout.
- **[frontend/AGENTS.md](frontend/AGENTS.md)** — frontend depth: Next.js App Router layout,
thread/streaming data flow, code style, commands.
Rules live in the `AGENTS.md` nearest to the code. Before you edit a directory, ## What is DeerFlow
read every `AGENTS.md` from that directory up to this file. Some coding agents do
not load the nested files on their own.
| Area | Guide | DeerFlow combines LangGraph and Next.js with thread-isolated sandbox execution,
| --- | --- | memory, subagents and extensible tools. IM channels connect through the Gateway.
| Backend: harness, Gateway, channels, tests | [backend/AGENTS.md](backend/AGENTS.md) |
| Frontend | [frontend/AGENTS.md](frontend/AGENTS.md) |
| nginx, Compose, provisioner | [docker/AGENTS.md](docker/AGENTS.md) |
| Orchestration scripts, `scripts/pnpm.py` | [scripts/AGENTS.md](scripts/AGENTS.md) |
| Skill review, skill tests | [skills/AGENTS.md](skills/AGENTS.md) |
| Extension examples | `examples/*/AGENTS.md` |
Humans start at [README.md](README.md), [CONTRIBUTING.md](CONTRIBUTING.md) and ## Service Topology
[docs/guide/](docs/guide/).
## Service topology A single `make dev` / Docker stack runs four cooperating services:
| Service | Port | Role | | Service | Port | Role |
| --- | --- | --- | | --- | --- | --- |
| Nginx | 2026 | The single entry point; open this in the browser | | **Nginx** | `2026` | Unified reverse-proxy entry point — open this in the browser |
| Gateway | 8001 | FastAPI REST API and the embedded agent runtime | | **Gateway API** | `8001` | FastAPI REST API + embedded LangGraph-compatible agent runtime |
| Frontend | 3000 | Next.js web interface | | **Frontend** | `3000` | Next.js web interface |
| Provisioner | 8002 | Optional; only for provisioner or Kubernetes sandboxes | | **Provisioner** | `8002` | Optional — only when sandbox is configured for provisioner/K8s mode |
Nginx serves the frontend, proxies `/api/*` to the Gateway and rewrites Nginx is the single public entry: it proxies `/api/*` to the Gateway, rewriting
`/api/langgraph/*` to the Gateway's native routes. `/api/langgraph/*` onto the Gateway's native routes, and serves the frontend — see
[backend/AGENTS.md](backend/AGENTS.md) for the runtime and router detail. It compresses
HTML and configured textual assets, deliberately leaving SSE, fonts, images, audio, and
video uncompressed at the proxy layer.
Before changing ingress, port bindings or provisioner mounts, read Keep the dedicated `/api/threads/{thread_id}/browser/stream` WebSocket regex before
[service topology details](docs/agent-service-topology.md). the generic threads regex in Docker, local and Helm nginx configs. Upgrade headers
and the 600s read timeout are pinned by `backend/tests/test_nginx_browser_websocket.py`.
Helm uses nginx's default connect/send timeouts for the in-cluster Gateway.
## Repository map Both Compose files publish nginx at `"${BIND_HOST:-127.0.0.1}:${PORT:-2026}:2026"`
(README's **loopback default**); bare `"${PORT}:2026"` binds `0.0.0.0`. Root `PORT`
controls Docker ingress only; local Next.js stays on `3000` so `.env` cannot
redirect `make dev`'s port wait. Nginx's IPv4+IPv6 `default_server` and Gateway's
`0.0.0.0:8001` bind are container-internal; only published nginx is external.
Require explicit bind addresses for new published ports;
`backend/tests/test_compose_default_bind_host.py` pins every service in both files.
| Path | Content | Provisioner PVC mode declares `USERDATA_PVC_NAME` once as `user-data`; extra and
| --- | --- | Lark broker credential mounts reuse it with their existing subPaths and read-only
| `backend/packages/harness/` | `deerflow-harness`, import `deerflow.*`: the agent framework | flags. Keep credential mounts broker-only and keep distinct volumes in hostPath mode.
| `backend/packages/extension-api/` | `deerflow-extension-api`: the public extension contract |
| `backend/app/` | The Gateway and the IM channels, import `app.*` |
| `frontend/` | The Next.js app (pnpm) |
| `docker/`, `deploy/helm/` | Compose files, nginx config, provisioner, Helm chart |
| `skills/public/`, `skills/custom/` | Committed skills and local, gitignored skills |
| `contracts/` | JSON contracts shared across components |
| `examples/` | Installable extension examples |
| `scripts/`, `tests/` | Root orchestration scripts, and tests for public skills |
`config.yaml` and `extensions_config.json` are copied from the example files at ## Repository Map
the repository root. Both are gitignored and the Gateway can write them. Do not
commit them.
## Commands ```
deer-flow/
`make help` lists the root targets. First setup is `make config`, then ├── Makefile # Root orchestration: drives the full stack (dev/start/stop, docker, setup)
`make install`, then `make dev`, which serves the stack on `localhost:2026` and ├── config.example.yaml # Template → copy to config.yaml (gitignored) at repo root
writes `logs/gateway.log` and `logs/frontend.log`. ├── extensions_config.example.json # Template → copy to extensions_config.json (gitignored): MCP servers + skills
├── backend/ # Python backend — see backend/AGENTS.md
```bash │ ├── Makefile # Per-module backend commands (dev, gateway, test, lint, migrate-rev)
cd backend && make test && make test-blocking-io # offline suites │ ├── extensions/sources/ # Deployable snapshots of locally installed Python extensions
cd backend && make format # CI runs ruff format --check │ ├── packages/extension-api/ # deerflow-extension-api package (import: deerflow_extension_api.*) — public extension contract
cd backend && python -m pytest tests/path/test_x.py::test_name -q │ ├── packages/harness/ # deerflow-harness package (import: deerflow.*) — agent framework
cd frontend && pnpm check && pnpm test │ └── app/ # FastAPI Gateway + IM channels (import: app.*)
cd frontend && pnpm rstest run <pattern> ├── frontend/ # Next.js frontend (pnpm) — see frontend/AGENTS.md
make check-agent-guidance # size budget of these guides ├── docker/ # docker-compose files, nginx config, provisioner
├── skills/ # Agent skills: public/ (committed), custom/ (gitignored)
│ # Managed integration skill packs are global at .deer-flow/integrations/skills/{provider}/
│ # Integration credentials and enabled state remain per-user
├── contracts/ # Cross-component JSON contracts (e.g. subagent status, skill review)
├── examples/ # Extension examples: deerflow-extension-{example,bookmarks,agent-teams}
├── scripts/ # Root orchestration scripts invoked by the Makefile (check, configure, doctor, support_bundle, serve, nginx, docker, deploy, setup_wizard)
├── tests/ # Root-level tests (currently tests/skills/ — public skill tests)
└── docs/ # Cross-cutting docs, plans, and design notes
``` ```
## Rules for every change Third-party extensions load from operator-controlled `config.yaml -> plugins:`.
This imports code, so the list stays outside API-writable `extensions_config.json`.
Extensions contribute middleware, lifecycle observers, Gateway services, FastAPI
routers, and experimental full-stack plugins. Use
`deerflow extensions install/upgrade/list/enable/disable/remove` or root
`make extension-*` wrappers. Restart Gateway after every mutation. Build hooks
and extension code run with Gateway privileges; use only trusted operator sources.
Transactions, accepted source forms, locking, and contribution contracts:
[extensions guide](backend/packages/harness/deerflow/extensions/AGENTS.md).
User manual: `frontend/src/content/{en,zh}/harness/extensions/`.
- **Evaluate an extension first.** Before you add a feature to core code, check **Extension-first evaluation** — before implementing a feature by editing core code,
whether it can ship as a packaged extension. Core is the place for bug fixes evaluate whether it can ship as a packaged extension through the contribution points
and for changes to the agent loop, memory, context compaction and above. Stay in core for bug fixes and for changes to the agent loop, memory, context
authentication. When the existing hooks cannot express a feature, add a compaction, or authentication. If existing hooks cannot express the feature, add a
generic hook to the extension contract and an extension that uses it; business generic hook to the extension contract plus an extension that uses it — do not
logic is not hard-coded into core. Contract and examples: hard-code business logic into core. Working examples:
[extensions guide](backend/packages/harness/deerflow/extensions/AGENTS.md), `examples/deerflow-extension-{example,bookmarks,agent-teams}`.
`examples/`. [Workflow guide](examples/deerflow-extension-workflows/AGENTS.md): public
- **Extensions are operator-controlled code.** They load from `plugins:` in AgentRuns; POSIX, one process/store; approval and session-authorized recovery; uncertain admissions need reconciliation;
`config.yaml`. The list stays out of the API-writable `extensions_config.json`, no multi-Gateway failover or hard currency budget.
because loading an extension imports code with Gateway privileges. Install
from trusted sources only, and restart the Gateway after every extension
change.
- **Cover behavior changes in the owning module's suite.** Fold regression cases
into that module's existing suite instead of opening a one-fix test file, and
update or delete obsolete tests in the same change.
- **Document behavior next to its topic, in the same change**: user-facing
behavior in `docs/guide/` or `backend/docs/`. `README.md` is an index; change
it only to add or re-point a link.
- **Keep the version fields identical**: `backend/pyproject.toml`,
`backend/packages/harness/pyproject.toml`, `frontend/package.json`, and
`version` and `appVersion` in `deploy/helm/deer-flow/Chart.yaml`.
`scripts/bump_version.sh <ver>` updates them and `backend/uv.lock`, and
`scripts/verify_versions.sh <ver>` checks the result. Tag CI blocks publishing
on drift. See [RELEASING.md](RELEASING.md).
## What belongs in an `AGENTS.md` Knowledge management/space policy: `examples/deerflow-extension-knowledge-{management,platform}/`
(scoped `AGENTS.md`, `CONTRACT.md`). Use existing plugin/router/principal contracts;
retrieval stays independent. Space policy intersects administrator/resource/operation
and upstream grants, never grants chat access. SQLite holds plugin-owned space policy.
Provider stages are not completion evidence; reconcile uncertain writes, never retry.
An agent reads these files on every task, so each line costs attention. A guide Root runtime configs: copy `config.example.yaml` → `config.yaml` and
holds four kinds of content: `extensions_config.example.json` → `extensions_config.json` (MCP/skills).
Both are gitignored and Gateway-editable; schema/resolution:
[backend/AGENTS.md](backend/AGENTS.md).
1. Scope: what the directory owns, in one or two sentences. Skill quality review note:
2. Verification: the exact commands. - `skills/public/skill-reviewer/` is the built-in read-only reviewer (harness tool
3. Traps: where the code misleads, or where a plausible change breaks something `review_skill_package`, contracts in `contracts/skill_review/`). Model-visible review
that a local test run does not show. data is tag-neutralized; raw payloads stay in tool artifacts. See
4. Decisions and their reasons that the code cannot state, and links to docs. [backend/AGENTS.md](backend/AGENTS.md) for the ownership boundaries.
- CI waivers live in `.github/skill-review-waivers.v1.json`, enforced by
`scripts/review_changed_public_skills.py`. Only the manifest from the trusted base
revision can suppress a run, and blocker findings can never be waived.
Values, defaults, field lists, function inventories, test names, issue numbers Scheduled-task note:
and history stay in the code, the tests and git. Write full sentences in the - `scheduler.tool_enabled` (default off) offers owner-bound schedule tools only
positive form and give the reason. `make check-agent-guidance` enforces the size through Gateway capability admission. Interactive turns create/manage their
budget. schedules; scheduled turns can request stopping only their own schedule.
Per-occurrence goal success does not end a recurring schedule.
- The scheduled-task MVP adds a workspace page at `/workspace/scheduled-tasks` plus a
background scheduler gated by `config.yaml -> scheduler.enabled`.
- Scheduled runs are non-interactive: `ask_clarification` is excluded. `non_interactive`,
`disable_clarification`, and `github_token` are honored only for internally-authenticated
callers; client-supplied copies are dropped.
- Busy occurrences persist as `queued`; `scheduler.queue_timeout_seconds` bounds the wait.
Do not reintroduce skip-on-overlap.
### Office preview example ## Commands: Root vs. Module
`examples/deerflow-extension-office-preview/` packages Office readers through the **Root stack commands** (from repo root):
optional `artifactPreviews` browser contract. Keep parser dependencies and resources
in the extension; rebuild its manifest and static module graph after UI changes. ```bash
Test packaged assets with the Office E2E fixtures; rendering must preserve original make setup # Interactive setup wizard (recommended for new users)
downloads and state its search limits. make doctor # Check configuration and system requirements
make support-bundle # Generate redacted troubleshooting summary, AI issue draft, and optional zip
make config # Generate local config files from the examples
make check # Check that required tools are installed
make install # Install all dependencies (frontend + backend + pre-commit hooks)
make extension-install SOURCE=... # Install and enable a trusted Python extension
make extension-upgrade SOURCE=... # Replace an installed extension and keep its config
make extension-list # List configured Python extensions
make extension-enable NAME=... # Enable an installed extension (restart required)
make extension-disable NAME=... # Disable without uninstalling (restart required)
make extension-remove NAME=... # Remove package and config entry (restart required)
make dev # Start all services with hot-reload (Gateway + Frontend + Nginx)
make start # Start all services in production mode (local, optimized); SKIP_FRONTEND_BUILD=1 reuses the last frontend build
make stop # Stop all running services
make up / down # Build/stop the production Docker stack (browser at localhost:2026)
make docker-start / docker-stop / docker-logs # Docker development environment
```
Production uses image Python (`uv run --no-sync`) and `exec` for SIGTERM;
Compose sets `init: true` (`backend/tests/test_gateway_sigterm_delivery.py`).
`make up` waits for Gateway `/health`; failures show Compose status and Gateway logs.
Docker logs/restarts resolve `DEER_FLOW_ROOT` from this checkout before Compose,
as start/stop do.
Full list: `make help`.
**Module commands** (from each module):
```bash
# Backend (see backend/AGENTS.md for the full set)
cd backend && make dev # Gateway API with reload (port 8001)
cd backend && make test # Four parallel shards; excludes live and blocking-I/O tests
cd backend && make test-blocking-io # Strict blocking-I/O suite
cd backend && make lint # ruff check
cd backend && make format # ruff format
# Frontend (see frontend/AGENTS.md for the full set)
cd frontend && pnpm dev # Dev server: Webpack by default (override with DEER_FLOW_DEV_BUNDLER=turbo)
cd frontend && pnpm check # Lint + type check (run before committing)
cd frontend && pnpm test # Unit tests
```
Host pnpm calls use `scripts/pnpm.py`: native Windows tries `pnpm.cmd` before
`pnpm`; POSIX reverses the order. Its Corepack fallback applies the same ordering
to `corepack.cmd` and `corepack`. The runner operates from `frontend/` so
Corepack honors its pinned package-manager version.
### Prerequisites before `make dev`
Run `make config`, then `make install`, then `make dev` on first setup.
`make dev` requires existing config; both runtime configs are API-editable and
gitignored. Never commit them.
### Run a single test
```bash
# Backend (pytest); run one file or one test function
cd backend && python -m pytest tests/test_compose_default_bind_host.py -q
cd backend && python -m pytest tests/path/to/test.py::test_func -q
# Frontend (rstest)
cd frontend && pnpm rstest run <pattern> # e.g. pnpm rstest run my-component
```
### Logs
- Docker stack: `make docker-logs` (or `docker compose -f docker/... logs -f <svc>`).
- Local `make dev`: Gateway and frontend output goes to
`logs/gateway.log` and `logs/frontend.log` in the repository root.
Run `tail -f logs/gateway.log logs/frontend.log` there to follow both.
## References
- Backend work → **[backend/AGENTS.md](backend/AGENTS.md)**
- Frontend work → **[frontend/AGENTS.md](frontend/AGENTS.md)**
- Setup & install → **[Install.md](Install.md)**, **[CONTRIBUTING.md](CONTRIBUTING.md)**
- Project overview & usage → **[README.md](README.md)** (translations: `README_zh.md`,
`README_ja.md`, `README_fr.md`, `README_ru.md`, `README_pt.md`, `README_ko.md`)
- Security policy → **[SECURITY.md](SECURITY.md)**
- Changes → **[CHANGELOG.md](CHANGELOG.md)**
- Cutting a release → **[RELEASING.md](RELEASING.md)**
## Cross-Cutting Conventions
Repo-wide conventions:
- Update `README.md` for user-facing changes and the relevant `AGENTS.md` for
development/architecture changes in the same change set.
- **Test-driven development** — features and bug fixes ship with tests. Backend tests live
in `backend/tests/` (TDD is mandatory there; see [backend/AGENTS.md](backend/AGENTS.md));
frontend tests live in `frontend/tests/`.
Skill-creator tests must preserve YAML values/body, restore bytecode settings,
and check invalid metadata through offline CLI subprocesses.
Public skill script regressions live in `tests/skills/` and run in Skill Review CI
independently of package review. Exercise dependency fallbacks with the optional
import unavailable and mock HTTP transport to keep tests offline.
Video, podcast, and chart-visualization CLI failures exit non-zero;
diagnostics on stderr, success URLs on stdout; test offline.
- **Before pushing** — backend `make format`, frontend `pnpm check`.
Backend CI enforces `ruff format --check`.
- **Skill text encoding** — use explicit UTF-8 for textual skill resources.
Read `SKILL.md` with `encoding="utf-8-sig"` to strip a leading BOM; write with
`encoding="utf-8"`. Never rely on the platform locale.
- **Version sources must stay in lockstep** — a release version must match identically in
`backend/pyproject.toml`, `backend/packages/harness/pyproject.toml`, `frontend/package.json`,
and `deploy/helm/deer-flow/Chart.yaml` (`version` + `appVersion`), and `backend/uv.lock` must
record the same version for the root `deer-flow` and `deerflow-harness` workspace members
(uv stores its PEP 440 form, e.g. `2.1.0rc0`). Pushing a `v*` git tag triggers CI
that runs `scripts/verify_versions.sh` and **blocks all publishing** if any source drifts.
Before bumping a version, run `scripts/bump_version.sh <ver>` (aligns the five fields and
refreshes `backend/uv.lock` at once — it needs `uv` on `PATH`) and
`scripts/verify_versions.sh <ver>` to catch drift early. See [RELEASING.md](RELEASING.md).
- **Don't edit `CLAUDE.md`** — it only contains `@AGENTS.md`. All agent guidance changes
belong here in `AGENTS.md`; `CLAUDE.md` is a thin import shim.

View File

@ -7,519 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
This section accumulates work toward the **2.3.0** milestone
([2.3.0](https://github.com/bytedance/deer-flow/milestone/4)).
### Added
- **crawl4ai:** `web_fetch` accepts an optional `max_chars` output cap (default
4096). A page cut at the cap ends with a note giving the kept and total
length. ([#8553](https://github.com/bytedance/deer-flow/pull/8553))
- **summarization:** The built-in compaction prompt guides the summarizer to
preserve active user requirements, literal approval phrases, action conditions,
and explicit revisions. Explicit `summarization.summary_prompt` configurations
continue to take precedence. ([#8114](https://github.com/bytedance/deer-flow/pull/8114))
- **sandbox:** Short ranged `read_file` calls on uploaded and workspace files
display source line numbers when the result contains 1–40 lines and the
labeled view fits the output budget. ([#8109](https://github.com/bytedance/deer-flow/pull/8109))
- **projects:** Owner-scoped project memory with automatic-extraction, delete and
move-to-instructions controls. Project facts share DeerMem's extraction call
while remaining isolated from user facts. New shelf documents receive
best-effort summaries by default. ([#8117])
- **hitl:** Optional Ask, Auto and Full tool-permission modes, independent of
reasoning mode. Auto uses a separate tool-free review call with an existing
model profile; uncertain or high-risk operations require a human. Cards show
complete arguments and support approve, reject, edit and exact-operation chat
grants with revocation. Root approvals survive restart through checkpoints;
interactive subagents wait through an owner-scoped channel with cancellation
and expiry. Mandatory deployment rules and account permissions apply in every
mode. Personal/platform MCP connections, policy and arguments bind approvals.
Disabled by default; see the configuration guide. `config_version` 66.
- **knowledge:** The WeKnora retrieval extension offers opt-in shared read-only
access for authenticated users, without maintaining a per-user allowlist.
Exact-user allowlists remain the default; shared access requires matching
host-verified identity and grants no management permissions. ([#7944](https://github.com/bytedance/deer-flow/pull/7944))
- **community:** New SpecStream `web_search` and `web_fetch` provider. Search returns
ranked results with a direct answer when the sources agree on one, and fetch
returns a page or document as markdown. ([#7968](https://github.com/bytedance/deer-flow/pull/7968))
- **subagents:** Durable batch items can wait for explicitly named prerequisites.
An optional, once-only lead-Agent follow-up completes a previously requested
summary or delivery after the batch ends, with persisted admission, cancellation
and authorization checks. Active Goals retain continuation ownership. ([#7839](https://github.com/bytedance/deer-flow/pull/7839))
- **chat:** Running Web chats offer Queue and Steer in the composer. Queue
waits for the next turn; Steer lets the main Agent handle updates while
native subagents pause and resume. Unconfirmed messages can be retried
after a Gateway restart. ([#7729])
- **models:** Administrators can select StepFun in **Settings → Models** and
connect an ordinary StepFun API account with an API key and model ID.
([#7988](https://github.com/bytedance/deer-flow/pull/7988))
### Changed
- **checkpoint:** DeltaChannel deployments now require `langgraph-checkpoint`
4.3.0, SQLite saver 3.1.2, and Postgres saver 3.1.3, excluding versions that
could reorder parallel writes during replay or lose paged ancestor history.
The ordering and Postgres pagination contracts now fail on regression instead
of skipping. ([#8139])
### Fixed
- **agents:** A todo list revised after the last `write_todos` call (for
example an approved plan edited on resume) is shown to the model again
instead of being silently skipped, and a stale injected reminder is
refreshed in place, or removed when the visible call already shows the
current list. Injected reminders are stamped with middleware
provenance, and caller-edited todo text is neutralized before rendering so
it cannot forge framework tags. Reminders persisted before provenance
stamps existed are migrated or superseded instead of being left next to
a fresh one, an explicitly cleared list keeps a stamped clear-state
notice only while a superseded non-empty write is still visible, and a
hidden caller message that only wraps text in
reminder tags is never treated as a pre-stamp reminder,
and todo items render as data after the framework block rather than
inside it. ([#8168](https://github.com/bytedance/deer-flow/issues/8168))
- **scheduler:** Scheduled-task IM notices no longer forward a credential that
carries no secret-like key. A URL's user info
(`postgres://admin:hunter2@host`) and an `Authorization` or `Cookie` header
value (`Authorization: Bearer ...`) used to reach the platform verbatim; both
now read `[redacted]`, and the scheme with the rest of the sentence stays
readable. A URL without credentials is unchanged. A `Cookie` header or a
`Digest` credential is replaced through the end of the line, so text that
follows it on the same line is removed as well. ([#8250])
- **frontend:** Cron presets in the task form now require minute 0-59, hour
0-23 and day of month 1-31, so an out-of-range expression such as
`0 24 * * *` stays a custom schedule and keeps its original text. Previously,
it was parsed as a preset and could be clamped to a different time when
serialized for submission. Creating or duplicating a task with an invalid
expression, or updating its schedule configuration while the expression is
invalid, returns the Gateway's `422`; edits to other fields do not revalidate
an unchanged schedule. ([#8020])
- **gateway:** Creating a thread with checkpoint-owned keys such as `step`,
`parents` or `counters_since_delta_snapshot` in its metadata no longer
leaves the thread broken. Those keys used to land on the thread's first
checkpoint, so a bad `parents` made the thread's history fail with 500 for
good, and a bad `step` or delta counter made every later turn fail. A
`deerflow_agent_name` key was also copied into the next state update as if
the server had set it. The first checkpoint now takes none of these keys
from the request. ([#8019])
- **mcp:** Two enabled MCP servers could bind the same tool name (server `a`
exposing `b_x` and server `a_b` exposing `x` both bind `a_b_x`). Both
declarations reached the model and the provider silently kept only one.
Duplicate bound names are now dropped with a warning naming the surviving
server, in enabled-server declaration order. Note the surviving server is
stable only while its discovery keeps succeeding: if the winner's discovery
fails transiently, the later duplicate becomes served again, so the
implementation behind a bound name can alternate across cache generations
with server health.
([#8135](https://github.com/bytedance/deer-flow/pull/8135))
- **channels:** WeCom no longer drops images between 2 MB and 10 MB. The
adapter capped image uploads at 2 MB — the voice limit in the same protocol —
so a larger chart was skipped before upload and the turn arrived without it.
The cap now matches the platform's 10 MB for images; the 20 MB file limit is
unchanged. ([#8174])
- **threads:** Deleting a conversation on Windows no longer fails with
`Failed to delete local thread data.` when the workspace holds a file whose
path exceeds `MAX_PATH`. The thread directory is now resolved through the
Windows extended-length namespace before removal.
([#8144](https://github.com/bytedance/deer-flow/pull/8144))
- **channels:** A WeCom group command that follows the bot mention now runs as a
command. WeCom keeps the mention inside the message text (`@RobotA /new`), and
the classifier required a bare leading `/`, so `/new` and `/status` sent in a
group became chat turns. Leading mentions are skipped for the command lookup
only; ordinary chat keeps them and `/connect` is unchanged. Mirrors the Feishu
and DingTalk handling. ([#8118])
- **subagents:** Apply tool allowlists and denylists to middleware-declared
tools even when global authorization is disabled, including the default
denial of `task`. Restricted subagents reject non-Sequence declarations
explicitly, and invalid declarations report middleware-specific configuration
guidance. Final graph assembly checks both explicit and middleware tools;
framework-generated discovery helpers retain their filtered catalogs.
([#8136](https://github.com/bytedance/deer-flow/pull/8136))
- **frontend:** **Share** in a sidebar chat's menu now copies a link to the
deployment you are using. On `localhost` and `127.0.0.1`, the default
`make dev` and Docker addresses, it copied a link to the hosted demo
(`deer-flow-v2.vercel.app`) instead. That link never opened the
conversation, and opening it sent the thread id to an outside host.
([#8126])
- **runtime:** In multi-worker mode (`run_ownership.heartbeat_enabled`), a
worker that had lost its run to a peer could put the row back. Its assembly
evidence write was an unconditional full-row upsert, so after a peer
reclaimed the run it reset the row to `running` and erased the takeover
error. The run could then finish as `success` after the peer had already
reported it failed, or be reclaimed a second time. The evidence is now merged
into the row's metadata only while the worker still holds a live lease on an
active run (`RunStore.merge_owned_metadata()`); otherwise the worker stops
the run before executing it. Custom `RunStore` implementations used with
heartbeats must implement that method. ([#8046])
- **subagents:** Concurrent creates for the same managed-subagent name in shared
file storage now preserve the winning definition and return HTTP 409 to the
losing request instead of reporting two successes and overwriting one definition.
Gateway startup also probes hard-link support and warns if the storage volume
cannot support managed subagent creation. ([#8132](https://github.com/bytedance/deer-flow/pull/8132))
- **agents:** A high-risk tool call without a usable id no longer wedges the
thread when `hitl_approval` is enabled. A provider that omits a tool-call id
(`None`) or repeats one within a response made the middleware pause with an
approval payload the Gateway can never validate: every resume answered 422
and every new run stayed 409-blocked, all-reject included. An empty id was
technically resumable but is denied as well, since strict providers reject it
when the conversation is replayed. Such calls are now removed from the model
response with a visible rejection note instead of pausing, and deny paths no
longer build an invalid `ToolMessage` for a null id. A call whose id an
ordinary call also carries is stripped before it can be answered by result,
so the next request cannot advertise the id twice with two results.
A pause stored before
this change stays unresolvable; in-place recovery is tracked in [#8071].
([#8069])
- **runtime:** A HITL rejection, including the all-reject escape after approval is
disabled or the gated tools change during a pause, now reaches the thread's
message history under the resume run instead of existing only in checkpoint
state. ([#8073](https://github.com/bytedance/deer-flow/pull/8073))
- **summarization:** vLLM compaction counts reasoning tokens replayed to the
model when checking the trigger and estimating how much history to keep.
([#8077](https://github.com/bytedance/deer-flow/pull/8077))
- **gateway:** Posting feedback twice for the same run now returns a 409
instead of a 500. `POST /api/threads/{id}/runs/{run_id}/feedback` allows one
feedback row per user and run; a retry, or feedback on another message of the
same run, hit that unique key and the Gateway failed with an unhandled
database error. The 409 points callers at `PUT` on the same route, which
updates the existing feedback. ([#8064])
- **frontend:** Reopening a conversation restores successfully handed-off shared
artifacts in the Artifacts sidebar. ([#8080](https://github.com/bytedance/deer-flow/pull/8080))
- **sandbox:** AIO commands from independent subagents now run concurrently when
they carry per-call environment variables, including Lark CLI commands.
Commands within one subagent remain ordered and client cleanup drains them.
- **sandbox:** BoxLite VMs recovered at startup now run health checks, commands,
and cleanup on the provider's event loop, avoiding sync/async SDK mismatches
that made healthy recovered VMs fail their first command. ([#8072])
- **uploads:** Re-uploading a file whose name collides with a compound archive
suffix no longer inserts the dedupe counter inside the suffix. A second
`report.tar.gz` is now named `report_1.tar.gz` (matching `report_1.tar` and
`report_1.txt`), instead of `report.tar_1.gz`, so the extension stays intact
for file-type detection. ([#8042](https://github.com/bytedance/deer-flow/pull/8042))
- **gateway:** Deleting a thread no longer reports success while its
conversation stays readable. When the checkpoint store failed during
`DELETE /api/threads/{id}`, the route logged it at DEBUG, removed the
thread's metadata row and returned success; any signed-in user could then
read the leftover title and messages through `GET /threads/{id}`, `/state`,
`/history` and `/goal`, and the owner could not retry. The delete now
returns a 500 and keeps the thread, so the owner can delete it again.
([#7992])
- **gateway:** Creating a thread with a caller-supplied `thread_id` that
already belongs to another user now returns a non-disclosing 404
(`Thread not found`) instead of a 500. The duplicate-key recovery path reads
the surviving row back bypassing the owner scope so the cross-owner case
mirrors `ThreadOwnershipConflictError`; a duplicate key with no surviving row
is still surfaced as a 500. ([#8057])
- **models:** Cancelling a Codex-backed run now closes its upstream HTTP/SSE
connection, including while waiting for response headers, and retry waits
are cancellable. Local resources are released; the remote service may still
continue generation. ([#8053](https://github.com/bytedance/deer-flow/pull/8053))
- **middleware:** With PII redaction enabled, a long run of text without
spaces (such as a pasted hex dump) no longer stalls the Gateway. The email
detector was quadratic in the length of such a run, and redaction re-scans
every user message on every model call, so one 100 KB paste blocked every
thread for about 6 s per model call. The scan is now linear, and it redacts
exactly the same addresses as before. ([#8006])
- **agents:** Token budgets count separate accepted model calls even when a
provider reuses message IDs, so repeated IDs no longer bypass the configured
cap. Hard stops preserve already-completed structured-output tool results.
([#8050](https://github.com/bytedance/deer-flow/pull/8050))
- **subagents:** Managed subagent creation now rejects Windows reserved device
names (`CON`, `PRN`, `AUX`, `NUL`, `COM1-9`, `LPT1-9`) at the shared
`normalize_managed_subagent_name(..., for_creation=True)` validator and
Gateway `/api/subagents` boundary before attempting filesystem writes,
preventing `OSError` failures on Windows hosts while keeping existing
read and delete operations permissive.
- **scheduler:** A stored `schedule_spec` that is JSON null, a list or a string
no longer aborts the scheduler poll. `stored_next_run_at` caught the value
errors from a dropped zone or a newer cron parser, but a non-object spec
fails on `.get`; the launch-failure handler recomputed it again, so the
`AttributeError` escaped `run_once`'s claimed-task loop. Such a task is now
paused with the reason, like the other unusable schedules. The poll loop also
isolates one task's dispatch failure from the rest of its claimed batch, so a
future per-record raise costs one tick instead of every other claimed task.
([#7998])
- **scheduler:** Exceptions escaping the queue-timeout sweep or the
queued-occurrence drain are now contained to that occurrence. The
scheduler logs the failed row and continues with the remaining queue
and the tasks claimed in the same poll. Expired rows are excluded before
owner ranking and the batch limit, and a launch claim enforces the same
cutoff, so a row left queued by a failed sweep neither starts nor crowds
healthy work out of the queue while timeout recovery retries it. ([#7998])
- **scheduler:** One scheduled task whose saved schedule can no longer be
computed no longer stops every other task. When a stored timezone or cron
expression stopped working (a zone missing from the time zone database
after an upgrade, a cron expression a newer croniter rejects), recomputing
its next run raised inside the scheduler poll; once its launch lease
expired, every later poll failed before admitting any due task. That task
is now paused with the reason as its last error, and resuming it reports
the problem until the schedule is fixed. ([#7993])
- **models:** A Claude model using a Claude Code OAuth token no longer fails
every request once the request carries `betas`. The OAuth betas
(`oauth-2025-04-20`, …) were only the client's default `anthropic-beta`
header, and the SDK sends a request's `betas` as that header instead, so a
configured `betas` list (even `[]`), per-call `betas`, or a server tool for
which langchain-anthropic adds a beta left them out and Anthropic rejected
the token. The OAuth betas now lead any request `betas` and any
`anthropic-beta` in `extra_headers`.
([#8061](https://github.com/bytedance/deer-flow/pull/8061))
- **community:** A search or fetch API key that ends in a newline no longer
leaks into the conversation. GroundRoute (`GROUNDROUTE_API_KEY`), InfoQuest,
Tavily, Exa, Jina, Firecrawl, fastCRW and Crawl4AI put the key into an HTTP
header as read, so a key from a file (a Kubernetes Secret created with
`--from-file`) made the transport fail with `Illegal header value b'Bearer
<key>\n'`. That message, key included, became the tool result the model and
the conversation history kept, and four of them also logged it. Keys now go
through `provider_credentials.resolve_api_key` like the other providers', and
a blank configured key falls back to the environment for Tavily, Exa,
Firecrawl and fastCRW. fastCRW without a key of its own no longer lets the
Firecrawl SDK send `FIRECRAWL_API_KEY` to the fastCRW endpoint, and a blank
`TAVILY_API_KEY`, `EXA_API_KEY` or `FIRECRAWL_API_KEY` now counts as missing
instead of reaching the SDK as is. ([#7981])
- **community:** Browserless is the last search/fetch provider that read its
token raw. A `BROWSERLESS_TOKEN` or configured `token` from a file kept its
trailing newline and became the auth query parameter, so every `web_fetch`
and `web_capture` request failed authentication while the key was correct.
Both now go through `provider_credentials.resolve_api_key`, and only an
omitted `token` key falls back to the environment: an explicit `""` or
`null` keeps opting a self-hosted capture endpoint out of authentication.
([#8043])
- **docker:** Images built from a checkout no longer contain its local
configuration. `.dockerignore` did not exclude `config.yaml`,
`config.yaml.bak`, `extensions_config.json` or `mcp_config.json`, so a
checkout that keeps them in the legacy `backend/` location baked its model
API keys and MCP credentials into every gateway image layer through
`COPY backend ./backend`. `frontend/.env.local` reached the frontend image the
same way. They are now excluded at the root and in `backend/`, along with
`.env*.local` at any depth, `frontend/*.pem`, and the credential files the
extension manager refuses inside extension snapshots. A locally built
frontend image no longer inlines `NEXT_PUBLIC_*` values from
`frontend/.env.local`; the Docker stack's single nginx origin needs none of
them. Published CI images were not affected; rebuild local images that were
pushed or shared. ([#7958])
- **agents:** Unfinished todos no longer trigger additional model calls or
tool execution after a loop-detection, run token-budget, provider-safety, or
model output-length stop. Todo state is preserved so users can continue in a
later run. ([#7953])
- **runtime:** A thread can accept new runs and mutations after a transient
database failure leaves a completed operation's reservation in place. The
next request for the thread on the same Gateway worker retries the release,
including in single-worker deployments with lease heartbeats disabled.
([#8068](https://github.com/bytedance/deer-flow/pull/8068))
- **channels:** Long Feishu/Lark answers are no longer lost. Card text was
unbounded and ASCII-escaped, so an answer of about 4,400 CJK characters made
the card request exceed Feishu's 30 KB limit (`230025`); the final patch and
its reply fallback were both rejected, and the running card stayed on its
last streamed text or a bare `▉`. Cards now send CJK unescaped and are
budgeted by the bytes they add to the request. A streamed update shows what
fits, and a longer final answer continues in up to 10 cards replied to the
same message, split at line breaks; a retry resumes after the cards already
delivered. ([#7798])
- **channels:** WeCom group messages now have their own conversation. Every
message used the sender's userid as both chat and topic ID, so a member's
private chat and every group they wrote in shared one DeerFlow thread
wherever no group binding kept them apart: in auth-disabled mode, with
`require_bound_identity: false`, and under legacy group bindings. A group
reply could then draw on the member's private chat or another group, and a
reply sent without its frame went to the private chat. Groups are now keyed
by `chatid` with one thread per member, and private chats keep their
threads. A group bound with its own `/connect` keeps its thread; a legacy
group binding, which covers every group of the bot, starts a new one in
each group. ([#7794])
- **memory:** DeerMem rejects backups with duplicate fact IDs before replacing
saved memory, regardless of entry order. ([#8151])
- **memory:** Importing a backup without a `facts` array now returns HTTP 422
and preserves saved memory. An explicit empty array still clears the selected
fact bucket. ([#8131])
- **memory:** An agent-scoped memory write whose `agent_name` is a Windows
reserved device name (`NUL`, `CON`, `COM1`, ...) is now rejected with a `422`
on the two routes that create that scope, `POST /memory/facts` and
`POST /memory/import`. DeerMem resolves the scope to
`{storage}/users/{uid}/agents/{name}/facts` and creates it on the first write;
the character-class check admitted such names, so the write raised
`FileNotFoundError` and the endpoint answered an opaque `500`. The check reuses
`windows_incompatible_segment()` and applies on every platform. Read and delete
routes stay permissive, so a scope with a reserved-name identifier that an
older release stored on a Linux host can still be exported and cleared.
([#7941])
- **skills:** A custom skill name that is a Windows reserved device name
(`nul`, `con`, `com1`, ...) is now rejected when the skill is created —
`skill_manage` `create` and `.skill` archive install — on every platform. The
hyphen-case grammar admitted such names, and the skill name becomes a
directory under `custom/`, so creating one "succeeded" on Windows without
producing a directory and the first write inside it failed with
`FileNotFoundError`; on Linux the install succeeded but could never be
copied, mounted or exported to a Windows host. The archive path also refuses
member path segments that cannot be created on every host, matching support
file writes. Reading and deleting an existing skill stay permissive, so a
skill an older release created on a Linux host can still be inspected and
removed. ([#7945])
- **sandbox:** Fresh lazy AIO runs with an explicit authorized skill view no
longer create or acquire a sandbox before the first sandbox-backed tool
call. Existing sandbox bindings and providers that require skill uploads
retain their eager synchronization behavior. ([#7782])
- **parsing:** Follow-up suggestions and the `/goal` evaluator keep a literal
`<think>` tag that appears inside a JSON string value, such as an answer
quoting the tag, while reasoning around the JSON is still removed. An
unclosed literal tag inside a string no longer truncates the document and
fails parsing, and reasoning outside the payload still strips and truncates
as before. ([#7907])
- **gateway:** A caller-supplied thread ID that is a Windows reserved device
name (`NUL`, `CON`, `COM1`, ...) is now rejected at the shared
`validate_thread_id()` boundary. Such IDs previously passed validation but
failed workspace creation on Windows hosts with `FileNotFoundError`. The
check reuses `windows_incompatible_segment()` and applies on every platform,
so threads with reserved-name IDs created on Linux hosts will fail
validation on read/resume/upload routes after upgrade (deletion still
works). ([#7892])
- **extensions:** Context-compaction observers now learn which task a
compaction happened in. Inside a lead run or subagent they receive that
task's store instead of a detached one, and `CompactionEvent` gains
`task_id`, `run_id` and `thread_id` (default `None`), copied from the
`TaskInfo` the host now seeds into every task store even when no lifecycle
contributor is registered. A manual `/compact` still gets a detached store
and `None` ids. `deerflow-extension-api` is now 0.2.10; existing
extensions keep working. ([#7831])
- **channels:** A DingTalk reply in AI card mode (`card_template_id`) is no
longer lost when a card request fails, for example without card permission
or during a DingTalk outage. dingtalk-stream logs a failed card request and
returns as if it succeeded, so neither the text running reply nor the
`sampleMarkdown` fallback for the final answer ever ran. The channel now
sends card requests itself and falls back when one fails. ([#7781])
- **harness:** Retrying a failed item no longer reopens a cancelled durable
subagent batch. `retry_item` kept only a paused batch as it was, so a failed
item of a cancelled batch put the batch back to `queued`, the worker claimed
and ran the item, and the batch ended `completed`. The retry route now
answers 409 for a cancelled batch, including when the cancel commits while
the retry is in flight on SQLite, and the workspace no longer offers Retry
there. Retrying in a completed, failed, running or paused batch is
unchanged. ([#7792])
- **gateway:** A run that names a missing or invalid custom agent now says so.
Messaging a chat whose custom agent was deleted, or passing a malformed
`agent_name`, returned the 422 detail "knowledge_scope assistant configuration
could not be resolved" even when no knowledge scope was involved. The 422 now
reports `Agent '<name>' not found`, an invalid `agent_name`, or an agent
config that could not be loaded. ([#8087])
- **agents:** `PUT /api/agents/{name}` with `"description": null` now resets the
description to empty. It used to store the null, which the agent config
rejects, so the agent then failed every load: the update, GET and repair
updates returned 500, the file backend dropped it from the agent list, the
database backend failed the owner's whole list, and chats with it failed.
Agents already stored with a null description load again. ([#7638])
- **sandbox:** Cancelled native Runs now stop their owned AIO and POSIX local
bash processes, including ordinary `nohup` children, before releasing the
execution lease. Concurrent work and background services from successful
earlier turns remain running. ([#7772])
- **agents:** A clarification no longer overwrites an earlier question when the
provider reuses a tool-call ID across turns (for example `call_0` on every
response). Its message ID, which is also the human-input `request_id`, named
only the call ID, so the later question replaced the earlier one in place and
the later call was left without a result. The ID now also names the
AIMessage that issued the call; a retry of the same call keeps its ID.
([#7762])
- **projects:** The trash retention sweep no longer deletes live document
originals when the data directory, `users/`, a user's directory or a
user's `projects/` is a symlink. It protected each document by its resolved
path but walked the unresolved tree, so no document matched and every
original older than 24 hours was removed as an orphan, at Gateway startup
and from `GET /api/trash/documents`. ([#7732])
- **chat:** Cancelling a queued input after dispatch starts no longer
prevents subsequent queued inputs from executing. ([#7746])
- **dev:** `scripts/dev_multi_instance.sh logs all` now prints the nginx logs
as well as both Gateway logs; it printed only the Gateway logs, the same as
`logs` with no argument. `logs nginx` and `logs all` also include `nginx.log`,
the nginx start command's own output, which no option printed before.
([#7723])
- **memory:** `GET /api/memory/config` and `/api/memory/status` now mask
credential values in `backend_config` (`api_key`, tokens, passwords,
`Authorization` headers, at any depth) as `***`. They returned the config as
loaded, with `$VAR` references already resolved, so a DeerMem extraction
model key or a Honcho `api_key` reached every caller with `memory:read` in
plaintext, which with authorization disabled (the default) is every
signed-in user. Non-secret knobs, `api_key_env` names and unset values are
unchanged. ([#7665])
- **gateway:** `GET /threads/{thread_id}/token-usage` now resolves the live
config in a worker thread. `build_context_usage` called the accessor inline,
and `get_app_config()` revalidates on every call — it digests the whole
`config.yaml`, then `extensions_config.json` — so a config edit landing just
before a thread view stalled the Gateway event loop that runs, streams and
every other thread share. The response is unchanged. ([#7727])
- **community:** The shared SSRF guard now returns its documented `Error: ...`
rejection for malformed URLs instead of raising `ValueError`.
`validate_public_http_url` and `validate_delegated_backend_url` called
`urlparse()` unguarded, so an authority it rejects, such as the unmatched
IPv6 bracket in `http://[::1/api`, escaped to the caller. That surfaced as an
unhandled 500 from the personal MCP router and as generic exception text in
the crawl4ai and fastCRW `web_fetch` tools. Both validators now reject any
malformed authority before the scheme check and the private-address escape
hatches, including a raw bracket in userinfo, which RFC 3986 forbids and
Python versions disagree on. This is a fail-closed contract fix plus
version-drift hardening: no host reachable through a well-formed URL becomes
blocked. ([#8079])
## [2.2.0] — 2026-10-29 ## [2.2.0] — 2026-10-29
This section accumulates work toward the **2.2.0** milestone This section accumulates work toward the **2.2.0** milestone
@ -14351,7 +13838,8 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
- **ci:** Consolidate PR/issue labeling and fix the reviewing-job crash and - **ci:** Consolidate PR/issue labeling and fix the reviewing-job crash and
label thrash. ([#3455]) label thrash. ([#3455])
[Unreleased]: https://github.com/bytedance/deer-flow/compare/v2.1.0...HEAD [Unreleased]: https://github.com/bytedance/deer-flow/compare/v2.2.0...HEAD
[2.2.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.2.0
[2.1.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.1.0 [2.1.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.1.0
[2.0.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.0.0 [2.0.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.0.0
@ -14611,8 +14099,8 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#3810]: https://github.com/bytedance/deer-flow/pull/3810 [#3810]: https://github.com/bytedance/deer-flow/pull/3810
[#3812]: https://github.com/bytedance/deer-flow/pull/3812 [#3812]: https://github.com/bytedance/deer-flow/pull/3812
[#3821]: https://github.com/bytedance/deer-flow/pull/3821 [#3821]: https://github.com/bytedance/deer-flow/pull/3821
[#3823]: https://github.com/bytedance/deer-flow/commit/a0d9744d5af14c520efdb45a2988691d59ef246e [#3823]: https://github.com/bytedance/deer-flow/pull/3823
[#3824]: https://github.com/bytedance/deer-flow/commit/904cee4a7248dcd3e57de9b56677bb1386e0fcbb [#3824]: https://github.com/bytedance/deer-flow/pull/3824
[#3826]: https://github.com/bytedance/deer-flow/pull/3826 [#3826]: https://github.com/bytedance/deer-flow/pull/3826
[#3828]: https://github.com/bytedance/deer-flow/pull/3828 [#3828]: https://github.com/bytedance/deer-flow/pull/3828
[#3833]: https://github.com/bytedance/deer-flow/pull/3833 [#3833]: https://github.com/bytedance/deer-flow/pull/3833
@ -15035,11 +14523,11 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#4817]: https://github.com/bytedance/deer-flow/pull/4817 [#4817]: https://github.com/bytedance/deer-flow/pull/4817
[#4820]: https://github.com/bytedance/deer-flow/pull/4820 [#4820]: https://github.com/bytedance/deer-flow/pull/4820
[#4822]: https://github.com/bytedance/deer-flow/pull/4822 [#4822]: https://github.com/bytedance/deer-flow/pull/4822
[#4823]: https://github.com/bytedance/deer-flow/commit/3a967d4f9abee1272c1b3f142310120367c38fb3 [#4823]: https://github.com/bytedance/deer-flow/pull/4823
[#4825]: https://github.com/bytedance/deer-flow/commit/9668b35b1a66e22358b2447e3de256d9138ad5ad [#4825]: https://github.com/bytedance/deer-flow/pull/4825
[#4826]: https://github.com/bytedance/deer-flow/pull/4826 [#4826]: https://github.com/bytedance/deer-flow/pull/4826
[#4827]: https://github.com/bytedance/deer-flow/pull/4827 [#4827]: https://github.com/bytedance/deer-flow/pull/4827
[#4830]: https://github.com/bytedance/deer-flow/commit/adf6c422c2aa2aa023d6534369999981594f12e3 [#4830]: https://github.com/bytedance/deer-flow/pull/4830
[#4833]: https://github.com/bytedance/deer-flow/pull/4833 [#4833]: https://github.com/bytedance/deer-flow/pull/4833
[#4834]: https://github.com/bytedance/deer-flow/pull/4834 [#4834]: https://github.com/bytedance/deer-flow/pull/4834
[#4836]: https://github.com/bytedance/deer-flow/pull/4836 [#4836]: https://github.com/bytedance/deer-flow/pull/4836
@ -15074,7 +14562,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#4918]: https://github.com/bytedance/deer-flow/pull/4918 [#4918]: https://github.com/bytedance/deer-flow/pull/4918
[#4919]: https://github.com/bytedance/deer-flow/pull/4919 [#4919]: https://github.com/bytedance/deer-flow/pull/4919
[#4921]: https://github.com/bytedance/deer-flow/pull/4921 [#4921]: https://github.com/bytedance/deer-flow/pull/4921
[#4928]: https://github.com/bytedance/deer-flow/commit/f1f4af99bbf1cffb83a80744bf6e4a44ee8f24be [#4928]: https://github.com/bytedance/deer-flow/pull/4928
[#4929]: https://github.com/bytedance/deer-flow/pull/4929 [#4929]: https://github.com/bytedance/deer-flow/pull/4929
[#4933]: https://github.com/bytedance/deer-flow/pull/4933 [#4933]: https://github.com/bytedance/deer-flow/pull/4933
[#4936]: https://github.com/bytedance/deer-flow/pull/4936 [#4936]: https://github.com/bytedance/deer-flow/pull/4936
@ -15124,7 +14612,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5039]: https://github.com/bytedance/deer-flow/pull/5039 [#5039]: https://github.com/bytedance/deer-flow/pull/5039
[#5041]: https://github.com/bytedance/deer-flow/pull/5041 [#5041]: https://github.com/bytedance/deer-flow/pull/5041
[#5045]: https://github.com/bytedance/deer-flow/pull/5045 [#5045]: https://github.com/bytedance/deer-flow/pull/5045
[#5047]: https://github.com/bytedance/deer-flow/commit/c6f6a01f56b04b6c99d73df82ed6053beb8c1a10 [#5047]: https://github.com/bytedance/deer-flow/pull/5047
[#5049]: https://github.com/bytedance/deer-flow/pull/5049 [#5049]: https://github.com/bytedance/deer-flow/pull/5049
[#5050]: https://github.com/bytedance/deer-flow/pull/5050 [#5050]: https://github.com/bytedance/deer-flow/pull/5050
[#5051]: https://github.com/bytedance/deer-flow/pull/5051 [#5051]: https://github.com/bytedance/deer-flow/pull/5051
@ -15193,7 +14681,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5217]: https://github.com/bytedance/deer-flow/pull/5217 [#5217]: https://github.com/bytedance/deer-flow/pull/5217
[#5219]: https://github.com/bytedance/deer-flow/pull/5219 [#5219]: https://github.com/bytedance/deer-flow/pull/5219
[#5221]: https://github.com/bytedance/deer-flow/pull/5221 [#5221]: https://github.com/bytedance/deer-flow/pull/5221
[#5224]: https://github.com/bytedance/deer-flow/commit/572744975d369fda88168aaa7b481282f939affe [#5224]: https://github.com/bytedance/deer-flow/pull/5224
[#5225]: https://github.com/bytedance/deer-flow/pull/5225 [#5225]: https://github.com/bytedance/deer-flow/pull/5225
[#5227]: https://github.com/bytedance/deer-flow/pull/5227 [#5227]: https://github.com/bytedance/deer-flow/pull/5227
[#5228]: https://github.com/bytedance/deer-flow/pull/5228 [#5228]: https://github.com/bytedance/deer-flow/pull/5228
@ -15202,9 +14690,9 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5236]: https://github.com/bytedance/deer-flow/pull/5236 [#5236]: https://github.com/bytedance/deer-flow/pull/5236
[#5238]: https://github.com/bytedance/deer-flow/pull/5238 [#5238]: https://github.com/bytedance/deer-flow/pull/5238
[#5239]: https://github.com/bytedance/deer-flow/pull/5239 [#5239]: https://github.com/bytedance/deer-flow/pull/5239
[#5244]: https://github.com/bytedance/deer-flow/commit/9ce6fdcb2252ea005b4fa98ca50bd3857e1f681a [#5244]: https://github.com/bytedance/deer-flow/pull/5244
[#5245]: https://github.com/bytedance/deer-flow/pull/5245 [#5245]: https://github.com/bytedance/deer-flow/pull/5245
[#5247]: https://github.com/bytedance/deer-flow/commit/fa89a125267be4213009376ec0e232a0c2411ca8 [#5247]: https://github.com/bytedance/deer-flow/pull/5247
[#5249]: https://github.com/bytedance/deer-flow/pull/5249 [#5249]: https://github.com/bytedance/deer-flow/pull/5249
[#5251]: https://github.com/bytedance/deer-flow/pull/5251 [#5251]: https://github.com/bytedance/deer-flow/pull/5251
[#5254]: https://github.com/bytedance/deer-flow/pull/5254 [#5254]: https://github.com/bytedance/deer-flow/pull/5254
@ -15261,7 +14749,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5367]: https://github.com/bytedance/deer-flow/pull/5367 [#5367]: https://github.com/bytedance/deer-flow/pull/5367
[#5369]: https://github.com/bytedance/deer-flow/pull/5369 [#5369]: https://github.com/bytedance/deer-flow/pull/5369
[#5371]: https://github.com/bytedance/deer-flow/pull/5371 [#5371]: https://github.com/bytedance/deer-flow/pull/5371
[#5373]: https://github.com/bytedance/deer-flow/commit/d5ae3882b6708fa9af7289a0c3c0be3eee157203 [#5373]: https://github.com/bytedance/deer-flow/pull/5373
[#5374]: https://github.com/bytedance/deer-flow/pull/5374 [#5374]: https://github.com/bytedance/deer-flow/pull/5374
[#5375]: https://github.com/bytedance/deer-flow/pull/5375 [#5375]: https://github.com/bytedance/deer-flow/pull/5375
[#5377]: https://github.com/bytedance/deer-flow/pull/5377 [#5377]: https://github.com/bytedance/deer-flow/pull/5377
@ -15288,7 +14776,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5408]: https://github.com/bytedance/deer-flow/pull/5408 [#5408]: https://github.com/bytedance/deer-flow/pull/5408
[#5410]: https://github.com/bytedance/deer-flow/pull/5410 [#5410]: https://github.com/bytedance/deer-flow/pull/5410
[#5411]: https://github.com/bytedance/deer-flow/pull/5411 [#5411]: https://github.com/bytedance/deer-flow/pull/5411
[#5413]: https://github.com/bytedance/deer-flow/commit/daf32cd24632f2cc7465aeb62f2a1e1e768eceb2 [#5413]: https://github.com/bytedance/deer-flow/pull/5413
[#5415]: https://github.com/bytedance/deer-flow/pull/5415 [#5415]: https://github.com/bytedance/deer-flow/pull/5415
[#5416]: https://github.com/bytedance/deer-flow/pull/5416 [#5416]: https://github.com/bytedance/deer-flow/pull/5416
[#5418]: https://github.com/bytedance/deer-flow/pull/5418 [#5418]: https://github.com/bytedance/deer-flow/pull/5418
@ -15471,8 +14959,8 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5736]: https://github.com/bytedance/deer-flow/pull/5736 [#5736]: https://github.com/bytedance/deer-flow/pull/5736
[#5738]: https://github.com/bytedance/deer-flow/pull/5738 [#5738]: https://github.com/bytedance/deer-flow/pull/5738
[#5739]: https://github.com/bytedance/deer-flow/pull/5739 [#5739]: https://github.com/bytedance/deer-flow/pull/5739
[#5740]: https://github.com/bytedance/deer-flow/commit/e7128dc7d6b4d49153b10f7276f010384ec4e6af [#5740]: https://github.com/bytedance/deer-flow/pull/5740
[#5741]: https://github.com/bytedance/deer-flow/commit/363b0fc1b4a5bd6c142d1f1df9fb9743cca550a3 [#5741]: https://github.com/bytedance/deer-flow/pull/5741
[#5745]: https://github.com/bytedance/deer-flow/pull/5745 [#5745]: https://github.com/bytedance/deer-flow/pull/5745
[#5748]: https://github.com/bytedance/deer-flow/pull/5748 [#5748]: https://github.com/bytedance/deer-flow/pull/5748
[#5750]: https://github.com/bytedance/deer-flow/pull/5750 [#5750]: https://github.com/bytedance/deer-flow/pull/5750
@ -15485,7 +14973,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5760]: https://github.com/bytedance/deer-flow/pull/5760 [#5760]: https://github.com/bytedance/deer-flow/pull/5760
[#5761]: https://github.com/bytedance/deer-flow/pull/5761 [#5761]: https://github.com/bytedance/deer-flow/pull/5761
[#5762]: https://github.com/bytedance/deer-flow/pull/5762 [#5762]: https://github.com/bytedance/deer-flow/pull/5762
[#5763]: https://github.com/bytedance/deer-flow/commit/39351315bf5d096fc84ad8307d3702b6aa5b3e24 [#5763]: https://github.com/bytedance/deer-flow/pull/5763
[#5767]: https://github.com/bytedance/deer-flow/pull/5767 [#5767]: https://github.com/bytedance/deer-flow/pull/5767
[#5769]: https://github.com/bytedance/deer-flow/pull/5769 [#5769]: https://github.com/bytedance/deer-flow/pull/5769
[#5775]: https://github.com/bytedance/deer-flow/pull/5775 [#5775]: https://github.com/bytedance/deer-flow/pull/5775
@ -15553,7 +15041,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5880]: https://github.com/bytedance/deer-flow/pull/5880 [#5880]: https://github.com/bytedance/deer-flow/pull/5880
[#5881]: https://github.com/bytedance/deer-flow/pull/5881 [#5881]: https://github.com/bytedance/deer-flow/pull/5881
[#5883]: https://github.com/bytedance/deer-flow/pull/5883 [#5883]: https://github.com/bytedance/deer-flow/pull/5883
[#5884]: https://github.com/bytedance/deer-flow/commit/e8cb5e9c4f5f274401eeb555aff62e713035cbf4 [#5884]: https://github.com/bytedance/deer-flow/pull/5884
[#5888]: https://github.com/bytedance/deer-flow/pull/5888 [#5888]: https://github.com/bytedance/deer-flow/pull/5888
[#5890]: https://github.com/bytedance/deer-flow/pull/5890 [#5890]: https://github.com/bytedance/deer-flow/pull/5890
[#5892]: https://github.com/bytedance/deer-flow/pull/5892 [#5892]: https://github.com/bytedance/deer-flow/pull/5892
@ -15615,9 +15103,9 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#5999]: https://github.com/bytedance/deer-flow/pull/5999 [#5999]: https://github.com/bytedance/deer-flow/pull/5999
[#6000]: https://github.com/bytedance/deer-flow/pull/6000 [#6000]: https://github.com/bytedance/deer-flow/pull/6000
[#6008]: https://github.com/bytedance/deer-flow/pull/6008 [#6008]: https://github.com/bytedance/deer-flow/pull/6008
[#6009]: https://github.com/bytedance/deer-flow/commit/b87ebd940227465d611084e5bf49582aaeb4e9bd [#6009]: https://github.com/bytedance/deer-flow/pull/6009
[#6013]: https://github.com/bytedance/deer-flow/pull/6013 [#6013]: https://github.com/bytedance/deer-flow/pull/6013
[#6015]: https://github.com/bytedance/deer-flow/commit/f87a04e581829ff35afd4fa228240071b486192f [#6015]: https://github.com/bytedance/deer-flow/pull/6015
[#6017]: https://github.com/bytedance/deer-flow/pull/6017 [#6017]: https://github.com/bytedance/deer-flow/pull/6017
[#6018]: https://github.com/bytedance/deer-flow/pull/6018 [#6018]: https://github.com/bytedance/deer-flow/pull/6018
[#6020]: https://github.com/bytedance/deer-flow/pull/6020 [#6020]: https://github.com/bytedance/deer-flow/pull/6020
@ -15641,7 +15129,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#6060]: https://github.com/bytedance/deer-flow/pull/6060 [#6060]: https://github.com/bytedance/deer-flow/pull/6060
[#6062]: https://github.com/bytedance/deer-flow/pull/6062 [#6062]: https://github.com/bytedance/deer-flow/pull/6062
[#6063]: https://github.com/bytedance/deer-flow/pull/6063 [#6063]: https://github.com/bytedance/deer-flow/pull/6063
[#6066]: https://github.com/bytedance/deer-flow/commit/73fdbcfdf4b5f4037b62bc2ce9d8b60ec04e69f8 [#6066]: https://github.com/bytedance/deer-flow/pull/6066
[#6067]: https://github.com/bytedance/deer-flow/pull/6067 [#6067]: https://github.com/bytedance/deer-flow/pull/6067
[#6068]: https://github.com/bytedance/deer-flow/pull/6068 [#6068]: https://github.com/bytedance/deer-flow/pull/6068
[#6069]: https://github.com/bytedance/deer-flow/pull/6069 [#6069]: https://github.com/bytedance/deer-flow/pull/6069
@ -15667,7 +15155,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#6105]: https://github.com/bytedance/deer-flow/pull/6105 [#6105]: https://github.com/bytedance/deer-flow/pull/6105
[#6107]: https://github.com/bytedance/deer-flow/pull/6107 [#6107]: https://github.com/bytedance/deer-flow/pull/6107
[#6109]: https://github.com/bytedance/deer-flow/pull/6109 [#6109]: https://github.com/bytedance/deer-flow/pull/6109
[#6112]: https://github.com/bytedance/deer-flow/commit/52b21d13ac6e674a19cb76013d097e73f108c994 [#6112]: https://github.com/bytedance/deer-flow/pull/6112
[#6113]: https://github.com/bytedance/deer-flow/pull/6113 [#6113]: https://github.com/bytedance/deer-flow/pull/6113
[#6115]: https://github.com/bytedance/deer-flow/pull/6115 [#6115]: https://github.com/bytedance/deer-flow/pull/6115
[#6117]: https://github.com/bytedance/deer-flow/pull/6117 [#6117]: https://github.com/bytedance/deer-flow/pull/6117
@ -15768,7 +15256,7 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#6298]: https://github.com/bytedance/deer-flow/pull/6298 [#6298]: https://github.com/bytedance/deer-flow/pull/6298
[#6299]: https://github.com/bytedance/deer-flow/pull/6299 [#6299]: https://github.com/bytedance/deer-flow/pull/6299
[#6302]: https://github.com/bytedance/deer-flow/pull/6302 [#6302]: https://github.com/bytedance/deer-flow/pull/6302
[#6304]: https://github.com/bytedance/deer-flow/commit/b85e4ae74bb407e1e2396243a8a6e8f5b2420e3f [#6304]: https://github.com/bytedance/deer-flow/pull/6304
[#6305]: https://github.com/bytedance/deer-flow/pull/6305 [#6305]: https://github.com/bytedance/deer-flow/pull/6305
[#6306]: https://github.com/bytedance/deer-flow/pull/6306 [#6306]: https://github.com/bytedance/deer-flow/pull/6306
[#6307]: https://github.com/bytedance/deer-flow/pull/6307 [#6307]: https://github.com/bytedance/deer-flow/pull/6307
@ -16152,7 +15640,6 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#7017]: https://github.com/bytedance/deer-flow/pull/7017 [#7017]: https://github.com/bytedance/deer-flow/pull/7017
[#7018]: https://github.com/bytedance/deer-flow/pull/7018 [#7018]: https://github.com/bytedance/deer-flow/pull/7018
[#7020]: https://github.com/bytedance/deer-flow/pull/7020 [#7020]: https://github.com/bytedance/deer-flow/pull/7020
[#7022]: https://github.com/bytedance/deer-flow/issues/7022
[#7023]: https://github.com/bytedance/deer-flow/pull/7023 [#7023]: https://github.com/bytedance/deer-flow/pull/7023
[#7024]: https://github.com/bytedance/deer-flow/pull/7024 [#7024]: https://github.com/bytedance/deer-flow/pull/7024
[#7031]: https://github.com/bytedance/deer-flow/pull/7031 [#7031]: https://github.com/bytedance/deer-flow/pull/7031
@ -16425,48 +15912,3 @@ with **180 merged pull requests** since the first 2.0 milestone tag.
[#7643]: https://github.com/bytedance/deer-flow/pull/7643 [#7643]: https://github.com/bytedance/deer-flow/pull/7643
[#7651]: https://github.com/bytedance/deer-flow/pull/7651 [#7651]: https://github.com/bytedance/deer-flow/pull/7651
[#7659]: https://github.com/bytedance/deer-flow/pull/7659 [#7659]: https://github.com/bytedance/deer-flow/pull/7659
[#7638]: https://github.com/bytedance/deer-flow/pull/7638
[#7665]: https://github.com/bytedance/deer-flow/pull/7665
[#7723]: https://github.com/bytedance/deer-flow/pull/7723
[#7727]: https://github.com/bytedance/deer-flow/pull/7727
[#7729]: https://github.com/bytedance/deer-flow/pull/7729
[#7732]: https://github.com/bytedance/deer-flow/pull/7732
[#7746]: https://github.com/bytedance/deer-flow/pull/7746
[#7762]: https://github.com/bytedance/deer-flow/pull/7762
[#7772]: https://github.com/bytedance/deer-flow/pull/7772
[#7781]: https://github.com/bytedance/deer-flow/pull/7781
[#7782]: https://github.com/bytedance/deer-flow/pull/7782
[#7792]: https://github.com/bytedance/deer-flow/pull/7792
[#7794]: https://github.com/bytedance/deer-flow/pull/7794
[#7798]: https://github.com/bytedance/deer-flow/pull/7798
[#7831]: https://github.com/bytedance/deer-flow/pull/7831
[#7892]: https://github.com/bytedance/deer-flow/pull/7892
[#7907]: https://github.com/bytedance/deer-flow/pull/7907
[#7941]: https://github.com/bytedance/deer-flow/pull/7941
[#7945]: https://github.com/bytedance/deer-flow/issues/7945
[#7953]: https://github.com/bytedance/deer-flow/issues/7953
[#7958]: https://github.com/bytedance/deer-flow/pull/7958
[#7981]: https://github.com/bytedance/deer-flow/pull/7981
[#7992]: https://github.com/bytedance/deer-flow/pull/7992
[#7993]: https://github.com/bytedance/deer-flow/pull/7993
[#7998]: https://github.com/bytedance/deer-flow/issues/7998
[#8006]: https://github.com/bytedance/deer-flow/pull/8006
[#8019]: https://github.com/bytedance/deer-flow/pull/8019
[#8020]: https://github.com/bytedance/deer-flow/pull/8020
[#8043]: https://github.com/bytedance/deer-flow/pull/8043
[#8046]: https://github.com/bytedance/deer-flow/pull/8046
[#8057]: https://github.com/bytedance/deer-flow/pull/8057
[#8064]: https://github.com/bytedance/deer-flow/pull/8064
[#8069]: https://github.com/bytedance/deer-flow/issues/8069
[#8071]: https://github.com/bytedance/deer-flow/issues/8071
[#8072]: https://github.com/bytedance/deer-flow/pull/8072
[#8079]: https://github.com/bytedance/deer-flow/pull/8079
[#8087]: https://github.com/bytedance/deer-flow/pull/8087
[#8117]: https://github.com/bytedance/deer-flow/pull/8117
[#8118]: https://github.com/bytedance/deer-flow/pull/8118
[#8126]: https://github.com/bytedance/deer-flow/pull/8126
[#8131]: https://github.com/bytedance/deer-flow/pull/8131
[#8139]: https://github.com/bytedance/deer-flow/pull/8139
[#8151]: https://github.com/bytedance/deer-flow/pull/8151
[#8174]: https://github.com/bytedance/deer-flow/pull/8174
[#8250]: https://github.com/bytedance/deer-flow/pull/8250

View File

@ -9,209 +9,6 @@
## [未发布] ## [未发布]
本节累积面向 **2.3.0** 里程碑([2.3.0](https://github.com/bytedance/deer-flow/milestone/4))的工作。
### 新增
- **子智能体:** 后台批次可声明条目前置关系,并可登记一次主 Agent 接续,在批次结束后完成
用户已要求的汇总或交付。接续保留持久化启动记录、取消和授权检查;启用 Goal 时仍由 Goal 负责续跑。([#7839](https://github.com/bytedance/deer-flow/pull/7839))
- **对话:** 网页端在任务运行时,可在输入框选择 Queue(排队执行)或 Steer(调整当前任务)。
Queue 等当前任务结束后再执行下一条消息;Steer 让主 Agent 先处理新要求,原生子 Agent 可暂停后恢复。
Gateway 重启后,尚未确认生效的消息可以手动重试。([#7729])
- **模型:** 管理员可在 **设置 → 模型** 中选择 StepFun(阶跃星辰),
填写 API Key 和模型 ID 即可接入普通 API。([#7988](https://github.com/bytedance/deer-flow/pull/7988))
### 变更
- **Checkpoint:** DeltaChannel 部署现在要求 `langgraph-checkpoint` 4.3.0、
SQLite saver 3.1.2 和 Postgres saver 3.1.3,排除会在重放时重排并行写入或
丢失分页祖先历史的版本。顺序和 Postgres 分页契约在回归时现在会直接失败,
不再跳过。([#8139])
### 修复
- **调度器:** 定时任务发往 IM 的通知不再把不带密钥词形态的凭证原样发出。URL 中的账号信息
(`postgres://admin:hunter2@host`)以及 `Authorization`、`Cookie` 请求头的值
(`Authorization: Bearer ...`)此前会完整进入消息;现在替换为 `[redacted]`,协议名和句子
其余部分保持可读,不含凭证的 URL 不受影响。`Cookie` 请求头和 `Digest` 凭据会替换到行尾,
同一行后面紧跟的文字也会一并去掉。([#8250])
- **前端:** 任务表单的 Cron 预设现在要求分钟 0-59、小时 0-23、日期 1-31,
超出范围的表达式(例如 `0 24 * * *`)会保持为自定义并保留原始文本。此前它会被识别为预设,
在序列化以供提交时可能被限制到合法范围内的另一个时间。使用非法表达式创建或复制任务,
或在表达式仍非法时更新调度配置,会由 Gateway 返回 `422`;仅修改其他字段不会重新校验
未变化的调度配置。([#8020])
- **网关:** 创建对话时在元数据中带上 `step`、`parents`、`counters_since_delta_snapshot`
等由检查点自身维护的键,不再让该对话损坏。此前这些键会写入对话的首个检查点,错误的 `parents`
会让该对话的历史记录永久返回 500,错误的 `step` 或增量计数器会让之后每一轮对话都失败;
`deerflow_agent_name` 还会被当作服务端写入的值复制到下一次状态更新中。现在首个检查点不再从
请求中接收这些键。([#8019])
- **通道:** 企业微信不再丢弃 2–10 MB 的图片。此前适配器把图片上限定为 2 MB(同一协议中语音的限制),
超出即在上传前被跳过,消息到达时缺少图片。现在图片上限与平台的 10 MB 对齐;普通文件 20 MB 的限制不变。([#8174])
- **通道:** WeCom 群聊中 `@机器人 /new` 这类带提及的命令现在按命令执行。WeCom 会把提及保留在
正文里,而命令识别要求裸的前导 `/`,于是群里的 `/new`、`/status` 被当成聊天轮次。现在仅在命令
识别时跳过前导提及;普通聊天保留提及,`/connect` 行为不变。与飞书、钉钉的处理一致。([#8118])
- **前端:** 侧边栏对话菜单中的 **分享** 现在复制指向当前部署的链接。此前在 `localhost` 和
`127.0.0.1`(`make dev` 与 Docker 的默认地址)上,复制的是托管演示站
(`deer-flow-v2.vercel.app`)的链接:该链接无法打开对话,打开时还会把线程 ID 发送到外部主机。
([#8126])
- **运行时:** 多 Worker 模式(`run_ownership.heartbeat_enabled`)下,已被其他 Worker
接管的运行不再被原 Worker 恢复。此前装配证据通过无条件的整行 upsert 写入,在对端接管后会把
行改回 `running` 并清除接管错误;运行可能在对端已报告失败后以 `success` 结束,或被再次接管。
现在仅当该 Worker 仍持有活跃运行的有效租约时,才将证据合并到行元数据
(`RunStore.merge_owned_metadata()`),否则在执行前停止该运行。启用心跳的自定义
`RunStore` 实现必须实现该方法。([#8046])
- **网关:** 同一用户对同一次运行重复提交反馈时,现在返回 409 而不是 500。
`POST /api/threads/{id}/runs/{run_id}/feedback` 每个用户每次运行只允许一条反馈;此前重试,
或对同一次运行的另一条消息提交反馈,会触发该唯一约束,Gateway 因未处理的数据库错误而失败。
409 会提示调用方改用同一路由的 `PUT` 更新已有反馈。([#8064])
- **网关:** 删除线程时不再在对话仍可读取的情况下返回成功。此前
`DELETE /api/threads/{id}` 在检查点存储失败时只记录 DEBUG 日志,仍删除线程元数据行并
返回成功;之后任何已登录用户都能通过 `GET /threads/{id}`、`/state`、`/history` 和
`/goal` 读取残留的标题和消息,所有者也无法重试。现在删除会返回 500 并保留线程,所有者
可以再次删除。([#7992])
- **模型:** 取消使用 Codex 的任务时,会关闭上游 HTTP/SSE 连接,包括等待响应头期间;
重试等待也可取消。本地资源会释放,远端服务仍可能继续生成。([#8053](https://github.com/bytedance/deer-flow/pull/8053))
- **中间件:** 启用 PII 脱敏时,不含空格的长文本(例如粘贴的十六进制转储)不再让 Gateway
卡住。此前邮箱检测器的耗时与这类文本长度呈平方关系,而脱敏会在每次模型调用时重新扫描全部
用户消息,因此一次 100 KB 的粘贴会让每次模型调用阻塞所有线程约 6 秒。现在扫描为线性耗时,
且脱敏的地址与此前完全相同。([#8006])
- **调度器:** 队列超时扫描或队列排空中的单条记录出现异常时,调度器会记录该失败并继续处理剩余队列,以及同一轮启动的到期任务。过期记录会在所有者排名和批次限额之前被排除,启动领取还会再次检查同一截止时间,因此超时清理失败时遗留的排队记录既不会启动,也不会挤占正常排队工作的候选位置,只会继续等待超时恢复流程处理。([#7998])
- **调度器:** 一个已保存的计划无法再计算的定时任务,不再让其他所有任务停止运行。此前
已保存的时区或 cron 表达式失效时(例如升级后时区数据库中缺少该时区,或新版 croniter
不再接受该表达式),在调度器轮询中计算其下一次运行时间会抛出异常;其启动租约过期后,
之后每次轮询都会在接纳到期任务之前失败。现在该任务会被暂停,并把原因记录为最近错误;
在修复计划之前,恢复该任务会提示具体问题。([#7993])
- **模型:** 使用 Claude Code OAuth token 的 Claude 模型,不再在请求带有 `betas` 时每次
都失败。此前 OAuth 所需的 beta(`oauth-2025-04-20` 等)只放在客户端默认的
`anthropic-beta` 请求头里,而 SDK 会用请求自身的 `betas` 替换这个请求头;因此只要配置了
`betas`(即使是 `[]`)、调用时传入 `betas`,或使用了 langchain-anthropic 会为其追加 beta
的服务端工具,OAuth beta 就会丢失,Anthropic 随即拒绝该 token。现在 OAuth beta 会排在
请求 `betas` 以及 `extra_headers` 中 `anthropic-beta` 的最前面。
([#8061](https://github.com/bytedance/deer-flow/pull/8061))
- **社区工具:** 以换行结尾的搜索或抓取 API 密钥不再泄露到对话中。GroundRoute
(`GROUNDROUTE_API_KEY`)、InfoQuest、Tavily、Exa、Jina、Firecrawl、fastCRW 和
Crawl4AI 此前把读取到的密钥原样写入 HTTP 请求头;从文件读取的密钥(例如用
`--from-file` 创建的 Kubernetes Secret)会让传输层报出 `Illegal header value
b'Bearer <key>\n'`,这条包含完整密钥的消息成为模型和对话历史保存的工具结果,
其中四个提供方还会把它写入日志。现在这些密钥与其他提供方一样经过
`provider_credentials.resolve_api_key` 处理;Tavily、Exa、Firecrawl 和 fastCRW
的配置密钥为空时会回退到环境变量。fastCRW 没有自己的密钥时,不再让 Firecrawl SDK
把 `FIRECRAWL_API_KEY` 发送到 fastCRW 端点;`TAVILY_API_KEY`、`EXA_API_KEY` 或
`FIRECRAWL_API_KEY` 只含空白时按未设置处理,不再原样交给 SDK。([#7981])
- **社区工具:** Browserless 是最后一个直接读取原始 token 的搜索/抓取提供方。从文件读取的
`BROWSERLESS_TOKEN` 或配置 `token` 会保留尾部换行,并被原样用作鉴权查询参数,导致
`web_fetch` 和 `web_capture` 在密钥本身正确时也全部鉴权失败。现在两者都经过
`provider_credentials.resolve_api_key` 处理,且只有省略 `token` 键时才回退到环境变量:
显式配置 `""` 或 `null` 仍可让自建 capture 端点跳过鉴权。([#8043])
- **docker:** 从本地 checkout 构建的镜像不再包含本地配置。`.dockerignore`
此前没有排除 `config.yaml`、`config.yaml.bak`、`extensions_config.json` 和
`mcp_config.json`,因此配置放在旧位置 `backend/` 时,`COPY backend ./backend`
会把模型 API 密钥和 MCP 凭据写进每一层 gateway 镜像;`frontend/.env.local`
也以同样方式进入前端镜像。现在根目录和 `backend/` 下的这些文件、任意层级的
`.env*.local`、`frontend/*.pem`,以及扩展管理器拒绝写入扩展快照的凭据文件都会
被排除。本地构建的前端镜像不再内联 `frontend/.env.local` 中的 `NEXT_PUBLIC_*`
值;Docker 栈通过同一个 nginx 源提供前端和 Gateway,不需要这些变量。CI 发布的
镜像不受影响;已推送或分享过的本地镜像请重新构建。([#7958])
- **智能体:** 循环检测、运行 token 预算、模型服务安全限制或输出长度限制触发停止后,
未完成的 Todo 不再触发额外的模型调用或工具执行。Todo 状态仍会保留,
用户可在后续运行中继续处理。([#7953])
- **渠道:** 飞书/Lark 的长回答不再丢失。此前卡片文本没有长度上限,并以 ASCII 转义
序列化,约 4,400 个中日韩字符就会让卡片请求超过飞书 30 KB 的限制(`230025`):
最终更新及其回复兜底都会被拒绝,运行中卡片停留在最后一次流式内容或只剩 `▉`。
现在卡片不再转义中日韩字符,并按其在请求中占用的字节计算预算。流式更新只显示能
放下的部分;更长的最终回答会在同一条消息下以最多 10 张卡片按行续发,重试会从
已送达的卡片之后继续。([#7798])
- **渠道:** 企业微信群消息现在拥有独立的会话。此前每条消息都把发送者的 userid
同时用作会话 ID 和话题 ID,因此在没有群绑定加以区分的情况下(免认证模式、
`require_bound_identity: false`,以及旧版群绑定),成员的私聊和其发过言的所有群
共用同一个 DeerFlow 线程:群内回复可能用到该成员私聊或其他群的内容,失去原始
frame 的回复也会被发到私聊。现在群以 `chatid` 为键、每位成员一个线程,私聊线程
保持不变。通过各自 `/connect` 绑定的群保留原有线程;覆盖该机器人所有群的旧版
群绑定会在每个群中开始新线程。([#7794])
- **沙箱:** 使用显式授权技能视图的新 AIO 运行,在启用惰性初始化时,不再于首次调用
沙箱工具前创建或获取沙箱。已有沙箱绑定和需要上传技能的提供方继续保留原有的即时同步行为。
([#7782])
- **扩展:** 上下文压缩观察者现在能知道压缩发生在哪个任务里。在 Lead 运行或子 Agent
内部,观察者收到的是该任务的存储,而不再是分离存储;`CompactionEvent` 新增
`task_id`、`run_id`、`thread_id`(默认 `None`),取自宿主放进每个任务存储的
`TaskInfo`,即使没有注册生命周期贡献者也会放入。手动 `/compact` 仍收到分离存储,
id 为 `None`。`deerflow-extension-api` 升级到 0.2.10,已有扩展不受影响。([#7831])
- **智能体:** 即使模型提供方复用消息 ID,Token 预算也会分别统计已接受的模型调用,
避免重复 ID 绕过配置的上限;触发硬停止时保留已完成的结构化输出工具结果。
([#8050](https://github.com/bytedance/deer-flow/pull/8050))
- **渠道:** 钉钉 AI 卡片模式(`card_template_id`)下,卡片请求失败(例如缺少卡片权限或钉钉服务异常)时
不再丢失回复。dingtalk-stream 会记录失败的卡片请求后按成功返回,因此文本形式的运行中提示和最终答案的
`sampleMarkdown` 兜底都不会执行。现在渠道自行发送卡片请求,并在失败时回退。([#7781])
- **harness:** 重试失败条目不再重新打开已取消的持久子智能体批次。`retry_item`
此前只保留已暂停批次的状态,因此重试已取消批次中的失败条目会把批次改回
`queued`,worker 随即认领并执行该条目,批次最终变为 `completed`。现在对已取消
批次的重试路由返回 409,包括 SQLite 上取消在重试进行中提交的情况;工作区也不再
为这些条目显示重试按钮。在已完成、失败、运行中或已暂停批次中重试的行为不变。
([#7792])
- **网关:** 运行指定的自定义智能体不存在或名称无效时,现在会明确说明原因。此前向一个
自定义智能体已被删除的对话发消息,或传入格式错误的 `agent_name`,即使与知识库范围无关,
也会返回 422 和 "knowledge_scope assistant configuration could not be resolved"。现在
422 会提示 `Agent '<name>' not found`、`agent_name` 无效,或智能体配置无法加载。([#8087])
- **智能体:** `PUT /api/agents/{name}` 传入 `"description": null` 时现在会把描述重置为
空。此前会把 null 原样保存,而智能体配置不接受该值,导致之后每次加载都失败:更新本身、
GET 和修复性更新都返回 500,文件后端会把它从智能体列表中漏掉,数据库后端会让该用户的
整个列表失败,与它的对话也会失败。已以 null 描述保存的智能体现在可以重新加载。([#7638])
- **智能体:** 当模型提供方在不同轮次复用同一个工具调用 ID(例如每次响应都是 `call_0`)时,
澄清提问不再覆盖之前的问题。此前其消息 ID(同时也是人工输入的 `request_id`)只包含调用 ID,
后一个问题会原地替换前一个问题,后一次调用也因此缺少结果。现在 ID 还会包含发起该调用的
AIMessage;同一调用的重试仍保持原 ID。([#7762])
- **项目:** 当数据目录、`users/`、某个用户目录或用户的 `projects/` 是符号链接时,
回收站保留期清扫不再删除仍在使用的文档原件。此前它按解析后的路径保护每个文档,
却遍历未解析的目录树,导致没有任何文档能匹配上,所有超过 24 小时的原件都被当作
孤立文件删除,Gateway 启动时和 `GET /api/trash/documents` 都会触发。([#7732])
- **对话:** 队列分发开始后,取消某条排队输入不再阻止后续排队输入继续执行。([#7746])
- **开发:** `scripts/dev_multi_instance.sh logs all` 现在除两个 Gateway 日志外也会输出
nginx 日志;此前它只输出 Gateway 日志,与不带参数的 `logs` 相同。`logs nginx` 与
`logs all` 还会包含 `nginx.log`(nginx 启动命令自身的输出),此前没有任何选项会输出它。
([#7723])
- **记忆:** `GET /api/memory/config` 与 `/api/memory/status` 现在会把 `backend_config`
中的凭据值(`api_key`、token、密码、`Authorization` 请求头,任意层级)遮蔽为 `***`。
此前它们按加载结果原样返回配置,而 `$VAR` 引用此时已被解析,因此 DeerMem 提取模型的密钥
或 Honcho 的 `api_key` 会以明文返回给所有拥有 `memory:read` 的调用方;在默认关闭授权时,
这就是所有已登录用户。非机密配置项、`api_key_env` 变量名和未设置的值保持不变。([#7665])
- **网关:** `GET /threads/{thread_id}/token-usage` 现在在工作线程里解析实时配置。
此前 `build_context_usage` 直接内联调用该访问器,而 `get_app_config()` 每次调用都会重新校验
——它先对整个 `config.yaml` 取摘要,再对 `extensions_config.json` 做同样的事——所以在有人打开
会话视图前刚好改了配置,就会让运行、消息流与其他线程共用的网关事件循环整段停顿。响应内容不变。([#7727])
## [2.2.0] — 2026-10-29 ## [2.2.0] — 2026-10-29
本节累积面向 **2.2.0** 里程碑([2.2.0](https://github.com/bytedance/deer-flow/milestone/3))的工作。 本节累积面向 **2.2.0** 里程碑([2.2.0](https://github.com/bytedance/deer-flow/milestone/3))的工作。
@ -426,12 +223,6 @@
选择器缺失、是目录或不可读时会在调用 Docker 之前直接失败,而文件删除后 选择器缺失、是目录或不可读时会在调用 Docker 之前直接失败,而文件删除后
`make down` 仍能停止整个栈;不设置或为空的选择器保持可选的仓库根 `.env` `make down` 仍能停止整个栈;不设置或为空的选择器保持可选的仓库根 `.env`
默认值。([#6522]) 默认值。([#6522])
- **HITL:** 新增独立于推理模式的 Ask、Auto、Full 工具权限模式。Auto 通过单独的
无工具模型调用审核具体操作,默认复用现有模型配置;不确定或高风险操作转人工审批。
卡片展示完整参数,支持批准、拒绝、修改参数及可撤销的会话精确授权。主代理审批通过
checkpoint 支持重启恢复;交互式子代理通过属主限定的通道等待,并处理取消和过期。
所有模式均保留部署规则和账户权限,个人/平台 MCP 连接、参数和策略均参与授权绑定。
默认关闭;`config_version` 66。
- **MCP:** 按未变更的服务器缓存完成包装的工具,仅在绑定对账后重新发现缺失或配置 - **MCP:** 按未变更的服务器缓存完成包装的工具,仅在绑定对账后重新发现缺失或配置
发生变化的服务器。将成功但未发现工具的结果与发现失败分开保存,并保留代际、共享 发生变化的服务器。将成功但未发现工具的结果与发现失败分开保存,并保留代际、共享
@ -10818,7 +10609,8 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
- **CI:** 统一 PR / issue 打标签逻辑,修复 reviewing 任务的崩溃与标签抖动。 - **CI:** 统一 PR / issue 打标签逻辑,修复 reviewing 任务的崩溃与标签抖动。
([#3455]) ([#3455])
[未发布]: https://github.com/bytedance/deer-flow/compare/v2.1.0...HEAD [未发布]: https://github.com/bytedance/deer-flow/compare/v2.2.0...HEAD
[2.2.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.2.0
[2.1.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.1.0 [2.1.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.1.0
[2.0.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.0.0 [2.0.0]: https://github.com/bytedance/deer-flow/releases/tag/v2.0.0
@ -11078,8 +10870,8 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#3810]: https://github.com/bytedance/deer-flow/pull/3810 [#3810]: https://github.com/bytedance/deer-flow/pull/3810
[#3812]: https://github.com/bytedance/deer-flow/pull/3812 [#3812]: https://github.com/bytedance/deer-flow/pull/3812
[#3821]: https://github.com/bytedance/deer-flow/pull/3821 [#3821]: https://github.com/bytedance/deer-flow/pull/3821
[#3823]: https://github.com/bytedance/deer-flow/commit/a0d9744d5af14c520efdb45a2988691d59ef246e [#3823]: https://github.com/bytedance/deer-flow/pull/3823
[#3824]: https://github.com/bytedance/deer-flow/commit/904cee4a7248dcd3e57de9b56677bb1386e0fcbb [#3824]: https://github.com/bytedance/deer-flow/pull/3824
[#3826]: https://github.com/bytedance/deer-flow/pull/3826 [#3826]: https://github.com/bytedance/deer-flow/pull/3826
[#3828]: https://github.com/bytedance/deer-flow/pull/3828 [#3828]: https://github.com/bytedance/deer-flow/pull/3828
[#3833]: https://github.com/bytedance/deer-flow/pull/3833 [#3833]: https://github.com/bytedance/deer-flow/pull/3833
@ -11502,11 +11294,11 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#4817]: https://github.com/bytedance/deer-flow/pull/4817 [#4817]: https://github.com/bytedance/deer-flow/pull/4817
[#4820]: https://github.com/bytedance/deer-flow/pull/4820 [#4820]: https://github.com/bytedance/deer-flow/pull/4820
[#4822]: https://github.com/bytedance/deer-flow/pull/4822 [#4822]: https://github.com/bytedance/deer-flow/pull/4822
[#4823]: https://github.com/bytedance/deer-flow/commit/3a967d4f9abee1272c1b3f142310120367c38fb3 [#4823]: https://github.com/bytedance/deer-flow/pull/4823
[#4825]: https://github.com/bytedance/deer-flow/commit/9668b35b1a66e22358b2447e3de256d9138ad5ad [#4825]: https://github.com/bytedance/deer-flow/pull/4825
[#4826]: https://github.com/bytedance/deer-flow/pull/4826 [#4826]: https://github.com/bytedance/deer-flow/pull/4826
[#4827]: https://github.com/bytedance/deer-flow/pull/4827 [#4827]: https://github.com/bytedance/deer-flow/pull/4827
[#4830]: https://github.com/bytedance/deer-flow/commit/adf6c422c2aa2aa023d6534369999981594f12e3 [#4830]: https://github.com/bytedance/deer-flow/pull/4830
[#4833]: https://github.com/bytedance/deer-flow/pull/4833 [#4833]: https://github.com/bytedance/deer-flow/pull/4833
[#4834]: https://github.com/bytedance/deer-flow/pull/4834 [#4834]: https://github.com/bytedance/deer-flow/pull/4834
[#4836]: https://github.com/bytedance/deer-flow/pull/4836 [#4836]: https://github.com/bytedance/deer-flow/pull/4836
@ -11541,7 +11333,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#4918]: https://github.com/bytedance/deer-flow/pull/4918 [#4918]: https://github.com/bytedance/deer-flow/pull/4918
[#4919]: https://github.com/bytedance/deer-flow/pull/4919 [#4919]: https://github.com/bytedance/deer-flow/pull/4919
[#4921]: https://github.com/bytedance/deer-flow/pull/4921 [#4921]: https://github.com/bytedance/deer-flow/pull/4921
[#4928]: https://github.com/bytedance/deer-flow/commit/f1f4af99bbf1cffb83a80744bf6e4a44ee8f24be [#4928]: https://github.com/bytedance/deer-flow/pull/4928
[#4929]: https://github.com/bytedance/deer-flow/pull/4929 [#4929]: https://github.com/bytedance/deer-flow/pull/4929
[#4933]: https://github.com/bytedance/deer-flow/pull/4933 [#4933]: https://github.com/bytedance/deer-flow/pull/4933
[#4936]: https://github.com/bytedance/deer-flow/pull/4936 [#4936]: https://github.com/bytedance/deer-flow/pull/4936
@ -11591,7 +11383,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5039]: https://github.com/bytedance/deer-flow/pull/5039 [#5039]: https://github.com/bytedance/deer-flow/pull/5039
[#5041]: https://github.com/bytedance/deer-flow/pull/5041 [#5041]: https://github.com/bytedance/deer-flow/pull/5041
[#5045]: https://github.com/bytedance/deer-flow/pull/5045 [#5045]: https://github.com/bytedance/deer-flow/pull/5045
[#5047]: https://github.com/bytedance/deer-flow/commit/c6f6a01f56b04b6c99d73df82ed6053beb8c1a10 [#5047]: https://github.com/bytedance/deer-flow/pull/5047
[#5049]: https://github.com/bytedance/deer-flow/pull/5049 [#5049]: https://github.com/bytedance/deer-flow/pull/5049
[#5050]: https://github.com/bytedance/deer-flow/pull/5050 [#5050]: https://github.com/bytedance/deer-flow/pull/5050
[#5051]: https://github.com/bytedance/deer-flow/pull/5051 [#5051]: https://github.com/bytedance/deer-flow/pull/5051
@ -11660,7 +11452,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5217]: https://github.com/bytedance/deer-flow/pull/5217 [#5217]: https://github.com/bytedance/deer-flow/pull/5217
[#5219]: https://github.com/bytedance/deer-flow/pull/5219 [#5219]: https://github.com/bytedance/deer-flow/pull/5219
[#5221]: https://github.com/bytedance/deer-flow/pull/5221 [#5221]: https://github.com/bytedance/deer-flow/pull/5221
[#5224]: https://github.com/bytedance/deer-flow/commit/572744975d369fda88168aaa7b481282f939affe [#5224]: https://github.com/bytedance/deer-flow/pull/5224
[#5225]: https://github.com/bytedance/deer-flow/pull/5225 [#5225]: https://github.com/bytedance/deer-flow/pull/5225
[#5227]: https://github.com/bytedance/deer-flow/pull/5227 [#5227]: https://github.com/bytedance/deer-flow/pull/5227
[#5228]: https://github.com/bytedance/deer-flow/pull/5228 [#5228]: https://github.com/bytedance/deer-flow/pull/5228
@ -11669,9 +11461,9 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5236]: https://github.com/bytedance/deer-flow/pull/5236 [#5236]: https://github.com/bytedance/deer-flow/pull/5236
[#5238]: https://github.com/bytedance/deer-flow/pull/5238 [#5238]: https://github.com/bytedance/deer-flow/pull/5238
[#5239]: https://github.com/bytedance/deer-flow/pull/5239 [#5239]: https://github.com/bytedance/deer-flow/pull/5239
[#5244]: https://github.com/bytedance/deer-flow/commit/9ce6fdcb2252ea005b4fa98ca50bd3857e1f681a [#5244]: https://github.com/bytedance/deer-flow/pull/5244
[#5245]: https://github.com/bytedance/deer-flow/pull/5245 [#5245]: https://github.com/bytedance/deer-flow/pull/5245
[#5247]: https://github.com/bytedance/deer-flow/commit/fa89a125267be4213009376ec0e232a0c2411ca8 [#5247]: https://github.com/bytedance/deer-flow/pull/5247
[#5249]: https://github.com/bytedance/deer-flow/pull/5249 [#5249]: https://github.com/bytedance/deer-flow/pull/5249
[#5251]: https://github.com/bytedance/deer-flow/pull/5251 [#5251]: https://github.com/bytedance/deer-flow/pull/5251
[#5254]: https://github.com/bytedance/deer-flow/pull/5254 [#5254]: https://github.com/bytedance/deer-flow/pull/5254
@ -11728,7 +11520,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5367]: https://github.com/bytedance/deer-flow/pull/5367 [#5367]: https://github.com/bytedance/deer-flow/pull/5367
[#5369]: https://github.com/bytedance/deer-flow/pull/5369 [#5369]: https://github.com/bytedance/deer-flow/pull/5369
[#5371]: https://github.com/bytedance/deer-flow/pull/5371 [#5371]: https://github.com/bytedance/deer-flow/pull/5371
[#5373]: https://github.com/bytedance/deer-flow/commit/d5ae3882b6708fa9af7289a0c3c0be3eee157203 [#5373]: https://github.com/bytedance/deer-flow/pull/5373
[#5374]: https://github.com/bytedance/deer-flow/pull/5374 [#5374]: https://github.com/bytedance/deer-flow/pull/5374
[#5375]: https://github.com/bytedance/deer-flow/pull/5375 [#5375]: https://github.com/bytedance/deer-flow/pull/5375
[#5377]: https://github.com/bytedance/deer-flow/pull/5377 [#5377]: https://github.com/bytedance/deer-flow/pull/5377
@ -11755,7 +11547,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5408]: https://github.com/bytedance/deer-flow/pull/5408 [#5408]: https://github.com/bytedance/deer-flow/pull/5408
[#5410]: https://github.com/bytedance/deer-flow/pull/5410 [#5410]: https://github.com/bytedance/deer-flow/pull/5410
[#5411]: https://github.com/bytedance/deer-flow/pull/5411 [#5411]: https://github.com/bytedance/deer-flow/pull/5411
[#5413]: https://github.com/bytedance/deer-flow/commit/daf32cd24632f2cc7465aeb62f2a1e1e768eceb2 [#5413]: https://github.com/bytedance/deer-flow/pull/5413
[#5415]: https://github.com/bytedance/deer-flow/pull/5415 [#5415]: https://github.com/bytedance/deer-flow/pull/5415
[#5416]: https://github.com/bytedance/deer-flow/pull/5416 [#5416]: https://github.com/bytedance/deer-flow/pull/5416
[#5418]: https://github.com/bytedance/deer-flow/pull/5418 [#5418]: https://github.com/bytedance/deer-flow/pull/5418
@ -11938,8 +11730,8 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5736]: https://github.com/bytedance/deer-flow/pull/5736 [#5736]: https://github.com/bytedance/deer-flow/pull/5736
[#5738]: https://github.com/bytedance/deer-flow/pull/5738 [#5738]: https://github.com/bytedance/deer-flow/pull/5738
[#5739]: https://github.com/bytedance/deer-flow/pull/5739 [#5739]: https://github.com/bytedance/deer-flow/pull/5739
[#5740]: https://github.com/bytedance/deer-flow/commit/e7128dc7d6b4d49153b10f7276f010384ec4e6af [#5740]: https://github.com/bytedance/deer-flow/pull/5740
[#5741]: https://github.com/bytedance/deer-flow/commit/363b0fc1b4a5bd6c142d1f1df9fb9743cca550a3 [#5741]: https://github.com/bytedance/deer-flow/pull/5741
[#5745]: https://github.com/bytedance/deer-flow/pull/5745 [#5745]: https://github.com/bytedance/deer-flow/pull/5745
[#5748]: https://github.com/bytedance/deer-flow/pull/5748 [#5748]: https://github.com/bytedance/deer-flow/pull/5748
[#5750]: https://github.com/bytedance/deer-flow/pull/5750 [#5750]: https://github.com/bytedance/deer-flow/pull/5750
@ -11952,7 +11744,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5760]: https://github.com/bytedance/deer-flow/pull/5760 [#5760]: https://github.com/bytedance/deer-flow/pull/5760
[#5761]: https://github.com/bytedance/deer-flow/pull/5761 [#5761]: https://github.com/bytedance/deer-flow/pull/5761
[#5762]: https://github.com/bytedance/deer-flow/pull/5762 [#5762]: https://github.com/bytedance/deer-flow/pull/5762
[#5763]: https://github.com/bytedance/deer-flow/commit/39351315bf5d096fc84ad8307d3702b6aa5b3e24 [#5763]: https://github.com/bytedance/deer-flow/pull/5763
[#5767]: https://github.com/bytedance/deer-flow/pull/5767 [#5767]: https://github.com/bytedance/deer-flow/pull/5767
[#5769]: https://github.com/bytedance/deer-flow/pull/5769 [#5769]: https://github.com/bytedance/deer-flow/pull/5769
[#5775]: https://github.com/bytedance/deer-flow/pull/5775 [#5775]: https://github.com/bytedance/deer-flow/pull/5775
@ -12020,7 +11812,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5880]: https://github.com/bytedance/deer-flow/pull/5880 [#5880]: https://github.com/bytedance/deer-flow/pull/5880
[#5881]: https://github.com/bytedance/deer-flow/pull/5881 [#5881]: https://github.com/bytedance/deer-flow/pull/5881
[#5883]: https://github.com/bytedance/deer-flow/pull/5883 [#5883]: https://github.com/bytedance/deer-flow/pull/5883
[#5884]: https://github.com/bytedance/deer-flow/commit/e8cb5e9c4f5f274401eeb555aff62e713035cbf4 [#5884]: https://github.com/bytedance/deer-flow/pull/5884
[#5888]: https://github.com/bytedance/deer-flow/pull/5888 [#5888]: https://github.com/bytedance/deer-flow/pull/5888
[#5890]: https://github.com/bytedance/deer-flow/pull/5890 [#5890]: https://github.com/bytedance/deer-flow/pull/5890
[#5892]: https://github.com/bytedance/deer-flow/pull/5892 [#5892]: https://github.com/bytedance/deer-flow/pull/5892
@ -12082,9 +11874,9 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#5999]: https://github.com/bytedance/deer-flow/pull/5999 [#5999]: https://github.com/bytedance/deer-flow/pull/5999
[#6000]: https://github.com/bytedance/deer-flow/pull/6000 [#6000]: https://github.com/bytedance/deer-flow/pull/6000
[#6008]: https://github.com/bytedance/deer-flow/pull/6008 [#6008]: https://github.com/bytedance/deer-flow/pull/6008
[#6009]: https://github.com/bytedance/deer-flow/commit/b87ebd940227465d611084e5bf49582aaeb4e9bd [#6009]: https://github.com/bytedance/deer-flow/pull/6009
[#6013]: https://github.com/bytedance/deer-flow/pull/6013 [#6013]: https://github.com/bytedance/deer-flow/pull/6013
[#6015]: https://github.com/bytedance/deer-flow/commit/f87a04e581829ff35afd4fa228240071b486192f [#6015]: https://github.com/bytedance/deer-flow/pull/6015
[#6017]: https://github.com/bytedance/deer-flow/pull/6017 [#6017]: https://github.com/bytedance/deer-flow/pull/6017
[#6018]: https://github.com/bytedance/deer-flow/pull/6018 [#6018]: https://github.com/bytedance/deer-flow/pull/6018
[#6020]: https://github.com/bytedance/deer-flow/pull/6020 [#6020]: https://github.com/bytedance/deer-flow/pull/6020
@ -12108,7 +11900,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#6060]: https://github.com/bytedance/deer-flow/pull/6060 [#6060]: https://github.com/bytedance/deer-flow/pull/6060
[#6062]: https://github.com/bytedance/deer-flow/pull/6062 [#6062]: https://github.com/bytedance/deer-flow/pull/6062
[#6063]: https://github.com/bytedance/deer-flow/pull/6063 [#6063]: https://github.com/bytedance/deer-flow/pull/6063
[#6066]: https://github.com/bytedance/deer-flow/commit/73fdbcfdf4b5f4037b62bc2ce9d8b60ec04e69f8 [#6066]: https://github.com/bytedance/deer-flow/pull/6066
[#6067]: https://github.com/bytedance/deer-flow/pull/6067 [#6067]: https://github.com/bytedance/deer-flow/pull/6067
[#6068]: https://github.com/bytedance/deer-flow/pull/6068 [#6068]: https://github.com/bytedance/deer-flow/pull/6068
[#6069]: https://github.com/bytedance/deer-flow/pull/6069 [#6069]: https://github.com/bytedance/deer-flow/pull/6069
@ -12134,7 +11926,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#6105]: https://github.com/bytedance/deer-flow/pull/6105 [#6105]: https://github.com/bytedance/deer-flow/pull/6105
[#6107]: https://github.com/bytedance/deer-flow/pull/6107 [#6107]: https://github.com/bytedance/deer-flow/pull/6107
[#6109]: https://github.com/bytedance/deer-flow/pull/6109 [#6109]: https://github.com/bytedance/deer-flow/pull/6109
[#6112]: https://github.com/bytedance/deer-flow/commit/52b21d13ac6e674a19cb76013d097e73f108c994 [#6112]: https://github.com/bytedance/deer-flow/pull/6112
[#6113]: https://github.com/bytedance/deer-flow/pull/6113 [#6113]: https://github.com/bytedance/deer-flow/pull/6113
[#6115]: https://github.com/bytedance/deer-flow/pull/6115 [#6115]: https://github.com/bytedance/deer-flow/pull/6115
[#6117]: https://github.com/bytedance/deer-flow/pull/6117 [#6117]: https://github.com/bytedance/deer-flow/pull/6117
@ -12235,7 +12027,7 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#6298]: https://github.com/bytedance/deer-flow/pull/6298 [#6298]: https://github.com/bytedance/deer-flow/pull/6298
[#6299]: https://github.com/bytedance/deer-flow/pull/6299 [#6299]: https://github.com/bytedance/deer-flow/pull/6299
[#6302]: https://github.com/bytedance/deer-flow/pull/6302 [#6302]: https://github.com/bytedance/deer-flow/pull/6302
[#6304]: https://github.com/bytedance/deer-flow/commit/b85e4ae74bb407e1e2396243a8a6e8f5b2420e3f [#6304]: https://github.com/bytedance/deer-flow/pull/6304
[#6305]: https://github.com/bytedance/deer-flow/pull/6305 [#6305]: https://github.com/bytedance/deer-flow/pull/6305
[#6306]: https://github.com/bytedance/deer-flow/pull/6306 [#6306]: https://github.com/bytedance/deer-flow/pull/6306
[#6307]: https://github.com/bytedance/deer-flow/pull/6307 [#6307]: https://github.com/bytedance/deer-flow/pull/6307
@ -12619,7 +12411,6 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#7017]: https://github.com/bytedance/deer-flow/pull/7017 [#7017]: https://github.com/bytedance/deer-flow/pull/7017
[#7018]: https://github.com/bytedance/deer-flow/pull/7018 [#7018]: https://github.com/bytedance/deer-flow/pull/7018
[#7020]: https://github.com/bytedance/deer-flow/pull/7020 [#7020]: https://github.com/bytedance/deer-flow/pull/7020
[#7022]: https://github.com/bytedance/deer-flow/issues/7022
[#7023]: https://github.com/bytedance/deer-flow/pull/7023 [#7023]: https://github.com/bytedance/deer-flow/pull/7023
[#7024]: https://github.com/bytedance/deer-flow/pull/7024 [#7024]: https://github.com/bytedance/deer-flow/pull/7024
[#7031]: https://github.com/bytedance/deer-flow/pull/7031 [#7031]: https://github.com/bytedance/deer-flow/pull/7031
@ -12892,36 +12683,3 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子
[#7643]: https://github.com/bytedance/deer-flow/pull/7643 [#7643]: https://github.com/bytedance/deer-flow/pull/7643
[#7651]: https://github.com/bytedance/deer-flow/pull/7651 [#7651]: https://github.com/bytedance/deer-flow/pull/7651
[#7659]: https://github.com/bytedance/deer-flow/pull/7659 [#7659]: https://github.com/bytedance/deer-flow/pull/7659
[#7638]: https://github.com/bytedance/deer-flow/pull/7638
[#7665]: https://github.com/bytedance/deer-flow/pull/7665
[#7723]: https://github.com/bytedance/deer-flow/pull/7723
[#7727]: https://github.com/bytedance/deer-flow/pull/7727
[#7729]: https://github.com/bytedance/deer-flow/pull/7729
[#7732]: https://github.com/bytedance/deer-flow/pull/7732
[#7746]: https://github.com/bytedance/deer-flow/pull/7746
[#7762]: https://github.com/bytedance/deer-flow/pull/7762
[#7772]: https://github.com/bytedance/deer-flow/pull/7772
[#7781]: https://github.com/bytedance/deer-flow/pull/7781
[#7792]: https://github.com/bytedance/deer-flow/pull/7792
[#7794]: https://github.com/bytedance/deer-flow/pull/7794
[#7798]: https://github.com/bytedance/deer-flow/pull/7798
[#7831]: https://github.com/bytedance/deer-flow/pull/7831
[#7782]: https://github.com/bytedance/deer-flow/pull/7782
[#7953]: https://github.com/bytedance/deer-flow/issues/7953
[#7958]: https://github.com/bytedance/deer-flow/pull/7958
[#7981]: https://github.com/bytedance/deer-flow/pull/7981
[#7992]: https://github.com/bytedance/deer-flow/pull/7992
[#7993]: https://github.com/bytedance/deer-flow/pull/7993
[#7998]: https://github.com/bytedance/deer-flow/issues/7998
[#8006]: https://github.com/bytedance/deer-flow/pull/8006
[#8019]: https://github.com/bytedance/deer-flow/pull/8019
[#8020]: https://github.com/bytedance/deer-flow/pull/8020
[#8043]: https://github.com/bytedance/deer-flow/pull/8043
[#8046]: https://github.com/bytedance/deer-flow/pull/8046
[#8064]: https://github.com/bytedance/deer-flow/pull/8064
[#8087]: https://github.com/bytedance/deer-flow/pull/8087
[#8118]: https://github.com/bytedance/deer-flow/pull/8118
[#8126]: https://github.com/bytedance/deer-flow/pull/8126
[#8139]: https://github.com/bytedance/deer-flow/pull/8139
[#8174]: https://github.com/bytedance/deer-flow/pull/8174
[#8250]: https://github.com/bytedance/deer-flow/pull/8250

View File

@ -320,14 +320,6 @@ Nginx (port 2026) ← Unified entry point
git push origin feature/your-feature-name git push origin feature/your-feature-name
``` ```
Please don't include changes to `CHANGELOG.md` or `CHANGELOG_zh.md` in your
pull request. Maintainers add the changelog entry at merge time: this keeps
the Unreleased section's structure and entry ordering consistent and its
English and Chinese files in sync, and it avoids conflicts with other
in-flight merges, where the Unreleased section changes frequently. If your
PR touches the changelog, a reviewer will ask you to drop that hunk — the
rest of the PR is unaffected.
## AI assistance disclosure ## AI assistance disclosure
DeerFlow is an AI project and we welcome AI-assisted contributions. To help DeerFlow is an AI project and we welcome AI-assisted contributions. To help
@ -350,7 +342,7 @@ before review.
python -m pip install -r tests/skills/requirements.txt python -m pip install -r tests/skills/requirements.txt
python -m pytest tests/skills -q python -m pytest tests/skills -q
# Default backend tests (six parallel shards matching CI; excludes live, blocking-I/O, bundled-extension and benchmark tests) # Default backend tests (four parallel shards; excludes live and blocking-I/O tests)
cd backend cd backend
make test make test
@ -360,9 +352,6 @@ make test TEST_JOBS=1
# Strict blocking-I/O tests # Strict blocking-I/O tests
make test-blocking-io make test-blocking-io
# Behavior suites of the bundled extension examples
make test-bundled-extensions
# Live DeerFlowClient integration tests (explicit opt-in) # Live DeerFlowClient integration tests (explicit opt-in)
# Requires a valid root config.yaml and API credentials. # Requires a valid root config.yaml and API credentials.
make test-live make test-live
@ -388,69 +377,12 @@ must also set `DEER_FLOW_RUN_LIVE_TESTS=1`.
### PR Regression Checks ### PR Regression Checks
Pull requests trigger the following CI workflows: Every pull request triggers the following CI workflows:
- **Backend unit tests** — [.github/workflows/backend-unit-tests.yml](.github/workflows/backend-unit-tests.yml) (skipped only when every changed file is one the backend suite never reads) - **Backend unit tests** — [.github/workflows/backend-unit-tests.yml](.github/workflows/backend-unit-tests.yml)
- **Bundled extension tests** — [.github/workflows/bundled-extension-tests.yml](.github/workflows/bundled-extension-tests.yml) (triggered by example packages, `backend/packages/**`, `backend/app/gateway/**` and the marked test modules) - **Frontend unit tests** — [.github/workflows/frontend-unit-tests.yml](.github/workflows/frontend-unit-tests.yml)
- **Frontend unit tests** — [.github/workflows/frontend-unit-tests.yml](.github/workflows/frontend-unit-tests.yml) (run when `frontend/` or a file it reads changes)
- **Frontend E2E tests** — [.github/workflows/e2e-tests.yml](.github/workflows/e2e-tests.yml) (triggered only when `frontend/` files change) - **Frontend E2E tests** — [.github/workflows/e2e-tests.yml](.github/workflows/e2e-tests.yml) (triggered only when `frontend/` files change)
[scripts/ci_changed_scopes.py](scripts/ci_changed_scopes.py) holds the path rules
for the unit test and lint workflows. Pushes to `main` and changes under
`.github/` run every scope. When a test starts reading a file outside its own
tree, add that path to the script. On every pull request, the
`frontend-scope-reads` lint job flags literal references outside the frontend
scope, including paths based on `import.meta.url`. The backend guard in
`backend/tests/test_ci_changed_scopes.py` flags frontend paths that would skip
the backend suite, including paths built from module-level Python constants.
The browser E2E and full-stack replay jobs use the official Playwright image,
which includes Chromium and its system libraries. When upgrading the locked
Playwright version, update the image tags in both browser workflows to match.
Each job launches Chromium before running tests; auth recovery tests run only
after that browser readiness check succeeds.
These containers use uv-managed Python instead of the host's Python tool cache,
so the interpreter's OpenSSL libraries match its runtime. Backend dependency
setup also verifies SSL and SQLite imports before launching fixture gateways.
### Test and diagnostics notes
Backend `make test` runs six duration-balanced shards concurrently (matching CI) and reports
failure if any shard fails. Use `make test TEST_JOBS=1` to run the shards sequentially.
It excludes live external-API, blocking-I/O and bundled-extension coverage.
Run `cd backend && make test-blocking-io` for strict blocking-I/O checks.
Maintainers can run the real `DeerFlowClient` suite with `cd backend && make test-live`.
This command requires a valid root `config.yaml` and API credentials.
It can incur API costs and create local sandboxes, artifacts, or files.
Direct pytest runs additionally require `DEER_FLOW_RUN_LIVE_TESTS=1`.
Bundled extension examples keep their behavior suites in `backend/tests/` under
the `bundled_extension` pytest marker. The core shards exclude them so an
optional example cannot fail an unrelated core PR, and a separate CI workflow
runs them when an example, the public extension contract or the bundled tests
change. Run `cd backend && make test-bundled-extensions` to exercise them
locally. Tests that validate a host mechanism — loading, registration, the
public extension API and authorization — stay in the core shards even when an
example package is the payload. The host/extension compatibility checks (an
extension requiring a newer API than the host provides, authorization of
contributed routes) live in `backend/tests/test_extension_host_contracts.py` so
a broken compatibility guarantee fails core CI.
Regression coverage includes Docker sandbox mode detection and provisioner kubeconfig-path handling tests in `backend/tests/`.
Backend blocking-IO diagnostics are available from the repository root with
`make detect-blocking-io`: it statically scans backend business code for
blocking IO that may run on the backend event loop, prints a concise summary,
and writes complete JSON findings to `.deer-flow/blocking-io-findings.json`.
The JSON includes compact review records with `priority`, `location`,
`blocking_call`, `event_loop_exposure`, `reason`, and `code`.
Gateway artifact serving now forces active web content types (`text/html` and XML documents such as `.xml`, `.xhtml`, and `.svg`) to download as attachments instead of inline rendering, reducing XSS risk for generated artifacts.
Frontend route asset budgets can be checked with `cd frontend && pnpm
perf:check`. The command measures `/login` from a normal production build, then
performs a production static-demo build for the fixture-backed workspace routes.
It measures the unique JavaScript and CSS referenced by representative routes
and writes the detailed result to `.next/performance-results.json`.
## Code Style ## Code Style
- **Backend (Python)**: We use `ruff` for linting and formatting. Run `make format` before committing. - **Backend (Python)**: We use `ruff` for linting and formatting. Run `make format` before committing.

4029
README.md

File diff suppressed because one or more lines are too long

View File

@ -156,14 +156,6 @@ Ce prompt est destiné aux coding agents. Il leur demande de cloner le dépôt s
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: gpt-5-responses - name: gpt-5-responses
display_name: GPT-5 (Responses API) display_name: GPT-5 (Responses API)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI

View File

@ -147,14 +147,6 @@ DeerFlow がまだ clone されていなければ先に clone してから、htt
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: gpt-5-responses - name: gpt-5-responses
display_name: GPT-5 (Responses API) display_name: GPT-5 (Responses API)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI

View File

@ -233,14 +233,6 @@ MindIE XML 도구 호출은 [인자 파싱 및 줄바꿈 호환성 가이드](ba
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: gpt-5-responses - name: gpt-5-responses
display_name: GPT-5 (Responses API) display_name: GPT-5 (Responses API)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI
@ -1203,7 +1195,7 @@ Agent settings에서 **Tool access**는 설정된 모든 도구 그룹을 상속
비전을 지원하는 에이전트의 경우 `view_image`와 그 뒤에 이어지는 모델 컨텍스트 이미지 읽기에도 `sandbox:execute`가 필요합니다. 도구 이름만 허용해서는 이미지 파일 접근 권한이 부여되지 않으며, 샌드박스 실행이 거부된 역할은 권한이 변경된 후 이전에 기록된 이미지 메타데이터를 다시 읽을 수 없습니다. 외부 실행 입력과 스레드 상태 업데이트로는 `viewed_images`나 `thread_data`를 설정할 수 없습니다. 저장된 이미지를 호스트 사본에서 읽을 때는 해당 경로가 현재 사용자의 스레드와 기록된 가상 이미지 경로로 해석되어야 합니다. 비전을 지원하는 에이전트의 경우 `view_image`와 그 뒤에 이어지는 모델 컨텍스트 이미지 읽기에도 `sandbox:execute`가 필요합니다. 도구 이름만 허용해서는 이미지 파일 접근 권한이 부여되지 않으며, 샌드박스 실행이 거부된 역할은 권한이 변경된 후 이전에 기록된 이미지 메타데이터를 다시 읽을 수 없습니다. 외부 실행 입력과 스레드 상태 업데이트로는 `viewed_images`나 `thread_data`를 설정할 수 없습니다. 저장된 이미지를 호스트 사본에서 읽을 때는 해당 경로가 현재 사용자의 스레드와 기록된 가상 이미지 경로로 해석되어야 합니다.
각 모델 요청에는 최근에 본 이미지가 최대 4개, base64 이미지 데이터가 최대 28 MiB까지 포함됩니다. 이 제한으로 제외된 이미지는 생략된 것으로 보고되며, 에이전트는 `view_image`를 다시 호출해 이미지를 컨텍스트로 다시 가져올 수 있습니다. 각 모델 요청에는 최근에 본 이미지가 최대 4개, base64 이미지 데이터가 최대 28 MiB까지 포함됩니다. 이 제한으로 제외된 이미지는 생략된 것으로 보고되며, 에이전트는 `view_image`를 다시 호출해 이미지를 컨텍스트로 다시 가져올 수 있습니다.
고급 배포에서는 `config.yaml` 또는 `extensions_config.json`의 `extensions.middlewares` 아래에 `AgentMiddleware` 클래스를 선언하여 에이전트 런타임 자체를 확장할 수도 있습니다. 각 항목은 `module.path:ClassName` 문자열(인자 없는 생성자) 또는 객체 `{class, kwargs, apply_to}`이며, 객체의 `kwargs`는 생성자에 전달됩니다. `kwargs` 값은 JSON 타입(객체, 배열, 문자열, 숫자, 불리언, null)이어야 하며, YAML 날짜와 타임스탬프는 JSON과 일치하도록 ISO 문자열로 변환됩니다. DeerFlow는 각 체인에 대해 선택된 설정 항목을 리드 에이전트와 서브에이전트 파이프라인에 불러오며, 그 위치는 기본 제공 런타임 미들웨어와 루프/토큰 가드 뒤, 그리고 terminal-response/safety/clarification 꼬리 앞입니다. 따라서 엔터프라이즈 포크는 기본 제공 미들웨어 빌더를 패치하지 않고도 도메인 가드레일, 도구 호출 거버넌스, 관측성 훅을 추가할 수 있습니다. 패키지 누락, 잘못된 클래스, 손상된 모듈, 생성자 오류는 에이전트 생성 시점에 명확한 오류로 실패합니다. `config.yaml`과 `extensions_config.json`은 운영자가 제어하는 신뢰된 파일로 취급하세요. 커스텀 도구, 모델, 샌드박스, 가드레일, MCP 서버, MCP 인터셉터 선언과 마찬가지로 미들웨어 경로는 곧 코드 실행입니다. Gateway의 스킬/MCP 토글 엔드포인트는 이 필드를 보존하지만 `extensions.middlewares`에 대한 API 쓰기 경로는 제공하지 않습니다. 객체의 선택적 `apply_to`는 `both`(기본값), `lead`, `subagent`를 지원하며, 문자열 항목과 이 필드를 생략한 객체는 계속 두 파이프라인 모두에 적용됩니다. 해당 체인에서 제외된 항목은 임포트하거나 인스턴스화하지 않습니다. 고급 배포에서는 `config.yaml` 또는 `extensions_config.json`의 `extensions.middlewares` 아래에 `AgentMiddleware` 클래스를 선언하여 에이전트 런타임 자체를 확장할 수도 있습니다. 각 항목은 `module.path:ClassName` 문자열(인자 없는 생성자) 또는 객체 `{class, kwargs}`이며, 객체의 `kwargs`는 생성자에 전달됩니다. `kwargs` 값은 JSON 타입(객체, 배열, 문자열, 숫자, 불리언, null)이어야 하며, YAML 날짜와 타임스탬프는 JSON과 일치하도록 ISO 문자열로 변환됩니다. DeerFlow는 설정된 같은 목록을 리드 에이전트와 서브에이전트 파이프라인에 불러오며, 그 위치는 기본 제공 런타임 미들웨어와 루프/토큰 가드 뒤, 그리고 terminal-response/safety/clarification 꼬리 앞입니다. 따라서 엔터프라이즈 포크는 기본 제공 미들웨어 빌더를 패치하지 않고도 도메인 가드레일, 도구 호출 거버넌스, 관측성 훅을 추가할 수 있습니다. 패키지 누락, 잘못된 클래스, 손상된 모듈, 생성자 오류는 에이전트 생성 시점에 명확한 오류로 실패합니다. `config.yaml`과 `extensions_config.json`은 운영자가 제어하는 신뢰된 파일로 취급하세요. 커스텀 도구, 모델, 샌드박스, 가드레일, MCP 서버, MCP 인터셉터 선언과 마찬가지로 미들웨어 경로는 곧 코드 실행입니다. Gateway의 스킬/MCP 토글 엔드포인트는 이 필드를 보존하지만 `extensions.middlewares`에 대한 API 쓰기 경로는 제공하지 않습니다. 리드 에이전트 전용/서브에이전트 전용 미들웨어 목록을 따로 지정하는 기능은 아직 지원되지 않습니다.
패키지화되고 설정 가능한 런타임 통합에는 DeerFlow의 확장 관리자를 사용하세요. 확장 관리자는 Python 패키지 요구 사항, 공개 HTTPS Git URL, 또는 로컬 디렉터리를 받아 백엔드 전용 `extensions` 의존성 그룹에 패키지를 설치하고, `backend/uv.lock`을 업데이트하며, 시작 시에만 읽는 `config.yaml`의 최상위 `plugins:` 목록에 활성화된 항목을 추가합니다. 패키지화되고 설정 가능한 런타임 통합에는 DeerFlow의 확장 관리자를 사용하세요. 확장 관리자는 Python 패키지 요구 사항, 공개 HTTPS Git URL, 또는 로컬 디렉터리를 받아 백엔드 전용 `extensions` 의존성 그룹에 패키지를 설치하고, `backend/uv.lock`을 업데이트하며, 시작 시에만 읽는 `config.yaml`의 최상위 `plugins:` 목록에 활성화된 항목을 추가합니다.
@ -1850,7 +1842,7 @@ WeChat은 바인딩 후 현재 대화 컨텍스트를 안전하게 저장하기
양식이 그룹 알림 지원 여부를 확인하는 동안에는 로딩 안내를 표시하고 저장된 선택을 유지합니다. 양식이 그룹 알림 지원 여부를 확인하는 동안에는 로딩 안내를 표시하고 저장된 선택을 유지합니다.
그룹은 자동으로 선택되지 않습니다. 선택을 해제하면 새 그룹 알림이 중지되고, 선택을 변경하면 이후 알림에 반영되며, 이미 큐에 들어간 알림은 원래 대상을 유지합니다. 연결이 해제된 바인딩은 대기 중인 알림을 절대 받지 않습니다. 첫 버전에서는 작업 양식 또는 REST API로 설정하며, 대화용 일정 도구의 입력은 기존과 같습니다. [그룹 전달 가이드](backend/docs/IM_CHANNEL_CONNECTIONS.md#group-notifications)를 참고하세요. 그룹은 자동으로 선택되지 않습니다. 선택을 해제하면 새 그룹 알림이 중지되고, 선택을 변경하면 이후 알림에 반영되며, 이미 큐에 들어간 알림은 원래 대상을 유지합니다. 연결이 해제된 바인딩은 대기 중인 알림을 절대 받지 않습니다. 첫 버전에서는 작업 양식 또는 REST API로 설정하며, 대화용 일정 도구의 입력은 기존과 같습니다. [그룹 전달 가이드](backend/docs/IM_CHANNEL_CONNECTIONS.md#feishu-group-notifications)를 참고하세요.
### 수명 주기, 안전 상한, 중지 조건 ### 수명 주기, 안전 상한, 중지 조건

View File

@ -207,14 +207,6 @@ Para o endpoint oficial do Gemini compatível com OpenAI, do Google, use o [perf
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: gpt-5-responses - name: gpt-5-responses
display_name: GPT-5 (Responses API) display_name: GPT-5 (Responses API)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI

View File

@ -159,14 +159,6 @@ DeerFlow интегрирован с инструментарием для ум
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: gpt-5-responses - name: gpt-5-responses
display_name: GPT-5 (Responses API) display_name: GPT-5 (Responses API)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI

View File

@ -27,11 +27,11 @@ https://github.com/user-attachments/assets/a8bcadc4-e040-4cf2-8fda-dd768b999c18
- [**LLM Space**](https://github.com/deer-flow/llm-space) - 认识 DeerFlow 背后的秘密武器——一款桌面工具,用于原型化 agent 想法、检查 harness 的每个步骤、回放失败用例并基准测试性能。 - [**LLM Space**](https://github.com/deer-flow/llm-space) - 认识 DeerFlow 背后的秘密武器——一款桌面工具,用于原型化 agent 想法、检查 harness 的每个步骤、回放失败用例并基准测试性能。
## BytePlus Agent Plan 与火山引擎方舟 Coding Plan ## 字节跳动火山引擎方舟 Coding Plan
- **BytePlus Agent Plan(个人版 & 企业版)**:一把 API Key 打通 DeerFlow 全链路——旗舰对话模型(`dola-seed-2.1-turbo`、`deepseek-v4-pro`、`deepseek-v4.1-flash`)、**Seedream 5.0/5.5** 生图与 PPT 视觉生成(`image-generation` / `ppt-generation`),以及 **Seedance 2.5** 原生音画同步视频生成(`video-generation`,Large / Max / 企业共享包可用),统一以透明的 AFP(Agent Fuel Points)计量。 - 我们推荐使用 Doubao-Seed-2.0-Code、DeepSeek v3.2 和 Kimi 2.5 运行 DeerFlow
- [了解 BytePlus Agent Plan](https://www.byteplus.com/en/activity/agentplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [控制台](https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [个人版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-personal-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [企业版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) - [现在就加入 Coding Plan](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow)
- [中国大陆地区的开发者请点击这里(火山引擎 Coding Plan)](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) - [海外地区的开发者请点击这里](https://www.byteplus.com/en/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow)
## InfoQuest ## InfoQuest
@ -50,7 +50,7 @@ DeerFlow 新近集成了 BytePlus 自研的智能搜索与抓取工具集——[
- [🦌 DeerFlow - 2.0](#-deerflow---20) - [🦌 DeerFlow - 2.0](#-deerflow---20)
- [官网](#官网) - [官网](#官网)
- [姐妹项目](#姐妹项目) - [姐妹项目](#姐妹项目)
- [BytePlus Agent Plan 与火山引擎方舟 Coding Plan](#byteplus-agent-plan-与火山引擎方舟-coding-plan) - [字节跳动火山引擎方舟 Coding Plan](#字节跳动火山引擎方舟-coding-plan)
- [InfoQuest](#infoquest) - [InfoQuest](#infoquest)
- [目录](#目录) - [目录](#目录)
- [一句话交给 Coding Agent 安装](#一句话交给-coding-agent-安装) - [一句话交给 Coding Agent 安装](#一句话交给-coding-agent-安装)
@ -109,7 +109,7 @@ DeerFlow 新近集成了 BytePlus 自研的智能搜索与抓取工具集——[
管理员可在 **设置 → 模型 → 添加模型** 中选择厂商,仅填写 **API Key** 和 管理员可在 **设置 → 模型 → 添加模型** 中选择厂商,仅填写 **API Key** 和
**模型 ID**。后端预置 OpenAI、Anthropic、DeepSeek、百炼/通义千问、火山/豆包、 **模型 ID**。后端预置 OpenAI、Anthropic、DeepSeek、百炼/通义千问、火山/豆包、
Moonshot/Kimi、智谱/Z.AI、MiniMax 和阶跃星辰(StepFun)的端点、认证与适配器,地域和 Coding Plan Moonshot/Kimi、智谱/Z.AI 和 MiniMax 的端点、认证与适配器,地域和 Coding Plan
使用明确区分的选项。模型 ID 不受内置枚举限制;内部名称自动生成且保持稳定。 使用明确区分的选项。模型 ID 不受内置枚举限制;内部名称自动生成且保持稳定。
新模型默认启用,保存后自动刷新聊天及 Agent 的模型选择器,无需重启 Gateway。 新模型默认启用,保存后自动刷新聊天及 Agent 的模型选择器,无需重启 Gateway。
@ -183,14 +183,6 @@ YAML 同名模型优先,已有任务保留原配置快照。托管模型使用
api_key: $OPPER_API_KEY api_key: $OPPER_API_KEY
base_url: https://api.opper.ai/v3/compat base_url: https://api.opper.ai/v3/compat
- name: nvidia-nemotron-3.5-super-vl
display_name: Nemotron 3.5 Super VL 120B (NVIDIA NIM)
use: langchain_openai:ChatOpenAI
model: nvidia/nemotron-3.5-super-vl-120b-a12b
api_key: $NVIDIA_API_KEY
base_url: https://integrate.api.nvidia.com/v1
supports_vision: true
- name: api-route-gpt-6.1-sol - name: api-route-gpt-6.1-sol
display_name: GPT 6.1 Sol (API Route) display_name: GPT 6.1 Sol (API Route)
use: langchain_openai:ChatOpenAI use: langchain_openai:ChatOpenAI
@ -422,12 +414,10 @@ DeerFlow 的内置自定义事件同时通过两种 LangGraph 流式接口提供
### 进阶配置 ### 进阶配置
#### Sandbox 模式 #### Sandbox 模式
DeerFlow 支持多种沙箱模式。 DeerFlow 支持多种 sandbox 执行方式:
- **本地执行**(直接在宿主机上运行 sandbox 代码)
- **本地工作区**(通过工作区文件工具访问已配置的挂载)
- **Docker 执行**(在隔离的 Docker 容器里运行 sandbox 代码) - **Docker 执行**(在隔离的 Docker 容器里运行 sandbox 代码)
- **Docker + Kubernetes 执行**(通过 provisioner 服务在 Kubernetes Pod 中运行 sandbox 代码) - **Docker + Kubernetes 执行**(通过 provisioner 服务在 Kubernetes Pod 中运行 sandbox 代码)
- **BytePlus veFaaS 云端沙箱**(基于 [BytePlus veFaaS](https://www.byteplus.com/en/product/vefaas?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) Serverless AIO 沙箱,支持推测预热、空闲暂停/自动唤醒、线程级快照、镜像预热与可选 TOS 挂载,详见 [veFaaS Sandbox Provider](backend/packages/harness/deerflow/community/vefaas_sandbox/README.md))
Docker 开发时,服务启动行为会遵循 `config.yaml` 里的 sandbox 模式。在 Local / Docker 模式下,不会启动 `provisioner`。 Docker 开发时,服务启动行为会遵循 `config.yaml` 里的 sandbox 模式。在 Local / Docker 模式下,不会启动 `provisioner`。
@ -722,18 +712,6 @@ DeerFlow 2.0 不再是一个需要你自己拼装的 framework。它是一个开
## 核心特性 ## 核心特性
### Token 用量统计
点击侧边栏的 **Token 用量**(`/workspace/usage`),查看近 7/30 天的用量、
每日输入/输出 Token、各模型的缓存命中输入 Token,以及支持失败筛选和分页的
运行记录。运行记录包含所有日期,不受图表所选周期限制。
此功能需要 `runs:read` 权限和 SQLite 或 PostgreSQL 数据库,静态演示不提供统计。
数据来自已持久化的服务商用量;运行过程中或服务商未返回用量时可能不完整,不能
作为服务商账单。缓存命中 Token 已包含在输入 Token 中。每日分桶使用浏览器当前
UTC 偏移,并按运行的创建日期归属。页面复用现有 `/api/console` 接口,保留服务端
价格配置及可选的费用、币种字段。
### Skills 与 Tools ### Skills 与 Tools
Skills 是 DeerFlow 能做“几乎任何事”的关键。 Skills 是 DeerFlow 能做“几乎任何事”的关键。
@ -840,11 +818,8 @@ Web UI 输入框支持浏览器侧语音听写。浏览器提供 Web Speech API
/goal finish the implementation and make all tests pass /goal finish the implementation and make all tests pass
/goal # 查看当前激活的 goal /goal # 查看当前激活的 goal
/goal clear # 清除它 /goal clear # 清除它
/goal from-chat # 仅 IM:根据当前对话生成 goal
``` ```
在受支持的 IM 渠道里,`/goal from-chat [提示]` 会从当前对话中归纳 goal,而不是把文字当成目标本身。它会保留对话中已经约定的约束和停止条件,展示保存后的目标,并只启动一次 run。命令后的可选提示用于补充约束,不需要重述完整目标。如果对话不足以形成清楚的目标,则不会保存或启动任何内容,回复会说明原因;如果助手还在等你回答,回复会先请你回复。
每次 Gateway 驱动的 run 结束后,DeerFlow 会用一个 non-thinking 的评估模型,把可见的对话内容(包括助手的工具调用和截短的工具结果)拿去和激活的 goal 比对。工具调用成功本身不代表 goal 已完成;如果助手不得不猜测缺失或含糊的信息,评估模型会报告 `needs_user_input`。评估模型必须返回一个带类型的 blocker(`missing_evidence`、`needs_user_input`、`run_failed`、`external_wait` 或 `goal_not_met_yet`),并附上可见证据。只有在最近一轮 assistant 回复已被持久化 checkpoint、blocker 是 `goal_not_met_yet`、评估期间 thread 没有变化、且无进展熔断器没有触发时,DeerFlow 才会注入一次 hidden continuation。安全上限默认是 8 次 hidden continuation;连续两次相同的无进展评估后就会停止。`/goal clear` 以及任何用户手动输入的新内容,优先级都高于排队中的 continuation。当 goal 被满足时,DeerFlow 会自动清除它,并发布更新后的 thread 状态。同一个 checkpoint 会把这次达成记为 `goal_outcome`,保留到下一次修改 goal。 每次 Gateway 驱动的 run 结束后,DeerFlow 会用一个 non-thinking 的评估模型,把可见的对话内容(包括助手的工具调用和截短的工具结果)拿去和激活的 goal 比对。工具调用成功本身不代表 goal 已完成;如果助手不得不猜测缺失或含糊的信息,评估模型会报告 `needs_user_input`。评估模型必须返回一个带类型的 blocker(`missing_evidence`、`needs_user_input`、`run_failed`、`external_wait` 或 `goal_not_met_yet`),并附上可见证据。只有在最近一轮 assistant 回复已被持久化 checkpoint、blocker 是 `goal_not_met_yet`、评估期间 thread 没有变化、且无进展熔断器没有触发时,DeerFlow 才会注入一次 hidden continuation。安全上限默认是 8 次 hidden continuation;连续两次相同的无进展评估后就会停止。`/goal clear` 以及任何用户手动输入的新内容,优先级都高于排队中的 continuation。当 goal 被满足时,DeerFlow 会自动清除它,并发布更新后的 thread 状态。同一个 checkpoint 会把这次达成记为 `goal_outcome`,保留到下一次修改 goal。
重新生成此前的回答时,会沿用当前对话的 goal 和已用续跑预算,不会恢复已清除或已达成的旧 goal。重放历史 checkpoint 时会移除旧回答的达成记录,避免把它当作新回答已经达成的证明。 重新生成此前的回答时,会沿用当前对话的 goal 和已用续跑预算,不会恢复已清除或已达成的旧 goal。重放历史 checkpoint 时会移除旧回答的达成记录,避免把它当作新回答已经达成的证明。
@ -867,11 +842,6 @@ Web UI 会在输入框上方展示当前激活的 goal,说明自动续跑为
### Sub-Agents ### Sub-Agents
显式后台 `batch_task` 可用 `depends_on` 声明同批条目的前置关系,前置工作完成后即可继续,
无需等待无关任务。用户已要求后续汇总或交付时,可用可选的 `continuation` 登记一次主 Agent 接续;
启用 Goal 时仍由 Goal 负责续跑。执行、取消、授权和恢复范围见
[批次依赖与完成接续说明](backend/docs/BATCH_CONTINUATION.md)。
Sub-agent 是一种执行优化,而不是遇到复杂任务时的默认选择。 Sub-agent 是一种执行优化,而不是遇到复杂任务时的默认选择。
lead agent 只会在委派具有明确净收益时动态拉起 sub-agents,例如真正缩短耗时的并行工作、专业能力收益或上下文隔离收益。存在跨 Agent 依赖或重叠副作用的工作不会并行分派;当专业能力或上下文隔离收益明显占优时,一条有界的顺序任务链仍可交给一个 sub-agent 完成。lead agent 会使用能取得收益的最少 sub-agents,并在每一批完成后重新评估,而不会仅仅因为任务规模大或步骤多就继续拆分。每个 sub-agent 都有自己独立的上下文、工具和终止条件,返回结构化结果后由 lead agent 验证并汇总成完整输出。 lead agent 只会在委派具有明确净收益时动态拉起 sub-agents,例如真正缩短耗时的并行工作、专业能力收益或上下文隔离收益。存在跨 Agent 依赖或重叠副作用的工作不会并行分派;当专业能力或上下文隔离收益明显占优时,一条有界的顺序任务链仍可交给一个 sub-agent 完成。lead agent 会使用能取得收益的最少 sub-agents,并在每一批完成后重新评估,而不会仅仅因为任务规模大或步骤多就继续拆分。每个 sub-agent 都有自己独立的上下文、工具和终止条件,返回结构化结果后由 lead agent 验证并汇总成完整输出。
@ -890,12 +860,12 @@ lead agent 只会在委派具有明确净收益时动态拉起 sub-agents,例
DeerFlow 不只是“会说它能做”,它是真的有一台自己的“电脑”。 DeerFlow 不只是“会说它能做”,它是真的有一台自己的“电脑”。
沙箱的运行方式取决于配置。本地工作区使用专用文件工具,Docker 模式在隔离的容器中运行,Kubernetes 模式通过 provisioner 服务在 Pod 中运行。Agent 可以在沙箱中访问 skills、workspace、uploads、outputs,读写和编辑文件,也可以查看图片。需要执行 Bash 命令或通过 Shell 运行代码时,请选择提供 Shell 的隔离沙箱。各模式的配置方式见[沙箱指南](docs/guide/sandbox.md#sandbox-mode)。 每个任务都运行在隔离的 Docker 容器里,里面有完整的文件系统,包括 skills、workspace、uploads、outputs。agent 可以读写和编辑文件,可以执行 bash 命令和代码,也可以查看图片。整个过程都在 sandbox 内完成,可审计、会隔离,不会在不同 session 之间互相污染。
这就是“带工具的聊天机器人”和“真正有执行环境的 agent”之间的差别。 这就是“带工具的聊天机器人”和“真正有执行环境的 agent”之间的差别。
```text ```text
# 沙箱中的虚拟路径 # sandbox 容器内的路径
/mnt/user-data/ /mnt/user-data/
├── uploads/ ← 你的文件 ├── uploads/ ← 你的文件
├── workspace/ ← agents 的工作目录 ├── workspace/ ← agents 的工作目录

File diff suppressed because one or more lines are too long

View File

@ -1,70 +1,327 @@
# Backend (`backend/`) # AGENTS.md
The Python backend: the publishable harness in `packages/harness/deerflow/`, the ## Project Overview
public extension contract in `packages/extension-api/`, and the unpublished
Gateway and IM channels in `app/`. In every deployment the agent runtime runs
inside the Gateway. Design docs are in [docs/](docs/); start with
[ARCHITECTURE.md](docs/ARCHITECTURE.md) and [API.md](docs/API.md).
## Guides by area The LangGraph backend provides sandbox execution, persistent memory, subagent delegation, and extensible tools, isolated per thread.
Read the guide for an area before you change it. Service roles and ports: [root service topology](../AGENTS.md#service-topology).
| Area | Guide | **Runtime**:
| --- | --- | - `make dev`, Docker dev, and production all run the agent runtime in Gateway via `RunManager` + `run_agent()` + `StreamBridge` (`packages/harness/deerflow/runtime/`). Nginx exposes that runtime at `/api/langgraph/*` and rewrites it to Gateway's native `/api/*` routers.
| Run streaming, checkpoints, run ownership | [runtime](packages/harness/deerflow/runtime/AGENTS.md) | - Gateway streams `write_file` and `str_replace` argument deltas in bounded batches for multi-mode `messages-tuple` consumers; single-mode message consumers retain the original per-chunk contract. Non-message frames flush pending batches, and `values` remains an optional complete-state snapshot rather than a prerequisite for batching.
| Repositories, leases, scheduled tasks, schema changes | [persistence](packages/harness/deerflow/persistence/AGENTS.md), [migrations](packages/harness/deerflow/persistence/migrations/AGENTS.md) | - `stream_subgraphs` preserves subgraph SSE namespaces (`values|<ns>`, LangGraph Platform style); bare `values` would overwrite the SDK thread view (#4399). Delegated subagents inherit the parent's checkpoint namespace. Root-only consumers (file-tool chunk batcher, subagent event persistence, LLM error-fallback detection) ignore namespaced frames. The web frontend uses root `task_*` events without subgraph streaming.
| Scheduler failure isolation | [design conventions](app/scheduler/guide/failure-isolation.md) | - Background subagent identity is deliberately split: the provider `tool_call_id` remains the correlation key for `ToolMessage`, `task_*` SSE events, persisted lifecycle events, frontend cards, and the public `ExtensionData.scope_id` contract (stored as `SubagentResult.external_task_id`), while `SubagentExecutor.execute_async()` generates a full server-side `execution_id` for `SubagentResult.task_id`, the process-wide registry, polling, cancellation, timeout handling, and cleanup. Provider IDs are not globally unique across parent runs, so they must never become registry ownership keys; scheduler closures retain their own `SubagentResult` rather than resolving ownership again through the mutable registry. Terminal subagent token usage travels in the current run's `ToolMessage.additional_kwargs` and is attributed from message state, never through a process-global provider-ID cache.
| `config.yaml`, `extensions_config.json` | [config](packages/harness/deerflow/config/AGENTS.md) | - Scheduled runs use Gateway's normal run path. `launch_scheduled_thread_run` reads `get_app_config()` at dispatch: `scheduler.recursion_limit` defaults to 1000 (web UI), capped by `max_recursion_limit`; YAML changes apply next run without restart. IM enqueue checks recipients before locking preferences in the outcome transaction.
| Lead agent, prompt, thread state, middleware chain | [agents](packages/harness/deerflow/agents/AGENTS.md), [middlewares](packages/harness/deerflow/agents/middlewares/AGENTS.md) | - Run-history `status` filters are occurrence states, not task states. `ScheduledTaskRunStatus` in `persistence/scheduled_tasks/model.py` is the shared API/repository vocabulary and must match the active and terminal occurrence-status sets. Keep owner lookup before reading history, and apply SQL task/status predicates before pagination; omitted status preserves the existing response.
| Memory, subagents, skills, tools | [memory](packages/harness/deerflow/agents/memory/AGENTS.md), [subagents](packages/harness/deerflow/subagents/AGENTS.md), [skills](packages/harness/deerflow/skills/AGENTS.md), [tools](packages/harness/deerflow/tools/AGENTS.md) | - The background scheduler is single-instance by default. `scheduler.multi_instance=true` opts into lease-aware recovery across Gateway instances and requires shared Postgres, `run_ownership.heartbeat_enabled=true`, and `run_events.backend=db`; otherwise startup rejects the configuration. Live scheduled runs are preserved when a peer starts; expired launch claims return to the durable queue, expired run leases are atomically taken over, stale launch writes are fenced by lease ownership, and the Postgres advisory-locked budget makes `max_concurrent_runs` a shared global cap for `launching`/`running` rows.
| Sandbox, uploads, MCP, models, extensions | [sandbox](packages/harness/deerflow/sandbox/AGENTS.md), [uploads](packages/harness/deerflow/uploads/AGENTS.md), [mcp](packages/harness/deerflow/mcp/AGENTS.md), [models](packages/harness/deerflow/models/AGENTS.md), [extensions](packages/harness/deerflow/extensions/AGENTS.md) | - The multi-process startup gate also fires on `deployment.multi_instance: true`; contract in `docs/CONFIGURATION.md`.
| Trace ID, embedded client, other root modules | [harness package](packages/harness/deerflow/AGENTS.md) | - Long-running MCP work uses a separate durable task runtime (`McpTaskService` + `mcp_tasks`, lease-based recovery) rather than keeping remote task IDs or status polling inside the Agent loop; only submit remains Agent-visible, the database is the source of truth, and `ThreadState` receives only a bounded current-thread projection. Full contract — including notification retries, dead-lettering, and the cancel endpoint's worker-stopped 503 (leases, cancellation fencing, delivery idempotency, management-tool exposure): [packages/harness/deerflow/mcp/AGENTS.md](packages/harness/deerflow/mcp/AGENTS.md).
| Search, fetch and sandbox providers | [community](packages/harness/deerflow/community/AGENTS.md), then the provider's own guide | - Scheduled-task dispatch permits one active occurrence per task via `uq_scheduled_task_run_active` (`task_id WHERE status IN ('queued','launching','running')`). Durable `queued` rows survive restarts; only lease-fenced `launching` may call Gateway launch; `running` references the durable run. Stable admission idempotency keys reuse that run after recovery. Reused-thread `ConflictError` returns `launching` to `queued`; other launch errors become `failed`. Atomic queue claims enforce `max_concurrent_runs` and the per-owner cap, excluding waiting rows; the budget count and its UPDATE are separate statements, so writers must serialize before the count (Postgres advisory lock; SQLite `BEGIN IMMEDIATE`, whose deferred transaction otherwise reserves the writer only at the UPDATE) or claims on distinct rows overshoot the cap. Repeated triggers coalesce; same-thread FIFO blocks behind older active rows. Queue admission, PATCH/resume, pause and delete lock the parent before the occurrence, freezing active task definitions. Pause/delete atomically cancel `queued` work but reject `launching`/`running`; PATCH/resume reject all active states. Only queued conflicts offer pause cancellation. Manual triggers may queue/run while paused. Manual-trial run origins reuse the admitted `scheduled_for`, so an idempotent retry submits the same request instead of colliding with the first attempt.
| Gateway, routers, IM channels | [gateway](app/gateway/AGENTS.md), [routers](app/gateway/routers/AGENTS.md), [channels](app/channels/AGENTS.md) | - Scheduled-task lifecycle, recovery and queue timeout: [persistence guide](packages/harness/deerflow/persistence/AGENTS.md#scheduled-task-lifecycle).
| Tests, benchmarks | [tests](tests/AGENTS.md), [benchmarks](scripts/benchmark/AGENTS.md) | - `POST /api/scheduled-tasks/preview-cron` requires authenticated `threads:read`. Bounded cron previews call the shared scheduler calculator in `asyncio.to_thread`, preserving its DST semantics. Capture the optional aware reference once; return UTC and offset-bearing local occurrences without acquiring task/thread/run stores or dispatching work. This advisory API does not reserve execution.
- Gateway MCP/skill updates write `extensions_config.json` at runtime. Production Compose mounts it read-write (`config.yaml` stays `:ro`); Helm seeds a writable home-volume copy. Hold both `extensions_config_write_lock` and the sidecar advisory `extensions_config_file_lock` during read-modify-write to prevent lost updates across workers. `atomic_write_extensions_config` uses temp-file replacement; only mount-point `EBUSY` permits a non-atomic in-place overwrite (crashes can truncate). Warn about this fallback once per target; propagate other errors. `get_extensions_config()` revalidates reads by file signature; see [config caching](packages/harness/deerflow/config/AGENTS.md). Tests: `tests/test_compose_extensions_config_writable.py`, `tests/test_extensions_config_atomic_write.py`, `tests/test_helm_extensions_config_writable.py`.
- MCP cache reset scope and discovery fencing: [MCP guide](packages/harness/deerflow/mcp/AGENTS.md).
Keep the [child history inventory](../docs/guide/subagents.md#inspect-one-threads-child-history) **Project structure:** The [root repository map](../AGENTS.md#repository-map)
read-only. Read identities and both row counts from one SQLite snapshot. indexes the stack. Backend code lives in `app/` (Gateway and channels),
`packages/harness/deerflow/` (agent runtime), and `packages/extension-api/`
(public extension contracts). Tests, detailed docs, and standalone benchmarks
live in `tests/`, `docs/`, and `scripts/benchmark/` respectively. Module-local
`AGENTS.md` files describe their implementation boundaries.
## Verify ## Important Development Guidelines
### Documentation Update Policy
Every code change must keep docs accurate and current: update `README.md` for
user-facing behavior and the relevant `AGENTS.md` for development changes.
`CLAUDE.md` imports `AGENTS.md`; do not edit the shim.
Image result URL policy: [image search guide](packages/harness/deerflow/community/image_search/AGENTS.md).
### Backend Benchmarks
`scripts/benchmark/context_snapshot/`: explicit `run-live` needs provider env
vars; `summarize` and pytest are offline. See its README for the protocol.
Benchmarks in `scripts/benchmark/` must be standalone and reproducible. Import
production functions; never duplicate them or introduce an alternative runtime.
Sandbox benchmarks reuse production lifecycle. Reject negative/NaN timing values
before provider creation, export no secrets, and fail on final cleanup errors.
See the sandbox benchmark README for supported options and tests.
- Pin every external dataset by immutable revision and SHA-256. Callers provide
the local dataset path; evaluation commands must not silently download data.
- Never commit upstream dataset text, credentials, complete provider requests,
or response headers. Committed manifests may contain stable IDs and source
locators. Synthetic cases must identify themselves as synthetic.
- Read provider credentials and endpoints from named environment variables.
Version model IDs, inference parameters, prompts, retry rules, clocks, and
random seeds in the evaluation config.
- Public raw results may contain case IDs, policy decisions, model hypotheses,
grades, and non-secret response metadata. Keep dataset questions, reference
answers, memory content, and full provider payloads in ignored local run
directories.
- Use fixed clocks and deterministic ordering for offline selection. Results
must record the config, manifest, prompt, dataset, and git revisions used.
`scripts/benchmark/deermem_eviction/` evaluates the production
`select_facts_for_capacity()` implementation used by DeerMem. It compares only
the historical `confidence` policy and PR #4789's opt-in `hybrid-v1`; do not add
another eviction strategy to this evaluation. Run its offline checks from
`backend/`:
```bash ```bash
make test # offline suite in parallel shards PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction validate-contracts
make test-blocking-io # strict blocking-I/O suite PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction validate --dataset "$LONGMEMEVAL_ORACLE_PATH"
make test-bundled-extensions # behavior suites of bundled examples (not in make test) PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction run-policy \
make lint --dataset "$LONGMEMEVAL_ORACLE_PATH" \
make format --output-dir /tmp/deermem-eviction-policy-run
make test-live # calls real APIs; needs DEER_FLOW_RUN_LIVE_TESTS=1 PYTHONPATH=. uv run pytest tests/test_bench_deermem_eviction_*.py -q
``` ```
Run `make test` and `make test-blocking-io` before and after a change. Cover The offline test suite must not require network access, provider credentials,
behavior changes in the owning module's existing suite under `tests/` rather or the LongMemEval dataset. Small LongMemEval-shaped fixtures must be synthetic
than opening a new file per fix, and update or delete superseded tests in the and generated by tests.
same change. Live tests stay opt-in, so the default suite needs no network and
no API key.
## Rules `scripts/benchmark/concurrency/` measures multi-process contention on the
`users` table (N separate OS processes, not asyncio tasks) for SQLite vs
Postgres -- the scenario `CONFIGURATION.md` requires Postgres for. `worker.py`
connects directly via SQLAlchemy (skipping the ~8.5s Alembic bootstrap the
orchestrator already ran once) and mirrors the app's per-connection SQLite
PRAGMAs; `run_concurrency_bench.py` seeds a disposable per-run Postgres schema,
synchronises workers on a READY/GO barrier before timing, and exits non-zero on
any crash, short op count, or `errors > 0`. Postgres runs need a throwaway
database via `--pg-url`; nothing here touches `public`. Run from `backend/`:
- **The harness never imports `app`.** `app.*` imports `deerflow.*`, and not the ```bash
reverse, because the harness is published on its own. uv run python scripts/benchmark/concurrency/run_concurrency_bench.py \
`tests/test_harness_boundary.py` enforces this in CI. --backend sqlite --workers 2,4,8,16 --ops-per-worker 50 --read-ratio 0.7
- **Start the Gateway with `make dev` or `make gateway`.** `make dev` excludes uv run pytest tests/test_bench_concurrency.py tests/test_bench_worker.py -q
`DEER_FLOW_HOME` and `backend/sandbox` from the reload watcher. A bare ```
`uvicorn --reload` restarts the Gateway during a run, because agent tasks write
Python files below `DEER_FLOW_HOME`.
- **From the repository root, run backend tools with
`uv run --no-sync --project backend`.** `--project` keeps the caller's working
directory, so relative config paths still resolve. `--no-sync` keeps installed
extras such as the PostgreSQL drivers.
- **Run Python through `uv run` inside `backend/`**, without `--no-sync`, so the
environment matches the lock.
- **Guard POSIX-only test markers with `os.name`.** Windows collects the same
files.
- **Tool approvals need addressable calls.** Strip missing, empty and duplicate
tool-call IDs before creating a pause or a tool result. See the
[run interaction policy](docs/RUN_INTERACTION_POLICY.md#hitl-tool-approval).
- **Add a schema change with `make migrate-rev MSG="..."`** and follow the
migrations guide.
- **Notification preferences are a send-time trust boundary.** Malformed provider or per-event resolver output must fail closed and remain retryable without consuming an attempt; never treat malformed data as opt-in. ## Commands
Root orchestration and extension commands live in the
[root guide](../AGENTS.md#commands-root-vs-module); run them from the repo root.
`make detect-thread-boundaries` inventories backend executor, thread and event-loop
boundaries.
**Backend directory** (for backend development only):
```bash
make install # Install backend dependencies
make dev # Gateway API, reload (port 8001)
make gateway # Gateway API only (port 8001)
make test # four offline workers; TEST_JOBS=1 for serial
make test-live # live tests (real APIs)
make test-blocking-io # strict Blockbuster gate on tests/blocking_io/
make test-shard SPLITS=4 GROUP=2 # one duration-aware shard
make test-shard-durations # refresh baseline
make lint # ruff lint
make format # ruff format
make migrate-rev MSG="..." # Autogenerate a new alembic revision (see Schema Migrations section)
```
The backend `make dev` target pre-creates and excludes `DEER_FLOW_HOME`
(default: `backend/.deer-flow`) and `backend/sandbox` from Uvicorn's reload
watcher. Do not replace it with a bare `uvicorn --reload`: agent tasks write
Python and other runtime files below `DEER_FLOW_HOME`, which would otherwise
restart the Gateway during an active run.
Configuration checks and operator migration scripts reuse the installed backend
environment with `uv run --no-sync --project backend` from the repository root.
`--project` preserves the caller's working directory and relative runtime/config
selectors; `--no-sync` retains installed extras such as PostgreSQL drivers.
Read the nearest scoped `AGENTS.md` for subsystem ownership.
## Architecture
Read-only knowledge: [contract](docs/KNOWLEDGE.md) covers independent retrieval
tools, scope intersection and extension-owned providers.
### Harness / App Split
The backend is split into two layers with a strict dependency direction:
- **Harness** (`packages/harness/deerflow/`): Publishable agent framework package (`deerflow-harness`). Import prefix: `deerflow.*`. Contains agent orchestration, tools, sandbox, models, MCP, skills, config — everything needed to build and run agents.
- **App** (`app/`): Unpublished application code. Import prefix: `app.*`. Contains the FastAPI Gateway API and IM channel integrations (Feishu, Slack, Telegram, DingTalk). Feishu option clarifications can render as interactive button cards behind `channels.feishu.card_interaction_enabled` (default off); see `app/channels/AGENTS.md`.
Channel credential staging (`app/channels/credential_staging.py`) is swept on worker-thread state loads, including SQL legacy import. Only owned regular files older than 24h are removed; leave anonymous temporary files alone and keep WeChat constructors IO-free.
**Dependency rule**: App imports deerflow, but deerflow never imports app. This boundary is enforced by `tests/test_harness_boundary.py` which runs in CI.
**Import conventions**:
```python
# Harness internal
from deerflow.agents import make_lead_agent
from deerflow.models import create_chat_model
# App internal
from app.gateway.app import app
from app.channels.service import start_channel_service
# App → Harness (allowed)
from deerflow.config import get_app_config
# Harness → App (FORBIDDEN — enforced by test_harness_boundary.py)
# from app.gateway.routers.uploads import ... # ← will fail CI
```
Package import hygiene: the `deerflow.agents` and `deerflow.subagents` package
roots expose heavyweight graph/executor entrypoints lazily. The
`deerflow.agents:make_lead_agent` LangGraph Server entrypoint is a concrete thin
module-level function because the server resolves graph factories directly from
the module dictionary; the wrapper keeps the lead-agent and skill-cache imports
inside the function so importing the package remains lightweight. Internal
modules that only need lightweight types, config, or registries should import
the concrete submodule instead of adding eager package-root imports that pull in
the tool graph or subagent executor during state/schema imports.
`ThreadMetaStore.search()` keeps JSON filter semantics identical across memory,
SQLite, and PostgreSQL: missing differs from null, bool differs from int, and
float filters accept integer or real JSON numbers through `json_value_matches`.
### Gateway Run-Context Trust Boundary
Gate server-owned run context on both client feeds (`body.context` and
`body.config`): `merge_run_context_overrides` admits it only for `internal=True`,
while `strip_internal_context_keys` scrubs both destinations. A validated
`context.locale` (`en-US` / `zh-CN`) is a runtime-only language preference for
replies and memory writes; it never persists into checkpoint `configurable`,
and an explicit invalid/null top-level value clears a legacy preference. Treat
`disable_clarification` like `non_interactive`. Before run/state writes,
`_normalize_input_messages` rejects canonical external system/developer roles;
only `AUTH_SOURCE_INTERNAL` run input may retain them.
`contracts/ui_locales.v1.json` pins the UI/Gateway locale allowlists in tests;
DeerMem's portable map stays separate. Scheduled/MCP notification runs omit
locale; persisted owner locale is used for scheduled IM notices only.
`start_run` assigns IDs to ID-less messages before recording input or invoking
the graph; keyed retries keep those IDs stable, while the pre-stamp input
remains the idempotency identity. The record and checkpoint share IDs so
frontend reconnect can deduplicate the user's message.
## Development Workflow
### Test-Driven Development (TDD) — MANDATORY
**Every new feature or bug fix MUST be accompanied by unit tests. No exceptions.**
- Write tests in `backend/tests/` following the existing naming convention `test_<feature>.py`
- Run both offline targets before and after your change: `make test` and `make test-blocking-io`
- Tests must pass before a feature is considered complete
- For lightweight config/utility modules, prefer pure unit tests with no external dependencies
- If a module causes circular import issues in tests, add a `sys.modules` mock in `tests/conftest.py` (see existing example for `deerflow.subagents.executor`)
Keep live tests opt-in via `DEER_FLOW_RUN_LIVE_TESTS=1`; guard POSIX-only
markers with `os.name` for Windows collection.
Jina logging tests use dummy keys; the Jina redirect regression runs offline via `httpx.MockTransport` and keeps POST across temporary redirects; InfoQuest connect/read timeout is 30s, separate from crawl timeouts (`tests/test_jina_client.py`, `tests/test_infoquest_http_timeout.py`).
### Running the Full Application
Run `make dev` from the repo root to start all services at `http://localhost:2026`.
**All startup modes:**
| | **Local Foreground** | **Local Daemon** | **Docker Dev** | **Docker Prod** |
|---|---|---|---|---|
| **Dev** | `./scripts/serve.sh --dev`<br/>`make dev` | `./scripts/serve.sh --dev --daemon`<br/>`make dev-daemon` | `./scripts/docker.sh start`<br/>`make docker-start` | — |
| **Prod** | `./scripts/serve.sh --prod`<br/>`make start` | `./scripts/serve.sh --prod --daemon`<br/>`make start-daemon` | — | `./scripts/deploy.sh`<br/>`make up` |
| Action | Local | Docker Dev | Docker Prod |
|---|---|---|---|
| **Stop** | `./scripts/serve.sh --stop`<br/>`make stop` | `./scripts/docker.sh stop`<br/>`make docker-stop` | `./scripts/deploy.sh down`<br/>`make down` |
| **Restart** | `./scripts/serve.sh --restart [flags]` | `./scripts/docker.sh restart` | — |
### Running Backend Services Separately
From the **backend** directory:
```bash
# Gateway API
make gateway
```
Direct access (without nginx):
- Gateway: `http://localhost:8001`
### Frontend Configuration
The frontend uses environment variables to connect to backend services:
- `NEXT_PUBLIC_LANGGRAPH_BASE_URL` - Defaults to `/api/langgraph` (through nginx)
- `NEXT_PUBLIC_BACKEND_BASE_URL` - Defaults to empty string (through nginx)
When using `make dev` from root, the frontend automatically connects through nginx.
## Key Features
### Web Search Recency
Optional `web_search` `time_range=day|week|month|year` mappings:
DDG → `d|w|m|y`; Brave → `pd|pw|pm|py`; Tavily/SearXNG → unchanged;
Sofya → unchanged in `freshness`; Serper → `qdr:d|w|m|y` in `tbs`.
Omission preserves request shape; Serper null also omits `tbs`. Image search is unchanged.
DDGS 9.14.1 recency uses only enabled Brave/DuckDuckGo/Yahoo engines honoring
`timelimit`: `auto`/`all` selects this set; drop incompatible engines and fall back
to this set if empty. Re-check on DDGS upgrades.
### Tavily Fetch
Title fallback: result URL, then request URL.
### File Upload
Outlines use ATX syntax (1–6 hashes, space/tab separator, ≤3 leading spaces), strip closing hashes and skip fenced code; closing markers use a linear suffix scan — never unanchored whitespace regex on unbounded headings.
- Endpoint: `POST /api/threads/{thread_id}/uploads`; PDF/PPT/Excel/Word via `markitdown`, one conversion worker per request; directories rejected, keeping uploads all-or-nothing; duplicate filenames in one request get `_N` suffixes.
- Files live in thread-isolated `users/{user_id}/threads/{thread_id}/user-data/uploads` (IM channels thread the owner via the `user_id=` kwarg — see IM Channels → Owner-scoped file storage; HTTP/embedded callers resolve `get_effective_user_id()`); per-thread `upload-companions/` holds source mtime/ctime.
- Gateway HTTP uploads stage `.upload-*.part` files hidden from upload listings, agent context, and sandbox listings/searches; publication is atomic after size validation. Startup sweep keeps lone `.part` files under 24h (possibly in flight on another replica); `st_nlink > 1` means a published alias, removed at any age so the multi-link check can still replace the file.
- Upload/list/delete handlers offload filesystem work through `deerflow.utils.file_io.run_file_io` (ContextVar-preserving); non-mounted sandbox uploads use `SandboxProvider.acquire_async()` and offload `read_bytes()` + `sandbox.update_file()` together. Mounted uploads skip acquire/sync; AIO remote/provisioner requires accurate `sandbox.thread_data_mounts: true`, omission keeps backend auto-detection.
- `UploadsMiddleware` caps outline titles at 200 characters and previews at 2000 including markers. Titles use `original_user_content`; attachment-only titles use a sanitized, bounded filename or count.
See [docs/FILE_UPLOAD.md](docs/FILE_UPLOAD.md) for details.
### Plan Mode
`config.configurable.is_plan_mode=True` enables TodoList `write_todos` for
multi-step tasks: one `in_progress` task, real-time updates. See
[usage](docs/plan_mode_usage.md).
### Run Interaction Policy
Interaction-sensitive changes must follow [policy](docs/RUN_INTERACTION_POLICY.md).
### Context Summarization
Automatic conversation summarization when approaching token limits, configured
under the `summarization` key in `config.yaml` (triggers: tokens, messages, or
fraction of max input); recent messages are kept while older ones are summarized.
- Manual compaction uses `POST /api/threads/{id}/compact`, reuses the same `DeerFlowSummarizationMiddleware`, writes a new checkpoint with updated `messages`/`summary_text`, and bumps only those channel versions. The route uses the shared `reserve_checkpoint_write()` boundary (also used by manual state updates); its short-lived `checkpoint_write` operation shares the durable active-thread uniqueness constraint with run admission, preventing worker-local and cross-worker checkpoint-write races.
- Cache only first-candidate no-ops; never suppress primary retries with fallback results. See [reuse and telemetry](docs/summarization.md#reuse-and-telemetry) for cache and counter contracts.
See [docs/summarization.md](docs/summarization.md) for details.
### Vision Support
For models with `supports_vision: true`: `ViewImageMiddleware` processes images and adds `view_image_tool`. Images reach the model as base64 in a hidden message carrying a reserved ID prefix plus a server-owned metadata marker (Gateway strips the marker from untrusted input; the middleware requires both to recognize its own message). The injection happens inside `wrap_model_call`, so payloads never enter graph state — checkpoints keep only lightweight `viewed_images` metadata, and client-chosen IDs survive; the middleware also sweeps its own message out of every request before rebuilding it, so a payload stranded in an older checkpoint by an interrupted run stops being resent.
## Code Style
- Uses `ruff` for linting and formatting
- Line length: 240 characters
- Python 3.12+ with type hints
- Double quotes, space indentation
## Documentation
See `docs/` directory for detailed documentation:
- [CONFIGURATION.md](docs/CONFIGURATION.md) - Configuration options
- [ARCHITECTURE.md](docs/ARCHITECTURE.md) - Architecture details
- [API.md](docs/API.md) - API reference
- [SETUP.md](docs/SETUP.md) - Setup guide
- [FILE_UPLOAD.md](docs/FILE_UPLOAD.md) - File upload feature
- [PATH_EXAMPLES.md](docs/PATH_EXAMPLES.md) - Path types and usage
- [summarization.md](docs/summarization.md) - Context summarization
- [plan_mode_usage.md](docs/plan_mode_usage.md) - Plan mode with TodoList

View File

@ -19,15 +19,15 @@ dev:
gateway: gateway:
PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run --locked uvicorn app.gateway.app:app --host 127.0.0.1 --port 8001 PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run --locked uvicorn app.gateway.app:app --host 127.0.0.1 --port 8001
# Run all six duration-balanced shards locally (matching CI); wait for every shard on failure. # Run all four duration-balanced shards locally; wait for every shard on failure.
TEST_JOBS ?= 6 TEST_JOBS ?= 4
TEST_SHARD_TARGETS := test-shard-1 test-shard-2 test-shard-3 test-shard-4 test-shard-5 test-shard-6 TEST_SHARD_TARGETS := test-shard-1 test-shard-2 test-shard-3 test-shard-4
.PHONY: test test-shard test-bundled-extensions test-benchmark $(TEST_SHARD_TARGETS) .PHONY: test test-shard $(TEST_SHARD_TARGETS)
test: test:
$(MAKE) --no-print-directory -k -j$(TEST_JOBS) $(TEST_SHARD_TARGETS) $(MAKE) --no-print-directory -k -j$(TEST_JOBS) $(TEST_SHARD_TARGETS)
$(TEST_SHARD_TARGETS): $(TEST_SHARD_TARGETS):
$(MAKE) --no-print-directory test-shard SPLITS=6 GROUP=$(patsubst test-shard-%,%,$@) $(MAKE) --no-print-directory test-shard SPLITS=4 GROUP=$(patsubst test-shard-%,%,$@)
test-live: test-live:
DEER_FLOW_RUN_LIVE_TESTS=1 PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m live tests/ -v -s DEER_FLOW_RUN_LIVE_TESTS=1 PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m live tests/ -v -s
@ -41,35 +41,21 @@ test-blocking-io:
# read from .test_durations. Shards only READ that file (no --store-durations), # read from .test_durations. Shards only READ that file (no --store-durations),
# so concurrent CI jobs cannot race writes on it. Refresh it with # so concurrent CI jobs cannot race writes on it. Refresh it with
# `make test-shard-durations` after a meaningful change to the test set. # `make test-shard-durations` after a meaningful change to the test set.
# `make test-shard SPLITS=6 GROUP=2` runs shard 2 of 6; a bare `make test-shard` # `make test-shard SPLITS=4 GROUP=2` runs shard 2 of 4; a bare `make test-shard`
# runs the whole offline suite as a single split; `make test` runs all six shards. # runs the whole offline suite as a single split; `make test` runs all four shards.
SPLITS ?= 1 SPLITS ?= 1
GROUP ?= 1 GROUP ?= 1
DURATIONS_FILE ?= .test_durations DURATIONS_FILE ?= .test_durations
test-shard: test-shard:
@test -f "$(DURATIONS_FILE)" || \ @test -f "$(DURATIONS_FILE)" || \
(echo "error: $(DURATIONS_FILE) is missing; run 'make test-shard-durations' to regenerate the duration baseline" >&2; exit 1) (echo "error: $(DURATIONS_FILE) is missing; run 'make test-shard-durations' to regenerate the duration baseline" >&2; exit 1)
PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "not live and not bundled_extension and not benchmark" --ignore=tests/blocking_io --splits $(SPLITS) --group $(GROUP) --splitting-algorithm least_duration --durations-path=$(DURATIONS_FILE) tests/ -q PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "not live" --ignore=tests/blocking_io --splits $(SPLITS) --group $(GROUP) --splitting-algorithm least_duration --durations-path=$(DURATIONS_FILE) tests/ -q
# Regenerate .test_durations from the offline core suite (non-live, # Regenerate .test_durations from the full offline (non-live, non-blocking-I/O)
# non-blocking-I/O, non-bundled-extension, non-benchmark) so duration-aware # suite so duration-aware sharding reflects real wall-clock cost. Run locally or
# sharding reflects real wall-clock cost. Run locally or in a periodic job, then # in a periodic job, then commit the refreshed file.
# commit the refreshed file.
test-shard-durations: test-shard-durations:
PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "not live and not bundled_extension and not benchmark" --ignore=tests/blocking_io --store-durations --clean-durations --durations-path=$(DURATIONS_FILE) tests/ -q PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "not live" --ignore=tests/blocking_io --store-durations --clean-durations --durations-path=$(DURATIONS_FILE) tests/ -q
# Bundled extension examples own their behavior suites; the core shards exclude
# them so an optional example cannot fail an unrelated core PR. The extension CI
# workflow runs this target when an example, the extension contract or the
# bundled tests themselves change.
test-bundled-extensions:
PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "bundled_extension and not live" tests/ -q
# Offline benchmark script suites carry the `benchmark` marker; the core shards
# exclude them so benchmark harness scripts do not slow down unrelated core PRs.
# The benchmark CI workflow runs this target when benchmark scripts or tests change.
test-benchmark:
PYTHONPATH=. PYTHONIOENCODING=utf-8 PYTHONUTF8=1 uv run pytest -m "benchmark and not live" tests/ -q
lint: lint:
uv run ruff check . uv run ruff check .

View File

@ -54,10 +54,6 @@ The single LangGraph agent (`lead_agent`) is the runtime entry point, created vi
Middlewares execute in strict order, each handling a specific concern: Middlewares execute in strict order, each handling a specific concern:
Starting a new graph invocation resets tool-progress tracking. Results and model
retries still finishing from an earlier invocation cannot block its tools or
restore obsolete progress hints, including same-run goal continuations.
| # | Middleware | Purpose | | # | Middleware | Purpose |
|---|-----------|---------| |---|-----------|---------|
| 1 | **ThreadDataMiddleware** | Creates per-thread isolated directories (workspace, uploads, outputs) | | 1 | **ThreadDataMiddleware** | Creates per-thread isolated directories (workspace, uploads, outputs) |
@ -70,24 +66,14 @@ restore obsolete progress hints, including same-run goal continuations.
| 8 | **ViewImageMiddleware** | Injects image data for vision-capable models (conditional) | | 8 | **ViewImageMiddleware** | Injects image data for vision-capable models (conditional) |
| 9 | **ClarificationMiddleware** | Intercepts clarification requests and interrupts execution (must be last) | | 9 | **ClarificationMiddleware** | Intercepts clarification requests and interrupts execution (must be last) |
When `loop_detection.enabled` is set, loop detection checks repeated tool-call When `loop_detection.enabled` is set, loop detection checks both repeated
sets whose results show no progress. Warnings do not skip the rest of a tool-call sets and per-tool frequency. Warnings do not skip the rest of a
tool-call batch: a hash-based hard limit stops the entire batch before tool tool-call batch: any hard limit reached takes precedence and stops the entire
execution. Tool-name frequency is retained as an INFO observability metric for batch before tool execution. Warning-only batches remain fully counted and
workload and cost analysis; its thresholds never warn or stop a run. Warning- receive a transient hint on the next model request.
only batches remain fully counted and receive a transient hint on the next
model request.
### Sandbox System ### Sandbox System
With lazy initialization, a fresh AIO or OpenSandbox run prepares its
authorized Agent skill view without acquiring a sandbox until a sandbox-backed
tool needs one. OpenSandbox installs that view when the tool acquires the
remote. A run with existing sandbox state still rebinds eagerly. OpenSandbox
also synchronizes eagerly when another operation holds or is initializing the
thread's remote. Other upload-based providers acquire and synchronize skills
eagerly. Explicit sandbox prewarming remains a separate opt-in behavior.
Per-thread isolated execution with virtual path translation: Per-thread isolated execution with virtual path translation:
- **Abstract interface**: `execute_command`, `read_file`, `write_file`, `list_dir` - **Abstract interface**: `execute_command`, `read_file`, `write_file`, `list_dir`
@ -119,10 +105,6 @@ the same item or undo a pause/cancellation observed after their initial read.
### Memory System ### Memory System
If the local retrieval index is busy, read-only, or temporarily unavailable,
DeerMem falls back to substring search without deleting it. Automatic index
recreation is reserved for SQLite-confirmed corruption or a non-database file.
LLM-powered persistent context retention across conversations: LLM-powered persistent context retention across conversations:
- **Automatic extraction**: Analyzes conversations for user context, facts, and preferences - **Automatic extraction**: Analyzes conversations for user context, facts, and preferences
@ -174,8 +156,8 @@ to a boundary (SQLite) or causing the search to fail (PostgreSQL).
| `POST /api/skills/install` | Install skill from `.skill` archive | | `POST /api/skills/install` | Install skill from `.skill` archive |
| `GET /api/memory` | Retrieve memory data | | `GET /api/memory` | Retrieve memory data |
| `POST /api/memory/reload` | Force memory reload | | `POST /api/memory/reload` | Force memory reload |
| `GET /api/memory/config` | Memory configuration; credential values in `backend_config` are masked | | `GET /api/memory/config` | Memory configuration |
| `GET /api/memory/status` | Combined config (masked the same way) + data | | `GET /api/memory/status` | Combined config + data |
| `GET /api/threads/{id}/runs/{run_id}/events` | Debug/audit events for one run; filter `event_types=context:memory` for effective memory identity | | `GET /api/threads/{id}/runs/{run_id}/events` | Debug/audit events for one run; filter `event_types=context:memory` for effective memory identity |
| `POST /api/threads/{id}/uploads` | Upload files (optional PDF/PPT/Excel/Word-to-Markdown conversion, rejects directory paths, auto-renames duplicate filenames in one request) | | `POST /api/threads/{id}/uploads` | Upload files (optional PDF/PPT/Excel/Word-to-Markdown conversion, rejects directory paths, auto-renames duplicate filenames in one request) |
| `GET /api/threads/{id}/uploads/list` | List uploaded files | | `GET /api/threads/{id}/uploads/list` | List uploaded files |
@ -555,8 +537,7 @@ the only execution path, which keeps operational mistakes off the table. See
### Testing ### Testing
```bash ```bash
# Default offline backend suite (six parallel shards matching CI; excludes live, # Default offline backend suite (four parallel shards; excludes live and blocking-I/O tests)
# blocking-I/O, bundled-extension and benchmark tests)
make test make test
# Run the same shards sequentially # Run the same shards sequentially

View File

@ -126,8 +126,8 @@ FastAPI 应用程序,为前端集成提供 REST 接口:
| `POST /api/skills/install` | 从 `.skill` 归档文件安装技能 | | `POST /api/skills/install` | 从 `.skill` 归档文件安装技能 |
| `GET /api/memory` | 获取记忆数据 | | `GET /api/memory` | 获取记忆数据 |
| `POST /api/memory/reload` | 强制重新加载记忆 | | `POST /api/memory/reload` | 强制重新加载记忆 |
| `GET /api/memory/config` | 获取记忆配置;`backend_config` 中的凭据值会被遮蔽 | | `GET /api/memory/config` | 获取记忆配置 |
| `GET /api/memory/status` | 获取组合后的配置(同样遮蔽凭据)和数据状态 | | `GET /api/memory/status` | 获取组合后的配置和数据状态 |
| `GET /api/threads/{id}/runs/{run_id}/events` | 获取某次运行的调试或审计事件;可使用 `event_types=context:memory` 筛选实际记忆标识 | | `GET /api/threads/{id}/runs/{run_id}/events` | 获取某次运行的调试或审计事件;可使用 `event_types=context:memory` 筛选实际记忆标识 |
| `POST /api/threads/{id}/uploads` | 上传文件(可选地将 PDF、PPT、Excel、Word 转换为 Markdown;拒绝目录路径;自动重命名单次请求中的重复文件名) | | `POST /api/threads/{id}/uploads` | 上传文件(可选地将 PDF、PPT、Excel、Word 转换为 Markdown;拒绝目录路径;自动重命名单次请求中的重复文件名) |
| `GET /api/threads/{id}/uploads/list` | 列出已上传的文件 | | `GET /api/threads/{id}/uploads/list` | 列出已上传的文件 |

File diff suppressed because one or more lines are too long

View File

@ -250,12 +250,7 @@ class Channel(ABC):
log_prefix: str | None = None, log_prefix: str | None = None,
operation_name: str = "send", operation_name: str = "send",
) -> T: ) -> T:
"""Run an outbound send operation with the shared channel retry policy. """Run an outbound send operation with the shared channel retry policy."""
The wait between attempts is ``_outbound_retry_delay``. The default
is ``2**attempt``; a provider that is told how long to wait overrides
that without changing the attempt bound or the other channels.
"""
prefix = log_prefix or f"[{self.name}]" prefix = log_prefix or f"[{self.name}]"
last_exc: Exception | None = None last_exc: Exception | None = None
for attempt in range(max_retries): for attempt in range(max_retries):
@ -264,9 +259,9 @@ class Channel(ABC):
except Exception as exc: except Exception as exc:
last_exc = exc last_exc = exc
if attempt < max_retries - 1: if attempt < max_retries - 1:
delay = self._outbound_retry_delay(attempt, exc) delay = 2**attempt
logger.warning( logger.warning(
"%s %s failed (attempt %d/%d), retrying in %ss: %s", "%s %s failed (attempt %d/%d), retrying in %ds: %s",
prefix, prefix,
operation_name, operation_name,
attempt + 1, attempt + 1,
@ -281,16 +276,6 @@ class Channel(ABC):
raise RuntimeError(f"{self.name} {operation_name} failed without an exception from any attempt") raise RuntimeError(f"{self.name} {operation_name} failed without an exception from any attempt")
raise last_exc raise last_exc
def _outbound_retry_delay(self, attempt: int, exc: Exception) -> float:
"""Seconds to wait before the next attempt.
``exc`` is the failure just caught. The shared policy ignores it and
sleeps ``2**attempt`` (1s, then 2s, then 4s, ...). A provider that
receives a server wait hint overrides this and may return a longer
delay; it must not shorten the local backoff.
"""
return 2**attempt
def _log_future_error(self, fut: Any, name: str, msg_id: Any) -> None: def _log_future_error(self, fut: Any, name: str, msg_id: Any) -> None:
"""Callback for concurrent futures scheduled from channel worker threads.""" """Callback for concurrent futures scheduled from channel worker threads."""
try: try:

View File

@ -8,9 +8,6 @@ required.
from __future__ import annotations from __future__ import annotations
FEISHU_TASK_COMMAND = "/task"
FEISHU_TASK_START_SUBCOMMAND = "start"
KNOWN_CHANNEL_COMMANDS: frozenset[str] = frozenset( KNOWN_CHANNEL_COMMANDS: frozenset[str] = frozenset(
{ {
"/agent", "/agent",
@ -92,11 +89,3 @@ def is_known_channel_command(text: str) -> bool:
if not text.startswith("/"): if not text.startswith("/"):
return False return False
return text.split(maxsplit=1)[0].lower() in KNOWN_CHANNEL_COMMANDS return text.split(maxsplit=1)[0].lower() in KNOWN_CHANNEL_COMMANDS
def is_feishu_task_command(text: str) -> bool:
"""Return whether text starts with the Feishu ``/task start`` control command."""
if not text.startswith("/"):
return False
parts = text.split(maxsplit=2)
return len(parts) >= 2 and parts[0].lower() == FEISHU_TASK_COMMAND and parts[1].lower() == FEISHU_TASK_START_SUBCOMMAND

View File

@ -44,17 +44,6 @@ async def attach_connection_identity(
return inbound return inbound
def fallback_store_channel(channel_name: str, topic_id: str | None, repo: Any) -> str:
"""Select the binding namespace for a topic without a connection.
Feishu deployments using connection identities keep unbound topics in a
separate namespace. Room bindings and legacy deployments use the channel name.
"""
if channel_name == "feishu" and topic_id and repo is not None:
return "feishu-unbound"
return channel_name
async def lookup_thread_id(msg: InboundMessage, *, repo: Any, store: Any) -> str | None: async def lookup_thread_id(msg: InboundMessage, *, repo: Any, store: Any) -> str | None:
"""Return the DeerFlow thread mapped to *msg*'s conversation/topic, if any. """Return the DeerFlow thread mapped to *msg*'s conversation/topic, if any.
@ -69,23 +58,4 @@ async def lookup_thread_id(msg: InboundMessage, *, repo: Any, store: Any) -> str
return await repo.get_thread_id(msg.connection_id, msg.chat_id, msg.topic_id) return await repo.get_thread_id(msg.connection_id, msg.chat_id, msg.topic_id)
if store is None: if store is None:
return None return None
return await store.get_thread_id(fallback_store_channel(msg.channel_name, msg.topic_id, repo), msg.chat_id, topic_id=msg.topic_id) return await store.get_thread_id(msg.channel_name, msg.chat_id, topic_id=msg.topic_id)
def feishu_private_binding(connection: dict) -> dict[str, str] | None:
"""Return the exact live Feishu DM binding, including its revocation fence."""
if connection.get("provider") != "feishu" or connection.get("status") != "connected":
return None
metadata = connection.get("metadata")
if not isinstance(metadata, dict):
return None
chat_id = metadata.get("chat_id")
if metadata.get("chat_type") != "p2p" or not chat_id or connection.get("workspace_id") != chat_id:
return None
return {
"provider": "feishu",
"id": connection["id"],
"updated_at": connection["updated_at"],
"chat_id": chat_id,
"account_id": connection["external_account_id"],
}

View File

@ -10,7 +10,6 @@ import re
import stat import stat
import threading import threading
import time import time
import uuid
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from urllib.parse import quote_plus from urllib.parse import quote_plus
@ -113,23 +112,26 @@ def _extract_text_from_rich_text(rich_text_list: list) -> str:
_FENCED_CODE_BLOCK_RE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL) _FENCED_CODE_BLOCK_RE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
# Match complete backtick runs of equal length so shorter runs stay inside the code. _INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")
_INLINE_CODE_RE = re.compile(r"(?<!`)(?P<delimiter>`+)(?!`)(?P<code>[^\n]+?)(?<!`)(?P=delimiter)(?!`)")
_HORIZONTAL_RULE_RE = re.compile(r"^-{3,}$", re.MULTILINE) _HORIZONTAL_RULE_RE = re.compile(r"^-{3,}$", re.MULTILINE)
_TABLE_SEPARATOR_RE = re.compile(r"^\|[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|$", re.MULTILINE) _TABLE_SEPARATOR_RE = re.compile(r"^\|[-:| ]+\|$", re.MULTILINE)
def _split_markdown_table_row(row: str) -> list[str]: def _split_markdown_table_row(row: str) -> list[str]:
"""Split at unescaped pipes, preserving the original cell text.""" r"""Keep escaped pipes and empty cells when removing the outer borders.
row = row.strip()
cells = [] Known boundary: the single-character lookbehind in the split pattern
start = 0 cannot distinguish an escaped pipe (``\|``) from an escaped backslash
# Consume backslash escapes in pairs so only an unescaped pipe ends a cell. immediately followed by a real separator (``\\|``). A cell ending in a
for match in re.finditer(r"\\.|[|]", row): literal backslash therefore absorbs the next cell: ``| foo\\ | bar |``
if match[0] == "|": splits as one cell instead of two. GFM counts consecutive backslashes
cells.append(row[start : match.start()]) for this reason; doing so is out of scope here — this helper is
start = match.end() intentionally not a general Markdown parser.
cells.append(row[start:]) """
# ``(?<!\\)`` inspects only one preceding character, so the second
# backslash of ``\\|`` is mistaken for an escaping backslash and the
# pipe is kept whole. See the boundary note in the docstring above.
cells = re.split(r"(?<!\\)\|", row.strip())
if cells and cells[0] == "": if cells and cells[0] == "":
cells.pop(0) cells.pop(0)
if cells and cells[-1] == "": if cells and cells[-1] == "":
@ -147,10 +149,6 @@ def _convert_markdown_table(text: str) -> str:
# Detect table: header row followed by separator row # Detect table: header row followed by separator row
if i + 1 < len(lines) and line.strip().startswith("|") and _TABLE_SEPARATOR_RE.match(lines[i + 1].strip()): if i + 1 < len(lines) and line.strip().startswith("|") and _TABLE_SEPARATOR_RE.match(lines[i + 1].strip()):
headers = _split_markdown_table_row(line) headers = _split_markdown_table_row(line)
if len(headers) != len(_split_markdown_table_row(lines[i + 1])):
result.append(line)
i += 1
continue
i += 2 # skip header + separator i += 2 # skip header + separator
while i < len(lines) and lines[i].strip().startswith("|"): while i < len(lines) and lines[i].strip().startswith("|"):
cells = _split_markdown_table_row(lines[i]) cells = _split_markdown_table_row(lines[i])
@ -174,15 +172,8 @@ def _adapt_markdown_for_dingtalk(text: str) -> str:
quoted_lines = "\n".join(f"> {line}" for line in code.split("\n")) quoted_lines = "\n".join(f"> {line}" for line in code.split("\n"))
return f"{prefix}{quoted_lines}\n" return f"{prefix}{quoted_lines}\n"
def _inline_code_to_bold(match: re.Match) -> str:
code = match.group("code")
# CommonMark drops one padding space from each end of a nonblank span.
if code.startswith(" ") and code.endswith(" ") and code.strip(" "):
code = code[1:-1]
return f"**{code}**"
text = _FENCED_CODE_BLOCK_RE.sub(_code_block_to_quote, text) text = _FENCED_CODE_BLOCK_RE.sub(_code_block_to_quote, text)
text = _INLINE_CODE_RE.sub(_inline_code_to_bold, text) text = _INLINE_CODE_RE.sub(r"**\1**", text)
text = _convert_markdown_table(text) text = _convert_markdown_table(text)
text = _HORIZONTAL_RULE_RE.sub("───────────", text) text = _HORIZONTAL_RULE_RE.sub("───────────", text)
return text return text
@ -211,6 +202,7 @@ class DingTalkChannel(Channel):
self._stream_lock = threading.Lock() self._stream_lock = threading.Lock()
self._incoming_messages: dict[str, Any] = {} self._incoming_messages: dict[str, Any] = {}
self._incoming_messages_lock = threading.Lock() self._incoming_messages_lock = threading.Lock()
self._card_repliers: dict[str, Any] = {}
# Serialize inbound-file writes into the uploads directory to avoid # Serialize inbound-file writes into the uploads directory to avoid
# racing writers clobbering one another (mirrors FeishuChannel). # racing writers clobbering one another (mirrors FeishuChannel).
self._file_write_lock = threading.Lock() self._file_write_lock = threading.Lock()
@ -271,6 +263,7 @@ class DingTalkChannel(Channel):
self._dingtalk_client = None self._dingtalk_client = None
with self._incoming_messages_lock: with self._incoming_messages_lock:
self._incoming_messages.clear() self._incoming_messages.clear()
self._card_repliers.clear()
self._card_track_ids.clear() self._card_track_ids.clear()
if self._thread: if self._thread:
# The thread exits once its loop has stopped; keep the join off the # The thread exits once its loop has stopped; keep the join off the
@ -358,10 +351,12 @@ class DingTalkChannel(Channel):
logger.warning("[DingTalk] card stream failed, falling back to sampleMarkdown") logger.warning("[DingTalk] card stream failed, falling back to sampleMarkdown")
if msg.is_final: if msg.is_final:
self._card_track_ids.pop(source_key, None) self._card_track_ids.pop(source_key, None)
self._card_repliers.pop(out_track_id, None)
await self._send_markdown_fallback(robot_code, conversation_type, sender_staff_id, conversation_id, msg.text) await self._send_markdown_fallback(robot_code, conversation_type, sender_staff_id, conversation_id, msg.text)
return return
if msg.is_final: if msg.is_final:
self._card_track_ids.pop(source_key, None) self._card_track_ids.pop(source_key, None)
self._card_repliers.pop(out_track_id, None)
return return
async def send_markdown() -> None: async def send_markdown() -> None:
@ -446,24 +441,6 @@ class DingTalkChannel(Channel):
}, },
) )
response.raise_for_status() response.raise_for_status()
data = response.json()
process_key = data.get("processQueryKey") if isinstance(data, dict) else None
if not isinstance(process_key, str) or not process_key.strip():
logger.warning(
"[DingTalk] file send response missing processQueryKey for %s; treating as not delivered",
attachment.filename,
)
return False
if conversation_type != _CONVERSATION_TYPE_GROUP:
target = sender_staff_id
for field in ("invalidStaffIdList", "flowControlledStaffIdList"):
failed = data.get(field, [])
if not isinstance(failed, list):
logger.warning("[DingTalk] unexpected %s in file send response for %s", field, attachment.filename)
return False
if target in failed:
logger.warning("[DingTalk] file not delivered for %s (%s)", attachment.filename, field)
return False
logger.info("[DingTalk] file sent: %s", attachment.filename) logger.info("[DingTalk] file sent: %s", attachment.filename)
return True return True
@ -1267,42 +1244,30 @@ class DingTalkChannel(Channel):
logger.warning("[DingTalk] SDK client or chatbot_message unavailable, skipping AI card") logger.warning("[DingTalk] SDK client or chatbot_message unavailable, skipping AI card")
return None return None
out_track_id = uuid.uuid4().hex
try: try:
await self._card_request("POST", "/v1.0/card/instances/createAndDeliver", self._card_create_body(out_track_id, chatbot_message, initial_text)) from dingtalk_stream.card_replier import AICardReplier
except ImportError:
logger.warning("[DingTalk] dingtalk-stream card_replier not available")
return None
try:
token_client = _CardTokenClient(self._dingtalk_client.credential)
token_client.access_token = await self._get_access_token()
replier = AICardReplier(token_client, chatbot_message)
card_instance_id = await replier.async_create_and_deliver_card(
card_template_id=self._card_template_id,
card_data={"content": initial_text},
)
if not card_instance_id:
return None
self._card_repliers[card_instance_id] = replier
logger.info("[DingTalk] AI card created: outTrackId=%s", card_instance_id)
return card_instance_id
except Exception: except Exception:
logger.exception("[DingTalk] failed to create AI card") logger.exception("[DingTalk] failed to create AI card")
return None return None
logger.info("[DingTalk] AI card created: outTrackId=%s", out_track_id)
return out_track_id
def _card_create_body(self, out_track_id: str, chatbot_message: Any, initial_text: str) -> dict[str, Any]:
"""The ``createAndDeliver`` body dingtalk-stream's ``AICardReplier`` sends."""
body: dict[str, Any] = {
"cardTemplateId": self._card_template_id,
"outTrackId": out_track_id,
"cardData": {"cardParamMap": {"content": initial_text}},
"callbackType": "STREAM",
"imGroupOpenSpaceModel": {"supportForward": True},
"imRobotOpenSpaceModel": {"supportForward": True},
}
hosting_context = getattr(chatbot_message, "hosting_context", None)
conversation_type = str(chatbot_message.conversation_type)
if conversation_type == _CONVERSATION_TYPE_GROUP:
body["openSpaceId"] = f"dtv1.card//IM_GROUP.{chatbot_message.conversation_id}"
deliver_model: dict[str, Any] = {"robotCode": self._client_id}
body["imGroupOpenDeliverModel"] = deliver_model
elif conversation_type == _CONVERSATION_TYPE_P2P:
body["openSpaceId"] = f"dtv1.card//IM_ROBOT.{chatbot_message.sender_staff_id}"
deliver_model = {"spaceType": "IM_ROBOT"}
body["imRobotOpenDeliverModel"] = deliver_model
else:
return body
if hosting_context is not None:
deliver_model["extension"] = {"hostingRepliedContext": json.dumps({"userId": hosting_context.user_id})}
return body
async def _stream_update_card( async def _stream_update_card(
self, self,
out_track_id: str, out_track_id: str,
@ -1311,35 +1276,20 @@ class DingTalkChannel(Channel):
is_finalize: bool = False, is_finalize: bool = False,
is_error: bool = False, is_error: bool = False,
) -> None: ) -> None:
await self._card_request( replier = self._card_repliers.get(out_track_id)
"PUT", if not replier:
"/v1.0/card/streaming", raise RuntimeError(f"No AICardReplier found for track ID {out_track_id}")
{
"outTrackId": out_track_id, replier.dingtalk_client.access_token = await self._get_access_token()
"guid": str(uuid.uuid4()), await replier.async_streaming(
"key": "content", card_instance_id=out_track_id,
"content": content, content_key="content",
"isFull": True, content_value=content,
"isFinalize": is_finalize, append=False,
"isError": is_error, finished=is_finalize,
}, failed=is_error,
) )
async def _card_request(self, method: str, path: str, body: dict[str, Any]) -> None:
"""Send an AI card request with the channel token; raise if it fails.
dingtalk-stream's ``AICardReplier`` logs a failed card request and
returns as if it succeeded; its create call even returns the card ID.
Neither the running reply's text fallback nor the sampleMarkdown
fallback in ``send`` could then run, so the reply was lost.
"""
token = await self._get_access_token()
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
response = await client.request(method, f"{DINGTALK_API_BASE}{path}", headers=self._api_headers(token), json=body)
if response.is_error:
logger.warning("[DingTalk] card request %s %s returned %s: %s", method, path, response.status_code, response.text[:500])
response.raise_for_status()
# -- media upload -------------------------------------------------------- # -- media upload --------------------------------------------------------
async def _upload_media(self, file_path: str | Path, media_type: str) -> str | None: async def _upload_media(self, file_path: str | Path, media_type: str) -> str | None:
@ -1368,6 +1318,26 @@ class DingTalkChannel(Channel):
return None return None
class _CardTokenClient:
"""The client ``AICardReplier`` sees: it serves the channel's access token.
The replier's async methods call ``dingtalk_client.get_access_token()``
inline, and dingtalk-stream's version refreshes through ``requests.post``
with no timeout, so on the Gateway loop every refresh (about every two
hours) blocked the loop for the whole request, indefinitely if DingTalk
stalled. The channel sets ``access_token`` from its own bounded
``_get_access_token()`` before every replier call, so the replier never
fetches a token itself.
"""
def __init__(self, credential: Any) -> None:
self.credential = credential
self.access_token = ""
def get_access_token(self) -> str:
return self.access_token
class _DingTalkMessageHandler: class _DingTalkMessageHandler:
"""Callback handler registered with dingtalk-stream.""" """Callback handler registered with dingtalk-stream."""

View File

@ -6,11 +6,10 @@ import asyncio
import io import io
import json import json
import logging import logging
import re
import threading import threading
from concurrent.futures import Future from concurrent.futures import Future
from pathlib import Path from pathlib import Path
from typing import Any, NamedTuple from typing import Any
from urllib.parse import urlsplit from urllib.parse import urlsplit
import httpx import httpx
@ -29,146 +28,12 @@ from app.channels.message_bus import (
OutboundMessage, OutboundMessage,
ResolvedAttachment, ResolvedAttachment,
) )
from deerflow.utils.atomic_write import publish_bytes_atomically
from deerflow.utils.file_io import await_drained from deerflow.utils.file_io import await_drained
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_DISCORD_MAX_MESSAGE_LEN = 2000 _DISCORD_MAX_MESSAGE_LEN = 2000
# Discord's client does not follow CommonMark for code blocks. A block starts
# at a run of three backticks anywhere in a line, takes a language tag only when
# a line break follows it directly, and ends at the next three backticks, even
# right after the last code text. There are no tilde fences, and a longer run
# does not nest a shorter one. A backslash escapes a backtick outside a block.
# The pattern mirrors the client's code-block rule; a run with nothing but
# line breaks before the next run opens no block. The client's parser turns
# CRLF and a lone CR into LF first, so each counts as one line break here.
_CODE_FENCE = "```"
_LINE_BREAK = r"(?:\r\n?|\n)"
_CODE_BLOCK_RE = re.compile(rf"```(?:([a-z0-9_+\-.#]+?){_LINE_BREAK})?{_LINE_BREAK}*([^\r\n][\s\S]*?){_LINE_BREAK}*```", re.IGNORECASE)
_CODE_LANGUAGE_RE = re.compile(rf"([a-z0-9_+\-.#]+?){_LINE_BREAK}", re.IGNORECASE)
_FENCE_OR_ESCAPE_RE = re.compile(r"\\[^0-9A-Za-z\s]|```")
_CODE_FENCE_RE = re.compile(_CODE_FENCE)
# Appended to a message that ends inside a block; the client drops the line
# break before the closing run.
_CODE_FENCE_CLOSE_LEN = len("\n" + _CODE_FENCE)
class _CodeBlock(NamedTuple):
"""A code block of the reply as Discord renders the whole reply."""
start: int # index of the opening run
end: int | None # index after the closing run; None when the reply never closes it
opener: str # the opening run and its language tag, repeated to reopen the block
def _code_blocks(text: str) -> list[_CodeBlock]:
"""The code blocks of *text*, in order.
Parsed once over the whole reply: which run closes a block can depend on
text far past a split, so a single message cannot tell.
"""
blocks: list[_CodeBlock] = []
pos = 0
while (match := _FENCE_OR_ESCAPE_RE.search(text, pos)) is not None:
start = match.start()
if match.group() != _CODE_FENCE:
pos = match.end()
continue
if (block := _CODE_BLOCK_RE.match(text, start)) is not None:
blocks.append(_CodeBlock(start, block.end(), _CODE_FENCE + (block.group(1) or "")))
pos = block.end()
continue
if text.find(_CODE_FENCE, start + len(_CODE_FENCE)) < 0:
language = _CODE_LANGUAGE_RE.match(text, start + len(_CODE_FENCE))
blocks.append(_CodeBlock(start, None, _CODE_FENCE + (language.group(1) if language else "")))
break
# An empty block is plain text; a later run may still open one.
pos = start + 1
return blocks
def _block_at(blocks: list[_CodeBlock], index: int) -> _CodeBlock | None:
"""The block that a cut of the reply at *index* falls inside."""
for block in blocks:
if block.start >= index:
break
if block.end is None or index < block.end:
return block
return None
def _fence_is_carried(block: _CodeBlock | None) -> bool:
"""Whether a split closes *block* and reopens it in the next message.
The added lines must leave most of the next message for content; a longer
language tag is split like plain text.
"""
return block is not None and len(block.opener) + 1 + _CODE_FENCE_CLOSE_LEN <= _DISCORD_MAX_MESSAGE_LEN // 4
def _close_code_block(piece: str) -> str:
return piece + ("" if piece.endswith("\n") else "\n") + _CODE_FENCE
def _hard_split_point(text: str, start: int, budget: int) -> int:
"""Cut *text* *budget* characters after *start*, moved back so it splits no backtick run, escape or CRLF.
Any of these cuts would change which runs open and close code blocks.
"""
split_at = start + budget
while split_at > start and (text[split_at - 1] == "\\" or text[split_at - 1 : split_at + 1] in ("``", "\r\n")):
split_at -= 1
return split_at if split_at > start else start + budget
def _line_split_point(text: str, start: int, budget: int) -> int:
"""Where to end a message of *text* from *start* within *budget* characters, preferring a line break."""
split_at = text.rfind("\n", start, start + budget)
if split_at <= start:
return _hard_split_point(text, start, budget)
# Keep the delimiter on this chunk's tail so consecutive Discord messages
# reconstruct the original text exactly.
return split_at + 1
def _next_split(text: str, start: int, budget: int, blocks: list[_CodeBlock]) -> tuple[int, _CodeBlock | None]:
"""Where to end the message of *text* that starts at *start*, and the block open there.
*budget* is the room left after any reopened language tag.
"""
split_at = _line_split_point(text, start, budget)
block = _block_at(blocks, split_at)
if not _fence_is_carried(block):
return split_at, block
# The cut falls inside a block, which this message closes and the next one
# reopens. Take the latest line end or closing run where this message's
# block holds code after its language tag and the reopened one will too. A
# block opening on the message's last line, or a cut just before the block's
# own closing run, would leave one of them empty: Discord shows an empty
# block as plain backticks, or its language tag as the code.
end = start + budget
candidates = {index + 1 for index in range(start, end) if text[index] == "\n"}
candidates.update(run.end() for run in _CODE_FENCE_RE.finditer(text, start, end))
for candidate in sorted(candidates, reverse=True):
block = _block_at(blocks, candidate)
if not _fence_is_carried(block):
return candidate, block
holds_code = text[max(start, block.start + len(block.opener)) : candidate].strip("\r\n")
next_holds_code = block.end is None or text[candidate : block.end - len(_CODE_FENCE)].strip("\r\n")
if candidate <= end - _CODE_FENCE_CLOSE_LEN and holds_code and next_holds_code:
return candidate, block
# The block's first line in this message does not fit: cut into it.
split_at = _hard_split_point(text, start, budget - _CODE_FENCE_CLOSE_LEN)
block = _block_at(blocks, split_at)
if _fence_is_carried(block) and block.start > start and not text[block.start + len(block.opener) : split_at].strip("\r\n"):
# The cut lands in the block's opening run or language tag, or before its
# first code: end the message before the opening run instead.
return block.start, None
return split_at, block
# Bound for outbound work scheduled onto the Discord client's event loop. # Bound for outbound work scheduled onto the Discord client's event loop.
# Discord API calls normally return in well under a second; anything still # Discord API calls normally return in well under a second; anything still
# pending after this is a dead or wedged client, not a slow response. # pending after this is a dead or wedged client, not a slow response.
@ -410,10 +275,7 @@ class DiscordChannel(Channel):
try: try:
snapshot = dict(self._active_threads) snapshot = dict(self._active_threads)
self._thread_store_path.parent.mkdir(parents=True, exist_ok=True) self._thread_store_path.parent.mkdir(parents=True, exist_ok=True)
# Publish through the shared helper: it fsyncs the staged bytes self._thread_store_path.write_text(json.dumps(snapshot, indent=2), encoding="utf-8", newline="")
# before the rename (so a machine crash cannot leave an empty
# mapping behind) and re-applies an existing file's mode.
publish_bytes_atomically(self._thread_store_path, json.dumps(snapshot, indent=2).encode("utf-8"))
except Exception: except Exception:
logger.exception("[Discord] failed to persist thread mappings") logger.exception("[Discord] failed to persist thread mappings")
@ -1454,33 +1316,23 @@ class DiscordChannel(Channel):
@staticmethod @staticmethod
def _split_text(text: str) -> list[str]: def _split_text(text: str) -> list[str]:
"""Split *text* into messages within Discord's length limit.
Splits prefer line breaks. A code block that a split cuts is closed at
the end of the message and reopened with its language tag at the start
of the next, so both halves render as code. Apart from those added
fences, the messages join back to *text*.
"""
if not text: if not text:
return [""] return [""]
chunks: list[str] = [] chunks: list[str] = []
blocks = _code_blocks(text) remaining = text
start = 0 while len(remaining) > _DISCORD_MAX_MESSAGE_LEN:
reopen = "" # the language tag line of a block carried into this message split_at = remaining.rfind("\n", 0, _DISCORD_MAX_MESSAGE_LEN)
while True: if split_at <= 0:
budget = _DISCORD_MAX_MESSAGE_LEN - len(reopen) split_at = _DISCORD_MAX_MESSAGE_LEN
if len(text) - start <= budget:
chunks.append(reopen + text[start:])
break
split_at, block = _next_split(text, start, budget, blocks)
chunk = reopen + text[start:split_at]
if _fence_is_carried(block):
chunks.append(_close_code_block(chunk))
reopen = f"{block.opener}\n"
else: else:
chunks.append(chunk) # Keep the delimiter on this chunk's tail so consecutive
reopen = "" # Discord messages reconstruct the original text exactly.
start = split_at split_at += 1
chunks.append(remaining[:split_at])
remaining = remaining[split_at:]
if remaining:
chunks.append(remaining)
return chunks return chunks

View File

@ -13,14 +13,12 @@ from collections import deque
from collections.abc import Callable, Coroutine from collections.abc import Callable, Coroutine
from concurrent.futures import CancelledError as FutureCancelledError from concurrent.futures import CancelledError as FutureCancelledError
from concurrent.futures import Future from concurrent.futures import Future
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field
from io import BytesIO
from pathlib import PurePosixPath
from typing import Any, Literal, TypeVar from typing import Any, Literal, TypeVar
from app.channels.base import Channel, ChannelStopTimeout, ChannelUnavailable, abort_connection_transport, shutdown_private_loop from app.channels.base import Channel, ChannelStopTimeout, ChannelUnavailable, abort_connection_transport, shutdown_private_loop
from app.channels.commands import is_feishu_task_command, is_known_channel_command, strip_leading_mentions from app.channels.commands import is_known_channel_command, strip_leading_mentions
from app.channels.connection_identity import attach_connection_identity, fallback_store_channel, lookup_thread_id from app.channels.connection_identity import attach_connection_identity, lookup_thread_id
from app.channels.feishu_card_interaction import ( from app.channels.feishu_card_interaction import (
ClarificationCardRequest, ClarificationCardRequest,
PendingCardEntry, PendingCardEntry,
@ -57,9 +55,6 @@ PENDING_CLARIFICATION_TTL_SECONDS = 30 * 60
FEISHU_STOP_TIMEOUT_SECONDS = 5 FEISHU_STOP_TIMEOUT_SECONDS = 5
FEISHU_WS_CLOSE_TIMEOUT_SECONDS = 2 FEISHU_WS_CLOSE_TIMEOUT_SECONDS = 2
_PENDING_CARD_METADATA_KEY = "_feishu_pending_card_id" _PENDING_CARD_METADATA_KEY = "_feishu_pending_card_id"
# Number of attachments from a post's top-level ``files`` array.
_POST_FILES_COUNT_METADATA_KEY = "_feishu_post_files_count"
_DEFER_POST_FILE_PLACEHOLDERS_METADATA_KEY = "_feishu_defer_post_file_placeholders"
# Channel-store deadlines. ``_on_message`` runs on lark-oapi's private event loop, # Channel-store deadlines. ``_on_message`` runs on lark-oapi's private event loop,
# which also carries the SDK's websocket reads, pongs and its 120s ping loop: # which also carries the SDK's websocket reads, pongs and its 120s ping loop:
# every second the bridge blocks that loop is a second the connection cannot # every second the bridge blocks that loop is a second the connection cannot
@ -112,7 +107,6 @@ class _ParsedMessage:
chat_type: str | None chat_type: str | None
text: str text: str
files: list[dict[str, Any]] files: list[dict[str, Any]]
post_file_count: int = 0
msg_type: InboundMessageType = InboundMessageType.CHAT msg_type: InboundMessageType = InboundMessageType.CHAT
@ -124,9 +118,6 @@ class _Routing:
from_stored_mapping: bool from_stored_mapping: bool
from_pending: bool from_pending: bool
clarification_card_id: str | None = None clarification_card_id: str | None = None
connection_id: str | None = None
owner_user_id: str | None = None
workspace_id: str | None = None
@dataclass(slots=True) @dataclass(slots=True)
@ -153,189 +144,10 @@ class _RoutingAttempt:
FEISHU_INBOUND_BATCH_WINDOW_SECONDS = 0.75 FEISHU_INBOUND_BATCH_WINDOW_SECONDS = 0.75
FEISHU_MAX_INBOUND_FILE_BYTES = 20_000_000 FEISHU_MAX_INBOUND_FILE_BYTES = 20_000_000
SOURCE_PREVIEW_METADATA_KEY = "feishu_source_preview" SOURCE_PREVIEW_METADATA_KEY = "feishu_source_preview"
# Feishu rejects a card request body over 30 KB (230025), and style tags make
# the stored message larger than the body sent. Card text is budgeted by the
# bytes it adds to that body, leaving room for the other fields and that growth.
FEISHU_CARD_MAX_BYTES = 24 * 1024
# A long final answer continues in further cards, up to this many per reply.
FEISHU_MAX_CARDS_PER_REPLY = 10
_CARD_TRUNCATION_MARKER = "\n\n... (truncated)"
_CARD_CONTINUES_MARKER = "\n\n…"
_LONE_SURROGATE = re.compile("[\ud800-\udfff]")
# A markdown image marker, rewritten for the card so Feishu never sees one.
_MARKDOWN_IMAGE = re.compile(r"!\[(?P<alt>[^\]]*)\]\((?P<target>[^)\s]*)[^)]*\)")
_FENCED_CODE = re.compile(r"(?ms)^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*\n.*?^[ \t]*(?P=fence)[ \t]*$")
# Both delimiters are complete backtick runs of the same length.
_INLINE_CODE_SPAN = re.compile(r"(?<!`)(?P<ticks>`+)(?!`)[^\n]*?(?<!`)(?P=ticks)(?!`)")
# A fence a streamed snapshot cut open: what follows its opener is still code.
_UNCLOSED_FENCE = re.compile(r"(?m)^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*$")
def _rewrite_outside_inline_code(chunk: str, rewrite: Callable[[str], str]) -> str: def _is_feishu_command(text: str) -> bool:
"""Apply *rewrite* to the parts of *chunk* that are not inline code spans.""" return is_known_channel_command(text)
out: list[str] = []
cursor = 0
for span in _INLINE_CODE_SPAN.finditer(chunk):
out.append(rewrite(chunk[cursor : span.start()]))
out.append(span.group(0))
cursor = span.end()
out.append(rewrite(chunk[cursor:]))
return "".join(out)
def _card_markdown(text: str) -> str:
"""Rewrite the markdown a Feishu card cannot render.
A card markdown element only accepts a markdown image whose target is an
uploaded ``image_key``. A URL target makes Feishu reject every update of that
card with 230099 / 11310 ("the card contains images but no imagekey is passed
in"), which is how a reply carrying ``![alt](url)`` loses the rest of its
streamed text. Dropping the marker keeps the reference, and its link, in a
form the card renders. Code stays literal: a fenced block renders as code
there, and rewriting what it shows would misreport the answer.
"""
if "![" not in text:
return text
def as_link(chunk: str) -> str:
return _MARKDOWN_IMAGE.sub(lambda match: f"[{match.group('alt')}]({match.group('target')})", chunk)
out: list[str] = []
cursor = 0
for fenced in _FENCED_CODE.finditer(text):
out.append(_rewrite_outside_inline_code(text[cursor : fenced.start()], as_link))
out.append(fenced.group(0))
cursor = fenced.end()
tail = text[cursor:]
# A snapshot streamed before its closing fence arrives has an open block at the
# end; that content is code too, so what follows the opener stays literal.
open_fence = _UNCLOSED_FENCE.search(tail)
literal_from = open_fence.start() if open_fence else len(tail)
out.append(_rewrite_outside_inline_code(tail[:literal_from], as_link))
out.append(tail[literal_from:])
return "".join(out)
# Characters JSON escapes, measured after the second escape: ``"`` is ``\\\"``.
_ESCAPED_CARD_CHAR_BYTES = {'"': 4, "\\": 4, "\b": 3, "\f": 3, "\n": 3, "\r": 3, "\t": 3}
def _card_char_bytes(char: str) -> int:
escaped = _ESCAPED_CARD_CHAR_BYTES.get(char)
if escaped is not None:
return escaped
code = ord(char)
if code < 0x20:
return 7 # \u00XX, whose backslash is escaped again
if code < 0x80:
return 1
if code < 0x800:
return 2
if code < 0x10000:
return 3 # a lone surrogate is sent as U+FFFD
return 4
def _card_text_bytes(text: str) -> int:
"""Bytes *text* adds to a card request body.
The text is escaped twice: once inside the card JSON, and again as the
request body's ``content`` string. JSON escapes each character on its own,
so the cost of a text is the sum of its characters' costs.
"""
return sum(map(_card_char_bytes, text))
def _card_text_budget() -> int:
return FEISHU_CARD_MAX_BYTES - _card_text_bytes(FeishuChannel._build_card_content(""))
def _fitting_prefix_end(text: str, start: int, budget: int) -> tuple[int, int]:
"""Return the end of the longest prefix of ``text[start:]`` within *budget*, and its last newline."""
used = 0
end = start
last_newline = -1
while end < len(text):
cost = _card_char_bytes(text[end])
if used + cost > budget:
break
used += cost
if text[end] == "\n":
last_newline = end
end += 1
return end, last_newline
def _clip_card_text(text: str, marker: str = _CARD_TRUNCATION_MARKER) -> str:
"""Clip *text* to one card, ending it with *marker* when anything was cut."""
budget = _card_text_budget()
if _card_text_bytes(text) <= budget:
return text
end, _ = _fitting_prefix_end(text, 0, budget - _card_text_bytes(marker))
return text[:end] + marker
def _split_card_text(text: str) -> list[str]:
"""Split *text* into cards, preferring line boundaries so markdown survives.
Each newline stays on the tail of its card, so the cards join back to
the original text. Past ``FEISHU_MAX_CARDS_PER_REPLY`` the last card is
clipped instead.
"""
budget = _card_text_budget()
if _card_text_bytes(text) <= budget:
return [text]
cards: list[str] = []
start = 0
while start < len(text):
if len(cards) == FEISHU_MAX_CARDS_PER_REPLY - 1:
logger.warning("[Feishu] reply of %d characters exceeds %d cards, clipping the last one", len(text), FEISHU_MAX_CARDS_PER_REPLY)
cards.append(_clip_card_text(text[start:]))
break
end, last_newline = _fitting_prefix_end(text, start, budget)
if end < len(text) and last_newline >= start:
end = last_newline + 1
end = max(end, start + 1) # always advance, even past an oversized character
cards.append(text[start:end])
start = end
return cards
def _is_feishu_command(text: str, *, coordination_tasks_enabled: bool = False) -> bool:
return is_known_channel_command(text) or (coordination_tasks_enabled and is_feishu_task_command(text))
def _append_post_file_placeholders(text: str, count: int) -> str:
paragraphs = [text] if text else []
paragraphs.extend(["[file]"] * count)
return "\n\n".join(paragraphs)
def _post_link_text(element: dict) -> str:
"""Render a post ``a`` element as a Markdown link, keeping its label and URL."""
label = element.get("text") if isinstance(element.get("text"), str) else ""
href = element.get("href") if isinstance(element.get("href"), str) else ""
if not (label and href) or label == href:
return href or label
# Escape brackets so a "]" in the label cannot end the link text early, and
# put a URL with parentheses or spaces in <...>, where it needs no escaping.
label = re.sub(r"[\\\[\]]", lambda match: "\\" + match.group(), label)
destination = f"<{href}>" if re.search(r"[\s()]", href) else href
return f"[{label}]({destination})"
def _post_code_block_text(element: dict) -> str:
"""Render a post ``code_block`` element as a fenced block that the code's own backticks cannot close."""
code = element.get("text")
if not isinstance(code, str) or not code.strip():
return ""
language = element.get("language")
info = language.lower() if isinstance(language, str) and re.fullmatch(r"[\w+#.-]+", language) else ""
fence = "`" * max(3, max((len(run) for run in re.findall(r"`+", code)), default=0) + 1)
code = code.rstrip("\n")
return f"{fence}{info}\n{code}\n{fence}"
class FeishuChannel(Channel): class FeishuChannel(Channel):
@ -374,9 +186,9 @@ class FeishuChannel(Channel):
self._background_tasks: set[asyncio.Task] = set() self._background_tasks: set[asyncio.Task] = set()
self._running_card_ids: dict[str, str] = {} self._running_card_ids: dict[str, str] = {}
self._running_card_tasks: dict[str, asyncio.Task] = {} self._running_card_tasks: dict[str, asyncio.Task] = {}
# Thread aliases (chat_id, thread_id, topic_id, sender_id, connection_id) written # Thread aliases (chat_id, thread_id, topic_id, user_id) already written
# for each in-flight reply, keyed by source message id. # for each in-flight reply, keyed by source message id.
self._remembered_thread_aliases: dict[str, set[tuple[str, str, str, str, str | None]]] = {} self._remembered_thread_aliases: dict[str, set[tuple[str, str, str, str]]] = {}
self._pending_clarifications: dict[tuple[str, str], list[dict[str, Any]]] = {} self._pending_clarifications: dict[tuple[str, str], list[dict[str, Any]]] = {}
# Interactive clarification cards (button answers). Off by default: the # Interactive clarification cards (button answers). Off by default: the
# feature needs a one-time console subscription to card.action.trigger. # feature needs a one-time console subscription to card.action.trigger.
@ -737,10 +549,8 @@ class FeishuChannel(Channel):
len(msg.text), len(msg.text),
) )
# Cards already delivered by an earlier attempt are not sent again.
delivered: list[str | None] = []
await self._send_with_retry( await self._send_with_retry(
lambda: self._send_card_message(msg, delivered=delivered), lambda: self._send_card_message(msg),
max_retries=_max_retries, max_retries=_max_retries,
log_prefix="[Feishu]", log_prefix="[Feishu]",
) )
@ -773,39 +583,30 @@ class FeishuChannel(Channel):
# Legacy and group bindings do not prove that their chat is private. # Legacy and group bindings do not prove that their chat is private.
await self.send_notification(target=target, text_markdown=text_markdown) await self.send_notification(target=target, text_markdown=text_markdown)
async def send_task_result(self, *, chat_id: str, text_markdown: str, delivery_id: str) -> None: async def _send_notification_card(self, *, receive_id: str, receive_id_type: Literal["open_id", "chat_id"], text_markdown: str) -> None:
"""Push to the original DM after the outbox validates the binding."""
await self._send_notification_card(receive_id=chat_id, receive_id_type="chat_id", text_markdown=_clip_card_text(text_markdown), delivery_id=delivery_id)
async def _send_notification_card(self, *, receive_id: str, receive_id_type: Literal["open_id", "chat_id"], text_markdown: str, delivery_id: str | None = None) -> None:
"""Send once and wait for the SDK ACK. """Send once and wait for the SDK ACK.
The notification outbox owns retries. Transport failures park its row; The notification outbox owns retries. Transport failures park its row;
a platform rejection remains a counted delivery attempt. a platform rejection remains a counted delivery attempt.
""" """
await self._create_notification_message(receive_id, receive_id_type, "interactive", self._build_card_content(text_markdown), delivery_id) if not self.is_running or not self._api_client:
async def _create_notification_message(self, receive_id: str, receive_id_type: Literal["open_id", "chat_id"], msg_type: str, content: str, delivery_id: str | None) -> None:
client = self._api_client
if not self.is_running or not client:
raise ChannelUnavailable("Feishu channel is not running") raise ChannelUnavailable("Feishu channel is not running")
body = self._CreateMessageRequestBody.builder().receive_id(receive_id).msg_type(msg_type).content(content)
if delivery_id is not None:
body.uuid(delivery_id)
request = self._CreateMessageRequest.builder().receive_id_type(receive_id_type).request_body(body.build()).build()
response = await self._call_notification_sdk(lambda: client.im.v1.message.create(request))
if not response.success():
raise RuntimeError(f"Feishu notification rejected: code={response.code}")
@staticmethod
async def _call_notification_sdk(call: Callable[[], _T]) -> _T:
from requests.exceptions import ConnectionError as RequestsConnectionError from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import Timeout as RequestsTimeout from requests.exceptions import Timeout as RequestsTimeout
request = (
self._CreateMessageRequest.builder()
.receive_id_type(receive_id_type)
.request_body(self._CreateMessageRequestBody.builder().receive_id(receive_id).msg_type("interactive").content(self._build_card_content(text_markdown)).build())
.build()
)
try: try:
return await asyncio.to_thread(call) response = await asyncio.to_thread(self._api_client.im.v1.message.create, request)
except (RequestsConnectionError, RequestsTimeout, ConnectionError, TimeoutError, OSError) as exc: except (RequestsConnectionError, RequestsTimeout, ConnectionError, TimeoutError, OSError) as exc:
raise ChannelUnavailable("Feishu notification transport is unavailable") from exc raise ChannelUnavailable("Feishu notification transport is unavailable") from exc
if not response.success():
raise RuntimeError(f"Feishu notification rejected: code={response.code}")
async def send_group_notification_for_owner(self, *, owner_user_id: str | None, target: str, text_markdown: str) -> None: async def send_group_notification_for_owner(self, *, owner_user_id: str | None, target: str, text_markdown: str) -> None:
if self._connection_repo is None or not owner_user_id: if self._connection_repo is None or not owner_user_id:
@ -867,36 +668,18 @@ class FeishuChannel(Channel):
async def _upload_image(self, path) -> str: async def _upload_image(self, path) -> str:
"""Upload an image to Feishu and return the image_key.""" """Upload an image to Feishu and return the image_key."""
response = await asyncio.to_thread(self._upload_image_sync, path) response = await asyncio.to_thread(self._upload_image_sync, path)
return self._uploaded_key(response, "image")
async def upload_task_attachment(self, *, path: str, content: bytes) -> str:
"""Upload the saved artifact as a file so Feishu preserves its name and bytes."""
if not self.is_running or not self._api_client:
raise ChannelUnavailable("Feishu channel is not running")
filename = PurePosixPath(path).name
def upload():
with BytesIO(content) as stream:
return self._upload_file_stream(stream, filename, self._file_type(PurePosixPath(filename).suffix.lower()))
response = await self._call_notification_sdk(upload)
if not response.success(): if not response.success():
raise RuntimeError(f"Feishu attachment upload rejected: code={response.code}") raise RuntimeError(f"Feishu image upload failed: code={response.code}, msg={response.msg}")
return self._uploaded_key(response, "file") return response.data.image_key
async def send_task_attachment(self, *, chat_id: str, file_key: str, delivery_id: str) -> None:
await self._create_notification_message(chat_id, "chat_id", "file", json.dumps({"file_key": file_key}), delivery_id)
def _upload_file_stream(self, stream, filename: str, file_type: str):
request = self._CreateFileRequest.builder().request_body(self._CreateFileRequestBody.builder().file_type(file_type).file_name(filename).file(stream).build()).build()
return self._api_client.im.v1.file.create(request)
def _upload_file_sync(self, path, filename: str, file_type: str): def _upload_file_sync(self, path, filename: str, file_type: str):
with open(str(path), "rb") as f: with open(str(path), "rb") as f:
return self._upload_file_stream(f, filename, file_type) request = self._CreateFileRequest.builder().request_body(self._CreateFileRequestBody.builder().file_type(file_type).file_name(filename).file(f).build()).build()
return self._api_client.im.v1.file.create(request)
@staticmethod async def _upload_file(self, path, filename: str) -> str:
def _file_type(suffix: str) -> str: """Upload a file to Feishu and return the file_key."""
suffix = path.suffix.lower() if hasattr(path, "suffix") else ""
if suffix in (".xls", ".xlsx", ".csv"): if suffix in (".xls", ".xlsx", ".csv"):
file_type = "xls" file_type = "xls"
elif suffix in (".ppt", ".pptx"): elif suffix in (".ppt", ".pptx"):
@ -908,23 +691,10 @@ class FeishuChannel(Channel):
else: else:
file_type = "stream" file_type = "stream"
return file_type response = await asyncio.to_thread(self._upload_file_sync, path, filename, file_type)
async def _upload_file(self, path, filename: str) -> str:
"""Upload a file to Feishu and return the file_key."""
suffix = path.suffix.lower() if hasattr(path, "suffix") else ""
response = await asyncio.to_thread(self._upload_file_sync, path, filename, self._file_type(suffix))
return self._uploaded_key(response, "file")
@staticmethod
def _uploaded_key(response, kind: str) -> str:
"""Return the ``image_key``/``file_key`` of an upload response or raise with its log_id."""
if not response.success(): if not response.success():
raise RuntimeError(f"Feishu {kind} upload failed: code={response.code}, msg={response.msg}, log_id={response.get_log_id()}") raise RuntimeError(f"Feishu file upload failed: code={response.code}, msg={response.msg}")
key = getattr(getattr(response, "data", None), f"{kind}_key", None) return response.data.file_key
if not isinstance(key, str) or not key:
raise RuntimeError(f"Feishu {kind} upload returned no {kind}_key: log_id={response.get_log_id()}")
return key
async def receive_file(self, msg: InboundMessage, thread_id: str, *, user_id: str | None = None) -> InboundMessage: async def receive_file(self, msg: InboundMessage, thread_id: str, *, user_id: str | None = None) -> InboundMessage:
"""Download a Feishu file into the thread uploads directory. """Download a Feishu file into the thread uploads directory.
@ -939,10 +709,6 @@ class FeishuChannel(Channel):
logger.warning("[Feishu] received message with no files: %s", msg) logger.warning("[Feishu] received message with no files: %s", msg)
return msg return msg
text = msg.text text = msg.text
post_file_count = msg.metadata.pop(_POST_FILES_COUNT_METADATA_KEY, 0)
defer_post_file_placeholders = msg.metadata.pop(_DEFER_POST_FILE_PLACEHOLDERS_METADATA_KEY, False)
if not isinstance(post_file_count, int) or post_file_count < 0:
post_file_count = 0
search_from = 0 search_from = 0
def replace_next_placeholder(placeholder: str, replacement: str) -> None: def replace_next_placeholder(placeholder: str, replacement: str) -> None:
@ -953,40 +719,14 @@ class FeishuChannel(Channel):
text = f"{text[:idx]}{replacement}{text[idx + len(placeholder) :]}" text = f"{text[:idx]}{replacement}{text[idx + len(placeholder) :]}"
search_from = idx + len(replacement) search_from = idx + len(replacement)
downloaded: list[tuple[str, str]] = []
for file in files: for file in files:
if file.get("image_key"): if file.get("image_key"):
virtual_path = await self._receive_single_file(msg.thread_ts, file["image_key"], "image", thread_id, user_id=user_id) virtual_path = await self._receive_single_file(msg.thread_ts, file["image_key"], "image", thread_id, user_id=user_id)
downloaded.append(("[image]", virtual_path)) replace_next_placeholder("[image]", virtual_path)
elif file.get("file_key"): elif file.get("file_key"):
virtual_path = await self._receive_single_file(msg.thread_ts, file["file_key"], "file", thread_id, user_id=user_id) virtual_path = await self._receive_single_file(msg.thread_ts, file["file_key"], "file", thread_id, user_id=user_id)
downloaded.append(("[file]", virtual_path)) replace_next_placeholder("[file]", virtual_path)
# Top-level post attachments append their ``[file]`` placeholders
# after the parsed body, so their slots are the final
# ``post_file_count`` ones. Fill them from the end first: a literal
# ``[file]`` typed by the user must not consume a top-level
# attachment's path. Inline rich-text attachments keep the historical
# left-to-right matching below; that path is deliberately unchanged.
post_file_count = min(post_file_count, len(downloaded))
if defer_post_file_placeholders is True:
# A command such as /goal has now entered the chat path. Add the
# generated slots to the chat text after its arguments were parsed.
text = _append_post_file_placeholders(text, post_file_count)
suffix_end = len(text)
for placeholder, virtual_path in reversed(downloaded[len(downloaded) - post_file_count :] if post_file_count else []):
idx = text.rfind(placeholder, 0, suffix_end)
if idx < 0:
continue
text = f"{text[:idx]}{virtual_path}{text[idx + len(placeholder) :]}"
suffix_end = idx
for placeholder, virtual_path in downloaded[: len(downloaded) - post_file_count]:
replace_next_placeholder(placeholder, virtual_path)
msg.text = text msg.text = text
# Clear the descriptors so the generic URL-based _ingest_inbound_files
# pass does not try to re-fetch files that were downloaded by key.
msg.files = []
return msg return msg
async def _receive_single_file( async def _receive_single_file(
@ -1118,11 +858,9 @@ class FeishuChannel(Channel):
""" """
card = { card = {
"config": {"wide_screen_mode": True, "update_multi": True}, "config": {"wide_screen_mode": True, "update_multi": True},
# Unpaired surrogates cannot be encoded as UTF-8. "elements": [{"tag": "markdown", "content": text}],
"elements": [{"tag": "markdown", "content": _card_markdown(_LONE_SURROGATE.sub("\ufffd", text))}],
} }
# ASCII escapes would make each CJK character 6 bytes instead of 3. return json.dumps(card)
return json.dumps(card, ensure_ascii=False)
# -- reaction helpers -------------------------------------------------- # -- reaction helpers --------------------------------------------------
@ -1202,7 +940,7 @@ class FeishuChannel(Channel):
metadata: dict[str, Any] | None = None, metadata: dict[str, Any] | None = None,
) -> str | None: ) -> str | None:
"""Create the running card and cache its message ID when available.""" """Create the running card and cache its message ID when available."""
running_card_id = await self._reply_card(source_message_id, _clip_card_text(self._compose_card_text(text, metadata), _CARD_CONTINUES_MARKER)) running_card_id = await self._reply_card(source_message_id, self._compose_card_text(text, metadata))
if running_card_id: if running_card_id:
self._running_card_ids[source_message_id] = running_card_id self._running_card_ids[source_message_id] = running_card_id
logger.info("[Feishu] running card created: source=%s card=%s", source_message_id, running_card_id) logger.info("[Feishu] running card created: source=%s card=%s", source_message_id, running_card_id)
@ -1273,7 +1011,15 @@ class FeishuChannel(Channel):
# is reused across a thread's cards without exposing callback tokens. # is reused across a thread's cards without exposing callback tokens.
topic_id = f"feishu-card:{msg.thread_id}" topic_id = f"feishu-card:{msg.thread_id}"
try: try:
await self._record_thread_alias(msg.chat_id, topic_id, msg.thread_id, user_id, msg.connection_id, msg.owner_user_id) if msg.connection_id:
if self._connection_repo is None or not msg.owner_user_id:
return None
await self._connection_repo.set_thread_id(connection_id=msg.connection_id, owner_user_id=msg.owner_user_id, provider=self.name, external_conversation_id=msg.chat_id, thread_id=msg.thread_id, external_topic_id=topic_id)
else:
store = self.config.get("channel_store")
if store is None:
return None
await store.set_thread_id(self.name, msg.chat_id, msg.thread_id, topic_id=topic_id, user_id=user_id)
except Exception: except Exception:
logger.exception("[Feishu] cannot bind clarification card to thread %s; using text fallback", msg.thread_id) logger.exception("[Feishu] cannot bind clarification card to thread %s; using text fallback", msg.thread_id)
return None return None
@ -1308,14 +1054,8 @@ class FeishuChannel(Channel):
self._remember_pending_clarification(msg, card_message_id, topic_id=topic_id) self._remember_pending_clarification(msg, card_message_id, topic_id=topic_id)
await self._remember_thread_mapping(msg, msg.thread_ts, card_message_id) await self._remember_thread_mapping(msg, msg.thread_ts, card_message_id)
async def _send_card_message(self, msg: OutboundMessage, *, delivered: list[str | None] | None = None) -> None: async def _send_card_message(self, msg: OutboundMessage) -> None:
"""Send or update the Feishu card tied to the current request. """Send or update the Feishu card tied to the current request."""
A final answer over one card's budget continues in further cards replied
to the same source message; a streamed update shows only what fits.
*delivered* collects the IDs of the final answer's cards across retries.
"""
delivered = [] if delivered is None else delivered
source_message_id = msg.thread_ts source_message_id = msg.thread_ts
# Option clarifications render as an interactive button card on the # Option clarifications render as an interactive button card on the
# final outbound; everything else keeps the plain markdown card. # final outbound; everything else keeps the plain markdown card.
@ -1323,45 +1063,11 @@ class FeishuChannel(Channel):
card_topic_id = await self._bind_card_thread(msg) if card_request else None card_topic_id = await self._bind_card_thread(msg) if card_request else None
if card_topic_id is None: if card_topic_id is None:
card_request = None card_request = None
card_text = build_button_card(card_request) if card_request else self._compose_card_text(msg.text, msg.metadata)
# Button cards arrive as serialized card JSON and bypass the markdown # Button cards arrive as serialized card JSON and bypass the markdown
# wrapper; the plain path keeps its exact historical call signature. # wrapper; the plain path keeps its exact historical call signature.
raw_card_kw: dict[str, bool] = {"raw_card_content": True} if card_request else {} raw_card_kw: dict[str, bool] = {"raw_card_content": True} if card_request else {}
if source_message_id: if source_message_id:
if card_request:
cards = [build_button_card(card_request)]
elif msg.is_final:
cards = _split_card_text(self._compose_card_text(msg.text, msg.metadata))
else:
cards = [_clip_card_text(self._compose_card_text(msg.text, msg.metadata), _CARD_CONTINUES_MARKER)]
if not delivered:
await self._send_first_card(msg, cards[0], card_request=card_request, card_topic_id=card_topic_id, delivered=delivered, raw_card_kw=raw_card_kw)
if msg.is_final:
for card_text in cards[len(delivered) :]:
delivered.append(await self._reply_card(source_message_id, card_text))
if len(delivered) > 1:
# A reply to any of the cards continues this thread.
await self._remember_thread_mapping(msg, *delivered[1:])
self._running_card_ids.pop(source_message_id, None)
self._remembered_thread_aliases.pop(source_message_id, None)
await self._add_reaction(source_message_id, "DONE")
return
for card_text in _split_card_text(msg.text)[len(delivered) :]:
await self._create_card(msg.chat_id, card_text)
delivered.append(None)
async def _send_first_card(
self,
msg: OutboundMessage,
card_text: str,
*,
card_request: ClarificationCardRequest | None,
card_topic_id: str | None,
delivered: list[str | None],
raw_card_kw: dict[str, bool],
) -> None:
"""Put *card_text* on the running card, or reply with it; record it in *delivered* when final."""
source_message_id = msg.thread_ts
running_card_id = self._running_card_ids.get(source_message_id) running_card_id = self._running_card_ids.get(source_message_id)
awaited_running_card_task = False awaited_running_card_task = False
@ -1382,11 +1088,8 @@ class FeishuChannel(Channel):
running_card_id, running_card_id,
) )
fallback_card_id = await self._reply_card(source_message_id, card_text, **raw_card_kw) fallback_card_id = await self._reply_card(source_message_id, card_text, **raw_card_kw)
delivered.append(fallback_card_id)
await self._remember_card_delivery(msg, card_request, fallback_card_id, topic_id=card_topic_id) await self._remember_card_delivery(msg, card_request, fallback_card_id, topic_id=card_topic_id)
else: else:
if msg.is_final:
delivered.append(running_card_id)
await self._remember_card_delivery(msg, card_request, running_card_id, topic_id=card_topic_id) await self._remember_card_delivery(msg, card_request, running_card_id, topic_id=card_topic_id)
logger.info("[Feishu] running card updated: source=%s card=%s", source_message_id, running_card_id) logger.info("[Feishu] running card updated: source=%s card=%s", source_message_id, running_card_id)
elif msg.is_final: elif msg.is_final:
@ -1395,7 +1098,6 @@ class FeishuChannel(Channel):
card_text, card_text,
**raw_card_kw, **raw_card_kw,
) )
delivered.append(final_card_id)
await self._remember_card_delivery(msg, card_request, final_card_id, topic_id=card_topic_id) await self._remember_card_delivery(msg, card_request, final_card_id, topic_id=card_topic_id)
elif awaited_running_card_task: elif awaited_running_card_task:
logger.warning( logger.warning(
@ -1410,27 +1112,27 @@ class FeishuChannel(Channel):
) )
await self._remember_thread_mapping(msg, source_message_id, created_card_id) await self._remember_thread_mapping(msg, source_message_id, created_card_id)
# -- internal ---------------------------------------------------------- if msg.is_final:
self._running_card_ids.pop(source_message_id, None)
self._remembered_thread_aliases.pop(source_message_id, None)
await self._add_reaction(source_message_id, "DONE")
return
async def _record_thread_alias(self, chat_id: str, topic_id: str, thread_id: str, user_id: str, connection_id: str | None, owner_id: str | None) -> None: await self._create_card(msg.chat_id, msg.text)
if connection_id:
if self._connection_repo is None or not owner_id: # -- internal ----------------------------------------------------------
raise ValueError("Missing Feishu connection owner or repository")
# A late reply can add an alias, but /new owns explicit topic rebinding.
await self._connection_repo.claim_thread_id(connection_id=connection_id, owner_user_id=owner_id, provider=self.name, external_conversation_id=chat_id, external_topic_id=topic_id, thread_id=thread_id)
else:
store = self.config["channel_store"]
await store.set_thread_id(fallback_store_channel(self.name, topic_id, self._connection_repo), chat_id, thread_id, topic_id=topic_id, user_id=user_id)
async def _remember_thread_mapping(self, msg: OutboundMessage, *topic_ids: str | None) -> None: async def _remember_thread_mapping(self, msg: OutboundMessage, *topic_ids: str | None) -> None:
"""Map the reply's message, card and topic ids to its DeerFlow thread. """Map the reply's message, card and topic ids to its DeerFlow thread.
Every streamed chunk of a reply carries the same aliases, and each write Every streamed chunk of a reply carries the same aliases, and each write
is a full ``store.json`` rewrite or a database upsert, so a non-final is a full ``store.json`` rewrite or a database upsert, so a non-final
chunk only records new aliases. The final outbound checks them all again chunk only writes the aliases this reply has not stored yet. The final
so a missing alias can be restored. outbound writes all of them again, leaving the store as it was when every
chunk wrote them.
""" """
if not msg.thread_id or (not msg.connection_id and self.config.get("channel_store") is None): store = self.config.get("channel_store")
if store is None or not msg.thread_id:
return return
topic_id = self._non_empty_str(msg.metadata.get("topic_id")) topic_id = self._non_empty_str(msg.metadata.get("topic_id"))
@ -1453,11 +1155,17 @@ class FeishuChannel(Channel):
if not topic_id or topic_id in seen: if not topic_id or topic_id in seen:
continue continue
seen.add(topic_id) seen.add(topic_id)
alias = (msg.chat_id, msg.thread_id, topic_id, user_id, msg.connection_id) alias = (msg.chat_id, msg.thread_id, topic_id, user_id)
if alias in remembered: if alias in remembered:
continue continue
try: try:
await self._record_thread_alias(msg.chat_id, topic_id, msg.thread_id, user_id, msg.connection_id, msg.owner_user_id) await store.set_thread_id(
self.name,
msg.chat_id,
msg.thread_id,
topic_id=topic_id,
user_id=user_id,
)
except Exception: except Exception:
# Not remembered, so the next chunk retries it. # Not remembered, so the next chunk retries it.
logger.exception("[Feishu] failed to remember thread mapping for topic_id=%s", topic_id) logger.exception("[Feishu] failed to remember thread mapping for topic_id=%s", topic_id)
@ -1644,8 +1352,6 @@ class FeishuChannel(Channel):
"topic_id": topic_id, "topic_id": topic_id,
"source_message_id": source_message_id, "source_message_id": source_message_id,
"card_message_id": card_message_id, "card_message_id": card_message_id,
"connection_id": msg.connection_id,
"owner_user_id": msg.owner_user_id if msg.connection_id else None,
"created_at": time.time(), "created_at": time.time(),
} }
with self._thread_lock: with self._thread_lock:
@ -1661,7 +1367,7 @@ class FeishuChannel(Channel):
msg.thread_id, msg.thread_id,
) )
def _consume_pending_clarification(self, chat_id: str, user_id: str, *, reply_to_ids: list[str] | None = None, connection_id: str | None = None, owner_user_id: str | None = None) -> dict[str, Any] | None: def _consume_pending_clarification(self, chat_id: str, user_id: str, *, reply_to_ids: list[str] | None = None) -> dict[str, Any] | None:
key = self._pending_key(chat_id, user_id) key = self._pending_key(chat_id, user_id)
with self._thread_lock: with self._thread_lock:
pending_items = self._pending_clarifications.get(key) pending_items = self._pending_clarifications.get(key)
@ -1670,15 +1376,14 @@ class FeishuChannel(Channel):
now = time.time() now = time.time()
pending_items = [pending for pending in pending_items if isinstance(pending.get("created_at"), (int, float)) and now - pending["created_at"] <= PENDING_CLARIFICATION_TTL_SECONDS] pending_items = [pending for pending in pending_items if isinstance(pending.get("created_at"), (int, float)) and now - pending["created_at"] <= PENDING_CLARIFICATION_TTL_SECONDS]
candidates = [(i, p) for i, p in enumerate(pending_items) if (p.get("connection_id"), p.get("owner_user_id")) == (connection_id, owner_user_id if connection_id else None)]
# Explicit replies target a card/source, while accepted ordinary # Explicit replies target a card/source, while accepted ordinary
# replies use their current thread alias. Shared roots cannot select # replies use their current thread alias. Shared roots cannot select
# a card belonging to a conversation replaced by /new. # a card belonging to a conversation replaced by /new.
if reply_to_ids is None: if reply_to_ids is None:
matched = candidates[0][0] if candidates else None matched = 0 if pending_items else None
else: else:
matched = next( matched = next(
(index for field in ("card_message_id", "source_message_id", "topic_id") for candidate in reply_to_ids for index, pending in candidates if pending.get(field) == candidate), (index for field in ("card_message_id", "source_message_id", "topic_id") for candidate in reply_to_ids for index, pending in enumerate(pending_items) if pending.get(field) == candidate),
None, None,
) )
pending = pending_items.pop(matched) if matched is not None else None pending = pending_items.pop(matched) if matched is not None else None
@ -1707,60 +1412,45 @@ class FeishuChannel(Channel):
async def _resolve_routing(self, attempt: _RoutingAttempt) -> _Routing: async def _resolve_routing(self, attempt: _RoutingAttempt) -> _Routing:
"""Decide a message's topic on the Gateway loop, consulting and updating the channel store. """Decide a message's topic on the Gateway loop, consulting and updating the channel store.
Bound chat replies prefer the parent message so an earlier card can still Stored mappings for the root / parent / thread ids win (``_first_stored_topic``);
be followed after ``/new``. Commands and unbound messages prefer the root. otherwise the route is the root (or the message itself; ``None`` in P2P chats),
The Feishu thread ID is checked last. A miss falls back to the root or unless a pending clarification for the sender names a topic — that topic's
the message itself (``None`` in P2P chats). If a pending clarification mapping is then persisted so the manager finds the clarified thread. The
supplies a topic, persist its mapping so the manager finds that thread. pending clarification is consumed once: a retried attempt keeps the decision
A retry reuses the same clarification and only repeats the write. and only redoes the write.
""" """
store = self.config.get("channel_store") store = self.config.get("channel_store")
parsed = attempt.parsed parsed = attempt.parsed
route = InboundMessage(channel_name=self.name, chat_id=parsed.chat_id, user_id=parsed.sender_id, text="")
if self._connection_repo is not None:
await self._attach_connection_identity(route)
default = _Routing(
topic_id=None if parsed.chat_type == "p2p" else (parsed.root_id or parsed.msg_id),
from_stored_mapping=False,
from_pending=False,
connection_id=route.connection_id,
owner_user_id=route.owner_user_id,
workspace_id=route.workspace_id,
)
if attempt.pending is None: if attempt.pending is None:
root_id = self._non_empty_str(parsed.root_id) candidates = [candidate for candidate in (self._non_empty_str(parsed.root_id), parsed.parent_id, parsed.feishu_thread_id) if candidate]
message_ids = (parsed.parent_id, root_id) if route.connection_id and parsed.msg_type == InboundMessageType.CHAT else (root_id, parsed.parent_id)
candidates = [candidate for candidate in (*message_ids, parsed.feishu_thread_id) if candidate]
if candidates: if candidates:
stored = await self._first_stored_topic(store, route, candidates) stored = await self._first_stored_topic(store, parsed.chat_id, candidates)
if stored: if stored:
pending = ( pending = (
self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=[parsed.parent_id], connection_id=route.connection_id, owner_user_id=route.owner_user_id) self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=[parsed.parent_id]) if self._card_interaction_enabled and parsed.msg_type == InboundMessageType.CHAT and parsed.parent_id else None
if self._card_interaction_enabled and parsed.msg_type == InboundMessageType.CHAT and parsed.parent_id
else None
) )
if pending: if pending:
return replace(default, topic_id=pending["topic_id"], from_stored_mapping=True, from_pending=True, clarification_card_id=self._non_empty_str(pending.get("card_message_id"))) return _Routing(pending["topic_id"], True, True, self._non_empty_str(pending.get("card_message_id")))
return replace(default, topic_id=stored, from_stored_mapping=True) return _Routing(stored, True, False)
topic_id: str | None = parsed.root_id or parsed.msg_id
if parsed.chat_type == "p2p":
topic_id = None
if parsed.msg_type != InboundMessageType.CHAT: if parsed.msg_type != InboundMessageType.CHAT:
return default return _Routing(topic_id, False, False)
if self._card_interaction_enabled and parsed.chat_type == "p2p" and not candidates: if self._card_interaction_enabled and parsed.chat_type == "p2p" and not candidates:
# Unthreaded P2P messages follow the current conversation, # Unthreaded P2P messages follow the current conversation,
# including /new. Only explicit card replies use the old alias. # including /new. Only explicit card replies use the old alias.
return default return _Routing(None, False, False)
reply_to_ids = [parsed.parent_id] if self._card_interaction_enabled and parsed.parent_id else None reply_to_ids = [parsed.parent_id] if self._card_interaction_enabled and parsed.parent_id else None
pending = self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=reply_to_ids, connection_id=route.connection_id, owner_user_id=route.owner_user_id) pending = self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=reply_to_ids)
if not (pending and self._non_empty_str(pending.get("topic_id"))): if not (pending and self._non_empty_str(pending.get("topic_id"))):
return default return _Routing(topic_id, False, False)
attempt.pending = pending attempt.pending = pending
pending_topic_id = self._non_empty_str(attempt.pending.get("topic_id")) pending_topic_id = self._non_empty_str(attempt.pending.get("topic_id"))
thread_id = self._non_empty_str(attempt.pending.get("thread_id")) thread_id = self._non_empty_str(attempt.pending.get("thread_id"))
if (attempt.pending.get("connection_id"), attempt.pending.get("owner_user_id")) != (route.connection_id, route.owner_user_id): if thread_id:
attempt.pending = None await store.set_thread_id(self.name, parsed.chat_id, thread_id, topic_id=pending_topic_id, user_id=parsed.sender_id)
return default return _Routing(pending_topic_id, False, True, self._non_empty_str(attempt.pending.get("card_message_id")))
if thread_id and (route.connection_id or store is not None):
await self._record_thread_alias(parsed.chat_id, pending_topic_id, thread_id, parsed.sender_id, route.connection_id, route.owner_user_id)
return replace(default, topic_id=pending_topic_id, from_pending=True, clarification_card_id=self._non_empty_str(attempt.pending.get("card_message_id")))
async def _resolve_routing_bounded(self, attempt: _RoutingAttempt) -> _Routing | StoreLookupUnresolved: async def _resolve_routing_bounded(self, attempt: _RoutingAttempt) -> _Routing | StoreLookupUnresolved:
"""``_resolve_routing`` under the store deadline; no answer in time (or a store error) is *unresolved*. """``_resolve_routing`` under the store deadline; no answer in time (or a store error) is *unresolved*.
@ -1780,11 +1470,10 @@ class FeishuChannel(Channel):
logger.warning("[Feishu] channel store call failed for message %s (%s); treating the lookup as unresolved", attempt.parsed.msg_id, exc.__class__.__name__, exc_info=True) logger.warning("[Feishu] channel store call failed for message %s (%s); treating the lookup as unresolved", attempt.parsed.msg_id, exc.__class__.__name__, exc_info=True)
return StoreLookupUnresolved(f"channel store error: {exc.__class__.__name__}") return StoreLookupUnresolved(f"channel store error: {exc.__class__.__name__}")
async def _first_stored_topic(self, store: Any, route: InboundMessage, candidates: list[str]) -> str | None: async def _first_stored_topic(self, store: Any, chat_id: str, candidates: list[str]) -> str | None:
"""The first candidate topic id the store already maps to a thread, in priority order.""" """The first candidate topic id the store already maps to a thread, in priority order."""
for candidate in candidates: for candidate in candidates:
route.topic_id = candidate if await store.get_thread_id(self.name, chat_id, topic_id=candidate):
if await lookup_thread_id(route, repo=self._connection_repo, store=store):
return candidate return candidate
return None return None
@ -1911,7 +1600,6 @@ class FeishuChannel(Channel):
metadata = { metadata = {
"message_id": parsed.msg_id, "message_id": parsed.msg_id,
"chat_type": parsed.chat_type,
"root_id": parsed.root_id, "root_id": parsed.root_id,
"parent_id": parsed.parent_id, "parent_id": parsed.parent_id,
"thread_id": parsed.feishu_thread_id, "thread_id": parsed.feishu_thread_id,
@ -1921,10 +1609,6 @@ class FeishuChannel(Channel):
} }
if source_preview: if source_preview:
metadata[SOURCE_PREVIEW_METADATA_KEY] = source_preview metadata[SOURCE_PREVIEW_METADATA_KEY] = source_preview
if parsed.post_file_count:
metadata[_POST_FILES_COUNT_METADATA_KEY] = parsed.post_file_count
if parsed.msg_type == InboundMessageType.COMMAND:
metadata[_DEFER_POST_FILE_PLACEHOLDERS_METADATA_KEY] = True
if routing.clarification_card_id: if routing.clarification_card_id:
metadata[_PENDING_CARD_METADATA_KEY] = routing.clarification_card_id metadata[_PENDING_CARD_METADATA_KEY] = routing.clarification_card_id
@ -1938,9 +1622,6 @@ class FeishuChannel(Channel):
metadata=metadata, metadata=metadata,
) )
inbound.topic_id = routing.topic_id inbound.topic_id = routing.topic_id
inbound.connection_id = routing.connection_id
inbound.owner_user_id = routing.owner_user_id
inbound.workspace_id = routing.workspace_id
if self._is_batchable_file_inbound( if self._is_batchable_file_inbound(
msg_type=parsed.msg_type, msg_type=parsed.msg_type,
@ -2022,15 +1703,14 @@ class FeishuChannel(Channel):
def _queue_file_inbound_batch(self, msg_id: str, inbound: InboundMessage) -> bool: def _queue_file_inbound_batch(self, msg_id: str, inbound: InboundMessage) -> bool:
key = self._pending_key(inbound.chat_id, inbound.user_id) key = self._pending_key(inbound.chat_id, inbound.user_id)
should_schedule_flush = False should_schedule_flush = False
previous_batch: tuple[str, InboundMessage, list[str]] | None = None expired_batch: tuple[str, InboundMessage, list[str]] | None = None
with self._thread_lock: with self._thread_lock:
batch = self._pending_inbound_batches.get(key) batch = self._pending_inbound_batches.get(key)
now = time.time() now = time.time()
if batch: if batch:
if now - batch["created_at"] <= FEISHU_INBOUND_BATCH_WINDOW_SECONDS:
batched_inbound = batch["inbound"] batched_inbound = batch["inbound"]
same_binding = (batched_inbound.connection_id, batched_inbound.owner_user_id) == (inbound.connection_id, inbound.owner_user_id)
if same_binding and now - batch["created_at"] <= FEISHU_INBOUND_BATCH_WINDOW_SECONDS:
batch["message_ids"].append(msg_id) batch["message_ids"].append(msg_id)
batch["text_parts"].append(inbound.text) batch["text_parts"].append(inbound.text)
batched_inbound.text = "\n\n".join(part for part in batch["text_parts"] if part) batched_inbound.text = "\n\n".join(part for part in batch["text_parts"] if part)
@ -2046,7 +1726,7 @@ class FeishuChannel(Channel):
) )
return True return True
previous_batch = (batch["anchor_message_id"], batch["inbound"], list(batch["message_ids"])) expired_batch = (batch["anchor_message_id"], batch["inbound"], list(batch["message_ids"]))
self._pending_inbound_batches[key] = { self._pending_inbound_batches[key] = {
"anchor_message_id": msg_id, "anchor_message_id": msg_id,
@ -2060,9 +1740,9 @@ class FeishuChannel(Channel):
if should_schedule_flush: if should_schedule_flush:
self._schedule_batch_flush(key, msg_id) self._schedule_batch_flush(key, msg_id)
if previous_batch: if expired_batch:
anchor_message_id, previous_inbound, source_message_ids = previous_batch anchor_message_id, expired_inbound, source_message_ids = expired_batch
self._schedule_prepare_inbound(anchor_message_id, previous_inbound, source_message_ids=source_message_ids) self._schedule_prepare_inbound(anchor_message_id, expired_inbound, source_message_ids=source_message_ids)
return True return True
def _pop_pending_inbound_batch(self, key: tuple[str, str], *, anchor_message_id: str | None = None) -> tuple[str, InboundMessage, list[str]] | None: def _pop_pending_inbound_batch(self, key: tuple[str, str], *, anchor_message_id: str | None = None) -> tuple[str, InboundMessage, list[str]] | None:
@ -2122,11 +1802,12 @@ class FeishuChannel(Channel):
"""Kick off Feishu side effects without delaying inbound dispatch.""" """Kick off Feishu side effects without delaying inbound dispatch."""
try: try:
clarification_card_id = inbound.metadata.pop(_PENDING_CARD_METADATA_KEY, None) clarification_card_id = inbound.metadata.pop(_PENDING_CARD_METADATA_KEY, None)
inbound = await self._attach_connection_identity(inbound)
if self._card_interaction_enabled and not clarification_card_id and inbound.msg_type == InboundMessageType.CHAT: if self._card_interaction_enabled and not clarification_card_id and inbound.msg_type == InboundMessageType.CHAT:
# Ordinary answers retire only the current thread's buttons; # Ordinary answers retire only the current thread's buttons;
# older cards cannot redirect a fresh /new conversation. # older cards cannot redirect a fresh /new conversation.
thread_id = await lookup_thread_id(inbound, repo=self._connection_repo, store=self.config.get("channel_store")) thread_id = await lookup_thread_id(inbound, repo=self._connection_repo, store=self.config.get("channel_store"))
pending = self._consume_pending_clarification(inbound.chat_id, inbound.user_id, reply_to_ids=[f"feishu-card:{thread_id}"], connection_id=inbound.connection_id, owner_user_id=inbound.owner_user_id) if thread_id else None pending = self._consume_pending_clarification(inbound.chat_id, inbound.user_id, reply_to_ids=[f"feishu-card:{thread_id}"]) if thread_id else None
if pending: if pending:
clarification_card_id = pending.get("card_message_id") clarification_card_id = pending.get("card_message_id")
inbound.metadata[RESOLVED_FROM_PENDING_CLARIFICATION_METADATA_KEY] = True inbound.metadata[RESOLVED_FROM_PENDING_CLARIFICATION_METADATA_KEY] = True
@ -2246,19 +1927,6 @@ class FeishuChannel(Channel):
text_value = element.get("text", "") text_value = element.get("text", "")
if text_value: if text_value:
paragraph_text_parts.append(text_value) paragraph_text_parts.append(text_value)
elif element.get("tag") == "a":
link_text = _post_link_text(element)
if link_text:
paragraph_text_parts.append(link_text)
elif element.get("tag") == "code_block":
code_block_text = _post_code_block_text(element)
if code_block_text:
# A fence must start its own line, so the block
# becomes its own paragraph.
if paragraph_text_parts:
text_paragraphs.append(" ".join(paragraph_text_parts))
paragraph_text_parts.clear()
text_paragraphs.append(code_block_text)
elif element.get("tag") == "img": elif element.get("tag") == "img":
image_key = element.get("image_key") image_key = element.get("image_key")
if isinstance(image_key, str) and image_key: if isinstance(image_key, str) and image_key:
@ -2279,26 +1947,6 @@ class FeishuChannel(Channel):
text = "" text = ""
text = text.strip() text = text.strip()
# Feishu desktop attaches files to a message as a post whose rich-text
# body holds the caption and whose top-level ``files`` array holds the
# attachments. The body may be empty. Keep these attachments last so
# ``receive_file`` can match their placeholders from the end. Skip
# folders and attachments already represented by a rich-text element.
attachments = content.get("files") if isinstance(content, dict) else None
if not isinstance(attachments, list):
attachments = []
post_file_count = 0
for attachment in attachments:
if not isinstance(attachment, dict) or attachment.get("is_folder"):
continue
file_key = attachment.get("file_key")
if not isinstance(file_key, str) or not file_key:
continue
if any(existing.get("file_key") == file_key for existing in files_list):
continue
files_list.append({"file_key": file_key})
post_file_count += 1
logger.info( logger.info(
"[Feishu] parsed message: chat_id=%s, msg_id=%s, root_id=%s, parent_id=%s, thread_id=%s, chat_type=%s, sender=%s, text_len=%d", "[Feishu] parsed message: chat_id=%s, msg_id=%s, root_id=%s, parent_id=%s, thread_id=%s, chat_type=%s, sender=%s, text_len=%d",
chat_id, chat_id,
@ -2324,7 +1972,6 @@ class FeishuChannel(Channel):
chat_type=chat_type, chat_type=chat_type,
text=text, text=text,
files=files_list, files=files_list,
post_file_count=post_file_count,
) )
def _on_message(self, event) -> None: def _on_message(self, event) -> None:
@ -2364,16 +2011,14 @@ class FeishuChannel(Channel):
# @mentions intact for the agent; the stripped form also flows into the # @mentions intact for the agent; the stripped form also flows into the
# inbound so ChannelManager._handle_command parses the bare command. # inbound so ChannelManager._handle_command parses the bare command.
command_text = strip_leading_mentions(text) command_text = strip_leading_mentions(text)
if _is_feishu_command(command_text, coordination_tasks_enabled=getattr(self.bus, "coordination_tasks_enabled", False) is True): if _is_feishu_command(command_text):
parsed.msg_type = InboundMessageType.COMMAND parsed.msg_type = InboundMessageType.COMMAND
parsed.text = command_text parsed.text = command_text
elif parsed.post_file_count:
parsed.text = _append_post_file_placeholders(text, parsed.post_file_count)
# topic_id determines which LangGraph thread the message maps to. # topic_id determines which LangGraph thread the message maps to.
# P2P chats: topic_id=None so all messages share one thread (like Telegram DMs). # P2P chats: topic_id=None so all messages share one thread (like Telegram DMs).
# But check stored mappings first for backward compatibility with pre-upgrade P2P threads. # But check stored mappings first for backward compatibility with pre-upgrade P2P threads.
if self.config.get("channel_store") is None and self._connection_repo is None: if self.config.get("channel_store") is None:
self._dispatch_inbound(parsed, self._route_without_store(parsed)) self._dispatch_inbound(parsed, self._route_without_store(parsed))
return return

View File

@ -123,12 +123,7 @@ class ClarificationCardRequest:
def build_button_card(request: ClarificationCardRequest) -> str: def build_button_card(request: ClarificationCardRequest) -> str:
"""Render the clarification as a Feishu interactive card with one button per option.""" """Render the clarification as a Feishu interactive card with one button per option."""
# Imported here because feishu.py imports this module, and the markdown rewrite
# lives beside the card it was written for.
from app.channels.feishu import _card_markdown
content = f"{request.context}\n\n{request.question}" if request.context else request.question content = f"{request.context}\n\n{request.question}" if request.context else request.question
content = _card_markdown(content)
card = { card = {
"config": {"wide_screen_mode": True, "update_multi": True}, "config": {"wide_screen_mode": True, "update_multi": True},
"header": {"title": {"tag": "plain_text", "content": "需要你的选择"}}, "header": {"title": {"tag": "plain_text", "content": "需要你的选择"}},

View File

@ -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). - 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 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. Each agent for every mention even when only one had useful work to do. Letting the
chooses whether to post using its configured tools. LLM call ``gh`` mid-run means silence is just "the LLM did not call gh."
- The agent often wants to post *intermediate* updates (an issue comment - The agent often wants to post *intermediate* updates (an issue comment
linking the PR, a separate comment on a new sub-issue, …) — the 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 auto-post-the-final-message contract didn't model that and forced the
final message to play double duty. final message to play double duty.
- The dispatcher's per-agent ``_is_self_event`` gate already prevents the - The dispatcher's per-agent ``_is_self_event`` gate already prevents the
comments the agent posts from looping the webhook back into a comments the LLM posts via ``gh`` from looping the webhook back into a
new run for the same agent. new run for the same agent.
""" """
@ -85,8 +85,9 @@ class GitHubChannel(Channel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Log the agent's final message — do NOT post it to GitHub. """Log the agent's final message — do NOT post it to GitHub.
GitHub agents use configured tools to post to issues and PRs. The GitHub agents post to issues/PRs themselves via ``gh`` mid-run; the
final assistant message goes to ``gateway.log``. final assistant message is logged for ``gateway.log`` visibility but
is not delivered to the platform. See the module docstring for why.
Metadata layout (read for logging context only): Metadata layout (read for logging context only):
- ``repo`` (str, e.g. ``"owner/name"``) — falls back to ``chat_id`` - ``repo`` (str, e.g. ``"owner/name"``) — falls back to ``chat_id``

View File

@ -16,7 +16,6 @@ from __future__ import annotations
import math import math
from collections.abc import Mapping from collections.abc import Mapping
from app.channels.reply_locale import supported_locale
from app.scheduler.notification_text import goal_reason_text from app.scheduler.notification_text import goal_reason_text
from deerflow.persistence.scheduled_task_runs.finalization import CHECK_FAILURE_CODES from deerflow.persistence.scheduled_task_runs.finalization import CHECK_FAILURE_CODES
from deerflow.runtime.goal import is_active_goal from deerflow.runtime.goal import is_active_goal
@ -39,18 +38,6 @@ _TEXT: dict[str, dict[str, str]] = {
"fetch_failed": "Failed to fetch goal information.", "fetch_failed": "Failed to fetch goal information.",
"clear_failed": "Failed to clear goal.", "clear_failed": "Failed to clear goal.",
"set_failed": "Failed to set goal.", "set_failed": "Failed to set goal.",
"busy": "A task is still running. Wait for it to finish before changing the goal.",
"from_chat_saved": "Goal set from the conversation: {objective}",
"from_chat_saved_but_not_started": "Goal saved from the conversation, but the task did not start. Send any message to pick it up, or check /goal.",
"from_chat_run_status_unknown": "Goal saved from the conversation. I couldn't confirm the task's status, and it may still be running. Check the conversation in DeerFlow before sending it again.",
"from_chat_unclear": "I couldn't form a clear goal from this conversation. Try adding a hint, e.g. /goal from-chat focus on the vendor totals.",
"from_chat_no_context": "There is no conversation content to build a goal from yet. Discuss the task first, or set it directly with /goal <objective>.",
"from_chat_pending_clarification": "The assistant is still waiting for your answer in this conversation. Reply to it first, then retry /goal from-chat.",
"from_chat_no_thread": "No conversation yet. Send a message first, then ask /goal from-chat.",
"from_chat_changed": "The conversation changed while the goal was being composed, so nothing was saved. Retry /goal from-chat, or set it directly with /goal <objective>.",
"from_chat_conversation_switched": "This chat switched to a new conversation while the goal was being composed, so the task did not start. The goal remains saved in the previous conversation: {objective}",
"from_chat_timeout": "Timed out waiting for the goal to be composed. The save may still finish — check with /goal, and retry if there is no goal.",
"from_chat_failed": "Failed to compose the goal from the conversation. Try again, or set it directly with /goal <objective>.",
}, },
"zh-CN": { "zh-CN": {
"goal": "目标:{objective}", "goal": "目标:{objective}",
@ -69,18 +56,6 @@ _TEXT: dict[str, dict[str, str]] = {
"fetch_failed": "无法获取目标信息。", "fetch_failed": "无法获取目标信息。",
"clear_failed": "无法清除目标。", "clear_failed": "无法清除目标。",
"set_failed": "无法设置目标。", "set_failed": "无法设置目标。",
"busy": "当前任务仍在运行,请等待结束后再修改目标。",
"from_chat_saved": "已从对话设置目标:{objective}",
"from_chat_saved_but_not_started": "目标已从对话保存,但任务未能启动。发送任意消息即可继续,或用 /goal 查看状态。",
"from_chat_run_status_unknown": "目标已从对话保存,但暂时无法确认任务状态,任务可能仍在运行。请先在 DeerFlow 中查看会话,再决定是否重试。",
"from_chat_unclear": "无法从当前对话中形成清楚的目标。可以补充提示,例如 /goal from-chat 重点核对供应商合计。",
"from_chat_no_context": "当前对话还没有可用于构建目标的内容。先讨论任务,或用 /goal <目标> 直接设置。",
"from_chat_pending_clarification": "助手还在等你回答对话里的问题。先回复它,再重试 /goal from-chat。",
"from_chat_no_thread": "还没有会话。先发一条消息,再用 /goal from-chat。",
"from_chat_changed": "生成目标期间对话内容发生了变化,本次未保存。请重试 /goal from-chat,或用 /goal <目标> 直接设置。",
"from_chat_conversation_switched": "生成目标期间当前聊天切换到了新会话,任务没有启动。目标仍保存在之前的会话里:{objective}",
"from_chat_timeout": "从对话生成目标超时。保存可能仍会完成——先用 /goal 查看,如果没有再重试。",
"from_chat_failed": "从对话生成目标失败。请重试,或用 /goal <目标> 直接设置。",
}, },
} }
@ -90,7 +65,6 @@ _WAITING_KEYS = {"needs_user_input": "waiting_for_you", "external_wait": "waitin
def goal_reply_text(key: str, locale: str) -> str: def goal_reply_text(key: str, locale: str) -> str:
"""A fixed ``/goal`` reply (``none``, ``cleared``, ``*_failed``) in ``locale``.""" """A fixed ``/goal`` reply (``none``, ``cleared``, ``*_failed``) in ``locale``."""
locale = supported_locale(locale)
return _TEXT[locale][key] return _TEXT[locale][key]
@ -128,7 +102,6 @@ def goal_status_text(goal: object, outcome: object, *, running: bool, locale: st
``running`` says whether the thread has a run pending or in progress. ``running`` says whether the thread has a run pending or in progress.
""" """
locale = supported_locale(locale)
text = _TEXT[locale] text = _TEXT[locale]
if is_active_goal_state(goal): if is_active_goal_state(goal):
lines = [text["goal"].format(objective=goal["objective"])] lines = [text["goal"].format(objective=goal["objective"])]

View File

@ -23,15 +23,14 @@ from typing import Any, NamedTuple
from urllib.parse import quote, urlparse from urllib.parse import quote, urlparse
import httpx import httpx
from deerflow_extension_api.agent_runs import AgentRunError
from fastapi import HTTPException from fastapi import HTTPException
from langgraph_sdk.errors import APIStatusError, ConflictError from langgraph_sdk.errors import ConflictError
from app.channels import buzz_run_policy as _buzz_run_policy # noqa: F401 from app.channels import buzz_run_policy as _buzz_run_policy # noqa: F401
from app.channels import feishu_run_policy as _feishu_run_policy # noqa: F401 from app.channels import feishu_run_policy as _feishu_run_policy # noqa: F401
from app.channels.capabilities import CHANNEL_CAPABILITIES from app.channels.capabilities import CHANNEL_CAPABILITIES
from app.channels.commands import FEISHU_TASK_START_SUBCOMMAND, KNOWN_CHANNEL_COMMANDS, is_feishu_task_command from app.channels.commands import KNOWN_CHANNEL_COMMANDS
from app.channels.connection_identity import fallback_store_channel, lookup_thread_id from app.channels.connection_identity import lookup_thread_id
from app.channels.dedupe_store import InboundDedupeStore, MemoryInboundDedupeStore from app.channels.dedupe_store import InboundDedupeStore, MemoryInboundDedupeStore
from app.channels.goal_status import goal_reply_text, goal_status_text, is_active_goal_state from app.channels.goal_status import goal_reply_text, goal_status_text, is_active_goal_state
from app.channels.message_bus import ( from app.channels.message_bus import (
@ -59,7 +58,6 @@ from app.gateway.path_utils import resolve_outputs_confined_path
from deerflow.agents.human_input import read_human_input_response from deerflow.agents.human_input import read_human_input_response
from deerflow.config.agents_config import list_custom_agents, load_agent_config from deerflow.config.agents_config import list_custom_agents, load_agent_config
from deerflow.config.paths import make_safe_user_id from deerflow.config.paths import make_safe_user_id
from deerflow.persistence.coordination.sql import TaskConflict
from deerflow.runtime import END_SENTINEL, StreamBridge from deerflow.runtime import END_SENTINEL, StreamBridge
from deerflow.runtime.goal import parse_goal_command from deerflow.runtime.goal import parse_goal_command
from deerflow.runtime.keyed_lock import AsyncKeyedLockTable from deerflow.runtime.keyed_lock import AsyncKeyedLockTable
@ -71,7 +69,6 @@ from deerflow.skills.storage.skill_storage import SkillStorage
from deerflow.trace_context import ensure_trace_context from deerflow.trace_context import ensure_trace_context
from deerflow.uploads.manager import apply_upload_sandbox_permits from deerflow.uploads.manager import apply_upload_sandbox_permits
from deerflow.utils.file_io import await_drained from deerflow.utils.file_io import await_drained
from deerflow.utils.http_policy import control_plane_trust_env
from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -144,7 +141,7 @@ _LIVE_RUN_STATUSES = frozenset({"pending", "running"})
@dataclass @dataclass
class _RunAdmission: class _RunAdmission:
"""How far one inbound message's run request got, for dedupe and goal replies. """How far one inbound message's run request got, for dedupe release.
``requested`` flips right before the run request leaves the manager; ``requested`` flips right before the run request leaves the manager;
``confirmed`` once the Gateway proved it admitted the run (a run id, a ``confirmed`` once the Gateway proved it admitted the run (a run id, a
@ -153,7 +150,6 @@ class _RunAdmission:
requested: bool = False requested: bool = False
confirmed: bool = False confirmed: bool = False
error: BaseException | None = None
_RUN_ADMISSION: ContextVar[_RunAdmission | None] = ContextVar("deerflow_channel_run_admission", default=None) _RUN_ADMISSION: ContextVar[_RunAdmission | None] = ContextVar("deerflow_channel_run_admission", default=None)
@ -164,22 +160,11 @@ _RUN_ADMISSION: ContextVar[_RunAdmission | None] = ContextVar("deerflow_channel_
# status errors mean the Gateway never admitted it. # status errors mean the Gateway never admitted it.
_RUN_REQUEST_REACHED_GATEWAY_ERRORS = (httpx.ReadTimeout, httpx.ReadError, httpx.RemoteProtocolError) _RUN_REQUEST_REACHED_GATEWAY_ERRORS = (httpx.ReadTimeout, httpx.ReadError, httpx.RemoteProtocolError)
# ``/goal from-chat`` makes the Gateway run a synthesis LLM call before it
# answers, which routinely exceeds the 10s budget the other ``/goal`` calls
# need for a checkpoint read/write — the live Feishu run timed out client-side
# while the Gateway went on to save the goal. Keep connect/write/pool short so
# a dead Gateway still fails fast, and extend only the read for the synthesis.
_GOAL_FROM_CHAT_TIMEOUT = httpx.Timeout(10.0, read=120.0)
class _RunFailedFrame(RuntimeError): class _RunFailedFrame(RuntimeError):
"""The stream's ``error`` frame: the run ended, so a retry is not a duplicate.""" """The stream's ``error`` frame: the run ended, so a retry is not a duplicate."""
class _ConversationSwitched(RuntimeError):
"""The chat no longer points at the thread whose goal was saved."""
@contextmanager @contextmanager
def _run_admission_scope(*, fresh: bool = False) -> Iterator[_RunAdmission]: def _run_admission_scope(*, fresh: bool = False) -> Iterator[_RunAdmission]:
"""Install the admission record for one inbound message. """Install the admission record for one inbound message.
@ -210,11 +195,6 @@ def _note_run_confirmed() -> None:
admission.confirmed = True admission.confirmed = True
def _note_run_error(error: BaseException) -> None:
if (admission := _RUN_ADMISSION.get()) is not None:
admission.error = error
# Recovery replies must say the turn was dropped: the run was rejected before # Recovery replies must say the turn was dropped: the run was rejected before
# starting, so the triggering message never reached the agent. # starting, so the triggering message never reached the agent.
_STALE_PIN_RETRY_NOTE = "Your message was not processed — please send it again." _STALE_PIN_RETRY_NOTE = "Your message was not processed — please send it again."
@ -321,59 +301,6 @@ _WECOM_MEDIA_COS_HOST_RE = re.compile(r"^ww-aibot-img-(?P<appid>\d+)\.cos\.[a-z0
_METADATA_DROP_KEYS = frozenset({"raw_message", "ref_msg"}) _METADATA_DROP_KEYS = frozenset({"raw_message", "ref_msg"})
def _make_gateway_client(gateway_url: str) -> httpx.AsyncClient:
"""Build the short-lived client for Gateway control-plane calls.
A loopback Gateway must bypass ``HTTP_PROXY``, while an external one keeps
the environment proxy. The policy itself lives in
:mod:`deerflow.utils.http_policy` so this module never imports the sandbox
provider stack.
"""
return httpx.AsyncClient(trust_env=control_plane_trust_env(gateway_url))
# Mirrors the client ``langgraph_sdk.get_client()`` builds, so the loopback path
# below differs from it only in ``trust_env``.
_LANGGRAPH_SDK_RETRIES = 5
_LANGGRAPH_SDK_TIMEOUT = httpx.Timeout(connect=5, read=300, write=300, pool=5)
def _make_langgraph_client(base_url: str, headers: Mapping[str, str]) -> Any:
"""Build the ``langgraph_sdk`` async client used for channel run submission.
``get_client()`` always builds ``httpx.AsyncHTTPTransport(retries=5)`` on an
``httpx.AsyncClient`` that keeps ``trust_env`` at its default ``True`` and
exposes neither ``transport`` nor ``trust_env``, so a loopback Gateway would
still be sent through ``HTTP_PROXY``: control-plane calls are fixed but
``runs.wait`` keeps hitting the proxy-generated error of #7876. Loopback and
private Gateways therefore get an explicit ``trust_env=False`` client handed
to the SDK; external Gateways keep the stock ``get_client()`` path.
"""
from langgraph_sdk import __version__ as sdk_version
from langgraph_sdk import get_client
if control_plane_trust_env(base_url):
return get_client(url=base_url, headers=dict(headers))
try: # langgraph-sdk keeps the async client in a private package since 0.3
from langgraph_sdk._async import LangGraphClient
except ImportError: # older releases expose it directly on ``langgraph_sdk.client``
from langgraph_sdk.client import LangGraphClient
# ``get_client`` also folds an ``LANGGRAPH_API_KEY`` env var into the SDK
# headers; a control-plane Gateway authenticates with the internal auth
# headers above, so only those are forwarded here.
return LangGraphClient(
httpx.AsyncClient(
base_url=base_url,
transport=httpx.AsyncHTTPTransport(retries=_LANGGRAPH_SDK_RETRIES),
timeout=_LANGGRAPH_SDK_TIMEOUT,
headers={"User-Agent": f"langgraph-sdk-py/{sdk_version}", **headers},
trust_env=False,
)
)
def _slim_metadata(meta: dict[str, Any]) -> dict[str, Any]: def _slim_metadata(meta: dict[str, Any]) -> dict[str, Any]:
"""Return a shallow copy of *meta* with known-large keys removed.""" """Return a shallow copy of *meta* with known-large keys removed."""
return {k: v for k, v in meta.items() if k not in _METADATA_DROP_KEYS} return {k: v for k, v in meta.items() if k not in _METADATA_DROP_KEYS}
@ -672,7 +599,7 @@ def _is_run_status_result(result: Any) -> bool:
return isinstance(result, dict) and "messages" not in result and isinstance(result.get("status"), str) return isinstance(result, dict) and "messages" not in result and isinstance(result.get("status"), str)
def _turn_of_message(values: Any, message_id: str, *, thread_id: str | None = None) -> dict[str, Any] | None: def _turn_of_message(values: Any, message_id: str) -> dict[str, Any] | None:
"""Thread *values* cut after the turn that answered human message *message_id*. """Thread *values* cut after the turn that answered human message *message_id*.
The cut ends before the next visible human message, so the response, artifact The cut ends before the next visible human message, so the response, artifact
@ -684,7 +611,7 @@ def _turn_of_message(values: Any, message_id: str, *, thread_id: str | None = No
for index, message in enumerate(messages): for index, message in enumerate(messages):
if isinstance(message, dict) and message.get("type") == "human" and message.get("id") == message_id: if isinstance(message, dict) and message.get("type") == "human" and message.get("id") == message_id:
end = next( end = next(
(later for later in range(index + 1, len(messages)) if isinstance(messages[later], dict) and messages[later].get("type") == "human" and not _is_hidden_human_control_message(messages[later], thread_id=thread_id)), (later for later in range(index + 1, len(messages)) if isinstance(messages[later], dict) and messages[later].get("type") == "human" and not _is_hidden_human_control_message(messages[later])),
len(messages), len(messages),
) )
return {**values, "messages": messages[:end]} return {**values, "messages": messages[:end]}
@ -883,7 +810,7 @@ def _apply_explicit_model_choice(
carrier["model_name"] = model_name carrier["model_name"] = model_name
def _extract_response_text(result: dict | list, *, thread_id: str | None = None) -> str: def _extract_response_text(result: dict | list) -> str:
"""Extract the last AI message text from a LangGraph runs.wait result. """Extract the last AI message text from a LangGraph runs.wait result.
``runs.wait`` returns the final state dict which contains a ``messages`` ``runs.wait`` returns the final state dict which contains a ``messages``
@ -910,7 +837,7 @@ def _extract_response_text(result: dict | list, *, thread_id: str | None = None)
# Stop at the last human message — anything before it is a previous turn # Stop at the last human message — anything before it is a previous turn
if msg_type == "human": if msg_type == "human":
if _is_hidden_human_control_message(msg, thread_id=thread_id): if _is_hidden_human_control_message(msg):
continue continue
break break
@ -1219,7 +1146,7 @@ def _accumulate_stream_text(
return buffers[message_id], message_id return buffers[message_id], message_id
def _extract_artifacts(result: dict | list, *, thread_id: str | None = None) -> list[str]: def _extract_artifacts(result: dict | list) -> list[str]:
"""Extract artifact paths from the last AI response cycle only. """Extract artifact paths from the last AI response cycle only.
Instead of reading the full accumulated ``artifacts`` state (which contains Instead of reading the full accumulated ``artifacts`` state (which contains
@ -1240,39 +1167,27 @@ def _extract_artifacts(result: dict | list, *, thread_id: str | None = None) ->
continue continue
# Stop at the last human message — anything before it is a previous turn # Stop at the last human message — anything before it is a previous turn
if msg.get("type") == "human": if msg.get("type") == "human":
if _is_hidden_human_control_message(msg, thread_id=thread_id): if _is_hidden_human_control_message(msg):
continue continue
break break
# Look for AI messages with present_files tool calls # Look for AI messages with present_files tool calls
if msg.get("type") == "ai": if msg.get("type") == "ai":
message_paths: list[str] = []
for tc in msg.get("tool_calls", []): for tc in msg.get("tool_calls", []):
if isinstance(tc, dict) and tc.get("name") == "present_files": if isinstance(tc, dict) and tc.get("name") == "present_files":
args = tc.get("args", {}) args = tc.get("args", {})
paths = args.get("filepaths", []) paths = args.get("filepaths", [])
if isinstance(paths, list): if isinstance(paths, list):
message_paths.extend(p for p in paths if isinstance(p, str)) artifacts.extend(p for p in paths if isinstance(p, str))
# The scan runs newest-first; prepend so earlier calls stay first. return artifacts
artifacts[:0] = message_paths
# Match the ``merge_artifacts`` reducer: first-presented order, no repeats,
# so a file presented twice in one turn is uploaded once.
return list(dict.fromkeys(artifacts))
def _is_hidden_human_control_message(msg: Mapping[str, Any], *, thread_id: str | None = None) -> bool: def _is_hidden_human_control_message(msg: Mapping[str, Any]) -> bool:
"""Distinguish internal control messages from real hidden user answers.""" """Distinguish internal control messages from real hidden user answers."""
if msg.get("type") != "human": if msg.get("type") != "human":
return False return False
additional_kwargs = msg.get("additional_kwargs") additional_kwargs = msg.get("additional_kwargs")
if not isinstance(additional_kwargs, Mapping): if not isinstance(additional_kwargs, Mapping):
if additional_kwargs is not None:
logger.warning(
"Ignoring malformed message additional_kwargs for thread %s at row seq %s: expected a mapping, got %s",
thread_id or msg.get("thread_id", "<unknown>"),
msg.get("seq", "<unknown>"),
type(additional_kwargs).__name__,
)
return False return False
return additional_kwargs.get("hide_from_ui") is True and read_human_input_response(additional_kwargs) is None return additional_kwargs.get("hide_from_ui") is True and read_human_input_response(additional_kwargs) is None
@ -1680,7 +1595,6 @@ class ChannelManager:
inbound_dedupe_store: InboundDedupeStore | None = None, inbound_dedupe_store: InboundDedupeStore | None = None,
get_stream_bridge: Callable[[], StreamBridge | None] | None = None, get_stream_bridge: Callable[[], StreamBridge | None] | None = None,
reply_locale: ReplyLocaleResolver | None = None, reply_locale: ReplyLocaleResolver | None = None,
dispatch_coordination_task: Callable[..., Awaitable[dict]] | None = None,
) -> None: ) -> None:
if isinstance(max_concurrency, bool) or not isinstance(max_concurrency, int) or max_concurrency <= 0: if isinstance(max_concurrency, bool) or not isinstance(max_concurrency, int) or max_concurrency <= 0:
raise ValueError("max_concurrency must be a positive integer") raise ValueError("max_concurrency must be a positive integer")
@ -1697,7 +1611,6 @@ class ChannelManager:
self._channel_sessions = dict(channel_sessions or {}) self._channel_sessions = dict(channel_sessions or {})
self._connection_repo = connection_repo self._connection_repo = connection_repo
self._require_bound_identity = require_bound_identity self._require_bound_identity = require_bound_identity
self._dispatch_coordination_task = dispatch_coordination_task
# Language of the /goal replies; ChannelService passes the owner-aware # Language of the /goal replies; ChannelService passes the owner-aware
# resolver, and a directly built manager replies in en-US. # resolver, and a directly built manager replies in en-US.
self._reply_locale = reply_locale or ReplyLocaleResolver() self._reply_locale = reply_locale or ReplyLocaleResolver()
@ -1766,7 +1679,6 @@ class ChannelManager:
# Adapters claim the same key through the bus before platform side # Adapters claim the same key through the bus before platform side
# effects a duplicate must not repeat (Discord thread creation). # effects a duplicate must not repeat (Discord thread creation).
self.bus.set_inbound_claim(self._claim_inbound, self._release_inbound_claim) self.bus.set_inbound_claim(self._claim_inbound, self._release_inbound_claim)
self.bus.coordination_tasks_enabled = dispatch_coordination_task is not None
# Per-thread follow-up buffers for busy fire_and_forget channels that # Per-thread follow-up buffers for busy fire_and_forget channels that
# opted into ChannelRunPolicy.buffer_followups_on_busy (issue #4121 # opted into ChannelRunPolicy.buffer_followups_on_busy (issue #4121
# Slice 2). Keyed by thread_id -> OrderedDict[dedupe_key -> entry], # Slice 2). Keyed by thread_id -> OrderedDict[dedupe_key -> entry],
@ -2183,21 +2095,14 @@ class ChannelManager:
self._maybe_spawn_followup_watcher(thread_id, result, carrier_msg) self._maybe_spawn_followup_watcher(thread_id, result, carrier_msg)
async def _publish_progress_update(self, msg: InboundMessage, thread_id: str, text: str, *, is_final: bool = False) -> None: async def _publish_progress_update(self, msg: InboundMessage, thread_id: str, text: str) -> None:
"""Publish a turn update; progress by default, final for standalone replies.
A non-final outbound joins the run's stream: streaming channels update
the same message with later chunks (and the final answer), while QQ and
DingTalk card mode drop it before a stream exists. Callers that must
stay visible on every channel publish ``is_final=True``.
"""
await self.bus.publish_outbound( await self.bus.publish_outbound(
OutboundMessage( OutboundMessage(
channel_name=msg.channel_name, channel_name=msg.channel_name,
chat_id=msg.chat_id, chat_id=msg.chat_id,
thread_id=thread_id, thread_id=thread_id,
text=text, text=text,
is_final=is_final, is_final=False,
thread_ts=msg.thread_ts, thread_ts=msg.thread_ts,
connection_id=msg.connection_id, connection_id=msg.connection_id,
owner_user_id=msg.owner_user_id, owner_user_id=msg.owner_user_id,
@ -2332,7 +2237,10 @@ class ChannelManager:
``ClarificationMiddleware`` would otherwise dead-end a webhook ``ClarificationMiddleware`` would otherwise dead-end a webhook
run waiting for a synchronous reply that only arrives as a run waiting for a synchronous reply that only arrives as a
later, separate webhook delivery. later, separate webhook delivery.
* Optional channel-specific credentials provider. * 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).
``recursion_limit`` is applied inside :meth:`_resolve_run_params` ``recursion_limit`` is applied inside :meth:`_resolve_run_params`
instead because it lives on ``run_config`` (not ``run_context``) instead because it lives on ``run_config`` (not ``run_context``)
@ -2403,9 +2311,11 @@ class ChannelManager:
def _get_client(self): def _get_client(self):
"""Return the ``langgraph_sdk`` async client, creating it on first use.""" """Return the ``langgraph_sdk`` async client, creating it on first use."""
if self._client is None: if self._client is None:
self._client = _make_langgraph_client( from langgraph_sdk import get_client
self._langgraph_url,
{**create_internal_auth_headers(), **self._csrf_headers()}, self._client = get_client(
url=self._langgraph_url,
headers={**create_internal_auth_headers(), **self._csrf_headers()},
) )
return self._client return self._client
@ -2820,15 +2730,11 @@ class ChannelManager:
# Transient/unexpected failure: release the dedupe key so a provider # Transient/unexpected failure: release the dedupe key so a provider
# redelivery of the same message can recover instead of being dropped # redelivery of the same message can recover instead of being dropped
# for the dedupe TTL -- unless the run may already be executing. # for the dedupe TTL -- unless the run may already be executing.
# Decided from this error, before the reply, so a shutdown that
# cancels the reply cannot turn a rejected run into a kept key.
# Stale /model pin admission failures are handled at the # Stale /model pin admission failures are handled at the
# run-creation sites, which know the selection the run used. # run-creation sites, which know the selection the run used.
await self._send_error_then_release_dedupe( if not self._keep_dedupe_key_after(msg, exc):
msg, await self._release_inbound_dedupe_key(msg)
"An internal error occurred. Please try again.", await self._send_error(msg, "An internal error occurred. Please try again.")
release=not self._keep_dedupe_key_after(msg, exc),
)
# -- chat handling ----------------------------------------------------- # -- chat handling -----------------------------------------------------
@ -2919,7 +2825,7 @@ class ChannelManager:
return return
await self.store.set_thread_id( await self.store.set_thread_id(
fallback_store_channel(msg.channel_name, msg.topic_id, self._connection_repo), msg.channel_name,
msg.chat_id, msg.chat_id,
thread_id, thread_id,
topic_id=msg.topic_id, topic_id=msg.topic_id,
@ -2937,7 +2843,7 @@ class ChannelManager:
external_topic_id=msg.topic_id, external_topic_id=msg.topic_id,
thread_id=thread_id, thread_id=thread_id,
) )
return await self.store.claim_thread_id(fallback_store_channel(msg.channel_name, msg.topic_id, self._connection_repo), msg.chat_id, thread_id, topic_id=msg.topic_id, user_id=msg.user_id) return await self.store.claim_thread_id(msg.channel_name, msg.chat_id, thread_id, topic_id=msg.topic_id, user_id=msg.user_id)
def _remember_thread_agent(self, thread_id: str, agent_name: str | None) -> None: def _remember_thread_agent(self, thread_id: str, agent_name: str | None) -> None:
if len(self._thread_agent_names) > IN_PROCESS_CACHE_MAX_ENTRIES: if len(self._thread_agent_names) > IN_PROCESS_CACHE_MAX_ENTRIES:
@ -3320,7 +3226,6 @@ class ChannelManager:
extra_context: dict[str, Any] | None = None, extra_context: dict[str, Any] | None = None,
*, *,
bound_identity_checked: bool = False, bound_identity_checked: bool = False,
expected_thread_id: str | None = None,
) -> None: ) -> None:
# Normal entry paths already run the bound-identity check in # Normal entry paths already run the bound-identity check in
# _handle_message() or _handle_command(). Keep this default False so # _handle_message() or _handle_command(). Keep this default False so
@ -3337,10 +3242,7 @@ class ChannelManager:
# first message for the chat. topic_id may be None (e.g. Telegram # first message for the chat. topic_id may be None (e.g. Telegram
# private chats) — the store handles this by using the "channel:chat_id" # private chats) — the store handles this by using the "channel:chat_id"
# key without a topic suffix. # key without a topic suffix.
if expected_thread_id is None:
thread_id, created = await self._get_or_create_thread(client, msg) thread_id, created = await self._get_or_create_thread(client, msg)
else:
thread_id, created = expected_thread_id, False
if not created: if not created:
logger.info("[Manager] reusing thread: thread_id=%s for topic_id=%s", thread_id, msg.topic_id) logger.info("[Manager] reusing thread: thread_id=%s for topic_id=%s", thread_id, msg.topic_id)
await self._update_thread_channel_metadata(client, msg, thread_id) await self._update_thread_channel_metadata(client, msg, thread_id)
@ -3380,7 +3282,6 @@ class ChannelManager:
thread_id, thread_id,
extra_context=extra_context, extra_context=extra_context,
storage_user_id=storage_user_id, storage_user_id=storage_user_id,
check_thread_binding=expected_thread_id is not None,
) )
finally: finally:
self._finish_serialized_thread_run( self._finish_serialized_thread_run(
@ -3398,7 +3299,6 @@ class ChannelManager:
*, *,
extra_context: dict[str, Any] | None = None, extra_context: dict[str, Any] | None = None,
storage_user_id: str | None = None, storage_user_id: str | None = None,
check_thread_binding: bool = False,
) -> None: ) -> None:
if storage_user_id is None: if storage_user_id is None:
storage_user_id = _channel_storage_user_id(msg) storage_user_id = _channel_storage_user_id(msg)
@ -3413,7 +3313,11 @@ class ChannelManager:
pinned_model_value = run_context.get("model_name") 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 expected_pin = pinned_model_value.strip() if isinstance(pinned_model_value, str) and pinned_model_value.strip() else None
# Apply the run policy registered by the channel. # 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.
policy = await self._apply_channel_policy(msg, run_context) policy = await self._apply_channel_policy(msg, run_context)
# If the inbound message contains file attachments, let the channel # If the inbound message contains file attachments, let the channel
@ -3434,11 +3338,6 @@ class ChannelManager:
uploaded = await _ingest_inbound_files(thread_id, msg, user_id=storage_user_id) uploaded = await _ingest_inbound_files(thread_id, msg, user_id=storage_user_id)
human_message = _human_input_message_with_channel_response(msg.text, metadata=msg.metadata, original_content=original_text, files=uploaded or None, message_id=human_message_id) human_message = _human_input_message_with_channel_response(msg.text, metadata=msg.metadata, original_content=original_text, files=uploaded or None, message_id=human_message_id)
# Metadata loading, queueing and file preparation may have awaited a
# /new. Keep the saved thread pinned and check its binding at handoff.
if check_thread_binding and await self._lookup_thread_id(msg) != thread_id:
raise _ConversationSwitched
if self._channel_supports_streaming(msg.channel_name): if self._channel_supports_streaming(msg.channel_name):
await self._handle_streaming_chat( await self._handle_streaming_chat(
client, client,
@ -3489,7 +3388,6 @@ class ChannelManager:
# behaviorally identical to the previous bare ``await``. # behaviorally identical to the previous bare ``await``.
result = await client.runs.create(thread_id, assistant_id, **run_kwargs) result = await client.runs.create(thread_id, assistant_id, **run_kwargs)
except Exception as exc: except Exception as exc:
_note_run_error(exc)
if _is_admitted_run_conflict(exc): if _is_admitted_run_conflict(exc):
# An earlier delivery's run; it posts its own outcome. # An earlier delivery's run; it posts its own outcome.
_note_run_confirmed() _note_run_confirmed()
@ -3499,14 +3397,16 @@ class ChannelManager:
logger.warning("[Manager] thread busy (concurrent run rejected): thread_id=%s", thread_id) logger.warning("[Manager] thread busy (concurrent run rejected): thread_id=%s", thread_id)
if policy.buffer_followups_on_busy: if policy.buffer_followups_on_busy:
self._buffer_followup(thread_id, msg) self._buffer_followup(thread_id, msg)
else:
# Swallowed like the generic handler would not be: release the # Swallowed like the generic handler would not be: release the
# key so the provider's redelivery can retry once the thread # key so the provider's redelivery can retry once the thread
# frees, instead of being dropped for the dedupe TTL. A # frees, instead of being dropped for the dedupe TTL.
# buffered follow-up keeps it. await self._release_inbound_dedupe_key(msg)
await self._send_error_then_release_dedupe(msg, THREAD_BUSY_MESSAGE, release=not policy.buffer_followups_on_busy) await self._send_error(msg, THREAD_BUSY_MESSAGE)
return return
if recovery := await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id): if recovery := await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id):
await self._send_error_then_release_dedupe(msg, recovery.text) await self._send_error(msg, recovery.text)
await self._release_inbound_dedupe_key(msg)
return return
raise raise
_note_run_confirmed() _note_run_confirmed()
@ -3528,7 +3428,6 @@ class ChannelManager:
**run_kwargs, **run_kwargs,
) )
except Exception as exc: except Exception as exc:
_note_run_error(exc)
if _is_admitted_run_conflict(exc): if _is_admitted_run_conflict(exc):
_note_run_confirmed() _note_run_confirmed()
logger.info("[Manager] run already admitted for this message: thread_id=%s (%s)", thread_id, exc) logger.info("[Manager] run already admitted for this message: thread_id=%s (%s)", thread_id, exc)
@ -3538,16 +3437,19 @@ class ChannelManager:
logger.warning("[Manager] thread busy (concurrent run rejected): thread_id=%s", thread_id) logger.warning("[Manager] thread busy (concurrent run rejected): thread_id=%s", thread_id)
# Same reason as the fire-and-forget branch above: this error is # Same reason as the fire-and-forget branch above: this error is
# handled here rather than re-raised, so release explicitly. # handled here rather than re-raised, so release explicitly.
await self._send_error_then_release_dedupe(msg, THREAD_BUSY_MESSAGE) await self._release_inbound_dedupe_key(msg)
await self._send_error(msg, THREAD_BUSY_MESSAGE)
return return
if step_limit_text := _step_limit_text(exc): if step_limit_text := _step_limit_text(exc):
_note_run_confirmed()
logger.warning("[Manager] run stopped at its step limit: thread_id=%s", thread_id) logger.warning("[Manager] run stopped at its step limit: thread_id=%s", thread_id)
# The run ended, as after a terminal error frame: release the key. await self._send_error(msg, step_limit_text)
await self._send_error_then_release_dedupe(msg, step_limit_text) # The run ended, as after a terminal error frame: release the key
# only after the reply, so a redelivery cannot overtake it.
await self._release_inbound_dedupe_key(msg)
return return
if recovery := await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id): if recovery := await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id):
await self._send_error_then_release_dedupe(msg, recovery.text) await self._release_inbound_dedupe_key(msg)
await self._send_error(msg, recovery.text)
return return
raise raise
_note_run_confirmed() _note_run_confirmed()
@ -3560,9 +3462,9 @@ class ChannelManager:
return return
result = await self._admitted_turn(client, msg, thread_id) or result result = await self._admitted_turn(client, msg, thread_id) or result
response_text = _extract_response_text(result, thread_id=thread_id) response_text = _extract_response_text(result)
pending_clarification = _has_current_turn_clarification(result) pending_clarification = _has_current_turn_clarification(result)
artifacts = _extract_artifacts(result, thread_id=thread_id) artifacts = _extract_artifacts(result)
logger.info( logger.info(
"[Manager] agent response received: thread_id=%s, response_len=%d, artifacts=%d", "[Manager] agent response received: thread_id=%s, response_len=%d, artifacts=%d",
@ -3615,7 +3517,7 @@ class ChannelManager:
except Exception: except Exception:
logger.warning("[Manager] failed to read thread state for an admitted run: thread_id=%s", thread_id, exc_info=True) logger.warning("[Manager] failed to read thread state for an admitted run: thread_id=%s", thread_id, exc_info=True)
return None return None
return _turn_of_message(state.get("values") if isinstance(state, dict) else None, message_id, thread_id=thread_id) return _turn_of_message(state.get("values") if isinstance(state, dict) else None, message_id)
async def _handle_streaming_chat( async def _handle_streaming_chat(
self, self,
@ -3692,7 +3594,7 @@ class ChannelManager:
# Clarification text is only in the values snapshot; # Clarification text is only in the values snapshot;
# publish it so the user sees the question mid-stream. # publish it so the user sees the question mid-stream.
if _has_current_turn_clarification(data): if _has_current_turn_clarification(data):
clarification_text = _extract_response_text(data, thread_id=thread_id) clarification_text = _extract_response_text(data)
if clarification_text and clarification_text != latest_text: if clarification_text and clarification_text != latest_text:
latest_text = clarification_text latest_text = clarification_text
@ -3739,14 +3641,12 @@ class ChannelManager:
pin_recovery = await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id) pin_recovery = await self._stale_pin_recovery(msg, exc, expected_pin=expected_pin, thread_id=thread_id)
pin_recovery_text = pin_recovery.text if pin_recovery else None pin_recovery_text = pin_recovery.text if pin_recovery else None
finally: finally:
if stream_error is not None:
_note_run_error(stream_error)
if replay_gap and last_values is None and not latest_text and stream_error is None: if replay_gap and last_values is None and not latest_text and stream_error is None:
last_values = await self._admitted_turn(client, msg, thread_id) last_values = await self._admitted_turn(client, msg, thread_id)
result = last_values if last_values is not None else {"messages": [{"type": "ai", "content": latest_text}]} result = last_values if last_values is not None else {"messages": [{"type": "ai", "content": latest_text}]}
response_text = _extract_response_text(result, thread_id=thread_id) response_text = _extract_response_text(result)
pending_clarification = _has_current_turn_clarification(result) pending_clarification = _has_current_turn_clarification(result)
artifacts = _extract_artifacts(result, thread_id=thread_id) artifacts = _extract_artifacts(result)
# Reuse the storage owner resolved by _handle_chat so artifact delivery # Reuse the storage owner resolved by _handle_chat so artifact delivery
# matches the upload bucket and we avoid re-running _safe_user_id_for_run # matches the upload bucket and we avoid re-running _safe_user_id_for_run
# (and its possible filesystem touch) on the streaming-error path. # (and its possible filesystem touch) on the streaming-error path.
@ -3879,13 +3779,11 @@ class ChannelManager:
reply = await self._handle_goal_command(msg, parts[1] if len(parts) > 1 else "") reply = await self._handle_goal_command(msg, parts[1] if len(parts) > 1 else "")
if reply is None: if reply is None:
return return
elif reply is None and msg.channel_name == "feishu" and self._dispatch_coordination_task is not None and is_feishu_task_command(text):
reply = await self._handle_task_command(msg, parts[1] if len(parts) > 1 else "")
elif reply is None and command == "help": elif reply is None and command == "help":
reply = ( reply = (
"Available commands:\n" "Available commands:\n"
"/bootstrap — Start a bootstrap session (enables agent setup)\n" "/bootstrap — Start a bootstrap session (enables agent setup)\n"
"/goal [condition|clear|from-chat [hint]] — Set, show, clear, or compose the goal from the conversation\n" "/goal [condition|clear] — Set, show, or clear an active goal\n"
"/new — Start a new conversation\n" "/new — Start a new conversation\n"
"/status — Show current thread info\n" "/status — Show current thread info\n"
"/models — List available models\n" "/models — List available models\n"
@ -3896,8 +3794,6 @@ class ChannelManager:
"/<skill-name> <task> — Activate an enabled skill for one turn\n" "/<skill-name> <task> — Activate an enabled skill for one turn\n"
"/help — Show this help" "/help — Show this help"
) )
if msg.channel_name == "feishu" and msg.metadata.get("chat_type") == "p2p" and self._dispatch_coordination_task is not None:
reply += "\n/task start <objective> — Start a task and receive its result in this chat"
elif reply is None: elif reply is None:
thread_id = await self._lookup_thread_id(msg) thread_id = await self._lookup_thread_id(msg)
if thread_id: if thread_id:
@ -3932,32 +3828,6 @@ class ChannelManager:
) )
await self.bus.publish_outbound(outbound) await self.bus.publish_outbound(outbound)
async def _handle_task_command(self, msg: InboundMessage, args: str) -> str:
if msg.metadata.get("chat_type") != "p2p":
return "Tasks are available in bound Feishu private chats."
if self._dispatch_coordination_task is None:
return "Tasks are unavailable on this DeerFlow deployment."
parts = args.split(maxsplit=1)
if len(parts) != 2 or parts[0].lower() != FEISHU_TASK_START_SUBCOMMAND or not 0 < len(parts[1]) <= 16384:
return "Usage: /task start <objective> (up to 16,384 characters)"
request_id = self._run_idempotency_key(msg)
if request_id is None:
return "This message has no delivery ID. Send a new message to start the task."
try:
view = await self._dispatch_coordination_task(msg, request_id=request_id, objective=parts[1], notify_completion=True)
except AgentRunError as exc:
if exc.status_code == 403:
return "Your DeerFlow account or this private chat is not authorized to start tasks."
logger.warning("Feishu task submission failed (%s)", exc.status_code)
return "Could not start the task. Try again later."
except TaskConflict:
return "This message ID was already used to start a different task."
task = view["task"]
reply = f"Task ID: {task['id']}\nStatus: {task['status']}"
if view["authorization_required"]:
reply += "\nThis task requires authorization to continue."
return reply
async def _handle_agent_command(self, msg: InboundMessage, args: str) -> str: async def _handle_agent_command(self, msg: InboundMessage, args: str) -> str:
"""List owner-scoped agents or pin one to a fresh conversation.""" """List owner-scoped agents or pin one to a fresh conversation."""
parts = args.split() parts = args.split()
@ -4154,27 +4024,6 @@ class ChannelManager:
self._remember_thread_model(thread_id, name) self._remember_thread_model(thread_id, name)
return f"Model '{name}' selected. It applies to this conversation from the next message." return f"Model '{name}' selected. It applies to this conversation from the next message."
@staticmethod
def _is_goal_in_flight_error(error: Exception) -> bool:
"""Recognize only the Gateway's known goal-write conflict, not arbitrary 409s."""
if not isinstance(error, httpx.HTTPStatusError) or error.response.status_code != 409:
return False
# POST (from-chat synthesis) saves the goal like PUT, so it carries the
# same "Set the goal ..." detail; recognizing it lets the IM reply reuse
# the busy wording for both the pre-check and the save-time race.
detail = {
"PUT": "Thread has a run in flight. Set the goal after the run finishes.",
"POST": "Thread has a run in flight. Set the goal after the run finishes.",
"DELETE": "Thread has a run in flight. Clear the goal after the run finishes.",
}.get(error.request.method)
if detail is None:
return False
try:
body = error.response.json()
except ValueError:
return False
return isinstance(body, Mapping) and body.get("detail") == detail
async def _goal_request( async def _goal_request(
self, self,
method: str, method: str,
@ -4182,15 +4031,13 @@ class ChannelManager:
*, *,
headers: dict[str, str], headers: dict[str, str],
json: dict[str, Any] | None = None, json: dict[str, Any] | None = None,
suffix: str = "",
timeout: float | httpx.Timeout = 10,
) -> dict[str, Any]: ) -> dict[str, Any]:
async with _make_gateway_client(self._gateway_url) as http: async with httpx.AsyncClient() as http:
request = getattr(http, method.lower()) request = getattr(http, method.lower())
kwargs: dict[str, Any] = {"timeout": timeout, "headers": {**headers, **self._csrf_headers()}} kwargs: dict[str, Any] = {"timeout": 10, "headers": {**headers, **self._csrf_headers()}}
if json is not None: if json is not None:
kwargs["json"] = json kwargs["json"] = json
response = await request(f"{self._gateway_url}/api/threads/{quote(thread_id, safe='')}/goal{suffix}", **kwargs) response = await request(f"{self._gateway_url}/api/threads/{quote(thread_id, safe='')}/goal", **kwargs)
response.raise_for_status() response.raise_for_status()
return response.json() or {} return response.json() or {}
@ -4250,24 +4097,17 @@ class ChannelManager:
return await self._goal_reply(msg, "cleared") return await self._goal_reply(msg, "cleared")
try: try:
await self._goal_request("delete", thread_id, headers=headers) await self._goal_request("delete", thread_id, headers=headers)
except Exception as exc: except Exception:
if self._is_goal_in_flight_error(exc):
return await self._goal_reply(msg, "busy")
logger.exception("Failed to clear goal through gateway") logger.exception("Failed to clear goal through gateway")
return await self._goal_reply(msg, "clear_failed") return await self._goal_reply(msg, "clear_failed")
return await self._goal_reply(msg, "cleared") return await self._goal_reply(msg, "cleared")
if command.kind == "from_chat":
return await self._handle_goal_from_chat(msg, thread_id, guidance=command.objective, headers=headers)
if not thread_id: if not thread_id:
thread_id, _ = await self._create_first_thread(self._get_client(), msg) thread_id, _ = await self._create_first_thread(self._get_client(), msg)
try: try:
await self._goal_request("put", thread_id, headers=headers, json={"objective": command.objective}) await self._goal_request("put", thread_id, headers=headers, json={"objective": command.objective})
except Exception as exc: except Exception:
if self._is_goal_in_flight_error(exc):
return await self._goal_reply(msg, "busy")
logger.exception("Failed to set goal through gateway") logger.exception("Failed to set goal through gateway")
return await self._goal_reply(msg, "set_failed") return await self._goal_reply(msg, "set_failed")
@ -4277,108 +4117,6 @@ class ChannelManager:
await self._handle_chat(chat_msg, bound_identity_checked=True) await self._handle_chat(chat_msg, bound_identity_checked=True)
return None return None
async def _handle_goal_from_chat(self, msg: InboundMessage, thread_id: str | None, *, guidance: str, headers: dict[str, str]) -> str | None:
"""``/goal from-chat``: synthesize an objective from the conversation, then start one run.
Unlike the literal ``set`` branch — which starts the run silently because
the user typed the objective — the objective here is model-synthesized,
so the user is shown what was saved before the run streams its output.
Saving and the busy/409 guard stay on the Gateway route; this only
reports the outcome and hands the saved objective to ``_handle_chat``.
Run handoff keeps this thread pinned and re-checks the binding after
confirmation delivery and preparation. Admission evidence distinguishes
rejected starts from requests whose response was lost.
"""
if not thread_id:
return await self._goal_reply(msg, "from_chat_no_thread")
try:
result = await self._goal_request("post", thread_id, headers=headers, json={"guidance": guidance or None}, suffix="/from-chat", timeout=_GOAL_FROM_CHAT_TIMEOUT)
except Exception as exc:
return await self._goal_from_chat_error_reply(msg, exc)
goal = result.get("goal") if isinstance(result, Mapping) else None
objective = goal.get("objective") if isinstance(goal, Mapping) else None
if not isinstance(objective, str) or not objective.strip():
logger.warning("Goal from-chat returned no usable objective")
return await self._goal_reply(msg, "from_chat_failed")
from dataclasses import replace as _dc_replace
chat_msg = _dc_replace(msg, text=objective, msg_type=InboundMessageType.CHAT)
reply = None
may_be_running = False
with _run_admission_scope() as admission:
try:
if await self._lookup_thread_id(msg) != thread_id:
raise _ConversationSwitched
locale = await self._reply_locale.locale_for(_effective_owner_user_id(msg))
try:
# A separate final outbound keeps the saved objective visible
# alongside the run's stream on every IM provider.
await self._publish_progress_update(msg, thread_id, goal_reply_text("from_chat_saved", locale).format(objective=objective), is_final=True)
except Exception:
logger.warning("Goal from-chat saved but the confirmation card failed", exc_info=True)
await self._handle_chat(chat_msg, bound_identity_checked=True, expected_thread_id=thread_id)
except _ConversationSwitched:
reply = (await self._goal_reply(msg, "from_chat_conversation_switched")).format(objective=objective)
except Exception as exc:
_note_run_error(exc)
logger.warning("Goal from-chat run handoff failed", exc_info=True)
if reply is None and admission.error is not None and not admission.confirmed:
error = admission.error
rejected = isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout))
if isinstance(error, (httpx.HTTPStatusError, APIStatusError)):
rejected = 400 <= error.response.status_code < 500
may_be_running = admission.requested and not rejected
reply = await self._goal_reply(msg, "from_chat_run_status_unknown" if may_be_running else "from_chat_saved_but_not_started")
if reply is not None:
# Use the saved thread even when its conversation binding cannot
# be read. Deliver the recovery advice before releasing dedupe.
await self._publish_progress_update(msg, thread_id, reply, is_final=True)
if admission.error is not None and not may_be_running:
await self._release_inbound_dedupe_key(msg)
return None
async def _goal_from_chat_error_reply(self, msg: InboundMessage, exc: Exception) -> str:
"""Map a from-chat Gateway error to the owner-language reply.
Only the known in-flight conflict, a client-side timeout, and the
structured synthesis outcomes (``unclear``, ``no_context``,
``pending_clarification``, ``goal_changed``) get their own wording;
anything else degrades to the generic retry reply. The model's ``reason``
is never read here, and the Gateway does not log it verbatim either.
"""
if self._is_goal_in_flight_error(exc):
return await self._goal_reply(msg, "busy")
if isinstance(exc, httpx.TimeoutException):
# The Gateway may finish synthesizing and save the goal after this
# client stops waiting, so the reply must not claim it failed.
logger.warning("Goal from-chat request timed out; the goal may still be saved", exc_info=True)
return await self._goal_reply(msg, "from_chat_timeout")
code = None
if isinstance(exc, httpx.HTTPStatusError):
try:
body = exc.response.json()
except ValueError:
body = None
detail = body.get("detail") if isinstance(body, Mapping) else None
if isinstance(detail, Mapping):
code = detail.get("code")
if code == "unclear":
return await self._goal_reply(msg, "from_chat_unclear")
if code == "no_context":
return await self._goal_reply(msg, "from_chat_no_context")
if code == "pending_clarification":
return await self._goal_reply(msg, "from_chat_pending_clarification")
if code == "goal_changed":
# The save's compare-and-swap found a newer checkpoint: another
# goal (or write) landed during synthesis, so nothing was saved.
return await self._goal_reply(msg, "from_chat_changed")
logger.warning("Goal from-chat failed through gateway", exc_info=True)
return await self._goal_reply(msg, "from_chat_failed")
async def _fetch_gateway_json(self, path: str, *, msg: InboundMessage | None = None) -> dict[str, Any]: async def _fetch_gateway_json(self, path: str, *, msg: InboundMessage | None = None) -> dict[str, Any]:
"""GET a Gateway API path and return the parsed JSON body. """GET a Gateway API path and return the parsed JSON body.
@ -4386,7 +4124,7 @@ class ChannelManager:
replies should catch and degrade (see ``_fetch_gateway``). replies should catch and degrade (see ``_fetch_gateway``).
""" """
headers = _owner_headers(msg) if msg is not None else None headers = _owner_headers(msg) if msg is not None else None
async with _make_gateway_client(self._gateway_url) as http: async with httpx.AsyncClient() as http:
resp = await http.get( resp = await http.get(
f"{self._gateway_url}{path}", f"{self._gateway_url}{path}",
timeout=10, timeout=10,
@ -4410,28 +4148,6 @@ class ChannelManager:
# -- error helper ------------------------------------------------------ # -- error helper ------------------------------------------------------
async def _send_error_then_release_dedupe(self, msg: InboundMessage, error_text: str, *, release: bool = True) -> None:
"""Send a failed run's reply, then release *msg*'s dedupe key if *release*.
The release comes after the reply, so a provider redelivery cannot
overtake it. The caller decides *release* from the run's own failure;
a reply that raises or is cancelled (shutdown cancels the worker while
the channel send is in flight) still releases, because the worker's
cancellation handler would otherwise read the cancellation as a
possibly admitted run and keep the key for the dedupe TTL.
"""
try:
await self._send_error(msg, error_text)
except BaseException:
if release:
try:
await self._release_inbound_dedupe_key(msg)
except Exception:
logger.exception("[Manager] failed to release inbound dedupe key after a failed reply")
raise
if release:
await self._release_inbound_dedupe_key(msg)
async def _send_error(self, msg: InboundMessage, error_text: str) -> None: async def _send_error(self, msg: InboundMessage, error_text: str) -> None:
outbound = OutboundMessage( outbound = OutboundMessage(
channel_name=msg.channel_name, channel_name=msg.channel_name,

View File

@ -223,7 +223,6 @@ class MessageBus:
if isinstance(inbound_queue_maxsize, bool) or not isinstance(inbound_queue_maxsize, int) or inbound_queue_maxsize <= 0: if isinstance(inbound_queue_maxsize, bool) or not isinstance(inbound_queue_maxsize, int) or inbound_queue_maxsize <= 0:
raise ValueError("inbound_queue_maxsize must be a positive integer") raise ValueError("inbound_queue_maxsize must be a positive integer")
self.coordination_tasks_enabled: bool = False
self._inbound_queue: asyncio.Queue[InboundMessage] = asyncio.Queue(maxsize=inbound_queue_maxsize) self._inbound_queue: asyncio.Queue[InboundMessage] = asyncio.Queue(maxsize=inbound_queue_maxsize)
# Provider callbacks may reserve capacity from SDK-owned threads before # Provider callbacks may reserve capacity from SDK-owned threads before
# scheduling async identity/ack preparation on the Gateway loop. # scheduling async identity/ack preparation on the Gateway loop.

View File

@ -215,7 +215,6 @@ class ChannelService:
require_bound_identity: bool = False, require_bound_identity: bool = False,
app_config: AppConfig | None = None, app_config: AppConfig | None = None,
get_stream_bridge: Callable[[], StreamBridge | None] | None = None, get_stream_bridge: Callable[[], StreamBridge | None] | None = None,
dispatch_coordination_task: Callable[..., Awaitable[dict]] | None = None,
store: ChannelStore | None = None, store: ChannelStore | None = None,
leadership: ChannelLeadership | None = None, leadership: ChannelLeadership | None = None,
runtime_config_store: RuntimeConfigStore | None = None, runtime_config_store: RuntimeConfigStore | None = None,
@ -237,7 +236,6 @@ class ChannelService:
# runs this constructor off the loop. # runs this constructor off the loop.
self.store: ChannelStore = store if store is not None else resolve_channel_store(app_config) self.store: ChannelStore = store if store is not None else resolve_channel_store(app_config)
self._connection_repo = connection_repo self._connection_repo = connection_repo
self._connections_configured = bool(getattr(getattr(app_config, "channel_connections", None), "enabled", False))
# Language of DeerFlow's own replies (/connect, /goal): the owner's web UI # Language of DeerFlow's own replies (/connect, /goal): the owner's web UI
# language, read from the connection repository's database, else # language, read from the connection repository's database, else
# channel_connections.notification_locale (captured here; restart-scoped). # channel_connections.notification_locale (captured here; restart-scoped).
@ -265,7 +263,6 @@ class ChannelService:
require_bound_identity=require_bound_identity, require_bound_identity=require_bound_identity,
inbound_dedupe_store=make_inbound_dedupe_store(app_config), inbound_dedupe_store=make_inbound_dedupe_store(app_config),
get_stream_bridge=get_stream_bridge, get_stream_bridge=get_stream_bridge,
dispatch_coordination_task=dispatch_coordination_task,
reply_locale=self._reply_locale, reply_locale=self._reply_locale,
) )
self._channels: dict[str, Any] = {} # name -> Channel instance self._channels: dict[str, Any] = {} # name -> Channel instance
@ -299,7 +296,6 @@ class ChannelService:
app_config: AppConfig | None = None, app_config: AppConfig | None = None,
*, *,
get_stream_bridge: Callable[[], StreamBridge | None] | None = None, get_stream_bridge: Callable[[], StreamBridge | None] | None = None,
dispatch_coordination_task: Callable[..., Awaitable[dict]] | None = None,
credentials_cipher: Any | None = None, credentials_cipher: Any | None = None,
multi_process: bool = False, multi_process: bool = False,
lease_owner_id: str | None = None, lease_owner_id: str | None = None,
@ -337,7 +333,6 @@ class ChannelService:
require_bound_identity=require_bound_identity, require_bound_identity=require_bound_identity,
app_config=app_config, app_config=app_config,
get_stream_bridge=get_stream_bridge, get_stream_bridge=get_stream_bridge,
dispatch_coordination_task=dispatch_coordination_task,
leadership=leadership, leadership=leadership,
runtime_config_store=runtime_config_store, runtime_config_store=runtime_config_store,
credentials_cipher=credentials_cipher, credentials_cipher=credentials_cipher,
@ -747,10 +742,6 @@ class ChannelService:
logger.warning("Refusing to start %s while ChannelService is stopped or stopping", name) logger.warning("Refusing to start %s while ChannelService is stopped or stopping", name)
return False return False
if name == "feishu" and self._connections_configured and self._connection_repo is None:
logger.error("Feishu requires an available connection repository when channel connections are enabled")
return False
import_path = _CHANNEL_REGISTRY.get(name) import_path = _CHANNEL_REGISTRY.get(name)
if not import_path: if not import_path:
logger.warning("Unknown channel type") logger.warning("Unknown channel type")
@ -1192,7 +1183,6 @@ async def start_channel_service(
app_config: AppConfig | None = None, app_config: AppConfig | None = None,
*, *,
get_stream_bridge: Callable[[], StreamBridge | None] | None = None, get_stream_bridge: Callable[[], StreamBridge | None] | None = None,
dispatch_coordination_task: Callable[..., Awaitable[dict]] | None = None,
credentials_cipher: Any | None = None, credentials_cipher: Any | None = None,
multi_process: bool = False, multi_process: bool = False,
lease_owner_id: str | None = None, lease_owner_id: str | None = None,
@ -1218,7 +1208,6 @@ async def start_channel_service(
ChannelService.from_app_config, ChannelService.from_app_config,
app_config, app_config,
get_stream_bridge=get_stream_bridge, get_stream_bridge=get_stream_bridge,
dispatch_coordination_task=dispatch_coordination_task,
credentials_cipher=credentials_cipher, credentials_cipher=credentials_cipher,
multi_process=multi_process, multi_process=multi_process,
lease_owner_id=lease_owner_id, lease_owner_id=lease_owner_id,

View File

@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio import asyncio
import html import html
import logging import logging
import math
import re import re
from typing import Any from typing import Any
from urllib.parse import urlsplit from urllib.parse import urlsplit
@ -30,11 +29,6 @@ from deerflow.uploads.manager import is_upload_staging_file, normalize_filename
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
SLACK_STOP_TIMEOUT_SECONDS = 5.0 SLACK_STOP_TIMEOUT_SECONDS = 5.0
# Outbound sends run inline on the shared inbound workers, so a long wait would
# hold a worker that other providers also need. A 429 Retry-After up to this
# budget is waited out; a longer one abandons the reply (logged) instead of
# sleeping, and never retries before Slack allows it.
SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS = 15.0
# Match the manager's URL download ceiling. Slack workspace limits may be higher; # Match the manager's URL download ceiling. Slack workspace limits may be higher;
# this keeps a single upload from exhausting Gateway memory. # this keeps a single upload from exhausting Gateway memory.
SLACK_MAX_INBOUND_FILE_BYTES = 50 * 1024 * 1024 SLACK_MAX_INBOUND_FILE_BYTES = 50 * 1024 * 1024
@ -281,56 +275,6 @@ class SlackChannel(Channel):
pass pass
raise raise
def _outbound_retry_delay(self, attempt: int, exc: Exception) -> float:
"""Wait out a Slack HTTP 429 before the next ``chat.postMessage``.
``WebClient`` keeps the SDK's default handlers, which retry connection
errors only, so a 429 reaches this shared loop. The header is seconds.
A missing or unusable hint keeps ``2**attempt``, and a shorter hint
does not shrink it. A hint above ``SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS``
re-raises the 429 so the shared loop stops retrying: sleeping that long
would occupy a shared inbound worker, and retrying sooner would be
rejected again.
"""
delay = super()._outbound_retry_delay(attempt, exc)
hint = self._slack_retry_after_seconds(exc)
if hint is None:
return delay
if hint > SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS:
logger.warning(
"[Slack] Retry-After %ss exceeds the inline wait budget of %ss; abandoning the send",
hint,
SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS,
)
raise exc
return max(delay, hint)
@staticmethod
def _slack_retry_after_seconds(exc: Exception) -> float | None:
response = getattr(exc, "response", None)
if getattr(response, "status_code", None) != 429:
return None
headers = getattr(response, "headers", None)
items = getattr(headers, "items", None)
if not callable(items):
return None
raw = None
for key, value in items():
if str(key).lower() == "retry-after":
raw = value
break
if isinstance(raw, (list, tuple)):
raw = raw[0] if raw else None
if raw is None or isinstance(raw, bool):
return None
try:
hint = float(raw)
except (TypeError, ValueError, OverflowError):
return None
if not math.isfinite(hint):
return None
return hint
async def send_file(self, msg: OutboundMessage, attachment: ResolvedAttachment) -> bool: async def send_file(self, msg: OutboundMessage, attachment: ResolvedAttachment) -> bool:
web_client = await self._get_web_client_for_message(msg) web_client = await self._get_web_client_for_message(msg)
if not web_client: if not web_client:

View File

@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
import math
import re import re
import threading import threading
import time import time
@ -35,9 +34,6 @@ TELEGRAM_MAX_INBOUND_FILE_BYTES = 20_000_000
# Keep Telegram cleanup inside the Gateway's five-second shutdown-hook budget. # Keep Telegram cleanup inside the Gateway's five-second shutdown-hook budget.
TELEGRAM_SHUTDOWN_TIMEOUT_SECONDS = 4.0 TELEGRAM_SHUTDOWN_TIMEOUT_SECONDS = 4.0
TELEGRAM_BRIDGE_DRAIN_TIMEOUT_SECONDS = 1.0 TELEGRAM_BRIDGE_DRAIN_TIMEOUT_SECONDS = 1.0
# Outbound listeners await sends inline. Bound each flood wait while still
# allowing a full group rate-limit window.
TELEGRAM_MAX_OUTBOUND_RETRY_DELAY_SECONDS = 60.0
STREAM_EDIT_MIN_INTERVAL_SECONDS = 1.0 STREAM_EDIT_MIN_INTERVAL_SECONDS = 1.0
# Groups (negative chat_id) are capped at 20 messages/minute by Telegram, # Groups (negative chat_id) are capped at 20 messages/minute by Telegram,
# so stream edits there must pace well below the private-chat 1 msg/s guideline. # so stream edits there must pace well below the private-chat 1 msg/s guideline.
@ -327,20 +323,14 @@ class TelegramChannel(Channel):
if not msg.is_final: if not msg.is_final:
await self._send_stream_update(chat_id, key, msg.text, reply_to=self._parse_message_id(msg.thread_ts)) await self._send_stream_update(chat_id, key, msg.text, reply_to=self._parse_message_id(msg.thread_ts))
state = self._stream_messages.get(key)
if state is not None:
binding = (msg.thread_id, msg.connection_id, msg.owner_user_id, msg.thread_ts, state["message_id"])
if state.get("thread_binding") != binding and await self._remember_reply_thread(msg, state["message_id"], stream_state=state):
state["thread_binding"] = binding
return return
state = self._stream_messages.pop(key, None) state = self._stream_messages.pop(key, None)
if state is not None: if state is not None:
await self._remember_reply_thread(msg, state["message_id"], stream_state=state)
if self._can_send_rich(msg.text) and await self._edit_rich_message(chat_id, state["message_id"], msg.text): if self._can_send_rich(msg.text) and await self._edit_rich_message(chat_id, state["message_id"], msg.text):
self._last_bot_message[msg.chat_id] = state["message_id"] self._last_bot_message[msg.chat_id] = state["message_id"]
return return
await self._finalize_stream_message(chat_id, msg.chat_id, state, msg.text, msg) await self._finalize_stream_message(chat_id, msg.chat_id, state, msg.text)
return return
if self._can_send_rich(msg.text): if self._can_send_rich(msg.text):
@ -350,51 +340,10 @@ class TelegramChannel(Channel):
logger.warning("[Telegram] Rich Message send failed in chat=%s; falling back to plain text: %s", chat_id, exc) logger.warning("[Telegram] Rich Message send failed in chat=%s; falling back to plain text: %s", chat_id, exc)
message_id = None message_id = None
if message_id is not None: if message_id is not None:
await self._remember_reply_thread(msg, message_id)
return return
for chunk in self._split_message(msg.text): for chunk in self._split_message(msg.text):
message_id = await self._send_new_message(chat_id, msg.chat_id, chunk, _max_retries=_max_retries) await self._send_new_message(chat_id, msg.chat_id, chunk, _max_retries=_max_retries)
await self._remember_reply_thread(msg, message_id)
async def _remember_reply_thread(self, msg: OutboundMessage, message_id: int | None, *, stream_state: dict[str, Any] | None = None) -> bool:
"""Keep group replies on their source thread, without undoing a later /new."""
if not msg.thread_id or message_id is None or int(msg.chat_id) >= 0:
return True
store = self.config.get("channel_store")
if msg.connection_id:
# Bound conversations must never fall back to the shared legacy store.
if self._connection_repo is None or not msg.owner_user_id:
return False
elif store is None:
return False
topic_ids = {str(message_id)}
if msg.thread_ts:
topic_ids.add(msg.thread_ts)
try:
for topic_id in topic_ids:
if msg.connection_id:
await self._connection_repo.claim_thread_id(
connection_id=msg.connection_id,
owner_user_id=msg.owner_user_id,
provider=self.name,
external_conversation_id=msg.chat_id,
external_topic_id=topic_id,
thread_id=msg.thread_id,
)
else:
await store.claim_thread_id(self.name, msg.chat_id, msg.thread_id, topic_id=topic_id)
except Exception:
# Delivery has already succeeded. Retry the binding on the next update,
# not the Telegram send, which could duplicate a visible reply.
if stream_state is not None and stream_state.get("thread_binding_error_logged"):
logger.debug("[Telegram] reply thread mapping retry failed in chat=%s", msg.chat_id)
else:
logger.exception("[Telegram] failed to remember reply thread mapping in chat=%s", msg.chat_id)
if stream_state is not None:
stream_state["thread_binding_error_logged"] = True
return False
return True
async def _send_stream_update(self, chat_id: int, key: str, text: str, reply_to: int | None = None) -> None: async def _send_stream_update(self, chat_id: int, key: str, text: str, reply_to: int | None = None) -> None:
"""Edit the in-flight streamed message with accumulated text. """Edit the in-flight streamed message with accumulated text.
@ -460,7 +409,7 @@ class TelegramChannel(Channel):
state["last_edit_at"] = _monotonic() state["last_edit_at"] = _monotonic()
state["last_text"] = display state["last_text"] = display
async def _finalize_stream_message(self, chat_id: int, chat_key: str, state: dict[str, Any], text: str, msg: OutboundMessage) -> None: async def _finalize_stream_message(self, chat_id: int, chat_key: str, state: dict[str, Any], text: str) -> None:
"""Apply the final text: edit the streamed message, splitting overflow into follow-ups.""" """Apply the final text: edit the streamed message, splitting overflow into follow-ups."""
bot = self._application.bot bot = self._application.bot
chunks = self._split_message(text or "") chunks = self._split_message(text or "")
@ -474,12 +423,10 @@ class TelegramChannel(Channel):
else: else:
# Edit could not be applied (e.g. message deleted) — deliver the # Edit could not be applied (e.g. message deleted) — deliver the
# first chunk as a fresh message with the standard retry policy. # first chunk as a fresh message with the standard retry policy.
message_id = await self._send_new_message(chat_id, chat_key, chunks[0]) await self._send_new_message(chat_id, chat_key, chunks[0])
await self._remember_reply_thread(msg, message_id, stream_state=state)
for chunk in chunks[1:]: for chunk in chunks[1:]:
message_id = await self._send_new_message(chat_id, chat_key, chunk) await self._send_new_message(chat_id, chat_key, chunk)
await self._remember_reply_thread(msg, message_id, stream_state=state)
async def _edit_final_chunk(self, bot, chat_id: int, message_id: int, text: str) -> bool: async def _edit_final_chunk(self, bot, chat_id: int, message_id: int, text: str) -> bool:
"""Edit with one rate-limit retry. Returns False if the edit could not be applied.""" """Edit with one rate-limit retry. Returns False if the edit could not be applied."""
@ -598,24 +545,13 @@ class TelegramChannel(Channel):
try: try:
input_file = await asyncio.to_thread(_load_telegram_input_file, attachment.actual_path, attachment.filename) input_file = await asyncio.to_thread(_load_telegram_input_file, attachment.actual_path, attachment.filename)
from telegram.error import BadRequest
if attachment.is_image and attachment.size <= 10 * 1024 * 1024: if attachment.is_image and attachment.size <= 10 * 1024 * 1024:
kwargs: dict[str, Any] = {"chat_id": chat_id, "photo": input_file} kwargs: dict[str, Any] = {"chat_id": chat_id, "photo": input_file}
if reply_to: if reply_to:
kwargs["reply_to_message_id"] = reply_to kwargs["reply_to_message_id"] = reply_to
if chat_id > 0: if chat_id > 0:
kwargs["allow_sending_without_reply"] = True kwargs["allow_sending_without_reply"] = True
try:
sent = await bot.send_photo(**kwargs) sent = await bot.send_photo(**kwargs)
except BadRequest as exc:
if str(exc).casefold() not in {"photo_invalid_dimensions", "image_process_failed"}:
raise
logger.info("[Telegram] photo rejected (%s); delivering as document: %s", exc, attachment.filename)
# A rejected photo can still be delivered unchanged as a file.
# Keep the reply target and reuse the already loaded bytes.
kwargs["document"] = kwargs.pop("photo")
sent = await bot.send_document(**kwargs)
else: else:
kwargs = {"chat_id": chat_id, "document": input_file} kwargs = {"chat_id": chat_id, "document": input_file}
if reply_to: if reply_to:
@ -625,7 +561,6 @@ class TelegramChannel(Channel):
sent = await bot.send_document(**kwargs) sent = await bot.send_document(**kwargs)
self._last_bot_message[msg.chat_id] = sent.message_id self._last_bot_message[msg.chat_id] = sent.message_id
await self._remember_reply_thread(msg, sent.message_id)
logger.info("[Telegram] file sent: %s to chat=%s", attachment.filename, msg.chat_id) logger.info("[Telegram] file sent: %s to chat=%s", attachment.filename, msg.chat_id)
return True return True
except Exception: except Exception:
@ -982,24 +917,6 @@ class TelegramChannel(Channel):
"last_text": last_text, "last_text": last_text,
} }
def _outbound_retry_delay(self, attempt: int, exc: Exception) -> float:
"""Extend the shared backoff for new plain or Rich final-reply sends.
Only sends through ``_send_with_retry`` use this policy. The running
acknowledgment and intermediate stream updates are best effort.
Final edits have their own retry path.
"""
delay = super()._outbound_retry_delay(attempt, exc)
if not self._is_retry_after(exc):
return delay
try:
hint = self._retry_after_seconds(exc)
except (TypeError, ValueError, OverflowError):
return delay
if not math.isfinite(hint):
return delay
return max(delay, min(hint, TELEGRAM_MAX_OUTBOUND_RETRY_DELAY_SECONDS))
@staticmethod @staticmethod
def _is_retry_after(exc: Exception) -> bool: def _is_retry_after(exc: Exception) -> bool:
return getattr(exc, "retry_after", None) is not None return getattr(exc, "retry_after", None) is not None
@ -1041,7 +958,7 @@ class TelegramChannel(Channel):
return chunks return chunks
async def _send_running_reply(self, chat_id: str, reply_to_message_id: int) -> None: async def _send_running_reply(self, chat_id: str, reply_to_message_id: int) -> None:
"""Send a best-effort acknowledgment before dispatching inbound work.""" """Send a 'Working on it...' reply and register it as the stream target."""
if not self._application: if not self._application:
return return
try: try:

View File

@ -32,7 +32,6 @@ from app.channels.commands import is_known_channel_command
from app.channels.connection_identity import attach_connection_identity from app.channels.connection_identity import attach_connection_identity
from app.channels.credential_staging import cleanup_stale_credential_staging, credential_staging_prefix from app.channels.credential_staging import cleanup_stale_credential_staging, credential_staging_prefix
from app.channels.message_bus import INBOUND_FILE_CLEANUP_KEY, InboundMessage, InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment, cleanup_inbound_files from app.channels.message_bus import INBOUND_FILE_CLEANUP_KEY, InboundMessage, InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment, cleanup_inbound_files
from deerflow.utils.atomic_write import publish_bytes_atomically
from deerflow.utils.file_io import await_drained from deerflow.utils.file_io import await_drained
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -1084,8 +1083,15 @@ class WechatChannel(Channel):
def _update_longpoll_timeout(self, data: Mapping[str, Any]) -> None: def _update_longpoll_timeout(self, data: Mapping[str, Any]) -> None:
if not self._respect_server_longpoll_timeout: if not self._respect_server_longpoll_timeout:
return return
timeout_ms = self._coerce_float(data.get("longpolling_timeout_ms"), 0.0) raw_timeout = data.get("longpolling_timeout_ms")
if 1_000 <= timeout_ms <= 300_000: if raw_timeout is None:
return
try:
timeout_ms = float(raw_timeout)
except (TypeError, ValueError):
return
if timeout_ms <= 0:
return
self._server_longpoll_timeout_seconds = timeout_ms / 1000.0 self._server_longpoll_timeout_seconds = timeout_ms / 1000.0
def _base_info(self) -> dict[str, str]: def _base_info(self) -> dict[str, str]:
@ -1701,10 +1707,7 @@ class WechatChannel(Channel):
return return
try: try:
self._cursor_path.parent.mkdir(parents=True, exist_ok=True) self._cursor_path.parent.mkdir(parents=True, exist_ok=True)
# Publish through the shared helper: it fsyncs the staged bytes self._cursor_path.write_text(json.dumps({"get_updates_buf": self._get_updates_buf}, ensure_ascii=False, indent=2), encoding="utf-8", newline="")
# before the rename (so a machine crash cannot leave a truncated
# cursor behind) and re-applies an existing file's mode.
publish_bytes_atomically(self._cursor_path, json.dumps({"get_updates_buf": self._get_updates_buf}, ensure_ascii=False, indent=2).encode("utf-8"))
except OSError: except OSError:
logger.warning("[WeChat] failed to persist cursor state to %s", self._cursor_path) logger.warning("[WeChat] failed to persist cursor state to %s", self._cursor_path)

View File

@ -9,7 +9,7 @@ from collections.abc import Awaitable, Callable, Mapping
from typing import Any, cast from typing import Any, cast
from app.channels.base import Channel, ChannelUnavailable, attachment_delivery_text from app.channels.base import Channel, ChannelUnavailable, attachment_delivery_text
from app.channels.commands import is_known_channel_command, strip_leading_mentions from app.channels.commands import is_known_channel_command
from app.channels.connection_identity import attach_connection_identity from app.channels.connection_identity import attach_connection_identity
from app.channels.message_bus import ( from app.channels.message_bus import (
InboundMessage, InboundMessage,
@ -40,10 +40,6 @@ else:
_WECOM_ACK_REJECTION_PREFIX = "Reply ack error" _WECOM_ACK_REJECTION_PREFIX = "Reply ack error"
def _group_workspace_id(aibotid: str | None, chatid: str) -> str:
return f"{aibotid}:group:{chatid}" if aibotid else f"group:{chatid}"
def _file_md5(path: str) -> str: def _file_md5(path: str) -> str:
md5_hasher = hashlib.md5() md5_hasher = hashlib.md5()
with open(path, "rb") as file_obj: with open(path, "rb") as file_obj:
@ -438,6 +434,8 @@ class WeComChannel(Channel):
logger.exception("[WeCom] failed to send attachment delivery feedback") logger.exception("[WeCom] failed to send attachment delivery feedback")
async def send_file(self, msg: OutboundMessage, attachment: ResolvedAttachment) -> bool: async def send_file(self, msg: OutboundMessage, attachment: ResolvedAttachment) -> bool:
if not msg.is_final:
return True
if not self._ws_client: if not self._ws_client:
return False return False
if not msg.thread_ts: if not msg.thread_ts:
@ -447,11 +445,7 @@ class WeComChannel(Channel):
return False return False
media_type = "image" if attachment.is_image else "file" media_type = "image" if attachment.is_image else "file"
# aibot media upload limits: image 10 MB, voice 2 MB, video 10 MB, size_limit = 2 * 1024 * 1024 if attachment.is_image else 20 * 1024 * 1024
# file 20 MB (https://developer.work.weixin.qq.com/document/path/101917).
# The image cap used to be 2 MB — the voice limit — which dropped every
# 2-10 MB image before it was uploaded.
size_limit = 10 * 1024 * 1024 if attachment.is_image else 20 * 1024 * 1024
if attachment.size > size_limit: if attachment.size > size_limit:
logger.warning( logger.warning(
"[WeCom] %s too large (%d bytes), skipping: %s", "[WeCom] %s too large (%d bytes), skipping: %s",
@ -587,22 +581,7 @@ class WeComChannel(Channel):
if handled: if handled:
return return
# WeCom group chats deliver "@bot /new" with the mention left in the text inbound_type = InboundMessageType.COMMAND if is_known_channel_command(text) else InboundMessageType.CHAT
# (Slack/Discord strip their own bot mention upstream). Skip a leading
# mention only for the command path so ordinary chat keeps any @mentions
# intact for the agent; the stripped form also flows into the inbound so
# ChannelManager._handle_command parses the bare command. Mirrors
# DingTalkChannel / FeishuChannel.
#
# This drops *any* leading mention, not only the bot's: WeCom text
# mentions carry display names, so the frame's `aibotid` cannot be
# matched against them and "@alice /status" is indistinguishable from
# "@bot /status". Feishu and DingTalk accept the same tradeoff;
# test_member_mention_before_a_command_also_classifies pins it.
command_text = strip_leading_mentions(text)
inbound_type = InboundMessageType.COMMAND if is_known_channel_command(command_text) else InboundMessageType.CHAT
if inbound_type is InboundMessageType.COMMAND:
text = command_text
inbound_metadata: dict[str, Any] = { inbound_metadata: dict[str, Any] = {
"aibotid": body.get("aibotid"), "aibotid": body.get("aibotid"),
"chattype": body.get("chattype"), "chattype": body.get("chattype"),
@ -610,12 +589,8 @@ class WeComChannel(Channel):
} }
if body.get("chatid") is not None: if body.get("chatid") is not None:
inbound_metadata["chatid"] = body.get("chatid") inbound_metadata["chatid"] = body.get("chatid")
# A group's conversation is the group, a private chat's the sender.
# Keyed by sender alone, a member's private chat and every group they
# wrote in shared one thread wherever no group connection kept them apart.
group_chatid = str(body.get("chatid") or "").strip() if body.get("chattype") == "group" else ""
inbound = self._make_inbound( inbound = self._make_inbound(
chat_id=group_chatid or user_id, chat_id=user_id, # keep user's conversation in memory
user_id=user_id, user_id=user_id,
text=text, text=text,
msg_type=inbound_type, msg_type=inbound_type,
@ -623,7 +598,7 @@ class WeComChannel(Channel):
files=files or [], files=files or [],
metadata=inbound_metadata, metadata=inbound_metadata,
) )
inbound.topic_id = user_id # one thread per member in each conversation inbound.topic_id = user_id # keep the same thread
stream_id = generate_req_id("stream") stream_id = generate_req_id("stream")
self._ws_frames[msg_id] = frame self._ws_frames[msg_id] = frame
@ -641,8 +616,6 @@ class WeComChannel(Channel):
pass pass
inbound = await self._attach_connection_identity(inbound) inbound = await self._attach_connection_identity(inbound)
if group_chatid:
await self._carry_over_sender_keyed_group_thread(inbound, group_chatid)
self._commit_reserved_inbound(reservation, inbound) self._commit_reserved_inbound(reservation, inbound)
finally: finally:
reservation.release() reservation.release()
@ -654,7 +627,7 @@ class WeComChannel(Channel):
if chattype == "group": if chattype == "group":
if not chatid or self._connection_repo is None: if not chatid or self._connection_repo is None:
return inbound return inbound
workspace_id = _group_workspace_id(aibotid, chatid) workspace_id = f"{aibotid}:group:{chatid}" if aibotid else f"group:{chatid}"
inbound = await attach_connection_identity(inbound, repo=self._connection_repo, provider="wecom", workspace_id=workspace_id, fallback_without_workspace=False) inbound = await attach_connection_identity(inbound, repo=self._connection_repo, provider="wecom", workspace_id=workspace_id, fallback_without_workspace=False)
if inbound.connection_id: if inbound.connection_id:
return inbound return inbound
@ -676,35 +649,6 @@ class WeComChannel(Channel):
fallback_without_workspace=True, fallback_without_workspace=True,
) )
async def _carry_over_sender_keyed_group_thread(self, inbound: InboundMessage, chatid: str) -> None:
"""Rebind a group connection's thread from the sender key it used to have.
Group messages were once keyed like private ones (``userid``, ``userid``).
A group connection belongs to one group, so its thread under that key is
this group's and moves to the group key once. A legacy group binding
spans every group of the bot; its old thread is left behind rather than
continued in whichever group writes first.
"""
repo = self._connection_repo
if repo is None or not inbound.connection_id or not inbound.owner_user_id:
return
aibotid = str(inbound.metadata.get("aibotid") or "").strip() or None
if inbound.workspace_id != _group_workspace_id(aibotid, chatid):
return
if await repo.get_thread_id(inbound.connection_id, inbound.chat_id, inbound.topic_id) is not None:
return
previous = await repo.get_thread_id(inbound.connection_id, inbound.user_id, inbound.user_id)
if previous is None:
return
await repo.claim_thread_id(
connection_id=inbound.connection_id,
owner_user_id=inbound.owner_user_id,
provider=self.name,
external_conversation_id=inbound.chat_id,
external_topic_id=inbound.topic_id,
thread_id=previous,
)
async def _bind_connection_from_connect_code(self, *, frame: dict[str, Any], user_id: str, code: str) -> bool: async def _bind_connection_from_connect_code(self, *, frame: dict[str, Any], user_id: str, code: str) -> bool:
if self._connection_repo is None or not code: if self._connection_repo is None or not code:
return False return False
@ -727,7 +671,7 @@ class WeComChannel(Channel):
if not chatid: if not chatid:
await self._send_connection_reply(frame, await self._connect_reply_text("incomplete", owner_user_id=state["owner_user_id"])) await self._send_connection_reply(frame, await self._connect_reply_text("incomplete", owner_user_id=state["owner_user_id"]))
return True return True
workspace_id = _group_workspace_id(aibotid, chatid) workspace_id = f"{aibotid}:group:{chatid}" if aibotid else f"group:{chatid}"
raw_group_name = str(body.get("chatname") or body.get("group_name") or "").strip() raw_group_name = str(body.get("chatname") or body.get("group_name") or "").strip()
workspace_name = notification_group_display_name(state.get("metadata")) or raw_group_name[:256] or None workspace_name = notification_group_display_name(state.get("metadata")) or raw_group_name[:256] or None
metadata: dict[str, Any] = { metadata: dict[str, Any] = {

View File

@ -1,102 +1,264 @@
# Gateway API (`app/gateway/`) ### Gateway API (`app/gateway/`)
The FastAPI application on port 8001. It serves the REST API, embeds the Reject external `sandbox`, `thread_data`, `viewed_images`, `goal_outcome`. Non-null goals: valid text, int counters/limits >=0, no Overwrite; keep sparse data.
LangGraph-compatible agent runtime, and owns auth, CSRF, run admission and thread
lifecycle. Route-level rules are in [routers/AGENTS.md](routers/AGENTS.md). The
endpoint list is the OpenAPI schema at `/docs`; [API.md](../../docs/API.md)
describes it for humans.
## Verify Studio retains sanitized creation metadata.
```bash Capability Center's `business` adapter validates bundled credentials and creates
cd backend an MCP connection. The MCP API permits only its isolated launcher and credential
python -m pytest tests -q -k "gateway or router or auth or run_manager" environment keys; reject arbitrary commands and manifest-policy bypasses. Keep
make test-blocking-io # request handlers share one event loop credentials out of tool schemas and preserve admin checks, masked atomic edits,
``` and MCP cache reloads.
Read these contracts before you change the matching area: Memory shutdown resolves hot-reloaded config/backend, flushes and closes in one
[thread lifecycle](../../docs/THREAD_LIFECYCLE.md) (branch, regenerate, edit `await_drained` operation. Resolve config off-loop inside the best-effort handler
replay, archive), [run event stream](../../docs/RUN_EVENT_STREAM.md), so malformed edits cannot abort teardown. Cancellation waits for owned workers.
[run interaction policy](../../docs/RUN_INTERACTION_POLICY.md), The host sets no close timeout: `close()` must be quick or internally bounded;
[auth design](../../docs/AUTH_DESIGN.md), [knowledge](../../docs/KNOWLEDGE.md). budget it, flush timeout and other hooks within pod grace. Drain extension
`stop_services()` across cancellation before later resources unwind; each
service `stop()` has a 30-second `asyncio.timeout`.
## Trust boundary Routers with persistent writes drain through
`app.gateway.persistent_writes.run_drained_write`.
- **Share tokens read only frozen snapshots.** See [sharing](../../../docs/guide/sharing.md). `lifespan` first holds `hold_sandbox_shutdown_ownership()`. After
- **Server-owned run context.** A client can send run context in `body.context` `langgraph_runtime` drains runs and extensions, close MCP (bounded, isolated),
and in `body.config`. Admit server-owned keys only from internally authenticated then drain `shutdown_sandbox_provider()` off-loop in `finally`, even on
callers and strip them from both places for everyone else. When you add a cancel. Never allocate for cleanup; log failures, stay retryable.
server-owned key, add it to that strip list in the same change.
- **Server-owned state.** Reject thread state fields that only the server may write
(sandbox, thread data, viewed images, goal outcome) and reserved metadata keys
when they come from a client. External run input cannot carry system or developer
messages.
- **Owner scoping.** Run-history helpers default to the request user and fail
closed when there is no user context. Pass `user_id=None` only in migration or
admin code that needs an unscoped read, and say why at the call site.
- **Thread IDs become paths.** Validate every caller-provided thread ID with
`deerflow.utils.thread_id` before it reaches persistence or the filesystem.
Legacy IDs stay readable and deletable, but they are never interpolated into a
host path.
- **Shared decisions.** Route permissions, model use and skill visibility are each
decided in one helper in `authz.py`. HTTP routes, decorator-only auth and the
Live Browser WebSocket all call it. A new entry point calls the same helper so
that it cannot drift from the others.
- **Tokens and cookies.** A request with an invalid Bearer token gets 401 and never
falls back to the session cookie; the CSRF middleware skips Bearer requests and
relies on this. Personal access tokens work only on allowlisted routes.
- **Proxy headers.** "Is this localhost" decisions use the direct `Host` header.
Forwarded headers are client-controlled unless the outer proxy replaces them.
- **Untrusted remote text.** MCP notifications and other remote events reach the
model framed as untrusted data, outside the trusted instruction.
## Runs and threads Retention holds durable thread admission and the checkpoint lock before
checkpoint reads. Inspect root head/parent and leaf writes only; protect selectors,
require equal channel versions and invalidate caches before deletion. No scans,
stats or blob GC; failures stay non-fatal.
- **One writer per thread.** A run, a checkpoint write, an artifact write, a branch `conversation_access.py` grants the opt-in read-only tool only for explicit
and a delete are all thread operations that share one durable uniqueness `conversation_references` with effective `runs:read`; never infer grants from
constraint. Reserve through `RunManager.reserve_thread_operation()` or messages or checkpoints. Pass the callback through `RunContext`, not serialized
`services.reserve_checkpoint_write()`. A separate lock would let two workers config, and let the worker inject and clear it. `conversation_reader.py` shares
write the same thread. Outside run execution, checkpoint mutations — manual HTTP transcript visibility/pagination without a Request; callers own authorization.
compaction, `POST /threads/{id}/state`, both goal routes (`PUT` / `DELETE Exclude non-text/internal content. `RunCreateRequest` lifts SDK-compatible
/threads/{id}/goal`), and the `/goal from-chat` save (`POST `context.conversation_references` into its top-level field before validation,
/threads/{id}/goal/from-chat`) — use `services.reserve_checkpoint_write()`. then removes it from context; supplying both is 422. This shares bounds/error
`PUT /goal` creates a missing checkpoint; from-chat does not. From-chat locations and keeps `merge_run_context_overrides` clear. Admission and
saves with `expected_checkpoint_id` pinned to the head its synthesis read: `/api/features` use `conversation_references_enabled()` as the sole configured
a write that landed during the model call rejects the stale objective predicate.
instead of clobbering the newer state, and the model call itself passes the
same `authorize_model_use` admission as the suggestions route.
- **Several workers.** In-memory run records exist only on the worker that owns the
run. Cancel, takeover and orphan recovery are compare-and-set operations on the
run store; use the store's claim and cancel primitives so that a lease renewal
between your read and your write is not overwritten. Multi-worker deployments
need `run_events.backend: db`.
- **Idempotency keys.** Scope an external `Idempotency-Key` to its owner and thread
before it reaches `RunManager`; the manager's index is process-wide.
- **`/wait` on a reused run** returns the durable run status and error. The latest
thread checkpoint can belong to a different run.
- **Stream gaps.** Stream bridges keep a bounded buffer. A client that asks for
events older than the buffer receives a `gap` event and the run continues.
- **`Content-Location` must stay CORS-exposed.** Run-creating routes return the run
ID in that header and the LangGraph SDK reads it from there only.
- **Run event contract.** Producer code, `deerflow/constants.py`, the event
catalog, `contracts/run_event_stream_contract.json` and
`docs/RUN_EVENT_STREAM.md` change together.
- **Thread membership in a project** is written by thread creation, branching and
the explicit move route. Run admission reads it and never changes it.
## Lifecycle FastAPI listens on 8001. `GET /health` is liveness; `GET /health/ready` concurrently
probes startup snapshots of ORM, checkpointer/Store and stream bridge
(`StreamBridge.ping()`) under one deadline and per-kind gates. Unreachable or
unresolved gating backends return 503; `memory` reports `not_configured`;
provisioner `/health` is report-only. See `health.py`. `GATEWAY_ENABLE_DOCS=false`
disables `/docs`, `/redoc` and `/openapi.json`.
- **Probe file-backed managed subagent storage once during startup, off the `build_run_config()` resolves the default LangGraph super-step budget from the
event loop.** Probe failures warn operators before their first create request; hot-reloaded top-level `recursion_limit` setting. A valid request-level value
atomic create stays fail-closed rather than falling back to an overwrite. takes precedence; invalid values fall back to that default, and
- **Shutdown order matters.** `lifespan` drains runs and extensions first, then `max_recursion_limit` caps both sources.
closes MCP, then shuts the sandbox provider down off the event loop. Cleanup code
keeps running after cancellation, allocates nothing new, and logs failures Durable MCP notifications use internal Agent runs. Keep their trusted delivery instruction outside the user-input boundary, and frame serialized remote events as untrusted before model invocation. Strict thread existence/ownership admission dead-letters events whose task outlives its deleted chat instead of recreating the thread. `start_run` marks run-manager admission conflicts with `BusyThreadConflict`; the notification launcher retries only that typed 409 and treats other 409 responses as permanent.
instead of raising.
- **Persistent writes in routers** go through CORS defaults to same-origin behind nginx on 2026. Split-origin and port-forwarded
`app.gateway.persistent_writes.run_drained_write` so that a client disconnect browser clients must set exact `GATEWAY_CORS_ORIGINS`, shared by `CORSMiddleware`
cannot leave a half-written file. and `CSRFMiddleware`. Expose `Content-Location` through `CORS_EXPOSED_HEADERS`
- **LangGraph Studio.** `langgraph_studio.py` is loaded by LangGraph's file loader (`csrf_middleware.py`): run-creating routes put the run ID there, and the LangGraph
before the runtime starts and without a `sys.modules` entry. Keep its SDK uses only that header for run metadata. Without exposure, JS cannot read it,
annotations eager, and identify Studio callers by the upstream `StudioUser` breaking `useStream.onCreated` and thread-gated actions.
type, because the identity string can be reused by any client.
Browser sessions belong to `app.gateway.auth.session_cookie`. Login's `remember_me`
flag never stores passwords. `SessionCookiePolicy` persists `HttpOnly access_token`
only for HTTPS/trusted-forwarded HTTPS, direct-host localhost HTTP, or explicit
operator opt-in; public HTTP otherwise uses session cookies. Session creators set
final `max_age` on `request.state`; CSRF mirrors it across login, password changes
and OIDC callbacks. A small `HttpOnly` preference cookie preserves the choice.
Logout clears auth cookies and suppresses CSRF re-issue.
OIDC redirects retain existing endpoint query bytes (RFC 6749 section 3.1).
Malformed IdP bodies raise `OIDCError` (502/`sso_failed`).
`tests/test_oidc_auth.py` pins query, state-cookie, nonce and PKCE agreement.
Personal Access Tokens (`app.gateway.auth.pat`, `Authorization: Bearer dfp_...`) run as their owning user: an invalid Bearer is a hard 401 with no cookie fallback, which keeps `CSRFMiddleware`'s Bearer skip safe (origin checks still run). Scopes narrow within the allowlisted threads/runs/projects routes (including `POST /api/threads/{id}/move`); every other authenticated route 403s PAT callers (admin included). PAT management and `/change-password` require session auth; only SHA-256 digests are stored (`0017`).
Thread→project membership is written by thread creation (`POST /api/threads` with
a validated `project_id`), branch creation (the new row inherits the source
thread's project; an archived/deleted project degrades the branch to unassigned
instead of failing), and explicit moves (`POST /api/threads/{id}/move`); run
admission never modifies membership; it only pins the resolved project context
read-only into the run context. The server-reserved `deerflow_project_id`
metadata key is a read-only exposure of the `threads_meta.project_id` column and
is stripped from client writes.
Localhost persistence deliberately reads the direct request `Host` and ignores `Forwarded` / `X-Forwarded-Host`. Scheme and auth-origin reconstruction still consume forwarding headers. The bundled nginx sets `X-Forwarded-Proto`, but preserves an upstream HTTPS value and does not overwrite every forwarded header, so the outer trusted proxy must replace or strip client-supplied forwarding headers before traffic reaches DeerFlow.
Standalone local LangGraph Studio is recognized only through the upstream
`Auth.types.StudioUser` principal type, never by its reusable identity string.
The type is resolved once at import; an older SDK without it degrades to normal
owner scoping.
For that principal's assistant reads/searches, `langgraph_auth.add_owner_filter`
selects genuine server-registered assistants plus assistants owned by Studio;
all other resources remain owner-scoped. Assistant create/update handlers make
both `user_id` and `created_by=user` server-owned, because LangGraph gives
`created_by=system` privileged ownership semantics during run creation. The
custom application module in `langgraph_studio.py` is imported before the
locked in-memory runtime lifespan. At that pre-runtime boundary it derives
genuine system assistant IDs from the CLI-provided graph registry, removes
their persisted active/version rows so graph registration recreates them, and
demotes every other legacy `created_by=system` marker in both active assistants
and version history. This must happen before runtime 0.30.0 loads and purges
system-marked rows; a user application lifespan is too late. LangGraph executes
this file-backed custom app without first registering its module in
`sys.modules`; keep its annotations eager so dataclass processing remains
compatible with that loader, and preserve the direct file-loader regression
test. An empty graph registry or absent persistence file is a no-op, while
persistence parse/write errors fail startup closed. The harness requires
in-memory runtime 0.30.0 or newer, and a persisted store containing no
expected registered assistant row emits a drift warning so changes to
LangGraph's internal persistence contract are observable. With current
create/update writes and all legacy versions sanitized, ordinary
owner-scoped assistant version selection remains enabled.
**Routers**:
| Router | Endpoints |
|--------|-----------|
| **Managed Models** (`/api/managed-models`) | Admin-only GET/PUT with revisions; streaming POST `/test` (DeepSeek thinking off). Clients/storage off-loop; YAML names reserved; keys private. |
| **Models** (`/api/models`) | `GET /` - list models; `GET /{name}` - model details |
| **Features** (`/api/features`) | `GET /` - UI capabilities: hot-reloaded agents, guarded browser, startup MCP tasks, separate batch repository/worker states so history stays readable without a worker, `conversation_references` (`read_conversation` configured, per-run reference cap), knowledge scope selection, `scheduled_tasks`, and `thread_activity` |
| **Thread Activity** (`/api/thread-activity`) | `GET /?cursor=` - per-user feed over `runs.change_seq`: no cursor seeds; lists threads of the caller's server-originated runs, passes interactive rows; `read_version`. `POST /api/threads/{id}/read` and search `unread` use `thread_read_markers`. SQL only |
| **Knowledge** (`/api/knowledge`) | Authenticated, capability-driven read-only retrieval catalog and per-assistant `/capabilities`; provider adapters own resource authorization and mapping. Unsupported filters fail admission/execution without widening scope; management stays outside core |
| **Console** (`/api/console`) | Read-only cross-thread observability for the current user: `GET /stats` - headline counters (runs/threads/agents/tokens/cost); `GET /runs` - paginated run history joined with thread titles (per-run cost); `GET /usage` - zero-filled daily token series + per-model breakdown with spend. Queries `runs`/`threads_meta` directly (no new `RunStore` methods); SQL only (503 on `database.backend: memory`). Real-cost estimation reads optional `models[*].pricing` (`currency`, `input_per_million`, `output_per_million`, `input_cache_hit_per_million`; `ModelConfig` is `extra="allow"`, so no schema change) and prices each run from its `token_usage_by_model` input/output split. Pricing is **cache-aware**: `RunJournal` accumulates prompt-cache hits from `usage_metadata.input_token_details.cache_read` into a sparse `cache_read_tokens` bucket key (also threaded through `SubagentTokenCollector` → `record_external_llm_usage_records`), and cache-hit input tokens are billed at `input_cache_hit_per_million` (omitted → billed at the miss price, a conservative upper bound). Mixed currencies null cost/currency fields. Legacy rows fall back to run-level totals at `model_name`; unpriced models yield `cost: null` and cost fields are null when no pricing is configured |
| **MCP** (`/api/mcp`) | GET /config - raw/masked; PUT /config - bulk; PATCH /config - toggle; POST /config/servers - add; PUT /config/server - replace; DELETE /config/servers/{server_name:path} - bodyless. POST /cache/reset. Validate expanded, save raw; reload/reset; invalid -> 400. |
| **MCP Tasks** (`/api/threads/{id}/mcp-tasks`) | `GET /` - current user's durable tasks for one owned thread; `GET /{task_id}` - bounded result/input/status-error/cancellation-error detail, including cancellation attempt count, without remote task IDs or driver configuration |
| **Skills** (`/api/skills`) | `GET /` - list; `GET /{name}` - inspect; `PUT /{name}` - toggle; `POST /install` - install a thread-local .skill archive; `POST /install/upload` - admin-only multipart, authorized before parsing and capped at a 100 MiB file plus 1 MiB framing; `POST /reload` - refresh, then publish the shared skills reset marker |
| **Subagents** (`/api/subagents`) | Admin managed-worker CRUD and listing. |
| **Integrations** (`/api/integrations`) | `GET /lark/status` - inspect managed Lark/Feishu CLI integration state, including `sandbox_runtime_mode` / `sandbox_runtime_probed` / `sandbox_runtime_ready` (whether `lark-cli` will be present in the sandbox at chat time); `POST /lark/install` - admin-only install of the official `lark-*` managed skill pack; `POST /lark/config/start` and `/lark/config/complete` - internal first-time Lark connection setup; `POST /lark/config/credentials` - atomically switch the caller's per-user Lark app after validating the new `app_id`/`app_secret` through the official CLI's live tenant-token probe, revoke/remove the previous OAuth tokens, and restore the prior credential tree if the switch fails; `POST /lark/auth/start` and `/lark/auth/complete` - browser device-flow user authorization without terminal access, with optional `domains` / exact `scope` for incremental permission grants. Config and auth flows carry a server-issued, per-user generation persisted under the credential lock; a rejected direct switch leaves the current generation unchanged, stale completions return 409, and browser re-registration uses the same token-clearing/revocation transaction as direct credential switches. |
| **Memory** (`/api/memory`) | `GET /` - memory data; `POST /reload` - force reload; `GET /config` - config; `GET /status` - config + data |
| **Uploads** (`/api/threads/{id}/uploads`) | `POST /` - upload/convert PDF/PPT/Excel/Word; upload/shelf names share `normalize_filename` before staging; non-mounted sync lease ends when its last holder exits; `GET /list`; `DELETE /{filename}` - regular files, symlinks 404, keeps converted `.md` (#5672) |
| **Threads** (`/api/threads/{id}`) | `DELETE /` - remove DeerFlow-managed local thread data after LangGraph thread deletion; `POST /branches` - branch a completed assistant turn with a replay checkpoint; inherited titles take next-free displayed sibling suffixes, including explicit/renamed ones, while explicit titles stay unchanged. Durable `branch` admission rejects races. Workspace files are not checkpointed: only a branch from the **latest** turn best-effort copies the workspace (`workspace_clone_mode="current_thread_best_effort"`); older turns skip it (`"skipped_historical_turn"`), so no later-timeline file leaks in. `sandbox`/`thread_data` channels are not copied (parent `sandbox_id` binds paths/release); the branch lazily acquires its own sandbox. Branch creation also seeds the new thread's run-event feed from the branch checkpoint's visible messages (`history_seed_mode` in the response): the thread feed reads run_events, not checkpoints, so without the seed the inherited history disappears from the UI after the branch's first run (#4380). Seeded rows get one synthetic run per inherited turn (`branch-seed-{thread_id}-{n}`, a new turn at every persisted human message, including an allowlisted hidden `ask_clarification` reply): `run_id` is a turn identity, and regenerating an inherited answer supersedes its whole `run_id` in `GET /messages/page`, so one shared seed id deleted all inherited history (#4458); `GET /goal`, `PUT /goal`, `DELETE /goal` - read, set, and clear the active thread goal; `POST /compact` - summarize older active context, deriving memory policy and bucket from the state-producing checkpoint rather than request `agent_name`, and block while a run is in flight; 409 unless idle; unexpected failures return a generic 500 detail |
| **Artifacts** (`/api/threads/{id}/artifacts`) | GET streams byte ranges; HTML/XML/XSL/`+xml` (also `.skill` members) and `?download=true` force attachments. PUT atomically replaces existing UTF-8 outputs on matching SHA-256; active runs conflict. Non-mounted sync uses a request lease and drains remote/local commit-or-rollback across cancellation before releasing reservations/leases. `resolve_outputs_confined_path` normalizes `..` and confines host paths against traversal/symlinks. Preserve POSIX ownership/mode where supported; Windows keeps temp-file permissions. Digest cache: path/dev/ino/ctime_ns/mtime_ns/size; identity invalidates same-size/mtime replacements. Large regular files use stat-prefixed ETags; If-Range requires matching ETags. Windows ctime is creation time. Keep cache reuse, size limits and worker hashing. |
| **Suggestions** (`/api/suggestions`) | `GET /config` - returns global suggestions config boolean; `POST /threads/{id}/suggestions` - generate follow-up questions; rich list/block model content is normalized and inline reasoning (`<think>...</think>`, including unclosed/truncated blocks from reasoning models like MiniMax-M3) is stripped before JSON parsing |
| **Input Polish** (`/api/input-polish`) | `POST /` - rewrite a composer draft before it is sent. This is a short authenticated `runs:create` LLM request using `input_polish` config; it does not create a LangGraph run, persist a message, or modify thread state. Shares the non-graph one-shot LLM path (`deerflow.utils.oneshot_llm.run_oneshot_llm`) with the suggestions route so model build + Langfuse metadata + invoke stay in one place; validates the same stripped view of the draft it sends to the model, and preserves literal `<think>` substrings in the rewrite (`strip_think_blocks(truncate_unclosed=False)`) |
| **Thread Runs** (`/api/threads/{id}/runs`) | `POST /` - create background run; `POST /stream` - create + SSE stream; `POST /wait` - create + block. Before the first journaled run, seed an empty feed from a checkpoint so legacy checkpoint-only history keeps its order and visibility; skip absent checkpoints or populated feeds. `POST /regenerate/prepare` - prepare clean input + checkpoint metadata for regenerating the latest completed or interrupted assistant answer, treating a protocol-valid hidden `human_input_response` as confirmed replay input while rejecting other hidden/control humans, preserving that response's hidden/correlation metadata, and carrying the latest non-empty thread title in graph input so resuming an older checkpoint cannot roll back a later manual rename (#4457); `POST /edit-regenerate/prepare` - prepare a checkpoint replay from the latest editable human turn with a replacement user message and edit replay metadata; it carries the current thread title the same way, but only when the replay base already has one — an untitled base belongs to a thread the title middleware has not named yet, so pinning the current title there would keep a name generated from the prompt the edit just replaced; `GET /` - newest 100 runs as an array; `GET /page` - keyset history page `{data, has_more, next_before_created_at, next_before_run_id}`; `GET /{rid}` - run details; `POST /{rid}/cancel` - cancel; `GET /{rid}/join` - join SSE; `GET /{rid}/stream` hides action/wait; GET action 405 pre-owner; POST needs `runs:cancel`; `GET /{rid}/messages` - paginated per-run messages `{data, has_more}`; `GET /{rid}/events` - full event stream; `GET /{rid}/workspace-changes` - workspace/output file change summary and optional diffs; `GET/POST /{rid}/artifacts/archive` - receipt manifest / bounded ZIP; `GET /../messages` - legacy thread message array; `GET /../messages/page` - backward thread-global `seq` history page with middleware/subagent-AI/successful-regenerate/edit-replay filtering and page-run-scoped feedback enrichment; subagent AI callbacks remain available through run events while parent `task` ToolMessages stay visible for card restoration; `GET /../token-usage` - aggregate tokens plus an optional `context_usage` percentage. Context usage approximately counts messages from the latest materialized thread state through `build_thread_checkpoint_state_accessor`, so full and delta checkpoint modes expose the same input. The percentage uses the latest run's model and its `context_window`. |
| **Feedback** (`/api/threads/{id}/runs/{rid}/feedback`) | `PUT /` - upsert feedback; `DELETE /` - delete user feedback; `POST /` - create feedback; `GET /` - list feedback; `GET /stats` - aggregate stats; `DELETE /{fid}` - delete specific |
| **Runs** (`/api/runs`) | `POST /stream`, `/wait` - stateless runs requiring `runs:create`; optional body `thread_id` is owner-checked. Scheduled-task create/update/resume/trigger also require `threads:write` plus `runs:create`. `GET /{rid}/messages`, `/feedback` - run messages/feedback |
| **GitHub Webhooks** (`/api/webhooks/github`) | `POST /` - receive GitHub App / repo webhook deliveries. Verifies `X-Hub-Signature-256` against `GITHUB_WEBHOOK_SECRET`; exempt from auth + CSRF because authenticity is enforced by HMAC. The route is fail-closed: mounted only when `GITHUB_WEBHOOK_SECRET` is set, or when explicit dev opt-in `DEER_FLOW_ALLOW_UNVERIFIED_GITHUB_WEBHOOKS=1` is set. Recognized events include `ping`, `issues`, `issue_comment`, `pull_request`, `pull_request_review`, and `pull_request_review_comment`; unknown events return 200 with `handled=false`. Fan-out runtime failures return 503, keeping the delivery recorded as failed for manual/API/scripted redelivery (GitHub does not automatically retry any failed delivery, 5xx included); permanent/non-retryable conditions such as `channels.github.enabled: false`, unknown events, malformed payloads, or unavailable channel service return 200 with a skipped/handled response. |
| **GitHub Event-Driven Agents** | Custom agents can declare a `github:` block in their `config.yaml` to bind to repos and event triggers. Webhook fan-out publishes one `InboundMessage` per matching binding to the channel bus; `GitHubChannel` routes those messages through `ChannelManager`. The response `dispatch` summarizes matched/fired/skipped agents. |
Edit replay and messages-input clarification may replace knowledge scope with a
validated client snapshot. Regenerate, null-input and `Command` resumes recover
scope from the genuine source user turn, skip hidden server context, and ignore
client scope. Treat `input.messages: null` as empty to allow promptless
conversation-reference runs.
Thread identifiers use the shared `deerflow.utils.thread_id` contract
`^[A-Za-z0-9_-]{1,64}$`. Caller-provided opaque IDs remain supported; UUIDs
are generated only for `None`, while explicit empty strings fail validation.
Gateway creation and state-producing request boundaries, embedded-client
entry points, filesystem/upload/event-store consumers, scheduled launches,
and the standalone Provisioner enforce the same contract before persistence
or workspace initialization. Route-addressable legacy IDs remain accepted by
pure reads and cleanup/control endpoints; deleting one best-effort removes
metadata and checkpoints but skips local filesystem cleanup, so the raw value
is never interpolated into a host path. New runs, workspace/sandbox
operations, and other state-producing mutations remain blocked.
**Message feed seq** (#4666): streaming `values` frames, `GET
/threads/{id}/state`, and `POST /threads/{id}/history` stamp serialized
messages with `additional_kwargs.deerflow_seq` so clients can place
checkpoint-kept messages against the paged feed; the REST reads resolve the
store via `threads.py::_optional_run_event_store` (a feed-less deployment
still reads threads), and `services.py::normalize_input` strips the
server-owned key from client input (#4380). Mechanism and identity rule:
`packages/harness/deerflow/runtime/AGENTS.md`.
**Workspace change review**: `packages/harness/deerflow/workspace_changes/`
captures a pre-run and post-run snapshot of the thread-owned `workspace` and
`outputs` directories. `runtime/runs/worker.py` performs the filesystem scan via
`asyncio.to_thread` and writes a `workspace_changes` event with category
`workspace` when changes exist. Uploads are intentionally excluded. Text diffs
are size-limited; binary, large, and sensitive-looking paths are persisted as
metadata only. Internal process-feedback directories never count as changes:
the scanner's `EXCLUDED_DIR_NAMES` drops `BROWSER_FRAMES_DIRNAME` (transient
browser screenshots) and `TOOL_RESULTS_DIRNAME` (the tool-output budget
middleware's default externalization subdir, `constants.py` is the shared
source of truth for both writers and the scanner), and the worker threads the
configured `tool_output.storage_subdir` through the snapshot capture as an
extra excluded dir name so custom storage locations stay excluded too.
**Run delivery receipts**: the worker derives delivery requirements from the
run's workspace snapshots rather than a client request option (files
created/modified under `/mnt/user-data/outputs`, minus internal
process-feedback exclusions) and idempotently persists a run-scoped
`run.delivery` receipt before the terminal run status; missing or
unverifiable `present_files` coverage downgrades the run to error, while runs
without changed outputs keep ordinary chat behavior. Journal mechanics
(callback attribution, receipt idempotency and retries, orphan recovery):
`packages/harness/deerflow/runtime/AGENTS.md`. Multi-worker deployments
require `run_events.backend: db` for shared, ordered delivery events; the
startup gate rejects memory/JSONL event stores when `GATEWAY_WORKERS > 1`
or `deployment.multi_instance: true`.
**RunManager / RunStore contract**:
- LangGraph-compatible run requests validate their supported subset before creating a run. `runtime/stream_modes.py` is the shared backend contract for public stream modes and the worker's `graph.astream` mapping; the public `messages-tuple` mode maps to LangGraph's internal `messages` mode, while public `messages`, `events`, and other unsupported modes are rejected instead of being dropped or replaced with `values`. `app/gateway/run_models.py::RunCreateRequest` is shared by HTTP and internal scheduled launch paths, retains only truthful compatibility defaults for unimplemented options (`if_not_exists="create"` plus `None` placeholders), returns 422 for unsupported values including `on_completion="complete"`, `on_completion="continue"`, and `multitask_strategy="enqueue"`, and forbids undeclared SDK options so fields such as `checkpoint_during` and `durability` cannot be silently discarded. A placeholder must still accept the stock SDK's own default: `langgraph_sdk` drops only `None` from its run payload, so `stream_resumable=False` reaches every request and means "non-resumable", which is what DeerFlow serves — rejecting it 422'd every IM channel run (#4466). `test_run_request_validation.py::test_gateway_accepts_langgraph_sdk_default_payload` pins the real SDK payload; channel tests mock the SDK and miss this drift.
- `RunManager.get()` is async; direct callers must `await` it.
- The history batch helpers `list_successful_regenerate_sources()`, `list_edit_regenerate_runs()`, and `get_many_by_thread()` default to `user_id=AUTO`: they resolve the request user and fail closed when no user context exists. Migration/admin callers that intentionally need an unscoped read must pass `user_id=None` explicitly.
- Edit-and-rerun visibility is derived from edit replay runs (`metadata.replay_kind="edit"` plus `regenerate_from_run_id`) by `RunManager.list_edit_replay_visibility()`: the newest attempt for each source run is authoritative. Pending/running/success attempts hide the original source run; failed, timed-out, or interrupted attempts hide only the failed attempt so the original conversation reappears.
- When a persistent `RunStore` is configured, `get()` and `list_by_thread()` hydrate historical runs from the store. In-memory records win for the same `run_id` so task, abort, and stream-control state stays attached to active local runs.
- Thread metadata status switches to `running` only after `RunManager.try_start()` succeeds. Pending-cancelled runs therefore skip the old `running` projection, while clients may observe the prior thread status during the short worker-startup window.
- `cancel()` returns a :class:`~deerflow.runtime.CancelOutcome` enum: `cancelled` (local cancel), `requested` (the non-owning worker durably recorded the first cancellation action for the live owner), `taken_over` (non-owning worker claimed the run because the owner's lease expired — marks it as `error`), `lease_valid_elsewhere` (legacy/custom store lacks the durable request primitive — caller retains the safe 409 + `Retry-After` fallback), `not_active_locally` (heartbeat disabled, preserving the old 409 path), `not_cancellable` (terminal state), or `unknown` (not found in memory or store). `create_or_reject(..., multitask_strategy="interrupt"|"rollback")` persists interrupted status through `RunStore.update_status()`, matching normal `set_status()` transitions.
- Interrupt/rollback admission registers the replacement before its best-effort persistence of locally interrupted predecessors. If the admitting caller is cancelled during that post-registration await, `RunManager` drains a shielded replacement cleanup before propagating `CancelledError`, including across repeated cancellation. The cleanup normally persists `interrupted`; if that best-effort transition fails, it retries the active-to-`interrupted` store transition strictly and verifies the result with the replacement's captured owner identity. A concurrent peer terminal transition wins and is synchronized back into the local record rather than being overwritten or deleted.
- Store-only hydrated runs are readable history. In multi-worker mode with heartbeat enabled, cancel on a store-only run records `runs.cancel_action` / `cancel_requested_at` while the owner's lease is live; the first action wins even if a retry later lands on the owner. `RunStore.request_cancel()` and owner completion through `finalize_if_not_cancelled()` are competing active-row CAS operations, so an accepted cancel cannot be overwritten by a later success. `RunStore.renew_lease()` renews and observes the request atomically in the SQL implementation. The owner then executes the normal process-local interrupt/rollback and terminal stream path without transferring the lease. An expired owner is taken over with the `orphan_recovered` stop reason so cross-worker consumers can synthesize END. `wait=true` and cancel-then-stream use the shared bridge to observe owner finalization; a non-standard process-local bridge returns accepted 202 instead of subscribing to an unreachable stream. In single-worker mode (heartbeat off), store-only runs still return 409.
- A local worker's `RunRecord.lease_expires_at` is the last durably confirmed ownership deadline. `_renew_leases()` bounds each renewal attempt by that deadline: transient store exceptions remain retryable while it is valid, but an exception or blocked call that reaches expiry sets the process-local `ownership_lost` fence, raises `abort_event`, and cancels the run task. Successful renewals collect durable cancellation actions; after all local renewals have been attempted, heartbeat only signals the corresponding process-local tasks, leaving status writes and rollback cleanup to the worker finalization path. Fenced workers do not perform subsequent journal/delivery-receipt, progress/completion/status, checkpoint/thread-metadata, or `on_run_completed` writes; the peer recovery path owns the terminal receipt. `RunStore.update_run_completion()` also refuses to replace a different terminal status, closing the peer-takeover/late-finalization race. `grace_seconds` delays peer reclamation for clock skew but is not extra execution time for an owner that can no longer confirm its lease. Already-committed remote tool side effects remain outside this local cancellation boundary.
- Startup/orphan reconciliation must claim stale active rows with `RunStore.claim_for_takeover()`, not a plain `update_status()`. The final claim re-checks `status` and lease expiry atomically, so a heartbeat renewal between the candidate scan and the recovery write keeps the run active.
- Run admission and independent writes are first-class thread operations. `runs.operation_kind` distinguishes `run` from `checkpoint_write`, `artifact_write`, `artifact_archive`, `branch`, and `delete`; every active kind shares the durable active-thread uniqueness constraint. New operation kinds must go through `RunStore.create_thread_operation_atomic()` and `RunManager.reserve_thread_operation()` rather than adding another lock or metadata marker. Live and lease-less reservations are non-interruptible; an expired leased reservation can be reclaimed immediately by interrupt/rollback admission without waiting for orphan reconciliation. Lease-less rows stay fail-closed because the store cannot distinguish a stale row from a live writer in another heartbeat-disabled worker; a rare failed delete therefore requires startup reconciliation, and heartbeat-disabled multi-worker deployment remains unsupported. Reservation bodies are attached to their caller task so loss detected by lease renewal cancels the writer before it can continue after takeover; the context manager translates that lease-loss cancellation to `ConflictError` after cleanup so Gateway mutation routes return a retryable 409 instead of dropping the HTTP request. The cleanup scope begins immediately after durable admission, including the await that attaches the caller task, so cancellation cannot strand a locally renewed pending reservation. A failed renewal is revalidated under the manager lock before cancellation; if the reservation completed and unregistered while the store update was in flight, its request task must not be cancelled after the write. Reservations are excluded from run history/reporting and from run-only helpers such as `list_by_thread()` and `has_inflight()`, release uses the captured owner rather than ambient user context, and local cleanup still runs when the best-effort store delete fails. `RunStore.create_run_atomic()` remains a deprecated compatibility shim for external stores that only admit normal runs; new stores must implement `create_thread_operation_atomic()` to support internal operation kinds.
- Gateway checkpoint mutations outside run execution must use `services.reserve_checkpoint_write()`, which composes the process-local thread lock with the durable `checkpoint_write` reservation. Manual compaction, `POST /threads/{id}/state`, and both goal mutation routes (`PUT` / `DELETE /threads/{id}/goal`, including creation of a missing goal checkpoint) use this boundary, so an existing run blocks the write and the reservation blocks new reject/interrupt/rollback runs across workers.
- Branch/state-update checkpoints copy only the source checkpoint's persisted `deerflow_agent_name`, never request metadata; missing or malformed bindings stay unbound so compaction fails closed.
- `DELETE /api/threads/{id}` holds a durable `delete` reservation for the whole cleanup and removes thread filesystem data (off-loop, drained on cancel), checkpoints, owner-scoped historical runs, run events, feedback and thread metadata best-effort. Historical-run cleanup removes only `operation_kind="run"` rows, so internal thread-operation rows — including the reservation protecting that request — stay durable until `RunManager.reserve_thread_operation()` exits. This cleans persisted rows; preventing an already-admitted write from re-creating state for a deleted thread is a separate thread-incarnation contract, not part of this cleanup.
- Creator SSE and `/wait` apply `on_disconnect` only to confirmed request disconnect or cancellation; bridge failures propagate without cancelling the run. `/wait` consumes bridge END; errors return SDK `__error__`, never stale state.
- Memory and Redis `StreamBridge` implementations retain only `stream_bridge.queue_maxsize` data events. A syntactically valid `Last-Event-ID` older than the retained watermark, or a live subscriber that falls behind it, yields `StreamGap` before any partial replay. `sse_consumer` maps that control item to an id-less SSE `gap` payload (`stream_replay_gap`) and intentionally leaves the run active; internal `/wait` consumers resume from its latest retained ID because they only need terminal completion. Redis checks bounds plus the non-blocking read in one transaction, using blocking `XREAD` only as a wake-up before repeating the atomic snapshot. For a no-cursor subscriber that established a wait on an empty stream, the first wake response remains provisional until that next snapshot verifies its tail is still retained; this closes the pre-first-delivery trimming window without changing malformed-cursor live tailing. The correctness tradeoff is one three-command snapshot pipeline per poll plus the blocking wake round trip while idle. Malformed cursor behavior remains backend-specific. Memory treats a syntactically numeric cursor below its watermark conservatively as a gap even when the evicted timestamp can no longer be verified; unknown ids at or above the watermark retain the legacy replay-from-earliest policy.
- Redis `StreamBridge` keys use a rolling retained-buffer TTL (`stream_bridge.stream_ttl_seconds`, refreshed on data and first-END writes) as a leak safety net, not as a run timeout. Startup and lease-driven periodic orphan recovery share one Gateway stream-terminalization path: after `RunManager` durably marks a run `error` with `stop_reason=orphan_recovered`, Gateway publishes `END_SENTINEL` and schedules stream cleanup. The periodic store scan, per-row status writes, and Gateway callback run as one supervised single-flight task, so a slow pass is skipped at the next interval instead of piling up or pausing the sole lease-renewal loop. Store retries have bounded attempts/backoff; an individual operation still relies on the database driver/pool timeout. `RunManager.shutdown()` gives active user runs priority within its shared deadline, then drains or cancels orphan recovery. Gateway tracks delayed recovered-stream cleanups and converts unfinished delays to immediate deletes before closing the bridge; the Redis TTL remains the outage safety net. Only startup recovery, before the runtime yields to requests, projects the latest affected thread to `error`; periodic recovery deliberately avoids that non-atomic projection because `ThreadMetaStore` has no `latest_run_id` conditional-update contract. Store-only SSE and `/wait` consumers wait for the bridge's real END marker after an ordinary durable terminal status, because status persistence can precede tail events. Terminal `orphan_recovered` and `scheduled_task_orphan_recovered` rows permit heartbeat fallback because their producer is gone; ordinary terminal rows still await END. Malformed `Last-Event-ID` reconnect values live-tail new Redis events rather than replaying the retained buffer. Keep cross-component recovery orchestration in Gateway through the generic `RunManager.on_orphans_recovered` callback; do not introduce a harness-to-app dependency. Callback failure warnings include every recovered `run_id` so operators can identify rows whose Gateway-side terminalization needs inspection.
- Thread-scoped create, stream and wait share an optional owner/thread-scoped `Idempotency-Key` (internal callers: owner-only, cross-thread reuse 409); never pass the raw external key to `RunManager`'s process-wide index. Stores resolve an existing key before `interrupt`/`rollback`, so a retry reuses rather than interrupts its run. Reuse requires matching input, assistant and conversation references; keyed resume stores a versioned strict typed-JSON SHA-256 (`true`, `1` and `1.0` differ) in the private `runs.idempotency_request_json` column, never public `kwargs`; ordinary input needs no extra identity. New readers accept the exact old-writer resume identity shape from `kwargs`, every response strips it; identity-less legacy resume fails closed. Validate strict resume JSON with or without a key; persist the identity only for keyed resume admission. Missing headers stay non-idempotent; stateless `/api/runs/*` is outside this contract (it creates a thread before admission).
- For a rolling upgrade, route every keyed resume submission/retry on create/stream/wait only to upgraded workers; otherwise pause that traffic or replace old workers first. Old workers ignore the private identity and can reuse `approve` for `deny` with null input. Old-reader schema compatibility does not protect admission. Upgraded workers reject identity-less legacy resumes with 409. Rollout details: `README.md`, `backend/docs/API.md`.
- Reused `/wait` returns durable status/error, never the latest thread checkpoint; `task is None` is not completion, and store-backed fields must refresh after waiting. Capture reuse before awaiting because the cached record's `idempotency_reused` flag is sticky. A creating `/runs/stream` retry whose terminal stream is gone opts into `gap`/`stream_replay_gap` via `emit_gap_on_missing_stream`, while observer joins and default/stateless consumers emit `end`; never infer this from disconnect policy or the sticky flag. A reused running `store_only` record on a process-local bridge returns 409 without `Retry-After`.
- Thread-scoped run creation accepts `checkpoint` / `checkpoint_id`; Gateway validates the checkpoint belongs to the request thread before writing `checkpoint_id` / `checkpoint_ns` into `config.configurable` for LangGraph branching. In `delta` checkpoint mode the worker rewrites that fork into a linear head write before the graph starts (see "A delta-mode run cannot fork" under Checkpoint Channel Modes), because delta state for a fork replays the abandoned sibling's writes.
- Thread-scoped Gateway runs evaluate an active `ThreadState.goal` after the visible turn completes. `runtime/goal.py` asks a non-thinking evaluator model to judge only visible conversation evidence and return a typed blocker; the evaluator model is created once per run and reused across hidden continuation checks. The evaluator runs after the graph root's tracing scope has already closed, so `create_goal_evaluator_model`/`evaluate_goal_completion` attach their own model-level tracing callbacks (`attach_tracing=True`) and inject Langfuse trace metadata (`thread_id`/`user_id`/`deerflow_trace_id`) directly onto the `ainvoke` call — the same standalone-caller pattern as `oneshot_llm.run_oneshot_llm` and `MemoryUpdater` (see Tracing System below). Satisfied goals are cleared; every non-satisfied evaluation — continuable or stand-down — is persisted with `last_evaluation` (the blocker, reason, and evidence summary; outcomes that stop the loop additionally record a `stand_down_reason` for observability), but only `goal_not_met_yet` evaluations are streamed as hidden `HumanMessage` continuations, and only when the turn did not end on an unanswered Human Input Card (`ask_clarification` or the sandbox network prompt; the question is still open, so the goal stands down with `blocker: "needs_user_input"` without calling the evaluator), a durable assistant end-of-turn checkpoint exists, the run has not been aborted, the run has not hit its token-budget hard stop (`stop_reason == "token_capped"`; the goal stands down with `stand_down_reason: "token_capped"`), the thread did not change during evaluation, and the no-progress breaker has not fired. The continuation cap is 8 — a hard maximum in the `0`–`8` range; callers requesting more are clamped (`set_goal`/TUI) or rejected with 422 (`PUT /goal`). The no-progress breaker keys on the latest visible assistant evidence (not the evaluator's free-text reason, which an LLM rewords every turn), so two consecutive continuations that add no new visible assistant output stop the loop after 2 attempts. Model-response cleanup helpers such as think-block stripping and code-fence stripping live in `deerflow.utils.llm_text` so `runtime/goal.py` and Gateway suggestion parsing share the same JSON-prep behavior.
- Run event stream changes must keep producer code, `deerflow/constants.py`, `runtime/events/catalog.py`, `contracts/run_event_stream_contract.json`, `backend/docs/RUN_EVENT_STREAM.md`, and `tests/test_run_event_stream_contract.py` in sync. The dependency-free constants module owns the persisted envelope limits (`event_type` 32 characters, `category` 16) and cross-layer workspace event identity; the catalog owns validated runtime definitions and categories. Dynamic middleware tags are limited to 21 characters after the `middleware:` prefix. The JSON contract owns payload schemas, backend-specific storage semantics, legacy aliases, and compatibility rules; conformance tests require both views and all producer groups to agree. `run.end.content` remains opaque and may retain nested Python values in memory while JSONL/database stores stringify non-JSON nested values, so consumers must not assume backend-identical nested output representations.
Scheduled-task PATCH: omitted `assistant_id` preserves the pin; explicit null resets to `lead_agent`.
Two origin keys; never read one for the other. `deerflow_scheduled_origin` marks the scheduled prompt message (`scheduled_goal_notes_contract.json`); `deerflow_origin` says who started a run/created a thread (`thread_origin_contract.json`), set only via `request.state.run_origin` or internal `body.metadata`.
**Thread lifecycle**: Before changing branching, regeneration, edit replay, or
archive/search behavior, read [Thread lifecycle invariants](../../docs/THREAD_LIFECYCLE.md).
It owns lineage and settled-checkpoint rules, legacy fallback boundaries, archive
filtering before pagination, owner isolation, and activity-time preservation.
MCP create/replace/state writes require unique installation IDs. DELETE validates
schema but permits residual legacy ID collisions. Explicit selections exclude
ambiguous IDs until repaired.
Capability skill discovery (`/api/capabilities/installations/skills`) reuses
`routers/skills.py::_filter_visible_skills` after its off-thread storage read.
It must preserve the ordinary skill listing's caller visibility and provider
failure policy rather than exposing the unfiltered user-scoped catalog.
Cap edit reads at `MAX_EDITABLE_ARTIFACT_BYTES + 1` despite stale `lstat`.
### Route and skill authorization
`authz.authorize_model_use` shares the `model:use` decision between model details
and follow-up suggestions, including the factory's first configured model when
the caller omits `model_name`. Suggestions check admission before their
best-effort LLM error handler: explicit denies return 403 without invoking the
model, while provider failures honor `authorization.fail_closed`.
`authz.py::resolve_route_permissions()` is shared by HTTP, decorator-only auth, and Live Browser WebSocket admission. It evaluates full `resource:action` targets; provider errors follow `authorization.fail_closed`, while disabled authorization preserves legacy permissions. Owner/admin checks stay separate. Live requires `threads:write` with `is_internal=False` after login/Origin checks; denial closes 4403 and setup errors close 4501. Admission is connection-scoped. On disconnect, Live drains owned `stop_screencast()` cleanup before releasing the session lease. Tests: `test_authorization_route_permissions.py`, `test_browser_readonly_security.py`, `test_auth.py`, `test_auth_middleware.py`.
Skill listing authorization mirrors the models pattern: `routers/skills.py` routes resolve `(provider, principal)` through `authz.py::resolve_skill_authorization()` — a thin sibling of `resolve_model_authorization`, both delegating to the shared `_resolve_route_scoped_authorization` core — and the shared `_filter_visible_skills` helper filters the user-scoped catalog (public + caller's custom skills) through `filter_resources(principal, "skill", ...)` by name. Three user-facing surfaces apply it: `GET /api/skills` (the frontend skill list / slash-command autocomplete), `GET /api/skills/custom`, and `GET /api/skills/{name}` — the detail endpoint returns the standard 404 for an invisible skill so it cannot become an existence oracle the filtered list closed (`get_model`'s 403 is an execution decision via `authorize("model", "use")`, which has no skills equivalent in this layer). Anonymous callers are unfiltered (mirroring `list_models`), and provider resolution/decision errors follow `authorization.fail_closed` (fail-closed → empty listing / 404, fail-open → full listing). Skill management endpoints (`install`/`upload`/`reload`/custom-skill CRUD) stay `require_admin_user`-gated, and runtime activation authorization is a separate layer. The built-in RBAC provider maps this to the per-role `skills` policy key. Tests: `tests/test_skills_listing_authorization.py`.
Batch workers pin `app.state.extensions`; never persist snapshots.
Personal MCP is owner-only; platform MCP shared.
### Web model provider presets
Managed model routes expose provider metadata; routing stays server-owned. Align validation, probing, storage, keys, and revisions.

View File

@ -1,7 +1,7 @@
import asyncio import asyncio
import logging import logging
from collections.abc import AsyncGenerator from collections.abc import AsyncGenerator
from contextlib import ExitStack, asynccontextmanager, suppress from contextlib import asynccontextmanager, suppress
from typing import Any from typing import Any
from deerflow_extension_api import ( from deerflow_extension_api import (
@ -31,7 +31,6 @@ from app.gateway.routers import (
channel_connections, channel_connections,
channels, channels,
console, console,
coordination,
features, features,
feedback, feedback,
github_webhooks, github_webhooks,
@ -40,9 +39,7 @@ from app.gateway.routers import (
integrations, integrations,
knowledge, knowledge,
mcp, mcp,
mcp_agent_auth,
mcp_tasks, mcp_tasks,
mcp_user_oauth,
memory, memory,
models, models,
personal_mcp, personal_mcp,
@ -52,8 +49,6 @@ from app.gateway.routers import (
projects, projects,
runs, runs,
scheduled_tasks, scheduled_tasks,
search,
shares,
skill_mutations, skill_mutations,
skills, skills,
subagent_batches, subagent_batches,
@ -65,12 +60,11 @@ from app.gateway.routers import (
trash, trash,
uploads, uploads,
user_preferences, user_preferences,
voice_input,
) )
from app.gateway.trace_middleware import TraceMiddleware from app.gateway.trace_middleware import TraceMiddleware
from deerflow.config import app_config as deerflow_app_config from deerflow.config import app_config as deerflow_app_config
from deerflow.logging_config import DEFAULT_LOG_DATE_FORMAT, DEFAULT_LOG_FORMAT, configure_logging from deerflow.logging_config import DEFAULT_LOG_DATE_FORMAT, DEFAULT_LOG_FORMAT, configure_logging
from deerflow.sandbox.sandbox_provider import get_sandbox_provider, hold_sandbox_shutdown_ownership from deerflow.sandbox.sandbox_provider import hold_sandbox_shutdown_ownership
from deerflow.tracing.monocle import setup_monocle_tracing_if_enabled from deerflow.tracing.monocle import setup_monocle_tracing_if_enabled
from deerflow.uploads.manager import cleanup_stale_upload_staging_files from deerflow.uploads.manager import cleanup_stale_upload_staging_files
from deerflow.utils.file_io import await_drained from deerflow.utils.file_io import await_drained
@ -364,24 +358,6 @@ async def _run_startup_trash_sweep(app: FastAPI, startup_config) -> None:
logger.warning("Trash retention sweep skipped", exc_info=True) logger.warning("Trash retention sweep skipped", exc_info=True)
async def _run_startup_queued_upload_sweep(app: FastAPI) -> None:
try:
from app.gateway.run_input_cleanup import cleanup_abandoned_queued_uploads
from deerflow.config.paths import get_paths
store = getattr(app.state, "run_store", None)
if store is not None:
removed = await cleanup_abandoned_queued_uploads(store, get_paths())
if removed:
logger.info("Removed %d abandoned queued upload stage(s)", removed)
except Exception:
logger.warning("Queued upload stage cleanup skipped", exc_info=True)
async def _run_startup_storage_sweeps(app: FastAPI, startup_config) -> None:
await asyncio.gather(_run_startup_trash_sweep(app, startup_config), _run_startup_queued_upload_sweep(app))
async def _shutdown_startup_trash_sweep(app: FastAPI) -> None: async def _shutdown_startup_trash_sweep(app: FastAPI) -> None:
"""Grace-budgeted shutdown for the background startup sweep (§8.3). """Grace-budgeted shutdown for the background startup sweep (§8.3).
@ -516,7 +492,7 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
silent backlog, so the enqueue side is detached when delivery cannot start. silent backlog, so the enqueue side is detached when delivery cannot start.
""" """
scheduled_task_service = getattr(app.state, "scheduled_task_service", None) scheduled_task_service = getattr(app.state, "scheduled_task_service", None)
if notification_repo is None: if scheduled_task_service is None or notification_repo is None:
return return
from app.channels.service import get_channel_service from app.channels.service import get_channel_service
@ -524,7 +500,6 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
channel_service = get_channel_service() channel_service = get_channel_service()
if channel_service is None: if channel_service is None:
logger.warning("channel_connections.enabled but no channel service is running; disabling scheduled-task IM notification enqueue to avoid a write-only outbox") logger.warning("channel_connections.enabled but no channel service is running; disabling scheduled-task IM notification enqueue to avoid a write-only outbox")
if scheduled_task_service is not None:
scheduled_task_service.detach_notification_outbox() scheduled_task_service.detach_notification_outbox()
return return
@ -582,7 +557,6 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
return True return True
prefs_repo = ImNotificationPreferencesRepository(get_session_factory()) prefs_repo = ImNotificationPreferencesRepository(get_session_factory())
coordination = getattr(app.state, "coordination_workers", None)
worker = NotificationDeliveryWorker( worker = NotificationDeliveryWorker(
delivery_repo=notification_repo, delivery_repo=notification_repo,
resolve_channel=channel_service.get_channel, resolve_channel=channel_service.get_channel,
@ -598,14 +572,12 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
resolve_notification_preferences=prefs_repo.get, resolve_notification_preferences=prefs_repo.get,
resolve_notification_event_preferences=prefs_repo.get_event_preferences, resolve_notification_event_preferences=prefs_repo.get_event_preferences,
resolve_human_input_pending=resolve_human_input_pending, resolve_human_input_pending=resolve_human_input_pending,
read_coordination_artifact=coordination.repo.read_artifact if coordination is not None else None,
poll_interval_seconds=startup_config.scheduler.poll_interval_seconds, poll_interval_seconds=startup_config.scheduler.poll_interval_seconds,
# Language of notices whose owner has no UI language preference. # Language of notices whose owner has no UI language preference.
default_locale=startup_config.channel_connections.notification_locale, default_locale=startup_config.channel_connections.notification_locale,
) )
await worker.start() await worker.start()
except Exception: except Exception:
if scheduled_task_service is not None:
scheduled_task_service.detach_notification_outbox() scheduled_task_service.detach_notification_outbox()
raise raise
app.state.notification_delivery_worker = worker app.state.notification_delivery_worker = worker
@ -614,13 +586,7 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
@asynccontextmanager @asynccontextmanager
async def _runtime_with_mcp_pool_shutdown(app: FastAPI, startup_config: AppConfig) -> AsyncGenerator[None, None]: async def _runtime_with_mcp_pool_shutdown(app: FastAPI, startup_config: AppConfig) -> AsyncGenerator[None, None]:
"""Close MCP transports and initialized sandboxes after runtime shutdown.""" """Close MCP transports and initialized sandboxes after runtime shutdown."""
signal_handlers = ExitStack()
try: try:
ownership = getattr(getattr(startup_config, "sandbox", None), "ownership", None)
if ownership is not None and ownership.redis_mode == "cluster":
# Discover Redis slots before async request handlers can cold-start the provider.
provider = await await_drained(asyncio.to_thread(get_sandbox_provider))
signal_handlers.enter_context(provider.gateway_signal_handlers())
async with langgraph_runtime(app, startup_config): async with langgraph_runtime(app, startup_config):
yield yield
finally: finally:
@ -653,8 +619,6 @@ async def _runtime_with_mcp_pool_shutdown(app: FastAPI, startup_config: AppConfi
await await_drained(asyncio.to_thread(shutdown_sandbox_provider)) await await_drained(asyncio.to_thread(shutdown_sandbox_provider))
except Exception: except Exception:
logger.exception("Failed to shut down sandbox provider") logger.exception("Failed to shut down sandbox provider")
finally:
signal_handlers.close()
@asynccontextmanager @asynccontextmanager
@ -695,9 +659,6 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
ensure_browser_runtime_available(startup_config) ensure_browser_runtime_available(startup_config)
logger.info("Configuration loaded successfully") logger.info("Configuration loaded successfully")
warn_if_auth_disabled_enabled() warn_if_auth_disabled_enabled()
hitl_approval = getattr(startup_config, "hitl_approval", None)
if getattr(hitl_approval, "enabled", False) is not True:
logger.warning("hitl_approval is not enabled. Tool calls can execute without runtime human review. Set hitl_approval.enabled to true in config.yaml to enable tool approvals. See docs/guide/skills-and-tools.md.")
except Exception as e: except Exception as e:
error_msg = f"Failed to load configuration during gateway startup: {e}" error_msg = f"Failed to load configuration during gateway startup: {e}"
logger.exception(error_msg) logger.exception(error_msg)
@ -787,10 +748,15 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# Must run AFTER langgraph_runtime so app.state.store is available for thread migration # Must run AFTER langgraph_runtime so app.state.store is available for thread migration
await _ensure_admin_user(app) await _ensure_admin_user(app)
# Run both storage sweeps after their repositories are ready, without # Phase-2 trash tier (§8.3): one retention sweep at startup, beside
# delaying gateway readiness. Shutdown drains in-flight writes before # the lazy trigger on the trash listing — no daemon, no scheduler.
# tearing the runtime down. # Runs after langgraph_runtime so app.state.project_document_repo is
app.state.startup_trash_sweep_task = asyncio.create_task(_run_startup_storage_sweeps(app, startup_config)) # available. The per-user reconciliation walks every row and file, so
# it is scheduled as a background task: gateway readiness never waits
# on it, a failure is logged by the task itself, and shutdown gives the
# in-flight sweep a bounded graceful budget before cancelling it; any
# already-started file worker drains before the runtime is torn down.
app.state.startup_trash_sweep_task = asyncio.create_task(_run_startup_trash_sweep(app, startup_config))
# Best-effort per-document summary generation. # Best-effort per-document summary generation.
# Workers start only when projects.summaries_enabled is true; the # Workers start only when projects.summaries_enabled is true; the
@ -868,11 +834,9 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# ChannelManager's follow-up-drain watcher (issue #4121 Slice 2) # ChannelManager's follow-up-drain watcher (issue #4121 Slice 2)
# uses to reach the same StreamBridge every other run consumer # uses to reach the same StreamBridge every other run consumer
# goes through `get_stream_bridge(request)` for. # goes through `get_stream_bridge(request)` for.
coordination = getattr(app.state, "coordination_workers", None)
channel_service = await start_channel_service( channel_service = await start_channel_service(
startup_config, startup_config,
get_stream_bridge=lambda: getattr(app.state, "stream_bridge", None), get_stream_bridge=lambda: getattr(app.state, "stream_bridge", None),
dispatch_coordination_task=coordination.dispatch_bound_channel if coordination is not None and scheduled_notification_repo is not None else None,
credentials_cipher=credentials_cipher, credentials_cipher=credentials_cipher,
# channels.leader_lease: auto follows the same multi-process # channels.leader_lease: auto follows the same multi-process
# signal the startup gate used; the lease owner is this # signal the startup gate used; the lease owner is this
@ -959,20 +923,11 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
if subagent_batches_config.enabled and batch_repo is None: if subagent_batches_config.enabled and batch_repo is None:
raise RuntimeError("subagent_batches.enabled requires database.backend sqlite or postgres") raise RuntimeError("subagent_batches.enabled requires database.backend sqlite or postgres")
if batch_repo is not None: if batch_repo is not None:
from app.subagent_batches.continuation import BatchContinuations
from app.subagent_batches.identity import resolve_batch_principal
continuations = BatchContinuations(app)
app.state.batch_continuations = continuations
batch_service = SubagentBatchService( batch_service = SubagentBatchService(
repository=batch_repo, repository=batch_repo,
config=subagent_batches_config, config=subagent_batches_config,
runtime_config=subagent_runtime_config, runtime_config=subagent_runtime_config,
extensions=getattr(app.state, "extensions", None), extensions=getattr(app.state, "extensions", None),
prepare_continuation=continuations.prepare,
dispatch_continuation=continuations.dispatch,
cancel_continuation=continuations.cancel,
resolve_principal=lambda batch: resolve_batch_principal(batch, load_user=app.state.agent_runs_host.load_user),
) )
app.state.subagent_batch_service = batch_service app.state.subagent_batch_service = batch_service
if subagent_batches_config.enabled: if subagent_batches_config.enabled:
@ -980,14 +935,7 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
set_subagent_batch_submitter(batch_service) set_subagent_batch_submitter(batch_service)
app.state.subagent_batches_available = True app.state.subagent_batches_available = True
workers = getattr(app.state, "coordination_workers", None)
try:
if workers is not None:
workers.start_recovery()
yield yield
finally:
if workers is not None:
await workers.close()
await _shutdown_startup_trash_sweep(app) await _shutdown_startup_trash_sweep(app)
try: try:
@ -1394,15 +1342,11 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for
# MCP API is mounted at /api/mcp # MCP API is mounted at /api/mcp
app.include_router(capabilities.router) app.include_router(capabilities.router)
# Runtime MCP agent credential grants (admin) at /api/mcp/agent-auth
app.include_router(mcp_agent_auth.router)
app.include_router(mcp.router) app.include_router(mcp.router)
app.include_router(personal_mcp.router) app.include_router(personal_mcp.router)
app.include_router(mcp_user_oauth.router)
# Durable MCP tasks are scoped to their owning thread. # Durable MCP tasks are scoped to their owning thread.
app.include_router(mcp_tasks.router) app.include_router(mcp_tasks.router)
app.include_router(coordination.router)
app.include_router(subagent_batches.router) app.include_router(subagent_batches.router)
# Memory API is mounted at /api/memory # Memory API is mounted at /api/memory
@ -1428,9 +1372,7 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for
app.include_router(uploads.router) app.include_router(uploads.router)
# Thread cleanup API is mounted at /api/threads/{thread_id} # Thread cleanup API is mounted at /api/threads/{thread_id}
app.include_router(search.router)
app.include_router(threads.router) app.include_router(threads.router)
app.include_router(shares.router)
# Per-user activity feed (own prefix, so /api/threads/{thread_id} never captures it) # Per-user activity feed (own prefix, so /api/threads/{thread_id} never captures it)
app.include_router(thread_activity.router) app.include_router(thread_activity.router)
@ -1457,7 +1399,6 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for
# Input polishing API is mounted at /api/input-polish # Input polishing API is mounted at /api/input-polish
app.include_router(input_polish.router) app.include_router(input_polish.router)
app.include_router(voice_input.router)
# User-facing IM channel connection API is mounted at /api/channels # User-facing IM channel connection API is mounted at /api/channels
app.include_router(channel_connections.router) app.include_router(channel_connections.router)

View File

@ -243,15 +243,7 @@ def build_artifact_archive(
reserved = frozenset(name.casefold() for name in {BROWSER_FRAMES_DIRNAME, TOOL_RESULTS_DIRNAME, *extra_reserved_dir_names}) reserved = frozenset(name.casefold() for name in {BROWSER_FRAMES_DIRNAME, TOOL_RESULTS_DIRNAME, *extra_reserved_dir_names})
members = [_member(root, path, reserved, deadline, root_components) for path in paths] members = [_member(root, path, reserved, deadline, root_components) for path in paths]
collision_keys = [unicodedata.normalize("NFC", member.entry).casefold() for member in members] collision_keys = [unicodedata.normalize("NFC", member.entry).casefold() for member in members]
collision_set = set(collision_keys) if len(collision_keys) != len(set(collision_keys)):
if len(collision_keys) != len(collision_set):
raise _reject()
implicit_dirs = set()
for key in collision_keys:
parts = key.split("/")
for i in range(1, len(parts)):
implicit_dirs.add("/".join(parts[:i]))
if collision_set & implicit_dirs:
raise _reject() raise _reject()
sizes = [member.initial.st_size for member in members] sizes = [member.initial.st_size for member in members]

View File

@ -63,7 +63,7 @@ class OIDCValidationError(OIDCError):
class OIDCUserInfoMismatch(OIDCError): class OIDCUserInfoMismatch(OIDCError):
"""UserInfo sub is missing or does not match ID token sub.""" """UserInfo sub does not match ID token sub."""
def _json_object(resp: httpx.Response, what: str) -> dict[str, Any]: def _json_object(resp: httpx.Response, what: str) -> dict[str, Any]:
@ -391,10 +391,8 @@ class OIDCService:
async def fetch_userinfo(self, metadata: OIDCMetadata, access_token: str, expected_sub: str) -> dict[str, Any]: async def fetch_userinfo(self, metadata: OIDCMetadata, access_token: str, expected_sub: str) -> dict[str, Any]:
"""Fetch userinfo from the UserInfo endpoint. """Fetch userinfo from the UserInfo endpoint.
The response is returned only when its ``sub`` equals ``expected_sub`` Validates that the ``sub`` claim matches ``expected_sub``
(from the ID token). OIDC Core 5.3.2 requires that check, and a (from the ID token) to prevent userinfo injection.
response without a ``sub`` cannot be tied to this login, so it raises
``OIDCUserInfoMismatch`` too instead of overriding the ID token claims.
""" """
if not metadata.userinfo_endpoint: if not metadata.userinfo_endpoint:
return {} return {}
@ -409,12 +407,7 @@ class OIDCService:
raise OIDCError(f"UserInfo fetch failed: {exc}") from exc raise OIDCError(f"UserInfo fetch failed: {exc}") from exc
userinfo = _json_object(resp, "UserInfo response") userinfo = _json_object(resp, "UserInfo response")
sub = userinfo.get("sub") if userinfo.get("sub") and userinfo["sub"] != expected_sub:
if sub is None or sub == "":
raise OIDCUserInfoMismatch("UserInfo response has no sub claim")
if not isinstance(sub, str):
raise OIDCUserInfoMismatch(f"UserInfo sub claim is not a string ({type(sub).__name__})")
if sub != expected_sub:
raise OIDCUserInfoMismatch("UserInfo sub does not match ID token sub") raise OIDCUserInfoMismatch("UserInfo sub does not match ID token sub")
return userinfo return userinfo

View File

@ -25,10 +25,6 @@ PAT_RANDOM_BYTES = 32
# automation does not turn every request into a database write. # automation does not turn every request into a database write.
PAT_LAST_USED_WRITE_INTERVAL_SECONDS = 300.0 PAT_LAST_USED_WRITE_INTERVAL_SECONDS = 300.0
# PAT-only scopes: not route permissions, so a session caller never needs
# them; a PAT reaches the routes they guard only while holding them.
PAT_ROUTE_SCOPES: frozenset[str] = frozenset({"schedules:read", "schedules:write", "subagents:read", "subagents:write"})
PAT_ALLOWED_SCOPES: frozenset[str] = frozenset( PAT_ALLOWED_SCOPES: frozenset[str] = frozenset(
{ {
"threads:read", "threads:read",
@ -40,24 +36,16 @@ PAT_ALLOWED_SCOPES: frozenset[str] = frozenset(
"projects:read", "projects:read",
"projects:write", "projects:write",
"projects:delete", "projects:delete",
# Deploying agent configuration from CI (#8310). agents:* are route
# permissions (``@require_permission``); schedules:* and subagents:*
# are PAT_ROUTE_SCOPES, enforced by _PAT_SCOPED_ROUTE_RULES below.
"agents:read",
"agents:write",
"schedules:read",
"schedules:write",
"subagents:read",
"subagents:write",
} }
) )
# Deliberately NOT in PAT_ALLOWED_SCOPES: the route permissions "memory:read" # Deliberately NOT in PAT_ALLOWED_SCOPES: the route permissions "memory:read",
# and "memory:write" exist in authz (they guard the memory router), but # "memory:write", "agents:read", and "agents:write" exist in authz
# _PAT_ROUTE_RULES default-denies the memory routes for PAT callers regardless # (they guard the memory/agent routers), but PATs stay on the thread/run
# of scopes. Opening a router to PATs must change all three of: this set, # lifecycle only — _PAT_ROUTE_RULES default-denies the memory/agent routes
# the route rules, and the API docs. ``agents:*`` open only /api/agents, not # for PAT callers regardless of scopes, so admitting these scopes would not
# /api/user-profile, which the same permissions guard for sessions. # even reach those routes. Opening them to PATs is a product decision that
# must change all three of: this set, _PAT_ROUTE_RULES, and the API docs.
PAT_MAX_NAME_LENGTH = 128 PAT_MAX_NAME_LENGTH = 128
@ -66,8 +54,9 @@ PAT_MAX_NAME_LENGTH = 128
# ``request.state.auth.permissions`` (``@require_permission``). Authenticated # ``request.state.auth.permissions`` (``@require_permission``). Authenticated
# mutation routes without that decorator — memory deletion, agent creation, # mutation routes without that decorator — memory deletion, agent creation,
# credential switching, channel configuration — would otherwise accept a # credential switching, channel configuration — would otherwise accept a
# PAT holding a single read scope. PAT callers can reach only the routes # PAT holding a single read scope. A route is reachable by PAT only when it
# explicitly listed in this table or the scoped table below. # is explicitly listed here, and only together with the thread/run lifecycle
# the v1 scopes govern; everything else answers 403 regardless of scopes.
_PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = ( _PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = (
(frozenset({"POST"}), re.compile(r"^/api/threads$")), (frozenset({"POST"}), re.compile(r"^/api/threads$")),
(frozenset({"POST"}), re.compile(r"^/api/threads/search$")), (frozenset({"POST"}), re.compile(r"^/api/threads/search$")),
@ -88,9 +77,6 @@ _PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = (
(frozenset({"GET", "PATCH", "DELETE"}), re.compile(r"^/api/projects/[^/]+$")), (frozenset({"GET", "PATCH", "DELETE"}), re.compile(r"^/api/projects/[^/]+$")),
(frozenset({"POST"}), re.compile(r"^/api/projects/[^/]+/(archive|restore)$")), (frozenset({"POST"}), re.compile(r"^/api/projects/[^/]+/(archive|restore)$")),
(frozenset({"GET"}), re.compile(r"^/api/projects/[^/]+/threads$")), (frozenset({"GET"}), re.compile(r"^/api/projects/[^/]+/threads$")),
(frozenset({"GET", "PATCH"}), re.compile(r"^/api/projects/[^/]+/memory$")),
(frozenset({"DELETE"}), re.compile(r"^/api/projects/[^/]+/memory/[^/]+$")),
(frozenset({"POST"}), re.compile(r"^/api/projects/[^/]+/memory/[^/]+/promote$")),
# Project document shelf (Phase 2 Slice B): enumerated per implemented # Project document shelf (Phase 2 Slice B): enumerated per implemented
# route — list/upload on the collection, content and trash on the item. # route — list/upload on the collection, content and trash on the item.
(frozenset({"GET", "POST"}), re.compile(r"^/api/projects/[^/]+/documents$")), (frozenset({"GET", "POST"}), re.compile(r"^/api/projects/[^/]+/documents$")),
@ -138,32 +124,6 @@ _PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = (
(frozenset({"GET"}), re.compile(r"^/api/runs/[^/]+/(messages|feedback)$")), (frozenset({"GET"}), re.compile(r"^/api/runs/[^/]+/(messages|feedback)$")),
) )
# Routes a PAT reaches only while holding the named scope, on top of any
# ``@require_permission`` check the route already has (#8310). Scheduled-task
# routes keep their threads:* / runs:create checks, so a token without run
# rights cannot schedule runs; the managed-subagent writes additionally stay
# admin-only (``require_admin_user(..., pat_scope="subagents:write")``).
_PAT_SCOPED_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str], str], ...] = (
# Own identity, so automation can confirm which account it acts as.
# Every PAT holds at least one scope; this route needs none of them.
(frozenset({"GET"}), re.compile(r"^/api/v1/auth/me$"), ""),
(frozenset({"GET"}), re.compile(r"^/api/agents$"), "agents:read"),
(frozenset({"POST"}), re.compile(r"^/api/agents$"), "agents:write"),
(frozenset({"GET"}), re.compile(r"^/api/agents/[^/]+$"), "agents:read"),
# The literal check (GET) and import (POST) actions use different methods.
(frozenset({"PUT", "DELETE"}), re.compile(r"^/api/agents/[^/]+$"), "agents:write"),
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks$"), "schedules:read"),
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks$"), "schedules:write"),
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks/preview-cron$"), "schedules:read"),
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks/(?!preview-cron$)[^/]+$"), "schedules:read"),
(frozenset({"PATCH", "DELETE"}), re.compile(r"^/api/scheduled-tasks/(?!preview-cron$)[^/]+$"), "schedules:write"),
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks/[^/]+/(pause|resume|trigger)$"), "schedules:write"),
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks/[^/]+/runs$"), "schedules:read"),
(frozenset({"GET"}), re.compile(r"^/api/subagents$"), "subagents:read"),
(frozenset({"POST"}), re.compile(r"^/api/subagents$"), "subagents:write"),
(frozenset({"PUT", "DELETE"}), re.compile(r"^/api/subagents/[^/]+$"), "subagents:write"),
)
_BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" _BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@ -174,20 +134,7 @@ def is_pat_allowed_route(method: str, path: str) -> bool:
redirect-style twin resolve identically. redirect-style twin resolve identically.
""" """
normalized = path.rstrip("/") or "/" normalized = path.rstrip("/") or "/"
return any(method in methods and pattern.match(normalized) for methods, pattern in _PAT_ROUTE_RULES) or pat_route_scope(method, path) is not None return any(method in methods and pattern.match(normalized) for methods, pattern in _PAT_ROUTE_RULES)
def pat_route_scope(method: str, path: str) -> str | None:
"""Return the scope a PAT needs for *method* + *path* beyond its route permissions.
``None`` means the route has no scoped rule; ``""`` means it is admitted
for every valid PAT.
"""
normalized = path.rstrip("/") or "/"
for methods, pattern, scope in _PAT_SCOPED_ROUTE_RULES:
if method in methods and pattern.match(normalized):
return scope
return None
@functools.cache @functools.cache

View File

@ -6,7 +6,7 @@ from app.gateway.auth.models import User
class LastAdminRemainsError(RuntimeError): class LastAdminRemainsError(RuntimeError):
"""Raised when a role write would demote the last remaining active admin. """Raised when a role write would demote the last remaining admin.
Bootstrap lockout protection: raised inside the same serialized Bootstrap lockout protection: raised inside the same serialized
transaction that would perform the write, so the check-then-act window transaction that would perform the write, so the check-then-act window
@ -123,9 +123,8 @@ class UserRepository(ABC):
Raises: Raises:
UserNotFoundError: the target row does not exist. UserNotFoundError: the target row does not exist.
LastAdminRemainsError: the write would demote the only remaining LastAdminRemainsError: the write would demote the only remaining
active admin (the count and the write share one serialized admin (the count and the write share one serialized
transaction — two concurrent demotions cannot both pass). transaction — two concurrent demotions cannot both pass).
An already disabled admin may be assigned a different role.
""" """
raise NotImplementedError raise NotImplementedError
@ -144,9 +143,6 @@ class UserRepository(ABC):
UserNotFoundError: If no row exists for ``user.id``. This is UserNotFoundError: If no row exists for ``user.id``. This is
a hard failure (not a no-op) so callers cannot mistake a a hard failure (not a no-op) so callers cannot mistake a
concurrent-delete race for a successful update. concurrent-delete race for a successful update.
ValueError: If the new email is already registered to another
user, including one that committed after the caller's
pre-check. Nothing is written.
""" """
raise NotImplementedError raise NotImplementedError

View File

@ -316,12 +316,11 @@ class SQLiteUserRepository(UserRepository):
row = await session.get(UserRow, user_id) row = await session.get(UserRow, user_id)
if row is None: if row is None:
raise UserNotFoundError(f"User {user_id} no longer exists") raise UserNotFoundError(f"User {user_id} no longer exists")
if row.system_role == "admin" and not row.disabled and system_role != "admin": if row.system_role == "admin" and system_role != "admin":
# Count ACTIVE admins only: a disabled admin cannot # Count ACTIVE admins only: a disabled admin cannot
# authenticate, so counting them would let "disable B, then # authenticate, so counting them would let "disable B, then
# demote self" (or a combined role+disable request) strand # demote self" (or a combined role+disable request) strand
# the deployment with zero usable management credentials. # the deployment with zero usable management credentials.
# Demoting an already disabled admin removes no active admin.
active_admins = await session.scalar(select(func.count()).select_from(UserRow).where(UserRow.system_role == "admin", UserRow.disabled.is_(False))) active_admins = await session.scalar(select(func.count()).select_from(UserRow).where(UserRow.system_role == "admin", UserRow.disabled.is_(False)))
if active_admins is None or active_admins <= 1: if active_admins is None or active_admins <= 1:
raise LastAdminRemainsError("cannot demote the last remaining admin") raise LastAdminRemainsError("cannot demote the last remaining admin")
@ -406,16 +405,7 @@ class SQLiteUserRepository(UserRepository):
row.oauth_id = user.oauth_id row.oauth_id = user.oauth_id
row.needs_setup = user.needs_setup row.needs_setup = user.needs_setup
row.token_version = user.token_version row.token_version = user.token_version
try:
await session.commit() await session.commit()
except IntegrityError as exc:
# The caller's email pre-check cannot see an insert or update
# of the same address that commits before this one. Report the
# lost race the way create_user does; any other violation
# propagates unchanged.
if _is_email_violation(exc):
raise ValueError(f"Email already registered: {user.email}") from exc
raise
return user return user
async def count_users(self) -> int: async def count_users(self) -> int:

View File

@ -10,7 +10,6 @@ Fine-grained permission checks remain in authz.py decorators.
""" """
import logging import logging
import re
from collections.abc import Callable from collections.abc import Callable
from fastapi import HTTPException, Request, Response from fastapi import HTTPException, Request, Response
@ -30,7 +29,7 @@ from app.gateway.auth_disabled import (
from app.gateway.authz import AuthContext, resolve_route_permissions from app.gateway.authz import AuthContext, resolve_route_permissions
from app.gateway.internal_auth import INTERNAL_AUTH_HEADER_NAME, get_internal_user, is_valid_internal_auth_token from app.gateway.internal_auth import INTERNAL_AUTH_HEADER_NAME, get_internal_user, is_valid_internal_auth_token
from app.gateway.request_path import get_request_route_path from app.gateway.request_path import get_request_route_path
from deerflow.runtime.user_context import bind_authenticated_user, reset_current_user, set_current_user from deerflow.runtime.user_context import reset_current_user, set_current_user
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -61,11 +60,7 @@ _PUBLIC_EXACT_PATHS: frozenset[str] = frozenset(
) )
def _is_public(path: str, method: str = "GET") -> bool: def _is_public(path: str) -> bool:
# A share token grants only these reads. Forks and any future write routes
# under /shares still pass through session authentication and permissions.
if method in {"GET", "HEAD"} and re.fullmatch(r"/api/shares/[A-Za-z0-9_-]{43}(?:/artifacts/.+)?", path):
return True
stripped = path.rstrip("/") stripped = path.rstrip("/")
if stripped in _PUBLIC_EXACT_PATHS: if stripped in _PUBLIC_EXACT_PATHS:
return True return True
@ -96,7 +91,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
super().__init__(app) super().__init__(app)
async def dispatch(self, request: Request, call_next: Callable) -> Response: async def dispatch(self, request: Request, call_next: Callable) -> Response:
if _is_public(get_request_route_path(request), request.method): if _is_public(get_request_route_path(request)):
return await call_next(request) return await call_next(request)
internal_user = None internal_user = None
@ -161,7 +156,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
# Auth-disabled mode is an operator override of all authentication, # Auth-disabled mode is an operator override of all authentication,
# so it stays ahead of the Bearer check (a stray Authorization # so it stays ahead of the Bearer check (a stray Authorization
# header from a proxy must not 401 an E2E sandbox). # header from a proxy must not 401 an E2E sandbox).
from app.gateway.auth.pat import authenticate_pat, is_pat_allowed_route, pat_route_scope from app.gateway.auth.pat import authenticate_pat, is_pat_allowed_route
try: try:
user, pat_scopes = await authenticate_pat(request.app, authorization) user, pat_scopes = await authenticate_pat(request.app, authorization)
@ -176,11 +171,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
status_code=403, status_code=403,
content={"detail": "PAT credentials are not permitted on this route"}, content={"detail": "PAT credentials are not permitted on this route"},
) )
required_scope = pat_route_scope(request.method, get_request_route_path(request))
if required_scope and required_scope not in pat_scopes:
return JSONResponse(status_code=403, content={"detail": f"Permission denied: {required_scope}"})
auth_source = AUTH_SOURCE_PAT auth_source = AUTH_SOURCE_PAT
request.state.pat_scopes = pat_scopes
elif access_token: elif access_token:
# Strict JWT validation: reject junk/expired tokens with 401 # Strict JWT validation: reject junk/expired tokens with 401
# right here instead of silently passing through. This closes # right here instead of silently passing through. This closes
@ -216,14 +207,6 @@ class AuthMiddleware(BaseHTTPMiddleware):
}, },
) )
# Browser extension pages are bound to the account that loaded their
# descriptor. Cookies can change in another tab before React observes it.
# This is a stale-view fence, not an authorization grant; CLI callers may
# omit it and all existing route/resource checks still apply.
expected_viewer = request.headers.get("x-deerflow-plugin-viewer")
if get_request_route_path(request).startswith("/api/extensions/") and expected_viewer is not None and expected_viewer != str(user.id):
return JSONResponse(status_code=409, content={"detail": "Account changed; reload this extension view."})
# Stamp both request.state.user (for the contextvar pattern) # Stamp both request.state.user (for the contextvar pattern)
# and request.state.auth (so @require_permission's "auth is # and request.state.auth (so @require_permission's "auth is
# None" branch short-circuits instead of running the entire # None" branch short-circuits instead of running the entire
@ -243,8 +226,6 @@ class AuthMiddleware(BaseHTTPMiddleware):
request.state.auth = AuthContext(user=user, permissions=permissions) request.state.auth = AuthContext(user=user, permissions=permissions)
token = set_current_user(user) token = set_current_user(user)
try: try:
verified_user_id = str(user.id) if auth_source in {AUTH_SOURCE_SESSION, AUTH_SOURCE_PAT} else None
with bind_authenticated_user(verified_user_id):
return await call_next(request) return await call_next(request)
finally: finally:
reset_current_user(token) reset_current_user(token)

View File

@ -191,10 +191,7 @@ def _get_route_authorization_config() -> AuthorizationConfig:
environments without a config.yaml), preserving legacy all-permissions behavior. environments without a config.yaml), preserving legacy all-permissions behavior.
``get_app_config()`` stats and hashes ``config.yaml`` and ``get_app_config()`` stats and hashes ``config.yaml`` and
``extensions_config.json`` on every call, so async request paths use ``extensions_config.json`` on every call, so async request paths use
:func:`_route_authorization_config_async`, and call the synchronous :func:`_route_authorization_config_async`.
helpers that read it (``resolve_model_authorization``,
``resolve_skill_authorization``, ``authorize_model_use``,
``authorize_sandbox_for_request``) through ``asyncio.to_thread``.
""" """
from deerflow.config.app_config import get_app_config from deerflow.config.app_config import get_app_config
@ -823,7 +820,7 @@ async def try_acquire_sandbox_for_request(
user = await get_optional_user_from_request(request) if request is not None else None user = await get_optional_user_from_request(request) if request is not None else None
if user is not None: if user is not None:
await asyncio.to_thread(authorize_sandbox_for_request, user, is_internal=_is_internal_caller(request, user), app_config=app_config) authorize_sandbox_for_request(user, is_internal=_is_internal_caller(request, user), app_config=app_config)
except SandboxAuthorizationError: except SandboxAuthorizationError:
logger.info("Sandbox sync skipped: sandbox execution not permitted for this caller (thread_id=%s)", thread_id) logger.info("Sandbox sync skipped: sandbox execution not permitted for this caller (thread_id=%s)", thread_id)
return SandboxRequestLease( return SandboxRequestLease(

View File

@ -194,11 +194,6 @@ class LarkAdapter:
class SkillAdapter: class SkillAdapter:
async def list_installations(self, context: AdapterContext) -> list[CapabilityInstallation]: async def list_installations(self, context: AdapterContext) -> list[CapabilityInstallation]:
# The listing reports the enabled flag, which the storage layer fails
# closed on an unreadable extensions config; keep this read surface
# loud about the broken config instead of serving the degraded list.
# Blocking filesystem IO: always off the event loop, like the scan below.
await asyncio.to_thread(skills._assert_extensions_config_readable)
response = await asyncio.to_thread(lambda: skills._get_user_skill_storage(context.config).load_skills(enabled_only=False)) response = await asyncio.to_thread(lambda: skills._get_user_skill_storage(context.config).load_skills(enabled_only=False))
response = await skills._filter_visible_skills(context.request, context.config, response) response = await skills._filter_visible_skills(context.request, context.config, response)
return [ return [

View File

@ -2,64 +2,22 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import logging
from collections.abc import Sequence from collections.abc import Sequence
from itertools import count
from typing import Any from typing import Any
from fastapi import HTTPException
from app.gateway.utils import sanitize_log_param
logger = logging.getLogger(__name__)
_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS = 30
_REPLAY_LINEAGE_TIMEOUT_DETAIL = "Timed out resolving the checkpoint before the target user message"
def task_interrupts_by_id(snapshot: Any) -> dict[str, list[Any]]:
"""Group non-empty task interrupts of one snapshot by task id."""
grouped: dict[str, list[Any]] = {}
for task in getattr(snapshot, "tasks", None) or ():
interrupts = list(getattr(task, "interrupts", ()) or ())
if interrupts:
grouped[task.id] = interrupts
return grouped
def is_hitl_approval_payload(value: Any) -> bool:
"""Whether an interrupt payload is a HITL tool-approval request."""
return isinstance(value, dict) and value.get("kind") == "hitl_approval"
def hitl_approval_payloads(grouped: dict[str, list[Any]]) -> list[dict[str, Any]]:
"""Flatten approval payloads from task_interrupts_by_id output."""
return [interrupt.value for interrupts in grouped.values() for interrupt in interrupts if is_hitl_approval_payload(interrupt.value)]
class CheckpointLineageError(RuntimeError): class CheckpointLineageError(RuntimeError):
"""Raised when a requested checkpoint ancestor cannot be resolved safely.""" """Raised when a requested checkpoint ancestor cannot be resolved safely."""
class CheckpointParentMissingError(CheckpointLineageError): class CheckpointParentMissingError(CheckpointLineageError):
"""Raised when a legacy checkpoint head does not record a parent link.""" """Raised when a legacy checkpoint does not record its parent link."""
class CheckpointLineageIntegrityError(CheckpointLineageError): class CheckpointLineageIntegrityError(CheckpointLineageError):
"""Raised when recorded checkpoint lineage is present but unsafe to use.""" """Raised when recorded checkpoint lineage is present but unsafe to use."""
class CheckpointLineageTimeoutError(CheckpointLineageError):
"""Raised when the replay lineage lookup exceeds its own deadline."""
def replay_lineage_timeout_http_error(thread_id: str, exc: CheckpointLineageTimeoutError) -> HTTPException:
"""Log a replay lookup deadline expiry and return its fixed client error."""
logger.warning("Replay checkpoint lookup timed out for thread %s", sanitize_log_param(thread_id), exc_info=exc)
return HTTPException(status_code=504, detail=_REPLAY_LINEAGE_TIMEOUT_DETAIL)
def checkpoint_messages(checkpoint_tuple: Any) -> list[Any]: def checkpoint_messages(checkpoint_tuple: Any) -> list[Any]:
values = getattr(checkpoint_tuple, "values", None) values = getattr(checkpoint_tuple, "values", None)
if isinstance(values, dict): if isinstance(values, dict):
@ -98,21 +56,6 @@ def _has_postgres_stamps(metadata: dict[str, Any]) -> bool:
return "run_durations" in metadata or "run_message_ids" in metadata return "run_durations" in metadata or "run_message_ids" in metadata
def channel_versions_match(
versions: dict[str, Any] | None,
parent_versions: dict[str, Any] | None,
) -> bool:
"""Whether two checkpoint version maps match channel-for-channel.
LangGraph versions are scoped to their channels, not globally unique.
Comparing only the values can mistake a state-changing checkpoint for a
metadata-only copy when two channels exchange their versions.
"""
# Empty maps are equal too; markerless inference applies its own non-empty guard.
return isinstance(versions, dict) and isinstance(parent_versions, dict) and versions == parent_versions
def is_duration_only_checkpoint(checkpoint_tuple: Any, *, parent: Any | None = None, stamp_fallback: bool = True, versions: dict[str, Any] | None = None, parent_versions: dict[str, Any] | None = None) -> bool: def is_duration_only_checkpoint(checkpoint_tuple: Any, *, parent: Any | None = None, stamp_fallback: bool = True, versions: dict[str, Any] | None = None, parent_versions: dict[str, Any] | None = None) -> bool:
"""Return whether the tuple is a metadata-only run-duration checkpoint. """Return whether the tuple is a metadata-only run-duration checkpoint.
@ -305,7 +248,7 @@ def _copies_parent_verbatim(checkpoint_tuple: Any, parent: Any, *, versions: dic
parent_versions = parent_versions if isinstance(parent_versions, dict) else _snapshot_versions(parent) parent_versions = parent_versions if isinstance(parent_versions, dict) else _snapshot_versions(parent)
if not isinstance(versions, dict) or not isinstance(parent_versions, dict) or not versions: if not isinstance(versions, dict) or not isinstance(parent_versions, dict) or not versions:
return False return False
return channel_versions_match(versions, parent_versions) return frozenset(versions.values()) == frozenset(parent_versions.values())
def history_parent_index(checkpoints: Sequence[Any]) -> dict[tuple[str, str], Any]: def history_parent_index(checkpoints: Sequence[Any]) -> dict[tuple[str, str], Any]:
@ -364,8 +307,6 @@ def _message_id(message: Any) -> str | None:
def _config_identity(config: dict[str, Any]) -> tuple[str, str, str] | None: def _config_identity(config: dict[str, Any]) -> tuple[str, str, str] | None:
configurable = config.get("configurable", {}) configurable = config.get("configurable", {})
if not isinstance(configurable, dict):
return None
thread_id = configurable.get("thread_id") thread_id = configurable.get("thread_id")
checkpoint_ns = configurable.get("checkpoint_ns", "") checkpoint_ns = configurable.get("checkpoint_ns", "")
checkpoint_id = configurable.get("checkpoint_id") checkpoint_id = configurable.get("checkpoint_id")
@ -396,28 +337,12 @@ def _checkpoint_exists(checkpoint_tuple: Any) -> bool:
return isinstance(getattr(checkpoint_tuple, "checkpoint", None), dict) return isinstance(getattr(checkpoint_tuple, "checkpoint", None), dict)
async def find_replay_checkpoint_before_message(
accessor: Any,
head_checkpoint: Any,
message_id: str,
) -> Any:
"""Resolve the replay base for branching, regeneration, or edit replay."""
deadline = asyncio.timeout(_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS)
try:
async with deadline:
return await find_checkpoint_before_message(accessor, head_checkpoint, message_id, max_depth=None)
except TimeoutError as exc:
if not deadline.expired():
raise # The checkpoint store raised its own timeout.
raise CheckpointLineageTimeoutError(_REPLAY_LINEAGE_TIMEOUT_DETAIL) from exc
async def find_checkpoint_before_message( async def find_checkpoint_before_message(
accessor: Any, accessor: Any,
head_checkpoint: Any, head_checkpoint: Any,
message_id: str, message_id: str,
*, *,
max_depth: int | None, max_depth: int,
) -> Any: ) -> Any:
"""Walk one parent lineage and return the first checkpoint before ``message_id``. """Walk one parent lineage and return the first checkpoint before ``message_id``.
@ -426,7 +351,6 @@ async def find_checkpoint_before_message(
a checkpoint from the wrong branch. Duration-only metadata checkpoints do not a checkpoint from the wrong branch. Duration-only metadata checkpoints do not
represent an addressable conversation state and are skipped, and so are represent an addressable conversation state and are skipped, and so are
checkpoints that still have pending tasks (see :func:`has_pending_tasks`). checkpoints that still have pending tasks (see :func:`has_pending_tasks`).
With ``max_depth=None``, the caller must bound the lookup with a deadline.
""" """
if message_id not in {_message_id(message) for message in checkpoint_messages(head_checkpoint)}: if message_id not in {_message_id(message) for message in checkpoint_messages(head_checkpoint)}:
@ -438,9 +362,13 @@ async def find_checkpoint_before_message(
if current_identity is not None: if current_identity is not None:
visited.add(current_identity) visited.add(current_identity)
# A Postgres stamp candidate may read its grandparent for the shape # Each distinct ancestor is read once: a Postgres stamp candidate also
# check. That snapshot is the next iteration's parent, so keep the last # needs its grandparent for the shape check, and a candidate the shape
# read only. A long walk does not need to retain every materialized state. # check refuses re-reads that grandparent as the next iteration's parent,
# so reads are memoized by config identity instead of carried by hand.
# Normal branch/regenerate histories cross the target boundary within
# 1–3 reads. Keep max_depth as a conservative safety cap for valid
# histories with many intermediate or duration-only checkpoints.
read_cache: dict[tuple[str, str, str], Any] = {} read_cache: dict[tuple[str, str, str], Any] = {}
async def read(config: dict[str, Any]) -> Any: async def read(config: dict[str, Any]) -> Any:
@ -449,26 +377,20 @@ async def find_checkpoint_before_message(
return read_cache[identity] return read_cache[identity]
checkpoint_tuple = await accessor.aget(config) checkpoint_tuple = await accessor.aget(config)
if identity is not None: if identity is not None:
read_cache.clear()
read_cache[identity] = checkpoint_tuple read_cache[identity] = checkpoint_tuple
return checkpoint_tuple return checkpoint_tuple
depths = count() if max_depth is None else range(max_depth) for _ in range(max_depth):
for depth in depths:
if max_depth is None and depth % 64 == 0:
# In-memory reads can finish inline. Yield so the deadline can fire.
await asyncio.sleep(0)
parent_config = getattr(current, "parent_config", None) parent_config = getattr(current, "parent_config", None)
if parent_config is None: if not isinstance(parent_config, dict):
if depth == 0: raise CheckpointParentMissingError("Checkpoint lineage ended before the target message")
raise CheckpointParentMissingError("Checkpoint head has no recorded parent link")
raise CheckpointLineageIntegrityError("Checkpoint lineage ended before the target message")
if not isinstance(parent_config, dict) or (parent_identity := _config_identity(parent_config)) is None:
raise CheckpointLineageIntegrityError("Checkpoint parent link is not addressable")
parent = await read(parent_config) parent = await read(parent_config)
if _checkpoint_identity(parent) != parent_identity or not _checkpoint_exists(parent): parent_identity = _checkpoint_identity(parent)
requested_parent_identity = _config_identity(parent_config)
if parent_identity is None or not _checkpoint_exists(parent) or (requested_parent_identity is not None and parent_identity != requested_parent_identity):
raise CheckpointLineageIntegrityError("Checkpoint parent link is not addressable") raise CheckpointLineageIntegrityError("Checkpoint parent link is not addressable")
if parent_identity is not None:
if parent_identity in visited: if parent_identity in visited:
raise CheckpointLineageIntegrityError("Checkpoint lineage contains a cycle") raise CheckpointLineageIntegrityError("Checkpoint lineage contains a cycle")
visited.add(parent_identity) visited.add(parent_identity)

View File

@ -1,23 +0,0 @@
"""Map checkpoint-mode guard failures to precise HTTP statuses.
A mismatch means the thread's persisted checkpoints conflict with the process's
frozen mode (operator-actionable, 409); a reconfiguration means the process
itself is mid mode-flip (transient, 503). Both must surface their message — a
generic 500 would force operators to grep logs to discover the root cause after
a mode flip.
"""
from __future__ import annotations
from fastapi import HTTPException
from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError, CheckpointModeReconfigurationError
CHECKPOINT_MODE_ERRORS = (CheckpointModeMismatchError, CheckpointModeReconfigurationError)
def checkpoint_mode_http_error(exc: Exception, thread_id: str) -> HTTPException:
"""Return the HTTP error for a checkpoint-mode guard failure."""
if isinstance(exc, CheckpointModeMismatchError):
return HTTPException(status_code=409, detail=f"Thread {thread_id}: {exc}")
return HTTPException(status_code=503, detail=str(exc))

View File

@ -53,7 +53,6 @@ from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from app.gateway.checkpoint_lineage import ( from app.gateway.checkpoint_lineage import (
channel_versions_match,
checkpoint_configurable, checkpoint_configurable,
is_duration_only_checkpoint, is_duration_only_checkpoint,
) )
@ -106,7 +105,7 @@ class _Node:
duration_only: bool duration_only: bool
metadata_source: str | None = None metadata_source: str | None = None
carries_run_durations: bool = False carries_run_durations: bool = False
versions: dict[str, Any] = field(default_factory=dict) versions: frozenset = frozenset()
def _thread_config(thread_id: str) -> dict[str, Any]: def _thread_config(thread_id: str) -> dict[str, Any]:
@ -157,8 +156,7 @@ def _mark_duration_leaves_without_the_marker(nodes: dict[tuple[str, str], _Node]
parent = nodes.get((node.parent_ns, node.parent_id)) parent = nodes.get((node.parent_ns, node.parent_id))
if parent is None or node.metadata_source != "update" or not node.carries_run_durations: if parent is None or node.metadata_source != "update" or not node.carries_run_durations:
continue continue
# Without the authoritative writes marker, require a non-empty map as evidence. if node.versions and node.versions == parent.versions:
if node.versions and parent.versions and channel_versions_match(node.versions, parent.versions):
node.duration_only = True node.duration_only = True
@ -454,7 +452,7 @@ async def enforce_thread_retention(
duration_only=is_duration_only_checkpoint(tuple_, stamp_fallback=False), duration_only=is_duration_only_checkpoint(tuple_, stamp_fallback=False),
metadata_source=metadata.get("source"), metadata_source=metadata.get("source"),
carries_run_durations=isinstance(run_durations, dict) and bool(run_durations), carries_run_durations=isinstance(run_durations, dict) and bool(run_durations),
versions=dict(channel_versions) if isinstance(channel_versions, dict) else {}, versions=frozenset(channel_versions.values()) if isinstance(channel_versions, dict) else frozenset(),
) )
if not nodes: if not nodes:
# Nothing to classify: an empty (or unknown) thread is a no-op, but # Nothing to classify: an empty (or unknown) thread is a no-op, but
@ -540,7 +538,7 @@ async def enforce_thread_retention(
survivor_versions: set[Any] = set() survivor_versions: set[Any] = set()
for key, node in nodes.items(): for key, node in nodes.items():
if key not in deleted_keys: if key not in deleted_keys:
survivor_versions.update(node.versions.values()) survivor_versions.update(node.versions)
# Invalidate before touching source-of-truth rows. If cache deletion # Invalidate before touching source-of-truth rows. If cache deletion
# fails, fail closed with every checkpoint intact; doing this after the # fails, fail closed with every checkpoint intact; doing this after the
@ -605,7 +603,7 @@ async def enforce_trailing_duration_retention(
latest_versions = latest.checkpoint.get("channel_versions") latest_versions = latest.checkpoint.get("channel_versions")
parent_versions = parent.checkpoint.get("channel_versions") parent_versions = parent.checkpoint.get("channel_versions")
if not channel_versions_match(latest_versions, parent_versions): if not isinstance(latest_versions, dict) or latest_versions != parent_versions:
return report return report
metadata = latest.metadata or {} metadata = latest.metadata or {}
run_durations = metadata.get("run_durations") run_durations = metadata.get("run_durations")
@ -617,9 +615,9 @@ async def enforce_trailing_duration_retention(
duration_only=is_duration_only_checkpoint(latest), duration_only=is_duration_only_checkpoint(latest),
metadata_source=metadata.get("source"), metadata_source=metadata.get("source"),
carries_run_durations=isinstance(run_durations, dict) and bool(run_durations), carries_run_durations=isinstance(run_durations, dict) and bool(run_durations),
versions=dict(latest_versions), versions=frozenset(latest_versions.values()),
) )
parent_node = _Node(ns="", cp_id=parent_id, parent_ns=None, parent_id=None, duration_only=False, versions=dict(parent_versions)) parent_node = _Node(ns="", cp_id=parent_id, parent_ns=None, parent_id=None, duration_only=False, versions=latest_node.versions)
_mark_duration_leaves_without_the_marker({("", latest_id): latest_node, ("", parent_id): parent_node}) _mark_duration_leaves_without_the_marker({("", latest_id): latest_node, ("", parent_id): parent_node})
if not latest_node.duration_only or await _checkpoint_has_writes(storage, ("", latest_id), thread_id): if not latest_node.duration_only or await _checkpoint_has_writes(storage, ("", latest_id), thread_id):
return report return report

View File

@ -66,10 +66,7 @@ def build_context_usage_payload(*, token_count: int, max_context_tokens: int | N
async def build_context_usage(request: Request, thread_id: str, run_store: Any, user_id: str | None = None) -> dict[str, Any] | None: async def build_context_usage(request: Request, thread_id: str, run_store: Any, user_id: str | None = None) -> dict[str, Any] | None:
"""Return approximate usage for the latest materialized thread checkpoint.""" """Return approximate usage for the latest materialized thread checkpoint."""
try: try:
# ``get_config`` revalidates ``config.yaml`` and app_config = get_config()
# ``extensions_config.json`` on every call (stat + full-file hash), so
# reading it here would put that IO on the loop every thread view pays.
app_config = await asyncio.to_thread(get_config)
except HTTPException: except HTTPException:
return None return None

View File

@ -5,14 +5,13 @@ from __future__ import annotations
import json import json
import logging import logging
import re import re
from collections.abc import Awaitable, Callable, Mapping from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit from urllib.parse import urlsplit
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
from app.gateway.conversation_reader import read_visible_message_page from app.gateway.conversation_reader import read_visible_message_page
from app.gateway.csrf_middleware import _normalize_origin, _request_origin
from deerflow.constants import CONVERSATION_TOOL_NAME, CONVERSATION_TOOL_USE from deerflow.constants import CONVERSATION_TOOL_NAME, CONVERSATION_TOOL_USE
from deerflow.utils.llm_text import strip_think_blocks from deerflow.utils.llm_text import strip_think_blocks
from deerflow.utils.thread_id import validate_thread_id from deerflow.utils.thread_id import validate_thread_id
@ -44,20 +43,13 @@ _BUDGET_TOO_SMALL = {
} }
def _source_id(reference: str, request_origin: str | None) -> str: def _source_id(reference: str, request_url: str) -> str:
"""URLs are local selectors on this DeerFlow's host, never network fetch targets. """URLs are same-origin local selectors, never network fetch targets."""
*request_origin* is the origin the client addressed, as the CSRF check
resolves it (forwarded host and port included). Only the host and port are
compared, not the scheme: behind a TLS proxy Gateway can see ``http`` for a
browser's ``https`` link, because uvicorn ignores ``X-Forwarded-Proto``
from an untrusted peer and a local nginx resends its own scheme.
"""
if "://" not in reference: if "://" not in reference:
return validate_thread_id(reference) return validate_thread_id(reference)
parsed = urlsplit(reference) parsed = urlsplit(reference)
origin = _normalize_origin(f"{parsed.scheme}://{parsed.netloc}") origin = urlsplit(request_url)
if origin is None or request_origin is None or urlsplit(origin).netloc != urlsplit(request_origin).netloc or parsed.query or parsed.fragment: if parsed.scheme not in {"http", "https"} or (parsed.scheme, parsed.netloc) != (origin.scheme, origin.netloc) or parsed.query or parsed.fragment:
raise ValueError("Use a thread ID or a conversation URL from this DeerFlow origin") raise ValueError("Use a thread ID or a conversation URL from this DeerFlow origin")
match = re.fullmatch(r"/workspace/(?:agents/[^/]+/)?chats/([^/]+)", parsed.path) match = re.fullmatch(r"/workspace/(?:agents/[^/]+/)?chats/([^/]+)", parsed.path)
if match is None: if match is None:
@ -65,39 +57,16 @@ def _source_id(reference: str, request_origin: str | None) -> str:
return validate_thread_id(match.group(1)) return validate_thread_id(match.group(1))
def _visible_text(row: dict, *, thread_id: str | None = None) -> tuple[str, str] | None: def _visible_text(row: dict) -> tuple[str, str] | None:
message = row.get("content") message = row.get("content")
if not isinstance(message, Mapping): if not isinstance(message, dict):
return None return None
role = message.get("type") or message.get("role") role = message.get("type") or message.get("role")
if not isinstance(role, str):
return None
role = {"human": "user", "ai": "assistant"}.get(role, role) role = {"human": "user", "ai": "assistant"}.get(role, role)
extra = message.get("additional_kwargs") extra = message.get("additional_kwargs") or {}
if extra is None:
extra = {}
elif not isinstance(extra, Mapping):
logger.warning(
"Ignoring malformed message additional_kwargs for thread %s at row seq %s: expected a mapping, got %s",
thread_id or "<unknown>",
row.get("seq", "<unknown>"),
type(extra).__name__,
)
extra = {}
if role not in {"user", "assistant"} or extra.get("hide_from_ui") or message.get("name") == "summary": if role not in {"user", "assistant"} or extra.get("hide_from_ui") or message.get("name") == "summary":
return None return None
metadata = row.get("metadata") if str((row.get("metadata") or {}).get("caller", "")).startswith(("middleware:", "subagent:")):
if metadata is None:
metadata = {}
elif not isinstance(metadata, Mapping):
logger.warning(
"Ignoring malformed conversation metadata for thread %s at row seq %s: expected a mapping, got %s",
thread_id or "<unknown>",
row.get("seq", "<unknown>"),
type(metadata).__name__,
)
metadata = {}
if str(metadata.get("caller", "")).startswith(("middleware:", "subagent:")):
return None return None
content = message.get("content") content = message.get("content")
if role == "user" and isinstance(extra.get("original_user_content"), str): if role == "user" and isinstance(extra.get("original_user_content"), str):
@ -189,8 +158,7 @@ def prepare_conversation_reader(
if auth is None or not auth.is_authenticated or not auth.has_permission("runs", "read") or not user_id: if auth is None or not auth.is_authenticated or not auth.has_permission("runs", "read") or not user_id:
raise HTTPException(status_code=403, detail="Permission denied: runs:read") raise HTTPException(status_code=403, detail="Permission denied: runs:read")
try: try:
request_origin = _request_origin(request) ids = tuple(dict.fromkeys(_source_id(reference, str(request.url)) for reference in references))
ids = tuple(dict.fromkeys(_source_id(reference, request_origin) for reference in references))
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc raise HTTPException(status_code=422, detail=str(exc)) from exc
return _prepare_owner_bound_conversation_reader(ids, user_id=user_id, run_context=run_context, run_manager=run_manager, app_config=app_config) return _prepare_owner_bound_conversation_reader(ids, user_id=user_id, run_context=run_context, run_manager=run_manager, app_config=app_config)
@ -260,7 +228,7 @@ def _prepare_owner_bound_conversation_reader(
found: dict[int, tuple[str, str, int]] = {} found: dict[int, tuple[str, str, int]] = {}
def include_target(row: dict) -> bool: def include_target(row: dict) -> bool:
parsed = _visible_text(row, thread_id=thread_id) if row["seq"] == message_seq else None parsed = _visible_text(row) if row["seq"] == message_seq else None
if parsed is None: if parsed is None:
return False return False
role, text = parsed role, text = parsed
@ -305,7 +273,7 @@ def _prepare_owner_bound_conversation_reader(
parsed_text: dict[int, tuple[str, str]] = {} parsed_text: dict[int, tuple[str, str]] = {}
def include_message(row: dict) -> bool: def include_message(row: dict) -> bool:
parsed = _visible_text(row, thread_id=thread_id) parsed = _visible_text(row)
if parsed is None: if parsed is None:
return False return False
role, text = parsed role, text = parsed

View File

@ -8,7 +8,7 @@ access from a model argument or an ambient HTTP request.
from __future__ import annotations from __future__ import annotations
import logging import logging
from collections.abc import Callable, Mapping from collections.abc import Callable
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
if TYPE_CHECKING: if TYPE_CHECKING:
@ -70,19 +70,8 @@ def _message_type(message: Any) -> str | None:
return str(value) if value else None return str(value) if value else None
def _is_thread_history_hidden_message_row(row: dict[str, Any], *, thread_id: str | None = None) -> bool: def _is_thread_history_hidden_message_row(row: dict[str, Any]) -> bool:
metadata = row.get("metadata") caller = str((row.get("metadata") or {}).get("caller", ""))
if metadata is None:
metadata = {}
elif not isinstance(metadata, Mapping):
logger.warning(
"Ignoring malformed conversation metadata for thread %s at row seq %s: expected a mapping, got %s",
thread_id or "<unknown>",
row.get("seq", "<unknown>"),
type(metadata).__name__,
)
metadata = {}
caller = str(metadata.get("caller", ""))
return caller.startswith("middleware:") or (caller.startswith("subagent:") and _message_type(row.get("content")) == "ai") return caller.startswith("middleware:") or (caller.startswith("subagent:") and _message_type(row.get("content")) == "ai")
@ -121,7 +110,7 @@ async def scan_visible_thread_messages(
if before_seq is not None and row["seq"] >= before_seq: if before_seq is not None and row["seq"] >= before_seq:
reached_before_bound = True reached_before_bound = True
break break
if (not include_middleware and _is_thread_history_hidden_message_row(row, thread_id=thread_id)) or row.get("run_id") in hidden_run_ids or (message_filter is not None and not message_filter(row)): if (not include_middleware and _is_thread_history_hidden_message_row(row)) or row.get("run_id") in hidden_run_ids or (message_filter is not None and not message_filter(row)):
continue continue
visible.append(row) visible.append(row)
if len(visible) == needed: if len(visible) == needed:
@ -148,7 +137,7 @@ async def scan_visible_thread_messages(
break break
_validate_message_scan_rows(raw, thread_id=thread_id, scan_before=scan_before, scan_after=None) _validate_message_scan_rows(raw, thread_id=thread_id, scan_before=scan_before, scan_after=None)
for row in reversed(raw): for row in reversed(raw):
if (not include_middleware and _is_thread_history_hidden_message_row(row, thread_id=thread_id)) or row.get("run_id") in hidden_run_ids or (message_filter is not None and not message_filter(row)): if (not include_middleware and _is_thread_history_hidden_message_row(row)) or row.get("run_id") in hidden_run_ids or (message_filter is not None and not message_filter(row)):
continue continue
visible_desc.append(row) visible_desc.append(row)
if len(visible_desc) == needed: if len(visible_desc) == needed:

View File

@ -1,410 +0,0 @@
"""Gateway execution of durable coordination tasks using caller-bound AgentRuns."""
import asyncio
import logging
from hashlib import sha256
from time import time
from uuid import uuid4
from deerflow_extension_api.agent_runs import AgentRunError
from fastapi import HTTPException
from app.channels.connection_identity import feishu_private_binding
from app.gateway.deps import get_agent_runs
from deerflow.persistence.coordination.model import TaskStatus
from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound
from deerflow.persistence.coordination.workers import THREAD_PREFIX, WORKER_CHECKPOINT_RUN, WORKER_SHUTDOWN
from deerflow.runtime.runs.manager import LEASE_ORPHAN_RECOVERY_ERROR, ORPHAN_RECOVERY_STOP_REASON, STARTUP_ORPHAN_RECOVERY_ERROR
logger = logging.getLogger(__name__)
CANCEL_RESPONSE_TIMEOUT = 5
RECOVERY_INTERVAL = 10
GRANT_LIFETIME = 24 * 60 * 60
WORKER_RUN_PERMISSIONS = frozenset({"runs:create", "runs:read", "threads:read", "threads:write"})
WORKER_CANCEL_PERMISSIONS = frozenset({"runs:read", "runs:cancel"})
WORKER_PERMISSIONS = WORKER_RUN_PERMISSIONS | WORKER_CANCEL_PERMISSIONS
class CoordinationWorkers:
def __init__(self, repository, host, connections=None):
self.repo = repository
self._host = host
self._connections = connections
self._drivers = {}
self._wakeups = set()
self._cancellations = {}
self._recovery = None
self._recovery_wakeup = asyncio.Event()
def start_recovery(self):
self._recovery = asyncio.create_task(self._recover())
async def close(self):
jobs = [*self._drivers.values(), *self._cancellations.values()]
if self._recovery is not None:
jobs.append(self._recovery)
for job in jobs:
job.cancel()
await asyncio.gather(*jobs, return_exceptions=True)
@staticmethod
def _new_grant(authority, *, channel=None):
if authority is None:
raise AgentRunError(403, "A task requires restorable run authorization")
return {
"id": uuid4().hex,
"authority": {**authority, "permissions": sorted(WORKER_PERMISSIONS.intersection(authority["permissions"]))},
"channel": channel,
"expires_at": time() + GRANT_LIFETIME,
}
async def dispatch(self, runs, owner, task_id, assistant_id, *, channel=None, background=False):
grant = self._new_grant(runs.capture_authority(), channel=channel)
turn = await self.repo.prepare(owner, task_id, assistant_id, initial_grant=grant)
if turn is not None and background:
self._recovery_wakeup.set()
elif turn is not None:
authorized, grant_id = await self.authority(owner, task_id)
await self._admit(authorized, owner, task_id, turn, grant_id)
self.watch(authorized, owner, task_id, grant_id)
return await self.view(owner, task_id)
async def dispatch_bound_channel(self, message, *, request_id, objective, assistant_id="lead_agent", notify_completion=False):
"""Entry point for a Gateway-side adapter after provider authentication."""
from app.gateway.auth_disabled import AUTH_SOURCE_SESSION
from app.gateway.authz import resolve_route_permissions
if self._connections is None or self._host.load_user is None or not message.connection_id or not message.owner_user_id or not message.user_id:
raise AgentRunError(403, "A bound messaging identity is required")
connection = await self._connections.find_connection_by_external_identity(
provider=message.channel_name,
external_account_id=message.user_id,
workspace_id=message.workspace_id or None,
)
owner = message.owner_user_id
if connection is None or connection["id"] != message.connection_id or connection["owner_user_id"] != owner:
raise AgentRunError(403, "The messaging identity is no longer bound")
origin = None
if notify_completion:
origin = feishu_private_binding(connection)
if origin is None or message.metadata.get("chat_type") != "p2p" or origin["chat_id"] != message.chat_id:
raise AgentRunError(403, "Tasks require a connected Feishu private chat")
user = await self._host.load_user(owner)
if user is None or user.disabled or user.needs_setup:
raise AgentRunError(403, "The task owner is unavailable")
permissions = WORKER_PERMISSIONS.intersection(await resolve_route_permissions(user, is_internal=False))
if not WORKER_RUN_PERMISSIONS.issubset(permissions):
raise AgentRunError(403, "Permission denied to run a managed task")
snapshot = {"token_version": user.token_version, "source": AUTH_SOURCE_SESSION, "permissions": sorted(permissions)}
runs = await self._host.restore_delegated_authority(user_id=owner, grant=snapshot)
request_key = sha256(f"{connection['id']}:{request_id}".encode()).hexdigest()
task = await self.repo.create(owner, request_id=f"im:{request_key}", objective=objective, coordinator=notify_completion, channel_origin=origin)
return await self.dispatch(runs, owner, task["id"], assistant_id, channel={"id": connection["id"], "updated_at": connection["updated_at"]}, background=notify_completion)
async def authority(self, owner, task_id, *, cancelling=False):
grant = await self.repo.grant(owner, task_id)
if grant is None:
raise AgentRunError(403, "Task requires authorization")
async def validate():
current = await self.repo.grant(owner, task_id)
if current is None or current["id"] != grant["id"]:
raise AgentRunError(403, "Task authorization was revoked")
runs = await self._host.restore_delegated_authority(
user_id=owner,
grant=grant["authority"],
validator=validate,
plugin_namespace="native-coordination",
required_permissions=WORKER_CANCEL_PERMISSIONS if cancelling else WORKER_RUN_PERMISSIONS,
)
return runs, grant["id"]
async def authorize(self, runs, owner, task_id):
await self.repo.set_grant(owner, task_id, self._new_grant(runs.capture_authority()))
return await self.view(owner, task_id)
async def submit_input(self, owner, task_id, *, request_id, content):
receipt = await self.repo.replay_input(owner, task_id, request_id=request_id, content=content)
if receipt is not None:
return receipt
runs, grant_id = await self.authority(owner, task_id)
receipt = await self.repo.append_input(owner, task_id, request_id=request_id, content=content)
self.watch(runs, owner, task_id, grant_id)
return receipt
async def submit_task_decision(self, owner, task_id, execution_id, run_id, grant_id, tasks):
_, current_grant_id = await self.authority(owner, task_id)
if grant_id != current_grant_id:
raise AgentRunError(403, "Coordinator authorization is no longer current")
task_ids = await self.repo.submit_task_decision(owner, task_id, execution_id, run_id, grant_id, tasks)
self._recovery_wakeup.set()
return task_ids
async def view(self, owner, task_id):
view = await self.repo.view(owner, task_id)
required = False
status = view["task"]["status"]
if status in (TaskStatus.QUEUED, TaskStatus.RUNNING, TaskStatus.CANCELLING):
try:
await self.authority(owner, task_id, cancelling=status == TaskStatus.CANCELLING)
except AgentRunError as exc:
if exc.status_code != 403:
raise
required = True
return {**view, "authorization_required": required}
async def recover_once(self):
after = ""
while page := await self.repo.recovery_page(after):
for task_id, owner, status, epoch in page:
key = (owner, task_id)
jobs = self._cancellations if status == TaskStatus.CANCELLING else self._drivers
if (job := jobs.get(key)) is not None and not job.done():
continue
try:
runs, grant_id = await self.authority(owner, task_id, cancelling=status == TaskStatus.CANCELLING)
except AgentRunError as exc:
if exc.status_code != 403:
raise
continue
if status == TaskStatus.CANCELLING:
self._cancel_job(runs, owner, task_id, epoch)
else:
self.watch(runs, owner, task_id, grant_id)
after = page[-1][0]
async def _recover(self):
while True:
self._recovery_wakeup.clear()
try:
await self.recover_once()
except Exception:
logger.exception("Coordination recovery scan failed")
try:
await asyncio.wait_for(self._recovery_wakeup.wait(), timeout=RECOVERY_INTERVAL)
except TimeoutError:
pass
async def _admit(self, runs, owner, task_id, turn, grant_id):
worker, execution, project = turn
thread = worker["thread_id"]
if execution["run_id"] is None:
try:
await runs.create_thread(thread_id=thread, assistant_id=worker["assistant_id"], project_id=project)
admitted = await runs.start_coordination_worker(task_id=task_id, execution_id=execution["id"], grant_id=grant_id)
return admitted.run_id
except AgentRunError as exc:
if exc.status_code in (400, 404, 422):
await self.repo.settle(owner, task_id, execution["id"], None, "admission_failed", [])
raise
return execution["run_id"]
def watch(self, runs, owner, task_id, grant_id):
key = (owner, task_id)
if (existing := self._drivers.get(key)) is not None and not existing.done():
self._wakeups.add(key)
return existing
async def drive():
delay = 1
while True:
self._wakeups.discard(key)
try:
await self._drive(runs, owner, task_id, grant_id)
except AgentRunError as exc:
if exc.status_code < 500:
raise
await asyncio.sleep(delay)
delay = min(30, delay * 2)
continue
if key not in self._wakeups:
return
task = asyncio.create_task(drive())
self._drivers[key] = task
def finished(job):
if self._drivers.get(key) is job:
self._drivers.pop(key)
self._wakeups.discard(key)
if not job.cancelled() and (error := job.exception()) is not None:
logger.warning("Coordination worker observation stopped for task %s (%s)", task_id, type(error).__name__)
task.add_done_callback(finished)
return task
async def _drive(self, runs, owner, task_id, grant_id):
while (turn := await self.repo.prepare(owner, task_id)) is not None:
worker, execution, _project = turn
if execution["status"] == "waiting_for_input":
return
if execution["run_id"] is None:
await self._admit(runs, owner, task_id, turn, grant_id)
continue
thread = worker["thread_id"]
try:
run = await runs.wait_coordination_worker(thread_id=thread, run_id=execution["run_id"], timeout=60)
except TimeoutError:
continue
artifacts = []
result_text = None
status = run.status
restart = run.stop_reason == WORKER_SHUTDOWN or (run.stop_reason == ORPHAN_RECOVERY_STOP_REASON and run.error in (STARTUP_ORPHAN_RECOVERY_ERROR, LEASE_ORPHAN_RECOVERY_ERROR))
if "expected_revision" in execution["frozen_input"]:
if restart and await self.repo.recover_checkpoint(owner, task_id, execution["id"], run.run_id, None):
continue
elif restart:
state = await runs.coordination_recovery_checkpoint(thread_id=thread, run_id=run.run_id)
if state and state.get("checkpoint_id") and state.get("metadata", {}).get(WORKER_CHECKPOINT_RUN) == run.run_id and state.get("next"):
if any(task.get("interrupts") for task in state.get("tasks", [])):
status = "waiting_for_input"
else:
await self.repo.recover_checkpoint(owner, task_id, execution["id"], run.run_id, state["checkpoint_id"])
continue
elif status == "success" and not run.stop_reason:
try:
artifacts = await runs.coordination_artifacts(thread_id=thread, run_id=run.run_id)
if execution["frozen_input"].get("collect_result"):
result_text = await runs.coordination_result_text(thread_id=thread, run_id=run.run_id)
except AgentRunError as exc:
if exc.status_code >= 500:
raise
status = "delivery_failed"
elif status == "success":
status = "stopped"
if not await self.repo.settle(owner, task_id, execution["id"], run.run_id, status, artifacts, result_text=result_text):
return # The Coordinator's children are still running.
if "expected_revision" in execution["frozen_input"] or execution["frozen_input"].get("collect_result"):
self._recovery_wakeup.set()
async def cancel(self, runs, owner, task_id, revision):
task = await self.repo.request_cancel(owner, task_id, expected_revision=revision)
if task["status"] == TaskStatus.CANCELLED:
return task
job = self._cancel_job(runs, owner, task_id, task["execution_epoch"])
# asyncio.wait leaves the tracked job running after the response deadline.
done, _ = await asyncio.wait({job}, timeout=CANCEL_RESPONSE_TIMEOUT)
return job.result() if done else task
def _cancel_job(self, runs, owner, task_id, epoch):
key = (owner, task_id)
job = self._cancellations.get(key)
if job is None or job.done():
job = asyncio.create_task(self._finish_cancellation(runs, owner, task_id, epoch))
self._cancellations[key] = job
def finished(completed):
if self._cancellations.get(key) is completed:
self._cancellations.pop(key)
if not completed.cancelled() and (error := completed.exception()) is not None:
logger.warning("Coordination cancellation stopped for task %s (%s)", task_id, type(error).__name__)
job.add_done_callback(finished)
return job
async def _finish_cancellation(self, runs, owner, task_id, epoch):
delay = 1
while True:
try:
await self._stop_subtree(runs, owner, task_id)
return await self.repo.confirm_cancel(owner, task_id, execution_epoch=epoch)
except AgentRunError as exc:
if exc.status_code < 500:
raise
await asyncio.sleep(delay)
delay = min(30, delay * 2)
async def _stop_subtree(self, runs, owner, task_id):
active = await self.repo.cancellations(owner, task_id)
for thread, run_id in active:
run = await runs.get(thread_id=thread, run_id=run_id)
if run.status in ("pending", "running"):
try:
await runs.cancel(thread_id=thread, run_id=run_id)
except AgentRunError as exc:
if exc.status_code != 409 or (await runs.get(thread_id=thread, run_id=run_id)).status in ("pending", "running"):
raise
for thread, run_id in active:
while True:
try:
await runs.wait_coordination_worker(thread_id=thread, run_id=run_id, timeout=60)
break
except TimeoutError:
continue
for batch in await self.repo.active_batches(owner, task_id):
await runs.cancel_worker_batch(thread_id=batch.thread_id, batch_id=batch.id)
def worker_context(request):
service = getattr(request.app.state, "coordination_workers", None)
if service is None:
raise HTTPException(503, "Coordination workers require SQL persistence")
runs = get_agent_runs(request)
if runs is None:
raise HTTPException(403, "Coordination workers require a user session")
return service, str(request.state.user.id), runs.for_plugin("native-coordination")
def worker_error(exc):
if isinstance(exc, TaskNotFound):
return HTTPException(404, "Task not found")
if isinstance(exc, AgentRunError):
return HTTPException(exc.status_code, str(exc) if exc.status_code < 500 else "Worker host unavailable")
return HTTPException(409, str(exc))
async def managed_task(request, thread_id):
if not thread_id.startswith(THREAD_PREFIX):
return None
service = getattr(request.app.state, "coordination_workers", None)
return await service.repo.task_for_thread(thread_id) if service is not None else None
async def direct_worker_run(request, task_id, body, key):
from app.gateway.deps import get_run_manager
service, owner, _runs = worker_context(request)
if getattr(request.state, "run_origin", None) or body.checkpoint or body.checkpoint_id or body.conversation_references or body.multitask_strategy != "reject":
raise HTTPException(409, "Use a task input to continue this managed worker")
try:
runs, grant_id = await service.authority(owner, task_id)
if body.command is not None:
if set(body.command) != {"resume"} or body.command["resume"] is None or body.input:
raise HTTPException(422, "An explicit interrupt response is required")
view = await service.repo.view(owner, task_id)
current = view["execution"]
if current and current["status"] == "running" and current["run_id"]:
native = await runs.get(thread_id=view["assignment"]["thread_id"], run_id=current["run_id"])
if native.status == "waiting_for_input":
await service.repo.settle(owner, task_id, current["id"], native.run_id, native.status, [])
turn = await service.repo.resume(owner, task_id, key=key or uuid4().hex, value=body.command["resume"])
run_id = await service._admit(runs, owner, task_id, turn, grant_id)
service.watch(runs, owner, task_id, grant_id)
else:
messages = (body.input or {}).get("messages")
if not isinstance(messages, list) or len(messages) != 1 or not isinstance(messages[0], dict):
raise HTTPException(422, "Managed workers accept one text message")
message = messages[0]
content = message.get("content")
if isinstance(content, list) and all(isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) for part in content):
content = "".join(part["text"] for part in content)
if message.get("role", message.get("type")) not in ("user", "human") or not isinstance(content, str) or not 0 < len(content.strip()) <= 16384:
raise HTTPException(422, "Managed workers accept one text message")
identifier = key or message.get("id") or uuid4().hex
if not isinstance(identifier, str):
raise HTTPException(422, "Message ID must be a string")
row = await service.repo.append_input(owner, task_id, request_id="chat:" + sha256(identifier.encode()).hexdigest(), content=content)
driver = service.watch(runs, owner, task_id, grant_id)
# Streaming and wait endpoints must observe the Run that consumed this input.
while not (run_id := await service.repo.run_for_input(owner, task_id, row["sequence"])):
if driver.done():
driver.result()
raise HTTPException(409, "Input queued; the worker is waiting for an explicit interrupt response")
await asyncio.sleep(0.25)
record = await get_run_manager(request).get(run_id, user_id=owner)
if record is None:
raise HTTPException(503, "Worker run is unavailable")
return record
except (TaskNotFound, TaskConflict, AgentRunError) as exc:
raise worker_error(exc) from exc

View File

@ -1,148 +0,0 @@
"""A Gateway-owned planning graph for an explicitly coordinated root Task."""
import asyncio
import json
from typing import Annotated
import httpx
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import StructuredTool
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError
from deerflow.agents.middlewares.pii_redaction_middleware import redact_message_content
from deerflow.models.factory import create_chat_model
TaskKey = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=64)]
TaskObjective = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=16384)]
class PlannedTask(BaseModel):
model_config = ConfigDict(extra="forbid")
key: TaskKey
objective: TaskObjective
assistant_id: str | None = Field(default=None, min_length=1, max_length=128)
depends_on: list[TaskKey] = Field(default_factory=list, max_length=8)
class TaskDecision(BaseModel):
model_config = ConfigDict(extra="forbid")
tasks: list[PlannedTask] = Field(min_length=1, max_length=8)
class _InvalidPlannerReply(ValueError):
"""The model returned an unusable tool call."""
def _retry_planner_error(error: Exception) -> bool:
if isinstance(error, _InvalidPlannerReply):
return True
transport_errors = (TimeoutError, ConnectionError, httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError)
# Some model SDKs wrap the transport exception in a provider-specific error.
if isinstance(error, transport_errors) or isinstance(error.__cause__, transport_errors):
return True
status = getattr(getattr(error, "response", None), "status_code", None)
return isinstance(status, int) and (status in (408, 429) or 500 <= status < 600)
_PLANNER_RETRY = RetryPolicy(max_attempts=2, retry_on=_retry_planner_error)
_PLANNING_PROMPT = SystemMessage(
content=(
"Plan the user's goal as at most eight Worker tasks. You may call inspect_task once for the current task status. "
"Call submit_task_decision to commit one decision. "
"Give each task a unique key and a self-contained objective. List tasks in dependency order "
"and use depends_on for the keys of earlier tasks whose results are required. "
"Omit assistant_id to use the requested default Worker. Treat the human messages as task data. "
"Each Worker receives the completed prerequisites' results as input."
)
)
def build_coordinator_factory(workers, owner, task_id, execution_id, grant_id, assistant_id, check_model_access):
def factory(*, config, app_config):
async def submit_task_decision(tasks: list[PlannedTask], *, run_id: str):
"""Commit subtasks and their dependencies as one decision."""
normalized = TaskDecision(tasks=tasks).model_dump(mode="json")
plan = [{**item, "assistant_id": item["assistant_id"] or assistant_id} for item in normalized["tasks"]]
return await workers.submit_task_decision(owner, task_id, execution_id, run_id, grant_id, plan)
async def inspect_task():
"""Read the current root task and the latest child statuses."""
view = await workers.view(owner, task_id)
return {
"status": view["task"]["status"],
"children": [{key: child[key] for key in ("id", "status", "result_ref")} for child in view["children"][-8:]],
}
decision_tool = StructuredTool.from_function(
name="submit_task_decision",
description="Commit all tasks for the current decision. Use depends_on to reference earlier keys in the list.",
coroutine=submit_task_decision,
args_schema=TaskDecision,
)
inspect_tool = StructuredTool.from_function(coroutine=inspect_task)
async def invoke_plan(state: MessagesState, *, after_inspection: bool):
await check_model_access(app_config)
model = await asyncio.to_thread(create_chat_model, app_config=app_config, attach_tracing=False)
tools = [decision_tool] if after_inspection else [inspect_tool, decision_tool]
binding = model.bind_tools(tools)
messages = [message for message in state["messages"] if isinstance(message, HumanMessage)]
if app_config.pii_redaction.enabled:
messages = [message.model_copy(update={"content": redact_message_content(message.content, app_config.pii_redaction)}) for message in messages]
if after_inspection:
messages.extend(state["messages"][-2:])
response = await binding.ainvoke([_PLANNING_PROMPT, *messages])
if not isinstance(response, AIMessage) or len(response.tool_calls) != 1 or response.invalid_tool_calls:
raise _InvalidPlannerReply("Coordinator must return exactly one tool call")
call = response.tool_calls[0]
if call["name"] not in {tool.name for tool in tools} or not call.get("id"):
raise _InvalidPlannerReply("Coordinator returned an invalid decision call")
if call["name"] == "inspect_task":
if call["args"]:
raise _InvalidPlannerReply("inspect_task does not accept arguments")
else:
try:
TaskDecision.model_validate(call["args"])
except ValidationError as exc:
raise _InvalidPlannerReply("Coordinator returned invalid task arguments") from exc
return {"messages": [response]}
async def plan(state: MessagesState):
return await invoke_plan(state, after_inspection=False)
async def plan_after_inspection(state: MessagesState):
return await invoke_plan(state, after_inspection=True)
def next_node(state: MessagesState):
return state["messages"][-1].tool_calls[0]["name"]
async def inspect(state: MessagesState):
call = state["messages"][-1].tool_calls[0]
info = await inspect_task()
return {"messages": [ToolMessage(content=json.dumps(info), tool_call_id=call["id"], name=inspect_tool.name)]}
async def submit(state: MessagesState, runtime: Runtime):
call = state["messages"][-1].tool_calls[0]
decision = TaskDecision.model_validate(call["args"])
task_ids = await submit_task_decision(decision.tasks, run_id=runtime.context["run_id"])
return {"messages": [ToolMessage(content=json.dumps(task_ids), tool_call_id=call["id"], name=decision_tool.name)]}
graph = StateGraph(MessagesState)
graph.add_node("plan", plan, retry_policy=_PLANNER_RETRY)
graph.add_node("inspect_task", inspect)
graph.add_node("plan_after_inspection", plan_after_inspection, retry_policy=_PLANNER_RETRY)
graph.add_node("submit_task_decision", submit)
graph.add_edge(START, "plan")
graph.add_conditional_edges("plan", next_node, ["inspect_task", "submit_task_decision"])
graph.add_edge("inspect_task", "plan_after_inspection")
graph.add_edge("plan_after_inspection", "submit_task_decision")
graph.add_edge("submit_task_decision", END)
return graph.compile()
return factory

View File

@ -20,7 +20,6 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
import os import os
import tempfile
from collections.abc import AsyncGenerator, Callable from collections.abc import AsyncGenerator, Callable
from contextlib import AsyncExitStack, asynccontextmanager from contextlib import AsyncExitStack, asynccontextmanager
from pathlib import Path from pathlib import Path
@ -53,30 +52,6 @@ logger = logging.getLogger(__name__)
# timeout. # timeout.
_RUN_DRAIN_TIMEOUT_SECONDS = 5.0 _RUN_DRAIN_TIMEOUT_SECONDS = 5.0
# Upper bound (seconds) a delegated-restore call may wait for the AgentRuns
# host to be installed during Gateway startup. Startup normally signals within
# its first seconds; the bound only fails a stuck startup instead of leaving
# unattended recovery hanging, and per-record failures keep manual recovery.
_EXTENSION_RESTORE_READY_TIMEOUT_SECONDS = 60.0
async def _agent_runs_host_after_install(app, installed: asyncio.Event):
"""Resolve the AgentRuns host once startup has installed it.
Extension services start before the run-admission stack (thread store, run
manager, AgentRuns host) exists, and unattended restoration can run during
that window, so wait for the explicit installation signal instead of
failing the whole recovery scan.
"""
try:
await asyncio.wait_for(installed.wait(), _EXTENSION_RESTORE_READY_TIMEOUT_SECONDS)
except TimeoutError:
pass
host = getattr(app.state, "agent_runs_host", None)
if host is None:
raise RuntimeError("Agent run host unavailable")
return host
def _browser_tools_enabled_in_config(config: AppConfig) -> bool: def _browser_tools_enabled_in_config(config: AppConfig) -> bool:
"""Return whether process-local agentic browser sessions are configured.""" """Return whether process-local agentic browser sessions are configured."""
@ -337,8 +312,6 @@ def credentials_key_consumers(config: AppConfig) -> list[str]:
if extensions is not None: if extensions is not None:
# deerflow.mcp.oauth_store keeps rotating refresh tokens in the database. # deerflow.mcp.oauth_store keeps rotating refresh tokens in the database.
for name, server in extensions.get_enabled_mcp_servers().items(): for name, server in extensions.get_enabled_mcp_servers().items():
if server.uses_browser_oauth:
consumers.append(f"mcpServers.{name}.user_oauth.enabled=true")
oauth = server.oauth oauth = server.oauth
if oauth is not None and oauth.enabled and oauth.grant_type == "refresh_token": if oauth is not None and oauth.enabled and oauth.grant_type == "refresh_token":
consumers.append(f"mcpServers.{name}.oauth.enabled=true") consumers.append(f"mcpServers.{name}.oauth.enabled=true")
@ -411,54 +384,6 @@ def _validate_agent_storage(config: AppConfig) -> None:
) )
def _validate_provisioner_environment(config: AppConfig) -> None:
"""Refuse a ``sandbox.environment`` map the provisioner would reject.
The sandbox provider is built lazily, so the map used to pass startup and
fail on the first sandbox create instead: no Pod appeared, the upload path
turned the resulting ``ValueError`` into a 400 against a request that was
fine, and ``/health/ready`` still reported ready. The limits checked here
are the provisioner's own, applied to the same filtered map the backend
forwards, and sandbox allocation itself stays lazy.
"""
from app.gateway.health import resolve_provisioner_url
sandbox = getattr(config, "sandbox", None)
if resolve_provisioner_url(config) is None or not str(getattr(sandbox, "use", "")).endswith(":AioSandboxProvider"):
return
environment = dict(getattr(sandbox, "environment", None) or {})
if not environment:
return
from deerflow.community.aio_sandbox.remote_backend import check_provisioner_environment, operator_provisioner_environment
try:
check_provisioner_environment(operator_provisioner_environment(environment))
except ValueError as exc:
raise SystemExit(f"{exc}. Correct sandbox.environment in config.yaml, or remove it to use the image defaults.") from None
def _probe_managed_subagent_file_storage() -> None:
"""Warn early if this volume cannot support create-only publication."""
from deerflow.config.paths import get_paths
root = get_paths().managed_subagents_dir
try:
root.mkdir(parents=True, exist_ok=True)
# A private directory keeps probe names out of the JSON catalog and
# lets independent Gateway workers probe without touching each other.
with tempfile.TemporaryDirectory(prefix=".hardlink-probe-", dir=root) as scratch:
source = Path(scratch) / "source"
source.touch()
os.link(source, Path(scratch) / "linked")
except OSError as exc:
logger.warning(
"Managed subagent hard-link probe failed for %s: %s. Managed subagent creation may fail on this volume. Use a volume with working hard links or set agent_storage.backend='db' with SQLite/Postgres.",
root,
exc,
)
def _validate_login_throttle_storage(config: AppConfig) -> None: def _validate_login_throttle_storage(config: AppConfig) -> None:
"""Warn when a multi-process deployment counts login failures per process. """Warn when a multi-process deployment counts login failures per process.
@ -579,35 +504,8 @@ async def _retry_recovered_run_stream_end(
*, *,
retry_delay: float, retry_delay: float,
cleanup_delay: float, cleanup_delay: float,
stream_was_present: bool | None = None,
) -> None: ) -> None:
await asyncio.sleep(max(0.0, retry_delay)) await asyncio.sleep(max(0.0, retry_delay))
if stream_was_present is True:
stream_exists = getattr(bridge, "stream_exists", None)
if callable(stream_exists):
try:
if not await stream_exists(run_id):
cleanup_expired_producer = getattr(bridge, "cleanup_expired_producer", None)
if callable(cleanup_expired_producer):
try:
await cleanup_expired_producer(run_id)
except Exception:
logger.warning(
"Failed to clean expired stream producer marker after retry for %s",
run_id,
exc_info=True,
)
logger.debug(
"Skipping recovered stream end retry for %s: stream expired during retry delay",
run_id,
)
return
except Exception:
logger.debug(
"Failed to recheck recovered stream existence for %s",
run_id,
exc_info=True,
)
await bridge.publish_end(run_id) await bridge.publish_end(run_id)
await bridge.cleanup(run_id, delay=cleanup_delay) await bridge.cleanup(run_id, delay=cleanup_delay)
@ -622,7 +520,7 @@ async def _publish_recovered_run_stream_end(
"""Terminate retained streams for runs recovered as orphaned.""" """Terminate retained streams for runs recovered as orphaned."""
cleanup_tasks: list[tuple[str, asyncio.Task[None]]] = [] cleanup_tasks: list[tuple[str, asyncio.Task[None]]] = []
def schedule_retry(record: RunRecord, *, stream_was_present: bool | None = None) -> bool: def schedule_retry(record: RunRecord) -> bool:
retry_delay = getattr( retry_delay = getattr(
bridge, bridge,
"producer_lease_retry_delay_seconds", "producer_lease_retry_delay_seconds",
@ -636,7 +534,6 @@ async def _publish_recovered_run_stream_end(
record.run_id, record.run_id,
retry_delay=float(retry_delay), retry_delay=float(retry_delay),
cleanup_delay=cleanup_delay, cleanup_delay=cleanup_delay,
stream_was_present=stream_was_present,
) )
) )
task.add_done_callback( task.add_done_callback(
@ -652,11 +549,9 @@ async def _publish_recovered_run_stream_end(
for record in recovered_runs: for record in recovered_runs:
stream_exists = getattr(bridge, "stream_exists", None) stream_exists = getattr(bridge, "stream_exists", None)
stream_was_present: bool | None = None
if stream_exists is not None: if stream_exists is not None:
try: try:
stream_was_present = bool(await stream_exists(record.run_id)) if not await stream_exists(record.run_id):
if not stream_was_present:
logger.debug("Skipping recovered stream end for %s: stream already expired", record.run_id) logger.debug("Skipping recovered stream end for %s: stream already expired", record.run_id)
cleanup_expired_producer = getattr( cleanup_expired_producer = getattr(
bridge, bridge,
@ -674,12 +569,10 @@ async def _publish_recovered_run_stream_end(
) )
cleaned = False cleaned = False
if not cleaned: if not cleaned:
schedule_retry(record, stream_was_present=False) schedule_retry(record)
continue continue
except Exception: except Exception:
logger.debug("Failed to check recovered stream existence for %s", record.run_id, exc_info=True) logger.debug("Failed to check recovered stream existence for %s", record.run_id, exc_info=True)
schedule_retry(record, stream_was_present=stream_was_present)
continue
try: try:
await bridge.publish_end(record.run_id) await bridge.publish_end(record.run_id)
except Exception: except Exception:
@ -688,7 +581,7 @@ async def _publish_recovered_run_stream_end(
record.run_id, record.run_id,
exc_info=True, exc_info=True,
) )
schedule_retry(record, stream_was_present=stream_was_present) schedule_retry(record)
continue continue
task = asyncio.create_task(bridge.cleanup(record.run_id, delay=cleanup_delay)) task = asyncio.create_task(bridge.cleanup(record.run_id, delay=cleanup_delay))
task.add_done_callback(lambda task, run_id=record.run_id: _log_recovered_stream_cleanup_result(task, run_id)) task.add_done_callback(lambda task, run_id=record.run_id: _log_recovered_stream_cleanup_result(task, run_id))
@ -895,12 +788,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
# Reject agent_storage.backend='db' on a non-durable database, and warn on # Reject agent_storage.backend='db' on a non-durable database, and warn on
# node-divergent file storage under multi-worker Postgres. # node-divergent file storage under multi-worker Postgres.
_validate_agent_storage(startup_config) _validate_agent_storage(startup_config)
# Reject a sandbox.environment map the provisioner cannot accept while the
# provider is still unbuilt, so the failure lands on the setting upstream of
# the first sandbox create instead of on a request that did nothing wrong.
_validate_provisioner_environment(startup_config)
if getattr(getattr(startup_config, "agent_storage", None), "backend", None) == "file":
await asyncio.to_thread(_probe_managed_subagent_file_storage)
# Warn when login lockouts stay per-process under several Gateway processes. # Warn when login lockouts stay per-process under several Gateway processes.
_validate_login_throttle_storage(startup_config) _validate_login_throttle_storage(startup_config)
# IM chat-to-thread bindings need no companion warning: ``resolve_channel_store`` # IM chat-to-thread bindings need no companion warning: ``resolve_channel_store``
@ -962,11 +849,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
await init_engine_from_config(config.database) await init_engine_from_config(config.database)
app.state.checkpointer = await stack.enter_async_context(make_checkpointer(config)) app.state.checkpointer = await stack.enter_async_context(make_checkpointer(config))
# The peer is closed before the parent saver, including partial
# startup failure. Its own shutdown fences and drains isolated tasks.
from deerflow.subagents.checkpoints import subagent_checkpoint_runtime
await stack.enter_async_context(subagent_checkpoint_runtime(config, app.state.checkpointer))
app.state.store = await stack.enter_async_context(make_store(config)) app.state.store = await stack.enter_async_context(make_store(config))
# Record the checkpointer/Store backend and the provisioner endpoint # Record the checkpointer/Store backend and the provisioner endpoint
@ -983,9 +865,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
# Initialize repositories — one get_session_factory() call for all. # Initialize repositories — one get_session_factory() call for all.
sf = get_session_factory() sf = get_session_factory()
from deerflow.approvals.store import ApprovalStore
app.state.approval_store = ApprovalStore(sf)
# The login throttle store is resolved once per process from the startup # The login throttle store is resolved once per process from the startup
# snapshot and the engine above (auth.local.throttle_storage is # snapshot and the engine above (auth.local.throttle_storage is
@ -1008,7 +887,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
else: else:
from deerflow.runtime.runs.store.memory import MemoryRunStore from deerflow.runtime.runs.store.memory import MemoryRunStore
app.state.coordination_workers = None
app.state.run_store = MemoryRunStore() app.state.run_store = MemoryRunStore()
app.state.feedback_repo = None app.state.feedback_repo = None
# Memory backend has no durable PAT store, so Bearer credentials # Memory backend has no durable PAT store, so Bearer credentials
@ -1020,15 +898,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
run_events_config = getattr(config, "run_events", None) run_events_config = getattr(config, "run_events", None)
app.state.run_events_config = run_events_config app.state.run_events_config = run_events_config
app.state.run_event_store = make_run_event_store(run_events_config) app.state.run_event_store = make_run_event_store(run_events_config)
if sf is not None:
from deerflow.persistence.run.producer import validate_producer_fencing
# An activated database also forbids a memory/JSONL downgrade.
await validate_producer_fencing(
sf,
mode=getattr(run_events_config, "producer_fencing", "off"),
cutover_id=getattr(run_events_config, "producer_cutover_id", None),
)
from deerflow.runtime.events.terminal import RecoveryTerminalPublisher from deerflow.runtime.events.terminal import RecoveryTerminalPublisher
app.state.recovery_terminal_publisher = RecoveryTerminalPublisher(app.state.run_event_store, app.state.run_store) app.state.recovery_terminal_publisher = RecoveryTerminalPublisher(app.state.run_event_store, app.state.run_store)
@ -1078,13 +947,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
# Register cleanup before starting: start() can partially acquire # Register cleanup before starting: start() can partially acquire
# resources and then fail or be cancelled. # resources and then fail or be cancelled.
stack.push_async_callback(stop_extension_services) stack.push_async_callback(stop_extension_services)
agent_runs_host_installed = asyncio.Event()
async def restore_agent_runs_authority(*, user_id: str, grant: dict, validator=None, plugin_namespace: str | None = None):
host = await _agent_runs_host_after_install(app, agent_runs_host_installed)
return await host.restore_delegated_authority(user_id=user_id, grant=grant, validator=validator, plugin_namespace=plugin_namespace)
record_runtime_diagnostics( record_runtime_diagnostics(
await start_services( await start_services(
extensions, extensions,
@ -1093,7 +955,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
run_evidence_reader=app.state.run_evidence_reader, run_evidence_reader=app.state.run_evidence_reader,
host_capabilities=host_capabilities.bindings, host_capabilities=host_capabilities.bindings,
attempted_services=attempted_services, attempted_services=attempted_services,
agent_runs_restore=restore_agent_runs_authority,
) )
) )
@ -1191,16 +1052,6 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
app.state.agent_runs_host = GatewayAgentRunsHost(app, load_user=SQLiteUserRepository(sf).get_user_by_id if sf is not None else None) app.state.agent_runs_host = GatewayAgentRunsHost(app, load_user=SQLiteUserRepository(sf).get_user_by_id if sf is not None else None)
stack.callback(app.state.agent_runs_host.close) stack.callback(app.state.agent_runs_host.close)
if sf is not None:
from app.gateway.coordination_workers import CoordinationWorkers
from deerflow.persistence.channel_connections.sql import ChannelConnectionRepository
from deerflow.persistence.coordination.workers import CoordinationWorkerRepository
app.state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(sf), app.state.agent_runs_host, ChannelConnectionRepository(sf))
stack.push_async_callback(app.state.coordination_workers.close)
# Extension unattended recovery waits on this before restoring grants;
# past it, the whole run-admission stack above is ready.
agent_runs_host_installed.set()
# Start the lease heartbeat if enabled (multi-worker deployments). # Start the lease heartbeat if enabled (multi-worker deployments).
await app.state.run_manager.start_heartbeat() await app.state.run_manager.start_heartbeat()
@ -1385,31 +1236,17 @@ def _selected_checkpoint_ids(config: dict[str, Any]) -> frozenset[str]:
return frozenset(selected) return frozenset(selected)
def _run_completion_hook(*, scheduled_task_service: Any | None, batch_continuations: Any | None = None): def _run_completion_hook(*, scheduled_task_service: Any | None):
"""Notify the scheduler after ordinary run finalization.""" """Notify the scheduler after ordinary run finalization."""
async def handle(record: Any) -> None: async def handle(record: Any) -> None:
# Scheduler persistence is best-effort: a store outage must not skip the
# batch cancellation below, or claimed follow-ups of hard-stopped runs
# stay in `dispatching` forever (#7969).
try:
if scheduled_task_service is not None: if scheduled_task_service is not None:
await scheduled_task_service.handle_run_completion(record) await scheduled_task_service.handle_run_completion(record)
except Exception:
logger.warning("Scheduled task completion hook failed for run %s (non-fatal)", record.run_id, exc_info=True)
if batch_continuations is not None:
await batch_continuations.source_finished(record)
return handle return handle
def get_agent_runs(request: Request):
"""Return the host-bound AgentRuns capability for *request*, or ``None``."""
host = getattr(request.app.state, "agent_runs_host", None)
# Internal/channel and PAT runs deliberately receive no retained delegation.
return host.bind(request) if host is not None else None
def get_run_context(request: Request) -> RunContext: def get_run_context(request: Request) -> RunContext:
"""Build a :class:`RunContext` from ``app.state`` singletons. """Build a :class:`RunContext` from ``app.state`` singletons.
@ -1419,12 +1256,10 @@ def get_run_context(request: Request) -> RunContext:
``event_store`` / ``run_events_config`` pair stays frozen to the snapshot ``event_store`` / ``run_events_config`` pair stays frozen to the snapshot
captured in :func:`langgraph_runtime` so callers never see a store bound to captured in :func:`langgraph_runtime` so callers never see a store bound to
one backend paired with a config pointing at another. one backend paired with a config pointing at another.
Loading ``app_config`` stats and hashes ``config.yaml`` (and reparses it
after an edit), so async callers build the context with
``asyncio.to_thread``.
""" """
agent_runs = get_agent_runs(request) host = getattr(request.app.state, "agent_runs_host", None)
# Internal/channel and PAT runs deliberately receive no retained delegation.
agent_runs = host.bind(request) if host is not None else None
checkpointer = get_checkpointer(request) checkpointer = get_checkpointer(request)
scheduled_task_service = getattr(request.app.state, "scheduled_task_service", None) scheduled_task_service = getattr(request.app.state, "scheduled_task_service", None)
return RunContext( return RunContext(
@ -1437,13 +1272,11 @@ def get_run_context(request: Request) -> RunContext:
checkpoint_snapshot_frequency=getattr(request.app.state, "checkpoint_snapshot_frequency", None), checkpoint_snapshot_frequency=getattr(request.app.state, "checkpoint_snapshot_frequency", None),
thread_store=get_thread_store(request), thread_store=get_thread_store(request),
mcp_task_repo=getattr(request.app.state, "mcp_task_repo", None), mcp_task_repo=getattr(request.app.state, "mcp_task_repo", None),
approval_store=getattr(request.app.state, "approval_store", None),
app_config=get_config(), app_config=get_config(),
extensions=getattr(request.app.state, "extensions", None), extensions=getattr(request.app.state, "extensions", None),
on_run_admitted=_run_admission_hook(checkpointer=checkpointer), on_run_admitted=_run_admission_hook(checkpointer=checkpointer),
on_run_completed=_run_completion_hook( on_run_completed=_run_completion_hook(
scheduled_task_service=scheduled_task_service, scheduled_task_service=scheduled_task_service,
batch_continuations=getattr(request.app.state, "batch_continuations", None),
), ),
) )
@ -1606,24 +1439,13 @@ async def is_admin_user(request: Request) -> bool:
return getattr(user, "system_role", None) == "admin" return getattr(user, "system_role", None) == "admin"
async def require_admin_user(request: Request, *, detail: str, pat_scope: str | None = None) -> None: async def require_admin_user(request: Request, *, detail: str) -> None:
"""Require the authenticated caller to be an admin user. """Require the authenticated caller to be an admin user.
``detail`` is the route-specific 403 message. The shared predicate keeps ``detail`` is the route-specific 403 message. The shared predicate keeps
read-side redaction and write authorization on the same admin definition. read-side redaction and write authorization on the same admin definition.
``pat_scope`` names the one opt-in exception to "PATs never carry admin
capability": a route that passes it also admits a PAT whose owner is an
admin *and* which holds that scope. Only routes that pass it are affected;
``is_admin_user`` stays False for every PAT.
""" """
from app.gateway.auth_disabled import AUTH_SOURCE_PAT
if pat_scope is not None and getattr(request.state, "auth_source", None) == AUTH_SOURCE_PAT:
user = getattr(request.state, "user", None)
if pat_scope in getattr(request.state, "pat_scopes", frozenset()) and getattr(user, "system_role", None) == "admin":
return
raise HTTPException(status_code=403, detail=detail)
if not await is_admin_user(request): if not await is_admin_user(request):
raise HTTPException(status_code=403, detail=detail) raise HTTPException(status_code=403, detail=detail)

View File

@ -18,7 +18,7 @@ from pydantic import TypeAdapter, ValidationError
from app.gateway.auth_disabled import AUTH_SOURCE_AUTH_DISABLED, AUTH_SOURCE_SESSION, get_auth_disabled_user, is_auth_disabled from app.gateway.auth_disabled import AUTH_SOURCE_AUTH_DISABLED, AUTH_SOURCE_SESSION, get_auth_disabled_user, is_auth_disabled
from app.gateway.authz import AuthContext, resolve_route_permissions from app.gateway.authz import AuthContext, resolve_route_permissions
from deerflow.runtime.run_origin import DEERFLOW_ORIGIN_KEY, make_origin from deerflow.runtime.run_origin import make_origin
from deerflow.runtime.user_context import reset_current_user, set_current_user from deerflow.runtime.user_context import reset_current_user, set_current_user
from deerflow.utils.thread_id import ThreadId from deerflow.utils.thread_id import ThreadId
@ -60,10 +60,6 @@ class GatewayAgentRunsHost:
self.active = False self.active = False
def bind(self, request: Request): def bind(self, request: Request):
# A background task's synthetic authorization must not be re-minted
# as a general-purpose session handle for the agent it starts.
if getattr(request.state, "coordination_grant_id", None) is not None:
return None
user = getattr(request.state, "user", None) user = getattr(request.state, "user", None)
auth = getattr(request.state, "auth", None) auth = getattr(request.state, "auth", None)
if user is None or auth is None or not auth.is_authenticated: if user is None or auth is None or not auth.is_authenticated:
@ -77,87 +73,15 @@ class GatewayAgentRunsHost:
return None return None
return _BoundAgentRuns(self, str(user.id), user.token_version, source, frozenset(auth.permissions)) return _BoundAgentRuns(self, str(user.id), user.token_version, source, frozenset(auth.permissions))
def capture_batch_authority(self, runs, *, user_id: str) -> dict:
"""Capture only a native batch's existing host grant; never browser input."""
if not isinstance(runs, _BoundAgentRuns) or runs._host is not self or runs._user_id != user_id or not self.active:
raise AgentRunError(403, "Batch follow-up requires its originating Agent run authority")
return {"token_version": runs._token_version, "source": runs._source, "permissions": sorted(runs._permissions)}
async def restore_batch_authority(self, *, user_id: str, grant: dict):
"""Restore a persisted native batch grant with its original permission ceiling."""
source, version, permissions = grant.get("source"), grant.get("token_version"), grant.get("permissions")
if source not in (AUTH_SOURCE_SESSION, AUTH_SOURCE_AUTH_DISABLED) or type(version) is not int or not isinstance(permissions, list) or any(not isinstance(value, str) for value in permissions):
raise AgentRunError(403, "Invalid batch follow-up authority")
user = get_auth_disabled_user() if source == AUTH_SOURCE_AUTH_DISABLED and is_auth_disabled() else await self.load_user(user_id) if source == AUTH_SOURCE_SESSION and self.load_user is not None else None
if user is None or str(user.id) != user_id or user.token_version != version or user.needs_setup or getattr(user, "disabled", False):
raise AgentRunError(403, "Batch follow-up authorization revoked")
return _BoundAgentRuns(self, user_id, version, source, frozenset(permissions), origin=make_origin("subagent_batch"))
async def restore_delegated_authority(
self,
*,
user_id: str,
grant: dict,
validator: Callable[[], Awaitable[None]] | None = None,
plugin_namespace: str | None = None,
required_permissions: frozenset[str] = frozenset(),
):
"""Restore a persisted delegated grant (e.g. workflow recovery) with its ceiling.
The grant is the mapping ``capture_authority`` returned at mint time
(token_version, source, permissions); expiry and revocation are the
caller's contract, enforced through ``validator`` on every operation
this handle performs. Restoring re-loads the user row and fails closed
on a changed token_version, needs_setup or a disabled account, exactly
like ``restore_batch_authority``; it never creates fresh authority.
Callers can preflight required permissions against the grant and current
policy. Host operations still revalidate permissions at use.
"""
source, version, permissions = grant.get("source"), grant.get("token_version"), grant.get("permissions")
if source not in (AUTH_SOURCE_SESSION, AUTH_SOURCE_AUTH_DISABLED) or type(version) is not int or not isinstance(permissions, list) or any(not isinstance(value, str) for value in permissions):
raise AgentRunError(403, "Invalid delegated authority")
user = get_auth_disabled_user() if source == AUTH_SOURCE_AUTH_DISABLED and is_auth_disabled() else await self.load_user(user_id) if source == AUTH_SOURCE_SESSION and self.load_user is not None else None
if user is None or str(user.id) != user_id or user.token_version != version or user.needs_setup or getattr(user, "disabled", False):
raise AgentRunError(403, "Delegated authorization revoked")
granted_permissions = frozenset(permissions)
if required_permissions:
current_permissions = await resolve_route_permissions(user, is_internal=False)
if not required_permissions.issubset(granted_permissions.intersection(current_permissions)):
raise AgentRunError(403, "Delegated authorization lacks required permissions")
return _BoundAgentRuns(
self,
user_id,
version,
source,
granted_permissions,
plugin_namespace=plugin_namespace,
origin=make_origin("extension", namespace=plugin_namespace),
delegation_validator=validator,
)
class _BoundAgentRuns: class _BoundAgentRuns:
def __init__(self, host, user_id: str, token_version: int, source: str, permissions: frozenset[str], plugin_namespace: str | None = None, origin: dict | None = None, delegation_validator: Callable[[], Awaitable[None]] | None = None): def __init__(self, host, user_id: str, token_version: int, source: str, permissions: frozenset[str], plugin_namespace: str | None = None):
self._host = host self._host = host
self._user_id = user_id self._user_id = user_id
self._token_version = token_version self._token_version = token_version
self._source = source self._source = source
self._permissions = permissions self._permissions = permissions
self._plugin_namespace = plugin_namespace self._plugin_namespace = plugin_namespace
self._origin = origin
self._delegation_validator = delegation_validator
def capture_authority(self) -> dict | None:
"""Persistable restorable snapshot of this handle's existing authority.
Returns the mint-time ceiling (token_version, source, permissions) for
a host-originated session handle, or None when this handle's authority
is not restorable. The host never validates the caller here: capture
only reflects authority the live handle already holds.
"""
if not self._host.active or self._source not in (AUTH_SOURCE_SESSION, AUTH_SOURCE_AUTH_DISABLED):
return None
return {"token_version": self._token_version, "source": self._source, "permissions": sorted(self._permissions)}
def for_plugin(self, namespace: str): def for_plugin(self, namespace: str):
if not isinstance(namespace, str) or not namespace or len(namespace) > 96 or ":" in namespace: if not isinstance(namespace, str) or not namespace or len(namespace) > 96 or ":" in namespace:
@ -166,7 +90,7 @@ class _BoundAgentRuns:
if namespace != self._plugin_namespace: if namespace != self._plugin_namespace:
raise AgentRunError(422, "Agent run handle is already bound to a plugin") raise AgentRunError(422, "Agent run handle is already bound to a plugin")
return self return self
return _BoundAgentRuns(self._host, self._user_id, self._token_version, self._source, self._permissions, namespace, self._origin, self._delegation_validator) return _BoundAgentRuns(self._host, self._user_id, self._token_version, self._source, self._permissions, namespace)
@asynccontextmanager @asynccontextmanager
async def _request(self, permission: str, thread_id: str | None = None): async def _request(self, permission: str, thread_id: str | None = None):
@ -176,15 +100,8 @@ class _BoundAgentRuns:
user = get_auth_disabled_user() if is_auth_disabled() else None user = get_auth_disabled_user() if is_auth_disabled() else None
else: else:
user = await self._host.load_user(self._user_id) if self._host.load_user is not None else None user = await self._host.load_user(self._user_id) if self._host.load_user is not None else None
if user is None or str(user.id) != self._user_id or user.token_version != self._token_version or user.needs_setup or getattr(user, "disabled", False): if user is None or str(user.id) != self._user_id or user.token_version != self._token_version or user.needs_setup:
raise AgentRunError(403, "Agent run authorization revoked") raise AgentRunError(403, "Agent run authorization revoked")
if self._delegation_validator is not None:
try:
await self._delegation_validator()
except AgentRunError:
raise
except Exception as exc:
raise AgentRunError(403, "Delegated authorization revoked") from exc
permissions = self._permissions.intersection(await resolve_route_permissions(user, is_internal=False)) permissions = self._permissions.intersection(await resolve_route_permissions(user, is_internal=False))
if permission not in permissions: if permission not in permissions:
raise AgentRunError(403, f"Permission denied: {permission}") raise AgentRunError(403, f"Permission denied: {permission}")
@ -196,7 +113,7 @@ class _BoundAgentRuns:
request.state.auth = AuthContext(user, list(permissions)) request.state.auth = AuthContext(user, list(permissions))
# Host-set, never HTTP input: threads and runs created through this # Host-set, never HTTP input: threads and runs created through this
# handle are marked as extension work (activity feed, unread state). # handle are marked as extension work (activity feed, unread state).
request.state.run_origin = self._origin or make_origin("extension", namespace=self._plugin_namespace) request.state.run_origin = make_origin("extension", namespace=self._plugin_namespace)
token = set_current_user(user) token = set_current_user(user)
try: try:
if thread_id is not None: if thread_id is not None:
@ -229,56 +146,13 @@ class _BoundAgentRuns:
raise AgentRunError(409, "Host assembly evidence unavailable") raise AgentRunError(409, "Host assembly evidence unavailable")
return copy.deepcopy(evidence) return copy.deepcopy(evidence)
async def validate_artifact_source(self, *, thread_id, run_id, idempotency_key): async def read_artifact(self, *, thread_id, path):
from app.gateway.deps import get_run_manager from app.gateway.extension_artifacts import read_output_snapshot
from app.gateway.extension_artifacts import validate_capture_support
from app.gateway.routers.thread_runs import _scope_http_run_idempotency_key
from deerflow.utils.file_io import await_drained
if self._plugin_namespace is None or not isinstance(idempotency_key, str) or not 1 <= len(idempotency_key) <= 200:
raise AgentRunError(422, "Artifact registration requires a plugin-scoped execution key")
async with self._request("runs:read", thread_id) as request:
run = await get_run_manager(request).get(run_id, user_id=self._user_id)
key = _scope_http_run_idempotency_key(request, thread_id, f"extension:{self._plugin_namespace}:{idempotency_key}")
origin = (run.metadata or {}).get(DEERFLOW_ORIGIN_KEY) if run is not None else None
if run is None or run.thread_id != thread_id or run.status != "running" or run.idempotency_key != key or origin != make_origin("extension", namespace=self._plugin_namespace):
raise AgentRunError(422, "Register files during the executing team run")
async with self._request("threads:read", thread_id) as request:
await await_drained(validate_capture_support(request, self._user_id, thread_id))
async def read_artifact(self, *, thread_id, path, expected_checkpoint_id=None):
from app.gateway.extension_artifacts import read_snapshot
from app.gateway.routers.artifacts import reserve_artifact_write from app.gateway.routers.artifacts import reserve_artifact_write
from deerflow.runtime.runs.manager import ConflictError
from deerflow.utils.file_io import await_drained
async with self._request("threads:read", thread_id) as request: async with self._request("threads:read", thread_id) as request:
try:
async with reserve_artifact_write(request, thread_id, user_id=self._user_id): async with reserve_artifact_write(request, thread_id, user_id=self._user_id):
if expected_checkpoint_id is not None: return await asyncio.to_thread(read_output_snapshot, self._user_id, thread_id, path)
if not isinstance(expected_checkpoint_id, str) or not expected_checkpoint_id:
raise AgentRunError(422, "Invalid producing checkpoint")
state = await self.get_state(thread_id=thread_id)
if state.get("checkpoint_id") != expected_checkpoint_id:
raise AgentRunError(412, "Producing conversation changed before artifact capture")
return await await_drained(read_snapshot(request, self._user_id, thread_id, path))
except ConflictError as exc:
raise AgentRunError(409, "Producing conversation is busy") from exc
async def import_artifact(self, *, thread_id, filename, content):
from app.gateway.extension_artifacts import import_snapshot
from app.gateway.routers.artifacts import reserve_artifact_write
from deerflow.runtime.runs.manager import ConflictError
from deerflow.utils.file_io import await_drained
if self._plugin_namespace is None:
raise AgentRunError(422, "Artifact import requires a plugin-scoped capability")
async with self._request("threads:write", thread_id) as request:
try:
async with reserve_artifact_write(request, thread_id, user_id=self._user_id):
return await await_drained(import_snapshot(request, self._user_id, thread_id, self._plugin_namespace, filename, content))
except ConflictError as exc:
raise AgentRunError(409, "Recipient conversation is busy") from exc
async def configuration_revision(self, *, assistant_ids: list[str], durable: bool = False) -> str: async def configuration_revision(self, *, assistant_ids: list[str], durable: bool = False) -> str:
from deerflow.config.agents_config import load_agent_config, load_agent_soul from deerflow.config.agents_config import load_agent_config, load_agent_soul
@ -317,15 +191,14 @@ class _BoundAgentRuns:
return await asyncio.to_thread(snapshot) return await asyncio.to_thread(snapshot)
async def create_thread(self, *, assistant_id="lead_agent", thread_id=None, metadata=None, project_id=None) -> str: async def create_thread(self, *, assistant_id="lead_agent", thread_id=None, metadata=None) -> str:
from app.gateway.routers.threads import ThreadCreateRequest, create_thread from app.gateway.routers.threads import ThreadCreateRequest, create_thread
async with self._request("threads:write") as request: async with self._request("threads:write") as request:
response = await create_thread(ThreadCreateRequest(assistant_id=assistant_id, thread_id=thread_id, project_id=project_id, metadata=_json_object(metadata) or {}), request) response = await create_thread(ThreadCreateRequest(assistant_id=assistant_id, thread_id=thread_id, metadata=_json_object(metadata) or {}), request)
return response.thread_id return response.thread_id
async def _start(self, *, thread_id, input=None, resume=None, context=None, idempotency_key=None, execution_fence=None, artifact_imports=None): async def _start(self, *, thread_id, input=None, resume=None, context=None, idempotency_key=None, execution_fence=None):
from app.gateway.extension_artifacts import validate_import_receipts
from app.gateway.routers.thread_runs import create_run from app.gateway.routers.thread_runs import create_run
from app.gateway.run_models import RunCreateRequest from app.gateway.run_models import RunCreateRequest
from app.gateway.services import resolve_thread_assistant_id from app.gateway.services import resolve_thread_assistant_id
@ -336,16 +209,9 @@ class _BoundAgentRuns:
run_input = _json_object(input) run_input = _json_object(input)
run_context = _json_object(context) run_context = _json_object(context)
command = _json_object({"resume": resume}) if resume is not None else None command = _json_object({"resume": resume}) if resume is not None else None
imports = _json_object({"items": artifact_imports})["items"] if artifact_imports is not None else None
if imports is not None:
if self._plugin_namespace is None or resume is not None:
raise AgentRunError(422, "Artifact admission requires a plugin-scoped new run")
validate_import_receipts(imports)
if run_context is not None and any(key in run_context for key in ("agent_name", "is_bootstrap")): if run_context is not None and any(key in run_context for key in ("agent_name", "is_bootstrap")):
raise AgentRunError(422, "Agent identity is bound to the thread") raise AgentRunError(422, "Agent identity is bound to the thread")
async with self._request("runs:create", thread_id) as request: async with self._request("runs:create", thread_id) as request:
if imports:
request.state.extension_artifact_imports = imports
if execution_fence is not None: if execution_fence is not None:
if not isinstance(execution_fence, ExecutionFence) or self._plugin_namespace is None or execution_fence.namespace != self._plugin_namespace: if not isinstance(execution_fence, ExecutionFence) or self._plugin_namespace is None or execution_fence.namespace != self._plugin_namespace:
raise AgentRunError(422, "Execution fence must belong to this plugin") raise AgentRunError(422, "Execution fence must belong to this plugin")
@ -359,176 +225,8 @@ class _BoundAgentRuns:
response = await create_run(thread_id, body, request, idempotency_key=f"extension:{self._plugin_namespace or ''}:{idempotency_key}" if idempotency_key is not None else None) response = await create_run(thread_id, body, request, idempotency_key=f"extension:{self._plugin_namespace or ''}:{idempotency_key}" if idempotency_key is not None else None)
return _view(response) return _view(response)
async def start(self, *, thread_id, input, context=None, idempotency_key=None, execution_fence=None, artifact_imports=None) -> AgentRun: async def start(self, *, thread_id, input, context=None, idempotency_key=None, execution_fence=None) -> AgentRun:
return await self._start(thread_id=thread_id, input=input, context=context, idempotency_key=idempotency_key, execution_fence=execution_fence, artifact_imports=artifact_imports) return await self._start(thread_id=thread_id, input=input, context=context, idempotency_key=idempotency_key, execution_fence=execution_fence)
async def start_coordination_worker(self, *, task_id, execution_id, grant_id):
from app.gateway.run_models import RunCreateRequest
from app.gateway.services import start_run
from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound
from deerflow.persistence.coordination.workers import RUN_KEY_PREFIX
from deerflow.persistence.thread_meta.base import THREAD_PROJECT_METADATA_KEY
async with self._request("runs:create") as request:
try:
worker, frozen, project_id, saved_settings, channel_origin = await request.app.state.coordination_workers.repo.admission(self._user_id, task_id, execution_id)
except TaskNotFound as exc:
raise AgentRunError(404, "Worker task unavailable") from exc
except TaskConflict as exc:
raise AgentRunError(409, str(exc)) from exc
thread_id = worker["thread_id"]
frozen = dict(frozen)
planner_input_key = frozen.pop("planner_input_key", None)
async with self._request("runs:create", thread_id) as request:
record = await request.app.state.thread_store.get(thread_id, user_id=self._user_id)
if record is None or record.get("assistant_id") != worker["assistant_id"] or (record.get("metadata") or {}).get(THREAD_PROJECT_METADATA_KEY) != project_id:
raise AgentRunError(409, "Worker thread binding changed")
settings = saved_settings or {}
context = {key: settings[key] for key in ("thinking_enabled", "is_plan_mode") if key in settings}
context["subagent_enabled"] = True
body = RunCreateRequest(
assistant_id=worker["assistant_id"],
input=frozen if "messages" in frozen else None,
command=frozen.get("command"),
checkpoint_id=frozen.get("checkpoint_id"),
config={"recursion_limit": settings["recursion_limit"]} if "recursion_limit" in settings else None,
context=context,
on_disconnect="continue",
)
if channel_origin is not None:
request.state.run_origin = make_origin("im_channel", provider=channel_origin["provider"])
request.state.coordination_execution_id = execution_id
request.state.coordination_grant_id = grant_id
coordinator_factory = None
if "expected_revision" in frozen:
from app.gateway.authz import authorize_model_use
from app.gateway.coordinator_agent import build_coordinator_factory
async def check_model_access(app_config):
async with self._request("runs:create", thread_id) as model_request:
await asyncio.to_thread(authorize_model_use, model_request.state.user, None, is_internal=False, app_config=app_config)
workers = request.app.state.coordination_workers
coordinator_factory = build_coordinator_factory(workers, self._user_id, task_id, execution_id, grant_id, worker["assistant_id"], check_model_access)
record = await start_run(
body,
thread_id,
request,
require_existing_thread=True,
idempotency_key=RUN_KEY_PREFIX + execution_id,
agent_factory_override=coordinator_factory,
input_message_idempotency_key=planner_input_key,
)
return _view(record)
async def wait_coordination_worker(self, *, thread_id, run_id, timeout=60):
"""Observe the committed terminal status, written after the delivery receipt."""
from app.gateway.deps import get_run_event_store, get_run_store
from deerflow.extensions.run_evidence import StoreRunEvidenceReader
async with asyncio.timeout(timeout):
delay = 0.25
while True:
async with self._request("runs:read", thread_id) as request:
evidence = StoreRunEvidenceReader(get_run_store(request), get_run_event_store(request), user_id=self._user_id)
row = await evidence.get_run_status(thread_id=thread_id, run_id=run_id)
if row is None:
raise AgentRunError(404, "Worker run unavailable")
if row.status not in ("pending", "running"):
return row
await asyncio.sleep(delay)
delay = min(delay * 2, 4)
async def cancel_worker_batch(self, *, thread_id, batch_id):
from app.gateway.deps import get_subagent_batch_service
async with self._request("runs:cancel", thread_id) as request:
await get_subagent_batch_service(request).cancel_batch(batch_id=batch_id, user_id=self._user_id, continuation_authority=self)
async def coordination_result_text(self, *, thread_id, run_id):
from app.gateway.conversation_access import _visible_text
from app.gateway.deps import get_run_event_store
async with self._request("runs:read", thread_id) as request:
rows = await get_run_event_store(request).list_messages_by_run(thread_id, run_id, user_id=self._user_id, limit=12)
for row in reversed(rows):
if row.get("event_type") in ("llm.ai.response", "ai_message"):
visible = _visible_text(row, thread_id=thread_id)
if visible is not None and visible[0] == "assistant":
return visible[1][:4000]
return None
async def coordination_recovery_checkpoint(self, *, thread_id, run_id):
from app.gateway.deps import get_run_store
async with self._request("runs:read", thread_id) as request:
row = await get_run_store(request).get(run_id, user_id=self._user_id)
if row is None or row["thread_id"] != thread_id or row.get("cancel_requested_at"):
return None
try:
return await self.get_state(thread_id=thread_id)
except AgentRunError as exc:
if exc.status_code != 404:
raise
# A stopped Run can have no readable checkpoint after restart.
return None
async def coordination_artifacts(self, *, thread_id, run_id):
from app.gateway.artifact_archive import MAX_FILE_BYTES, MAX_FILES, MAX_TOTAL_BYTES
from app.gateway.deps import get_run_event_store
from app.gateway.extension_artifacts import read_snapshot
from app.gateway.routers.artifacts import reserve_artifact_write
from deerflow.constants import DELIVERY_PRESENTATION_TOOL_NAMES
from deerflow.runtime.runs.manager import ConflictError
from deerflow.utils.file_io import await_drained
async with self._request("runs:read", thread_id) as request:
events = await get_run_event_store(request).list_events(thread_id, run_id, event_types=["run.delivery"], limit=2, user_id=self._user_id)
if len(events) != 1:
raise AgentRunError(409, "Run delivery receipt is unavailable")
by_tool = (events[0].get("content") or {}).get("by_tool")
if not isinstance(by_tool, dict) or any(not isinstance(paths, list) or any(not isinstance(path, str) for path in paths) for paths in by_tool.values()):
raise AgentRunError(409, "Invalid run delivery receipt")
paths = dict.fromkeys(path for tool in DELIVERY_PRESENTATION_TOOL_NAMES for path in by_tool.get(tool, []))
if not paths:
return []
if len(paths) > MAX_FILES:
raise AgentRunError(422, "Too many task artifacts")
artifacts = []
remaining = MAX_TOTAL_BYTES
async with self._request("threads:read", thread_id) as request:
try:
async with reserve_artifact_write(request, thread_id, user_id=self._user_id):
for path in paths:
content = await await_drained(read_snapshot(request, self._user_id, thread_id, path, max_bytes=min(MAX_FILE_BYTES, remaining)))
digest = await asyncio.to_thread(hashlib.sha256, content)
artifacts.append((path, digest.hexdigest(), content))
remaining -= len(content)
except ConflictError as exc:
raise AgentRunError(503, "Worker artifacts are temporarily busy") from exc
return artifacts
async def start_batch_followup(self, *, thread_id, batch_id, input, context, config, execution_fence, goal_wakeup=None):
"""Native single follow-up; the existing SQL admission fences cancellation."""
from app.gateway.run_models import RunCreateRequest
from app.gateway.services import resolve_thread_assistant_id, start_run
from deerflow.subagents.batch_runtime import BATCH_CONTINUATION_NAMESPACE, batch_continuation_key
if self._origin != make_origin("subagent_batch") or execution_fence.namespace != BATCH_CONTINUATION_NAMESPACE or execution_fence.resource_id != batch_id:
raise AgentRunError(403, "Invalid native batch continuation")
async with self._request("runs:create", thread_id) as request:
request.state.extension_execution_fence = execution_fence
assistant_id = await resolve_thread_assistant_id(request, thread_id, fail_closed=True)
body = RunCreateRequest(
assistant_id=assistant_id,
input=_json_object(input),
context=_json_object(context),
config=_json_object(config),
metadata={"batch_goal_wakeup": _json_object(goal_wakeup)} if goal_wakeup is not None else None,
on_disconnect="continue",
)
record = await start_run(body, thread_id, request, idempotency_key=batch_continuation_key(batch_id), require_existing_thread=True)
return _view(record)
async def resume(self, *, thread_id, resume, idempotency_key=None) -> AgentRun: async def resume(self, *, thread_id, resume, idempotency_key=None) -> AgentRun:
if resume is None: if resume is None:
@ -547,39 +245,6 @@ class _BoundAgentRuns:
async with self._request("threads:read", thread_id) as request: async with self._request("threads:read", thread_id) as request:
return (await get_thread_state(thread_id, request)).model_dump(mode="json") return (await get_thread_state(thread_id, request)).model_dump(mode="json")
async def send_input(self, *, thread_id, run_id, text, mode, request_id, context=None):
from app.gateway.run_inputs import RunInputRequest, submit_run_input
async with self._request("runs:create", thread_id) as request:
body = RunInputRequest(request_id=request_id, text=text, mode=mode, context=_json_object(context) or {})
body = body.model_copy(update={"request_id": hashlib.sha256(f"{self._plugin_namespace or 'host'}:{body.request_id}".encode()).hexdigest()})
return await submit_run_input(thread_id, run_id, body, request)
async def dispatch_input(self, *, thread_id, run_id, input_id):
from app.gateway.run_inputs import dispatch_one_input
async with self._request("runs:create", thread_id) as request:
return await dispatch_one_input(thread_id, run_id, input_id, request)
async def list_inputs(self, *, thread_id):
from app.gateway.routers.thread_runs import get_thread_inputs
async with self._request("threads:read", thread_id) as request:
return await get_thread_inputs(thread_id, request)
async def authorize_control(self, *, thread_id, run_id, clear_goal=False):
from app.gateway.deps import get_run_manager
async with self._request("runs:cancel", thread_id) as request:
run = await get_run_manager(request).get(run_id, user_id=self._user_id)
if run is None or run.thread_id != thread_id:
raise AgentRunError(404, "Run unavailable")
if run.status not in ("pending", "running"):
raise AgentRunError(409, "Run already stopped")
if clear_goal:
async with self._request("threads:write", thread_id):
pass
async def cancel(self, *, thread_id, run_id, execution_fence=None) -> None: async def cancel(self, *, thread_id, run_id, execution_fence=None) -> None:
from app.gateway.routers.thread_runs import cancel_run from app.gateway.routers.thread_runs import cancel_run

View File

@ -1,243 +1,24 @@
"""Bounded output capture without symlink traversal or mutable-path rereads.""" """Bounded output capture without symlink traversal or mutable-path rereads."""
import hashlib
import logging
import os import os
import re
import stat import stat
import uuid
from collections.abc import AsyncIterator
from contextlib import AsyncExitStack, asynccontextmanager
from typing import Any
from deerflow_extension_api import AgentRunError from deerflow_extension_api import AgentRunError
from fastapi import Request
from app.gateway.authz import try_acquire_sandbox_for_request
from app.gateway.path_utils import normalize_outputs_virtual_path from app.gateway.path_utils import normalize_outputs_virtual_path
from deerflow.config.paths import get_paths from deerflow.config.paths import get_paths
from deerflow.sandbox.sandbox import Sandbox
from deerflow.sandbox.sandbox_provider import get_sandbox_provider
MAX_BYTES = 2 * 1024 * 1024 MAX_BYTES = 2 * 1024 * 1024
logger = logging.getLogger(__name__)
def validate_import_receipts(values: object) -> None: def read_output_snapshot(user_id, thread_id, path):
"""Reject malformed receipts or more than four bounded imports with 422."""
if not isinstance(values, list) or len(values) > 4:
raise AgentRunError(422, "Choose at most four imported artifacts")
for value in values:
if not isinstance(value, dict) or set(value) != {"filename", "path", "sha256", "size"}:
raise AgentRunError(422, "Invalid artifact import receipt")
filename = value["filename"]
if not isinstance(filename, str) or not filename or filename in (".", "..") or any(c in filename for c in "/\\") or any(ord(c) < 32 for c in filename):
raise AgentRunError(422, "Invalid artifact import filename")
try:
valid = len(filename.encode()) <= 255
except UnicodeError:
valid = False
if (
not valid
or value["path"] != "/mnt/user-data/uploads/" + filename
or not isinstance(value["sha256"], str)
or re.fullmatch(r"[0-9a-f]{64}", value["sha256"]) is None
or type(value["size"]) is not int
or not 0 <= value["size"] <= MAX_BYTES
):
raise AgentRunError(422, "Invalid artifact import receipt")
@asynccontextmanager
async def snapshot_sandbox(request: Request, user_id: str, thread_id: str) -> AsyncIterator[Sandbox | None]:
"""Yield a remote sandbox lease, or None for host-mounted thread data.
Permission denial raises 403 and an unavailable sandbox raises 503. Release
drains on cancellation; exact snapshots never fall back after a denied lease.
"""
from app.gateway.routers.uploads import _uses_thread_data_mounts
from deerflow.config.app_config import get_app_config
from deerflow.utils.file_io import await_drained, run_file_io
provider = get_sandbox_provider()
lease = None
try:
if not _uses_thread_data_mounts(provider):
lease = await try_acquire_sandbox_for_request(request, provider, thread_id, user_id=user_id, app_config=await run_file_io(get_app_config), owner_prefix="gateway:artifact-snapshot", release_on_last=True)
if lease.denied:
raise AgentRunError(403, "Sandbox permission denied for artifact snapshots")
if lease.sandbox is None:
raise AgentRunError(503, "Sandbox unavailable for artifact snapshots")
yield lease.sandbox if lease is not None else None
finally:
if lease is not None:
await await_drained(lease.release())
async def validate_capture_support(request: Request, user_id: str, thread_id: str) -> None:
"""Require POSIX capture and probe remote support before registration.
Raise 422 for unsupported capture, retaining lease authorization failures.
"""
from deerflow.sandbox.artifact_snapshot import validate_snapshot_support
from deerflow.utils.file_io import run_file_io
if os.name != "posix":
raise AgentRunError(422, "Artifact capture requires POSIX")
async with snapshot_sandbox(request, user_id, thread_id) as sandbox:
if sandbox is not None:
await run_file_io(validate_snapshot_support, sandbox)
def validate_import(filename: object, content: object) -> None:
"""Reject unsafe filenames, non-POSIX hosts or content over 2 MiB with 422."""
if os.name != "posix" or not isinstance(filename, str) or not filename or filename in (".", "..") or any(c in filename for c in "/\\") or any(ord(c) < 32 for c in filename):
raise AgentRunError(422, "Use a plain artifact filename on POSIX")
try:
valid = len(filename.encode()) <= 160
except UnicodeError:
valid = False
if not valid or not isinstance(content, bytes) or len(content) > MAX_BYTES:
raise AgentRunError(422, "Artifact filename is too long or content exceeds 2 MiB")
def write_import_snapshot(user_id: str, thread_id: str, namespace: str, filename: str, content: bytes) -> dict[str, Any]:
"""Publish a confined content-addressed upload and return its import receipt.
Reuse only identical regular files; retain existing edits and raise 422 for
unsafe or changed destinations. Run filesystem work off the event loop.
"""
validate_import(filename, content)
digest = hashlib.sha256(content).hexdigest()
identity = hashlib.sha256(namespace.encode() + b"\0" + filename.encode() + b"\0" + content).hexdigest()[:32]
destination = f"artifact-{identity}-{filename}"
paths = get_paths()
root = paths.base_dir.resolve()
relative = paths.sandbox_uploads_dir(thread_id, user_id=user_id).relative_to(paths.base_dir)
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
temporary = ".upload-" + uuid.uuid4().hex + ".part"
created = False
try:
for part in relative.parts:
try:
os.mkdir(part, mode=0o755, dir_fd=directory)
except FileExistsError:
pass
next_dir = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
os.close(directory)
directory = next_dir
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory)
created = True
with os.fdopen(fd, "wb") as target:
target.write(content)
target.flush()
os.fsync(target.fileno())
os.fchmod(target.fileno(), 0o644)
try:
os.link(temporary, destination, src_dir_fd=directory, dst_dir_fd=directory, follow_symlinks=False)
except FileExistsError:
pass
os.unlink(temporary, dir_fd=directory)
created = False
fd = os.open(destination, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
with os.fdopen(fd, "rb") as existing:
before = os.fstat(existing.fileno())
if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or before.st_size != len(content):
raise AgentRunError(422, "Imported artifact was changed; existing file retained")
data = existing.read(MAX_BYTES + 1)
after = os.fstat(existing.fileno())
if data != content or (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns):
raise AgentRunError(422, "Imported artifact was changed; existing file retained")
return {"filename": destination, "path": "/mnt/user-data/uploads/" + destination, "sha256": digest, "size": len(content)}
except OSError as exc:
raise AgentRunError(422, "Artifact import destination unavailable or unsafe") from exc
finally:
try:
if created:
os.unlink(temporary, dir_fd=directory)
except OSError:
logger.warning("Failed to clean up an abandoned artifact import staging file", exc_info=True)
finally:
os.close(directory)
async def import_snapshot(request: Request, user_id: str, thread_id: str, namespace: str, filename: str, content: bytes) -> dict[str, Any]:
"""Return a receipt after publishing identical host and remote uploads.
Retain existing edits; unsafe/changed snapshots raise 422 and lease failures
keep their authorization/availability status. Cancellation drains file I/O.
"""
from deerflow.sandbox.artifact_snapshot import publish_snapshot
from deerflow.utils.file_io import run_file_io
validate_import(filename, content)
async with snapshot_sandbox(request, user_id, thread_id) as sandbox:
result = await run_file_io(write_import_snapshot, user_id, thread_id, namespace, filename, content)
if sandbox is not None:
await run_file_io(publish_snapshot, sandbox, result["filename"], content)
return result
async def read_snapshot(request: Request, user_id: str, thread_id: str, path: str, *, max_bytes: int = MAX_BYTES) -> bytes:
"""Capture bounded output bytes through host storage or an authorized lease.
Non-output paths raise HTTP 400; unsafe files raise 422 and host mutation
during capture raises 409. Remote snapshot and lease errors retain their
status. Cancellation drains I/O.
"""
from deerflow.sandbox.artifact_snapshot import read_snapshot as read_remote
from deerflow.utils.file_io import run_file_io
path = normalize_outputs_virtual_path(path)
async with snapshot_sandbox(request, user_id, thread_id) as sandbox:
if sandbox is not None:
return await run_file_io(read_remote, sandbox, path.removeprefix("/mnt/user-data/outputs/"), max_bytes=max_bytes)
return await run_file_io(read_output_snapshot, user_id, thread_id, path, max_bytes=max_bytes)
async def verify_imports(request: Request, user_id: str, thread_id: str, receipts: list[dict[str, Any]], *, lifetime: AsyncExitStack | None = None) -> None:
"""Verify receipt bytes after new admission and before Agent construction.
A supplied lifetime retains the remote lease through execution; otherwise it
ends here. Missing, changed or inaccessible copies raise an artifact-specific
422. Cancellation drains file I/O before the enclosing lease is released.
"""
from deerflow.sandbox.artifact_snapshot import verify_snapshot
from deerflow.utils.file_io import run_file_io
try:
async with AsyncExitStack() as temporary:
# A run retains its remote client through execution: releasing it
# after preflight could let the provider recycle the verified VM.
sandbox = await (lifetime or temporary).enter_async_context(snapshot_sandbox(request, user_id, thread_id))
for receipt in receipts:
data = await run_file_io(_read_host_snapshot, user_id, thread_id, receipt["filename"], "uploads")
if len(data) != receipt["size"] or hashlib.sha256(data).hexdigest() != receipt["sha256"]:
raise AgentRunError(422, "Imported copy changed")
if sandbox is not None:
await run_file_io(verify_snapshot, sandbox, receipt["filename"], receipt["sha256"], receipt["size"])
except (AgentRunError, OSError) as exc:
raise AgentRunError(422, "Attached artifact copy is unavailable or changed; inspect the team artifacts and send a new request") from exc
def read_output_snapshot(user_id: str, thread_id: str, path: str, *, max_bytes: int = MAX_BYTES) -> bytes:
"""Read bounded host output bytes without following links.
Non-output paths raise HTTP 400; unsafe files raise 422 and mutation during
capture raises 409. Run filesystem work off the event loop.
"""
if os.name != "posix" or not isinstance(path, str): if os.name != "posix" or not isinstance(path, str):
raise AgentRunError(422, "Output capture requires POSIX and an output path") raise AgentRunError(422, "Output capture requires POSIX and an output path")
path = normalize_outputs_virtual_path(path) path = normalize_outputs_virtual_path(path)
return _read_host_snapshot(user_id, thread_id, path.removeprefix("/mnt/user-data/outputs/"), "outputs", max_bytes=max_bytes)
def _read_host_snapshot(user_id: str, thread_id: str, path: str, area: str, *, max_bytes: int = MAX_BYTES) -> bytes:
paths = get_paths() paths = get_paths()
root = paths.base_dir.resolve() root = paths.base_dir.resolve()
base = paths.sandbox_outputs_dir(thread_id, user_id=user_id) if area == "outputs" else paths.sandbox_uploads_dir(thread_id, user_id=user_id) relative = paths.sandbox_outputs_dir(thread_id, user_id=user_id).relative_to(paths.base_dir)
relative = base.relative_to(paths.base_dir) parts = (*relative.parts, *path.removeprefix("/mnt/user-data/outputs/").split("/"))
parts = (*relative.parts, *path.split("/"))
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
try: try:
for part in parts[:-1]: for part in parts[:-1]:
@ -247,11 +28,11 @@ def _read_host_snapshot(user_id: str, thread_id: str, path: str, area: str, *, m
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
with os.fdopen(fd, "rb") as source: with os.fdopen(fd, "rb") as source:
before = os.fstat(source.fileno()) before = os.fstat(source.fileno())
if not stat.S_ISREG(before.st_mode) or before.st_size > max_bytes or before.st_nlink != 1: if not stat.S_ISREG(before.st_mode) or before.st_size > MAX_BYTES:
raise AgentRunError(422, "Artifact must be a regular, unlinked file within the capture limit") raise AgentRunError(422, "Artifact must be a regular file of at most 2 MiB")
content = source.read(max_bytes + 1) content = source.read(MAX_BYTES + 1)
after = os.fstat(source.fileno()) after = os.fstat(source.fileno())
if len(content) > max_bytes or (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns): if len(content) > MAX_BYTES or (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns):
raise AgentRunError(409, "Artifact changed during capture") raise AgentRunError(409, "Artifact changed during capture")
return content return content
except OSError as exc: except OSError as exc:

View File

@ -8,6 +8,7 @@ single-purpose modules so each piece can be tested in isolation:
* :mod:`prompts` — payload → user prompt strings. * :mod:`prompts` — payload → user prompt strings.
* :mod:`registry` — scan custom agents and index them by (repo, event). * :mod:`registry` — scan custom agents and index them by (repo, event).
* :mod:`app_auth` — GitHub App JWT and installation-token minting. * :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:`run_policy` — ChannelRunPolicy entry registered into ChannelManager.
* :mod:`dispatcher` — orchestrates all of the above and creates a langgraph run. * :mod:`dispatcher` — orchestrates all of the above and creates a langgraph run.
@ -16,5 +17,8 @@ of this package.
""" """
# Side-effect import: registers the GitHub channel's ChannelRunPolicy # Side-effect import: registers the GitHub channel's ChannelRunPolicy
# so the manager and tests find it before the first delivery. # (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.
from app.gateway.github import run_policy # noqa: F401 from app.gateway.github import run_policy # noqa: F401

View File

@ -16,12 +16,6 @@ installation id, with a 55-minute TTL so we refresh well before the
60-minute GitHub limit. If two webhook deliveries land within a few 60-minute GitHub limit. If two webhook deliveries land within a few
seconds we'll mint two tokens — that's fine and well under any seconds we'll mint two tokens — that's fine and well under any
rate limit. rate limit.
Building the App JWT reads the private key and signs with it, so the
async mint runs it in a worker thread. Parsing a PEM key is the costly
step (tens of ms for RSA-2048, holding the GIL, so a worker thread alone
would still stall the event loop), so the parsed key is reused for as
long as the configured PEM text stays the same.
""" """
from __future__ import annotations from __future__ import annotations
@ -29,11 +23,9 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
import os import os
import threading
import time import time
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any
import httpx import httpx
import jwt import jwt
@ -75,12 +67,6 @@ _install_locks: dict[int, asyncio.Lock] = {}
# insert the per-installation lock, never while we hold one. # insert the per-installation lock, never while we hold one.
_install_locks_lock = asyncio.Lock() _install_locks_lock = asyncio.Lock()
# The most recently parsed App private key, as ``(pem_text, key)``. A
# changed PEM (a rotated env var or key file) is parsed again on the next
# mint. The lock keeps concurrent worker-thread mints from parsing twice.
_signing_key: tuple[str, Any] | None = None
_signing_key_lock = threading.Lock()
async def _lock_for(installation_id: int) -> asyncio.Lock: async def _lock_for(installation_id: int) -> asyncio.Lock:
"""Return the lock dedicated to ``installation_id``, creating on demand.""" """Return the lock dedicated to ``installation_id``, creating on demand."""
@ -128,24 +114,6 @@ def load_app_private_key() -> str:
return p.read_text(encoding="utf-8") return p.read_text(encoding="utf-8")
def _app_signing_key() -> Any:
"""Return the App private key ready for RS256, parsing it only when it changed.
The PEM is still read on every call, so a rotated key is used by the
next mint without a restart.
"""
global _signing_key
pem = load_app_private_key()
with _signing_key_lock:
cached = _signing_key
if cached is not None and cached[0] == pem:
return cached[1]
# Same parsing (and the same errors) as passing the PEM to jwt.encode.
key = jwt.get_algorithm_by_name("RS256").prepare_key(pem)
_signing_key = (pem, key)
return key
def mint_app_jwt(*, now: float | None = None) -> str: def mint_app_jwt(*, now: float | None = None) -> str:
"""Sign a short-lived JWT identifying this App to GitHub. """Sign a short-lived JWT identifying this App to GitHub.
@ -164,7 +132,7 @@ def mint_app_jwt(*, now: float | None = None) -> str:
# numeric App id rendered as a decimal string. # numeric App id rendered as a decimal string.
"iss": str(app_id()), "iss": str(app_id()),
} }
return jwt.encode(payload, _app_signing_key(), algorithm="RS256") return jwt.encode(payload, load_app_private_key(), algorithm="RS256")
async def _request_new_installation_token( async def _request_new_installation_token(
@ -173,10 +141,8 @@ async def _request_new_installation_token(
client: httpx.AsyncClient | None = None, client: httpx.AsyncClient | None = None,
) -> _CachedToken: ) -> _CachedToken:
"""Hit ``POST /app/installations/{id}/access_tokens`` once.""" """Hit ``POST /app/installations/{id}/access_tokens`` once."""
# Reading the key file and signing are blocking; keep them off the loop.
app_jwt = await asyncio.to_thread(mint_app_jwt)
headers = { headers = {
"Authorization": f"Bearer {app_jwt}", "Authorization": f"Bearer {mint_app_jwt()}",
"Accept": "application/vnd.github+json", "Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28", "X-GitHub-Api-Version": "2022-11-28",
} }
@ -258,11 +224,6 @@ async def mint_installation_token(
def _clear_token_cache_for_tests() -> None: def _clear_token_cache_for_tests() -> None:
"""Drop every cached token and the parsed key. Tests reach for this between cases.""" """Drop every cached token. Tests reach for this between cases."""
global _signing_key
_token_cache.clear() _token_cache.clear()
_install_locks.clear() _install_locks.clear()
# Under the lock, so a mint parsing in a worker thread finishes first
# instead of storing its key after the reset.
with _signing_key_lock:
_signing_key = None

View File

@ -32,7 +32,7 @@ from app.channels.message_bus import InboundMessage, InboundMessageType, Message
from app.gateway.github.identity import extract_target, resolve_thread_id from app.gateway.github.identity import extract_target, resolve_thread_id
from app.gateway.github.prompts import build_prompt from app.gateway.github.prompts import build_prompt
from app.gateway.github.registry import build_github_agent_registry, lookup_agents from app.gateway.github.registry import build_github_agent_registry, lookup_agents
from app.gateway.github.triggers import event_should_fire, is_actor_authorized from app.gateway.github.triggers import event_should_fire
from deerflow.config.agents_config import GitHubAgentConfig, GitHubTriggerConfig from deerflow.config.agents_config import GitHubAgentConfig, GitHubTriggerConfig
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -240,8 +240,7 @@ async def fanout_event(
fired: list[str] = [] fired: list[str] = []
skipped: list[dict[str, str]] = [] skipped: list[dict[str, str]] = []
raw_sender = payload.get("sender") sender_login = (payload.get("sender") or {}).get("login")
sender_login = raw_sender.get("login") if isinstance(raw_sender, dict) and isinstance(raw_sender.get("login"), str) else None
# 3. Redundant review-comment fan-out filter — see # 3. Redundant review-comment fan-out filter — see
# :func:`_is_redundant_review_comment`. Whether the PAYLOAD has the # :func:`_is_redundant_review_comment`. Whether the PAYLOAD has the
@ -362,7 +361,7 @@ async def fanout_event(
# useful for operator debugging (PR #4131 review, Minor finding, # useful for operator debugging (PR #4131 review, Minor finding,
# willem-bd). # willem-bd).
review_trigger = review_trigger_by_binding.get((match.user_id, agent.name)) review_trigger = review_trigger_by_binding.get((match.user_id, agent.name))
if is_redundant_review_comment and review_trigger is not None and not review_trigger.require_mention and (not fire or is_actor_authorized(event, payload, review_trigger)[0]): if is_redundant_review_comment and review_trigger is not None and not review_trigger.require_mention:
skip_reason = reason if not fire else "redundant_review_comment" skip_reason = reason if not fire else "redundant_review_comment"
logger.info( logger.info(
"github_fanout: agent=%s skipped (reason=%s, repo=%s#%s, delivery=%s)", "github_fanout: agent=%s skipped (reason=%s, repo=%s#%s, delivery=%s)",

View File

@ -9,8 +9,12 @@ Design notes:
("review this PR"), so the agent's SOUL.md gets to define behavior. ("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 The dispatcher appends one terse instruction at the end so a stock
``lead_agent`` SOUL still does something useful. ``lead_agent`` SOUL still does something useful.
* The channel logs the final message. GitHub actions during the run use * The channel layer is **log-only on the outbound path** — the agent's
GitHub tools configured for the agent. 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.
* We embed the comment body verbatim because that's the most useful * We embed the comment body verbatim because that's the most useful
signal — the agent needs to see what the human actually typed. We signal — the agent needs to see what the human actually typed. We
do not try to escape it; agents understand markdown. do not try to escape it; agents understand markdown.
@ -47,9 +51,10 @@ def _pull_request_prompt(payload: dict[str, Any]) -> str:
f" Author: {author}\n" f" Author: {author}\n"
f" URL: {url}\n\n" f" URL: {url}\n\n"
f"Description:\n{body or '(no description)'}\n\n" f"Description:\n{body or '(no description)'}\n\n"
"Decide what action (if any) to take in response to this event. " f"Decide what action (if any) to take for this pull request and carry it out. "
"Your final assistant message goes to the run log. " f"Your final assistant message is for the run log only — it will NOT be "
"Use a configured GitHub tool for actions that require repository access." 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."
) )
@ -86,9 +91,10 @@ def _issue_comment_prompt(payload: dict[str, Any]) -> str:
f" Author: {author}\n" f" Author: {author}\n"
f" URL: {url}\n\n" f" URL: {url}\n\n"
f" Body:\n{body or '(empty comment)'}\n\n" f" Body:\n{body or '(empty comment)'}\n\n"
"Decide what action (if any) to take in response to this event. " f"Decide what action (if any) to take in response to this comment, in the context "
"Your final assistant message goes to the run log. " f"of the parent {target} above. Your final assistant message is for the run log "
"Use a configured GitHub tool for actions that require repository access." 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."
) )
@ -111,9 +117,10 @@ def _pr_review_comment_prompt(payload: dict[str, Any]) -> str:
f" File: {path}:{line}\n\n" f" File: {path}:{line}\n\n"
f" Diff context:\n```\n{diff_hunk}\n```\n\n" f" Diff context:\n```\n{diff_hunk}\n```\n\n"
f" Body:\n{body or '(empty comment)'}\n\n" f" Body:\n{body or '(empty comment)'}\n\n"
"Decide what action (if any) to take in response to this event. " f"Decide what action (if any) to take in response to this review comment, in the "
"Your final assistant message goes to the run log. " f"context of the parent pull request above. Your final assistant message is for the "
"Use a configured GitHub tool for actions that require repository access." 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."
) )
@ -142,7 +149,7 @@ def _pr_review_prompt(payload: dict[str, Any]) -> str:
# instruction never renders a broken `gh api` path. # instruction never renders a broken `gh api` path.
fetch_hint = "" fetch_hint = ""
if review_id is not None and number is not None: 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, use a configured GitHub tool to fetch them from `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, fetch them with `gh api repos/{repo}/pulls/{number}/reviews/{review_id}/comments`.\n\n"
return ( return (
f"A pull request review was submitted on #{number} in {repo}.\n\n" f"A pull request review was submitted on #{number} in {repo}.\n\n"
f"{parent_block}\n" f"{parent_block}\n"
@ -151,9 +158,12 @@ def _pr_review_prompt(payload: dict[str, Any]) -> str:
f" State: {state}\n\n" f" State: {state}\n\n"
f" Body:\n{body or '(no review body)'}\n\n" f" Body:\n{body or '(no review body)'}\n\n"
f"{fetch_hint}" f"{fetch_hint}"
"Decide what action (if any) to take in response to this event. " f"Decide what action (if any) to take in response to this review, in the context "
"Your final assistant message goes to the run log. " f"of the parent pull request above. Your final assistant message is for the run "
"Use a configured GitHub tool for actions that require repository access." 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."
) )
@ -172,9 +182,11 @@ def _issues_prompt(payload: dict[str, Any]) -> str:
f" Author: {author}\n" f" Author: {author}\n"
f" URL: {url}\n\n" f" URL: {url}\n\n"
f"Description:\n{body or '(no description)'}\n\n" f"Description:\n{body or '(no description)'}\n\n"
"Decide what action (if any) to take in response to this event. " f"Decide what action (if any) to take for this issue and carry it out. "
"Your final assistant message goes to the run log. " f"Your final assistant message is for the run log only — it will NOT be "
"Use a configured GitHub tool for actions that require repository access." 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."
) )

View File

@ -95,7 +95,7 @@ def _build_index(agents: list[tuple[str, AgentConfig]]) -> _Registry:
# it is here, so this branch is unreachable. Keep the # it is here, so this branch is unreachable. Keep the
# guard for type-checker happiness. # guard for type-checker happiness.
continue continue
index.setdefault((binding.repo.lower(), event), []).append(GitHubAgentMatch(user_id=user_id, agent=cfg, trigger=resolved)) index.setdefault((binding.repo, event), []).append(GitHubAgentMatch(user_id=user_id, agent=cfg, trigger=resolved))
return index return index
@ -145,4 +145,4 @@ def lookup_agents(
and the pre-resolved trigger config for this specific event, so the and the pre-resolved trigger config for this specific event, so the
caller does not need to walk the agent's ``bindings`` again. caller does not need to walk the agent's ``bindings`` again.
""" """
return registry.get((repo.lower(), event), []) return registry.get((repo, event), [])

View File

@ -1,7 +1,92 @@
"""Per-run policy for inbound GitHub events.""" """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.
"""
from __future__ import annotations 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: def register_policy() -> None:
"""Register the GitHub channel's :class:`ChannelRunPolicy` entry. """Register the GitHub channel's :class:`ChannelRunPolicy` entry.
@ -25,6 +110,7 @@ def register_policy() -> None:
# Per-agent overrides via GitHubAgentConfig.recursion_limit still # Per-agent overrides via GitHubAgentConfig.recursion_limit still
# win (read in ChannelManager._resolve_run_params from msg.metadata). # win (read in ChannelManager._resolve_run_params from msg.metadata).
default_recursion_limit=250, default_recursion_limit=250,
credentials_provider=inject_github_credentials,
# GitHub deliveries are HMAC-authenticated at the webhook route, # GitHub deliveries are HMAC-authenticated at the webhook route,
# and the binding from "sender" to DeerFlow user is encoded in # and the binding from "sender" to DeerFlow user is encoded in
# the agent's config.yaml ownership (not in the channel-connections # the agent's config.yaml ownership (not in the channel-connections
@ -33,8 +119,9 @@ def register_policy() -> None:
# the agent even when channel_connections.enabled=True for # the agent even when channel_connections.enabled=True for
# interactive IM channels in the same deployment. # interactive IM channels in the same deployment.
requires_bound_identity=False, requires_bound_identity=False,
# GitHub agents use configured tools for outbound actions. The # GitHub agents post their own outbound to the issue/PR via the
# channel's ``send`` is log-only by design. We don't need to keep an HTTP stream open on # ``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
# ``runs.wait`` for ~6-minute coding runs and then watch it die # ``runs.wait`` for ~6-minute coding runs and then watch it die
# at the SDK's 300s ``httpx.ReadTimeout``. Fire-and-forget swaps # at the SDK's 300s ``httpx.ReadTimeout``. Fire-and-forget swaps
# the manager call to ``runs.create`` (returns immediately once # the manager call to ``runs.create`` (returns immediately once
@ -43,7 +130,7 @@ def register_policy() -> None:
# still raised synchronously by ``start_run`` before the run is # still raised synchronously by ``start_run`` before the run is
# accepted, so the busy-thread path is preserved. # accepted, so the busy-thread path is preserved.
fire_and_forget=True, fire_and_forget=True,
# GitHub's ``send`` is log-only, # GitHub's ``send`` is log-only (agents post via ``gh`` themselves),
# so a busy-thread ``THREAD_BUSY_MESSAGE`` is otherwise invisible to # so a busy-thread ``THREAD_BUSY_MESSAGE`` is otherwise invisible to
# the commenter — a concurrent comment is silently dropped from # the commenter — a concurrent comment is silently dropped from
# their point of view (issue #4121). Buffering + draining follow-ups # their point of view (issue #4121). Buffering + draining follow-ups

View File

@ -64,87 +64,34 @@ def _comment_body(event: str, payload: dict[str, Any]) -> str:
``pull_request_review`` the body is the review summary. Other events ``pull_request_review`` the body is the review summary. Other events
have no user-authored text to mention-check and return ``""``. have no user-authored text to mention-check and return ``""``.
""" """
authored = _authored_object(event, payload) if event in ("issue_comment", "pull_request_review_comment"):
if authored is None: body = (payload.get("comment") or {}).get("body")
return ""
body = authored.get("body")
return body if isinstance(body, str) else "" return body if isinstance(body, str) else ""
if event == "issues":
body = (payload.get("issue") or {}).get("body")
return body if isinstance(body, str) else ""
if event == "pull_request":
body = (payload.get("pull_request") or {}).get("body")
return body if isinstance(body, str) else ""
if event == "pull_request_review":
body = (payload.get("review") or {}).get("body")
return body if isinstance(body, str) else ""
return ""
def _author_login(event: str, payload: dict[str, Any]) -> str | None: def _author_login(event: str, payload: dict[str, Any]) -> str | None:
"""Login of the webhook ``sender`` who triggered the event.""" """Login of the human who triggered the event, for ``allow_authors``."""
del event
sender = payload.get("sender")
if not isinstance(sender, dict):
return None
sender_login = sender.get("login")
if isinstance(sender_login, str) and sender_login.strip():
return sender_login.strip()
return None
def _authored_object(event: str, payload: dict[str, Any]) -> dict[str, Any] | None:
if event in ("issue_comment", "pull_request_review_comment"): if event in ("issue_comment", "pull_request_review_comment"):
authored = payload.get("comment") login = (payload.get("comment") or {}).get("user", {}).get("login")
elif event == "pull_request": elif event == "pull_request":
authored = payload.get("pull_request") login = (payload.get("pull_request") or {}).get("user", {}).get("login")
elif event == "pull_request_review": elif event == "pull_request_review":
authored = payload.get("review") login = (payload.get("review") or {}).get("user", {}).get("login")
elif event == "issues": elif event == "issues":
authored = payload.get("issue") login = (payload.get("issue") or {}).get("user", {}).get("login")
else: else:
return None login = (payload.get("sender") or {}).get("login")
return authored if isinstance(authored, dict) else None return login if isinstance(login, str) else None
def _author_association(event: str, payload: dict[str, Any]) -> str | None:
"""Return the GitHub ``author_association`` attributable to the actor.
GitHub attaches ``author_association`` to the authored object rather than
``sender``. Require a valid ``sender.login`` and only accept the object's
association when ``sender.login`` matches the object's ``user.login``
(case-insensitively), so missing/null senders fail closed and a different
actor editing or labeling an owner's issue/PR/comment never inherits the
owner's association.
"""
authored = _authored_object(event, payload)
if authored is None:
return None
sender_login = _author_login(event, payload)
authored_user = authored.get("user")
authored_login = authored_user.get("login") if isinstance(authored_user, dict) else None
if not sender_login or not isinstance(authored_login, str) or not authored_login.strip():
return None
if sender_login.lower() != authored_login.strip().lower():
return None
raw = authored.get("author_association")
if not isinstance(raw, str):
return None
normalized = raw.strip().upper()
return normalized or None
def is_actor_authorized(
event: str,
payload: dict[str, Any],
trigger: GitHubTriggerConfig,
) -> tuple[bool, bool, str | None, str | None]:
"""Evaluate fail-closed actor authorization for ``trigger``.
Returns ``(authorized, matched_allow_authors, author, association)``.
"""
if event == "ping":
return True, False, None, None
author = _author_login(event, payload)
allowed_authors = {entry.strip().lower() for entry in trigger.allow_authors if entry.strip()}
if author and author.lower() in allowed_authors:
return True, True, author, None
association = _author_association(event, payload)
allowed_associations = {entry.strip().upper() for entry in trigger.allow_author_associations if entry.strip()}
if association and association in allowed_associations:
return True, False, author, association
return False, False, author, association
def _resolved_trigger( def _resolved_trigger(
@ -172,12 +119,12 @@ def _resolved_trigger(
default = DEFAULT_TRIGGERS.get(event) default = DEFAULT_TRIGGERS.get(event)
if default is None: if default is None:
return override.model_copy(deep=True) return override
# Field-wise merge: take fields the binding explicitly set, # Field-wise merge: take fields the binding explicitly set,
# backfill the rest from the per-event default. # backfill the rest from the per-event default.
explicit = override.model_dump(exclude_unset=True) explicit = override.model_dump(exclude_unset=True)
merged = default.model_copy(update=explicit, deep=True) merged = default.model_copy(update=explicit)
return merged return merged
@ -231,15 +178,16 @@ def event_should_fire(
if action not in trigger.actions: if action not in trigger.actions:
return False, f"action={action!r} not in {trigger.actions}" return False, f"action={action!r} not in {trigger.actions}"
# Fail-closed actor authorization for user-authored events: the triggering # allow_authors bypasses require_mention entirely. Useful so a repo
# actor must either appear in ``allow_authors`` (case-insensitive) or carry # owner can talk to the bot without typing the handle every time.
# an ``author_association`` matching ``allow_author_associations`` (default: # Match is case-insensitive — GitHub logins are, and the sibling gates
# OWNER, MEMBER, COLLABORATOR). # in this module already are (``_mentions`` uses re.IGNORECASE; the
authorized, matched_allow_authors, author, association = is_actor_authorized(event, payload, trigger) # self-event check lowercases both sides). A bare ``in`` membership
if not authorized: # test would drop an owner whose YAML casing differs from the payload.
return False, f"unauthorized_author:{author!r} (association={association!r})" if trigger.allow_authors:
if matched_allow_authors and trigger.allow_authors_bypass_mention: author = _author_login(event, payload)
return True, f"allow_authors:{author!r}" if author and author.lower() in {a.lower() for a in trigger.allow_authors}:
return True, f"allow_authors:{author}"
if trigger.require_mention: if trigger.require_mention:
# ``trigger.mention_login`` is normalized (whitespace-only -> None) # ``trigger.mention_login`` is normalized (whitespace-only -> None)

View File

@ -33,8 +33,8 @@ process-local backend (``memory``) has nothing to probe and reports
unreachable. Connection-opening probes are serialized behind strict unreachable. Connection-opening probes are serialized behind strict
per-process gates, one per probe kind: the route is public through the per-process gates, one per probe kind: the route is public through the
``/health`` auth prefix, so unlimited concurrent requests must never translate ``/health`` auth prefix, so unlimited concurrent requests must never translate
into unlimited new PostgreSQL connections, an ORM or Redis pool held by probe into unlimited new PostgreSQL connections, Redis pool growth or a connection
traffic or a connection flood at the provisioner. flood at the provisioner.
""" """
from __future__ import annotations from __future__ import annotations
@ -51,7 +51,6 @@ from sqlalchemy import text
from deerflow.persistence.engine import get_engine from deerflow.persistence.engine import get_engine
from deerflow.utils.file_io import await_drained from deerflow.utils.file_io import await_drained
from deerflow.utils.http_policy import control_plane_trust_env
if TYPE_CHECKING: if TYPE_CHECKING:
from deerflow.config.app_config import AppConfig from deerflow.config.app_config import AppConfig
@ -123,20 +122,12 @@ PROBE_UNREACHABLE = "unreachable"
async def check_database_health() -> str: async def check_database_health() -> str:
"""Probe the persistence engine; return one of the PROBE_* values. """Probe the persistence engine; return one of the PROBE_* values."""
The probe checks a connection out of the application's own engine pool,
the one every repository uses. Probes are serialized so unauthenticated
probe traffic holds at most one of those connections per process instead
of the whole pool, which would leave request handlers waiting for
database connections.
"""
engine = get_engine() engine = get_engine()
if engine is None: if engine is None:
# backend=memory, or the engine has not been initialized yet: there is # backend=memory, or the engine has not been initialized yet: there is
# no database to probe. # no database to probe.
return PROBE_NOT_CONFIGURED return PROBE_NOT_CONFIGURED
async with _probe_gate("database"):
try: try:
async with asyncio.timeout(_PROBE_TIMEOUT_SECONDS): async with asyncio.timeout(_PROBE_TIMEOUT_SECONDS):
async with engine.connect() as connection: async with engine.connect() as connection:
@ -322,7 +313,10 @@ def _make_provisioner_client(provisioner_url: str) -> httpx.AsyncClient:
``NO_PROXY``, so without this a private provisioner behind a proxy-only ``NO_PROXY``, so without this a private provisioner behind a proxy-only
egress would be reported unreachable on every probe. egress would be reported unreachable on every probe.
""" """
return httpx.AsyncClient(timeout=_PROBE_TIMEOUT_SECONDS, trust_env=control_plane_trust_env(provisioner_url)) # Lazy: importing the aio_sandbox package pulls in the whole provider stack.
from deerflow.community.aio_sandbox.backend import sandbox_http_trust_env
return httpx.AsyncClient(timeout=_PROBE_TIMEOUT_SECONDS, trust_env=sandbox_http_trust_env(provisioner_url))
async def _probe_provisioner(provisioner_url: str | None) -> str: async def _probe_provisioner(provisioner_url: str | None) -> str:

View File

@ -1,74 +0,0 @@
"""Host-authorized history copies under durable thread-operation admission."""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from fastapi import Request
from app.gateway.deps import get_run_manager, get_thread_store
from app.gateway.internal_auth import get_trusted_internal_owner_user_id
from deerflow.persistence.run.sql import RunRepository
from deerflow.persistence.thread_meta.sql import ThreadMetaRepository
from deerflow.runtime.events.producer import RunEventProducerRejected, history_seed_authority, producer_scope
from deerflow.runtime.events.store.db import DbRunEventStore
from deerflow.runtime.runs.manager import RunRecord
from deerflow.runtime.runs.schemas import ThreadOperationKind
@dataclass(frozen=True)
class HistorySeedReservation:
record: RunRecord
thread: dict | None
@asynccontextmanager
async def reserve_history_seed(request: Request, thread_id: str) -> AsyncIterator[HistorySeedReservation | None]:
"""Keep snapshot reads and seed writes exclusive with delete and admission."""
events = request.app.state.run_event_store
manager = getattr(request.app.state, "run_manager", None)
runs = getattr(manager, "_store", None)
threads = getattr(request.app.state, "thread_store", None)
if not isinstance(events, DbRunEventStore):
yield None
return
if not isinstance(runs, RunRepository) or not isinstance(threads, ThreadMetaRepository):
if events._producer_fencing == "strict":
raise RunEventProducerRejected("History seeding requires shared SQL lifecycle stores")
yield None
return
if runs._sf.kw.get("bind") is not events._sf.kw.get("bind") or threads._sf.kw.get("bind") is not events._sf.kw.get("bind"):
raise RunEventProducerRejected("History seeding requires shared SQL lifecycle stores")
async with get_run_manager(request).reserve_thread_operation(
thread_id,
kind=ThreadOperationKind.checkpoint_write,
user_id=get_trusted_internal_owner_user_id(request),
) as reservation:
yield HistorySeedReservation(reservation, await threads.get(thread_id, user_id=None))
async def write_history_seed(
request: Request,
events: list[dict],
*,
reservation: HistorySeedReservation | None,
seed_kind: str,
thread: dict | None = None,
assistant_id: str | None = None,
) -> None:
store = request.app.state.run_event_store
if reservation is None:
await store.put_batch(events)
return
if thread is None:
# Only the checkpoint migration may materialize missing legacy metadata.
# The caller read that checkpoint while holding this same reservation.
if seed_kind != "checkpoint":
raise RunEventProducerRejected("Branch seeding requires its original thread identity")
threads = get_thread_store(request)
thread = reservation.thread
if thread is None:
thread = await threads.create(reservation.record.thread_id, assistant_id=assistant_id, user_id=reservation.record.user_id)
authority = history_seed_authority(reservation.record, thread, seed_kind=seed_kind)
with producer_scope(authority):
await store.put_batch(events)

View File

@ -1,351 +0,0 @@
"""Server-side validation for HITL tool-approval resume and admission.
All checks live here (called from ``services.start_run``) so every entry point
— HTTP routes, extension host, internal launchers — shares one choke point.
"""
from __future__ import annotations
import logging
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
from fastapi import HTTPException
from app.gateway.checkpoint_lineage import hitl_approval_payloads
from deerflow.approvals.protocol import combine_approval_payloads
from deerflow.runtime.checkpoint_history import recent_checkpoint_history
logger = logging.getLogger(__name__)
class ApprovalRequestIds(dict):
"""Identity map plus the validated LangGraph interrupt-ID resume map."""
resume_map: dict | None = None
if TYPE_CHECKING:
from deerflow.runtime.runs.manager import ApprovalAnswerHandle
def _error(status: int, code: str, message: str) -> HTTPException:
return HTTPException(status_code=status, detail={"code": code, "message": message})
def _responses_of(command: Any) -> list[Any] | None:
if not isinstance(command, Mapping):
return None
resume = command.get("resume")
if not isinstance(resume, Mapping):
return None
responses = resume.get("responses")
return responses if isinstance(responses, list) else None
def _all_reject(responses: list[Any] | None) -> bool:
return bool(responses) and all(isinstance(r, Mapping) and r.get("option_id") == "reject" for r in responses)
async def has_any_pending_interrupt(accessor: Any, read_config: dict[str, Any]) -> bool:
"""Whether a recent checkpoint has an unconsumed interrupt write.
Used for generic (non-hitl) resume admission where snapshot.next may be
empty after a head-moving write. The newest resume/interrupt marker wins,
so an answered pause cannot be resurrected by its older interrupt write.
"""
async for checkpoint in recent_checkpoint_history(accessor.checkpointer, read_config):
writes = list(getattr(checkpoint, "pending_writes", ()) or ())
if any(len(write) >= 2 and write[1] == "__resume__" for write in writes):
return False
if any(len(write) >= 2 and write[1] == "__interrupt__" for write in writes):
return True
return False
async def _pending_interrupts_from_checkpoint_history(checkpointer: Any, read_config: dict[str, Any]) -> dict[str, list[Any]]:
"""Read pending interrupts without materializing a graph state snapshot."""
async for checkpoint in recent_checkpoint_history(checkpointer, read_config):
writes = list(getattr(checkpoint, "pending_writes", ()) or ())
if any(len(write) >= 2 and write[1] == "__resume__" for write in writes):
return {}
interrupt_writes = [write for write in writes if len(write) >= 3 and write[1] == "__interrupt__"]
if not interrupt_writes:
continue
grouped: dict[str, list[Any]] = {}
for write in interrupt_writes:
interrupts = write[2] if isinstance(write[2], (list, tuple)) else (write[2],)
grouped.setdefault(str(write[0]), []).extend(interrupts)
return grouped
return {}
async def has_waiting_for_input_run(request: Any, thread_id: str) -> bool:
"""Whether any run in the thread is paused for input (any interrupt kind)."""
from app.gateway.deps import get_run_store
try:
run_store = get_run_store(request)
except (HTTPException, AttributeError) as exc:
if isinstance(exc, AttributeError) or exc.status_code == 503:
return False
raise
runs = await run_store.list_by_thread(thread_id, limit=5)
return any(run.get("status") == "waiting_for_input" for run in runs)
async def mark_approval_answered(request: Any, thread_id: str, *, expected_request_ids: dict[str, str] | None = None) -> ApprovalAnswerHandle | None:
"""Mark the validated paused run as answered and return its recovery handle."""
from app.gateway.deps import get_run_manager, get_run_store
try:
run_manager = get_run_manager(request)
except (HTTPException, AttributeError) as exc:
if isinstance(exc, HTTPException) and exc.status_code != 503:
raise
# Lightweight compositions may provide only a store. Keep their
# persistence on RunManager's retry and in-memory mutation path too.
from deerflow.runtime import RunManager
try:
run_manager = RunManager(store=get_run_store(request))
except (HTTPException, AttributeError) as store_exc:
if isinstance(store_exc, AttributeError) or store_exc.status_code == 503:
return None
raise
return await run_manager.mark_approval_answered(thread_id, expected_request_ids=expected_request_ids)
async def _interrupt_from_checkpoint_history(accessor: Any, read_config: dict[str, Any], payload: dict[str, Any]) -> tuple[str, Any] | None:
"""Recover the original LangGraph task identity after the head has moved."""
if accessor is None:
return None
if getattr(accessor, "checkpointer", None) is None:
return None
async for checkpoint in recent_checkpoint_history(accessor.checkpointer, read_config):
writes = list(getattr(checkpoint, "pending_writes", ()) or ())
if any(len(write) >= 2 and write[1] == "__resume__" for write in writes):
return None
for write in writes:
if len(write) < 3 or write[1] != "__interrupt__":
continue
interrupts = write[2] if isinstance(write[2], (list, tuple)) else (write[2],)
for pending_interrupt in interrupts:
if getattr(pending_interrupt, "value", None) == payload:
return str(write[0]), pending_interrupt
return None
async def find_pending_interrupts(
request: Any,
thread_id: str,
*,
accessor: Any = None,
read_config: dict[str, Any] | None = None,
snapshot: Any = None,
) -> dict[str, list[Any]]:
"""Find pending interrupts from an existing snapshot or raw checkpoints.
The live snapshot catches a pause before the worker has finalized the run;
raw pending writes cover head-moving writes and restricted mutation graphs;
the durable run record remains the final fallback.
"""
from langgraph.types import Interrupt
from app.gateway.checkpoint_lineage import task_interrupts_by_id
from app.gateway.deps import get_checkpointer, get_run_store
if snapshot is None and accessor is not None and read_config is not None:
snapshot = await accessor.aget(read_config)
if snapshot is not None:
grouped = task_interrupts_by_id(snapshot)
if grouped:
return grouped
try:
run_store = get_run_store(request)
except (HTTPException, AttributeError) as exc:
if not isinstance(exc, AttributeError) and exc.status_code != 503:
raise
runs = []
else:
runs = await run_store.list_by_thread(thread_id, limit=10)
# A current loop snapshot is authoritative for ordinary polling. Update
# checkpoints can have moved the head past an unconsumed interrupt, and
# checkpoint-only compositions have no snapshot: retain recovery for both.
if (
snapshot is not None
and (getattr(snapshot, "metadata", None) or {}).get("source") == "loop"
and (getattr(snapshot, "config", None) or {}).get("configurable", {}).get("checkpoint_id")
and not (read_config or {}).get("configurable", {}).get("checkpoint_id")
and not any(run.get("status") == "waiting_for_input" for run in runs)
):
return {}
checkpointer = getattr(accessor, "checkpointer", None)
if checkpointer is None:
try:
checkpointer = get_checkpointer(request)
except (HTTPException, AttributeError) as exc:
if not isinstance(exc, AttributeError) and exc.status_code != 503:
raise
if checkpointer is not None:
grouped = await _pending_interrupts_from_checkpoint_history(
checkpointer,
read_config or {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}},
)
if grouped:
return grouped
for run in runs:
if run.get("status") != "waiting_for_input":
continue
payload = (run.get("metadata") or {}).get("hitl_approval")
if payload:
recovered = await _interrupt_from_checkpoint_history(accessor, read_config, payload) if read_config is not None else None
if recovered is not None:
task_id, pending_interrupt = recovered
return {task_id: [pending_interrupt]}
task_id = run.get("run_id") or "approval"
return {task_id: [Interrupt(value=payload, id=payload.get("request_id", task_id))]}
return {}
def _approval_request_ids(payload: dict[str, Any]) -> dict[str, str]:
"""Extract and validate the action identity binding for one HITL pause."""
expected_ids = payload.get("pending_tool_call_ids")
if not isinstance(expected_ids, list) or any(not isinstance(call_id, str) for call_id in expected_ids) or len(set(expected_ids)) != len(expected_ids):
raise _error(422, "invalid_approval_response", "pending approval has invalid tool_call_ids")
expected_set = set(expected_ids)
actions = payload.get("actions")
if not isinstance(actions, list):
raise _error(422, "invalid_approval_response", "pending approval has invalid actions")
expected_request_ids: dict[str, str] = {}
for action in actions:
if not isinstance(action, Mapping):
raise _error(422, "invalid_approval_response", "pending approval has invalid actions")
call_id = action.get("tool_call_id")
request_id = action.get("request_id")
if not isinstance(call_id, str) or call_id not in expected_set or call_id in expected_request_ids or not isinstance(request_id, str) or not request_id:
raise _error(422, "invalid_approval_response", "pending approval has invalid actions")
expected_request_ids[call_id] = request_id
if set(expected_request_ids) != expected_set:
raise _error(422, "invalid_approval_response", "pending approval has invalid actions")
return expected_request_ids
async def current_approval_request_ids(
request: Any,
thread_id: str,
*,
accessor: Any,
read_config: dict[str, Any],
) -> dict[str, str] | None:
"""Read the current live pause's identity for checkpoint-only recovery."""
pending = await find_pending_interrupts(request, thread_id, accessor=accessor, read_config=read_config)
payloads = hitl_approval_payloads(pending)
return _approval_request_ids(combine_approval_payloads(payloads)) if payloads else None
async def validate_resume_request(*, request: Any, thread_id: str, accessor: Any, read_config: dict[str, Any], enabled: bool, body: Any) -> dict[str, str] | None:
"""Validate a command.resume against the current pause, or raise 409/422.
Static breakpoints (next non-empty, no approval payload) pass through
unchanged. All-reject remains the escape hatch for the validated pause when
the feature is disabled or the payload was lost; attachment later verifies
that checkpoint-only recovery still targets that same pause.
"""
snapshot = await accessor.aget(read_config)
responses = _responses_of(getattr(body, "command", None))
all_reject = _all_reject(responses)
pending = await find_pending_interrupts(request, thread_id, accessor=accessor, read_config=read_config, snapshot=snapshot)
payloads = hitl_approval_payloads(pending)
has_waiting_run = await has_waiting_for_input_run(request, thread_id)
has_pending_interrupt = await has_any_pending_interrupt(accessor, read_config)
head_checkpoint_id = (getattr(snapshot, "config", None) or {}).get("configurable", {}).get("checkpoint_id")
if not pending and not has_waiting_run and not (getattr(snapshot, "next", None) or ()) and not has_pending_interrupt:
raise _error(409, "no_pending_approval", "No resumable pause exists for this thread")
if not payloads:
return None
if responses is None:
raise _error(422, "invalid_approval_response", "resume must carry a 'responses' list for hitl_approval")
expected_request_ids = ApprovalRequestIds(_approval_request_ids(combine_approval_payloads(payloads)))
action_by_request = {action["request_id"]: action for payload in payloads for action in payload["actions"]}
expected_ids = list(expected_request_ids)
expected_set = set(expected_ids)
if len(responses) != len(expected_ids):
raise _error(422, "invalid_approval_response", f"expected {len(expected_ids)} responses, got {len(responses)}")
seen_ids: set[str] = set()
for response in responses:
if not isinstance(response, Mapping):
raise _error(422, "invalid_approval_response", "each response must be an object")
response_id = response.get("tool_call_id")
if not isinstance(response_id, str) or response_id not in expected_set:
raise _error(422, "invalid_approval_response", "unknown tool_call_id")
if response.get("request_id") != expected_request_ids[response_id]:
raise _error(422, "invalid_approval_response", "stale or mismatched request_id")
if response_id in seen_ids:
raise _error(422, "invalid_approval_response", "duplicate tool_call_id")
seen_ids.add(response_id)
action = action_by_request[response["request_id"]]
supported = ("approve", "reject", "edit", "approve_thread") if all(payload.get("version") == 2 for payload in payloads) else ("approve", "reject")
if response.get("option_id") not in supported:
raise _error(422, "invalid_approval_response", f"unsupported option_id; expected one of {', '.join(repr(option) for option in supported)}")
if response.get("option_id") == "approve_thread" and not action.get("grant_allowed"):
raise _error(422, "invalid_approval_response", "This operation does not permit a thread grant")
if response.get("option_id") == "edit":
from jsonschema import Draft202012Validator
from deerflow.approvals.policy import canonical_json
args, schema = response.get("args"), action.get("args_schema")
try:
limit = min(payload.get("max_payload_bytes", 512 * 1024) for payload in payloads)
if not isinstance(args, dict) or not isinstance(schema, dict) or len(canonical_json(args).encode()) > limit:
raise ValueError("Invalid arguments")
Draft202012Validator(schema).validate(args)
if isinstance(schema.get("properties"), dict) and set(args) - set(schema["properties"]):
raise ValueError("Unknown or injected arguments")
except Exception as exc:
raise _error(422, "invalid_approval_arguments", "Edited arguments do not match the tool schema") from exc
if all(payload.get("version") == 2 for payload in payloads):
expected_request_ids.resume_map = {
item.id: {"responses": [response for response in responses if response["request_id"] in {action["request_id"] for action in item.value["actions"]}]}
for interrupts in pending.values()
for item in interrupts
if isinstance(getattr(item, "value", None), dict) and item.value.get("kind") == "hitl_approval"
}
if all_reject:
return expected_request_ids
if not enabled:
raise _error(409, "hitl_approval_disabled", "hitl_approval is currently disabled; resume with all-reject to clear the pause")
requested_checkpoint_id = getattr(body, "checkpoint_id", None)
body_checkpoint = getattr(body, "checkpoint", None)
if requested_checkpoint_id is None and isinstance(body_checkpoint, Mapping):
requested_checkpoint_id = body_checkpoint.get("checkpoint_id")
if requested_checkpoint_id and head_checkpoint_id and str(requested_checkpoint_id) != str(head_checkpoint_id):
raise _error(422, "checkpoint_not_head", "A resume must target the current head checkpoint, never an older pause checkpoint")
return expected_request_ids
async def reject_new_run_when_approval_pending(
request: Any,
thread_id: str,
*,
accessor: Any = None,
read_config: dict[str, Any] | None = None,
) -> None:
"""Reject a brand-new (non-resume) run while an approval is pending.
Without this guard a fresh input silently discards the pending approval
(measured behavior of LangGraph). Internal launchers catch this specific
error code to implement skip-and-retry semantics.
"""
pending = await find_pending_interrupts(request, thread_id, accessor=accessor, read_config=read_config)
if hitl_approval_payloads(pending):
raise _error(409, "approval_pending", "Thread has a pending tool approval; resume or reject it before starting a new run")

View File

@ -1,78 +0,0 @@
"""Bounded, read-only provider catalog retrieval. Never follow credentialed redirects."""
import asyncio
import json
import httpx
from deerflow.config.managed_model_providers import get_managed_model_provider
from deerflow.config.managed_models import ManagedModel
MAX_MODELS = 2000
MAX_BYTES = 2 * 1024 * 1024
class DiscoveryError(ValueError):
def __init__(self, code: str):
self.code = code
super().__init__(code)
async def fetch_model_catalog(profile: ManagedModel) -> tuple[list[str], bool]:
provider = get_managed_model_provider(profile.provider)
endpoint = provider.endpoint or profile.base_url
key = profile.api_key.get_secret_value() if profile.api_key else None
native = provider.protocol == "anthropic-messages"
url = endpoint.rstrip("/") + ("/v1/models" if native else "/models")
headers = {"Accept": "application/json", "Accept-Encoding": "identity"}
if native:
headers.update({"x-api-key": key or "", "anthropic-version": "2023-06-01"})
elif key:
headers["Authorization"] = f"Bearer {key}"
# HTTPX constructs TLS trust synchronously; keep that work off the event loop.
client = await asyncio.to_thread(httpx.AsyncClient, timeout=15, follow_redirects=False)
names: set[str] = set()
cursor = None
size = 0
try:
async with asyncio.timeout(20), client:
for _ in range(20):
params = {"limit": 100, **({"after_id": cursor} if cursor else {})} if native else None
async with client.stream("GET", url, headers=headers, params=params) as response:
if response.status_code in (401, 403):
raise DiscoveryError("authentication_failed")
if response.status_code in (404, 405):
raise DiscoveryError("discovery_unsupported")
if response.status_code != 200:
raise DiscoveryError("discovery_failed")
# Reject compression before HTTPX can allocate a decoded
# chunk larger than our response budget.
if response.headers.get("content-encoding", "identity").strip().lower() != "identity":
raise DiscoveryError("discovery_failed")
chunks = []
async for chunk in response.aiter_bytes():
size += len(chunk)
if size > MAX_BYTES:
raise DiscoveryError("response_limit")
chunks.append(chunk)
data = json.loads(b"".join(chunks))
if not isinstance(data, dict) or not isinstance(data.get("data"), list):
raise DiscoveryError("discovery_failed")
for item in data["data"]:
name = item.get("id") if isinstance(item, dict) else None
if not isinstance(name, str) or not name or len(name) > 200 or name != name.strip() or any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in name):
continue
names.add(name)
if len(names) >= MAX_MODELS:
return sorted(names), True
if not native or not data.get("has_more"):
return sorted(names), bool(data.get("has_more"))
next_cursor = data.get("last_id")
if not isinstance(next_cursor, str) or not next_cursor or next_cursor == cursor or len(next_cursor) > 200:
raise DiscoveryError("discovery_failed")
cursor = next_cursor
return sorted(names), True
except DiscoveryError:
raise
except Exception:
raise DiscoveryError("discovery_failed") from None

View File

@ -1,55 +1,100 @@
# Gateway routers (`app/gateway/routers/`) # Router contracts
One module per API area. The parent [Gateway guide](../AGENTS.md) covers trust `GET /api/plugins/diagnostics` uses `require_admin_user` before reading the
boundaries and run admission; this file covers what every route handler has to do. canonical runtime diagnostic snapshot. Return bounded entry-point identifiers,
known levels and fixed summaries; raw messages stay in logs. Never clear the
sink or expand PAT permissions.
## Verify Branch metadata inherits valid `assistant_id` values verbatim. Validate with
`custom_agent_name` and clear invalid legacy values to null in the new row;
leave the source record unchanged.
```bash Console usage attributes legacy rows without a per-model usage map to
cd backend `model_name`, including their recorded `total_input_tokens`. Accumulate those
python -m pytest tests -q -k "<area>_router" # e.g. threads_router, console_router inputs with newer usage buckets for the same model; do not infer cache hits.
make test-blocking-io # after adding any file, config or network read Regression coverage lives in `tests/test_console_router.py`.
```
## Rules for a route handler Shared scheduled-task update validation preserves an unchanged future `once`
instant on a live task inside `scheduler.min_once_delay_seconds`; new/changed
instants and terminal reactivation still enforce the minimum delay.
- **Authorize first.** Check the session, role or permission before the handler Scheduled-task admission rejects nonexistent naive `run_at` and `end_at`
reads credentials, parses an upload or makes an outbound request. An wall times through the shared Gateway datetime resolver. Keep this check out
unauthorized caller must not be able to trigger that work. of runtime `next_run_at`: legacy tasks retain their accepted execution time,
- **Fixed text in 5xx responses.** Exceptions from storage, config loading and including unchanged live once definitions. Explicit offsets retain their instant;
subprocesses contain host paths. Log the exception on the server and return a ambiguous naive times keep the existing fold choice.
fixed detail string.
- **No blocking calls on the event loop.** `get_app_config()` stats and hashes the The MCP task list accepts optional `TaskStatus` and `active_only` query filters.
config files on every call, and storage backends do file I/O. Call both through Pass both to the repository before its limit; preserve `threads:read`, owner
`asyncio.to_thread`. The blocking-I/O suite fails the build otherwise. checks, current-thread incarnation scoping, and the unfiltered array response.
- **Writes survive disconnects.** Wrap a persistent write in
`app.gateway.persistent_writes.run_drained_write`. A cancelled request then Custom Agent packages are strict, versioned definition-only JSON documents.
still waits for the worker that owns the write, and no half-written state stays Export explicitly projects the caller's portable `AgentConfig` fields and SOUL;
behind. exclude `github` installation bindings, memory contents, conversations and
- **Catalog responses are projections.** A listing endpoint returns names and credentials. Import may rename locally but must remain owner-scoped and
display fields. Provider paths, credentials and raw tool or server configuration create-only: collisions return 409, never overwrite or upsert. Ordinary creation
stay on the server. and import share `_persist_new_agent`, which uses `run_drained_write` so a
- **Provenance comes from the session.** Values that say who or what triggered an cancelled request still drains the owned persistence worker.
action (for example the plugin `ActionContext.interaction`) are set from the
authenticated request only. Ignore the same field in a request body. `GET /api/skills`, `/api/skills/custom` and `/api/skills/{name}` serve every
- **Unreadable configuration is not default configuration.** When a policy cannot signed-in user, so their unexpected-failure 500s return a fixed detail. Load
be read, skip the optional work (cleanup, sweep) and keep serving. Applying a errors (e.g. a malformed `extensions_config.json`) carry host paths and stay in
default policy can delete data the operator wanted to keep. the server log.
- **Imports create, they do not overwrite.** Agent and skill imports are scoped to
the caller and return 409 on a name collision. Exports leave out credentials, Thread upload, upload delete and shelf attach-to-thread 500s name the file but
memory, conversations and installation bindings. not the cause: staging and unlink `OSError`s carry host paths and stay in the
- **Memory backup imports** replace the selected facts and require an explicit server log.
`facts` array. Omitting it returns 422. An empty array clears that bucket.
- **Outbound requests from a route** (model discovery, connection tests) have a Skill mutation operation lists return `next_cursor: null` when `has_more` is false, including empty pages after a supplied `after_id`. The next cursor is the final returned operation only when a further page exists.
time limit and a size limit, do not follow redirects, and return redacted
provider errors. `GET /api/agent-tool-groups` projects only configured group names for the
- **Locks that several Gateway processes share** are file locks beside the data, custom-Agent settings allowlist. Never expose tool provider paths, credentials,
taken off the event loop. A process mutex alone does not order writes between or raw tool configuration through this catalog.
workers.
- **Path segments from clients.** A name that becomes a directory (agent name, Custom Agent update guards apply legacy shared-file checks only when the
skill name, file name) is validated when it is created, including Windows resolved store is `FileAgentStore`, including the `update_agent` tool. DB
reserved device names. Read and delete routes stay permissive so that data imports retain source files for rollback; those files cannot veto SQL updates.
stored by an older release can still be exported and removed. Keep store resolution and filesystem checks off-loop in the HTTP route.
- **Search results use the latest owner-visible message.** A historical jump Agent PUT uses `preserve_non_managed_fields(..., new_tool_groups=...)` to clear
resolves only the requested thread. Use the shared history seed path for an inherited knowledge default when changed groups remove knowledge access.
legacy checkpoints so it keeps its existing write reservation. Explicit scope/null updates still win; unchanged groups are not a migration.
Agent/profile and deployment/personal MCP mutation 500s plus the
scheduled-task `invalid_assistant` 422 use fixed text. Log exceptions
server-side; they can carry host paths.
Committed MCP reconciliation failures are logged once by
`fail_mcp_reconciliation`, with only the underlying exception type.
`_run_drained_mcp_apply` passes `_McpCommittedReconciliationError` as an expected
error to `run_drained_write` to avoid a duplicate diagnostic. It still drains
retired-pool cleanup outside the config locks and reports the fixed-detail 500.
Custom-skill edit, delete and rollback hold the owning root's process mutex and
`.custom.mutation.lock` sidecar across predecessor read, storage mutation and
history append. Peer Gateway processes sharing that root must use this same
critical section to preserve history ordering. Keep the sidecar distinct from
the nested projection lock, retain it across requests, and acquire/release both
off-loop inside the drained worker. Unrelated users retain independent locks;
external filesystem writers do not participate in this history guarantee.
Plugin actions stamp `ActionContext.interaction=session` only from authenticated
session provenance. Never accept it from payloads or propagate it to model tools;
extensions use it to distinguish owner review from model/tool output.
Skill archive upload copies (`_copy_uploaded_skill_archive`) report the original
size-limit or read error when temporary cleanup or its warning log fails.
Successful copies still return the uploaded bytes unchanged. The upload route's
`finally` discards that archive through the same helper before closing the
multipart form. Form close is suppressed, so a close, cleanup, or warning
failure cannot turn a successful install into a 500, replace an install
error, or skip the discard. Coverage: `tests/test_skill_archive_upload_cleanup.py`.
State updates synchronize titles into thread metadata only for the root checkpoint
namespace. Nonroot writes preserve the conversation title, branch-title sequence
and activity timestamp. `tests/test_threads_router.py` checks metadata/search
isolation and root title synchronization in full and delta modes.
Unauthenticated auth routes (`/register`, `/setup-status`, `/providers`,
`/oauth/{provider}`, `/callback/{provider}`, the `/login/local` throttle) read
`get_app_config()` through `asyncio.to_thread`: each read stats and hashes the
config files. Coverage: `tests/blocking_io/test_auth_router_config_reads.py`.

View File

@ -12,7 +12,6 @@ from . import (
thread_runs, thread_runs,
threads, threads,
uploads, uploads,
voice_input,
) )
__all__ = [ __all__ = [
@ -20,7 +19,6 @@ __all__ = [
"assistants_compat", "assistants_compat",
"browser", "browser",
"input_polish", "input_polish",
"voice_input",
"mcp", "mcp",
"models", "models",
"scheduled_tasks", "scheduled_tasks",

View File

@ -96,7 +96,7 @@ class AgentUpdateRequest(BaseModel):
"""Request body for updating a custom agent.""" """Request body for updating a custom agent."""
display_name: AgentDisplayName | None = Field(default=None, description="Updated display name; null clears it") display_name: AgentDisplayName | None = Field(default=None, description="Updated display name; null clears it")
description: str | None = Field(default=None, description="Updated description; null resets it to empty") description: str | None = Field(default=None, description="Updated description")
model: str | None = Field(default=None, description="Updated model override") model: str | None = Field(default=None, description="Updated model override")
tool_groups: list[str] | None = Field(default=None, description="Updated tool group whitelist") tool_groups: list[str] | None = Field(default=None, description="Updated tool group whitelist")
mcp_plugins: list[str] | None = Field(default=None, description="MCP installation selection (None=all, []=none)") mcp_plugins: list[str] | None = Field(default=None, description="MCP installation selection (None=all, []=none)")
@ -174,8 +174,6 @@ def _validate_model_exists(model: str | None) -> None:
Best-effort: if the app config cannot be loaded (e.g. no ``config.yaml`` on Best-effort: if the app config cannot be loaded (e.g. no ``config.yaml`` on
disk in a bare/test deployment), skip the check rather than failing the disk in a bare/test deployment), skip the check rather than failing the
write — the runtime still falls back to the default for an unknown model. write — the runtime still falls back to the default for an unknown model.
It reads the live config, so async routes call it through
``asyncio.to_thread``.
""" """
if not model: if not model:
return return
@ -388,7 +386,7 @@ async def import_agent_package(body: AgentPackage, request: Request, name: str |
_require_agents_api_enabled() _require_agents_api_enabled()
target_name = name or body.agent.name target_name = name or body.agent.name
_validate_agent_name(target_name) _validate_agent_name(target_name)
await asyncio.to_thread(_validate_model_exists, body.agent.model) _validate_model_exists(body.agent.model)
normalized_name = _normalize_agent_name(target_name) normalized_name = _normalize_agent_name(target_name)
user_id = get_effective_user_id() user_id = get_effective_user_id()
@ -518,7 +516,7 @@ async def create_agent_endpoint(body: AgentCreateRequest, request: Request) -> A
""" """
_require_agents_api_enabled() _require_agents_api_enabled()
_validate_agent_name(body.name) _validate_agent_name(body.name)
await asyncio.to_thread(_validate_model_exists, body.model) _validate_model_exists(body.model)
normalized_name = _normalize_agent_name(body.name) normalized_name = _normalize_agent_name(body.name)
user_id = get_effective_user_id() user_id = get_effective_user_id()
@ -590,7 +588,7 @@ async def update_agent(name: str, body: AgentUpdateRequest, request: Request) ->
) )
if "model" in body.model_fields_set: if "model" in body.model_fields_set:
await asyncio.to_thread(_validate_model_exists, body.model) _validate_model_exists(body.model)
try: try:
# Update config if any config fields changed # Update config if any config fields changed
@ -603,9 +601,7 @@ async def update_agent(name: str, body: AgentUpdateRequest, request: Request) ->
if config_changed: if config_changed:
updated = { updated = {
"name": agent_cfg.name, "name": agent_cfg.name,
# Explicit null resets to the AgentConfig default; storing None "description": body.description if "description" in fields_set else agent_cfg.description,
# would make every later load of this agent fail validation.
"description": (body.description or "") if "description" in fields_set else agent_cfg.description,
} }
if "display_name" in fields_set: if "display_name" in fields_set:
updated["display_name"] = body.display_name or None updated["display_name"] = body.display_name or None

View File

@ -4,27 +4,23 @@ import hashlib
import logging import logging
import mimetypes import mimetypes
import os import os
import secrets
import stat import stat
import tempfile import tempfile
import threading
import zipfile import zipfile
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from typing import BinaryIO
from urllib.parse import quote from urllib.parse import quote
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse, Response from fastapi.responses import FileResponse, Response
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from starlette.datastructures import MutableHeaders
from app.gateway.authz import SandboxRequestLease, require_permission, try_acquire_sandbox_for_request from app.gateway.authz import SandboxRequestLease, require_permission, try_acquire_sandbox_for_request
from app.gateway.deps import get_run_manager from app.gateway.deps import get_run_manager
from app.gateway.internal_auth import get_trusted_internal_owner_user_id from app.gateway.internal_auth import get_trusted_internal_owner_user_id
from app.gateway.path_utils import normalize_outputs_virtual_path, resolve_outputs_confined_path, resolve_thread_virtual_path from app.gateway.path_utils import normalize_outputs_virtual_path, resolve_outputs_confined_path, resolve_thread_virtual_path
from deerflow.authz.sandbox_authz import safe_app_config_async from deerflow.authz.sandbox_authz import safe_app_config
from deerflow.config.paths import make_safe_user_id from deerflow.config.paths import make_safe_user_id
from deerflow.runtime import ConflictError, ThreadOperationKind from deerflow.runtime import ConflictError, ThreadOperationKind
from deerflow.runtime.user_context import get_effective_user_id from deerflow.runtime.user_context import get_effective_user_id
@ -45,8 +41,6 @@ _SKILL_ARCHIVE_READ_CHUNK_SIZE = 64 * 1024
MAX_EDITABLE_ARTIFACT_BYTES = 2 * 1024 * 1024 MAX_EDITABLE_ARTIFACT_BYTES = 2 * 1024 * 1024
MAX_VIEWED_IMAGE_BLOB_BYTES = 20 * 1024 * 1024 MAX_VIEWED_IMAGE_BLOB_BYTES = 20 * 1024 * 1024
_ARTIFACT_EDIT_TEMP_PREFIX = ".artifact-edit-" _ARTIFACT_EDIT_TEMP_PREFIX = ".artifact-edit-"
_ARTIFACT_COPY_BEFORE_STREAM = os.name == "nt"
_artifact_digest_source = threading.local()
class ArtifactUpdateRequest(BaseModel): class ArtifactUpdateRequest(BaseModel):
@ -309,11 +303,6 @@ def _load_skill_archive_member(actual_skill_path: Path, skill_file_path: str, in
raise HTTPException(status_code=404, detail=f"Skill file not found: {skill_file_path}") raise HTTPException(status_code=404, detail=f"Skill file not found: {skill_file_path}")
if not actual_skill_path.is_file(): if not actual_skill_path.is_file():
raise HTTPException(status_code=400, detail=f"Path is not a file: {skill_file_path}") raise HTTPException(status_code=400, detail=f"Path is not a file: {skill_file_path}")
# A trailing ".skill/" requests no member at all. Without this guard the
# archive lookup's fallback matches the first directory entry (name ends
# with "/") and returns its empty body with 200 instead of 404 (#8500).
if not internal_path:
raise HTTPException(status_code=404, detail=f"No skill archive member requested: {skill_file_path}")
content = _extract_file_from_skill_archive(actual_skill_path, internal_path) content = _extract_file_from_skill_archive(actual_skill_path, internal_path)
if content is None: if content is None:
raise HTTPException(status_code=404, detail=f"File '{internal_path}' not found in skill archive") raise HTTPException(status_code=404, detail=f"File '{internal_path}' not found in skill archive")
@ -345,7 +334,7 @@ def _read_artifact_payload(actual_path: Path, path: str, download: bool) -> tupl
return ("inline_file", mime_type) return ("inline_file", mime_type)
def _sha256_of_file(path: Path, *, pinned: tuple[BinaryIO, os.stat_result] | None = None) -> str: def _sha256_of_file(path: Path) -> str:
"""Return the hex SHA-256 digest of *path* without loading it whole. """Return the hex SHA-256 digest of *path* without loading it whole.
Computing the digest on the Gateway lets the browser skip its own Computing the digest on the Gateway lets the browser skip its own
@ -357,217 +346,45 @@ def _sha256_of_file(path: Path, *, pinned: tuple[BinaryIO, os.stat_result] | Non
requests a browser issues while scrubbing/paginating a preview do not each requests a browser issues while scrubbing/paginating a preview do not each
re-hash a potentially huge artifact from scratch (raised in PR review). re-hash a potentially huge artifact from scratch (raised in PR review).
""" """
file_stat = path.stat() if pinned is None else pinned[1] stat = path.stat()
# Sandbox syncs and other writers can atomically replace a same-size file # Sandbox syncs and other writers can atomically replace a same-size file
# while preserving its mtime. Identity separates those generations; ctime # while preserving its mtime. Identity separates those generations; ctime
# also invalidates in-place writes where the filesystem exposes change time. # also invalidates in-place writes where the filesystem exposes change time.
key = ( return _sha256_of_file_cached(
str(path), str(path),
file_stat.st_dev, stat.st_dev,
file_stat.st_ino, stat.st_ino,
file_stat.st_ctime_ns, stat.st_ctime_ns,
file_stat.st_mtime_ns, stat.st_mtime_ns,
file_stat.st_size, stat.st_size,
) )
if pinned is None:
return _sha256_of_file_cached(*key)
previous = getattr(_artifact_digest_source, "pinned", None)
_artifact_digest_source.pinned = (key, pinned[0])
try:
return _sha256_of_file_cached(*key)
finally:
_artifact_digest_source.pinned = previous
@functools.lru_cache(maxsize=256) @functools.lru_cache(maxsize=256)
def _sha256_of_file_cached(path: str, device: int, inode: int, ctime_ns: int, mtime_ns: int, size: int) -> str: def _sha256_of_file_cached(path: str, device: int, inode: int, ctime_ns: int, mtime_ns: int, size: int) -> str:
"""Cached SHA-256 of *path*; metadata arguments separate file generations.""" """Cached SHA-256 of *path*; metadata arguments separate file generations."""
pinned = getattr(_artifact_digest_source, "pinned", None) digest = hashlib.sha256()
# A nested lookup for a different file must hash its own bytes.
if pinned is None or pinned[0] != (path, device, inode, ctime_ns, mtime_ns, size):
with open(path, "rb") as handle: with open(path, "rb") as handle:
return hashlib.file_digest(handle, "sha256").hexdigest() for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
handle = pinned[1] return digest.hexdigest()
previous_offset = handle.tell()
try:
handle.seek(0)
return hashlib.file_digest(handle, "sha256").hexdigest()
finally:
handle.seek(previous_offset)
def _artifact_etag(path: Path) -> str: def _artifact_etag(path: Path) -> str:
"""Keep content revisions for editable files and metadata tags for large files.""" """Keep content revisions for editable files and metadata-only tags for large files."""
file_stat = path.stat() file_stat = path.stat()
if file_stat.st_size <= MAX_EDITABLE_ARTIFACT_BYTES: if file_stat.st_size <= MAX_EDITABLE_ARTIFACT_BYTES:
# Populate the shared cache only with metadata from the hashed handle. return f'"{_sha256_of_file(path)}"'
with path.open("rb") as handle:
return _artifact_etag_from_handle(path, handle, os.fstat(handle.fileno()))
return _artifact_stat_etag(file_stat)
def _artifact_stat_etag(file_stat: os.stat_result) -> str:
# Do not read oversized artifacts just to validate a small byte range. # Do not read oversized artifacts just to validate a small byte range.
# The prefix keeps this opaque validator distinct from an editable SHA-256. # The prefix keeps this opaque validator distinct from an editable SHA-256.
identity = f"{file_stat.st_dev}:{file_stat.st_ino}:{file_stat.st_ctime_ns}:{file_stat.st_mtime_ns}:{file_stat.st_size}" identity = f"{file_stat.st_dev}:{file_stat.st_ino}:{file_stat.st_ctime_ns}:{file_stat.st_mtime_ns}:{file_stat.st_size}"
return f'"stat-{hashlib.sha256(identity.encode("ascii")).hexdigest()}"' return f'"stat-{hashlib.sha256(identity.encode("ascii")).hexdigest()}"'
def _artifact_etag_from_handle(path: Path, handle: BinaryIO, file_stat: os.stat_result) -> str:
"""Build the validator from the same file generation the response will read."""
if file_stat.st_size <= MAX_EDITABLE_ARTIFACT_BYTES:
digest = _sha256_of_file(path, pinned=(handle, file_stat))
return f'"{digest}"'
return _artifact_stat_etag(file_stat)
def _prepare_artifact_stream(path: Path) -> tuple[BinaryIO, os.stat_result, str]:
"""Pin one file generation before response headers authorize a byte range."""
handle = path.open("rb")
try:
file_stat = os.fstat(handle.fileno())
if not stat.S_ISREG(file_stat.st_mode):
raise RuntimeError(f"File at path {path} is not a file.")
return handle, file_stat, _artifact_etag_from_handle(path, handle, file_stat)
except BaseException:
_close_artifact_handle(handle)
raise
def _copy_artifact_ranges(handle: BinaryIO, ranges: list[tuple[int, int]]) -> BinaryIO:
"""Pack the selected ranges into a private temporary file in send order."""
snapshot = tempfile.TemporaryFile(mode="w+b")
try:
for start, end in ranges:
handle.seek(start)
remaining = end - start
while remaining:
chunk = handle.read(min(1 << 20, remaining))
if not chunk:
raise OSError("Artifact was truncated while preparing the response")
snapshot.write(chunk)
remaining -= len(chunk)
snapshot.seek(0)
return snapshot
except BaseException:
_close_artifact_handle(snapshot)
raise
def _close_artifact_handle(handle: BinaryIO) -> None:
try:
handle.close()
except OSError:
logger.warning("Could not close artifact response handle", exc_info=True)
class _ArtifactFileResponse(FileResponse): class _ArtifactFileResponse(FileResponse):
"""Require an ETag to authorize conditional ranges of replaceable artifacts.""" """Require an ETag to authorize conditional ranges of replaceable artifacts."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._artifact_handle: BinaryIO | None = None
async def __call__(self, scope, receive, send) -> None:
async def prepare() -> None:
self._artifact_handle, self.stat_result, etag = await asyncio.to_thread(_prepare_artifact_stream, Path(self.path))
self.headers["etag"] = etag
self.set_stat_headers(self.stat_result)
try:
await await_drained(prepare())
await super().__call__(scope, receive, send)
finally:
if self._artifact_handle is not None:
handle, self._artifact_handle = self._artifact_handle, None
await await_drained(asyncio.to_thread(_close_artifact_handle, handle))
async def _snapshot_windows_body(self, ranges: list[tuple[int, int]], send_header_only: bool) -> bool:
if not _ARTIFACT_COPY_BEFORE_STREAM:
return False
source = self._artifact_handle
assert source is not None
async def snapshot() -> None:
# Windows replacement needs the public handle closed. A private
# copy also leaves the artifact's link count unchanged for ZIP.
self._artifact_handle = None if send_header_only else await asyncio.to_thread(_copy_artifact_ranges, source, ranges)
await asyncio.to_thread(_close_artifact_handle, source)
await await_drained(snapshot())
return True
async def _handle_simple(self, send, send_header_only: bool, send_pathsend: bool) -> None:
assert self.stat_result is not None
await self._snapshot_windows_body([(0, self.stat_result.st_size)], send_header_only)
await send({"type": "http.response.start", "status": self.status_code, "headers": self.raw_headers})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
return
handle = self._artifact_handle
assert handle is not None
await await_drained(asyncio.to_thread(handle.seek, 0))
more_body = True
while more_body:
chunk = await await_drained(asyncio.to_thread(handle.read, self.chunk_size))
more_body = len(chunk) == self.chunk_size
await send({"type": "http.response.body", "body": chunk, "more_body": more_body})
async def _handle_single_range(self, send, start: int, end: int, file_size: int, send_header_only: bool) -> None:
snapshot = await self._snapshot_windows_body([(start, end)], send_header_only)
headers = MutableHeaders(raw=list(self.raw_headers))
headers["content-range"] = f"bytes {start}-{end - 1}/{file_size}"
headers["content-length"] = str(end - start)
await send({"type": "http.response.start", "status": 206, "headers": headers.raw})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
return
handle = self._artifact_handle
assert handle is not None
if not snapshot:
await await_drained(asyncio.to_thread(handle.seek, start))
more_body = True
while more_body:
chunk = await await_drained(asyncio.to_thread(handle.read, min(self.chunk_size, end - start)))
start += len(chunk)
more_body = len(chunk) == self.chunk_size and start < end
await send({"type": "http.response.body", "body": chunk, "more_body": more_body})
async def _handle_multiple_ranges(self, send, ranges: list[tuple[int, int]], file_size: int, send_header_only: bool) -> None:
snapshot = await self._snapshot_windows_body(ranges, send_header_only)
boundary = secrets.token_hex(13)
content_length, header_generator = self.generate_multipart(ranges, boundary, file_size, self.headers["content-type"])
headers = MutableHeaders(raw=list(self.raw_headers))
headers["content-type"] = f"multipart/byteranges; boundary={boundary}"
headers["content-length"] = str(content_length)
await send({"type": "http.response.start", "status": 206, "headers": headers.raw})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
return
handle = self._artifact_handle
assert handle is not None
for start, end in ranges:
await send({"type": "http.response.body", "body": header_generator(start, end), "more_body": True})
if not snapshot:
await await_drained(asyncio.to_thread(handle.seek, start))
while start < end:
chunk = await await_drained(asyncio.to_thread(handle.read, min(self.chunk_size, end - start)))
if not chunk:
raise OSError("Artifact was truncated while streaming a byte range")
start += len(chunk)
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"\r\n", "more_body": True})
await send({"type": "http.response.body", "body": f"--{boundary}--".encode("latin-1"), "more_body": False})
def _should_use_range(self, http_if_range: str) -> bool: def _should_use_range(self, http_if_range: str) -> bool:
# Sandbox syncs can preserve mtimes across replacements, so Last-Modified # Sandbox syncs can preserve mtimes across replacements, so Last-Modified
# is not a strong validator. Date-form If-Range must return the full file. # is not a strong validator. Date-form If-Range must return the full file.
@ -853,7 +670,7 @@ async def update_artifact(
sandbox_provider, sandbox_provider,
thread_id, thread_id,
user_id=effective_user_id, user_id=effective_user_id,
app_config=await safe_app_config_async(), app_config=safe_app_config(),
owner_prefix="gateway:artifact", owner_prefix="gateway:artifact",
) )
sandbox = sandbox_lease.sandbox sandbox = sandbox_lease.sandbox

View File

@ -38,7 +38,7 @@ from app.gateway.auth.session_cookie_state import SKIP_AUTH_CSRF_COOKIE_STATE_AT
from app.gateway.auth.user_provisioning import get_or_provision_oidc_user from app.gateway.auth.user_provisioning import get_or_provision_oidc_user
from app.gateway.csrf_middleware import CSRF_COOKIE_NAME, _request_origin, auth_csrf_cookie_settings, generate_csrf_token, is_secure_request from app.gateway.csrf_middleware import CSRF_COOKIE_NAME, _request_origin, auth_csrf_cookie_settings, generate_csrf_token, is_secure_request
from app.gateway.deps import get_current_user_from_request, get_local_provider from app.gateway.deps import get_current_user_from_request, get_local_provider
from app.gateway.utils import constant_time_equals, sanitize_log_param from app.gateway.utils import constant_time_equals
from deerflow.config.auth_config import OIDCAuthConfig, OIDCProviderConfig from deerflow.config.auth_config import OIDCAuthConfig, OIDCProviderConfig
from deerflow.persistence.login_throttle import LoginThrottleStore from deerflow.persistence.login_throttle import LoginThrottleStore
@ -579,12 +579,7 @@ async def change_password(request: Request, response: Response, body: ChangePass
if user.needs_setup and body.new_email is not None: if user.needs_setup and body.new_email is not None:
user.needs_setup = False user.needs_setup = False
try:
await provider.update_user(user) await provider.update_user(user)
except ValueError:
# The address was registered between the pre-check above and this
# write; the repository rejected it and wrote nothing.
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.EMAIL_ALREADY_EXISTS, message="Email already in use").model_dump())
# Re-issue cookie with new token_version # Re-issue cookie with new token_version
token = create_access_token(str(user.id), token_version=user.token_version) token = create_access_token(str(user.id), token_version=user.token_version)
@ -1052,14 +1047,7 @@ async def oauth_callback(
# ── Provider error ─────────────────────────────────────────────── # ── Provider error ───────────────────────────────────────────────
if error: if error:
# This branch runs before any check, so all three values come straight logger.warning("OIDC provider returned error for %s: %s (description: %s)", provider, error, error_description)
# from an unauthenticated request.
logger.warning(
"OIDC provider returned error for %s: %s (description: %s)",
sanitize_log_param(provider),
sanitize_log_param(error),
sanitize_log_param(error_description) if error_description is not None else None,
)
redirect = _build_error_redirect(oidc_config.frontend_base_url, "sso_failed") redirect = _build_error_redirect(oidc_config.frontend_base_url, "sso_failed")
return RedirectResponse(url=redirect, status_code=status.HTTP_302_FOUND) return RedirectResponse(url=redirect, status_code=status.HTTP_302_FOUND)

View File

@ -85,7 +85,7 @@ async def navigate_browser(thread_id: ThreadId, body: BrowserNavigateRequest, re
if thread_store is None or not await _browser_thread_owned_by(thread_store, thread_id, user_id): if thread_store is None or not await _browser_thread_owned_by(thread_store, thread_id, user_id):
raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found")
if not await asyncio.to_thread(_browser_tools_enabled): if not _browser_tools_enabled():
raise HTTPException(status_code=404, detail="Browser automation is not enabled") raise HTTPException(status_code=404, detail="Browser automation is not enabled")
try: try:
@ -260,7 +260,7 @@ async def browser_stream(websocket: WebSocket, thread_id: ThreadId) -> None:
await websocket.close(code=4404) await websocket.close(code=4404)
return return
if not await asyncio.to_thread(_browser_tools_enabled): if not _browser_tools_enabled():
await websocket.close(code=4404) await websocket.close(code=4404)
return return
@ -310,7 +310,7 @@ async def browser_stream(websocket: WebSocket, thread_id: ThreadId) -> None:
# the user's real Chrome when configured. # the user's real Chrome when configured.
from deerflow.config import get_app_config from deerflow.config import get_app_config
tool_cfg = (await asyncio.to_thread(get_app_config)).get_tool_config("browser_navigate") tool_cfg = get_app_config().get_tool_config("browser_navigate")
extra = (tool_cfg.model_extra or {}) if tool_cfg is not None else {} extra = (tool_cfg.model_extra or {}) if tool_cfg is not None else {}
def _cfg_int(key: str, default: int) -> int: def _cfg_int(key: str, default: int) -> int:

View File

@ -178,7 +178,6 @@ def _get_user_id(request: Request) -> str:
def _get_app_config(): def _get_app_config():
"""The live app config. It stats and hashes the config files, so async callers run it through ``asyncio.to_thread``."""
from deerflow.config.app_config import get_app_config from deerflow.config.app_config import get_app_config
return get_app_config() return get_app_config()
@ -189,10 +188,9 @@ async def _get_runtime_config_store(request: Request) -> RuntimeConfigStore:
store = getattr(request.app.state, "channel_runtime_config_store", None) store = getattr(request.app.state, "channel_runtime_config_store", None)
if store is not None: if store is not None:
return store return store
# Resolving reads the config, paths and the JSON store's file from disk; # Resolving reads paths (and the JSON store's file) from disk; keep it off
# keep it off the event loop. The database store holds no state of its own. # the event loop. The database store holds no state of its own.
app_config = await asyncio.to_thread(_get_app_config) store = await asyncio.to_thread(resolve_runtime_config_store, _get_app_config(), cipher=getattr(request.app.state, "credentials_cipher", None))
store = await asyncio.to_thread(resolve_runtime_config_store, app_config, cipher=getattr(request.app.state, "credentials_cipher", None))
request.app.state.channel_runtime_config_store = store request.app.state.channel_runtime_config_store = store
return store return store
@ -203,7 +201,7 @@ async def _get_channel_connections_config(request: Request) -> ChannelConnection
# since the last one. # since the last one.
config = getattr(request.app.state, "channel_connections_config", None) config = getattr(request.app.state, "channel_connections_config", None)
if not isinstance(config, ChannelConnectionsConfig): if not isinstance(config, ChannelConnectionsConfig):
config = (await asyncio.to_thread(_get_app_config)).channel_connections config = _get_app_config().channel_connections
if not (config.enabled and config.telegram.enabled): if not (config.enabled and config.telegram.enabled):
# Only the Telegram deep-link username comes from the runtime store. # Only the Telegram deep-link username comes from the runtime store.
return config return config
@ -216,7 +214,7 @@ async def _get_channels_config(request: Request) -> dict[str, Any]:
async def _load_channels_config(request: Request, config: ChannelConnectionsConfig) -> dict[str, Any]: async def _load_channels_config(request: Request, config: ChannelConnectionsConfig) -> dict[str, Any]:
app_config = await asyncio.to_thread(_get_app_config) app_config = _get_app_config()
extra = app_config.model_extra or {} extra = app_config.model_extra or {}
channels_config = extra.get("channels") channels_config = extra.get("channels")
result = dict(channels_config) if isinstance(channels_config, dict) else {} result = dict(channels_config) if isinstance(channels_config, dict) else {}
@ -801,7 +799,7 @@ async def _require_wechat_qr_login(request: Request) -> ChannelConnectionsConfig
except ValueError: except ValueError:
workers = 0 workers = 0
# Kubernetes replicas run one worker each; they declare their peers instead. # Kubernetes replicas run one worker each; they declare their peers instead.
if workers != 1 or multi_instance_declaration(await asyncio.to_thread(_get_app_config)) is not None: if workers != 1 or multi_instance_declaration(_get_app_config()) is not None:
raise HTTPException( raise HTTPException(
status_code=503, status_code=503,
detail=( detail=(

View File

@ -13,7 +13,6 @@ which persists no run history to report on.
import asyncio import asyncio
import logging import logging
import math
from datetime import UTC, datetime, time, timedelta from datetime import UTC, datetime, time, timedelta
from typing import NamedTuple from typing import NamedTuple
@ -27,7 +26,6 @@ from deerflow.config import get_app_config
from deerflow.config.agents_config import list_custom_agents from deerflow.config.agents_config import list_custom_agents
from deerflow.persistence.engine import get_session_factory from deerflow.persistence.engine import get_session_factory
from deerflow.persistence.run.model import RunRow from deerflow.persistence.run.model import RunRow
from deerflow.persistence.subagent_batches import SubagentBatchRepository
from deerflow.persistence.thread_meta.model import ThreadMetaRow from deerflow.persistence.thread_meta.model import ThreadMetaRow
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -91,7 +89,6 @@ class ConsoleUsageDay(BaseModel):
input_tokens: int = 0 input_tokens: int = 0
output_tokens: int = 0 output_tokens: int = 0
runs: int = 0 runs: int = 0
batch_items: int = Field(default=0, description="Subagent batch items with an attempt whose usage was written this day; those tokens are included above")
cost: float | None = Field(default=0.0, description="Estimated spend for the day across priced runs; null when any call explicitly lacks usage") cost: float | None = Field(default=0.0, description="Estimated spend for the day across priced runs; null when any call explicitly lacks usage")
@ -112,7 +109,6 @@ class ConsoleUsageResponse(BaseModel):
by_model: dict[str, ConsoleUsageModelBreakdown] by_model: dict[str, ConsoleUsageModelBreakdown]
total_tokens: int total_tokens: int
total_runs: int total_runs: int
total_batch_items: int = Field(default=0, description="Subagent batch items in the window; they are not runs, but their tokens are included in the totals and by_model")
total_cost: float | None = Field(default=None, description="Estimated spend for the window; null when pricing is unavailable or any call explicitly lacks usage") total_cost: float | None = Field(default=None, description="Estimated spend for the window; null when pricing is unavailable or any call explicitly lacks usage")
currency: str | None = Field(default=None, description="Display currency taken from the first configured pricing entry") currency: str | None = Field(default=None, description="Display currency taken from the first configured pricing entry")
@ -163,8 +159,6 @@ def _build_pricing_map() -> dict[str, _ModelPricing]:
schema change. Entries are keyed by both the config ``name`` and the schema change. Entries are keyed by both the config ``name`` and the
provider ``model`` id (plus lowercase variants), because provider ``model`` id (plus lowercase variants), because
``token_usage_by_model`` buckets carry the provider-reported model name. ``token_usage_by_model`` buckets carry the provider-reported model name.
It reads the live config, so async routes call it through
``asyncio.to_thread``.
""" """
try: try:
models = get_app_config().models models = get_app_config().models
@ -187,14 +181,6 @@ def _build_pricing_map() -> dict[str, _ModelPricing]:
except (TypeError, ValueError): except (TypeError, ValueError):
logger.warning("console: ignoring malformed pricing on model %s", model_cfg.name) logger.warning("console: ignoring malformed pricing on model %s", model_cfg.name)
continue continue
# ``float("nan")`` / ``float(".inf")`` parse successfully, and NaN then
# survives every ``<=`` comparison below and every ``round()``, ending up
# in the JSON body where Starlette rejects it (allow_nan=False) -- a 500
# for the whole usage report. Treat non-finite prices as malformed, the
# same way the rest of the config layer does (allow_inf_nan=False).
if any(not math.isfinite(price) for price in (input_price, output_price, cache_hit_price) if price is not None):
logger.warning("console: ignoring non-finite pricing on model %s", model_cfg.name)
continue
if input_price <= 0 and output_price <= 0: if input_price <= 0 and output_price <= 0:
continue continue
model_currency = str(raw.get("currency") or "USD").strip().upper() or "USD" model_currency = str(raw.get("currency") or "USD").strip().upper() or "USD"
@ -242,36 +228,8 @@ def _token_cost(input_tokens: int, output_tokens: int, price: _ModelPricing, cac
return (uncached / 1_000_000) * price.input_per_million + (cache_read / 1_000_000) * hit_price + (output_tokens / 1_000_000) * price.output_per_million return (uncached / 1_000_000) * price.input_per_million + (cache_read / 1_000_000) * hit_price + (output_tokens / 1_000_000) * price.output_per_million
def _token_count(value: object) -> int:
"""Coerce one stored token counter to a non-negative ``int``.
``token_usage_by_model`` is a JSON column written from provider-reported
usage, so a bucket value is not guaranteed to be a number: providers have
shipped counters as strings ("n/a", "1.0"), and rows written by older
build/import paths may hold anything JSON can express. The console already
skips buckets that are not dicts and pricing that is not numeric; coercing
counters the same way keeps one junk bucket from failing the whole report
with a 500. Booleans are rejected because ``int(True) == 1`` would invent a
token, and negatives cannot be spend.
A JSON integer is not bounded by the float range: ``10**400`` parses as an
exact ``int``, and ``_token_cost`` then divides it by a million, which
raises ``OverflowError`` on the way back to a float. Such a value is junk
in exactly the same way as ``"n/a"``, so it is rejected here too.
"""
if isinstance(value, bool):
return 0
try:
count = int(value) # type: ignore[arg-type]
if count < 0 or not math.isfinite(float(count)):
return 0
except (TypeError, ValueError, OverflowError):
return 0
return count
def _usage_is_missing(usage: dict) -> bool: def _usage_is_missing(usage: dict) -> bool:
return _token_count(usage.get("missing_usage_calls")) > 0 return int(usage.get("missing_usage_calls") or 0) > 0
def _has_missing_usage(token_usage_by_model: object) -> bool: def _has_missing_usage(token_usage_by_model: object) -> bool:
@ -305,11 +263,11 @@ def _run_cost(
price = _lookup_pricing(pricing, model) price = _lookup_pricing(pricing, model)
if price is None: if price is None:
continue continue
input_tokens = _token_count(usage.get("input_tokens")) input_tokens = int(usage.get("input_tokens") or 0)
output_tokens = _token_count(usage.get("output_tokens")) output_tokens = int(usage.get("output_tokens") or 0)
if input_tokens == 0 and output_tokens == 0: if input_tokens == 0 and output_tokens == 0:
continue continue
cost += _token_cost(input_tokens, output_tokens, price, _token_count(usage.get("cache_read_tokens"))) cost += _token_cost(input_tokens, output_tokens, price, int(usage.get("cache_read_tokens") or 0))
priced = True priced = True
if priced: if priced:
return cost return cost
@ -344,7 +302,7 @@ async def console_stats(request: Request) -> ConsoleStatsResponse:
run_where += (RunRow.user_id == user_id,) run_where += (RunRow.user_id == user_id,)
thread_where = (ThreadMetaRow.user_id == user_id,) if user_id else () thread_where = (ThreadMetaRow.user_id == user_id,) if user_id else ()
pricing = await asyncio.to_thread(_build_pricing_map) pricing = _build_pricing_map()
async with sf() as session: async with sf() as session:
total_runs = await session.scalar(select(func.count()).select_from(RunRow).where(*run_where)) or 0 total_runs = await session.scalar(select(func.count()).select_from(RunRow).where(*run_where)) or 0
@ -381,15 +339,6 @@ async def console_stats(request: Request) -> ConsoleStatsResponse:
cost_sum += cost cost_sum += cost
total_cost = round(cost_sum, 6) if cost_sum is not None else None total_cost = round(cost_sum, 6) if cost_sum is not None else None
# Subagent batch items are not runs; their tokens and spend still count.
# Each entry is one model's tokens of one item attempt, priced at that
# model's rate with its cache hits.
for item in await SubagentBatchRepository(sf).list_item_token_usage(user_id=user_id or None):
total_tokens += item["total_tokens"]
price = _lookup_pricing(pricing, item["model_name"])
if total_cost is not None and price is not None:
total_cost = round(total_cost + _token_cost(item["input_tokens"], item["output_tokens"], price, item["cache_read_tokens"]), 6)
try: try:
# Filesystem scan; resolves the effective user internally (AuthMiddleware # Filesystem scan; resolves the effective user internally (AuthMiddleware
# sets the context for real requests, "default" in no-auth mode). # sets the context for real requests, "default" in no-auth mode).
@ -444,7 +393,7 @@ async def console_runs(
async with sf() as session: async with sf() as session:
rows = (await session.execute(stmt)).all() rows = (await session.execute(stmt)).all()
pricing = await asyncio.to_thread(_build_pricing_map) pricing = _build_pricing_map()
has_more = len(rows) > limit has_more = len(rows) > limit
now = datetime.now(UTC) now = datetime.now(UTC)
items: list[ConsoleRunItem] = [] items: list[ConsoleRunItem] = []
@ -515,7 +464,7 @@ async def console_usage(
d = (start_local + timedelta(days=i)).isoformat() d = (start_local + timedelta(days=i)).isoformat()
day_buckets[d] = ConsoleUsageDay(date=d) day_buckets[d] = ConsoleUsageDay(date=d)
pricing = await asyncio.to_thread(_build_pricing_map) pricing = _build_pricing_map()
by_model: dict[str, ConsoleUsageModelBreakdown] = {} by_model: dict[str, ConsoleUsageModelBreakdown] = {}
total_tokens = 0 total_tokens = 0
total_runs = 0 total_runs = 0
@ -562,9 +511,9 @@ async def console_usage(
entry.runs += 1 entry.runs += 1
if not isinstance(usage, dict): if not isinstance(usage, dict):
continue continue
entry.tokens += _token_count(usage.get("total_tokens")) entry.tokens += int(usage.get("total_tokens", 0) or 0)
entry.input_tokens += _token_count(usage.get("input_tokens")) entry.input_tokens += int(usage.get("input_tokens") or 0)
entry.cache_read_tokens += _token_count(usage.get("cache_read_tokens")) entry.cache_read_tokens += int(usage.get("cache_read_tokens") or 0)
price = _lookup_pricing(pricing, model) price = _lookup_pricing(pricing, model)
if _usage_is_missing(usage): if _usage_is_missing(usage):
missing_models.add(model.lower()) missing_models.add(model.lower())
@ -573,7 +522,7 @@ async def console_usage(
# equal rates on an unrelated model are not aliases. # equal rates on an unrelated model are not aliases.
missing_model_prices.add(id(price)) missing_model_prices.add(id(price))
if price is not None: if price is not None:
model_cost = _token_cost(_token_count(usage.get("input_tokens")), _token_count(usage.get("output_tokens")), price, _token_count(usage.get("cache_read_tokens"))) model_cost = _token_cost(int(usage.get("input_tokens") or 0), int(usage.get("output_tokens") or 0), price, int(usage.get("cache_read_tokens") or 0))
entry.cost = round((entry.cost or 0.0) + model_cost, 6) entry.cost = round((entry.cost or 0.0) + model_cost, 6)
elif row.model_name and run_tokens > 0: elif row.model_name and run_tokens > 0:
# Legacy rows predating token_usage_by_model: fall back to the run's model. # Legacy rows predating token_usage_by_model: fall back to the run's model.
@ -584,40 +533,6 @@ async def console_usage(
if run_cost is not None: if run_cost is not None:
entry.cost = round((entry.cost or 0.0) + run_cost, 6) entry.cost = round((entry.cost or 0.0) + run_cost, 6)
# Subagent batch items run outside any run. Each entry is one model's
# tokens of one item attempt, dated by when that attempt's usage was
# written and priced at that model's rate with its cache hits.
batch_items = await SubagentBatchRepository(sf).list_item_token_usage(user_id=user_id or None, updated_since=window_start_utc)
window_items: set[str] = set()
day_items: dict[str, set[str]] = {}
for item in batch_items:
at = _as_utc(item["at"])
day = ((at + tz_delta).date()).isoformat() if at is not None else None
bucket = day_buckets.get(day) if day is not None else None
if bucket is None:
continue
bucket.total_tokens += item["total_tokens"]
bucket.input_tokens += item["input_tokens"]
bucket.output_tokens += item["output_tokens"]
day_items.setdefault(day, set()).add(item["item_id"])
bucket.batch_items = len(day_items[day])
total_tokens += item["total_tokens"]
window_items.add(item["item_id"])
model = item["model_name"] or "unknown"
entry = by_model.setdefault(model, ConsoleUsageModelBreakdown())
entry.tokens += item["total_tokens"]
entry.input_tokens += item["input_tokens"]
entry.cache_read_tokens += item["cache_read_tokens"]
price = _lookup_pricing(pricing, item["model_name"])
if price is not None:
item_cost = _token_cost(item["input_tokens"], item["output_tokens"], price, item["cache_read_tokens"])
entry.cost = round((entry.cost or 0.0) + item_cost, 6)
if bucket.cost is not None:
bucket.cost = round(bucket.cost + item_cost, 6)
if total_cost is not None:
total_cost = round(total_cost + item_cost, 6)
total_batch_items = len(window_items)
# Missing usage stays unknown even if a later known bucket or legacy row # Missing usage stays unknown even if a later known bucket or legacy row
# shares this model. Do not restore its quote by treating None as zero. # shares this model. Do not restore its quote by treating None as zero.
for model, entry in by_model.items(): for model, entry in by_model.items():
@ -630,7 +545,6 @@ async def console_usage(
by_model=by_model, by_model=by_model,
total_tokens=total_tokens, total_tokens=total_tokens,
total_runs=total_runs, total_runs=total_runs,
total_batch_items=total_batch_items,
total_cost=total_cost, total_cost=total_cost,
currency=_pricing_currency(pricing), currency=_pricing_currency(pricing),
) )

View File

@ -1,163 +0,0 @@
"""Session-authorized task execution shared by coordination entry points."""
from hashlib import sha256
from pathlib import PurePosixPath
from typing import Annotated
from deerflow_extension_api.agent_runs import AgentRunError
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import Response
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StringConstraints
from app.gateway.authz import require_permission
from app.gateway.coordination_workers import worker_context, worker_error
from deerflow.persistence.coordination.model import TaskStatus
from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound
from deerflow.utils.file_io import await_drained
router = APIRouter(prefix="/api/coordination/tasks", tags=["coordination"])
RequestId = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=200)]
TaskText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=16384)]
class WorkerRunSettings(BaseModel):
model_config = ConfigDict(extra="forbid")
recursion_limit: int | None = Field(default=None, strict=True, ge=1)
thinking_enabled: StrictBool | None = None
is_plan_mode: StrictBool | None = None
class CreateWorkerTask(BaseModel):
request_id: RequestId
objective: TaskText
assistant_id: str = Field(default="lead_agent", min_length=1, max_length=128)
project_id: str | None = Field(default=None, min_length=1, max_length=64)
coordinator: StrictBool = False
run: WorkerRunSettings | None = None
class WorkerInput(BaseModel):
request_id: RequestId
content: TaskText
class CancelTask(BaseModel):
expected_revision: int = Field(ge=0)
@router.post("")
@require_permission("runs", "create")
async def create_worker_task(body: CreateWorkerTask, request: Request):
service, owner, runs = worker_context(request)
async def dispatch():
task = await service.repo.create(
owner,
request_id=body.request_id,
objective=body.objective,
project_id=body.project_id,
coordinator=body.coordinator,
run_settings=body.run.model_dump(exclude_none=True) if body.run is not None else None,
)
return await service.dispatch(runs, owner, task["id"], body.assistant_id)
try:
return await await_drained(dispatch())
except (TaskConflict, TaskNotFound, AgentRunError) as exc:
raise worker_error(exc) from exc
@router.get("/{task_id}")
@require_permission("runs", "read")
async def get_worker_task(task_id: str, request: Request):
service, owner, _runs = worker_context(request)
try:
return await service.view(owner, task_id)
except TaskNotFound as exc:
raise HTTPException(404, "Task not found") from exc
@router.post("/{task_id}/inputs")
@require_permission("runs", "create")
async def add_worker_input(task_id: str, body: WorkerInput, request: Request):
service, owner, _runs = worker_context(request)
try:
return await service.submit_input(owner, task_id, request_id="input:" + sha256(body.request_id.encode()).hexdigest(), content=body.content)
except (TaskNotFound, TaskConflict, AgentRunError) as exc:
raise worker_error(exc) from exc
@router.get("/{task_id}/inputs")
@require_permission("runs", "read")
async def list_worker_inputs(task_id: str, request: Request, after: int = Query(0, ge=0, le=2**63 - 1), limit: int = Query(100, ge=1, le=100)):
service, owner, _runs = worker_context(request)
try:
return await service.repo.list_worker_inputs(owner, task_id, after=after, limit=limit)
except TaskNotFound as exc:
raise HTTPException(404, "Task not found") from exc
@router.post("/{task_id}/cancel", responses={202: {"description": "Cancellation is still in progress"}})
@require_permission("runs", "cancel")
async def cancel_worker_task(task_id: str, body: CancelTask, request: Request, response: Response):
service, owner, runs = worker_context(request)
try:
task = await await_drained(service.cancel(runs, owner, task_id, body.expected_revision))
except (TaskConflict, TaskNotFound, AgentRunError) as exc:
raise worker_error(exc) from exc
if task["status"] == TaskStatus.CANCELLING:
response.status_code = 202
return task
@router.put("/{task_id}/authorization")
@require_permission("runs", "create")
async def authorize_worker_task(task_id: str, request: Request):
service, owner, runs = worker_context(request)
try:
return await service.authorize(runs, owner, task_id)
except (TaskNotFound, TaskConflict, AgentRunError) as exc:
raise worker_error(exc) from exc
@router.delete("/{task_id}/authorization", status_code=204)
@require_permission("runs", "cancel")
async def revoke_worker_task(task_id: str, request: Request):
service, owner, _runs = worker_context(request)
try:
await service.repo.set_grant(owner, task_id, None)
except (TaskNotFound, TaskConflict) as exc:
raise worker_error(exc) from exc
return Response(status_code=204)
@router.get("/{task_id}/artifacts")
@require_permission("threads", "read")
async def list_worker_artifacts(task_id: str, request: Request, limit: int = Query(100, ge=1, le=100), offset: int = Query(0, ge=0)):
service, owner, _runs = worker_context(request)
try:
return await service.repo.list_artifacts(owner, task_id, limit=limit, offset=offset)
except TaskNotFound as exc:
raise HTTPException(404, "Task not found") from exc
@router.get("/{task_id}/artifacts/{artifact_id}")
@require_permission("threads", "read")
async def download_worker_artifact(task_id: str, artifact_id: str, request: Request):
from app.gateway.routers.artifacts import _build_content_disposition
service, owner, _runs = worker_context(request)
try:
path, content = await service.repo.read_artifact(owner, task_id, artifact_id)
except TaskNotFound as exc:
raise HTTPException(404, "Artifact not found") from exc
return Response(
content,
media_type="application/octet-stream",
headers={
"Content-Disposition": _build_content_disposition("attachment", PurePosixPath(path).name),
"Cache-Control": "private, no-store",
"X-Content-Type-Options": "nosniff",
},
)

View File

@ -7,8 +7,6 @@ request, while startup-scoped capabilities report the runtime that actually
started. started.
""" """
from typing import Literal
from fastapi import APIRouter, Depends, Request from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@ -84,18 +82,6 @@ class ThreadActivityFeature(BaseModel):
available: bool = Field(..., description="Whether GET /api/thread-activity, POST /api/threads/{thread_id}/read and the thread search `unread` field work (SQL persistence)") available: bool = Field(..., description="Whether GET /api/thread-activity, POST /api/threads/{thread_id}/read and the thread search `unread` field work (SQL persistence)")
class ToolApprovalFeature(BaseModel):
enabled: bool = False
default_mode: Literal["ask", "auto", "full"] = "ask"
allowed_modes: list[Literal["ask", "auto", "full"]] = Field(default_factory=list)
class VoiceInputFeature(BaseModel):
enabled: bool = False
max_audio_bytes: int = 0
max_duration_seconds: int = 0
class FeaturesResponse(BaseModel): class FeaturesResponse(BaseModel):
"""Frontend-facing feature availability flags.""" """Frontend-facing feature availability flags."""
@ -107,9 +93,6 @@ class FeaturesResponse(BaseModel):
knowledge_base: KnowledgeBaseFeature knowledge_base: KnowledgeBaseFeature
scheduled_tasks: ScheduledTasksFeature scheduled_tasks: ScheduledTasksFeature
thread_activity: ThreadActivityFeature thread_activity: ThreadActivityFeature
run_inputs: bool = False
voice_input: VoiceInputFeature = Field(default_factory=VoiceInputFeature)
tool_approval: ToolApprovalFeature = Field(default_factory=ToolApprovalFeature)
@router.get( @router.get(
@ -121,13 +104,8 @@ class FeaturesResponse(BaseModel):
async def list_features(request: Request, config: AppConfig = Depends(get_config)) -> FeaturesResponse: async def list_features(request: Request, config: AppConfig = Depends(get_config)) -> FeaturesResponse:
"""Return availability of optional frontend features.""" """Return availability of optional frontend features."""
browser = browser_capability(config) browser = browser_capability(config)
approval = getattr(config, "hitl_approval", None)
voice = getattr(config, "voice_input", None)
subagent_batch_worker_running = bool(getattr(request.app.state, "subagent_batches_available", False)) subagent_batch_worker_running = bool(getattr(request.app.state, "subagent_batches_available", False))
return FeaturesResponse( return FeaturesResponse(
voice_input=VoiceInputFeature(enabled=True, max_audio_bytes=voice.max_audio_bytes, max_duration_seconds=voice.max_duration_seconds) if voice is not None else VoiceInputFeature(),
tool_approval=ToolApprovalFeature(enabled=approval.enabled, default_mode=approval.default_mode, allowed_modes=approval.allowed_modes) if approval is not None else ToolApprovalFeature(),
run_inputs=getattr(getattr(request.app.state, "run_manager", None), "input_store", None) is not None,
agents_api=AgentsApiFeature(enabled=config.agents_api.enabled), agents_api=AgentsApiFeature(enabled=config.agents_api.enabled),
browser_control=BrowserControlFeature(enabled=browser.available), browser_control=BrowserControlFeature(enabled=browser.available),
# MCP task bindings and the submitter are startup-scoped. Report the # MCP task bindings and the submitter are startup-scoped. Report the

View File

@ -14,7 +14,6 @@ from pydantic import BaseModel, Field
from app.gateway.authz import require_permission from app.gateway.authz import require_permission
from app.gateway.deps import get_current_user, get_feedback_repo, get_run_store from app.gateway.deps import get_current_user, get_feedback_repo, get_run_store
from deerflow.persistence.feedback import FeedbackAlreadyExistsError
from deerflow.utils.thread_id import ThreadId from deerflow.utils.thread_id import ThreadId
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -134,7 +133,6 @@ async def create_feedback(
raise HTTPException(status_code=404, detail=f"Run {run_id} not found in thread {thread_id}") raise HTTPException(status_code=404, detail=f"Run {run_id} not found in thread {thread_id}")
feedback_repo = get_feedback_repo(request) feedback_repo = get_feedback_repo(request)
try:
return await feedback_repo.create( return await feedback_repo.create(
run_id=run_id, run_id=run_id,
thread_id=thread_id, thread_id=thread_id,
@ -143,11 +141,6 @@ async def create_feedback(
message_id=body.message_id, message_id=body.message_id,
comment=body.comment, comment=body.comment,
) )
except FeedbackAlreadyExistsError:
raise HTTPException(
status_code=409,
detail="Feedback already exists for this run; use PUT to update it",
) from None
@router.get("/{thread_id}/runs/{run_id}/feedback", response_model=list[FeedbackResponse]) @router.get("/{thread_id}/runs/{run_id}/feedback", response_model=list[FeedbackResponse])

View File

@ -257,7 +257,7 @@ async def receive_github_webhook(
# Parse JSON payload after signature is verified (verify-then-parse). # Parse JSON payload after signature is verified (verify-then-parse).
try: try:
parsed = json.loads(body) if body else {} payload: dict[str, Any] = json.loads(body) if body else {}
except json.JSONDecodeError as exc: except json.JSONDecodeError as exc:
logger.warning( logger.warning(
"github_webhook: invalid JSON body (event=%s delivery=%s): %s", "github_webhook: invalid JSON body (event=%s delivery=%s): %s",
@ -266,9 +266,6 @@ async def receive_github_webhook(
exc, exc,
) )
raise HTTPException(status_code=400, detail="Invalid JSON body") from exc raise HTTPException(status_code=400, detail="Invalid JSON body") from exc
if not isinstance(parsed, dict):
raise HTTPException(status_code=400, detail="Invalid JSON body")
payload: dict[str, Any] = parsed
if x_github_event in _KNOWN_EVENTS: if x_github_event in _KNOWN_EVENTS:
logger.info( logger.info(

View File

@ -17,7 +17,7 @@ from deerflow.config.agents_config import load_agent_config
from deerflow.config.app_config import AppConfig from deerflow.config.app_config import AppConfig
from deerflow.knowledge import KnowledgeRequestContext, RetrievalCatalogPage from deerflow.knowledge import KnowledgeRequestContext, RetrievalCatalogPage
from deerflow.knowledge.providers import get_knowledge_capabilities, resolve_knowledge_provider from deerflow.knowledge.providers import get_knowledge_capabilities, resolve_knowledge_provider
from deerflow.runtime.user_context import get_authenticated_user_id, get_effective_user_id from deerflow.runtime.user_context import get_effective_user_id
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/knowledge", tags=["knowledge"]) router = APIRouter(prefix="/api/knowledge", tags=["knowledge"])
@ -94,8 +94,7 @@ async def list_retrieval_catalog_datasets(
config: AppConfig = Depends(get_config), config: AppConfig = Depends(get_config),
) -> dict[str, Any]: ) -> dict[str, Any]:
provider = await _scope_catalog(config, agent_name, request, "catalog") provider = await _scope_catalog(config, agent_name, request, "catalog")
context = KnowledgeRequestContext(user_id=get_effective_user_id(), agent_name=agent_name, authenticated_user_id=get_authenticated_user_id()) return await _catalog_result(provider.catalog(context=KnowledgeRequestContext(user_id=get_effective_user_id(), agent_name=agent_name), page=page, page_size=page_size, search=search))
return await _catalog_result(provider.catalog(context=context, page=page, page_size=page_size, search=search))
@router.get("/retrieval-catalog/datasets/{dataset_id:path}/documents") @router.get("/retrieval-catalog/datasets/{dataset_id:path}/documents")
@ -110,5 +109,4 @@ async def list_retrieval_catalog_documents(
config: AppConfig = Depends(get_config), config: AppConfig = Depends(get_config),
) -> dict[str, Any]: ) -> dict[str, Any]:
provider = await _scope_catalog(config, agent_name, request, "documents") provider = await _scope_catalog(config, agent_name, request, "documents")
context = KnowledgeRequestContext(user_id=get_effective_user_id(), agent_name=agent_name, authenticated_user_id=get_authenticated_user_id()) return await _catalog_result(provider.documents(dataset_id, context=KnowledgeRequestContext(user_id=get_effective_user_id(), agent_name=agent_name), page=page, page_size=page_size, search=search))
return await _catalog_result(provider.documents(dataset_id, context=context, page=page, page_size=page_size, search=search))

View File

@ -8,7 +8,7 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.routing import APIRoute from fastapi.routing import APIRoute
from langchain_core.messages import HumanMessage from langchain_core.messages import HumanMessage
from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator, model_validator from pydantic import BaseModel, ConfigDict, model_validator
from app.gateway.deps import require_admin_user from app.gateway.deps import require_admin_user
from app.gateway.persistent_writes import run_drained_write from app.gateway.persistent_writes import run_drained_write
@ -180,100 +180,3 @@ async def test_model(request: Request, body: SaveModelRequest):
except Exception as exc: except Exception as exc:
# Provider exception strings may contain keys, URLs or response bodies. # Provider exception strings may contain keys, URLs or response bodies.
return {"ok": False, "message": "authentication_failed" if getattr(exc, "status_code", None) in (401, 403) else "connection_failed"} return {"ok": False, "message": "authentication_failed" if getattr(exc, "status_code", None) in (401, 403) else "connection_failed"}
class ModelConnection(BaseModel):
"""A transient connection draft; credentials never enter a browser query cache."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
provider: str = "openai"
base_url: str | None = None
api_key: SecretStr | None = None
saved_model_name: str | None = Field(default=None, max_length=100)
expected_revision: str | None = Field(default=None, max_length=100)
@model_validator(mode="after")
def valid_connection(self):
ManagedModel(provider=self.provider, base_url=self.base_url, api_key=self.api_key, model="catalog-check")
if bool(self.saved_model_name) != bool(self.expected_revision):
raise ValueError("Saved connection requires its revision")
return self
class ImportModelRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
connection: ModelConnection
model: str = Field(min_length=1, max_length=200)
@field_validator("model")
@classmethod
def valid_id(cls, value):
if value != value.strip():
raise ValueError("Invalid model ID")
return ManagedModel.valid_model_id(value)
def _connection_profile(body: ModelConnection, model: str = "catalog-check") -> ManagedModel:
previous = None
if body.saved_model_name:
previous = next((item for item in ManagedModelStore().list() if item.name == body.saved_model_name), None)
if previous is None or previous.revision != body.expected_revision:
raise HTTPException(409, "Connection changed; reload before continuing")
profile = ManagedModel(provider=body.provider, base_url=body.base_url, api_key=body.api_key, model=model)
profile = profile.model_copy(update={"api_key": retained_api_key(profile, previous)})
if profile.provider != "openai-compatible" and not (profile.api_key and profile.api_key.get_secret_value()):
raise HTTPException(422, {"code": "missing_api_key", "message": "Enter the connection API key"})
return profile
def _same_connection(left: ManagedModel, right: ManagedModel) -> bool:
return (left.provider, left.base_url, left.api_key) == (right.provider, right.base_url, right.api_key)
def _existing_import(profile: ManagedModel) -> ManagedModel | None:
return next((item for item in ManagedModelStore().list() if item.model == profile.model and _same_connection(item, profile)), None)
@router.post("/discover")
async def discover_models(request: Request, body: ModelConnection):
from app.gateway.model_discovery import DiscoveryError, fetch_model_catalog
await require_admin_user(request, detail=_ADMIN)
try:
profile = await asyncio.to_thread(_connection_profile, body)
ids, truncated = await fetch_model_catalog(profile)
records = await asyncio.to_thread(lambda: ManagedModelStore().list())
configured = {item.model for item in records if _same_connection(item, profile)}
return {"models": [{"id": mid, "configured": mid in configured} for mid in ids], "truncated": truncated}
except DiscoveryError as exc:
raise HTTPException(502, {"code": exc.code, "message": "Could not retrieve the model catalog"}) from None
except (OSError, ValueError):
raise HTTPException(503, "Managed model storage is unavailable") from None
def _save_import(profile: ManagedModel, connection: ModelConnection):
config = get_app_config()
reserved = {item.name for item in config.models if item.name not in config._managed_model_names}
source = (connection.saved_model_name, connection.expected_revision) if connection.saved_model_name and connection.expected_revision else None
try:
return ManagedModelStore().save(profile, expected_revision=None, reserved_names=reserved, deduplicate=True, expected_source=source).public()
except FileExistsError:
raise HTTPException(409, "Connection changed; reload before importing") from None
@router.post("/import")
async def import_model(request: Request, body: ImportModelRequest):
"""One bounded, retry-safe item. The UI sequences items and reports partial success."""
await require_admin_user(request, detail=_ADMIN)
try:
profile = await asyncio.to_thread(_connection_profile, body.connection, body.model)
existing = await asyncio.to_thread(_existing_import, profile)
if existing:
return {"status": "existing", "model": existing.public()}
probe = await test_model(request, SaveModelRequest(config=profile))
if not probe["ok"]:
return {"status": "failed", "message": probe["message"]}
saved = await run_drained_write("Import managed model", _save_import, (HTTPException,), profile, body.connection)
return {"status": "saved", "model": saved}
except (OSError, ValueError):
raise HTTPException(503, "Managed model storage is unavailable") from None

View File

@ -15,7 +15,6 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_valida
from app.gateway.deps import require_admin_user from app.gateway.deps import require_admin_user
from app.gateway.mcp_oauth_tokens import forget_unconfigured_mcp_oauth_tokens from app.gateway.mcp_oauth_tokens import forget_unconfigured_mcp_oauth_tokens
from app.gateway.persistent_writes import run_drained_write from app.gateway.persistent_writes import run_drained_write
from app.gateway.secret_masking import MASKED_VALUE, mask_secret_values, normalize_config_key
from deerflow.config.extensions_config import ( from deerflow.config.extensions_config import (
ExtensionsConfig, ExtensionsConfig,
McpRoutingConfig, McpRoutingConfig,
@ -458,7 +457,6 @@ class McpServerConfigResponse(BaseModel):
url: str | None = Field(default=None, description="URL of the MCP server (for sse or http type)") url: str | None = Field(default=None, description="URL of the MCP server (for sse or http type)")
headers: dict[str, str] = Field(default_factory=dict, description="HTTP headers to send (for sse or http type)") headers: dict[str, str] = Field(default_factory=dict, description="HTTP headers to send (for sse or http type)")
oauth: McpOAuthConfigResponse | None = Field(default=None, description="OAuth configuration for MCP HTTP/SSE servers") oauth: McpOAuthConfigResponse | None = Field(default=None, description="OAuth configuration for MCP HTTP/SSE servers")
agent_auth: bool = Field(default=False, description="Require an administrator-granted agent credential on this deployment HTTP server")
user_auth: McpUserScopedAuthConfigResponse | None = Field(default=None, description="Per-user credential injection for MCP HTTP/SSE servers") user_auth: McpUserScopedAuthConfigResponse | None = Field(default=None, description="Per-user credential injection for MCP HTTP/SSE servers")
headers_from_context: McpContextHeadersConfigResponse | None = Field(default=None, description="Per-request credential injection for MCP HTTP/SSE servers: map header names to config.context.secrets keys") headers_from_context: McpContextHeadersConfigResponse | None = Field(default=None, description="Per-request credential injection for MCP HTTP/SSE servers: map header names to config.context.secrets keys")
description: str = Field(default="", description="Human-readable description of what this MCP server provides") description: str = Field(default="", description="Human-readable description of what this MCP server provides")
@ -554,19 +552,29 @@ class McpCacheResetResponse(BaseModel):
message: str = Field(description="Human-readable reset status") message: str = Field(description="Human-readable reset status")
_MASKED_VALUE = MASKED_VALUE _MASKED_VALUE = "***"
_SENSITIVE_EXTRA_KEY_RE = re.compile( _SENSITIVE_EXTRA_KEY_RE = re.compile(
r"(^|_)(api_key|apikey|access_key|private_key|client_secret|secret|token|password|passwd|credential|credentials|authorization|bearer)(_|$)", r"(^|_)(api_key|apikey|access_key|private_key|client_secret|secret|token|password|passwd|credential|credentials|authorization|bearer)(_|$)",
re.IGNORECASE, re.IGNORECASE,
) )
def _normalize_config_key(key: str) -> str:
with_boundaries = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", key)
with_boundaries = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", with_boundaries)
return re.sub(r"[^a-z0-9]+", "_", with_boundaries.lower()).strip("_")
def _is_sensitive_extra_key(key: str) -> bool: def _is_sensitive_extra_key(key: str) -> bool:
return bool(_SENSITIVE_EXTRA_KEY_RE.search(normalize_config_key(key))) return bool(_SENSITIVE_EXTRA_KEY_RE.search(_normalize_config_key(key)))
def _mask_sensitive_extra_value(value: Any) -> Any: def _mask_sensitive_extra_value(value: Any) -> Any:
return mask_secret_values(value, _is_sensitive_extra_key) if isinstance(value, dict):
return {key: _MASKED_VALUE if _is_sensitive_extra_key(str(key)) else _mask_sensitive_extra_value(nested) for key, nested in value.items()}
if isinstance(value, list):
return [_mask_sensitive_extra_value(item) for item in value]
return value
def _contains_masked_sensitive_extra_value(key: str, value: Any) -> bool: def _contains_masked_sensitive_extra_value(key: str, value: Any) -> bool:
@ -1107,9 +1115,6 @@ def _merge_preserving_secrets(
} }
if preserve_omitted_fields and "user_auth" not in incoming.model_fields_set: if preserve_omitted_fields and "user_auth" not in incoming.model_fields_set:
update["user_auth"] = existing.user_auth update["user_auth"] = existing.user_auth
# Changing an ordinary field must not silently remove credential enforcement.
if "agent_auth" not in incoming.model_fields_set:
update["agent_auth"] = existing.agent_auth
if preserve_omitted_fields and "headers_from_context" not in incoming.model_fields_set: if preserve_omitted_fields and "headers_from_context" not in incoming.model_fields_set:
update["headers_from_context"] = existing.headers_from_context update["headers_from_context"] = existing.headers_from_context
if preserve_omitted_fields and "routing" not in incoming.model_fields_set: if preserve_omitted_fields and "routing" not in incoming.model_fields_set:
@ -1134,8 +1139,6 @@ def _merge_preserving_secrets(
# it and silently detach an Agent's capability selection. # it and silently detach an Agent's capability selection.
if isinstance(existing_extra.get("capability"), dict): if isinstance(existing_extra.get("capability"), dict):
update["capability"] = existing_extra["capability"] update["capability"] = existing_extra["capability"]
if "user_oauth" not in incoming_extra and "user_oauth" in existing_extra:
update["user_oauth"] = existing_extra["user_oauth"]
merged = incoming.model_copy(update=update) merged = incoming.model_copy(update=update)
_ensure_no_masked_secrets(merged) _ensure_no_masked_secrets(merged)
return merged return merged

View File

@ -1,274 +0,0 @@
"""Administrator API for runtime MCP agent credential grants.
``config.yaml`` keeps which server is protected and which OAuth client each
binding uses. For a binding declared with ``grants: runtime``, administrators
maintain the owners and approved definition digests here; each change applies
to the next call and run without a Gateway restart. A grant covers the agent,
server, destination and OAuth client the binding had when it was approved; if
``config.yaml`` later changes one of them, the grant admits nobody (``approval:
stale``) until an administrator replaces it. A grant whose binding was removed
from ``config.yaml`` is listed as ``approval: retired``. Stale and retired
grants, and grants of disabled bindings, keep their owners reserved for the
agent and server they were approved for, because a configuration rollback or
re-enabling the binding can make them current again; deleting the grant
releases them.
"""
from __future__ import annotations
import asyncio
from typing import Literal
from fastapi import APIRouter, HTTPException, Query, Request, Response
from pydantic import BaseModel
from app.gateway.deps import require_admin_user
from app.gateway.persistent_writes import run_drained_write
from deerflow.config.app_config import AppConfig, get_app_config
from deerflow.config.mcp_agent_auth_config import BindingId, McpAgentCredentialBinding, McpAgentGrant, StoredMcpAgentGrant
from deerflow.config.paths import get_paths
from deerflow.mcp.agent_auth import grant_subject
from deerflow.persistence.mcp_agent_grants import make_mcp_agent_grant_store
router = APIRouter(prefix="/api/mcp/agent-auth", tags=["mcp"])
_ADMIN_REQUIRED_DETAIL = "Admin privileges required to manage MCP agent credentials."
class _InvalidOwner(ValueError):
"""An owner id that file-backed agent storage cannot hold."""
class McpAgentStoredGrantResponse(BaseModel):
"""A runtime grant still stored for a binding that now keeps its grants in config.yaml."""
server: str
agent: str
owners: list[str]
definition_digests: list[str]
class McpAgentBindingResponse(BaseModel):
binding: str
server: str
agent: str
enabled: bool
grants: Literal["config", "runtime"]
# config: owners and digests come from config.yaml. current: the runtime
# grant is in force. stale: it was approved for another agent, server,
# destination or OAuth client and admits nobody. none: no runtime grant.
# retired: a stored grant whose binding is no longer configured; server and
# agent are the ones it was approved for.
approval: Literal["config", "current", "stale", "none", "retired"]
owners: list[str]
definition_digests: list[str]
# A grants: config binding whose earlier runtime grant is still stored: it
# admits nobody but keeps its owners reserved for the server and agent it was
# approved for until it is deleted. None otherwise.
stored_grant: McpAgentStoredGrantResponse | None = None
class McpAgentBindingsResponse(BaseModel):
bindings: list[McpAgentBindingResponse]
class McpAgentDefinitionDigestResponse(BaseModel):
binding: str
agent: str
owner: str
definition_digest: str
def _config() -> AppConfig:
return get_app_config(use_runtime_override=False)
def _binding(config: AppConfig, binding_id: str) -> McpAgentCredentialBinding:
binding = config.mcp_agent_auth.get(binding_id)
if binding is None:
raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured")
return binding
def _runtime_binding(config: AppConfig, binding_id: str) -> McpAgentCredentialBinding:
binding = _binding(config, binding_id)
if binding.grants != "runtime":
raise HTTPException(status_code=409, detail=f"MCP agent binding '{binding_id}' keeps its grants in config.yaml (grants: config)")
return binding
def _response(config: AppConfig, binding_id: str, binding: McpAgentCredentialBinding, grant: StoredMcpAgentGrant | None) -> McpAgentBindingResponse:
"""Owners and digests as configured or stored; ``approval`` says whether a stored grant is in force."""
stored_grant = None
if binding.grants == "config" and grant is not None:
stored_grant = McpAgentStoredGrantResponse(
server=grant.approved_for.server,
agent=grant.approved_for.agent,
owners=list(grant.owners),
definition_digests=list(grant.definition_digests),
)
if binding.grants == "config":
owners, digests, approval = binding.owners, binding.definition_digests, "config"
elif grant is None:
owners, digests, approval = [], [], "none"
else:
owners, digests = grant.owners, grant.definition_digests
approval = "current" if grant.approved_for == grant_subject(config, binding) else "stale"
return McpAgentBindingResponse(
binding=binding_id,
server=binding.server,
agent=binding.agent,
enabled=binding.enabled,
grants=binding.grants,
approval=approval,
owners=list(owners),
definition_digests=list(digests),
stored_grant=stored_grant,
)
def _retired_response(binding_id: str, grant: StoredMcpAgentGrant) -> McpAgentBindingResponse:
"""A stored grant whose binding is no longer configured, described by what it was approved for."""
return McpAgentBindingResponse(
binding=binding_id,
server=grant.approved_for.server,
agent=grant.approved_for.agent,
enabled=False,
grants="runtime",
approval="retired",
owners=list(grant.owners),
definition_digests=list(grant.definition_digests),
)
def _overlapping_binding(config: AppConfig, binding_id: str, binding: McpAgentCredentialBinding, grant: McpAgentGrant) -> str | None:
"""Return another binding that grants, or may grant again, one of these owners the same server and agent.
A stored runtime grant reserves its owners for the agent and server it was
approved for even while it is stale or its binding is gone from
``config.yaml``: a configuration rollback can make it current again, and
two matching grants would then reject the agent at admission. Deleting the
grant releases the owners. A disabled binding reserves its owners too, and
writing a grant to a disabled binding is checked the same way: enabling it
again must not make admission reject both bindings.
"""
owners = set(grant.owners)
for other_id, other in config.mcp_agent_auth.items():
if other_id == binding_id or other.grants != "config":
continue
if other.server == binding.server and other.agent == binding.agent and owners & set(other.owners):
return other_id
for other_id, other_grant in make_mcp_agent_grant_store(config).list().items():
if other_id == binding_id:
continue
subject = other_grant.approved_for
if subject.server == binding.server and subject.agent == binding.agent and owners & set(other_grant.owners):
return other_id
return None
@router.get("", response_model=McpAgentBindingsResponse, summary="List MCP Agent Credential Bindings")
async def list_bindings(request: Request) -> McpAgentBindingsResponse:
"""List every configured binding with the owners and digests in force, then retired grants; OAuth settings are never returned."""
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
config = await asyncio.to_thread(_config)
stored = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).list())
bindings = [_response(config, binding_id, binding, stored.get(binding_id)) for binding_id, binding in sorted(config.mcp_agent_auth.items())]
bindings += [_retired_response(binding_id, grant) for binding_id, grant in sorted(stored.items()) if binding_id not in config.mcp_agent_auth]
return McpAgentBindingsResponse(bindings=bindings)
@router.get("/{binding_id}", response_model=McpAgentBindingResponse, summary="Get MCP Agent Credential Binding")
async def get_binding(binding_id: BindingId, request: Request) -> McpAgentBindingResponse:
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
config = await asyncio.to_thread(_config)
binding = config.mcp_agent_auth.get(binding_id)
if binding is None:
retired = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).get(binding_id))
if retired is None:
raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured")
return _retired_response(binding_id, retired)
grant = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).get(binding_id))
return _response(config, binding_id, binding, grant)
@router.put("/{binding_id}/grants", response_model=McpAgentBindingResponse, summary="Replace Runtime MCP Agent Grant")
async def put_grant(binding_id: BindingId, grant: McpAgentGrant, request: Request) -> McpAgentBindingResponse:
"""Replace the owners and approved digests of a ``grants: runtime`` binding.
Removing an owner denies that owner's next call; removing a digest stops
new runs of that definition, while admitted runs keep the definition they
started with. The grant is recorded for the binding's current agent,
server, destination and OAuth client, and stays in force only while they
are unchanged; rotating the client secret keeps it.
"""
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
config = await asyncio.to_thread(_config)
binding = _runtime_binding(config, binding_id)
subject = grant_subject(config, binding)
if subject is None:
raise HTTPException(status_code=409, detail=f"MCP server '{binding.server}' of binding '{binding_id}' is not configured")
stored = StoredMcpAgentGrant(**grant.model_dump(), approved_for=subject)
overlap = await asyncio.to_thread(_overlapping_binding, config, binding_id, binding, grant)
if overlap is not None:
raise HTTPException(status_code=409, detail=f"Owners overlap with MCP agent binding '{overlap}' for the same server and agent")
try:
await run_drained_write("Replace MCP agent grant", lambda: make_mcp_agent_grant_store(config).put(binding_id, stored), (ValueError,))
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from None
return _response(config, binding_id, binding, stored)
@router.delete("/{binding_id}/grants", status_code=204, summary="Delete Runtime MCP Agent Grant")
async def delete_grant(binding_id: BindingId, request: Request) -> Response:
"""Delete the grant; the binding then admits nobody.
A stored grant left behind after its binding was removed from
``config.yaml`` or moved to ``grants: config`` can be deleted too; that
releases the owners it reserves.
"""
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
config = await asyncio.to_thread(_config)
if await run_drained_write("Delete MCP agent grant", lambda: make_mcp_agent_grant_store(config).delete(binding_id)):
return Response(status_code=204)
binding = config.mcp_agent_auth.get(binding_id)
if binding is None:
raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured and has no stored grant")
_runtime_binding(config, binding_id)
raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' has no runtime grant")
@router.get("/{binding_id}/definition-digest", response_model=McpAgentDefinitionDigestResponse, summary="Compute an Agent Definition Digest")
async def definition_digest(binding_id: BindingId, request: Request, owner: str = Query(min_length=1)) -> McpAgentDefinitionDigestResponse:
"""Digest of ``owner``'s stored copy of the binding's agent, as run admission computes it.
Review that copy before approving its digest: approval covers its settings
and exact SOUL, and any user holding an identical copy who is an owner.
"""
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
config = await asyncio.to_thread(_config)
binding = _binding(config, binding_id)
def compute() -> str | None:
from deerflow.config.agents_config import load_agent_config, load_agent_soul
from deerflow.mcp.agent_auth import agent_definition_digest
if config.agent_storage.backend != "db":
# File-backed agents live under the owner's user directory, so an
# owner id that cannot name one (e.g. "../alice") has no agent there.
try:
get_paths().user_dir(owner)
except ValueError as exc:
raise _InvalidOwner(str(exc)) from None
try:
agent_config = load_agent_config(binding.agent, user_id=owner)
except FileNotFoundError:
return None
return agent_definition_digest(agent_config, load_agent_soul(binding.agent, user_id=owner) or "")
try:
digest = await asyncio.to_thread(compute)
except _InvalidOwner as exc:
raise HTTPException(status_code=422, detail=f"Invalid owner for file-backed agent storage: {exc}") from None
if digest is None:
raise HTTPException(status_code=404, detail=f"User '{owner}' has no agent '{binding.agent}'")
return McpAgentDefinitionDigestResponse(binding=binding_id, agent=binding.agent, owner=owner, definition_digest=digest)

View File

@ -1,143 +0,0 @@
"""Browser-owned grants for operator-configured MCP connections."""
import asyncio
import hashlib
import logging
import re
import secrets
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import JSONResponse, RedirectResponse
from pydantic import BaseModel
from app.gateway.auth.session_cookie import ACCESS_TOKEN_COOKIE_NAME
from app.gateway.csrf_middleware import is_secure_request
from app.gateway.deps import get_current_user_from_request
from app.gateway.routers.auth import require_session_source
from deerflow.config.extensions_config import MCP_USER_OAUTH_CALLBACK_PATH
from deerflow.mcp import browser_oauth as oauth
from deerflow.mcp.oauth_store import McpOAuthTokenKey, McpOAuthTokenStoreUnavailable, get_mcp_oauth_token_store
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/mcp/user-oauth", tags=["mcp"])
_STATE = re.compile(r"[A-Za-z0-9_-]{43}\Z")
_LANDING = "/workspace/capabilities?tab=plugins&mcp_oauth={status}#my-mcp-connections"
class Connection(BaseModel):
server_key: str
display_name: str
status: str
class Connections(BaseModel):
connections: list[Connection]
async def _owner(request: Request) -> str:
require_session_source(request)
user = await get_current_user_from_request(request)
return str(user.id)
def _browser_binding(request: Request, nonce: str) -> str:
# Bind this browser attempt to the exact authenticated login session.
session = request.cookies[ACCESS_TOKEN_COOKIE_NAME]
return hashlib.sha256(f"{session}:{nonce}".encode()).hexdigest()
def _store():
store = get_mcp_oauth_token_store()
if store is None:
raise HTTPException(503, "MCP user OAuth requires shared SQL storage.")
return store
async def _servers():
try:
return await asyncio.to_thread(oauth.configured_servers)
except Exception:
raise HTTPException(503, "MCP server configuration is unavailable.") from None
async def _server(name):
server = (await _servers()).get(name)
if server is None:
raise HTTPException(404, "This MCP server does not offer user authorization.")
return server
@router.get("", response_model=Connections)
async def list_connections(response: Response, owner: str = Depends(_owner)):
servers = await _servers()
def list_rows():
result = []
for name, server in servers.items():
try:
state = oauth.connection_state(name, server, owner)
except McpOAuthTokenStoreUnavailable:
state = "unavailable"
result.append(Connection(server_key=name, display_name=name, status=state))
store = get_mcp_oauth_token_store()
if store is not None:
try:
saved = store.list_delegated_servers(owner)
except McpOAuthTokenStoreUnavailable:
raise HTTPException(503, "MCP authorization storage is unavailable.") from None
result.extend(Connection(server_key=name, display_name=name, status="removed") for name in saved if name not in servers)
return result
response.headers["Cache-Control"] = "no-store"
return Connections(connections=await asyncio.to_thread(list_rows))
@router.post("/{server_key}/connect")
async def connect(server_key: str, request: Request, owner: str = Depends(_owner)):
_store()
server = await _server(server_key)
state, binding = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
try:
destination = await oauth.begin_connection(server_key, server, owner, _browser_binding(request, binding), state)
except oauth.BrowserOAuthError as exc:
raise HTTPException(502, str(exc)) from None
except McpOAuthTokenStoreUnavailable:
raise HTTPException(503, "MCP authorization storage is unavailable.") from None
except Exception:
raise HTTPException(502, "Could not start MCP authorization. Check the server configuration.") from None
response = JSONResponse({"authorization_url": destination}, headers={"Cache-Control": "no-store"})
response.set_cookie("df_mcp_" + state, binding, max_age=300, path=MCP_USER_OAUTH_CALLBACK_PATH, httponly=True, samesite="lax", secure=is_secure_request(request))
return response
@router.get("/callback", response_class=RedirectResponse)
async def callback(request: Request, owner: str = Depends(_owner)):
state = request.query_params.get("state", "")
valid_state = bool(_STATE.fullmatch(state))
cookie = "df_mcp_" + state if valid_state else ""
binding = request.cookies.get(cookie) if cookie else None
ok = False
if binding:
try:
attempt = await asyncio.to_thread(_store().consume_delegated, state, owner_user_id=owner, browser_binding=_browser_binding(request, binding))
code = request.query_params.get("code")
issued_by = request.query_params.get("iss")
if attempt and code and len(code) <= 8192 and not request.query_params.get("error") and (issued_by is None or issued_by == attempt.context.issuer):
server = await _server(attempt.key.server_key)
ok = await oauth.finish_connection(attempt, server, code)
except Exception as exc:
# Provider and storage exceptions may contain credentials.
logger.warning("MCP user OAuth callback failed (%s)", type(exc).__name__)
response = RedirectResponse(_LANDING.format(status="connected" if ok else "failed"), status_code=303, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
if cookie:
response.delete_cookie(cookie, path=MCP_USER_OAUTH_CALLBACK_PATH, httponly=True, samesite="lax", secure=is_secure_request(request))
return response
@router.delete("/{server_key}", status_code=204)
async def disconnect(server_key: str, owner: str = Depends(_owner)):
try:
await asyncio.to_thread(_store().disconnect_delegated, McpOAuthTokenKey.for_delegated(server_key, owner))
except McpOAuthTokenStoreUnavailable:
raise HTTPException(503, "MCP authorization storage is unavailable.") from None
return Response(status_code=204, headers={"Cache-Control": "no-store"})

View File

@ -1,7 +1,6 @@
"""Memory API router for retrieving and managing global memory data.""" """Memory API router for retrieving and managing global memory data."""
import asyncio import asyncio
import re
from typing import Any, Literal from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
@ -10,13 +9,11 @@ from pydantic import BaseModel, Field, field_validator
from app.gateway.authz import require_permission from app.gateway.authz import require_permission
from app.gateway.internal_auth import get_trusted_internal_owner_user_id from app.gateway.internal_auth import get_trusted_internal_owner_user_id
from app.gateway.persistent_writes import run_drained_write from app.gateway.persistent_writes import run_drained_write
from app.gateway.secret_masking import mask_secret_values, normalize_config_key from deerflow.agents.memory import MemoryConflictError, MemoryCorruptionError, MemoryManager, get_memory_manager
from deerflow.agents.memory import MemoryConflictError, MemoryCorruptionError, MemoryDuplicateFactIdError, MemoryManager, get_memory_manager
from deerflow.config.agents_config import AGENT_NAME_PATTERN from deerflow.config.agents_config import AGENT_NAME_PATTERN
from deerflow.config.memory_config import get_memory_config from deerflow.config.memory_config import get_memory_config
from deerflow.config.paths import make_safe_user_id from deerflow.config.paths import make_safe_user_id
from deerflow.runtime.user_context import get_effective_user_id from deerflow.runtime.user_context import get_effective_user_id
from deerflow.utils.host_paths import windows_incompatible_segment
router = APIRouter(prefix="/api", tags=["memory"]) router = APIRouter(prefix="/api", tags=["memory"])
@ -120,12 +117,6 @@ class MemoryResponse(BaseModel):
facts: list[Fact] = Field(default_factory=list) facts: list[Fact] = Field(default_factory=list)
class MemoryImportRequest(MemoryResponse):
"""Replacement imports must explicitly supply the facts to restore."""
facts: list[Fact] = Field(description="Facts to restore. An empty list explicitly clears the selected fact bucket.")
def _map_memory_fact_value_error(exc: ValueError) -> HTTPException: def _map_memory_fact_value_error(exc: ValueError) -> HTTPException:
"""Convert updater validation errors into stable API responses.""" """Convert updater validation errors into stable API responses."""
if exc.args and exc.args[0] == "confidence": if exc.args and exc.args[0] == "confidence":
@ -168,8 +159,6 @@ def _unsupported_501(manager: object, label: str) -> HTTPException:
def _management_agent_name_or_501( def _management_agent_name_or_501(
manager: MemoryManager, manager: MemoryManager,
agent_name: str | None, agent_name: str | None,
*,
for_creation: bool = False,
) -> str | None: ) -> str | None:
"""Validate an optional agent-scoped management target. """Validate an optional agent-scoped management target.
@ -179,16 +168,6 @@ def _management_agent_name_or_501(
into a mutation of the wrong bucket. Preserve the caller's spelling here: into a mutation of the wrong bucket. Preserve the caller's spelling here:
remote backends such as Mem0 use the agent name as a case-sensitive storage remote backends such as Mem0 use the agent name as a case-sensitive storage
identity, while DeerMem performs its own lowercase canonicalization. identity, while DeerMem performs its own lowercase canonicalization.
``for_creation`` also refuses names that cannot become a host path
component. DeerMem resolves an agent scope to
``{storage}/users/{uid}/agents/{name}/facts`` and creates it on the first
write; the character class above admits Windows reserved device names
(``NUL``, ``CON``, ``COM1``, ...), so that write raised
``FileNotFoundError`` and the endpoint's ``OSError`` branch answered
``500``. Only the two endpoints that create the scope set this: reads and
deletes stay permissive so a scope an older release stored can still be
exported and cleared.
""" """
if agent_name is None: if agent_name is None:
return None return None
@ -197,20 +176,6 @@ def _management_agent_name_or_501(
status_code=422, status_code=422,
detail=(f"Invalid agent name '{agent_name}'. Must match {AGENT_NAME_PATTERN.pattern} (letters, digits, and hyphens only)."), detail=(f"Invalid agent name '{agent_name}'. Must match {AGENT_NAME_PATTERN.pattern} (letters, digits, and hyphens only)."),
) )
if for_creation:
# Reuse the canonical Windows-name check that agent directories,
# thread IDs, uploads, sandbox writes and skill support files use.
# Sibling PR #7939 applies the same rule inside the shared
# ``validate_agent_name()`` (``deerflow.config.agents_config``); this
# router inlines ``AGENT_NAME_PATTERN`` and preserves caller spelling for
# case-sensitive backends rather than delegating to it, so keep the two
# copies in sync if the reserved set ever changes.
reason = windows_incompatible_segment(agent_name)
if reason is not None:
raise HTTPException(
status_code=422,
detail=f"Invalid agent name '{agent_name}'. Contains a {reason}.",
)
if getattr(manager, "supports_agent_scoped_management", False) is not True: if getattr(manager, "supports_agent_scoped_management", False) is not True:
raise HTTPException( raise HTTPException(
status_code=501, status_code=501,
@ -269,18 +234,6 @@ class FactPatchRequest(BaseModel):
confidence: float | None = Field(default=None, ge=0.0, le=1.0, description="Confidence score (0-1)") confidence: float | None = Field(default=None, ge=0.0, le=1.0, description="Confidence score (0-1)")
# Anchored at the end of the key: DeerMem knobs such as ``token_counting`` and
# ``guaranteed_token_budget`` are not secrets, and ``api_key_env`` names an
# environment variable rather than holding the key. This is a denylist: plural
# ``tokens`` stays out because ``max_injection_tokens`` is a knob, and bare
# ``key``, ``auth`` or ``session`` are too generic to mask.
_SECRET_CONFIG_KEY_RE = re.compile(r"(^|_)(api_?keys?|access_keys?|secret_keys?|private_keys?|auth_keys?|secrets?|token|passwords?|passwds?|credentials?|authorization|bearer|cookies?)$")
def _is_secret_config_key(key: str) -> bool:
return bool(_SECRET_CONFIG_KEY_RE.search(normalize_config_key(key)))
class MemoryConfigResponse(BaseModel): class MemoryConfigResponse(BaseModel):
"""Response model for memory configuration.""" """Response model for memory configuration."""
@ -289,13 +242,7 @@ class MemoryConfigResponse(BaseModel):
injection_enabled: bool = Field(..., description="Whether memory is injected into the system prompt (call-site gate).") injection_enabled: bool = Field(..., description="Whether memory is injected into the system prompt (call-site gate).")
shutdown_flush_timeout_seconds: float = Field(..., description="Hard budget (s) to drain pending memory updates on Gateway graceful shutdown; must fit inside the pod's K8s terminationGracePeriodSeconds.") shutdown_flush_timeout_seconds: float = Field(..., description="Hard budget (s) to drain pending memory updates on Gateway graceful shutdown; must fit inside the pod's K8s terminationGracePeriodSeconds.")
manager_class: str = Field(..., description="Active memory backend selector (backend name or dotted path).") manager_class: str = Field(..., description="Active memory backend selector (backend name or dotted path).")
backend_config: dict = Field(..., description="Backend-private config (self-interpreted by the backend); credential values such as api_key are masked as ***.") backend_config: dict = Field(..., description="Backend-private config (self-interpreted by the backend).")
@field_validator("backend_config")
@classmethod
def _mask_backend_secrets(cls, value: dict) -> dict:
"""Config loading already resolved ``$VAR`` references, so keys would be plaintext."""
return mask_secret_values(value, _is_secret_config_key, keep_unset=True)
class MemoryStatusResponse(BaseModel): class MemoryStatusResponse(BaseModel):
@ -445,7 +392,7 @@ async def clear_memory(request: Request, agent_name: str | None = None) -> Memor
async def create_memory_fact_endpoint(body: FactCreateRequest, request: Request, agent_name: str | None = None) -> MemoryResponse: async def create_memory_fact_endpoint(body: FactCreateRequest, request: Request, agent_name: str | None = None) -> MemoryResponse:
"""Create a single fact manually.""" """Create a single fact manually."""
manager = await asyncio.to_thread(get_memory_manager) manager = await asyncio.to_thread(get_memory_manager)
selected_agent = _management_agent_name_or_501(manager, agent_name, for_creation=True) selected_agent = _management_agent_name_or_501(manager, agent_name)
scope_kwargs = _agent_scope_kwargs(selected_agent) scope_kwargs = _agent_scope_kwargs(selected_agent)
try: try:
memory_data, fact_id = await run_drained_write( memory_data, fact_id = await run_drained_write(
@ -572,16 +519,13 @@ async def export_memory(request: Request, agent_name: str | None = None) -> Memo
response_model=MemoryResponse, response_model=MemoryResponse,
response_model_exclude_none=True, response_model_exclude_none=True,
summary="Import Memory Data", summary="Import Memory Data",
description=( description="Import the default memory document, or replace only one selected agent's facts while preserving shared summaries.",
"Import the default memory document, or replace only one selected agent's facts while preserving shared summaries. "
"The request requires an explicit `facts` array. Omitting it returns HTTP 422, and an empty array clears the selected fact bucket."
),
) )
@require_permission("memory", "write") @require_permission("memory", "write")
async def import_memory(body: MemoryImportRequest, request: Request, agent_name: str | None = None) -> MemoryResponse: async def import_memory(body: MemoryResponse, request: Request, agent_name: str | None = None) -> MemoryResponse:
"""Import memory data, preserving shared summaries for a selected agent.""" """Import memory data, preserving shared summaries for a selected agent."""
manager = await asyncio.to_thread(get_memory_manager) manager = await asyncio.to_thread(get_memory_manager)
selected_agent = _management_agent_name_or_501(manager, agent_name, for_creation=True) selected_agent = _management_agent_name_or_501(manager, agent_name)
scope_kwargs = _agent_scope_kwargs(selected_agent) scope_kwargs = _agent_scope_kwargs(selected_agent)
try: try:
memory_data = await run_drained_write( memory_data = await run_drained_write(
@ -596,8 +540,6 @@ async def import_memory(body: MemoryImportRequest, request: Request, agent_name:
raise _unsupported_501(manager, "import memory") from None raise _unsupported_501(manager, "import memory") from None
except (MemoryConflictError, MemoryCorruptionError) as exc: except (MemoryConflictError, MemoryCorruptionError) as exc:
raise _map_memory_manager_error(exc) from exc raise _map_memory_manager_error(exc) from exc
except MemoryDuplicateFactIdError as exc:
raise HTTPException(status_code=400, detail="Invalid memory import: fact IDs must be unique.") from exc
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=400, detail="Invalid memory import: facts must be a list of objects with non-empty content.") from exc raise HTTPException(status_code=400, detail="Invalid memory import: facts must be a list of objects with non-empty content.") from exc
except OSError as exc: except OSError as exc:
@ -645,7 +587,7 @@ async def get_memory_config_endpoint(request: Request) -> MemoryConfigResponse:
} }
``` ```
""" """
config = await asyncio.to_thread(get_memory_config) config = get_memory_config()
return MemoryConfigResponse( return MemoryConfigResponse(
enabled=config.enabled, enabled=config.enabled,
mode=config.mode, mode=config.mode,
@ -670,7 +612,7 @@ async def get_memory_status(request: Request, agent_name: str | None = None) ->
Returns: Returns:
Combined memory configuration and current data. Combined memory configuration and current data.
""" """
config = await asyncio.to_thread(get_memory_config) config = get_memory_config()
manager = await asyncio.to_thread(get_memory_manager) manager = await asyncio.to_thread(get_memory_manager)
selected_agent = _management_agent_name_or_501(manager, agent_name) selected_agent = _management_agent_name_or_501(manager, agent_name)
memory_data = await _get_memory_or_501( memory_data = await _get_memory_or_501(

View File

@ -66,7 +66,6 @@ class ModelResponse(BaseModel):
description: str | None = Field(None, description="Model description") description: str | None = Field(None, description="Model description")
supports_thinking: bool = Field(default=False, description="Whether model supports thinking mode (deprecated: derived from `reasoning`)") supports_thinking: bool = Field(default=False, description="Whether model supports thinking mode (deprecated: derived from `reasoning`)")
supports_reasoning_effort: bool = Field(default=False, description="Whether model supports reasoning effort (deprecated: derived from `reasoning`)") supports_reasoning_effort: bool = Field(default=False, description="Whether model supports reasoning effort (deprecated: derived from `reasoning`)")
provider: str | None = Field(default=None, description="Managed provider display label; no endpoint or credentials")
reasoning: ReasoningCapabilitiesResponse = Field(..., description="Normalized reasoning capability contract") reasoning: ReasoningCapabilitiesResponse = Field(..., description="Normalized reasoning capability contract")
@ -76,7 +75,6 @@ def _model_response(model: ModelConfig) -> ModelResponse:
model=model.model, model=model.model,
display_name=model.display_name, display_name=model.display_name,
description=model.description, description=model.description,
provider=model._managed_provider,
supports_thinking=model.supports_thinking, supports_thinking=model.supports_thinking,
supports_reasoning_effort=model.supports_reasoning_effort, supports_reasoning_effort=model.supports_reasoning_effort,
reasoning=ReasoningCapabilitiesResponse(**reasoning_capabilities_payload(resolve_reasoning_contract(model))), reasoning=ReasoningCapabilitiesResponse(**reasoning_capabilities_payload(resolve_reasoning_contract(model))),
@ -197,7 +195,7 @@ async def list_models(
owner = await _resolve_bound_owner_for_model_list(request) owner = await _resolve_bound_owner_for_model_list(request)
principal_user = owner if owner is not None else user principal_user = owner if owner is not None else user
try: try:
provider, principal = await asyncio.to_thread(resolve_model_authorization, principal_user, is_internal=_is_internal_caller(request, user)) provider, principal = resolve_model_authorization(principal_user, is_internal=_is_internal_caller(request, user))
except _AuthorizationUnavailable as exc: except _AuthorizationUnavailable as exc:
if exc.fail_closed: if exc.fail_closed:
visible_models = [] visible_models = []
@ -263,6 +261,6 @@ async def get_model(
# model exists but the role lacks permission to use it). # model exists but the role lacks permission to use it).
user = await get_optional_user_from_request(request) user = await get_optional_user_from_request(request)
if user is not None: if user is not None:
await asyncio.to_thread(authorize_model_use, user, model_name, is_internal=_is_internal_caller(request, user), app_config=config) authorize_model_use(user, model_name, is_internal=_is_internal_caller(request, user), app_config=config)
return _model_response(model) return _model_response(model)

Some files were not shown because too many files have changed in this diff Show More