deer-flow / backend
AGENTS.md83k starsChanged 5 months agoMITView on GitHub
The backend runs a LangGraph-based super agent with sandbox execution, persistent memory, subagent delegation, and extensible tools in isolated per-thread environments. Architecture: - Gateway API (port 8001): REST API plus embedded LangGraph-compatible agent runtime - Frontend (port 3000): Next.js web interface - Nginx (port 2026): Unified reverse proxy entry point - Provisioner (port 8002, optional in Docker dev): Started only when sandbox is configured for provisioner/Kubernetes mode Runtime: - make dev, Docker dev, and production all run the agent runtime…
Trending
More talk lately.about the whole repository
Who's talking about bytedance/deer-flow
- @sungkim.bsky.social“ByteDance's DeerFlow A framework for deep research, combining language models with tools like web search, …”Bluesky · May 11, 2025 · 17 likes
- @langchain.bsky.social“🔬 DeerFlow: Deep Research Framework An open-source framework for conducting systematic deep research …”Bluesky · May 12, 2025 · 8 likes
- A Hacker News story“Has Anyone Tried Deerflow?”Hacker News · Mar 27, 2026 · 4 points
- A Hacker News story“DeerFlow, a community-driven Deep Research framework”Hacker News · May 12, 2025 · 4 points
- @toolhunt.bsky.social“ByteDance выкатили deer-flow — открытый SuperAgent harness для долгосрочных задач, который сам кодит, …”Bluesky · Aug 19, 2026 · 3 likes
The biggest 5 of 79 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 79
Talked about on GitHub, Bluesky and Hacker News (79 times).
On GitHub · 50
- Jun 22, 2026feat(agents): add DeerFlow (bytedance/deer-flow) framework support — jaylfc/taOS2 reactions · 4 comments
- Feb 26, 2026[Add App]DeerFlow - 2.0 — beclab/apps2 reactions · 1 comment
- May 31, 2025更加炫酷的打字动画 — ant-design/x2 reactions · 1 comment
- Mar 7, 2026Feature: Automatic Session Title Generation — Lightweight LLM-Based Title After First Exchange (inspired by DeerFlow) — NousResearch/hermes-agent1 reaction · 5 comments
- Nov 26, 2025Explore integrating deer-flow into research features — XJTU-RL/Power-Planer1 reaction
45 more on GitHub
- May 12, 2025Request - Bytedance DeerFlow Integration — onyx-dot-app/onyx1 reaction · 2 comments
- Nov 18, 2026North+GLM wildcard experiment (epoch 21): When a tool output exceeds the observation budget, the agent should automatically revise its plan to insert a recall step that fetches the missing tail via read_offloaded, ensuring the full output can be retrieved without exceeding the budget. — DervinEvolve/AI-Agent0 reactions
- Nov 11, 2026Extra Fingerprints to add — SocksTheWolf/AgenticAlert0 reactions · 1 comment
- Nov 10, 2026fix(models): add opt-in merge of consecutive user messages (#6751) — wycocoyu/deer-flow0 reactions
- Nov 10, 2026fix(frontend): restore the draft and welcome state when a new session send fails (upstream #8039) — Zhong-fan/deer-flow0 reactions · 2 comments
- Nov 9, 2026fix(agents): count vLLM reasoning tokens in the summarization trigger (upstream #8074) — Zhong-fan/deer-flow0 reactions · 1 comment
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions · 2 comments
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 9, 2026fix(gateway): evict completed RunRecords in production (upstream #5009) — Zhong-fan/deer-flow0 reactions
- Nov 4, 2026agent-skills.github.bytedance.deer-flow: 2.1.0 → 2.2.0 — sudosubin/agents.nix0 reactions
- Nov 4, 2026claude-code-plugins.github.bytedance.deer-flow: 2.1.0 → 2.2.0 — sudosubin/agents.nix0 reactions
- Oct 28, 2026fix(subagents): validate recovery before superseding source tasks — Aldenshile/deer-flow0 reactions
- Oct 26, 2026Add licensed skills, reusable materials, and source catalogues — EmbeddedLLM/nice-skills0 reactions
- Oct 26, 2026[Feature] Sub Agent 派生与 Agent 能力分档 — Code-MonkeyZhang/persona-agent0 reactions
- Oct 26, 2026[Refactor] Agent Core 拓扑重构以支撑能力分档与 Sub Agent — Code-MonkeyZhang/persona-agent0 reactions
- Oct 24, 2026fix(agent): enforce delegated skill scope and show saved progress — pyrelio88-afk/Selenyx0 reactions
- Oct 20, 2026Capability request: BoxLite sandbox (local micro-VM workspace backend) — pydantic/pydantic-ai0 reactions · 1 comment
- Oct 20, 2026Context runtime acceptance: accurate budgets, cancellation and durable task continuity — bei-shan/WodeAgent0 reactions
- Oct 19, 2026Framework drift review required — aporthq/aport-agent-guardrails0 reactions · 4 comments
- Oct 19, 2026fix(channels): acknowledge GitHub comments queued during a busy run — wannT-1/deer-flow0 reactions
- Oct 17, 2026fix(vikingbot): screen web search result URLs — volcengine/OpenViking0 reactions
- Oct 15, 2026fix(vikingbot): reconcile streaming token usage — volcengine/OpenViking0 reactions
- Oct 15, 2026sandbox: E2B cloud micro-VM provider and distributed ownership protocol — bei-shan/WodeAgent0 reactions
- Oct 15, 2026sandbox: session-scoped SandboxProvider API, BoxLite warm VM pool and file operations — bei-shan/WodeAgent0 reactions
- Oct 11, 2026Add DeerFlow and its optional Parallel Search MCP example — kyrolabs/awesome-langchain0 reactions
- Oct 10, 2026fix(bot): replay Gemini tool-call thought signatures — volcengine/OpenViking0 reactions
- Oct 7, 2026fix(parse): reject colliding ZIP member paths — volcengine/OpenViking0 reactions
- Oct 5, 2026fix(parse): handle mixed-case Markdown artifacts — volcengine/OpenViking0 reactions
- Oct 4, 2026fix(config): handle localhost case-insensitively — volcengine/OpenViking0 reactions
- Oct 4, 2026claude-code-plugins.github.bytedance.deer-flow: init at 2.1.0 — sudosubin/agents.nix0 reactions
- Oct 3, 2026agent-skills.github.bytedance.deer-flow: init at 2.1.0 — sudosubin/agents.nix0 reactions
- Sep 27, 2026fix: restrict redirect schemes and discard intermediate response bodies — chenhz01/adversarial-research-audit0 reactions · 1 comment
- Sep 20, 2026Add Runtime execution budgets — GK-studio-JP/ai-os-runtime0 reactions
- Sep 20, 2026Add bounded Context Capsule budget and provenance — GK-studio-JP/ai-os-context0 reactions
- Sep 20, 2026Port DeerFlow safety to Browser Worker relay — GK-studio-JP/ai-os-runtime-browser-worker0 reactions
- Sep 10, 2026feat(discovery): 週に一度、新しく出たツールの候補を集めて PR にする — konweb/nanteyomu0 reactions · 1 comment
- Sep 8, 2026fix(subagents): tear down dispatched child before batch retry — Zsanz3/deer-flow0 reactions · 2 comments
- Sep 3, 2026feat(wizard): add aimlapi.com as an LLM provider — aimlapi/deer-flow-aimlapi0 reactions
- Aug 31, 2026fix(lark): allow Windows hosts to prepare Linux sandbox CLI runtime — Zsanz3/deer-flow0 reactions · 3 comments
- Aug 24, 2026[¥200 验收后付] DeerFlow #532 多轮 Deep Research 连续上下文实现 — snownico0722/snownico0722.github.io0 reactions
- Aug 19, 2026[Integration] bytedance/deer-flow — You.com web_search provider + setup wizard entry — youdotcom-oss/integration-tracking0 reactions · 17 comments
On Bluesky · 21
- May 11, 2025ByteDance's DeerFlow A framework for deep research, combining language models with tools like web search, crawling, and Python execution,… — @sungkim.bsky.social17 likes and reposts
- May 12, 2025🔬 DeerFlow: Deep Research Framework An open-source framework for conducting systematic deep research through coordinated LangGraph agents.… — @langchain.bsky.social8 likes and reposts
- Aug 19, 2026ByteDance выкатили deer-flow — открытый SuperAgent harness для долгосрочных задач, который сам кодит, исследует и автоматизирует рутину от… — @toolhunt.bsky.social3 likes and reposts
- May 6, 2026🚀 Skyrocketing! 🚀 (200+ new stars) 📦 bytedance / deer-flow ⭐ 65,357 (+328) 🗒 Python An open-source long-horizon SuperAgent harness that… — @github-trending.bsky.social3 likes and reposts · 1 reply
- Mar 31, 2026This GitHub project caught my eye: DeerFlow 2.0 is a fully extensible super agent platform for smart automation, custom workflows, and deep… — @alexiskirke.bsky.social3 likes and reposts
16 more on Bluesky
- Jun 21, 2026今日のGitHubトレンド bytedance/deer-flow DeerFlowは、サブエージェント、メモリ、サンドボックスを統合し、拡張可能なスキルによって多様なタスクを実行するオープンソースのスーパーエージェントハーネスです。… — @dailygithubtrends.bsky.social2 likes and reposts
- Feb 26, 2026ByteDance's DeerFlow is a TypeScript super-agent that orchestrates sub-agents, sandboxes, and persistent memory to tackle complex… — @arifsolmaz.bsky.social2 likes and reposts · 1 reply
- Sep 7, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 bytedance / deer-flow ⭐ 81,682 (+188) 🗒 Python An open-source long-horizon SuperAgent harness that… — @github-trending.bsky.social1 likes and repost
- Mar 27, 2026💎 Hidden Gem! 💎 (1000+ new stars) 📦 bytedance / deer-flow ⭐ 47,567 (+2,388) 🗒 Python An open-source long-horizon SuperAgent harness… — @github-trending.bsky.social1 likes and repost · 1 reply
- Mar 12, 2026Repo: github.com/bytedance/de... Here's why this is different from every other agent framework: It has its own sandbox. A real isolated… — @jainamparmar.bsky.social1 likes and repost · 2 replies
- Mar 12, 2026github.com/bytedance/de... github.com/AlexsJones/s... github.com/AlexsJones/l... Sharing more repos to later crawl my own page for data… — @moe-dude.bsky.social1 likes and repost
- Mar 11, 2026DeerFlow : framework open-source d'agents IA orchestrant recherche, code et création — @news.humancoders.com1 likes and repost
- Mar 10, 2026💎 Hidden Gem! 💎 (1000+ new stars) 📦 bytedance / deer-flow ⭐ 27,977 (+1,443) 🗒 Python An open-source SuperAgent harness that researches,… — @github-trending.bsky.social1 likes and repost · 1 reply
- Mar 9, 2026DeerFlow : un framework open-source qui orchestre des sous-agents, mémoire et sandboxes pour gérer des tâches complexes de recherche et… — @camilleroux.com1 likes and repost
- Mar 1, 2026🚀 Skyrocketing! 🚀 (200+ new stars) 📦 bytedance / deer-flow ⭐ 22,795 (+352) 🗒 Python An open-source SuperAgent harness that researches,… — @github-trending.bsky.social1 likes and repost · 1 reply
- May 23, 2025DeerFlow DeerFlow is a community-driven framework for deep research, combining language models with tools like web search, crawling, and… — @pythonhub.dev1 likes and repost
- Aug 1, 2026🚀 Skyrocketing! 🚀 (200+ new stars) 📦 bytedance / deer-flow ⭐ 78,536 (+204) 🗒 Python An open-source long-horizon SuperAgent harness that… — @github-trending.bsky.social0 likes and reposts · 1 reply
- Jul 11, 2026READMEで確認できたのは、DeerFlow 自体はMITのOSS。でも初期設定ではLLMプロバイダと任意のWeb検索を選び、鍵は `.env` に入れる設計です。Docker推奨で、ローカルLLMを動かすなら必要な計算資源も別。… — @mint-echosphere.bsky.social0 likes and reposts · 1 reply
- Jun 27, 2026READMEで確認できた範囲だと、2.0が全面書き直し、MIT、sub-agents / memory / sandbox、そして「minutes to hours」の長尺タスク志向は本当です。ここはちゃんと強い。… — @mint-echosphere.bsky.social0 likes and reposts · 1 reply
- Jun 21, 2026🚀 Skyrocketing! 🚀 (200+ new stars) 📦 bytedance / deer-flow ⭐ 72,237 (+415) 🗒 Python An open-source long-horizon SuperAgent harness that… — @github-trending.bsky.social0 likes and reposts · 1 reply
- Mar 22, 2026💎 Hidden Gem! 💎 (1000+ new stars) 📦 bytedance / deer-flow ⭐ 33,811 (+1,508) 🗒 Python An open-source SuperAgent harness that researches,… — @github-trending.bsky.social0 likes and reposts · 1 reply
On Hacker News · 8
- Mar 27, 2026Has Anyone Tried Deerflow?4 points
- May 12, 2025DeerFlow, a community-driven Deep Research framework4 points
- Mar 30, 2026Deer-Flow Installing Line3 points · 1 comment
- Mar 16, 2026Deep Exploration and Efficient Research Flow2 points
- Mar 15, 2026DeerFlow 2.0: open-source SuperAgent harness that researches, codes, creates2 points
3 more on Hacker News
- May 13, 2025DeerFlow: Deep Research Framework2 points
- May 18, 2026DeerFlow 2.0 – Deep Exploration and Efficient Research Flow1 point
- Apr 18, 2026An open-source long-horizon SuperAgent harness that researches,codes and creates1 point · 1 comment
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository30 other files it gives its agents.
- AGENTS.mdAGENTS.md
- frontend/AGENTS.mdAGENTS.md
- scripts/AGENTS.mdAGENTS.md
- backend/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- frontend/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- academic-paper-reviewSkill
- bootstrapSkill
- chart-visualizationSkill
- claude-to-deerflowSkill
- code-documentationSkill
- consulting-analysisSkill
- data-analysisSkill
- deep-researchSkill
- find-skillsSkill
- frontend-designSkill
- github-deep-researchSkill
- image-generationSkill
- music-generationSkill
- newsletter-generationSkill
- podcast-generationSkill
- ppt-generationSkill
- skill-creatorSkill
- skill-reviewerSkill
- surprise-meSkill
- systematic-literature-reviewSkill
- vercel-deploySkill
- video-generationSkill
- web-design-guidelinesSkill
The file
We split this AGENTS.md into the rules it gives an agent
10 rules. About 2 are common, 2 are distinctive, and 6 are very specific to this project.
≈2
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Distinctive: line 88
Every code change must keep docs accurate and current: update README.md for user-facing behavior and the relevant AGENTS.md for development …
- Common: line 102
Never commit upstream dataset text, credentials, complete provider requests, or response headers.
- Common: line 105
Read provider credentials and endpoints from named environment variables.
- Distinctive: line 112
Use fixed clocks and deterministic ordering for offline selection.
- Very specific: line 248
Write tests in backend/tests/ following the existing naming convention test_<feature>.py
- Very specific: line 249
Run both offline targets before and after your change: make test and make test-blocking-io
- Very specific: line 252
If a module causes circular import issues in tests, add a sys.modules mock in tests/conftest.py (see existing example for …
- Very specific: line 269
Keep live tests opt-in via DEER_FLOW_RUN_LIVE_TESTS=1.
- Very specific: line 278
Run make dev from the repo root to start all services at http://localhost:2026.
- Very specific: line 315
When using make dev from root, the frontend automatically connects through nginx.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Project Overview
The backend runs a LangGraph-based super agent with sandbox execution, persistent memory, subagent delegation, and extensible tools in isolated per-thread environments.
Architecture:
- Gateway API (port 8001): REST API plus embedded LangGraph-compatible agent runtime
- Frontend (port 3000): Next.js web interface
- Nginx (port 2026): Unified reverse proxy entry point
- Provisioner (port 8002, optional in Docker dev): Started only when sandbox is configured for provisioner/Kubernetes mode
Runtime:
make dev, Docker dev, and production all run the agent runtime in Gateway viaRunManager+run_agent()+StreamBridge(packages/harness/deerflow/runtime/). Nginx exposes that runtime at/api/langgraph/*and rewrites it to Gateway's native/api/*routers.- Gateway streams
write_fileandstr_replaceargument deltas in bounded batches for multi-modemessages-tupleconsumers; single-mode message consumers retain the original per-chunk contract. Non-message frames flush pending batches, andvaluesremains an optional complete-state snapshot rather than a prerequisite for batching. - With
stream_subgraphs, subgraph frames keep their namespace in the SSE event name (values|<ns>, LangGraph Platform style) instead of impersonating root frames — a delegated subagent inherits the parent checkpoint namespace, so publishing itsvaluessnapshot as barevaluesreplaces the whole thread view in SDK clients (#4399). Root-only consumers (file-tool chunk batcher, subagent event persistence, LLM error-fallback detection) ignore namespaced frames. The web frontend does not request subgraph streaming; subtask progress rides root-namespacetask_*custom events. - Background subagent identity is deliberately split: the provider
tool_call_idremains the correlation key forToolMessage,task_*SSE events, persisted lifecycle events, frontend cards, and the publicExtensionData.scope_idcontract (stored asSubagentResult.external_task_id), whileSubagentExecutor.execute_async()generates a full server-sideexecution_idforSubagentResult.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 ownSubagentResultrather than resolving ownership again through the mutable registry. Terminal subagent token usage travels in the current run'sToolMessage.additional_kwargsand is attributed from message state, never through a process-global provider-ID cache. - Scheduled tasks dispatch through the normal Gateway run path.
launch_scheduled_thread_runreadsget_app_config()at dispatch and passesscheduler.recursion_limit(default 1000, matching the web UI; clamped bymax_recursion_limit), so YAML changes apply on the next run without restarting Gateway. - Run-history
statusfilters are occurrence states, not task states.ScheduledTaskRunStatusinpersistence/scheduled_tasks/model.pyis 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. - The background scheduler is single-instance by default.
scheduler.multi_instance=trueopts into lease-aware recovery across Gateway instances and requires shared Postgres,run_ownership.heartbeat_enabled=true, andrun_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 makesmax_concurrent_runsa shared global cap forlaunching/runningrows. - 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, andThreadStatereceives only a bounded current-thread projection. Full contract (leases, cancellation fencing, delivery idempotency, management-tool exposure): packages/harness/deerflow/mcp/AGENTS.md. - MCP task notification retries, dead-lettering, and the cancel endpoint's worker-stopped 503 are part of that same contract — see packages/harness/deerflow/mcp/AGENTS.md.
- Scheduled-task dispatch permits one active occurrence per task via
uq_scheduled_task_run_active(task_id WHERE status IN ('queued','launching','running')). Durablequeuedrows survive restarts; only lease-fencedlaunchingmay call Gateway launch;runningreferences the durable run. Stable admission idempotency keys reuse that run after recovery. Reused-threadConflictErrorreturnslaunchingtoqueued; other launch errors becomefailed. Atomic queue claims enforcemax_concurrent_runs, excluding waiting rows; the budget count and its UPDATE are separate statements, so writers must serialize before the count (Postgres advisory lock; SQLiteBEGIN 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 cancelqueuedwork but rejectlaunching/running; PATCH/resume reject all active states. Only queued conflicts offer pause cancellation. Manual triggers may queue/run while paused. Recovery locks task/run pairs in task-id/run-id order and restoresrun_id,started_atand live errors before releasing launch claims. Launch/failure/timeout updates use one parent-first transaction to prevent interleaved claims. Queue timeout fails the occurrence and advances scheduled work to prevent immediate requeue. Repository boundaries coerce serialized timestamps before SQLDateTimebinding. POST /api/scheduled-tasks/preview-cronrequires authenticatedthreads:read. Bounded cron previews call the shared scheduler calculator inasyncio.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.extensions_config.jsonis written at runtime by the Gateway (PUT/PATCH /api/mcp/config, the MCP enable switch, skill updates), so the production compose mounts it read-write whileconfig.yamlstays:ro; Helm copies its ConfigMap seed into a writable home-volume directory before Gateway starts. Every read-modify-write holds bothextensions_config_write_lockand the sidecar advisoryextensions_config_file_lock, because the process-local lock alone loses updates across workers. Docker mounts the compose file as its own mount point, and Linux refusesrename()over a mount point withEBUSYeven when the mount is writable — soatomic_write_extensions_configkeeps the temp-file-plus-rename path and falls back to an in-place overwrite only onEBUSY. That fallback is deliberately non-atomic (a crash mid-write truncates the file); it exists because the alternative is a write that can never succeed, and only its first occurrence per target is logged at warning level. Any othererrnostill propagates. Pinned bytests/test_compose_extensions_config_writable.py,tests/test_extensions_config_atomic_write.py, andtests/test_helm_extensions_config_writable.py.- MCP cache reset scope and discovery fencing: MCP guide.
Project Structure:
deer-flow/
├── Makefile # Root commands (check, install, dev, stop)
├── config.yaml # Main application configuration
├── extensions_config.json # MCP servers and skills configuration
├── backend/ # Backend application (this directory)
│ ├── Makefile # Backend-only commands (dev, gateway, lint)
│ ├── langgraph.json # LangGraph Studio graph configuration
│ ├── packages/
│ │ ├── extension-api/ # public, host-independent extension contracts (import: deerflow_extension_api.*)
│ │ └── harness/ # deerflow-harness package (import: deerflow.*)
│ │ ├── pyproject.toml
│ │ └── deerflow/
│ │ ├── agents/ # LangGraph agent system
│ │ │ ├── lead_agent/ # Main agent (factory + system prompt)
│ │ │ ├── middlewares/ # middleware components (see Middleware Chain section)
│ │ │ ├── memory/ # Memory extraction, queue, prompts
│ │ │ └── thread_state.py # ThreadState schema
│ │ ├── sandbox/ # Sandbox execution system
│ │ │ ├── local/ # Local filesystem provider
│ │ │ ├── sandbox.py # Abstract Sandbox interface
│ │ │ ├── tools.py # bash, ls, read/write/str_replace
│ │ │ └── middleware.py # Sandbox lifecycle management
│ │ ├── subagents/ # Subagent delegation system
│ │ │ ├── builtins/ # general-purpose, bash agents
│ │ │ ├── executor.py # Background execution engine
│ │ │ └── registry.py # Agent registry
│ │ ├── tools/builtins/ # Built-in tools (present_files, ask_clarification, view_image, review_skill_package)
│ │ ├── mcp/ # MCP integration (tools, cache, client)
│ │ ├── integrations/ # Managed first-party integration installers (e.g. Lark CLI skill pack)
│ │ ├── extensions/ # Python plugin loader, registry, placement, and isolation
│ │ ├── models/ # Model factory with thinking/vision support
│ │ ├── skills/ # Skills discovery, loading, parsing
│ │ ├── config/ # Configuration system (app, model, sandbox, tool, etc.)
│ │ ├── community/ # Community tools (search/fetch/scrape, image search, AIO sandbox)
│ │ ├── reflection/ # Dynamic module loading (resolve_variable, resolve_class)
│ │ ├── utils/ # Utilities (network, readability)
│ │ └── client.py # Embedded Python client (DeerFlowClient)
│ ├── app/ # Application layer (import: app.*)
│ │ ├── gateway/ # FastAPI Gateway API
│ │ │ ├── app.py # FastAPI application
│ │ │ └── routers/ # FastAPI route modules (models, mcp, memory, skills, uploads, threads, artifacts, agents, suggestions, channels)
│ │ └── channels/ # IM platform integrations
│ ├── scripts/benchmark/ # Standalone reproducible backend benchmarks
│ ├── tests/ # Test suite
│ └── docs/ # Documentation
├── frontend/ # Next.js frontend application
└── skills/ # Agent skills directory
├── public/ # Public skills (committed)
└── custom/ # Custom skills (gitignored)ATX outline closing markers use a linear suffix scan; do not use unanchored whitespace regex searches on unbounded uploaded headings. The long-heading regression exercises the production extractor under a generous process deadline.
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.
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.
- 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/:
PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction validate-contracts
PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction validate --dataset "$LONGMEMEVAL_ORACLE_PATH"
PYTHONPATH=. uv run python -m scripts.benchmark.deermem_eviction run-policy \
--dataset "$LONGMEMEVAL_ORACLE_PATH" \
--output-dir /tmp/deermem-eviction-policy-run
PYTHONPATH=. uv run pytest tests/test_bench_deermem_eviction_*.py -qThe offline test suite must not require network access, provider credentials, or the LongMemEval dataset. Small LongMemEval-shaped fixtures must be synthetic and generated by tests.
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/:
uv run python scripts/benchmark/concurrency/run_concurrency_bench.py \
--backend sqlite --workers 2,4,8,16 --ops-per-worker 50 --read-ratio 0.7
uv run pytest tests/test_bench_concurrency.py tests/test_bench_worker.py -qCommands
Root directory (for full application):
make check # Check system requirements
make install # Install all dependencies (frontend + backend)
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
make extension-disable NAME=... # Disable an extension without uninstalling it
make extension-remove NAME=... # Remove a managed extension
make detect-thread-boundaries # Inventory backend executor/thread/event-loop boundaries
make dev # Start all services (Gateway + Frontend + Nginx), with config.yaml preflight
make start # Start production services locally
make stop # Stop all servicesBackend directory (for backend development only):
make install # Install backend dependencies
make dev # Gateway API, reload (port 8001)
make gateway # Gateway API only (port 8001)
make test # offline tests (no live/blocking-io)
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.
More specific AGENTS.md files in backend code directories contain the subsystem sections split from this file. Follow the nearest file in the directory tree.
Architecture
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).
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:
# 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 CIPackage 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. 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.
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 conventiontest_<feature>.py - Run both offline targets before and after your change:
make testandmake 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.modulesmock intests/conftest.py(see existing example fordeerflow.subagents.executor)
# Run default offline tests
make test
# Run strict blocking-I/O tests
make test-blocking-io
# Explicit live integration tests (requires config.yaml and credentials;
# calls real APIs and may create local side effects)
make test-live
# Run a specific test file
PYTHONPATH=. uv run pytest tests/test_<feature>.py -vKeep 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 (tests/test_jina_client.py).
Jina/Browserless/InfoQuest resolve URLs without rebuilding HTML.
InfoQuest connect/read timeout is 30s, separate from crawl timeouts (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 | — |
Nginx routing:
/api/langgraph/*→ Gateway embedded runtime (8001), rewritten to/api/*/api/*(other) → Gateway API (8001)/(non-API) → Frontend (3000)
Running Backend Services Separately
From the backend directory:
# Gateway API
make gatewayDirect 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.
- Endpoint:
POST /api/threads/{thread_id}/uploads - Supports: PDF, PPT, Excel, Word documents (converted via
markitdown) - Rejects directories before copying to keep uploads all-or-nothing
- One conversion worker per request when called from an active event loop
- Files stored in thread-isolated directories under the resolving user's bucket (
users/{user_id}/threads/{thread_id}/user-data/uploads). For IM channels the owner is threaded explicitly via theuser_id=kwarg (see IM Channels → Owner-scoped file storage); HTTP/embedded callers resolve it fromget_effective_user_id() - Per-thread
upload-companions/: source mtime/ctime. - Duplicate filenames within one request get
_Nsuffixes to prevent overwrites. - Gateway HTTP uploads stage
.upload-*.partfiles, hidden from upload listings, agent context, and sandbox listings/searches. After size validation, publication is atomic; staged-name cleanup logs errors and leaves leftovers for startup sweep. - Gateway HTTP upload/list/delete handlers offload filesystem work through
deerflow.utils.file_io.run_file_io, a dedicated ContextVar-preserving file IO executor. Non-mounted sandbox uploads acquire sandboxes withSandboxProvider.acquire_async()and offloadread_bytes()plussandbox.update_file()together. - Mounted uploads skip sandbox acquire/sync. AIO remote/provisioner requires accurate
sandbox.thread_data_mounts: true; omission keeps backend auto-detection. UploadsMiddlewarecaps outline titles at 200 characters and previews at 2000 including markers. Titles useoriginal_user_content, not upload-prefixed content; attachment-only titles use a sanitized, bounded filename or count.
See 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.
Run Interaction Policy
Interaction-sensitive changes must follow policy.
Context Summarization
Automatic conversation summarization when approaching token limits:
- Configured in
config.yamlundersummarizationkey - Trigger types: tokens, messages, or fraction of max input
- Keeps recent messages while summarizing older ones
- Manual compaction uses
POST /api/threads/{id}/compact, reuses the sameDeerFlowSummarizationMiddleware, writes a new checkpoint with updatedmessagesandsummary_text, and bumps only those channel versions. The route uses the sharedreserve_checkpoint_write()boundary (also used by manual state updates). Its short-livedcheckpoint_writethread operation shares the durable active-thread uniqueness constraint with run admission, preventing either worker-local or cross-worker checkpoint-write races. - Each summarizer call emits a
middleware:summarizejournal event (MIDDLEWARE_SUMMARIZE_TAG;action="summary_result",changes.nooptrue when the output is byte-identical to the priorsummary_text) and bumpssummary_noop_count/summary_call_counton the middleware. This is observation only; the summarizer call is never skipped. Per-call LLM telemetry lives onRunJournal(see the runtime guide).
See docs/summarization.md for details.
Vision Support
For models with supports_vision: true:
ViewImageMiddlewareprocesses images in conversationview_image_tooladded to agent's toolset- Images are converted to base64 and appended to the model request as a hidden message carrying both a reserved ID prefix and a server-owned metadata marker; Gateway strips that marker from untrusted input, and the middleware requires both identifiers to recognize its own message. The middleware injects inside
wrap_model_call, so the payload never enters graph state: checkpoints retain only lightweightviewed_imagesmetadata, while client-chosen IDs survive. It 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
rufffor 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 - Configuration options
- ARCHITECTURE.md - Architecture details
- API.md - API reference
- SETUP.md - Setup guide
- FILE_UPLOAD.md - File upload feature
- PATH_EXAMPLES.md - Path types and usage
- summarization.md - Context summarization
- plan_mode_usage.md - Plan mode with TodoList
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

