Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat: ee agent sandbox support (#38528)
Yunlu Wen888bea991170
diff --git a/api/core/app/apps/agent_app/app_runner.py b/api/core/app/apps/agent_app/app_runner.pyindex 54e34ced9cf..08416d6c9ae 100644--- a/api/core/app/apps/agent_app/app_runner.py+++ b/api/core/app/apps/agent_app/app_runner.py@@ -690,6 +690,9 @@ class AgentAppRunner:if not isinstance(terminal, AgentBackendRunSucceededInternalEvent):if isinstance(terminal, AgentBackendRunFailedInternalEvent):+ reason = terminal.reason+ if reason == "sandbox_expired":+ raise AgentBackendError("The agent session sandbox has expired. Please start a new conversation.")raise _agent_backend_failure_to_exception(terminal)raise AgentBackendError("Agent backend run did not complete successfully.")diff --git a/api/core/app/apps/base_app_generate_response_converter.py b/api/core/app/apps/base_app_generate_response_converter.pyindex 942dfd56d0e..d30969d3714 100644--- a/api/core/app/apps/base_app_generate_response_converter.py+++ b/api/core/app/apps/base_app_generate_response_converter.py@@ -5,6 +5,7 @@ from typing import Any, Union, castfrom pydantic import JsonValue+from clients.agent_backend.errors import AgentBackendErrorfrom core.app.entities.app_invoke_entities import InvokeFromfrom core.app.entities.task_entities import AppBlockingResponse, AppStreamResponsefrom core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError@@ -127,6 +128,7 @@ class AppGenerateResponseConverter[TBlockingResponse: AppBlockingResponse](ABC):},ModelCurrentlyNotSupportError: {"code": "model_currently_not_support", "status": 400},InvokeError: {"code": "completion_request_error", "status": 400},+ AgentBackendError: {"code": "completion_request_error", "status": 400},InvokeRateLimitError: {"code": "rate_limit_error", "status": 429},}diff --git a/api/core/app/task_pipeline/based_generate_task_pipeline.py b/api/core/app/task_pipeline/based_generate_task_pipeline.pyindex b1419b3adfa..925e13f274c 100644--- a/api/core/app/task_pipeline/based_generate_task_pipeline.py+++ b/api/core/app/task_pipeline/based_generate_task_pipeline.py@@ -4,6 +4,7 @@ import timefrom sqlalchemy import selectfrom sqlalchemy.orm import Session+from clients.agent_backend.errors import AgentBackendErrorfrom core.app.apps.base_app_queue_manager import AppQueueManagerfrom core.app.entities.app_invoke_entities import (AppGenerateEntity,@@ -54,7 +55,7 @@ class BasedGenerateTaskPipeline[AppGenerateEntityT: AppGenerateEntity]:match e:case InvokeAuthorizationError():err = InvokeAuthorizationError("Incorrect API key provided")- case InvokeError() | ValueError():+ case InvokeError() | ValueError() | AgentBackendError():err = ecase _:description = getattr(e, "description", None)diff --git a/dify-agent/.example.env b/dify-agent/.example.envindex a800e531005..630595616f2 100644--- a/dify-agent/.example.env+++ b/dify-agent/.example.env@@ -27,10 +27,18 @@ DIFY_AGENT_INNER_API_URL=http://localhost:5001DIFY_AGENT_INNER_API_KEY=# Shell layer-# Base URL for the shellctl server used by the dify.shell layer. Leave empty to disable shell layer use.+# Shell backend used by the dify.shell layer: "shellctl" (default) or "enterprise".+DIFY_AGENT_SHELL_PROVIDER=shellctl+# shellctl provider: base URL for the shellctl server. Leave empty to disable shell layer use.DIFY_AGENT_SHELLCTL_ENTRYPOINT=# Optional bearer token sent to the shellctl server.DIFY_AGENT_SHELLCTL_AUTH_TOKEN=+# enterprise provider: sandbox gateway endpoint. Leave empty to disable shell layer use.+DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_ENDPOINT=+# Optional X-Inner-Api-Key sent to the enterprise sandbox gateway.+DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_AUTH_TOKEN=+DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_TIMEOUT=30+DIFY_AGENT_ENTERPRISE_SANDBOX_PROXY_TIMEOUT=60# Agent Stub# Public Agent Stub URL reachable from shellctl-managed remote machines.diff --git a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.mdindex 0b77cf64027..fa7f0fc22ae 100644--- a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md+++ b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md@@ -29,13 +29,16 @@ When a run includes `dify.shell`, the Dify Agent server must construct its layerproviders with a non-empty shellctl entrypoint:```python+from dify_agent.adapters.shell.shellctl import ShellctlProviderfrom dify_agent.runtime.compositor_factory import create_default_layer_providerslayer_providers = create_default_layer_providers(plugin_daemon_url="http://localhost:5002",plugin_daemon_api_key="replace-with-plugin-daemon-key",- shellctl_entrypoint="http://127.0.0.1:5004",- shellctl_auth_token="replace-with-shellctl-token", # optional; defaults to no token+ shell_provider=ShellctlProvider(+ entrypoint="http://127.0.0.1:5004",+ token="replace-with-shellctl-token", # optional; defaults to empty string+ ),)```diff --git a/dify-agent/src/dify_agent/adapters/shell/__init__.py b/dify-agent/src/dify_agent/adapters/shell/__init__.pyindex 533dbe21750..faeb0cfb808 100644--- a/dify-agent/src/dify_agent/adapters/shell/__init__.py+++ b/dify-agent/src/dify_agent/adapters/shell/__init__.py@@ -18,10 +18,6 @@ from dify_agent.adapters.shell.protocols import (def __getattr__(name: str) -> object:- if name == "DEFAULT_SHELL_PROVIDER":- from dify_agent.adapters.shell.config import DEFAULT_SHELL_PROVIDER-- return DEFAULT_SHELL_PROVIDERif name == "ShellAdapterSettings":from dify_agent.adapters.shell.config import ShellAdapterSettings@@ -39,7 +35,6 @@ def __getattr__(name: str) -> object:__all__ = ["CompleteShellCommandResult",- "DEFAULT_SHELL_PROVIDER","ShellAdapterSettings","ShellCommandProtocol","ShellCommandResult",diff --git a/dify-agent/src/dify_agent/adapters/shell/config.py b/dify-agent/src/dify_agent/adapters/shell/config.pyindex 53325270861..3d6140a7fbc 100644--- a/dify-agent/src/dify_agent/adapters/shell/config.py+++ b/dify-agent/src/dify_agent/adapters/shell/config.py@@ -1,5 +1,7 @@-from typing import ClassVar+from typing import ClassVar, Literal, Self+from urllib.parse import urlparse+from pydantic import Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictDEFAULT_SHELL_PROVIDER = "shellctl"@@ -14,10 +16,15 @@ class ShellAdapterSettings(BaseSettings):``DIFY_AGENT_SHELLCTL_AUTH_TOKEN`` explicitly."""- shell_provider: str = DEFAULT_SHELL_PROVIDER+ shell_provider: Literal["shellctl", "enterprise"] = "shellctl"shellctl_entrypoint: str | None = Noneshellctl_auth_token: str | None = None+ enterprise_sandbox_gateway_endpoint: str | None = None+ enterprise_sandbox_gateway_auth_token: str | None = None+ enterprise_sandbox_gateway_timeout: float = Field(default=30.0, gt=0)+ enterprise_sandbox_proxy_timeout: float = Field(default=60.0, gt=0)+model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(env_prefix="DIFY_AGENT_",env_file=(".env", "dify-agent/.env"),@@ -25,5 +32,30 @@ class ShellAdapterSettings(BaseSettings):populate_by_name=True,)--__all__ = ["DEFAULT_SHELL_PROVIDER", "ShellAdapterSettings"]+ @model_validator(mode="after")+ def validate_provider_fields(self) -> Self:+ match self.shell_provider:+ case "shellctl":+ if not self.shellctl_entrypoint or not self.shellctl_entrypoint.strip():+ raise ValueError("shellctl_entrypoint is required when shell_provider is 'shellctl'.")+ _validate_url(self.shellctl_entrypoint, field_name="shellctl_entrypoint")+ case "enterprise":+ if not self.enterprise_sandbox_gateway_endpoint or not self.enterprise_sandbox_gateway_endpoint.strip():+ raise ValueError(+ "enterprise_sandbox_gateway_endpoint is required when shell_provider is 'enterprise'."+ )+ _validate_url(+ self.enterprise_sandbox_gateway_endpoint, field_name="enterprise_sandbox_gateway_endpoint"+ )+ return self+++def _validate_url(value: str, *, field_name: str) -> None:+ parsed = urlparse(value.strip())+ if parsed.scheme not in ("http", "https") or not parsed.netloc:+ raise ValueError(f"{field_name} must be a valid http(s) URL, got: {value!r}")+++__all__ = [+ "ShellAdapterSettings",+]diff --git a/dify-agent/src/dify_agent/adapters/shell/enterprise/__init__.py b/dify-agent/src/dify_agent/adapters/shell/enterprise/__init__.pynew file mode 100644index 00000000000..71e609c8c54--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/enterprise/__init__.py@@ -0,0 +1,3 @@+from dify_agent.adapters.shell.enterprise.enterprise import EnterpriseShellProvider++__all__ = ["EnterpriseShellProvider"]diff --git a/dify-agent/src/dify_agent/adapters/shell/enterprise/enterprise.py b/dify-agent/src/dify_agent/adapters/shell/enterprise/enterprise.pynew file mode 100644index 00000000000..c56b4c32058--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/enterprise/enterprise.py@@ -0,0 +1,235 @@+from __future__ import annotations++import logging+from dataclasses import dataclass, field+from typing import TypedDict++import httpx2 as httpx++from dify_agent.adapters.shell.protocols import (+ SandboxExpiredError,+ ShellCommandProtocol,+ ShellFileTransferProtocol,+ ShellProviderError,+ ShellProviderProtocol,+ ShellResourceProtocol,+)+from dify_agent.adapters.shell.shellctl import (+ ShellctlClientProtocol,+ ShellctlCommands,+ ShellctlFileTransfer,+)++logger = logging.getLogger(__name__)+++class _CreateSandboxReply(TypedDict):+ sandboxId: str+ status: str+++# ---------------------------------------------------------------------------+# Gateway client (control plane)+# ---------------------------------------------------------------------------+++@dataclass(slots=True)+class EnterpriseGatewayClient:+ """HTTP client for the enterprise sandbox gateway control-plane API."""++ endpoint: str+ auth_token: str+ timeout: float = 30.0+ _client: httpx.AsyncClient = field(init=False)++ def __post_init__(self) -> None:+ headers: dict[str, str] = {}+ if self.auth_token:+ headers["X-Inner-Api-Key"] = self.auth_token+ self._client = httpx.AsyncClient(+ base_url=self.endpoint.rstrip("/"),+ headers=headers,+ timeout=httpx.Timeout(self.timeout),+ )++ async def create_sandbox(self, *, tenant_id: str | None = None, template: str | None = None) -> _CreateSandboxReply:+ body: dict[str, str] = {}+ if tenant_id:+ body["tenantId"] = tenant_id+ if template:+ body["template"] = template+ response = await self._request("POST", "/v1/sandboxes", json=body)+ return response.json()++ async def delete_sandbox(self, sandbox_id: str) -> None:+ await self._request("DELETE", f"/v1/sandboxes/{sandbox_id}")++ async def close(self) -> None:+ await self._client.aclose()++ async def _request(self, method: str, path: str, **kwargs: object) -> httpx.Response:+ try:+ response = await self._client.request(method, path, **kwargs)+ response.raise_for_status()+ return response+ except httpx.TimeoutException as exc:+ raise ShellProviderError(f"Gateway request timed out: {method} {path}", code="timeout") from exc+ except httpx.HTTPStatusError as exc:+ raise ShellProviderError(+ f"Gateway returned {exc.response.status_code}: {exc.response.text}",+ code="gateway_error",+ ) from exc+ except httpx.RequestError as exc:+ raise ShellProviderError(f"Gateway request failed: {exc}", code="request_error") from exc+++# ---------------------------------------------------------------------------+# Resource & Provider+# ---------------------------------------------------------------------------+++@dataclass(slots=True)+class EnterpriseResource(ShellResourceProtocol):+ """A live enterprise sandbox session.++ Holds the gateway client, sandbox ID, and the shellctl client for data-plane+ operations. ``suspend()`` closes the shellctl and gateway clients without+ deleting the sandbox, so the same sandbox can be re-attached later.+ ``delete()`` additionally calls the gateway to destroy the sandbox pod.+ """++ _sandbox_id: str+ gateway: EnterpriseGatewayClient+ shellctl_client: ShellctlClientProtocol+ commands: ShellCommandProtocol+ files: ShellFileTransferProtocol++ @property+ def sandbox_id(self) -> str | None:+ return self._sandbox_id++ async def suspend(self) -> None:+ try:+ await self.shellctl_client.close()+ except Exception as exc:+ logger.warning("Failed to close shellctl client for sandbox %s: %s", self._sandbox_id, exc)+ try:+ await self.gateway.close()+ except Exception as exc:+ logger.warning("Failed to close gateway client: %s", exc)++ async def delete(self) -> None:+ try:+ await self.shellctl_client.close()+ except Exception as exc:+ logger.warning("Failed to close shellctl client for sandbox %s: %s", self._sandbox_id, exc)+ try:+ logger.info("Deleting enterprise sandbox via gateway: id=%s", self._sandbox_id)+ await self.gateway.delete_sandbox(self._sandbox_id)+ logger.info("Enterprise sandbox deleted: id=%s", self._sandbox_id)+ except ShellProviderError as exc:+ logger.warning("Failed to delete sandbox %s via gateway: %s", self._sandbox_id, exc)+ try:+ await self.gateway.close()+ except Exception as exc:+ logger.warning("Failed to close gateway client: %s", exc)+++@dataclass(slots=True)+class EnterpriseShellProvider(ShellProviderProtocol):+ """Provisions enterprise sandboxes via the gateway, connects via shellctl.++ Lifecycle:+ 1. ``create()`` calls the gateway to provision a new sandbox pod.+ 2. ``attach(sandbox_id)`` builds a shellctl client pointed at the+ gateway's ``/proxy/{sandboxId}`` route for an *existing* sandbox,+ without provisioning a new one.+ 3. Both return an ``EnterpriseResource`` with shellctl-backed+ command/file adapters.+ 4. ``suspend()`` on the resource closes the shellctl and gateway+ clients but leaves the sandbox pod alive.+ 5. ``delete()`` on the resource closes clients and deletes the+ sandbox via the gateway.+ """++ gateway_endpoint: str+ auth_token: str+ tenant_id: str | None = None+ template: str | None = None+ gateway_timeout: float = 30.0+ proxy_timeout: float = 60.0++ async def create(self) -> EnterpriseResource:+ gateway = EnterpriseGatewayClient(+ endpoint=self.gateway_endpoint,+ auth_token=self.auth_token,+ timeout=self.gateway_timeout,+ )+ try:+ logger.info("Creating enterprise sandbox via gateway %s", self.gateway_endpoint)+ reply = await gateway.create_sandbox(tenant_id=self.tenant_id, template=self.template)+ sandbox_id = reply["sandboxId"]+ logger.info("Enterprise sandbox created: id=%s status=%s", sandbox_id, reply.get("status"))+ except BaseException:+ await gateway.close()+ raise+ return self._build_resource(sandbox_id=sandbox_id, gateway=gateway)++ async def attach(self, sandbox_id: str) -> EnterpriseResource:+ gateway = EnterpriseGatewayClient(+ endpoint=self.gateway_endpoint,+ auth_token=self.auth_token,+ timeout=self.gateway_timeout,+ )+ logger.info("Attaching to existing enterprise sandbox: id=%s", sandbox_id)+ resource = self._build_resource(sandbox_id=sandbox_id, gateway=gateway)+ # Verify the sandbox is alive by running a trivial command through the proxy.+ # If the sandbox has expired, the gateway returns a 404 with "sandbox_expired";+ # if the pod is already gone the gateway returns a 404 with reason "NOT_FOUND".+ # Both surface as a ShellProviderError from the shellctl client and mean the+ # sandbox must be re-created.+ try:+ await resource.commands.run("true", timeout=5.0)+ except ShellProviderError as exc:+ await resource.suspend()+ message = str(exc).lower()+ if "expired" in message or "not_found" in message:+ raise SandboxExpiredError(sandbox_id, cause=exc) from exc+ raise+ return resource++ def _build_resource(self, *, sandbox_id: str, gateway: EnterpriseGatewayClient) -> EnterpriseResource:+ proxy_base_url = f"{self.gateway_endpoint.rstrip('/')}/proxy/"+ headers: dict[str, str] = {"X-Sandbox-Id": sandbox_id}+ if self.auth_token:+ headers["X-Inner-Api-Key"] = self.auth_token+ proxy_http_client = httpx.AsyncClient(+ base_url=proxy_base_url,+ headers=headers,+ follow_redirects=True,+ timeout=httpx.Timeout(self.proxy_timeout),+ transport=httpx.AsyncHTTPTransport(retries=3),+ )++ from shellctl.client import ShellctlClient++ client: ShellctlClientProtocol = ShellctlClient(+ proxy_base_url,+ token=self.auth_token,+ client=proxy_http_client,+ )++ return EnterpriseResource(+ _sandbox_id=sandbox_id,+ gateway=gateway,+ shellctl_client=client,+ commands=ShellctlCommands(client=client),+ files=ShellctlFileTransfer(client=client),+ )+++__all__ = [+ "EnterpriseGatewayClient",+ "EnterpriseResource",+ "EnterpriseShellProvider",+]diff --git a/dify-agent/src/dify_agent/adapters/shell/factory.py b/dify-agent/src/dify_agent/adapters/shell/factory.pyindex 104cdf8148b..d5177d96118 100644--- a/dify-agent/src/dify_agent/adapters/shell/factory.py+++ b/dify-agent/src/dify_agent/adapters/shell/factory.py@@ -1,4 +1,5 @@from dify_agent.adapters.shell.config import ShellAdapterSettings+from dify_agent.adapters.shell.enterprise import EnterpriseShellProviderfrom dify_agent.adapters.shell.protocols import ShellProviderProtocolfrom dify_agent.adapters.shell.shellctl import ShellctlProvider@@ -6,7 +7,7 @@ from dify_agent.adapters.shell.shellctl import ShellctlProviderdef create_shell_provider(settings: ShellAdapterSettings | None = None) -> ShellProviderProtocol:"""Return the shell provider selected by ``DIFY_AGENT_SHELL_PROVIDER``."""resolved = settings or ShellAdapterSettings()- provider = resolved.shell_provider.strip().lower()+ provider = resolved.shell_providermatch provider:case "shellctl":entrypoint = (resolved.shellctl_entrypoint or "").strip()@@ -16,6 +17,13 @@ def create_shell_provider(settings: ShellAdapterSettings | None = None) -> Shellentrypoint=entrypoint,token=resolved.shellctl_auth_token or "",)+ case "enterprise":+ return EnterpriseShellProvider(+ gateway_endpoint=(resolved.enterprise_sandbox_gateway_endpoint or "").strip(),+ auth_token=resolved.enterprise_sandbox_gateway_auth_token or "",+ gateway_timeout=resolved.enterprise_sandbox_gateway_timeout,+ proxy_timeout=resolved.enterprise_sandbox_proxy_timeout,+ )case _:raise ValueError(f"Unknown shell provider: {resolved.shell_provider!r}.")diff --git a/dify-agent/src/dify_agent/adapters/shell/protocols.py b/dify-agent/src/dify_agent/adapters/shell/protocols.pyindex 9487a202f45..6c9988f0fbd 100644--- a/dify-agent/src/dify_agent/adapters/shell/protocols.py+++ b/dify-agent/src/dify_agent/adapters/shell/protocols.py@@ -53,6 +53,15 @@ class ShellProviderError(RuntimeError):self.code = code+class SandboxExpiredError(ShellProviderError):+ """Raised by a shell provider when ``attach()`` targets a sandbox that no longer exists."""++ def __init__(self, sandbox_id: str, *, cause: ShellProviderError) -> None:+ super().__init__(str(cause), code=cause.code)+ self.sandbox_id = sandbox_id+ self.__cause__ = cause++class ShellCommandProtocol(Protocol):async def run(self,@@ -118,8 +127,35 @@ class ShellResourceProtocol(Protocol):@propertydef files(self) -> ShellFileTransferProtocol: ...- async def close(self) -> None: ...+ @property+ def sandbox_id(self) -> str | None: ...++ async def suspend(self) -> None:+ """Detach from the sandbox without destroying it.++ Called when the resource scope exits with suspend intent. The sandbox+ remains alive and can be re-attached later via ``attach(sandbox_id)``.+ """+ ...++ async def delete(self) -> None:+ """Destroy the sandbox and release all resources.++ Called when the resource scope exits with delete intent. The sandbox is+ permanently removed and cannot be re-attached.+ """+ ...class ShellProviderProtocol(Protocol):- async def create(self) -> ShellResourceProtocol: ...+ async def create(self) -> ShellResourceProtocol:+ """Provision a new sandbox and return a live resource."""+ ...++ async def attach(self, sandbox_id: str) -> ShellResourceProtocol:+ """Connect to an existing sandbox without provisioning a new one.++ The returned resource carries the same ``sandbox_id`` so the caller can+ persist it across runs and re-attach as needed.+ """+ ...diff --git a/dify-agent/src/dify_agent/adapters/shell/shellctl.py b/dify-agent/src/dify_agent/adapters/shell/shellctl.pyindex ac57773c884..f285483bda5 100644--- a/dify-agent/src/dify_agent/adapters/shell/shellctl.py+++ b/dify-agent/src/dify_agent/adapters/shell/shellctl.py@@ -227,9 +227,20 @@ class ShellctlFileTransfer(ShellFileTransferProtocol):@dataclass(slots=True)class ShellctlResource(ShellResourceProtocol):+ """Live shellctl connection.++ For shellctl there is no separate sandbox lifecycle: the shellctl server is a+ long-running process that persists across runs. The ``sandbox_id`` is the+ shellctl entrypoint URL, used as a stable identifier so the layer can+ distinguish ``create()`` (first run) from ``attach()`` (subsequent runs).+ Both ``suspend()`` and ``delete()`` simply close the HTTP client; the server+ and its filesystem remain intact either way.+ """+client: ShellctlClientProtocol_commands: ShellCommandProtocol_files: ShellFileTransferProtocol+ _sandbox_id: str | None = None@propertydef commands(self) -> ShellCommandProtocol:@@ -239,7 +250,17 @@ class ShellctlResource(ShellResourceProtocol):def files(self) -> ShellFileTransferProtocol:return self._files- async def close(self) -> None:+ @property+ def sandbox_id(self) -> str | None:+ return self._sandbox_id++ async def suspend(self) -> None:+ await self._close_client()++ async def delete(self) -> None:+ await self._close_client()++ async def _close_client(self) -> None:try:await self.client.close()except RuntimeError as exc:@@ -254,6 +275,12 @@ class ShellctlProvider(ShellProviderProtocol):client_factory: ShellctlClientFactory | None = Noneasync def create(self) -> ShellctlResource:+ return self._build_resource(sandbox_id=self.entrypoint)++ async def attach(self, sandbox_id: str) -> ShellctlResource:+ return self._build_resource(sandbox_id=sandbox_id)++ def _build_resource(self, *, sandbox_id: str | None) -> ShellctlResource:client = (self.client_factory()if self.client_factory is not None@@ -267,6 +294,7 @@ class ShellctlProvider(ShellProviderProtocol):client=client,_commands=ShellctlCommands(client=client),_files=ShellctlFileTransfer(client=client),+ _sandbox_id=sandbox_id,)diff --git a/dify-agent/src/dify_agent/layers/shell/configs.py b/dify-agent/src/dify_agent/layers/shell/configs.pyindex f538ffa2636..3a195826744 100644--- a/dify-agent/src/dify_agent/layers/shell/configs.py+++ b/dify-agent/src/dify_agent/layers/shell/configs.py@@ -76,6 +76,13 @@ class DifyShellSandboxConfig(BaseModel):config: dict[str, object] = Field(default_factory=dict)+class DifyShellEnterpriseSandboxConfig(DifyShellSandboxConfig):+ """Enterprise sandbox provider configuration."""++ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")+ gateway_endpoint: str = Field(..., max_length=255)++class DifyShellLayerConfig(LayerConfig):"""Public config for the shellctl-backed Dify shell layer."""diff --git a/dify-agent/src/dify_agent/layers/shell/layer.py b/dify-agent/src/dify_agent/layers/shell/layer.pyindex 53af60641ce..686047ab78c 100644--- a/dify-agent/src/dify_agent/layers/shell/layer.py+++ b/dify-agent/src/dify_agent/layers/shell/layer.py@@ -9,6 +9,19 @@ compatible while live command execution no longer depends on the sandbox user'sambient home directory. Entering or re-entering the layer re-ensures the livehome/workspace directories for the currently bound ``agent_id`` before usercommands are sent.++Sandbox lifecycle:+ The shell provider exposes four operations: ``create``, ``attach``,+ ``suspend``, and ``delete``. On the first run (no ``sandbox_id`` in+ runtime state) ``resource_context()`` calls ``create()`` to provision a+ new sandbox and persists the returned ``sandbox_id``. On subsequent runs+ it calls ``attach(sandbox_id)`` to re-connect to the existing sandbox.+ If the sandbox has expired (the provider raises ``SandboxExpiredError``),+ the error propagates to the caller — the user must start a new session.+ On normal exit (suspend) the resource is detached via ``suspend()``,+ keeping the sandbox alive. On final cleanup (``on_context_delete``) the+ resource is destroyed via ``delete()``. This allows the enterprise+ provider to reuse the same sandbox pod across conversation turns."""from __future__ import annotations@@ -193,6 +206,7 @@ class DifyShellLayerDeps(LayerDeps):class DifyShellRuntimeState(BaseModel):session_id: str | None = Noneworkspace_cwd: str | None = None+ sandbox_id: str | None = Nonejob_ids: list[str] = Field(default_factory=list)job_offsets: dict[str, NonNegativeInt] = Field(default_factory=dict)@@ -239,6 +253,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCagent_stub_api_base_url: str | None = Noneagent_stub_token_factory: ShellAgentStubTokenFactory | None = None_shell_resource: ShellResourceProtocol | None = None+ _resource_should_delete: bool = False@classmethod@override@@ -289,15 +304,41 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC@override@asynccontextmanagerasync def resource_context(self) -> AsyncGenerator[None]:+ """Acquire the live shell resource for one run invocation.++ On the first run (no ``sandbox_id`` in runtime state) the provider's+ ``create()`` is called to provision a new sandbox. On subsequent runs+ ``attach(sandbox_id)`` re-connects to the existing sandbox. If the+ sandbox has expired (``SandboxExpiredError``), the error propagates+ to the caller — the user must start a new session.++ On exit, ``suspend()`` is called by default to keep the sandbox alive.+ If ``on_context_delete()`` ran (setting ``_resource_should_delete``),+ ``delete()`` is called instead to destroy the sandbox.+ """if self._shell_resource is not None:raise RuntimeError("DifyShellLayer resource_context() is already active for this layer instance.")- resource = await self.shell_provider.create()+ sandbox_id = self.runtime_state.sandbox_id+ if sandbox_id is not None:+ resource = await self.shell_provider.attach(sandbox_id)+ else:+ resource = await self.shell_provider.create()+ self.runtime_state = DifyShellRuntimeState.model_validate(+ {+ **self.runtime_state.model_dump(mode="python"),+ "sandbox_id": resource.sandbox_id,+ }+ )self._shell_resource = resource+ self._resource_should_delete = Falsetry:yieldfinally:self._shell_resource = None- await resource.close()+ if self._resource_should_delete:+ await resource.delete()+ else:+ await resource.suspend()@overrideasync def on_context_create(self) -> None:@@ -309,6 +350,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCexcept BaseException:if session_id is not None:await self._cleanup_workspace_best_effort(session_id)+ self._resource_should_delete = Trueraiseself.runtime_state = DifyShellRuntimeState.model_validate({@@ -347,6 +389,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC)await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)self._clear_tracked_jobs()+ self._resource_should_delete = Trueasync def _tool_run(self, script: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> ShellRunToolResult:try:diff --git a/dify-agent/src/dify_agent/runtime/compositor_factory.py b/dify-agent/src/dify_agent/runtime/compositor_factory.pyindex 1a9233eff99..cecdd848bdd 100644--- a/dify-agent/src/dify_agent/runtime/compositor_factory.py+++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py@@ -16,8 +16,10 @@ plugin/knowledge business-layer family:Public DTOs provide Dify context plus plugin/model/tool data, while server-onlyplugin daemon settings and Dify API inner settings are injected through provider-factories. Optional shellctl entrypoint/auth token and Agent Stub URL/token-factory are injected for ``DifyShellLayer``. The resulting ``Compositor``+factories. An already-selected shell provider (shellctl or enterprise, built at+the runtime boundary) and the Agent Stub URL/token factory are injected for+``DifyShellLayer``; a ``None`` shell provider leaves the shell layer disabled.+The resulting ``Compositor``remains Agenton state-only at the snapshot boundary: live resources such asHTTP clients are injected by runtime-owned providers, may be held on activelayer instances inside ``resource_context()``, and never enter session@@ -27,7 +29,10 @@ snapshots.from __future__ import annotationsfrom collections.abc import Mapping, Sequence-from typing import Any, cast+from typing import TYPE_CHECKING, Any, cast++if TYPE_CHECKING:+ from dify_agent.adapters.shell.protocols import ShellProviderProtocolfrom pydantic_ai.messages import UserContent@@ -62,32 +67,11 @@ def create_default_layer_providers(plugin_daemon_api_key: str = "",inner_api_url: str = "http://localhost:5001",inner_api_key: str = "",- shellctl_entrypoint: str | None = None,- shellctl_auth_token: str | None = None,+ shell_provider: ShellProviderProtocol | None = None,agent_stub_api_base_url: str | None = None,agent_stub_token_factory: ShellAgentStubTokenFactory | None = None,) -> tuple[DifyAgentLayerProvider, ...]:- """Return the server provider set of safe config-constructible layers.-- ``shellctl_auth_token`` defaults to no token. An explicit empty string- prevents ``ShellctlClient`` from falling back to the Dify Agent process's- ``SHELLCTL_AUTH_TOKEN`` environment variable; deployments that enable- shellctl bearer auth must set the Dify Agent server setting explicitly.- """- from dify_agent.adapters.shell.config import ShellAdapterSettings- from dify_agent.adapters.shell.factory import create_shell_provider-- shell_provider = (- create_shell_provider(- ShellAdapterSettings(- shell_provider="shellctl",- shellctl_entrypoint=shellctl_entrypoint,- shellctl_auth_token=shellctl_auth_token,- )- )- if shellctl_entrypoint- else None- )+ """Return the server provider set of safe config-constructible layers."""return (LayerProvider.from_layer_type(PromptLayer),LayerProvider.from_layer_type(PydanticAIHistoryLayer),diff --git a/dify-agent/src/dify_agent/runtime/runner.py b/dify-agent/src/dify_agent/runtime/runner.pyindex 13308fa4f9c..b7d1fe1260e 100644--- a/dify-agent/src/dify_agent/runtime/runner.py+++ b/dify-agent/src/dify_agent/runtime/runner.py@@ -60,6 +60,7 @@ from dify_agent.protocol.schemas import (from dify_agent.runtime.agent_factory import create_agent, normalize_user_inputfrom dify_agent.runtime.agenton_validation import is_agenton_enter_validation_runtime_errorfrom dify_agent.runtime.compositor_factory import build_pydantic_ai_compositor, create_default_layer_providers+from dify_agent.adapters.shell.protocols import SandboxExpiredErrorfrom dify_agent.runtime.event_sink import (RunEventSink,emit_pydantic_ai_event,@@ -110,6 +111,9 @@ def _run_failed_error_payload(exc: Exception) -> tuple[str, str | None]:message = str(exc) or type(exc).__name__reason: str | None = None+ if isinstance(exc, SandboxExpiredError):+ return message, "sandbox_expired"+if isinstance(exc, ModelHTTPError):body = exc.bodyif isinstance(body, Mapping):diff --git a/dify-agent/src/dify_agent/server/app.py b/dify-agent/src/dify_agent/server/app.pyindex 49816d4daf0..45302042d9a 100644--- a/dify-agent/src/dify_agent/server/app.py+++ b/dify-agent/src/dify_agent/server/app.py@@ -59,19 +59,17 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:agent_stub_file_request_handler = resolved_settings.create_agent_stub_file_request_handler()agent_stub_config_request_handler = resolved_settings.create_agent_stub_config_request_handler()agent_stub_drive_request_handler = resolved_settings.create_agent_stub_drive_request_handler()+ shell_provider = resolved_settings.build_shell_provider()layer_providers = create_default_layer_providers(plugin_daemon_url=resolved_settings.plugin_daemon_url,plugin_daemon_api_key=resolved_settings.plugin_daemon_api_key,inner_api_url=resolved_settings.inner_api_url,inner_api_key=resolved_settings.inner_api_key or "",- shellctl_entrypoint=resolved_settings.shellctl_entrypoint,- shellctl_auth_token=resolved_settings.shellctl_auth_token,+ shell_provider=shell_provider,agent_stub_api_base_url=resolved_settings.agent_stub_api_base_url,agent_stub_token_factory=agent_stub_token_factory,)- sandbox_file_service = (- SandboxFileService(layer_providers=layer_providers) if resolved_settings.shellctl_entrypoint else None- )+ sandbox_file_service = SandboxFileService(layer_providers=layer_providers) if shell_provider is not None else Nonestate: dict[str, object] = {}@asynccontextmanagerdiff --git a/dify-agent/src/dify_agent/server/settings.py b/dify-agent/src/dify_agent/server/settings.pyindex e614ed336b4..db482aa5ec2 100644--- a/dify-agent/src/dify_agent/server/settings.py+++ b/dify-agent/src/dify_agent/server/settings.py@@ -12,11 +12,14 @@ live here under the ``DIFY_AGENT_...`` environment-variable namespace.import httpx-from typing import ClassVar+from typing import TYPE_CHECKING, ClassVar, Literalfrom pydantic import AnyHttpUrl, Field, TypeAdapter, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict+if TYPE_CHECKING:+ from dify_agent.adapters.shell.protocols import ShellProviderProtocol+from dify_agent.agent_stub.protocol.agent_stub import normalize_agent_stub_api_base_url, parse_agent_stub_endpointfrom dify_agent.agent_stub.server.agent_stub_config import DifyApiAgentStubConfigRequestHandlerfrom dify_agent.agent_stub.server.agent_stub_drive import DifyApiAgentStubDriveRequestHandler@@ -38,8 +41,13 @@ class ServerSettings(BaseSettings):plugin_daemon_api_key: str = ""inner_api_url: str = "http://localhost:5001"inner_api_key: str | None = None+ shell_provider: Literal["shellctl", "enterprise"] = "shellctl"shellctl_entrypoint: str | None = Noneshellctl_auth_token: str | None = None+ enterprise_sandbox_gateway_endpoint: str | None = None+ enterprise_sandbox_gateway_auth_token: str | None = None+ enterprise_sandbox_gateway_timeout: float = Field(default=30.0, gt=0)+ enterprise_sandbox_proxy_timeout: float = Field(default=60.0, gt=0)agent_stub_api_base_url: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_API_BASE_URL")agent_stub_grpc_bind_address: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_GRPC_BIND_ADDRESS")server_secret_key: str | None = None@@ -131,6 +139,29 @@ class ServerSettings(BaseSettings):raise ValueError("DIFY_AGENT_STUB_GRPC_BIND_ADDRESS requires a grpc:// DIFY_AGENT_STUB_API_BASE_URL.")return self+ def build_shell_provider(self) -> "ShellProviderProtocol | None":+ from dify_agent.adapters.shell.config import ShellAdapterSettings+ from dify_agent.adapters.shell.factory import create_shell_provider++ match self.shell_provider:+ case "shellctl":+ if not self.shellctl_entrypoint:+ return None+ case "enterprise":+ if not self.enterprise_sandbox_gateway_endpoint:+ return None+ return create_shell_provider(+ ShellAdapterSettings(+ shell_provider=self.shell_provider,+ shellctl_entrypoint=self.shellctl_entrypoint,+ shellctl_auth_token=self.shellctl_auth_token,+ enterprise_sandbox_gateway_endpoint=self.enterprise_sandbox_gateway_endpoint,+ enterprise_sandbox_gateway_auth_token=self.enterprise_sandbox_gateway_auth_token,+ enterprise_sandbox_gateway_timeout=self.enterprise_sandbox_gateway_timeout,+ enterprise_sandbox_proxy_timeout=self.enterprise_sandbox_proxy_timeout,+ )+ )+def create_agent_stub_token_codec(self) -> AgentStubTokenCodec | None:"""Return the Agent Stub token codec when the server secret is configured."""if self.server_secret_key is None:diff --git a/dify-agent/tests/local/dify_agent/adapters/shell/test_config.py b/dify-agent/tests/local/dify_agent/adapters/shell/test_config.pynew file mode 100644index 00000000000..19110694403--- /dev/null+++ b/dify-agent/tests/local/dify_agent/adapters/shell/test_config.py@@ -0,0 +1,78 @@+"""Tests for ShellAdapterSettings provider-based field validation."""++from __future__ import annotations++import pytest+from pydantic import ValidationError++from dify_agent.adapters.shell.config import ShellAdapterSettings+++class TestShellctlValidation:+ def test_valid_url_passes(self) -> None:+ settings = ShellAdapterSettings(+ shell_provider="shellctl",+ shellctl_entrypoint="http://shellctl.example.com",+ )+ assert settings.shellctl_entrypoint == "http://shellctl.example.com"++ def test_https_url_passes(self) -> None:+ settings = ShellAdapterSettings(+ shell_provider="shellctl",+ shellctl_entrypoint="https://shellctl.internal:8443/v1",+ )+ assert settings.shellctl_entrypoint == "https://shellctl.internal:8443/v1"++ def test_missing_entrypoint_raises(self) -> None:+ with pytest.raises(ValidationError, match="shellctl_entrypoint is required"):+ ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=None)++ def test_blank_entrypoint_raises(self) -> None:+ with pytest.raises(ValidationError, match="shellctl_entrypoint is required"):+ ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=" ")++ def test_invalid_url_raises(self) -> None:+ with pytest.raises(ValidationError, match="must be a valid http\\(s\\) URL"):+ ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint="not-a-url")++ def test_ftp_scheme_rejected(self) -> None:+ with pytest.raises(ValidationError, match="must be a valid http\\(s\\) URL"):+ ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint="ftp://host/path")+++class TestEnterpriseValidation:+ def test_valid_url_passes(self) -> None:+ settings = ShellAdapterSettings(+ shell_provider="enterprise",+ enterprise_sandbox_gateway_endpoint="http://gateway.internal:9000",+ )+ assert settings.enterprise_sandbox_gateway_endpoint == "http://gateway.internal:9000"++ def test_https_url_passes(self) -> None:+ settings = ShellAdapterSettings(+ shell_provider="enterprise",+ enterprise_sandbox_gateway_endpoint="https://gateway.prod.example.com/api",+ )+ assert settings.enterprise_sandbox_gateway_endpoint == "https://gateway.prod.example.com/api"++ def test_missing_endpoint_raises(self) -> None:+ with pytest.raises(ValidationError, match="enterprise_sandbox_gateway_endpoint is required"):+ ShellAdapterSettings(shell_provider="enterprise", enterprise_sandbox_gateway_endpoint=None)++ def test_blank_endpoint_raises(self) -> None:+ with pytest.raises(ValidationError, match="enterprise_sandbox_gateway_endpoint is required"):+ ShellAdapterSettings(shell_provider="enterprise", enterprise_sandbox_gateway_endpoint="")++ def test_invalid_url_raises(self) -> None:+ with pytest.raises(ValidationError, match="must be a valid http\\(s\\) URL"):+ ShellAdapterSettings(+ shell_provider="enterprise",+ enterprise_sandbox_gateway_endpoint="just-a-hostname",+ )++ def test_ftp_scheme_rejected(self) -> None:+ with pytest.raises(ValidationError, match="must be a valid http\\(s\\) URL"):+ ShellAdapterSettings(+ shell_provider="enterprise",+ enterprise_sandbox_gateway_endpoint="ftp://gateway/path",+ )diff --git a/dify-agent/tests/local/dify_agent/adapters/shell/test_enterprise.py b/dify-agent/tests/local/dify_agent/adapters/shell/test_enterprise.pynew file mode 100644index 00000000000..86ac7e79172--- /dev/null+++ b/dify-agent/tests/local/dify_agent/adapters/shell/test_enterprise.py@@ -0,0 +1,42 @@+from unittest.mock import patch++import httpx2+import pytest++from dify_agent.adapters.shell.enterprise import EnterpriseShellProvider+++async def test_attach_uses_shellctl_compatible_http_client(monkeypatch: pytest.MonkeyPatch) -> None:+ def handler(request: httpx2.Request) -> httpx2.Response:+ assert request.url.path == "/proxy/v1/jobs/run"+ assert request.headers["X-Sandbox-Id"] == "sandbox-1"+ return httpx2.Response(+ 200,+ json={+ "job_id": "job-1",+ "done": True,+ "status": "exited",+ "exit_code": 0,+ "output_path": "/tmp/output.log",+ "output": "",+ "offset": 0,+ "truncated": False,+ },+ )++ transport = httpx2.MockTransport(handler)+ monkeypatch.setattr(httpx2, "AsyncHTTPTransport", lambda **kwargs: transport)+ with patch.object(httpx2, "AsyncClient", wraps=httpx2.AsyncClient) as async_client:+ provider = EnterpriseShellProvider(+ gateway_endpoint="http://gateway.example",+ auth_token="secret",+ proxy_timeout=90,+ )++ resource = await provider.attach("sandbox-1")++ timeout = async_client.call_args.kwargs["timeout"]+ assert isinstance(timeout, httpx2.Timeout)+ assert timeout.read == 90+ await resource.suspend()diff --git a/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py b/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.pyindex 390f2edbef1..9af8a15dbb1 100644--- a/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py+++ b/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py@@ -10,6 +10,7 @@ from typing import castimport httpx2 as httpximport pytest+from pydantic import ValidationErrorfrom dify_agent.adapters.shell import shellctlfrom dify_agent.adapters.shell.config import ShellAdapterSettings@@ -141,15 +142,13 @@ def _client_protocol(client: FakeShellctlClient) -> ShellctlClientProtocol:def test_factory_unknown_provider_raises() -> None:- settings = ShellAdapterSettings(shell_provider="nope")- with pytest.raises(ValueError, match="Unknown shell provider"):- create_shell_provider(settings)+ with pytest.raises(ValidationError):+ ShellAdapterSettings(shell_provider="nope") # type: ignore[arg-type]def test_factory_shellctl_requires_entrypoint() -> None:- settings = ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=None)- with pytest.raises(ValueError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):- create_shell_provider(settings)+ with pytest.raises(ValidationError, match="shellctl_entrypoint is required"):+ ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=None)def test_factory_builds_shellctl_provider_from_settings() -> None:@@ -160,13 +159,13 @@ def test_factory_builds_shellctl_provider_from_settings() -> None:assert provider.token == ""-def test_provider_create_opens_only_live_resource_and_close_closes_client() -> None:+def test_provider_create_opens_only_live_resource_and_suspend_closes_client() -> None:client = FakeShellctlClient()async def scenario() -> None:resource = await _provider(client).create()assert client.run_calls == []- await resource.close()+ await resource.suspend()asyncio.run(scenario())assert client.closed is True@@ -232,7 +231,7 @@ def test_commands_forward_parameters_and_map_metadata() -> None:interrupt_result = await resource.commands.interrupt("run-job", grace_seconds=1.5)tail_result = await resource.commands.tail("run-job")await resource.commands.delete("run-job", force=True, grace_seconds=2.0)- await resource.close()+ await resource.suspend()assert run_result == ShellCommandResult(job_id="run-job",diff --git a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.pyindex f2a702139bb..2a328c7770f 100644--- a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py+++ b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py@@ -21,6 +21,7 @@ from dify_agent.adapters.shell.protocols import (ShellCommandStatus,ShellFileTransferProtocol,ShellProviderError,+ SandboxExpiredError,ShellProviderProtocol,ShellResourceProtocol,)@@ -209,21 +210,39 @@ class FakeCommands:class FakeResource(ShellResourceProtocol):commands: FakeCommandsfiles: FakeFiles = field(default_factory=FakeFiles)- closed: bool = False+ suspended: bool = False+ deleted: bool = False+ _sandbox_id: str | None = None- async def close(self) -> None:- self.closed = True+ @property+ def sandbox_id(self) -> str | None:+ return self._sandbox_id++ async def suspend(self) -> None:+ self.suspended = True++ async def delete(self) -> None:+ self.deleted = True@dataclass(slots=True)class FakeProvider(ShellProviderProtocol):resource: FakeResourcecreate_calls: int = 0+ attach_calls: list[str] = field(default_factory=list)+ attach_error: ShellProviderError | None = Noneasync def create(self) -> ShellResourceProtocol:self.create_calls += 1return self.resource+ async def attach(self, sandbox_id: str) -> ShellResourceProtocol:+ self.attach_calls.append(sandbox_id)+ if self.attach_error is not None:+ raise self.attach_error+ self.resource._sandbox_id = sandbox_id+ return self.resource+def _layer(*, commands: FakeCommands, config: DifyShellLayerConfig | None = None@@ -259,12 +278,14 @@ def _runtime_state(*,session_id: str = "abc12ff",workspace_cwd: str = "~/workspace/abc12ff",+ sandbox_id: str | None = None,job_ids: list[str] | None = None,job_offsets: dict[str, int] | None = None,) -> DifyShellRuntimeState:return DifyShellRuntimeState(session_id=session_id,workspace_cwd=workspace_cwd,+ sandbox_id=sandbox_id,job_ids=[] if job_ids is None else job_ids,job_offsets={} if job_offsets is None else job_offsets,)@@ -274,14 +295,16 @@ def test_shell_type_id_constant_matches_implementation_class() -> None:assert DIFY_SHELL_LAYER_TYPE_ID == DifyShellLayer.type_id-def test_resource_context_calls_provider_create_and_resource_close() -> None:+def test_resource_context_calls_provider_create_and_suspends_on_exit() -> None:layer, provider = _layer(commands=FakeCommands())async def scenario() -> None:async with layer.resource_context():assert provider.create_calls == 1- assert provider.resource.closed is False- assert provider.resource.closed is True+ assert provider.resource.suspended is False+ assert provider.resource.deleted is False+ assert provider.resource.suspended is True+ assert provider.resource.deleted is Falseasyncio.run(scenario())@@ -312,13 +335,14 @@ def test_shell_layer_create_allocates_workspace_and_bootstraps(monkeypatch: pyteasync def scenario() -> None:async with layer.resource_context():await layer.on_context_create()- assert provider.resource.closed is False+ assert provider.resource.suspended is Falseasyncio.run(scenario())assert layer.runtime_state.session_id == "abc12ff"assert layer.runtime_state.workspace_cwd == "~/workspace/abc12ff"assert [call.job_id for call in provider.resource.commands.delete_calls] == ["mkdir-job", "bootstrap-job"]+ assert provider.resource.suspended is Truedef test_shell_layer_uses_agent_specific_home_and_workspace_cwd(@@ -370,8 +394,8 @@ def test_shell_layer_suspend_does_not_close_before_resource_context_exits() -> Nasync def scenario() -> None:async with layer.resource_context():await layer.on_context_suspend()- assert provider.resource.closed is False- assert provider.resource.closed is True+ assert provider.resource.suspended is False+ assert provider.resource.suspended is Trueasyncio.run(scenario())@@ -398,7 +422,7 @@ def test_shell_layer_resume_recreates_live_home_and_workspace() -> None:asyncio.run(scenario())assert [call.job_id for call in commands.delete_calls] == ["resume-job"]- assert provider.resource.closed is True+ assert provider.resource.suspended is Truedef test_shell_layer_resume_requires_agent_id_for_live_workspace_reentry() -> None:@@ -437,7 +461,7 @@ def test_shell_layer_delete_cleans_workspace_and_tracked_jobs() -> None:assert [call.job_id for call in commands.delete_calls] == ["cleanup-job", "user-job"]assert layer.runtime_state.job_ids == []assert layer.runtime_state.job_offsets == {}- assert provider.resource.closed is True+ assert provider.resource.deleted is Truedef test_shell_layer_tools_map_inputs_and_maintain_offsets_with_tail_end() -> None:@@ -541,7 +565,7 @@ def test_shell_layer_tools_map_inputs_and_maintain_offsets_with_tail_end() -> Noassert layer.runtime_state.job_offsets == {"user-job": 34}assert commands.tail_calls == [TailCall(job_id="user-job"), TailCall(job_id="user-job")]- assert provider.resource.closed is True+ assert provider.resource.suspended is Truedef test_shell_run_keeps_original_offset_when_tail_lookup_fails_for_truncated_output() -> None:@@ -586,7 +610,7 @@ def test_shell_run_keeps_original_offset_when_tail_lookup_fails_for_truncated_ouassert layer.runtime_state.job_offsets == {"user-job": 10}assert commands.tail_calls == [TailCall(job_id="user-job")]- assert provider.resource.closed is True+ assert provider.resource.suspended is Truedef test_shell_run_formats_large_non_truncated_output_without_tail_lookup() -> None:@@ -1214,3 +1238,97 @@ def test_shell_runtime_state_validates_workspace_identity_and_offset_keys() -> N"job_offsets": {"job-2": 3},})+++def test_resource_context_attaches_when_sandbox_id_is_present() -> None:+ layer, provider = _layer(commands=FakeCommands())+ layer.runtime_state = _runtime_state(sandbox_id="existing-sandbox-1")++ async def scenario() -> None:+ async with layer.resource_context():+ assert provider.create_calls == 0+ assert provider.attach_calls == ["existing-sandbox-1"]+ assert provider.resource.suspended is False+ assert provider.resource.suspended is True++ asyncio.run(scenario())+++def test_resource_context_deletes_on_context_delete() -> None:+ commands = FakeCommands(+ run_handler=lambda script, cwd, env, timeout: _command_result(+ "cleanup-job", status="exited", done=True, exit_code=0+ )+ )+ layer, provider = _layer(commands=commands)+ _bind_execution_context(layer)+ layer.runtime_state = _runtime_state()++ async def scenario() -> None:+ async with layer.resource_context():+ await layer.on_context_delete()+ assert provider.resource.deleted is True+ assert provider.resource.suspended is False++ asyncio.run(scenario())+++def test_resource_context_suspends_on_context_suspend() -> None:+ layer, provider = _layer(commands=FakeCommands())+ layer.runtime_state = _runtime_state()++ async def scenario() -> None:+ async with layer.resource_context():+ await layer.on_context_suspend()+ assert provider.resource.suspended is True+ assert provider.resource.deleted is False++ asyncio.run(scenario())+++def test_resource_context_persists_sandbox_id_from_provider() -> None:+ layer, provider = _layer(commands=FakeCommands())+ provider.resource._sandbox_id = "new-sandbox-42"++ async def scenario() -> None:+ async with layer.resource_context():+ pass++ asyncio.run(scenario())+ assert layer.runtime_state.sandbox_id == "new-sandbox-42"+++def test_resource_context_propagates_sandbox_expired() -> None:+ """When attach() raises SandboxExpiredError, the error propagates to the caller.+ The user must start a new session — no in-place recovery is attempted."""+ layer, provider = _layer(commands=FakeCommands())+ provider.attach_error = SandboxExpiredError(+ "stale-sandbox-1",+ cause=ShellProviderError(+ 'request_failed (404): {"reason":"NOT_FOUND","message":"error: code = 400 reason = sandbox_expired message = sandbox has expired"}',+ code="request_failed",+ ),+ )+ layer.runtime_state = _runtime_state(sandbox_id="stale-sandbox-1")++ async def scenario() -> None:+ with pytest.raises(SandboxExpiredError):+ async with layer.resource_context():+ pass++ asyncio.run(scenario())+ assert provider.attach_calls == ["stale-sandbox-1"]+ assert provider.create_calls == 0+++def test_resource_context_reraises_non_expired_attach_error() -> None:+ layer, provider = _layer(commands=FakeCommands())+ provider.attach_error = ShellProviderError("some other error", code="request_failed")+ layer.runtime_state = _runtime_state(sandbox_id="sandbox-1")++ async def scenario() -> None:+ async with layer.resource_context():+ pass++ with pytest.raises(ShellProviderError, match="some other error"):+ asyncio.run(scenario())diff --git a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.pyindex 6802f525a05..620c4e2acc5 100644--- a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py+++ b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py@@ -2,7 +2,6 @@ import sysimport typesfrom typing import cast-import pytestfrom pydantic import BaseModel@@ -85,7 +84,6 @@ if "jsonschema" not in sys.modules:sys.modules["jsonschema.protocols"] = jsonschema_protocols_modulesys.modules["jsonschema.validators"] = jsonschema_validators_module-from dify_agent.adapters.shell.config import ShellAdapterSettingsfrom dify_agent.adapters.shell.protocols import ShellProviderProtocolfrom dify_agent.layers.dify_core_tools import DIFY_CORE_TOOLS_LAYER_TYPE_ID, DifyCoreToolsLayerConfigfrom dify_agent.layers.dify_core_tools.layer import DifyCoreToolsLayer@@ -102,54 +100,15 @@ class FakeProvider:raise AssertionError("create should not be called by these tests")-def test_default_layer_providers_register_shell_layer_with_configured_token_factory(- monkeypatch: pytest.MonkeyPatch,-) -> None:- captured_settings: list[ShellAdapterSettings] = []+def test_default_layer_providers_wire_provided_shell_provider() -> None:fake_provider = FakeProvider()- def fake_create_shell_provider(settings: ShellAdapterSettings) -> ShellProviderProtocol:- captured_settings.append(settings)- return cast(ShellProviderProtocol, fake_provider)-- monkeypatch.setattr("dify_agent.adapters.shell.factory.create_shell_provider", fake_create_shell_provider)-- providers = create_default_layer_providers(- shellctl_entrypoint="http://shellctl.example",- shellctl_auth_token="shell-secret",- )+ providers = create_default_layer_providers(shell_provider=cast(ShellProviderProtocol, fake_provider))shell_provider = next(provider for provider in providers if provider.type_id == DIFY_SHELL_LAYER_TYPE_ID)shell_layer = shell_provider.create_layer(DifyShellLayerConfig())assert isinstance(shell_layer, DifyShellLayer)assert shell_layer.shell_provider is fake_provider- assert len(captured_settings) == 1- assert captured_settings[0].shellctl_entrypoint == "http://shellctl.example"- assert captured_settings[0].shellctl_auth_token == "shell-secret"---def test_default_layer_providers_keep_empty_shellctl_token_by_default(- monkeypatch: pytest.MonkeyPatch,-) -> None:- captured_settings: list[ShellAdapterSettings] = []-- def fake_create_shell_provider(settings: ShellAdapterSettings) -> ShellProviderProtocol:- captured_settings.append(settings)- return cast(ShellProviderProtocol, FakeProvider())-- monkeypatch.setattr("dify_agent.adapters.shell.factory.create_shell_provider", fake_create_shell_provider)-- providers = create_default_layer_providers(shellctl_entrypoint="http://shellctl.example")- shell_provider = next(provider for provider in providers if provider.type_id == DIFY_SHELL_LAYER_TYPE_ID)- _ = shell_provider.create_layer(DifyShellLayerConfig())-- assert len(captured_settings) == 1- assert captured_settings[0].shellctl_auth_token is None---def test_shell_provider_rejects_blank_settings_entrypoint_when_default_providers_are_built() -> None:- with pytest.raises(ValueError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):- _ = create_default_layer_providers(shellctl_entrypoint=" ")def test_default_layer_providers_forward_agent_stub_token_factory() -> None:@@ -164,7 +123,7 @@ def test_default_layer_providers_forward_agent_stub_token_factory() -> None:return f"token-for:{execution_context.tenant_id}:{session_id}"providers = create_default_layer_providers(- shellctl_entrypoint="http://shellctl.example",+ shell_provider=cast(ShellProviderProtocol, FakeProvider()),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=build_agent_stub_token,)diff --git a/dify-agent/tests/local/dify_agent/runtime/test_runner.py b/dify-agent/tests/local/dify_agent/runtime/test_runner.pyindex 7b7762a0ace..d131675dcf5 100644--- a/dify-agent/tests/local/dify_agent/runtime/test_runner.py+++ b/dify-agent/tests/local/dify_agent/runtime/test_runner.py@@ -1557,9 +1557,7 @@ def test_runner_rejects_duplicate_tool_names_between_shell_and_other_layers(),)layer_providers = tuple(- provider- for provider in create_default_layer_providers(shellctl_entrypoint="http://unused")- if provider.type_id != DIFY_SHELL_LAYER_TYPE_ID+ provider for provider in create_default_layer_providers() if provider.type_id != DIFY_SHELL_LAYER_TYPE_ID) + (shell_provider,)request = CreateRunRequest(@@ -2772,7 +2770,9 @@ def test_runner_treats_invalid_shell_snapshot_offsets_as_validation_error() -> Nrun_id="run-invalid-shell-offset",plugin_daemon_http_client=client,dify_api_http_client=client,- layer_providers=create_default_layer_providers(shellctl_entrypoint="http://shellctl"),+ layer_providers=create_default_layer_providers(+ shell_provider=ShellctlProvider(entrypoint="http://shellctl", token=""),+ ),).run()asyncio.run(scenario())diff --git a/dify-agent/tests/local/dify_agent/server/test_settings.py b/dify-agent/tests/local/dify_agent/server/test_settings.pyindex da37eb16747..c523eef909a 100644--- a/dify-agent/tests/local/dify_agent/server/test_settings.py+++ b/dify-agent/tests/local/dify_agent/server/test_settings.py@@ -8,6 +8,8 @@ import httpximport pytestfrom pydantic import ValidationError+from dify_agent.adapters.shell.enterprise import EnterpriseShellProvider+from dify_agent.adapters.shell.shellctl import ShellctlProviderfrom dify_agent.agent_stub.server.agent_stub_drive import DifyApiAgentStubDriveRequestHandlerfrom dify_agent.agent_stub.server.agent_stub_files import DifyApiAgentStubFileRequestHandlerfrom dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodec@@ -36,6 +38,16 @@ def test_server_settings_reads_shellctl_auth_token_from_env(monkeypatch: pytest.assert settings.shellctl_auth_token == "shell-secret"+def test_server_settings_reads_enterprise_timeouts_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_TIMEOUT", "45")+ monkeypatch.setenv("DIFY_AGENT_ENTERPRISE_SANDBOX_PROXY_TIMEOUT", "90")++ settings = ServerSettings()++ assert settings.enterprise_sandbox_gateway_timeout == 45+ assert settings.enterprise_sandbox_proxy_timeout == 90++def test_server_settings_defaults_shellctl_auth_token_to_none(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -222,3 +234,60 @@ def test_server_settings_create_agent_stub_drive_request_handler_returns_handlerassert timeout.read == 22assert timeout.write == 33assert timeout.pool == 44+++def test_build_shell_provider_returns_none_when_shellctl_entrypoint_is_unset(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.delenv("DIFY_AGENT_SHELLCTL_ENTRYPOINT", raising=False)+ monkeypatch.chdir(tmp_path)++ assert ServerSettings().build_shell_provider() is None+++def test_build_shell_provider_returns_shellctl_provider_when_configured() -> None:+ settings = ServerSettings(+ shell_provider="shellctl",+ shellctl_entrypoint="http://shellctl.example",+ shellctl_auth_token="shell-secret",+ )++ provider = settings.build_shell_provider()++ assert isinstance(provider, ShellctlProvider)+ assert provider.entrypoint == "http://shellctl.example"+ assert provider.token == "shell-secret"+++def test_build_shell_provider_returns_enterprise_provider_when_selected() -> None:+ settings = ServerSettings(+ shell_provider="enterprise",+ enterprise_sandbox_gateway_endpoint="https://gateway.example",+ enterprise_sandbox_gateway_auth_token="gateway-secret",+ enterprise_sandbox_gateway_timeout=45,+ enterprise_sandbox_proxy_timeout=90,+ )++ provider = settings.build_shell_provider()++ assert isinstance(provider, EnterpriseShellProvider)+ assert provider.gateway_endpoint == "https://gateway.example"+ assert provider.auth_token == "gateway-secret"+ assert provider.gateway_timeout == 45+ assert provider.proxy_timeout == 90+++def test_build_shell_provider_returns_none_when_enterprise_endpoint_is_unset(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.delenv("DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_ENDPOINT", raising=False)+ monkeypatch.chdir(tmp_path)++ assert ServerSettings(shell_provider="enterprise").build_shell_provider() is None+++def test_build_shell_provider_rejects_blank_shellctl_entrypoint() -> None:+ with pytest.raises(ValidationError, match="shellctl_entrypoint is required"):+ _ = ServerSettings(shell_provider="shellctl", shellctl_entrypoint=" ").build_shell_provider()