Dosu LogoDosu Logo
Ask
Join our Discord
Organization avatar
difyPublic
Dify
Documentsdify
Agent Runtime Layer Provider Registration
Agent Runtime Layer Provider Registration
Type
Topic
Status
Published
Created
Jul 31, 2026
Updated
Aug 19, 2026
Updated by
Dosu Bot

Agent Runtime Layer Provider Registration#

The dify-agent FastAPI server assembles a fixed set of LayerProvider objects at startup via create_default_layer_providers() in compositor_factory.py. These providers are passed to the RunScheduler during the FastAPI lifespan and service all subsequent run requests in-process. The key architectural rule is that DifyRuntimeLayer is conditionally registered — it is only appended when a valid RuntimeBackendProfile is available . If no backend is configured, the provider is simply absent from the set, with no startup error.


Provider Registration Flow#

create_app() wires providers in two steps:

  1. ServerSettings.build_runtime_backend_profile() resolves DIFY_AGENT_RUNTIME_BACKEND and the matching endpoint env var into a RuntimeBackendProfile, or returns None when the local backend is selected but DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT is not set .

  2. create_default_layer_providers() receives the profile (or None) and builds the provider tuple. All providers except DifyRuntimeLayer are always registered. DifyRuntimeLayer is conditionally appended:

    if runtime_backend_profile is not None:
        providers.extend([LayerProvider.from_factory(layer_type=DifyRuntimeLayer, ...)])
    

The always-present providers are :

  • PromptLayer, PydanticAIHistoryLayer, DifyOutputLayer, DifyAskHumanLayer, DifyConfigLayer — registered with LayerProvider.from_layer_type()
  • DifyExecutionContextLayer, DifyShellLayer, DifyPluginToolsLayer, DifyCoreToolsLayer, DifyKnowledgeBaseLayer — registered with LayerProvider.from_factory() (server credentials injected via closure)

DifyRuntimeLayer: Blocked Direct Construction#

DifyRuntimeLayer.from_config() raises TypeError at call time:

DifyRuntimeLayer requires a server-injected ExecutionBindingBackend

The only valid construction path is from_config_with_backend(), which accepts an ExecutionBindingBackend from the RuntimeBackendProfile. This backend is never included in per-run HTTP payloads — it is injected exclusively by the provider factory closure .

The RuntimeLease itself is lazy: it is only materialized inside resource_context(), an async context manager that opens and closes the lease around a run. Accessing DifyRuntimeLayer.lease outside this window raises RuntimeError.


DifyShellLayer's Dependency on DifyRuntimeLayer#

DifyShellLayer declares DifyRuntimeLayer as a required typed dependency via DifyShellLayerDeps:

class DifyShellLayerDeps(LayerDeps):
    execution_context: PlainLayer[...] | None
    runtime: DifyRuntimeLayer # required, not optional

DifyShellLayer never owns its sandbox connection. Every shell tool call resolves the active lease through _require_resource() , which reads self.deps.runtime.lease. The HOME path and workspace cwd are also read from the lease's layout .

Like DifyRuntimeLayer, DifyShellLayer.from_config() raises TypeError . The factory always calls from_config_with_settings(), which injects server-owned settings (shell_redact_patterns, agent_stub_api_base_url, agent_stub_token_factory) that are not present in the per-run config payload .


Runtime Failure Pattern: Missing DifyRuntimeLayer Provider#

Because the DifyRuntimeLayer provider is absent when no backend is configured, any run that includes a dify.runtime or dify.shell layer config will fail at run time, not at startup. The Compositor resolves layer type IDs against the registered provider set when building a run. If no provider matches dify.runtime, the Compositor raises an error during the build phase for that specific run request. Deployments running with runtime_backend=local but without DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT will silently succeed at startup but reject any agent run that requires shell or runtime resources.

The same deferred-failure pattern appears on the upstream API side: if AGENT_BACKEND_BASE_URL is not set, the agent backend client factory raises ValueError: base_url is required when creating a real Agent backend client at the first run request, not at startup .


Key Files#

FilePurpose
runtime/compositor_factory.pycreate_default_layer_providers() — provider set assembly and conditional DifyRuntimeLayer registration
layers/runtime/layer.pyDifyRuntimeLayer — lease lifecycle, forced factory construction
layers/shell/layer.pyDifyShellLayer — DifyRuntimeLayer dependency, _require_resource()
server/settings.pyServerSettings.build_runtime_backend_profile() — backend profile construction or None
Documents
Account Activity Tracking
Agent API Routes
Agent App Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent App Event Architecture
Agent App Input Variables
Agent Cost and Usage Tracking
Agent File Handling
Agent File Upload Configuration
Agent Icon Data Model
Agent Log Event Pipeline
Agent Message History
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Model Settings
Agent Node Data Models
Agent Response Schema
Agent Runtime
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Runtime Backend Initialization
Agent Runtime Layer Provider Registration
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Sandbox SSRF Allowlisting
Agent Shell Layer
Agent Strategy Plugin Architecture
Agent V2 Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent V2 Configure Interface
Agent V2 Feature Flags
Agent V2 File and Vision Handling
Agent V2 Variable System
API Documentation Pipeline
App Mode Configuration
App Publishing and Embedding
Audio to Text API
Auth Route Architecture
Automatic Rule Generation
Avatar Management
Branding Customization
Browser Tab and State Management
Builtin Tool Provider Credentials
Celery Task Resilience
Chat Avatar Rendering
Chatbot Conversation State Recovery
Chatbot Widget Embedding
Code Node Execution
Code Node Output Validation
Collaborative Workflow Editing
Conversation Auto-Naming
Conversation Deep-Linking
Credential Encryption and Secret Management
CSV Data Ingestion
Custom Tool Authentication
Custom Tool HTTP Timeout Configuration
Custom Tool OpenAPI Integration
Data Export
Database Migration System
Database Session Management
Database Transaction Isolation
Dataset Batch Import
Dataset Deletion
Dataset Permission Model
Dataset Segmentation Configuration
Dependency Injection and Testability
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Agent Monorepo Structure
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Cloud Billing
Dify OpenAPI
difyctl CLI
Docker Container Security
Docker Deployment and Upgrades
Docker Frontend Configuration
Docker Image Publishing
Docker Networking
Docker Storage and Permissions
Document Indexing Operations
Edition-Based Feature Gating
Elasticsearch Integration
Embedding Cache Integrity
External Knowledge Integration
File Access Control
File Array Handling
File Download Architecture
File Download Security
File Storage Synchronization
File Upload and Download Integrity
File Upload Configuration
File Upload Processing
File URL Resolution
Flask Application Architecture
Flask Blueprint and Route Registration
Graph Streaming Infrastructure
Home Directory Management
HTTP Request Node
HTTP Request Node Key-Value Editor
HTTP Request Node Size Constraints
httpx and Gevent Compatibility
Human Input Node
Hybrid Search
Icon URL Resolution
Iframe Embedding Security
Internationalization and Locale Management
Jina Reranker Integration
JSON-in-Markdown Parsing
JWT Authentication
Knowledge Base API
Knowledge Base Document Processing
Knowledge Base Metadata Filtering
Knowledge Base Summarization Pipeline
Langfuse Integration
Lexical Editor Integration
LLM Provider Message Validation
LLM Structured Output
Local Development Configuration
Local Embedding Model Deployment
Log Filtering
Markdown Extractor Heading Parsing
Markdown Rendering
MCP Client Transport and Connectivity
MCP Protocol Integration for Dify Workflows
MCP OAuth Integration
MCP Protocol Integration
Dify Agent Server 模块分析 (Commit 55f95dbc)
MCP Protocol Integration for Dify Workflows
MCP Provider Architecture
MCP Tool Integration
MCP Protocol Integration for Dify Workflows
MCP Tool Parameter Binding
Messaging Platform Integration
Milvus Integration
Model Provider Error Handling
Monaco Editor Integration
Multi-Tenant Context Propagation
Multimodal Knowledge Base Support
Next.js Routing and Redirects
Next.js SSR Authentication
Nginx Reverse Proxy Configuration
Notion Extractor Table Parsing
NumPy CPU Compatibility
OAuth Login Flow
Observability and Tracing
OpenAI-Compatible Server Integration
OpenAPI Spec Accuracy
OpenDAL Storage Backend
Ops Trace Data Models
Oracle Database Connectivity
Parallel Workflow Execution
Parent-Child Retrieval Architecture
Plugin API Key Configuration
Plugin Architecture
Plugin Credential Management
Plugin Daemon Architecture
Plugin Daemon Communication
Plugin Daemon Model Parameter Handling
Plugin Daemon Port Configuration
Plugin Database Integrity
Plugin Error Handling
Plugin File Handling
Plugin Lifecycle Management
Plugin Marketplace Connectivity
Plugin Model Caching
Plugin Permissions
Plugin Storage Configuration
Plugin System Timeouts
Plugin Taxonomy and Validation
Plugin Trigger OAuth Refresh
Private Address Detection
Provider Model & Credential Management
Pyrefly Type Checker
Rate Limiting and Concurrency Control
RBAC Initialization
Reasoning Model Integration
Reasoning Tag Filtering
Redis Connection Management
Redis Streaming Resilience
Release Breaking Changes
Remote File Handling and Validation
Retrieval Filtering and Scoring
RTL Locale Support
Sandbox Code Execution
Sandbox Network Isolation
Sandbox Seccomp Security
Segment Update and Attachment Lifecycle
Server Deployment Configuration
Service API Error Handling
Service API Pagination
Shell Provider Lifecycle
Snippet Variable Handling
SQLite Test Infrastructure
SSE Stream Lifecycle
SSE Stream Terminal Event Delivery
SSR Data Fetching
SSRF Proxy
Suggested Questions After Answer
Summary Index
Tenant-Isolated Document Indexing Queue
Test Doubles and In-Memory Repositories
Dify Agent Server 模块分析 (Commit 55f95dbc)
TiDB Vector Full-Text Search
Time Tools
Timestamp Management
Tool File URL Signing
Tool Node Input Validation
Tool Provider Authorization
Trace Task Pipeline
User and Tenant Context Propagation
User Roles and Permissions
Variable Pool Falsy Value Handling
Variable Resolution and Template Substitution
Vector Database Plugin Architecture
Vector Store Integration
Weaviate Vector Store
Web Container Docker Configuration
Webhook Trigger System
WebSocket Service Architecture
Word Document Extraction
Workflow Agent Node Configuration
Workflow Agent Retry Configuration
Workflow and Agent Composition
Workflow Conditional Branching
Workflow Container Nodes
Workflow Conversation State Management
Workflow Draft Synchronization
Workflow Execution Dispatch
Workflow Execution Persistence
Workflow Fail Branch Architecture
Workflow File Handling
Workflow Iteration Node Execution
Workflow LLM Node Configuration
Workflow Memory Management
Dify Agent Server 模块分析 (Commit 55f95dbc)
Workflow Node Canvas Summary Rendering
Workflow Node Versioning
Workflow Pause-Resume State Management
Workflow Resume Architecture
Workflow Run State Management
Workflow Schedule Triggers
Workflow Test Run Execution
Workflow Timeout and Execution Limits
Workflow Tool Visibility and Access Control
Workflow Variable Size Management