Deep Agents and the middle Framework: A Fusion Study
The formation record of Agent Framework v2.0: Deep Agents runs execution while middle runs governance and business; two fusion stages fill in lease fencing, timeout budgets, and output guardrails, and then memory, RAG, and skills are packaged as capability tools that all pass the gatekeeper.

This document records how Agent Framework v2.0 came to be: from evaluating Deep Agents, to fusing it with middle (the governed Agent platform from lesson-02), to freezing it as a standalone project and completing the capability tools. It covers session 019fcb96 and the whole development process after it.
1. Starting point: why combine the two
Before the fusion, there were two things at hand, each with its own strengths:
- middle (the middle branch of lesson-02): a self-built, complete Agent platform. Hand-drawn LangGraph graphs, 8 hand-written middlewares, with long-term memory, RAG, subagents, skills, sandbox, and evaluation — about 17k lines of code. Strong in complete business capability, weak in production-reliability details (no lease fencing, no expiry takeover, no cost observability).
- Deep Agents: an open-source Agent harness built on LangGraph, with an out-of-the-box Agent loop, planning, context compression, subagents, memory, HITL, skills, and checkpointing.
The judgment at the time (also the guiding principle of the whole fusion):
Deep Agents can replace the “general Agent harness”, but it cannot replace the governance, evaluation, evidence, and business layers you have already built.
So it was not either/or, but a division of labor: Deep Agents runs execution; middle runs governance and business.
2. Session 019fcb96: evaluation, download, and verification
Evaluation conclusion
After comparing LangGraph, the OpenAI Agents SDK, PydanticAI, Pi, and Temporal, Deep Agents was chosen as the execution kernel:
- It turns the Agent loop, planning, subagents, memory, HITL, and checkpointing into out-of-the-box capabilities
- Version 0.7.3, actively maintained (still releasing continuously in early August at evaluation time), but 0.x fast iteration, so the version needs pinning
- Its official documentation is explicit: do not rely on model self-restraint; permission boundaries must live in the tool and sandbox layers
Download and environment struggles
The download process itself was the first practical lesson: direct GitHub TLS failures, the archive blocked by the network egress, the terminal proxy not inheriting the browser proxy. A shallow clone finally succeeded. Testing then hit uv cache permission problems. Conclusion: environment problems must be distinguished from code problems; verify one by one before moving on.
Hands-on testing of both projects
- Deep Agents:
2444 passed, lint/type checks all green - middle (at the time): 203 tests passing
- lesson-02: 202 unit tests passing; offline fast eval 6/7, real-task eval 6/6
The key judgment beyond the numbers: Deep Agents’ tests verify general runtime behavior; they cannot be equated directly with business quality. middle’s evaluations are its own business assets and must not be lost in the fusion.
3. Fusion stage one: the core loop
Fusion entry points:
middle_integration.py: the composition root, connecting Deep Agents to middle’s control planemiddle_task_store.py: the adaptation layer from middle’s TaskStore to the runtime contractmiddle_bootstrap.py: the locally runnable entry point
Capabilities completed and verified:
- Deep Agents calls middle’s authorization policies; VFS reads and writes go through middle’s sandbox
- High-risk writes trigger human approval; after approval, the same Deep Agents checkpoint resumes
- Tasks, runs, approvals, and artifacts are persisted separately; audit keeps only redacted summaries
- Result artifact: the final answer is written to disk; pages display it read-only; it does not enter audit events
- Failure retry: failed tasks stay immutable; a retry creates a linked new task
- A tool-call cap (20 per run) prevents directory-traversal loops from exhausting the model timeout
- Task history, execution-attempt views, run-rebuild fixes (ended_at correct)
- Cancellation chain (cancel while queued, cooperative termination while running, late results discarded), idempotent submission
Runtime v0.3, stage one
Laying the foundation for a Durable Worker:
- middle adds an atomic
claim_and_start_run(claim + create run + write lease in one transaction) - Task lease fields: lease_id / lease_owner / lease_expires_at
DurableTaskWorker: only recovers queued tasks that never started; approval-resumed tasks are not wrongly replayed- When multiple Workers compete for one task, only one succeeds; restarts do not re-execute
One thing was explicitly deferred at this stage: automatic takeover of expired leases. The reason was the missing fencing token — an old Worker might keep producing side effects after its lease expired, competing with a new Worker. That “gap” became the starting point of the next stage.
4. Fusion stage two: reliability hardening and governance depth
This is the first half of the current conversation; its theme is “fill in the production reliability deferred last stage”.
Lease fencing and expiry takeover
lease_fence.py:RunLeaseIdentity(lease identity) binds each execution;ControlPlaneLeaseFencere-reads the task’s live lease before side effects and throwsLeaseLostErroron mismatch- All five side-effect boundaries are fenced: before tool execution, when requesting approval, when recording an artifact, at complete/fail terminal states, and before the result is written to disk
- middle adds an atomic
takeover_expired_lease: it only takes over expired leases; the new lease replaces the old one, and all later operations by the old Worker are rejected - Taken-over attempts converge to a
lost_leaseterminal state instead of showing as “running forever”
Unified heartbeat
A boundary check found a real gap: the approval-resume path had no lease-renewal heartbeat, so a resumed run executing longer than the lease duration could be wrongly judged takeable-over. Fix: the heartbeat moved down into the run adapter (lease_heartbeat.py), and the run / resume / takeover paths all renew leases uniformly.
Wall-clock timeout budget
- A task can carry
timeout_seconds; each execution computes a deadline from “start time + budget” - Checked before tool execution (
tool.deadline_exceededblocks side effects) and again before the result is written to disk (late answers are discarded and failed asTaskTimeoutError, retryable) - Failure classification: timeout / tool_budget / network / lease_lost / canceled / runtime / claim_integrity
Run-level observability
Each execution records duration, input/output/total tokens, an optional cost estimate, and a failure classification, persisted with the terminal event and shown directly in the console.
Output guardrails (lesson-03 evaluation-driven)
A round with the lesson-03 fixed evaluation set (8 real samples): framework mechanisms 8/8 normal, but three Agent behavior problems surfaced:
- Key echoing: the model wrote an API Key verbatim into its answer
- Fabricated search claims: claiming “according to my search results” with no search tool
- Deep retrieval over budget: the model explored with 19 tool calls, exceeding the 120-second budget
Two output guardrails were implemented accordingly:
- Sensitive-string redaction: credential fragments from the task request are replaced with
[已脱敏]before the answer is written to disk, recording anoutput.guard_redactedevent (hit counts only) - Claim interception: claiming “searched / official sources” without a web search tool fails as
claim_integrityand is not written to disk
Retest: the search_failure sample was correctly intercepted; in the secret_block sample the model did not echo the key (redaction was not triggered; the mechanism is covered by tests).
5. Freezing v2.0 as a standalone project
The user was explicit: do not hang it on the middle branch; make it a completely independent project. So:
- A new, independent
agent-framework-v2.0directory + independent git repository (branch main) - Version tag:
agent-framework-v2.0; the version document records the feature list, verification evidence, and production gaps - Independent test paths: the middle dependency is injected via the
MIDDLE_RUNTIME_ROOTenvironment variable, and the full suite also runs without it - A recorded to-do: splitting the middle dependency (the runtime still references middle’s TaskStore/sandbox/authorization via
--middle-root, about 8 entry modules; in future, either pin middle locally to a fixed interface version, or vendor the implementation for zero external dependencies)
6. Capability packaging: memory, RAG, skills, subagents
The user’s route choice: package middle’s capabilities as Deep Agents tools, all passing the 2.0 gatekeeper — rather than writing the capabilities into 2.0, and rather than turning them into MCP services.
Tool packaging
capability_tools.py:memory_search,memory_save(writes to a candidate queue, requires approval),retrieve_text,list_skills,load_skillcapability_policy.py:CompositeAuthorizer— capability tools declare their own policy in 2.0 (memory_save needs human approval, the rest are read-only), while all other tools keep delegating to middle’sauthorize_tool_call, without changing middle’s registry or policy files- Memory writes do not land directly in the store: they enter a candidate queue first and become formal memory only after human confirmation
End-to-end verification (real model):
list_skillspassed the gatekeeper, and the answer correctly listed middle’s real skillsmemory_savetriggered approval → approved → the candidate was queued into the memory_candidates table
Subagent gatekeeper verification
Real runs verified two conclusions:
- Deep Agents’ native subagents’ internal tools bypass the 2.0 gatekeeper by default: even when the authorizer explicitly refuses, a subagent’s internal write tools still execute, with no authorization events. Bare use is unacceptable.
- Passing
MiddleToolAuthorizationMiddlewareexplicitly in theSubAgentspec’smiddlewarebrings subagents’ internal tools under the gatekeeper. This is 2.0’s controlled way of enabling subagents.
Conclusion: subagents must be “explicitly fitted with the gatekeeper” to be enabled; the entry point is agent_options["subagents"], with no framework code changed.
7. Architecture panorama
Deep Agents(执行内核)
├─ Agent loop / planning / context / subagents / skills / HITL
└─ checkpoint(SQLite)
│
Agent Framework v2.0(治理与控制面)
├─ Task / Run / Approval / Artifact 契约与审计
├─ 授权门卫 + 沙箱桥接 + 输出护栏
├─ 租约 fencing / 过期接管 / 统一心跳
├─ 超时预算 / 工具上限 / 幂等 / 可追溯重试
├─ run 级观测(耗时 / token / 成本 / 失败分类)
└─ 能力工具(记忆 / RAG / 技能 / 子代理入口)
│
middle(业务与治理底座,外部依赖)
├─ TaskStore / VFS 沙箱 / 授权策略
└─ 记忆治理 / RAG 管线 / 技能体系
Test scale: middle 205 tests; 2.0 86 tests (the full suite without the middle dependency).
8. Key design principles
A few principles verified again and again through the process:
- The model may only propose; the policy layer decides. Permissions are not written in the Prompt; deterministic policies and sandboxes decide whether something executes.
- Capabilities pass the gatekeeper. Any new capability (memory, RAG, skills, subagents) connects in tool form, naturally inheriting authorization, approval, and audit. Native capabilities that bypass the gatekeeper by default must not be used bare.
- The governance runtime ≠ the business platform. 2.0 manages execution and safety; middle manages business semantics. “Completeness” is judged against the goal: an Agent with controlled execution is complete; a full research business loop (evidence/risk/explicit orchestration) still needs work.
- Progressive adoption. Start with a single Agent + controlled tools; enable subagents only when evaluations prove the need.
- Environment problems and code problems are separate. Download failures, cache permissions, and timing jitter all need attribution first; do not treat historical conclusions as the current state.
9. Status and to-dos
Done:
- Deep Agents + middle core fusion, reliability hardening, observability, output guardrails
- 2.0 frozen standalone (repository / tag / documents)
- Memory, RAG, and skill tools packaged and passing the gatekeeper; the controlled way of enabling subagents verified
Production gaps (to fill as needed, without changing 2.0’s existing contracts):
- Authentication, tenant isolation, rate limiting, and HTTPS (currently limited to trusted networks)
- Multi-instance deployment: Postgres checkpointer, cross-process queue leases, process supervision
- Multi-provider failover and cost caps at the model layer
- A minimal business loop for evidence / claims / risk
- A continuous evaluation pipeline (fixed regression / iteration / held-out)
- Splitting the middle dependency (vendoring, or pinning interface versions)
10. References
- Standalone project:
agent-framework-v2.0(standalone local repository) - Version anchor: tag
agent-framework-v2.0, version documentdocs/agent-framework-v2.0.md - Fusion entry:
generic_agent_runtime/middle_integration.py - Capability packaging:
generic_agent_runtime/capability_tools.py,generic_agent_runtime/capability_policy.py - Subagent verification:
tests/test_subagent_guard.py - Evaluation: lesson-03
cases/eval_cases.jsonl, reports in lesson-03runs/current-runtime-round-*