BitterSecurity/Decepticon
LangGraph red-team orchestrator delegating to ~20 specialist sub-agents in a Kali sandbox, gated by machine RoE checks and nftables.
Overview
Decepticon is a full red-team agent platform, and the largest project in this category: about 170,000 lines of Python across three packages, a Go launcher, a TypeScript CLI and a web dashboard. One orchestrator agent, decepticon, holds no offensive tools of its own. It keeps an operations plan (OPPLAN) of objectives and hands each piece of work to a specialist sub-agent through a task() tool. The specialists include recon, exploit, post-exploitation, AD, cloud, reversing, phishing, OSINT, ICS, a finding verifier, a reporter and others. All of them run shell commands inside a long-lived Kali container through an HTTP daemon and tmux sessions.
Agents are built with LangChain’s create_agent and served by a LangGraph server. Every model call goes through a LiteLLM proxy, and each role gets a model tier. Behavior is layered through a slot-based middleware stack. That stack is where the safety design lives: a fail-closed RoE guardrail on shell and HTTP tools, an nftables egress allowlist compiled from the same RoE, envelopes around untrusted tool output, an optional human-approval gate and optional USD budget caps.
Among the projects reviewed here, Decepticon has the most deliberate safety engineering. It is also the most capable offensive tool: it ships C2, phishing and lateral-movement specialists. The controls are real, but several are opt-in or best-effort, and the section on caveats spells out which.
Architecture
flowchart LR
CLI["CLI / web / MCP client"] --> LG["LangGraph server"]
LG --> ORCH["decepticon orchestrator"]
ORCH --> OPP["OPPLANMiddleware (opplan.json)"]
ORCH --> TASK["task() via SubAgentMiddleware"]
TASK --> SUB["Specialist sub-agents"]
SUB --> MW["Middleware: RoE, untrusted output, HITL, budget"]
MW --> BASH["bash tool"]
BASH --> HS["HTTPSandbox client"]
HS --> DMN["Sandbox daemon + tmux (Kali)"]
DMN --> NFT["nftables egress allowlist"]
ORCH --> LLM["LLMFactory -> LiteLLM proxy"]
SUB --> LLM
SUB --> WS["Engagement workspace + Neo4j"]
| Component | Path | Role |
|---|---|---|
| Orchestrator | packages/decepticon/decepticon/agents/standard/decepticon.py |
Builds the main graph; discovers sub-agents; no domain tools |
| Specialists | packages/decepticon/decepticon/agents/standard/, agents/plugins/ |
Recon, exploit, verifier, reporter, AD, cloud, etc., registered as entry points |
| Agent assembly | agents/build.py, agents/middleware_slots.py |
Tool and middleware composition, plugin overrides, safety-override gate |
| Slot contracts | packages/decepticon-core/decepticon_core/contracts/slots.py |
Slot order, per-role slot sets, safety-critical slots |
| RoE guardrail | middleware/roe.py, decepticon_core/types/roe.py |
Parser-side scope, command and time-window checks with an audit log |
| Egress | middleware/egress.py, sandbox_kernel/egress.py |
Compiles RoE to nftables and DNS allowlists inside the sandbox |
| Sandbox | backends/http_sandbox.py, sandbox_server/app.py, sandbox_kernel/ |
HTTP daemon, tmux sessions, output limits |
| Verification | tools/verification.py, tools/research/poc.py |
PoC plus negative-control validator |
| Models | llm/factory.py, decepticon_core/types/llm.py |
LiteLLM-backed models, role tiers, fallbacks |
(Paths without a package prefix are under packages/decepticon/decepticon/.)
How a request flows
- Engagement and RoE. An engagement is created from targets, for example through MCP
start_engagementor headless withdecepticon-cli scan.build_engagement_roeturns the targets into an always-enforcedmachine_enforcementblock and refuses to create one with no in-scope target (roe.py). The block is written toplan/roe.jsonin the workspace. - Orchestrator build.
create_decepticon_agentloads every sub-agent spec whose parent isdecepticonand wraps each one for streaming. It registers only theops_*workload tools, and only when the opscontrol daemon is present. Its recursion limit is 400 (decepticon.py). The LangGraph server exposes it and the specialists as graphs (langgraph.json). - Plan. The orchestrator commits and updates an objective DAG through OPPLAN tools.
OPPLANMiddlewareinjects the live objective status into every model call and allows one OPPLAN tool call per step (opplan.py). - Delegate.
task()starts a specialist graph with a fresh context. For example, the recon agent getsbash,web_search,web_fetchand reference lookups, and a recursion limit of 1000 (recon.py). - Gate. Each tool call in a specialist passes through
RoEGuardrailMiddleware. First the call is checked against an abort marker. It is then evaluated against RoE, recorded toaudit/roe-decisions.jsonl, paced, concurrency-limited, and only then executed (roe.py). - Execute.
bashforwards toHTTPSandbox.execute_tmux, which POSTs to the daemon’s/execute_tmux. The command runs in a named tmux session in the Kali container (http_sandbox.py). Output up to 15K characters returns inline. Longer output is written to.scratch/, and a size watchdog kills runaway commands (bash.py). - Wrap output.
UntrustedOutputMiddlewarewraps the result in an<UNTRUSTED_TOOL_OUTPUT>envelope with a heuristic injection-risk tag before the model reads it (untrusted_output.py). - Verify and report. Candidate findings go to the verifier. It runs a PoC and a baseline control. The reporter then writes one finding file at a time with a deterministic CVSS 3.1 score.
Key components
Middleware slots and the safety-override gate
MiddlewareSlot defines one ordered stack. SLOTS_PER_ROLE decides which slots each role gets. The base set that the standard roles share includes ROE_GUARDRAIL, UNTRUSTED_OUTPUT, the prompt-injection shield and BUDGET. Bash-using roles also get HITL_APPROVAL (slots.py). Seven slots are marked safety-critical, among them engagement context, RoE, untrusted output and HITL. A plugin bundle can disable or replace them, or the ask_user_question tool, only when DECEPTICON_ALLOW_SAFETY_OVERRIDES=1 is set (slots.py, build.py).
RoE guardrail (parser layer)
The gated tools are bash, bash_output, bash_kill, http_request, proxy_send_request, browser_action, web_fetch, web_search and detect_tech_stack (roe.py). A missing or unreadable roe.json refuses every gated call with ROE_CONFIG_MISSING. For URL tools the host is checked. For shell commands the guardrail applies forbidden-command regexes and then checks each target it can extract (roe.py). evaluate_target denies cloud-metadata addresses and .gov/.mil/.edu/.int by default. It then applies out-of-scope rules, and, when an in-scope list exists, denies everything not on it. Time windows and blackout windows are checked too (roe.py, L431-L543). The module’s own docstring says target extraction from shell text is best-effort.
Egress allowlist (network layer)
On the first agent turn of a workspace, _maybe_provision_egress compiles the RoE into an EgressPolicy and sends it to the sandbox’s /provision_egress endpoint (roe.py, egress.py). Inside the container, the applier adds the management subnet and resolvers, renders an inet nftables table plus a DNS allowlist, and loads it with nft -f (sandbox_kernel/egress.py). This layer catches what the parser cannot see, such as targets hidden in variables. It is on by default, and DECEPTICON_EGRESS_DISABLE turns it off.
Human approval and budget
HITLApprovalMiddleware pauses calls that match MITRE technique tags (credential dumping, destructive impact) or tool patterns (C2 implant deployment, SIEM rule pushes). Each rule denies on timeout (hitl.py). The slot factory returns None unless DECEPTICON_HITL__ENABLED is truthy, so the gate is off by default (middleware_slots.py). BudgetEnforcementMiddleware reads tagged spend from LiteLLM’s /spend/tags and stops a run at the cap. It is also disabled until a positive cap is set (budget.py). StepBudgetMiddleware adds wrap-up and hard-stop messages at 80% and 100% of the step budget (step_budget.py).
Finding validation
The verifier specialist gets validate_workspace_finding alongside bash (verifier.py). The tool requires a PoC command, success regexes, a baseline command, baseline regexes and a CVSS vector (verification.py). validate_poc marks a finding validated only when four things hold: the PoC exits 0 and matches, the baseline runs and matches its own patterns, and the baseline does not match the success patterns (poc.py). The model writes both commands and every pattern, so this gate catches sloppy claims, not dishonest ones. Severity comes from a pure CVSS 3.1 implementation, not from the model (cvss.py).
State and models
The workspace filesystem is the shared store. It holds plan/opplan.json, recon/, findings/, audit JSONL files and a flock-protected events.jsonl (event_log.py). A Neo4j knowledge graph is attached only to the analyst, contract-auditor and AD roles, and that slot is skipped if Neo4j is unavailable. LLMFactory builds ChatOpenAI clients against the LiteLLM proxy (factory.py). Roles map to HIGH, MID or LOW tiers: the orchestrator, exploit and analyst are HIGH, recon is LOW. The eco, max and test profiles override the tiers, and the fallback chain follows whichever credentials are configured (llm.py).
Extending it
- Sub-agents. Ship a module with a
SUBAGENT_SPECand register it under thedecepticon.subagentsentry-point group. The orchestrator picks up every spec whoseparent_agentsincludes it (pyproject.toml). - Overrides. A
PluginBundleunderdecepticon.bundlescan replace tools, prompts or middleware slots per role. Safety-critical slots need the env gate. - Library use. Every agent factory accepts
tools=,middleware=andsystem_prompt=as full replacements. Composing your own stack this way bypasses the slot system, including its safety slots. - Skills and workflows. Knowledge lives in
SKILL.mdtrees loaded progressively. Workflow templates (red-team, pentest, bug-bounty, vulnerability-research) live underworkflows/catalog/.
Running it
- Install. Use the install script, then
decepticon onboard(provider and model profile), thendecepticon. This starts LiteLLM, PostgreSQL, Neo4j, LangGraph and the sandbox, and opens the terminal CLI. BloodHound CE, Sliver C2 and the web dashboard start on demand. - Sandbox container. It runs as root inside the container with
cap_drop: ALL, a minimal set of capabilities added back (includingNET_RAWandNET_ADMIN),no-new-privileges, a 4 GB memory limit and a PID limit, onsandbox-net, separate from the management network (docker-compose.yml). - Other entry points. Run
decepticon-cli scan --target ...headless, usedecepticon mcp servefrom Claude Code or Codex, or install thedecepticonpip package as a client SDK pointed at your own proxy and sandbox URLs.
Strengths and caveats
- Strength: layered, fail-closed scope. A missing RoE blocks gated tools. Scope is enforced both in the command parser and at the network edge, and every decision is logged to an audit file.
- Strength: designed against prompt injection. Tool output is wrapped as untrusted data, the orchestrator holds no offensive tools, and safety slots cannot be silently removed by a plugin.
- Strength: evidence discipline. Findings require a PoC plus a negative control, and CVSS is computed, not guessed.
- Caveat: approval and spend caps are opt-in. By default no human confirms high-impact actions such as credential dumping or C2 deployment, and no USD cap applies.
- Caveat: the firewall shares a container with the agent. nftables rules are loaded in the same container where the agent’s shell runs as root with
NET_ADMIN. A failed provisioning is logged and retried on a later turn; it does not stop the run. The firewall stops mistakes and indirection, not a model working against it. - Caveat: gaps in the gated-tool list.
validate_workspace_findingruns model-written commands in the sandbox, but it is not on the parser’s gated list, so only the egress layer constrains it. - Caveat: unauthenticated daemon by default. The sandbox daemon accepts any caller when
SANDBOX_TOKENis unset, which its own docstring calls the typical dev setup (app.py). - Caveat: weight. Running it means a multi-container stack, a LiteLLM proxy and frontier-model spend over long runs. Reading the code is a large undertaking too.
Sources: code at cd252a5, verified Q&A.
How it answers the Open-source AI pentest and offensive-security agents questions
Each answer was drafted by a code-reading agent at commit cd252a5. Its citations were checked mechanically. Compare with the other open-source ai pentest and offensive-security agents →
How is the agent loop and planning implemented?
answeredSingle orchestrator, multi-agent role delegation. The system uses a single orchestrator (the decepticon agent) that plans and delegates to ~20 specialist sub-agents rather than a multi-agent crew working jointly. The orchestrator is built by create_decepticon_agent() in agents/standard/decepticon.py (lines 80–216), which compiles a LangGraph agent with a middleware stack including EngagementContextMiddleware, SkillsMiddleware, SubAgentMiddleware, OPPLANMiddleware, and StepBudgetMiddleware. The orchestrator carries no offensive tools — tools=[] — all work is delegated via the task() tool (SubAgentMiddleware) to specialist sub-agents like recon, exploit, ad_operator, cloud_hunter, and finding_verifier.
Planning and decomposition. Planning happens ahead of execution via Soundwave (interview-based planner generating 7 engagement documents plus RoE) or Autohunt (additive bootstrap planner). The orchestrator then projects an OPPLAN (Operations Plan) — a DAG of tactical objectives persisted at /workspace/plan/opplan.json. Each objective has phases, status, blocked_by dependencies, and owner. The OPPLAN is managed through tools like commit_opplan, update_objective, list_objectives, and load_opplan registered via OPPLANMiddleware (middleware/opplan.py, lines 1–58). Workflows (workflows/catalog/) define multi-stage templates (scope→discover→prove→verify→report) with WorkflowStage models specifying required artifacts and their specialist assignments. The WorkflowMiddleware dispatches stages when preconditions (completed stages, required artifacts) are met.
Turn structure and stop conditions. Each sub-agent runs its own LangGraph ReAct loop with a configurable recursion_limit (default 400 for orchestrator, 1000 for recon/exploit). The StepBudgetMiddleware (middleware/step_budget.py, lines 24–65) injects wrap-up system messages at 80% of the budget and a hard-stop directive at 100%, giving the model a chance to consolidate before the runtime hard cap raises GraphRecursionError. Sub-agents can also be paused by HITLApprovalMiddleware for high-impact actions requiring operator sign-off, or halted by BudgetEnforcementMiddleware when USD spend caps are reached.
How are security tools integrated and executed?
answeredTool surface per agent role. Tools are @tool-decorated Python functions from langchain_core.tools. Each agent role gets a curated subset via build_tools() (agents/build.py, lines 494–561), which composes a baseline dict, applies plugin overrides, and checks safety-critical tool gates. The Decepticon orchestrator itself has tools=[] — all offensive work is delegated to specialists.
Tool categories. The tools/ directory organizes tools by domain: bash (execute/kill/output/status — the core execution surface), network (nmap_scan, dns_recon, smb_recon, ssh_recon, ftp_recon, etc.), web (HTTP session with history, JWT forge/parse, GraphQL introspection, OAuth flow analysis), cloud (AWS, K8s, Terraform), browser (Playwright-based), c2, reporting (deterministic CVSS 3.1 score, HackerOne/Bugcrowd/SARIF templates, executive summary), evidence (asciicast recordings), verification (PoC runner with positive+negative controls), opplan (objective management), and references (CVE lookup, payload search, killchain lookup).
Execution backends. Bash tools delegate to HTTPSandbox.execute_tmux() (tools/bash/bash.py, lines 1–43), which runs commands inside a Docker sandbox container via tmux sessions managed by decepticon.sandbox_kernel.tmux. Web search/fetch tools (tools/web/search.py, lines 1–37) run a sandbox-side Python engine (python3 -m decepticon.sandbox_web) over the same HTTPSandbox.execute() surface, so all egress routes through the sandbox nftables allowlist.
Output tiers. The bash tool implements a three-tier output management system (tools/bash/bash.py, lines 69–94): inline return (≤15K chars), offload to <workspace>/.scratch/ file (15K–100K), or size watchdog kill (>5M). ANSI escape sequences are stripped, repetitive lines are compressed (nmap/nuclei patterns), and surrogate characters are sanitized. Errors return structured ToolErrorResult dicts with cause and recovery fields parsed by the TUI (tools/errors.py, lines 23–47).
How are scope, authorization and dangerous actions controlled?
answeredMulti-layer architectural enforcement. Scope and authorization are enforced through five independent layers that must all be satisfied for a potentially harmful action to proceed.
1. RoE document. The RoE model (decepticon_core/types/engagement.py, lines 275–304) defines engagement_name, client, dates, in_scope/out_of_scope entries (hostnames, CIDRs, domain globs), prohibited_actions, permitted_actions, and an authorization_reference. The MachineEnforcement model (decepticon_core/types/roe.py, lines 66–102) adds forbidden_destinations, forbidden_command_patterns, max_concurrent_connections, min_inter_request_delay_ms, and authorized/blackout time windows.
2. Parser-side guardrail. RoEGuardrailMiddleware (middleware/roe.py, lines 1–63) intercepts every call to gated tools (bash, http_request, browser_action, web_fetch, web_search, etc.) and extracts the target via extract_targets(). It uses evaluate_command(), evaluate_target(), and evaluate_time_window() from decepticon_core.types.roe to compare against the engagement's machine enforcement rules. Decisions are written to an audit sink (<workspace>/audit/roe-decisions.jsonl).
3. Network-layer backstop. EgressPolicy (middleware/egress.py, lines 1–80) compiles the same MachineEnforcement rules into nftables connect-allowlists and DNS allowlists that the sandbox kernel applies. Layer 2 cannot be bypassed by command indirection — packets to out-of-scope IPs are dropped at the network edge.
4. Human-in-the-loop. HITLApprovalMiddleware (middleware/hitl.py, lines 1–58) intercepts tool calls matching configurable high-impact policies (e.g. C2 deployment, credential dumping, lateral movement into sensitive scope) and pauses the run until an operator approves, denies, or redirects the action. Default is deny-on-timeout.
5. Budget and critical-tool protections. BudgetEnforcementMiddleware (middleware/budget.py) enforces USD spend caps via LiteLLM /spend/tags. Tools ask_user_question and complete_engagement_planning are SAFETY_CRITICAL_TOOLS (agents/build.py, lines 60–64) — disabling or replacing them requires the DECEPTICON_ALLOW_SAFETY_OVERRIDES=1 env gate. SafetyRegistry (decepticon_core/registry/safety.py) manages the merged set of safety-critical slots and tools.
How are findings validated and reported?
answeredPipeline: Detector → Verifier → Reporter. Findings flow through a three-stage pipeline. The Detector agent identifies potential vulnerabilities and writes them as structured observations. The Verifier agent (agents/plugins/verifier.py, lines 1–77) independently adjudicates each candidate: it crafts a minimal proof-of-concept, runs it inside the HTTPSandbox with both the exploit command and a negative control (baseline), and uses the validate_finding tool to promote or reject. This is a Zero-False-Positive (ZFP) workflow — the Verifier is the quality gate.
Workspace-first verification. The FindingVerifier agent (agents/standard/finding_verifier.py, lines 1–33) reuses the Verifier's sandbox tools but operates workspace-first (no Neo4j dependency). Its core tool is validate_workspace_finding() (tools/verification.py, lines 17–78), which takes a PoC command, success patterns (comma-separated regexes), a negative command, negative patterns, and a CVSS vector. Validation succeeds only when the positive command output matches a success pattern, the baseline matches a negative pattern, AND the baseline does not match any success pattern — preventing trivially-valid false positives. The result is persisted as JSON in the finding's evidence directory.
Dedup and quality. Deduplication is handled through the workspace filesystem — each finding gets a canonical path (findings/FIND-NNN.md or findings/{severity}_{number}_{title}.md). The finding quality tool (tools/reporting/finding_quality.py, lines 33–60) checks machine-verifiable invariants: YAML frontmatter structure, matching ID/severity, verification status field, and CVSS vector consistency.
Reporting. The FindingReporter sub-agent (agents/standard/finding_reporter.py, lines 17–93) completes one adjudicated finding at a time, using the deterministic cvss_score_tool (tools/reporting/cvss.py, lines 1–60) implementing the FIRST.org CVSS 3.1 formula — pure arithmetic, no LLM guesswork. Multiple export formats are supported via tools/reporting/__init__.py (lines 1–51): HackerOne markdown templates, Bugcrowd CSV, SARIF v2.1.0 JSON, engagement executive summaries, ZIP bundles, and asciicast recordings.
validate_workspace_finding (tools/verification.py L17-L75), not a graph-backed validate_finding; graph-backed verification is deferred, and the detector agent belongs to the separate vulnresearch plugins bundle. The model supplies both the PoC/baseline commands and the match patterns.How is engagement state and knowledge kept across a long run?
answeredMultiple coordinated persistence mechanisms. Engagement state is kept across turns through four complementary stores, each with a different purpose and lifetime.
1. OPPLAN (the tactical plan). The Operations Plan is a DAG of objectives persisted at /workspace/plan/opplan.json in the engagement filesystem. OPPLANMiddleware (middleware/opplan.py, lines 1–58) injects objective status into every LLM call (battle tracker), supports versioned DAG commits to prevent parallel mutation, and exposes CRUD tools (commit_opplan, update_objective, list_objectives). Each objective tracks phase, status (pending/in-progress/blocked/completed/cancelled), OPSEC level, notes, blocked_by dependencies, and C2 tier.
2. Event log. Each engagement has an append-only events.jsonl file (runtime/event_log.py, lines 1–80) under <workspace>/events.jsonl. It uses platform-appropriate exclusive file locking (POSIX flock / Windows msvcrt) so concurrent sub-agents do not interleave lines. The EventType enum provides typed event categories. read_events() yields events in order, skipping malformed lines for crash resilience.
3. Knowledge graph (optional Neo4j). KGMiddleware (middleware/kg.py, lines 1–77) attaches Neo4j-backed attack graph state to analyst/operator agents. Tools kg_record(observations) and kg_ingest(scanner_kind, path) let agents write hosts, services, credentials, and findings as typed nodes and edges with provenance. A cached summary block is injected into every system prompt and rebuilt when the graph revision advances. The KG is optional — it degrades gracefully with a single warning when Neo4j env vars are unset (middleware/kg_internal/store.py).
4. Workspace filesystem. The engagement workspace directory (/workspace/<slug>/) is the authoritative shared store, accessible to all sub-agents over the HTTPSandbox HTTP transport (via CompositeBackend). Agents write findings (findings/), recon data (recon/), and evidence (evidence/) as structured markdown and JSON files.
Context compaction. SummarizationMiddleware (slot SUMMARIZATION in middleware_slots.py, lines 445–446) auto-compacts long sessions via deepagents' summarization engine. The _SafeSummarizationProxy (lines 267–443) wraps it with a fallback: summarization failures log a warning and skip the turn rather than aborting the run. Compaction events are emitted to the event log for operator visibility. The RecordingMiddleware/ReplayMiddleware (runtime/recording.py) support full session recording for post-engagement replay.
Which models are supported and how are cost and context managed?
answeredMulti-provider via LiteLLM proxy. All LLM calls route through a LiteLLM Docker proxy for provider abstraction (llm/factory.py, lines 1–20). The LLMFactory binds role-specific ChatOpenAI instances pointing to the proxy. Supported AuthMethods include: ANTHROPIC_OAUTH, ANTHROPIC_API, OPENAI_OAUTH, OPENAI_API, COPILOT_OAUTH, GOOGLE_OAUTH, GOOGLE_API, DEEPSEEK_API, XAI_API, MISTRAL_API, OPENROUTER_API, NVIDIA_API, GROQ_API, TOGETHER_API, FIREWORKS_API, COHERE_API, MOONSHOT_API, KIMI_API, ZAI_API, MINIMAX_API, plus community gateways (Vercel, HuggingFace, Venice, ZenMux, Cloudflare, Qianfan, cheaper_inference) and OLLAMA/LM Studio for local models (llm/model_contracts.py, lines 43–51).
Per-role tier-based model selection. Each agent role is assigned a Tier (HIGH/MID/LOW) in AGENT_TIERS (decepticon_core/types/llm.py, lines 541–574). Example assignments: decepticon, exploit, analyst = HIGH; recon, soundwave = LOW; verifier, postexploit = MID. Three profiles control tier resolution: eco (per-role tiers), max (all HIGH), test (all LOW). Each AuthMethod defines a model per tier — e.g., HIGH for Anthropic = claude-opus-4-8, MID = claude-sonnet-4-6, LOW = claude-haiku-4-5. Per-role temperatures (AGENT_TEMPERATURES, lines 576–604) range from 0.1 (ICS operator) to 0.4 (decepticon, phisher).
Cost and budget controls. BudgetEnforcementMiddleware (middleware/budget.py, lines 1–56) enforces per-engagement and per-agent USD spend caps via the LiteLLM proxy's /spend/tags API. It tags every completion with engagement:<slug> and agent:<slug>:<agent> metadata. At the configured soft-warn threshold (default 70% of cap) it emits a stream event; at 100% it raises BudgetExceeded and terminates the run. Custom output token caps are configured per model route (64K for Claude Sonnet/Haiku 4.5, 128K for newer Claude models and GPT models) in _model_max_output_tokens() (llm/factory.py, lines 133–155).
Context-window management. AnthropicPromptCachingMiddleware (middleware_slots.py, line 450) caches system prompts for Anthropic models. SummarizationMiddleware (line 445) auto-compacts when the context budget is exceeded. The _SafeSummarizationProxy (lines 267–443) binds summarization to the per-request model and handles provider failures gracefully. The ModelFallbackMiddleware (lines 251–264) chains primary→fallback models on provider failure.