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
refactor: shell provider protocol (#38077)
Yunlu Wen7a111c22260b
diff --git a/dify-agent/src/dify_agent/adapters/shell/__init__.py b/dify-agent/src/dify_agent/adapters/shell/__init__.pynew file mode 100644index 00000000000..e87bb39feb7--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/__init__.py@@ -0,0 +1,41 @@+"""Provider-agnostic shell provisioning/execution adapter for the Dify agent.++The boundary protocols live in ``protocols``; the default shellctl backend in+``shellctl``; and env-var-driven provider selection in ``config``/``factory``.+``create_shell_provisioner`` is the recommended entry point for callers.+"""++from dify_agent.adapters.shell.config import DEFAULT_SHELL_PROVIDER, ShellAdapterSettings+from dify_agent.adapters.shell.factory import create_shell_provisioner+from dify_agent.adapters.shell.protocols import (+ ShellEnvironmentDescriptor,+ ShellExecutionResult,+ ShellExecutorProtocol,+ ShellFileTransferProtocol,+ ShellHandle,+ ShellProvisionProtocol,+)+from dify_agent.adapters.shell.shellctl import (+ ShellctlEnvironmentDescriptor,+ ShellctlProvisioner,+ ShellFileTransferError,+ ShellProvisionError,+ create_default_shellctl_client_factory,+)++__all__ = [+ "DEFAULT_SHELL_PROVIDER",+ "ShellAdapterSettings",+ "ShellEnvironmentDescriptor",+ "ShellExecutionResult",+ "ShellExecutorProtocol",+ "ShellFileTransferError",+ "ShellFileTransferProtocol",+ "ShellHandle",+ "ShellProvisionError",+ "ShellProvisionProtocol",+ "ShellctlEnvironmentDescriptor",+ "ShellctlProvisioner",+ "create_default_shellctl_client_factory",+ "create_shell_provisioner",+]diff --git a/dify-agent/src/dify_agent/adapters/shell/config.py b/dify-agent/src/dify_agent/adapters/shell/config.pynew file mode 100644index 00000000000..d2bd96ae348--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/config.py@@ -0,0 +1,29 @@+from typing import ClassVar++from pydantic_settings import BaseSettings, SettingsConfigDict++DEFAULT_SHELL_PROVIDER = "shellctl"+++class ShellAdapterSettings(BaseSettings):+ """Env-backed settings used to construct a shell provisioner.++ ``shellctl_auth_token`` defaults to ``None``; the factory forwards an empty+ string to the shellctl client so it does not fall back to ambient process+ credentials. Deployments that enable shellctl bearer auth must set+ ``DIFY_AGENT_SHELLCTL_AUTH_TOKEN`` explicitly.+ """++ shell_provider: str = DEFAULT_SHELL_PROVIDER+ shellctl_entrypoint: str | None = None+ shellctl_auth_token: str | None = None++ model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(+ env_prefix="DIFY_AGENT_",+ env_file=(".env", "dify-agent/.env"),+ extra="ignore",+ populate_by_name=True,+ )+++__all__ = ["DEFAULT_SHELL_PROVIDER", "ShellAdapterSettings"]diff --git a/dify-agent/src/dify_agent/adapters/shell/factory.py b/dify-agent/src/dify_agent/adapters/shell/factory.pynew file mode 100644index 00000000000..4de892affc8--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/factory.py@@ -0,0 +1,36 @@+from dify_agent.adapters.shell.config import ShellAdapterSettings+from dify_agent.adapters.shell.protocols import ShellProvisionProtocol+from dify_agent.adapters.shell.shellctl import (+ ShellctlEnvironmentDescriptor,+ ShellctlProvisioner,+ create_default_shellctl_client_factory,+)+++def create_shell_provisioner(+ settings: ShellAdapterSettings | None = None,+) -> ShellProvisionProtocol[ShellctlEnvironmentDescriptor]:+ """Return the shell provisioner selected by ``DIFY_AGENT_SHELL_PROVIDER``.++ Raises:+ ValueError: if the provider name is unknown, or if the ``shellctl``+ provider is selected without a non-empty ``DIFY_AGENT_SHELLCTL_ENTRYPOINT``.+ """+ resolved = settings or ShellAdapterSettings()+ provider = resolved.shell_provider.strip().lower()+ match provider:+ case "shellctl":+ entrypoint = (resolved.shellctl_entrypoint or "").strip()+ if not entrypoint:+ raise ValueError("DIFY_AGENT_SHELLCTL_ENTRYPOINT is required for the 'shellctl' shell provider.")+ return ShellctlProvisioner(+ client_factory=create_default_shellctl_client_factory(+ entrypoint=entrypoint,+ token=resolved.shellctl_auth_token or "",+ ),+ )+ case _:+ raise ValueError(f"Unknown shell provider: {resolved.shell_provider!r}.")+++__all__ = ["create_shell_provisioner"]diff --git a/dify-agent/src/dify_agent/adapters/shell/protocols.py b/dify-agent/src/dify_agent/adapters/shell/protocols.pynew file mode 100644index 00000000000..147441ccb7a--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/protocols.py@@ -0,0 +1,128 @@+from typing import Protocol, TypeVar++from pydantic import BaseModel, ConfigDict, model_validator+from typing_extensions import Self+++class ShellEnvironmentDescriptor(BaseModel):+ """Minimal, serializable seed used to re-derive a provisioned environment.++ Holds only the provider-agnostic identity needed to reattach to an existing+ shell environment across a snapshot/resume cycle — never live resources+ (clients, handles, executors). Callers persist this in their snapshot and+ pass it back to ``ShellProvisionProtocol.reattach`` to reconstruct an+ equivalent ``ShellHandle`` without allocating a new environment.++ Each provider defines its own concrete subclass carrying the fields it needs+ to reattach (e.g. workspace path + session id for shellctl). Validation runs+ at instantiation time via Pydantic so a malicious or corrupt snapshot cannot+ escape the workspace root or inject shell syntax into lifecycle commands,+ even if a future caller uses the provider directly.+ """++ model_config = ConfigDict(extra="forbid", frozen=True)++ @model_validator(mode="after")+ def _run_validate(self) -> Self:+ self.validate()+ return self++ def validate(self) -> None:+ """validate the correctness of the object.++ Advanced validations that requires remote procedure calls,+ for example access control, quota checks, should be implemented in+ provision and reattach.++ """+ raise NotImplementedError+++DescriptorT = TypeVar("DescriptorT", bound=ShellEnvironmentDescriptor)+++class ShellExecutionResult(Protocol):+ """Completed shell command result.++ ``stdout``/``stderr``/``exit_code`` are reserved fields. Backends that+ cannot distinguish a stream return an empty string for it, and return+ ``None`` from ``exit_code()`` when no exit status is available.+ """++ def stdout(self) -> str: ...++ def stderr(self) -> str: ...++ def exit_code(self) -> int | None: ...++ def truncated(self) -> bool: ...+++class ShellExecutorProtocol(Protocol):+ """Runs commands inside an already-provisioned shell environment.++ ``execute`` drains the command to completion before returning — there is no+ separate ``wait`` step. This suits the current server-side callers (sandbox+ file helpers, workspace bootstrap) that always run a script to completion.++ If a future use case needs to start a command, interact with its stdin, or+ interrupt it before completion, split this protocol into ``execute`` →+ ``ShellExecutionHandle`` plus ``wait`` / ``input`` / ``interrupt`` optional+ capabilities, mirroring the shape that was prototyped here before+ simplification.+ """++ async def execute(+ self,+ command: str,+ *,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ ) -> ShellExecutionResult: ...+++class ShellFileTransferProtocol(Protocol):+ """Moves file bytes between the caller and a provisioned shell environment.++ ``remote_path`` is interpreted by the backend relative to the provisioned+ environment (for the shellctl backend, the session workspace). Higher-level+ Dify/skill transfers are layered on top of this primitive, not implemented+ here. Implementations raise on transfer failure (missing path, decode error,+ or a non-zero transfer command).+ """++ async def upload(self, *, content: bytes, remote_path: str) -> None: ...++ async def download(self, *, remote_path: str) -> bytes: ...+++# pyrefly: ignore [variance-mismatch]+# intended to be invariant+class ShellHandle(Protocol[DescriptorT]):+ """Live reference to one provisioned shell environment.++ The handle itself is not serialized. ``descriptor()`` returns the minimal+ seed needed to reconstruct an equivalent handle after a snapshot/resume.+ """++ def descriptor(self) -> DescriptorT: ...++ async def get_executor(self) -> ShellExecutorProtocol: ...++ async def get_file_transfer(self) -> ShellFileTransferProtocol: ...+++class ShellProvisionProtocol(Protocol[DescriptorT]):+ """Creates, reattaches to, and destroys shell environments.++ ``provision`` allocates a fresh environment; ``reattach`` rebuilds a live+ handle for an environment that already exists (from a persisted descriptor)+ without allocating a new one, so resumed runs can keep executing and+ eventually clean up. ``destroy`` tears an environment down.+ """++ async def provision(self) -> ShellHandle[DescriptorT]: ...++ async def reattach(self, descriptor: DescriptorT) -> ShellHandle[DescriptorT]: ...++ async def destroy(self, handle: ShellHandle[DescriptorT]) -> None: ...diff --git a/dify-agent/src/dify_agent/adapters/shell/shellctl.py b/dify-agent/src/dify_agent/adapters/shell/shellctl.pynew file mode 100644index 00000000000..c1f4e786284--- /dev/null+++ b/dify-agent/src/dify_agent/adapters/shell/shellctl.py@@ -0,0 +1,486 @@+from __future__ import annotations++import base64+import binascii+import logging+import re+import secrets+from collections.abc import Callable+from dataclasses import dataclass+from typing import Protocol++from dify_agent.adapters.shell.protocols import ShellEnvironmentDescriptor, ShellHandle++logger = logging.getLogger(__name__)++_WORKSPACE_ROOT = "~/workspace"+_DEFAULT_TIMEOUT_SECONDS = 30.0+_SESSION_ID_PATTERN = re.compile(r"[0-9a-f]{7,16}")+# Drains at most this many shellctl output windows per wait so a stuck or+# pathologically chatty job cannot loop forever inside one wait() call.+_MAX_OUTPUT_WINDOWS = 64+_DEFAULT_TERMINATE_GRACE_SECONDS = 10.0+_FILE_TRANSFER_TIMEOUT_SECONDS = 60.0+# Sentinels frame base64 download payloads so prompt/tmux noise around the+# shellctl merged output stream can be stripped before decoding.+_TRANSFER_BEGIN = "<<<DIFY_SHELL_FILE_BEGIN>>>"+_TRANSFER_END = "<<<DIFY_SHELL_FILE_END>>>"+_DOWNLOAD_MISSING_EXIT_CODE = 66+++class ShellProvisionError(RuntimeError):+ """Raised when a shell environment cannot be provisioned."""+++class ShellFileTransferError(RuntimeError):+ """Raised when a file cannot be uploaded to or downloaded from the workspace."""+++class ShellctlEnvironmentDescriptor(ShellEnvironmentDescriptor):+ """Shellctl-specific descriptor carrying the workspace path and session id."""++ workspace_cwd: str+ session_id: str++ def validate(self) -> None:+ if not _SESSION_ID_PATTERN.fullmatch(self.session_id):+ raise ValueError(f"Invalid session_id in reattach descriptor: {self.session_id!r}.")+ expected_workspace = f"{_WORKSPACE_ROOT}/{self.session_id}"+ if self.workspace_cwd != expected_workspace:+ raise ValueError(+ f"workspace_cwd must equal {expected_workspace!r} for session_id {self.session_id!r}, "+ f"got {self.workspace_cwd!r}."+ )+++class ShellctlJobResult(Protocol):+ """Structural shape of one shellctl job result the adapter relies on.++ Mirrors the fields the adapter reads from ``shell_session_manager`` job+ results without importing the concrete type, so the merged output stream,+ paging offset, completion flag, and exit status stay duck-typed.+ """++ job_id: str+ done: bool+ output: str+ offset: int+ truncated: bool+ exit_code: int | None+++class ShellctlJobStatus(Protocol):+ """Structural shape of one shellctl status-only result (no output stream).++ Returned by ``terminate``; carries completion and exit status plus the+ latest paging offset so the adapter can drain any remaining output.+ """++ job_id: str+ done: bool+ offset: int+ exit_code: int | None+++class ShellctlClientProtocol(Protocol):+ """Boundary the shellctl adapter needs from a shell-session-manager client."""++ async def run(+ self,+ script: str,+ *,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ timeout: float = _DEFAULT_TIMEOUT_SECONDS,+ ) -> ShellctlJobResult: ...++ async def wait(+ self,+ job_id: str,+ *,+ offset: int,+ timeout: float = _DEFAULT_TIMEOUT_SECONDS,+ ) -> ShellctlJobResult: ...++ async def input(+ self,+ job_id: str,+ text: str,+ *,+ offset: int,+ timeout: float = _DEFAULT_TIMEOUT_SECONDS,+ ) -> ShellctlJobResult: ...++ async def terminate(+ self,+ job_id: str,+ grace_seconds: float = _DEFAULT_TERMINATE_GRACE_SECONDS,+ ) -> ShellctlJobStatus: ...++ async def delete(self, job_id: str, *, force: bool = False) -> object: ...++ async def close(self) -> None: ...+++type ShellctlClientFactory = Callable[[], ShellctlClientProtocol]+++class ShellctlExecutionResult:+ """Completed shellctl command result.++ shellctl merges stderr into a single output stream, so ``stderr()`` is+ always empty and the merged stream is reported as ``stdout()``.+ """++ _stdout: str+ _stderr: str+ _exit_code: int | None+ _truncated: bool++ def __init__(+ self,+ *,+ stdout: str,+ stderr: str = "",+ exit_code: int | None,+ truncated: bool = False,+ ) -> None:+ self._stdout = stdout+ self._stderr = stderr+ self._exit_code = exit_code+ self._truncated = truncated++ def stdout(self) -> str:+ return self._stdout++ def stderr(self) -> str:+ return self._stderr++ def exit_code(self) -> int | None:+ return self._exit_code++ def truncated(self) -> bool:+ """Whether the returned ``stdout`` may be incomplete.++ ``True`` means shellctl still reported more output past what was+ captured when draining stopped (its per-window ``truncated`` flag on the+ final window, e.g. the output-window cap was hit). Callers that need the+ command's *entire* output must treat a truncated result as a failure or+ re-read, rather than trusting ``stdout()`` as complete.+ """+ return self._truncated+++@dataclass(slots=True)+class ShellctlExecutor:+ """Runs commands in one provisioned shellctl workspace.++ Conforms structurally to ``ShellExecutorProtocol``. ``execute`` drains the+ command to completion (accumulating shellctl's paged output windows) and+ best-effort deletes the finished job before returning. The executor is+ single-environment and is not safe to share across workspaces.+ """++ client: ShellctlClientProtocol+ workspace_cwd: str+ timeout: float = _DEFAULT_TIMEOUT_SECONDS++ async def execute(+ self,+ command: str,+ *,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ ) -> ShellctlExecutionResult:+ result = await self.client.run(+ command,+ cwd=cwd if cwd is not None else self.workspace_cwd,+ env=env,+ timeout=self.timeout,+ )+ output_parts = [result.output]+ done = result.done+ truncated = result.truncated+ offset = result.offset+ exit_code = result.exit_code+ job_id = result.job_id+ windows = 1+ while (not done or truncated) and windows < _MAX_OUTPUT_WINDOWS:+ result = await self.client.wait(job_id, offset=offset, timeout=self.timeout)+ output_parts.append(result.output)+ done = result.done+ truncated = result.truncated+ offset = result.offset+ exit_code = result.exit_code+ windows += 1+ if done:+ await _delete_job_best_effort(self.client, job_id)+ return ShellctlExecutionResult(+ stdout="".join(output_parts),+ exit_code=exit_code,+ truncated=truncated,+ )+++@dataclass(slots=True)+class ShellctlFileTransfer:+ """Moves file bytes in and out of one provisioned shellctl workspace.++ Conforms structurally to ``ShellFileTransferProtocol``. Transfers run as+ workspace-scoped shellctl jobs over the merged text channel: uploads embed+ base64 in the command and pipe it through ``base64 -d``; downloads emit the+ file's base64 framed by sentinels so prompt/tmux noise can be stripped+ before decoding. Because the encoded payload is embedded in the upload+ command, very large files can exceed the shell argument limit; this+ primitive targets ordinary control-plane file sizes, not bulk binary+ transfer.+ """++ client: ShellctlClientProtocol+ workspace_cwd: str+ timeout: float = _FILE_TRANSFER_TIMEOUT_SECONDS++ async def upload(self, *, content: bytes, remote_path: str) -> None:+ encoded = base64.b64encode(content).decode("ascii")+ completed = await _run_to_completion(+ self.client,+ _upload_script(remote_path=remote_path, encoded=encoded),+ cwd=self.workspace_cwd,+ timeout=self.timeout,+ )+ if completed.exit_code != 0:+ raise ShellFileTransferError(+ f"Failed to upload to {remote_path!r}: exit_code={completed.exit_code}, "+ f"output={_output_tail(completed.output)!r}"+ )++ async def download(self, *, remote_path: str) -> bytes:+ completed = await _run_to_completion(+ self.client,+ _download_script(remote_path=remote_path),+ cwd=self.workspace_cwd,+ timeout=self.timeout,+ )+ if completed.exit_code == _DOWNLOAD_MISSING_EXIT_CODE:+ raise ShellFileTransferError(f"File not found in workspace: {remote_path!r}.")+ if completed.exit_code != 0:+ raise ShellFileTransferError(+ f"Failed to download {remote_path!r}: exit_code={completed.exit_code}, "+ f"output={_output_tail(completed.output)!r}"+ )+ framed = _extract_framed_payload(completed.output)+ try:+ return base64.b64decode("".join(framed.split()), validate=True)+ except (binascii.Error, ValueError) as exc:+ raise ShellFileTransferError(f"Failed to decode downloaded file {remote_path!r}: {exc}") from exc+++@dataclass(slots=True)+class ShellctlHandle:+ """Live reference to one provisioned shellctl workspace.++ Conforms structurally to ``ShellHandle``. Owns the shellctl ``client`` and+ the allocated ``workspace_cwd`` until the provisioner destroys it.+ ``get_executor`` returns a fresh executor bound to this workspace each call.+ """++ client: ShellctlClientProtocol+ workspace_cwd: str+ session_id: str++ def descriptor(self) -> ShellctlEnvironmentDescriptor:+ return ShellctlEnvironmentDescriptor(workspace_cwd=self.workspace_cwd, session_id=self.session_id)++ async def get_executor(self) -> ShellctlExecutor:+ return ShellctlExecutor(client=self.client, workspace_cwd=self.workspace_cwd)++ async def get_file_transfer(self) -> ShellctlFileTransfer:+ return ShellctlFileTransfer(client=self.client, workspace_cwd=self.workspace_cwd)+++@dataclass(slots=True)+class ShellctlProvisioner:+ """Provisions isolated shellctl workspaces, one client per environment.++ Conforms structurally to ``ShellProvisionProtocol``.+ """++ client_factory: ShellctlClientFactory+ timeout: float = _DEFAULT_TIMEOUT_SECONDS++ async def provision(self) -> ShellctlHandle:+ client = self.client_factory()+ session_id = _generate_session_id()+ workspace_cwd = f"{_WORKSPACE_ROOT}/{session_id}"+ try:+ completed = await _run_to_completion(client, _mkdir_script(session_id), cwd=None, timeout=self.timeout)+ except BaseException:+ await client.close()+ raise+ if completed.exit_code != 0:+ await client.close()+ raise ShellProvisionError(+ f"Failed to create shell workspace {workspace_cwd}: mkdir exited with code {completed.exit_code}."+ )+ return ShellctlHandle(client=client, workspace_cwd=workspace_cwd, session_id=session_id)++ async def reattach(self, descriptor: ShellctlEnvironmentDescriptor) -> ShellctlHandle:+ """Rebuild a live handle for an existing workspace without re-allocating it.++ Opens a fresh shellctl client and points it at the workspace recorded in+ ``descriptor``. No ``mkdir`` is issued: the workspace is assumed to still+ exist from the original ``provision``. Used on snapshot resume so a run+ can keep executing in and eventually clean up its prior workspace.+ """+ client = self.client_factory()+ return ShellctlHandle(+ client=client,+ workspace_cwd=descriptor.workspace_cwd,+ session_id=descriptor.session_id,+ )++ async def destroy(self, handle: ShellHandle[ShellctlEnvironmentDescriptor]) -> None:+ if not isinstance(handle, ShellctlHandle):+ raise TypeError("ShellctlProvisioner can only destroy handles it provisioned.")+ try:+ completed = await _run_to_completion(+ handle.client, _cleanup_script(handle.session_id), cwd=None, timeout=self.timeout+ )+ if completed.exit_code != 0:+ logger.warning(+ "Shell workspace cleanup for session %s exited with code %s.",+ handle.session_id,+ completed.exit_code,+ )+ except (RuntimeError, ValueError) as exc:+ logger.warning("Failed to remove shell workspace for session %s: %s", handle.session_id, exc)+ finally:+ await handle.client.close()+++def create_default_shellctl_client_factory(*, entrypoint: str, token: str) -> ShellctlClientFactory:+ """Return a factory that builds a real shell-session-manager shellctl client.++ The concrete client is imported lazily so importing this module does not+ require the private ``shell-session-manager`` package. An explicit empty+ ``token`` is forwarded as-is to avoid the client falling back to ambient+ process credentials.+ """++ def factory() -> ShellctlClientProtocol:+ from shell_session_manager.shellctl.client import ShellctlClient++ return ShellctlClient(entrypoint, token=token)++ return factory+++@dataclass(slots=True)+class _CompletedJob:+ """Drained result of one internal shellctl job: merged output plus exit code."""++ output: str+ exit_code: int | None+++async def _run_to_completion(+ client: ShellctlClientProtocol,+ script: str,+ *,+ cwd: str | None,+ timeout: float,+) -> _CompletedJob:+ """Run one internal lifecycle script to completion, returning output and exit code."""+ result = await client.run(script, cwd=cwd, env=None, timeout=timeout)+ output_parts = [result.output]+ done = result.done+ truncated = result.truncated+ offset = result.offset+ exit_code = result.exit_code+ job_id = result.job_id+ windows = 1+ while (not done or truncated) and windows < _MAX_OUTPUT_WINDOWS:+ result = await client.wait(job_id, offset=offset, timeout=timeout)+ output_parts.append(result.output)+ done = result.done+ truncated = result.truncated+ offset = result.offset+ exit_code = result.exit_code+ windows += 1+ if done:+ await _delete_job_best_effort(client, job_id)+ return _CompletedJob(output="".join(output_parts), exit_code=exit_code)+++async def _delete_job_best_effort(client: ShellctlClientProtocol, job_id: str) -> None:+ """Force-delete one shellctl job, never failing the caller on cleanup errors."""+ try:+ _ = await client.delete(job_id, force=True)+ except Exception as exc: # noqa: BLE001 - best-effort teardown must not surface cleanup errors+ logger.warning("Failed to delete shellctl job %s: %s", job_id, exc)+++def _generate_session_id() -> str:+ """Return a shell-safe random session id used as the workspace directory name."""+ return secrets.token_hex(8)+++def _mkdir_script(session_id: str) -> str:+ return f'mkdir -p "$HOME/workspace/{session_id}"'+++def _cleanup_script(session_id: str) -> str:+ return f'rm -rf -- "$HOME/workspace/{session_id}"'+++def _upload_script(*, remote_path: str, encoded: str) -> str:+ """Return a script that recreates a file from embedded base64 in the workspace."""+ quoted = _shquote(remote_path)+ return f"mkdir -p \"$(dirname -- {quoted})\" && printf %s '{encoded}' | base64 -d > {quoted}"+++def _download_script(*, remote_path: str) -> str:+ """Return a script that emits a file's base64 between transfer sentinels."""+ quoted = _shquote(remote_path)+ return (+ f"if [ ! -f {quoted} ]; then exit {_DOWNLOAD_MISSING_EXIT_CODE}; fi; "+ f"printf %s {_shquote(_TRANSFER_BEGIN)}; "+ f'base64 < {quoted} | tr -d "\\n"; '+ f"printf %s {_shquote(_TRANSFER_END)}"+ )+++def _extract_framed_payload(output: str) -> str:+ """Return the base64 text framed by the transfer sentinels in shellctl output."""+ begin = output.find(_TRANSFER_BEGIN)+ end = output.find(_TRANSFER_END, begin + len(_TRANSFER_BEGIN)) if begin != -1 else -1+ if begin == -1 or end == -1:+ raise ShellFileTransferError("download command returned no framed payload")+ return output[begin + len(_TRANSFER_BEGIN) : end]+++def _shquote(value: str) -> str:+ """Single-quote a value for POSIX shells, escaping embedded single quotes."""+ return "'" + value.replace("'", "'\\''") + "'"+++def _output_tail(output: str, *, limit: int = 500) -> str:+ """Return the trailing slice of command output for compact error messages."""+ return output[-limit:]+++__all__ = [+ "ShellFileTransferError",+ "ShellProvisionError",+ "ShellctlClientFactory",+ "ShellctlClientProtocol",+ "ShellctlEnvironmentDescriptor",+ "ShellctlExecutionResult",+ "ShellctlExecutor",+ "ShellctlFileTransfer",+ "ShellctlHandle",+ "ShellctlJobResult",+ "ShellctlJobStatus",+ "ShellctlProvisioner",+ "create_default_shellctl_client_factory",+]diff --git a/dify-agent/src/dify_agent/layers/shell/layer.py b/dify-agent/src/dify_agent/layers/shell/layer.pyindex 5efb072ace9..b54e0bb4d26 100644--- a/dify-agent/src/dify_agent/layers/shell/layer.py+++ b/dify-agent/src/dify_agent/layers/shell/layer.py@@ -1,28 +1,20 @@-"""Shellctl-backed Dify shell layer.+"""Shell layer backed by the shell adapter provisioner/executor mechanism.``DifyShellLayer`` is a stateful pydantic-ai tool layer that exposes exactly``shell_run``, ``shell_wait``, ``shell_input``, and ``shell_interrupt``. Thelayer persists only JSON-safe shell session state in ``runtime_state`` and keeps-its live shellctl HTTP client on the layer instance only while+its live ``ShellctlHandle`` on the layer instance only while``resource_context()`` is active. Agenton enters that resource scope before``on_context_create`` or ``on_context_resume`` and exits it after``on_context_suspend`` or ``on_context_delete``, so business hooks and shell-tools can rely on a live client without ever serializing it into snapshots.--The runtime state tracks shellctl job ids for both user-visible shell jobs and-internal lifecycle jobs such as workspace mkdir/cleanup commands. Those internal-jobs are intentionally not deleted ad hoc; shellctl job-state deletion is-centralized in ``on_context_delete`` so one lifecycle hook owns exit-time-cleanup for successful create/resume flows. If ``on_context_create`` or a later-side-effecting ``on_context_resume`` attempt fails after issuing shellctl jobs,-Agenton still exits ``resource_context()`` but never transitions the layer to-``ACTIVE``. In that failed-enter path, normal suspend/delete hooks do not run,-so the enter hook itself must perform best-effort business compensation before-re-raising the failure. Agent Soul shell env is injected into user-visible-commands and CLI bootstrap commands without persisting a workspace env file.-Agent Stub env injection uses shellctl's native per-run ``env`` argument for-user-visible ``shell.run`` and for trusted server-owned fixed scripts executed-through ``run_remote_script()``.+tools can rely on live resources without ever serializing them into snapshots.++The layer delegates workspace lifecycle to ``ShellProvisionProtocol``:+``provision`` allocates a fresh workspace, ``reattach`` rebuilds a live handle+for an existing workspace from a serialized descriptor, and ``destroy`` tears+the workspace down. User-facing shell tools call the shellctl client obtained+from the handle directly; trusted server-owned scripts go through+``ShellctlExecutor`` which auto-cleans completed jobs."""from __future__ import annotations@@ -32,24 +24,23 @@ from contextlib import asynccontextmanagerimport jsonimport loggingimport re-import secrets-import timefrom dataclasses import dataclass-from typing import ClassVar, NotRequired, Protocol, TypedDict+from typing import ClassVar, NotRequired, Protocol, TypedDict, castfrom pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, field_validator, model_validatorfrom pydantic_ai import Tool-from shell_session_manager.shellctl.client import ShellctlClient, ShellctlClientError+from shell_session_manager.shellctl.client import ShellctlClientErrorfrom shell_session_manager.shellctl.shared import (DEFAULT_TERMINATE_GRACE_SECONDS,DEFAULT_TIMEOUT_SECONDS,- DeleteJobResponse,JobResult,JobStatusView,)from typing_extensions import Self, overridefrom agenton.layers import LayerDeps, PydanticAILayer, PydanticAIPrompt, PydanticAITool+from dify_agent.adapters.shell.protocols import ShellProvisionProtocol+from dify_agent.adapters.shell.shellctl import ShellctlEnvironmentDescriptor, ShellctlExecutor, ShellctlHandlefrom dify_agent.agent_stub.server.shell_agent_stub_env import ShellAgentStubTokenFactory, build_shell_agent_stub_envfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.shell.configs import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig@@ -58,12 +49,6 @@ from dify_agent.layers.shell.configs import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLlogger = logging.getLogger(__name__)_WORKSPACE_ROOT = "~/workspace"-_WORKSPACE_COLLISION_EXIT_CODE = 17-_SESSION_TIME_HEX_MASK = 0xFFFFF-_SESSION_RANDOM_HEX_LENGTH = 2-_SESSION_ID_ATTEMPT_LIMIT = 256-_SESSION_ID_PATTERN = re.compile(r"^[0-9a-f]{7}$")-_REMOTE_COMMAND_MAX_OUTPUT_WINDOWS = 64_SHELL_LAYER_PREFIX_PROMPT = """You have access to a shell layer. It provides four tools:1. shell_run@@ -221,7 +206,7 @@ class ShellctlClientProtocol(Protocol):*,force: bool = False,grace_seconds: float | None = None,- ) -> DeleteJobResponse: ...+ ) -> object: ...async def close(self) -> None: ...@@ -237,12 +222,9 @@ class DifyShellRuntimeState(BaseModel):created before suspension. Callers should replace the stored list/dict valuesrather than mutating them in place so Pydantic assignment validation keepsguarding the serialized state. Hydrated public snapshots must keep- ``session_id`` in the proposal's safe lowercase-hex format and must keep- ``workspace_cwd`` exactly aligned with ``~/workspace/<session_id>`` so resume- and delete paths cannot escape the isolated workspace root or inject shell- syntax into lifecycle commands. Shellctl job ids remain opaque strings here;- the layer only enforces uniqueness plus the invariant that any stored offset- entry must belong to a tracked job id in the same runtime state.+ ``session_id`` and ``workspace_cwd`` consistent with the descriptor returned+ by the shell provisioner, so resume and delete paths cannot escape the+ isolated workspace root or inject shell syntax into lifecycle commands."""session_id: str | None = None@@ -255,10 +237,12 @@ class DifyShellRuntimeState(BaseModel):@field_validator("session_id")@classmethoddef validate_session_id(cls, value: str | None) -> str | None:- """Accept only the short lowercase-hex session ids defined by the proposal."""+ """Reject session ids that could escape the workspace root or inject shell syntax."""if value is None:return value- return _validated_session_id(value)+ if not re.fullmatch(r"[0-9a-f]{7,16}", value):+ raise ValueError("session_id must be 7 to 16 lowercase hex characters (got an invalid value).")+ return value@field_validator("job_ids")@classmethod@@ -286,24 +270,28 @@ class DifyShellRuntimeState(BaseModel):@dataclass(frozen=True, slots=True)class RemoteCommandResult:- """Completed remote sandbox command returned to server-owned callers."""+ """Completed remote sandbox command returned to server-owned callers.++ Only fields with live consumers are kept: ``output``/``exit_code`` (read by+ every caller), ``truncated`` (drive pull treats a truncated result as a+ failure because it needs the command's full output), and ``status`` (used in+ drive's human-readable error message). shellctl paging details such as the+ job id, completion flag, byte offset, and output path are intentionally not+ surfaced here, since no caller reads them.+ """- job_id: strstatus: str- done: boolexit_code: int | Noneoutput: str- offset: inttruncated: bool- output_path: str@dataclass(slots=True)class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerConfig, DifyShellRuntimeState]):- """Shell tool layer backed by a live shellctl client while active.+ """Shell tool layer backed by the shell provisioner/executor mechanism.- The mutable serializable state lives in ``runtime_state``; the live client is- intentionally kept off-snapshot in ``_shellctl_client``. Tool methods update+ The mutable serializable state lives in ``runtime_state``; the live+ ``ShellctlHandle`` is intentionally kept off-snapshot. Tool methods updatetracked job ids and output offsets after every successful shellctl response solater ``shell_wait``/``shell_input`` calls can resume from the last knownoffset without exposing offsets as model-controlled inputs.@@ -312,39 +300,35 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCtype_id: ClassVar[str | None] = DIFY_SHELL_LAYER_TYPE_IDconfig: DifyShellLayerConfig- shellctl_entrypoint: str- shellctl_client_factory: ShellctlClientFactory+ shell_provisioner: ShellProvisionProtocol[ShellctlEnvironmentDescriptor]agent_stub_api_base_url: str | None = Noneagent_stub_token_factory: ShellAgentStubTokenFactory | None = None- _shellctl_client: ShellctlClientProtocol | None = None+ _shell_handle: ShellctlHandle | None = None@classmethod@overridedef from_config(cls, config: DifyShellLayerConfig) -> Self:- """Reject construction that omits server-injected shellctl settings."""+ """Reject construction that omits the shell provisioner."""del config- raise TypeError("DifyShellLayer requires server-side shellctl settings and must use a provider factory.")+ raise TypeError("DifyShellLayer requires a shell provisioner and must use a provider factory.")@classmethoddef from_config_with_settings(cls,config: DifyShellLayerConfig,*,- shellctl_entrypoint: str | None,- shellctl_client_factory: ShellctlClientFactory,+ shell_provisioner: ShellProvisionProtocol[ShellctlEnvironmentDescriptor] | None,agent_stub_api_base_url: str | None = None,agent_stub_token_factory: ShellAgentStubTokenFactory | None = None,) -> Self:- """Create the layer from public config plus server-only shell settings."""- normalized_entrypoint = (shellctl_entrypoint or "").strip()- if not normalized_entrypoint:+ """Create the layer from public config plus shell provisioner settings."""+ if shell_provisioner is None:raise ValueError(- "DifyShellLayer requires a non-empty DIFY_AGENT_SHELLCTL_ENTRYPOINT when the 'dify.shell' layer is used."+ "DifyShellLayer requires a non-null shell provisioner when the 'dify.shell' layer is used.")layer = cls(config=config,- shellctl_entrypoint=normalized_entrypoint,- shellctl_client_factory=shellctl_client_factory,+ shell_provisioner=shell_provisioner,agent_stub_api_base_url=agent_stub_api_base_url,agent_stub_token_factory=agent_stub_token_factory,)@@ -369,107 +353,90 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC@override@asynccontextmanagerasync def resource_context(self) -> AsyncGenerator[None]:- """Hold one live shellctl client for one active Agenton layer scope.+ """Hold the live shell handle scope.- The shellctl client is a non-serializable live resource, so Agenton owns- only the timing of this scope, not the client itself. Business hooks and- tools should call ``_require_client()`` to ensure they are running inside- an active resource scope.+ The actual handle is set in ``on_context_create`` /+ ``on_context_resume``. This scope ensures cleanup if a lifecycle hook+ fails before the handle is set."""- if self._shellctl_client is not None:- raise RuntimeError("DifyShellLayer resource_context() is already active for this layer instance.")-- client = self.shellctl_client_factory(self.shellctl_entrypoint)- self._shellctl_client = clienttry:yieldfinally:- self._shellctl_client = None- await client.close()+ self._shell_handle = None@overrideasync def on_context_create(self) -> None:- """Allocate a new workspace session using the active live shellctl client.-- If workspace setup partially succeeds and this hook later raises, the- layer never becomes ``ACTIVE``. In that path Agenton still exits- ``resource_context()``, but ``on_context_delete()`` will not run, so this- hook must clean up any tracked shellctl job artifacts before re-raising.+ """Provision a new workspace session using the shell provisioner.++ The provisioner allocates the workspace directory and returns a+ ``ShellctlHandle``. The layer then bootstraps the workspace with Agent+ Soul env exports and CLI tool install commands. If workspace setup+ partially succeeds and this hook later raises, the layer never becomes+ ``ACTIVE``. In that path Agenton still exits ``resource_context()``, but+ ``on_context_delete()`` will not run, so this hook must clean up any+ tracked artifacts before re-raising."""try:- _ = self._require_client()- session_id, workspace_cwd = await self._allocate_workspace()- await self._bootstrap_workspace(workspace_cwd)+ handle = cast(ShellctlHandle, await self.shell_provisioner.provision())+ self._shell_handle = handle+ descriptor = handle.descriptor()+ await self._bootstrap_workspace(descriptor.workspace_cwd)except BaseException:await self._cleanup_create_failure()raiseself.runtime_state = DifyShellRuntimeState.model_validate({**self.runtime_state.model_dump(mode="python"),- "session_id": session_id,- "workspace_cwd": workspace_cwd,+ "session_id": descriptor.session_id,+ "workspace_cwd": descriptor.workspace_cwd,})@overrideasync def on_context_resume(self) -> None:- """Resume an existing serialized shell session inside an active resource scope.+ """Reattach to an existing serialized shell session.+ Builds a ``ShellEnvironmentDescriptor`` from the persisted runtime state+ and asks the provisioner to reattach without allocating a new workspace.If a future resume path adds self-heal side effects before raising, thishook must compensate for them itself because failed resume attempts never- transition the slot back to ``ACTIVE`` and therefore do not receive a- normal suspend/delete hook.+ transition the slot back to ``ACTIVE``."""- _ = self._require_client()- _ = self._require_session_identity()+ session_id, workspace_cwd = self._require_session_identity()+ descriptor = ShellctlEnvironmentDescriptor(+ workspace_cwd=workspace_cwd,+ session_id=session_id,+ )+ handle = cast(ShellctlHandle, await self.shell_provisioner.reattach(descriptor))+ self._shell_handle = handle@overrideasync def on_context_suspend(self) -> None:- """Preserve workspace and job state while the live client remains active.+ """Close the live client so it does not leak across snapshot boundaries.- ``resource_context()`` owns client teardown after this hook returns.+ ``reattach`` on the next resume creates a fresh client pointing at the+ same workspace. ``resource_context()`` clears the handle reference after+ this hook returns."""- _ = self._require_client()+ handle = self._shell_handle+ if handle is not None:+ await handle.client.close()@overrideasync def on_context_delete(self) -> None:- """Best-effort cleanup for workspace deletion and tracked shellctl jobs.-- Workspace removal must happen before tracked shellctl job deletion because- the cleanup itself is implemented as an internal shellctl run. That means- deleting job state first would prevent the layer from issuing the- proposal-required ``rm -rf`` cleanup job and then cleaning up that final- job record along with the rest of the session's tracked shellctl state.- ``resource_context()`` closes the live client only after this hook- finishes.- """- _ = self._require_client()+ """Best-effort cleanup for tracked shellctl jobs and workspace deletion.- cleanup_job_id: str | None = None- identity = self._try_session_identity()- if identity is not None:- session_id, _workspace_cwd = identity- try:- cleanup_result = await self._run_internal_job_to_completion(- _workspace_cleanup_script(session_id=session_id),- cwd=None,- )- cleanup_job_id = cleanup_result["job_id"]- if cleanup_result["exit_code"] != 0:- logger.warning(- "Shell workspace cleanup job %s for session %s exited with code %s.",- cleanup_job_id,- session_id,- cleanup_result["exit_code"],- )- except (RuntimeError, ValueError, ShellctlClientError) as exc:- logger.warning("Failed to remove shell workspace for session %s: %s", session_id, exc)-- tracked_job_ids = _deduplicate_preserving_order(- [*self.runtime_state.job_ids, *([cleanup_job_id] if cleanup_job_id is not None else [])]- )- await self._delete_tracked_jobs_best_effort(tracked_job_ids)+ Tracked shellctl jobs are force-deleted on a best-effort basis before the+ handle is destroyed, since job records may outlive the workspace. The+ provisioner's ``destroy`` handles workspace removal and client close.+ """+ handle = self._shell_handle+ if handle is None:+ return+ await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)self._clear_tracked_jobs()+ await self.shell_provisioner.destroy(handle)+ self._shell_handle = Noneasync def _tool_run(self, script: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> ShellRunToolResult:"""Start a new shell job inside the session workspace."""@@ -533,8 +500,10 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC"""Run one trusted server-side script inside the sandbox workspace.The sandbox file service uses this boundary for fixed list/read/upload- helpers. The layer owns output paging, transient shellctl job cleanup,- and optional Agent Stub env injection.+ helpers. Execution, output draining, and transient shellctl job cleanup+ are delegated to ``ShellctlExecutor`` from the shell adapter; the layer+ owns only the optional Agent Stub env injection and the+ ``RemoteCommandResult`` mapping.Unlike model-visible ``shell.run``, this server-owned boundary does notinject Agent Soul shell env. Keeping the user-controlled shell env out@@ -546,28 +515,32 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCenv = self._build_user_shell_run_env()if env is None:raise RuntimeError("Agent Stub environment injection is not available for this shell session.")- return await self._run_remote_job_to_completion(- script,+ handle = self._require_handle()+ executor = ShellctlExecutor(+ client=handle.client, # pyright: ignore[reportArgumentType]+ workspace_cwd=self._require_workspace_cwd(),timeout=timeout,- env=env,+ )+ result = await executor.execute(script, env=env)+ return RemoteCommandResult(+ status="exited" if not result.truncated() else "running",+ exit_code=result.exit_code(),+ output=result.stdout(),+ truncated=result.truncated(),)- async def _allocate_workspace(self) -> tuple[str, str]:- """Allocate a unique ``~/workspace/<session_id>`` directory by mkdir collision checks."""- for _attempt in range(_SESSION_ID_ATTEMPT_LIMIT):- session_id = _generate_session_id()- mkdir_result = await self._run_internal_job_to_completion(- _workspace_mkdir_script(session_id=session_id),- cwd=None,- )- if mkdir_result["exit_code"] == _WORKSPACE_COLLISION_EXIT_CODE:- continue- if mkdir_result["exit_code"] != 0:- raise RuntimeError(- f"Failed to create shell workspace {_workspace_cwd(session_id)}: {mkdir_result['status']} exit_code={mkdir_result['exit_code']}"- )- return session_id, _workspace_cwd(session_id)- raise RuntimeError("Failed to allocate a unique shell workspace session id after 256 attempts.")+ def environment_descriptor(self) -> ShellctlEnvironmentDescriptor:+ """Return the serializable workspace seed for the shell adapter.++ Bridges this layer's ``runtime_state`` to+ ``dify_agent.adapters.shell``: the returned descriptor identifies the+ session workspace so an adapter ``ShellProvisionProtocol.reattach`` can+ rebuild a live handle pointing at it without re-allocating, and without+ re-entering this layer. Raises ``ValueError`` if the session identity is+ missing or inconsistent.+ """+ session_id, workspace_cwd = self._require_session_identity()+ return ShellctlEnvironmentDescriptor(workspace_cwd=workspace_cwd, session_id=session_id)async def _bootstrap_workspace(self, workspace_cwd: str) -> None:"""Apply Agent Soul shell config to the freshly-created workspace."""@@ -581,21 +554,24 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC)async def _cleanup_create_failure(self) -> None:- """Best-effort shellctl job cleanup for create failures before ACTIVE state.+ """Best-effort cleanup for create failures before ACTIVE state.Agenton only calls ``on_context_delete`` for layers that successfully- entered ``ACTIVE``. If ``on_context_create`` fails after issuing one or- more internal shellctl jobs, those tracked job artifacts would otherwise- leak because no later lifecycle hook owns them. ``resource_context()``- still closes the live client for this failed enter attempt after the hook- unwinds.+ entered ``ACTIVE``. If ``on_context_create`` fails after issuing+ internal jobs, those tracked job artifacts would otherwise leak because+ no later lifecycle hook owns them. The provisioner's ``destroy`` handles+ workspace removal and client close."""- if not self.runtime_state.job_ids:+ handle = self._shell_handle+ if handle is None:return- try:- await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)- finally:- self._clear_tracked_jobs()+ if self.runtime_state.job_ids:+ try:+ await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)+ finally:+ self._clear_tracked_jobs()+ await self.shell_provisioner.destroy(handle)+ self._shell_handle = Noneasync def _run_internal_job_to_completion(self,@@ -616,56 +592,18 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCself._track_job_result(result)return _job_result_observation(result)- async def _run_remote_job_to_completion(- self,- script: str,- *,- timeout: float,- env: dict[str, str] | None,- ) -> RemoteCommandResult:- """Run a workspace-scoped script to completion and delete its job state.-- Shellctl's ``truncated`` flag is per output window: it means the caller- should continue from the returned offset. After this helper drains those- windows, only the final window can describe whether output is still- unread, usually because the safety window cap was reached.- """- client = self._require_client()- job_id: str | None = None- try:- result = await client.run(script, cwd=self._require_workspace_cwd(), env=env, timeout=timeout)- job_id = result.job_id- self._track_job_result(result)- output_parts = [result.output]- windows = 1- while (result.truncated or not result.done) and windows < _REMOTE_COMMAND_MAX_OUTPUT_WINDOWS:- result = await client.wait(result.job_id, offset=self._tracked_offset(result.job_id), timeout=timeout)- self._track_job_result(result)- output_parts.append(result.output)- windows += 1- return RemoteCommandResult(- job_id=result.job_id,- status=result.status.value,- done=result.done,- exit_code=result.exit_code,- output="".join(output_parts),- offset=result.offset,- truncated=result.truncated,- output_path=result.output_path,- )- finally:- if job_id is not None:- await self._delete_job_best_effort(job_id)- self._forget_tracked_job(job_id)-- def _require_client(self) -> ShellctlClientProtocol:- """Return the live client or reject tool/lifecycle use without one."""- if self._shellctl_client is None:+ def _require_handle(self) -> ShellctlHandle:+ """Return the live handle or reject tool/lifecycle use without one."""+ if self._shell_handle is None:raise RuntimeError(- "DifyShellLayer requires an active shellctl client inside resource_context(); "+ "DifyShellLayer requires an active shell handle inside resource_context(); "+ "enter the layer through Agenton or wrap direct hook/tool usage in resource_context().")- return self._shellctl_client+ return self._shell_handle++ def _require_client(self) -> ShellctlClientProtocol:+ """Return the live shellctl client from the handle."""+ return cast(ShellctlClientProtocol, self._require_handle().client)def _require_workspace_cwd(self) -> str:"""Return the configured workspace directory for user-facing shell jobs."""@@ -785,15 +723,6 @@ def _shell_layer_prefix_prompt() -> str:return _SHELL_LAYER_PREFIX_PROMPT-def create_shellctl_client_factory(*, token: str) -> ShellctlClientFactory:- """Return the default shellctl client factory used by server-side providers."""-- def factory(entrypoint: str) -> ShellctlClientProtocol:- return ShellctlClient(entrypoint, token=token)-- return factory--def _job_result_observation(result: JobResult) -> ShellJobObservation:return {"job_id": result.job_id,@@ -824,16 +753,8 @@ def _tool_error(message: str, *, job_id: str | None = None) -> ShellToolErrorObsreturn result-def _generate_session_id() -> str:- time_component = int(time.time()) & _SESSION_TIME_HEX_MASK- random_component = secrets.token_hex(1)- if len(random_component) != _SESSION_RANDOM_HEX_LENGTH:- raise RuntimeError("Expected a one-byte random hex suffix for Dify shell session ids.")- return f"{time_component:05x}{random_component}"--def _workspace_cwd(session_id: str) -> str:- return f"{_WORKSPACE_ROOT}/{_validated_session_id(session_id)}"+ return f"{_WORKSPACE_ROOT}/{session_id}"def _workspace_bootstrap_script(config: DifyShellLayerConfig) -> str:@@ -877,41 +798,11 @@ def _wrap_user_script(script: str, config: DifyShellLayerConfig) -> str:return "\n".join([*lines, script])-def _workspace_mkdir_script(*, session_id: str) -> str:- """Return the internal mkdir command used for proposal-defined collision checks.-- The parent ``$HOME/workspace`` directory is created with ``mkdir -p`` so it- can already exist, but the final session directory intentionally uses plain- ``mkdir``. That second call is the collision detector: when the target- already exists, the script maps that case to ``_WORKSPACE_COLLISION_EXIT_CODE``- so ``on_context_create()`` can retry with a different random suffix instead- of silently reusing another session's workspace.- """- safe_session_id = _validated_session_id(session_id)- workspace_dir = f"$HOME/workspace/{safe_session_id}"- return (- 'mkdir -p "$HOME/workspace"; '- f'if mkdir "{workspace_dir}"; then exit 0; fi; '- f'if [ -e "{workspace_dir}" ]; then exit {_WORKSPACE_COLLISION_EXIT_CODE}; fi; '- "exit 1"- )---def _workspace_cleanup_script(*, session_id: str) -> str:- return f'rm -rf -- "$HOME/workspace/{_validated_session_id(session_id)}"'--def _shquote(value: str) -> str:"""Single-quote a value for POSIX shells, escaping embedded single quotes."""return "'" + value.replace("'", "'\\''") + "'"-def _validated_session_id(session_id: str) -> str:- if not _SESSION_ID_PATTERN.fullmatch(session_id):- raise ValueError("session_id must match the 5+2 lowercase hex format '<5 hex><2 hex>'.")- return session_id--def _deduplicate_preserving_order(values: Sequence[str]) -> list[str]:seen: set[str] = set()result: list[str] = []@@ -928,7 +819,5 @@ __all__ = ["DifyShellLayer","DifyShellRuntimeState","RemoteCommandResult",- "ShellctlClientFactory","ShellctlClientProtocol",- "create_shellctl_client_factory",]diff --git a/dify-agent/src/dify_agent/runtime/compositor_factory.py b/dify-agent/src/dify_agent/runtime/compositor_factory.pyindex 610733cff98..1a70d306809 100644--- a/dify-agent/src/dify_agent/runtime/compositor_factory.py+++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py@@ -44,8 +44,10 @@ from dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.knowledge.configs import DifyKnowledgeBaseLayerConfigfrom dify_agent.layers.knowledge.layer import DifyKnowledgeBaseLayerfrom dify_agent.layers.output.output_layer import DifyOutputLayer+from dify_agent.adapters.shell.config import ShellAdapterSettings+from dify_agent.adapters.shell.factory import create_shell_provisionerfrom dify_agent.layers.shell.configs import DifyShellLayerConfig-from dify_agent.layers.shell.layer import DifyShellLayer, create_shellctl_client_factory+from dify_agent.layers.shell.layer import DifyShellLayertype DifyAgentLayerProvider = LayerProvider[Any]@@ -63,13 +65,11 @@ def create_default_layer_providers() -> tuple[DifyAgentLayerProvider, ...]:"""Return the server provider set of safe config-constructible layers.- ``shellctl_auth_token`` defaults to no token. Passing an explicit empty string- to ``create_shellctl_client_factory`` 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.+ ``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."""- shellctl_token = shellctl_auth_token or ""agent_stub_token_factory: ShellAgentStubTokenFactory | None = Noneif agent_stub_token_codec is not None:@@ -102,8 +102,15 @@ def create_default_layer_providers(layer_type=DifyShellLayer,create=lambda config: DifyShellLayer.from_config_with_settings(DifyShellLayerConfig.model_validate(config),- shellctl_entrypoint=shellctl_entrypoint,- shellctl_client_factory=create_shellctl_client_factory(token=shellctl_token),+ shell_provisioner=create_shell_provisioner(+ ShellAdapterSettings(+ shell_provider="shellctl",+ shellctl_entrypoint=shellctl_entrypoint,+ shellctl_auth_token=shellctl_auth_token,+ )+ )+ if shellctl_entrypoint+ else None,agent_stub_api_base_url=agent_stub_api_base_url,agent_stub_token_factory=agent_stub_token_factory,),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.pynew file mode 100644index 00000000000..74b11175c0d--- /dev/null+++ b/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py@@ -0,0 +1,331 @@+"""Local tests for the shellctl shell adapter and env-driven provider factory.++These exercise the provider-agnostic boundary contract (provision/execute/wait,+file transfer, optional input/interrupt) against a fake shellctl client, plus the+``DIFY_AGENT_SHELL_PROVIDER`` selection in the factory. They avoid the private+``shell-session-manager`` package by injecting a structural fake client.+"""++import asyncio+import base64+import secrets+from collections.abc import Callable+from dataclasses import dataclass, field++import pytest++from dify_agent.adapters.shell import shellctl+from dify_agent.adapters.shell.config import ShellAdapterSettings+from dify_agent.adapters.shell.factory import create_shell_provisioner+from dify_agent.adapters.shell.protocols import (+ ShellEnvironmentDescriptor,+)+from dify_agent.adapters.shell.shellctl import (+ ShellctlEnvironmentDescriptor,+ ShellctlProvisioner,+ ShellFileTransferError,+ ShellProvisionError,+)++_SESSION_HEX = "deadbeefdeadbeef"+_WORKSPACE_CWD = f"~/workspace/{_SESSION_HEX}"+++@dataclass(slots=True)+class _Job:+ job_id: str+ done: bool = True+ output: str = ""+ offset: int = 0+ truncated: bool = False+ exit_code: int | None = 0+++@dataclass(slots=True)+class _Status:+ job_id: str+ done: bool = True+ offset: int = 0+ exit_code: int | None = 0+++@dataclass(slots=True)+class _RunCall:+ script: str+ cwd: str | None+ env: dict[str, str] | None+++type _RunHandler = Callable[[str, str | None, dict[str, str] | None], _Job]+type _WaitHandler = Callable[[str, int], _Job]+type _InputHandler = Callable[[str, str, int], _Job]+type _TerminateHandler = Callable[[str], _Status]+++@dataclass(slots=True)+class FakeShellctlClient:+ """Structural shellctl client double recording calls and replaying handlers."""++ run_handler: _RunHandler | None = None+ wait_handler: _WaitHandler | None = None+ input_handler: _InputHandler | None = None+ terminate_handler: _TerminateHandler | None = None+ run_calls: list[_RunCall] = field(default_factory=list)+ wait_calls: list[tuple[str, int]] = field(default_factory=list)+ input_calls: list[tuple[str, str, int]] = field(default_factory=list)+ terminate_calls: list[tuple[str, float]] = field(default_factory=list)+ delete_calls: list[str] = field(default_factory=list)+ closed: bool = False++ async def run(self, script, *, cwd=None, env=None, timeout=30.0):+ del timeout+ self.run_calls.append(_RunCall(script=script, cwd=cwd, env=env))+ if self.run_handler is not None:+ return self.run_handler(script, cwd, env)+ return _Job(job_id="job", done=True, exit_code=0)++ async def wait(self, job_id, *, offset, timeout=30.0):+ del timeout+ self.wait_calls.append((job_id, offset))+ if self.wait_handler is not None:+ return self.wait_handler(job_id, offset)+ return _Job(job_id=job_id, done=True, offset=offset, exit_code=0)++ async def input(self, job_id, text, *, offset, timeout=30.0):+ del timeout+ self.input_calls.append((job_id, text, offset))+ if self.input_handler is not None:+ return self.input_handler(job_id, text, offset)+ return _Job(job_id=job_id, done=True, offset=offset, exit_code=0)++ async def terminate(self, job_id, grace_seconds=10.0):+ self.terminate_calls.append((job_id, grace_seconds))+ if self.terminate_handler is not None:+ return self.terminate_handler(job_id)+ return _Status(job_id=job_id, done=True, exit_code=130)++ async def delete(self, job_id, *, force=False):+ del force+ self.delete_calls.append(job_id)+ return None++ async def close(self):+ self.closed = True++[email protected](autouse=True)+def _fixed_session_id(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: _SESSION_HEX)+++def _provisioner(client: FakeShellctlClient) -> ShellctlProvisioner:+ return ShellctlProvisioner(client_factory=lambda: client)+++def test_provision_allocates_workspace_and_execute_drains_merged_output() -> None:+ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del env+ if script.startswith("mkdir"):+ assert cwd is None+ return _Job(job_id="mkdir-job", done=True, exit_code=0)+ assert cwd == _WORKSPACE_CWD+ return _Job(job_id="user-job", done=False, output="par", offset=3, truncated=False, exit_code=None)++ def wait_handler(job_id: str, offset: int) -> _Job:+ assert job_id == "user-job"+ assert offset == 3+ return _Job(job_id="user-job", done=True, output="tial", offset=7, exit_code=0)++ client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)++ async def scenario() -> None:+ handle = await _provisioner(client).provision()+ assert handle.workspace_cwd == _WORKSPACE_CWD+ executor = await handle.get_executor()+ result = await executor.execute("pwd", env={"FOO": "bar"})+ assert result.stdout() == "partial"+ assert result.stderr() == ""+ assert result.exit_code() == 0+ assert result.truncated() is False++ asyncio.run(scenario())++ assert client.run_calls[0].cwd is None+ user_run = next(call for call in client.run_calls if call.script == "pwd")+ assert user_run.env == {"FOO": "bar"}+ # completed jobs (internal mkdir + user command) are self-cleaned.+ assert "mkdir-job" in client.delete_calls+ assert "user-job" in client.delete_calls+++def test_execute_reports_truncated_when_output_window_cap_is_hit() -> None:+ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del cwd, env+ if script.startswith("mkdir"):+ return _Job(job_id="mkdir-job", done=True, exit_code=0)+ return _Job(job_id="user-job", done=False, output="x", offset=1, truncated=True, exit_code=None)++ def wait_handler(job_id: str, offset: int) -> _Job:+ return _Job(job_id=job_id, done=False, output="x", offset=offset + 1, truncated=True, exit_code=None)++ client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)++ async def scenario() -> bool:+ handle = await _provisioner(client).provision()+ executor = await handle.get_executor()+ result = await executor.execute("tail -f log")+ return result.truncated()++ assert asyncio.run(scenario()) is True+ # a job that never completed is left intact (not deleted/forgotten).+ assert "user-job" not in client.delete_calls+++def test_provision_failure_closes_client_and_raises() -> None:+ client = FakeShellctlClient(+ run_handler=lambda _script, _cwd, _env: _Job(job_id="mkdir-job", done=True, exit_code=1)+ )++ async def scenario() -> None:+ with pytest.raises(ShellProvisionError):+ await _provisioner(client).provision()++ asyncio.run(scenario())+ assert client.closed is True+++def test_destroy_runs_cleanup_in_default_cwd_then_closes_client() -> None:+ client = FakeShellctlClient(run_handler=lambda _script, _cwd, _env: _Job(job_id="job", done=True, exit_code=0))++ async def scenario() -> None:+ provisioner = _provisioner(client)+ handle = await provisioner.provision()+ await provisioner.destroy(handle)++ asyncio.run(scenario())++ cleanup_call = client.run_calls[-1]+ assert cleanup_call.cwd is None+ assert _SESSION_HEX in cleanup_call.script and cleanup_call.script.startswith("rm -rf")+ assert client.closed is True+++def test_file_transfer_download_decodes_sentinel_framed_base64() -> None:+ content = b"hello \x00 world"+ encoded = base64.b64encode(content).decode("ascii")+ framed = f"noise{shellctl._TRANSFER_BEGIN}{encoded}{shellctl._TRANSFER_END}trailing"++ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del env+ if script.startswith("mkdir"):+ return _Job(job_id="mkdir-job", done=True, exit_code=0)+ assert cwd == _WORKSPACE_CWD+ return _Job(job_id="dl-job", done=True, output=framed, exit_code=0)++ client = FakeShellctlClient(run_handler=run_handler)++ async def scenario() -> None:+ handle = await _provisioner(client).provision()+ transfer = await handle.get_file_transfer()+ downloaded = await transfer.download(remote_path="report.txt")+ assert downloaded == content++ asyncio.run(scenario())+++def test_file_transfer_download_missing_file_raises() -> None:+ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del cwd, env+ if script.startswith("mkdir"):+ return _Job(job_id="mkdir-job", done=True, exit_code=0)+ return _Job(job_id="dl-job", done=True, output="", exit_code=shellctl._DOWNLOAD_MISSING_EXIT_CODE)++ client = FakeShellctlClient(run_handler=run_handler)++ async def scenario() -> None:+ handle = await _provisioner(client).provision()+ transfer = await handle.get_file_transfer()+ with pytest.raises(ShellFileTransferError, match="not found"):+ await transfer.download(remote_path="missing.txt")++ asyncio.run(scenario())+++def test_file_transfer_upload_embeds_base64_and_succeeds() -> None:+ content = b"payload-bytes"+ encoded = base64.b64encode(content).decode("ascii")++ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del env+ if script.startswith('mkdir -p "$HOME'):+ return _Job(job_id="mkdir-job", done=True, exit_code=0)+ assert cwd == _WORKSPACE_CWD+ assert encoded in script+ return _Job(job_id="ul-job", done=True, exit_code=0)++ client = FakeShellctlClient(run_handler=run_handler)++ async def scenario() -> None:+ handle = await _provisioner(client).provision()+ transfer = await handle.get_file_transfer()+ await transfer.upload(content=content, remote_path="out.bin")++ asyncio.run(scenario())+++def test_provision_exposes_descriptor_seed() -> None:+ client = FakeShellctlClient(+ run_handler=lambda _script, _cwd, _env: _Job(job_id="mkdir-job", done=True, exit_code=0)+ )++ async def scenario() -> ShellEnvironmentDescriptor:+ handle = await _provisioner(client).provision()+ return handle.descriptor()++ descriptor = asyncio.run(scenario())+ assert isinstance(descriptor, ShellctlEnvironmentDescriptor)+ assert descriptor.workspace_cwd == _WORKSPACE_CWD+ assert descriptor.session_id == _SESSION_HEX+++def test_reattach_rebuilds_handle_without_mkdir_and_executes_in_same_workspace() -> None:+ descriptor = ShellctlEnvironmentDescriptor(workspace_cwd=_WORKSPACE_CWD, session_id=_SESSION_HEX)++ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:+ del env+ assert not script.startswith("mkdir")+ assert cwd == _WORKSPACE_CWD+ return _Job(job_id="user-job", done=True, output="ok", offset=2, exit_code=0)++ client = FakeShellctlClient(run_handler=run_handler)++ async def scenario() -> str:+ handle = await _provisioner(client).reattach(descriptor)+ executor = await handle.get_executor()+ result = await executor.execute("pwd")+ return result.stdout()++ assert asyncio.run(scenario()) == "ok"+ # reattach must not allocate a new workspace.+ assert all(not call.script.startswith("mkdir") for call in client.run_calls)+++def test_factory_unknown_provider_raises() -> None:+ settings = ShellAdapterSettings(shell_provider="nope")+ with pytest.raises(ValueError, match="Unknown shell provider"):+ create_shell_provisioner(settings)+++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_provisioner(settings)+++def test_factory_builds_shellctl_provisioner_from_settings() -> None:+ settings = ShellAdapterSettings(+ shell_provider="shellctl",+ shellctl_entrypoint="http://shellctl.example",+ )+ provisioner = create_shell_provisioner(settings)+ assert isinstance(provisioner, ShellctlProvisioner)diff --git a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.pyindex f9abc8e718b..f41ce2de61f 100644--- a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py+++ b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py@@ -2,25 +2,23 @@from __future__ import annotations-from typing import cast-import pytestfrom dify_agent.layers.drive import DifyDriveLayerConfig, DifyDriveSkillConfigfrom dify_agent.layers.drive.layer import DifyDriveLayer, DifyDriveLayerError+from dify_agent.adapters.shell.shellctl import ShellctlProvisionerfrom dify_agent.layers.shell import DifyShellLayerConfig-from dify_agent.layers.shell.layer import DifyShellLayer, RemoteCommandResult, ShellctlClientFactory+from dify_agent.layers.shell.layer import DifyShellLayer, RemoteCommandResult-def _unused_client_factory(_entrypoint: str):+def _unused_client_factory():raise AssertionError("shellctl client should not be used by these drive-layer tests")def _shell_layer() -> DifyShellLayer:return DifyShellLayer.from_config_with_settings(DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=cast(ShellctlClientFactory, _unused_client_factory),+ shell_provisioner=ShellctlProvisioner(client_factory=_unused_client_factory),)@@ -59,14 +57,10 @@ def _remote_result(truncated: bool = False,) -> RemoteCommandResult:return RemoteCommandResult(- job_id="remote-drive-pull",status="exited",- done=True,exit_code=exit_code,output=output,- offset=len(output),truncated=truncated,- output_path="/tmp/output.log",)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 df24f856b21..58aae61bd75 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@@ -1,7 +1,6 @@import asynciofrom collections.abc import Callable, Mappingimport secrets-import timefrom dataclasses import dataclassfrom typing import cast@@ -24,8 +23,14 @@ from dify_agent.layers.shell import (DifyShellSandboxConfig,DifyShellSecretRefConfig,)-from dify_agent.layers.shell.layer import DifyShellLayer, DifyShellRuntimeState, ShellctlClientFactory-from shell_session_manager.shellctl.shared import DeleteJobResponse, JobResult, JobStatusName, JobStatusView+from dify_agent.adapters.shell.shellctl import (+ ShellctlEnvironmentDescriptor,+ ShellctlHandle,+ ShellctlProvisioner,+ ShellProvisionError,+)+from dify_agent.layers.shell.layer import DifyShellLayer, DifyShellRuntimeState+from shell_session_manager.shellctl.shared import JobResult, JobStatusName, JobStatusViewdef _job_result(@@ -116,7 +121,6 @@ class TerminateCall:class DeleteCall:job_id: strforce: bool- grace_seconds: float | Noneclass FakeShellctlClient:@@ -135,7 +139,7 @@ class FakeShellctlClient:wait_handler: Callable[[str, int, float], JobResult] | None = None,input_handler: Callable[[str, str, int, float], JobResult] | None = None,terminate_handler: Callable[[str, float], JobStatusView] | None = None,- delete_handler: Callable[[str, bool, float | None], DeleteJobResponse] | None = None,+ delete_handler: Callable[[str, bool, float | None], object] | None = None,) -> None:self._run_handler = run_handlerself._wait_handler = wait_handler@@ -190,26 +194,22 @@ class FakeShellctlClient:job_id: str,*,force: bool = False,- grace_seconds: float | None = None,- ) -> DeleteJobResponse:- self.delete_calls.append(DeleteCall(job_id=job_id, force=force, grace_seconds=grace_seconds))+ ) -> object:+ self.delete_calls.append(DeleteCall(job_id=job_id, force=force))self.events.append(("delete", job_id))if self._delete_handler is None:- return DeleteJobResponse(job_id=job_id)- return self._delete_handler(job_id, force, grace_seconds)+ return None+ return self._delete_handler(job_id, force, None)async def close(self) -> None:self.closed = Trueself.events.append(("close", "client"))-def _shell_layer(- *, client_factory: ShellctlClientFactory, config: DifyShellLayerConfig | None = None-) -> DifyShellLayer:+def _shell_layer(*, client: FakeShellctlClient, config: DifyShellLayerConfig | None = None) -> DifyShellLayer:return DifyShellLayer.from_config_with_settings(config or DifyShellLayerConfig(),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=client_factory,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),)@@ -236,13 +236,12 @@ def _execution_context_layer() -> DifyExecutionContextLayer:)-def _shell_provider(*, client_factory: ShellctlClientFactory) -> LayerProvider[DifyShellLayer]:+def _shell_provider(*, client: FakeShellctlClient) -> LayerProvider[DifyShellLayer]:return LayerProvider.from_factory(layer_type=DifyShellLayer,create=lambda config: DifyShellLayer.from_config_with_settings(DifyShellLayerConfig.model_validate(config),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=client_factory,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),),)@@ -251,31 +250,34 @@ def test_shell_type_id_constant_matches_implementation_class() -> None:assert DIFY_SHELL_LAYER_TYPE_ID == DifyShellLayer.type_id-def test_shell_layer_create_generates_5_plus_2_hex_session_id_and_retries_workspace_collision(- monkeypatch: pytest.MonkeyPatch,-) -> None:- random_suffixes = iter(["aa", "bb"])- monkeypatch.setattr(time, "time", lambda: 0x12345F)- monkeypatch.setattr(secrets, "token_hex", lambda nbytes: next(random_suffixes))+def test_environment_descriptor_returns_workspace_seed_from_runtime_state() -> None:+ layer = _shell_layer(client=FakeShellctlClient())+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")++ descriptor = layer.environment_descriptor()++ assert descriptor == ShellctlEnvironmentDescriptor(workspace_cwd="~/workspace/abc12ff", session_id="abc12ff")+++def test_environment_descriptor_raises_without_session_identity() -> None:+ layer = _shell_layer(client=FakeShellctlClient())++ with pytest.raises(ValueError, match="session_id or workspace_cwd"):+ _ = layer.environment_descriptor()+++def test_shell_layer_create_provisions_workspace_and_bootstraps(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "deadbeefdeadbeef")def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:- assert cwd is Noneassert env is None- assert timeout == 30.0- if "2345faa" in script:- return _job_result("mkdir-collision", status=JobStatusName.EXITED, done=True, exit_code=17)- if "2345fbb" in script:- return _job_result("mkdir-success", status=JobStatusName.RUNNING, done=False, offset=4)- raise AssertionError(f"Unexpected script: {script}")-- def wait_handler(job_id: str, offset: int, timeout: float) -> JobResult:- assert job_id == "mkdir-success"- assert offset == 4- assert timeout == 30.0- return _job_result("mkdir-success", status=JobStatusName.EXITED, done=True, exit_code=0, offset=8)+ if cwd is None:+ assert 'mkdir -p "$HOME/workspace/deadbeefdeadbeef"' in script+ return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)+ raise AssertionError(f"Unexpected script with cwd={cwd}: {script}")- client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ client = FakeShellctlClient(run_handler=run_handler)+ layer = _shell_layer(client=client)async def scenario() -> None:async with layer.resource_context():@@ -284,29 +286,25 @@ def test_shell_layer_create_generates_5_plus_2_hex_session_id_and_retries_workspasyncio.run(scenario())- assert layer.runtime_state.session_id == "2345fbb"- assert layer.runtime_state.workspace_cwd == "~/workspace/2345fbb"- assert layer.runtime_state.job_ids == ["mkdir-collision", "mkdir-success"]- assert layer.runtime_state.job_offsets == {"mkdir-collision": 0, "mkdir-success": 8}- assert 'mkdir "$HOME/workspace/2345fbb"' in client.run_calls[1].script- assert 'mkdir -p "$HOME/workspace/2345fbb"' not in client.run_calls[1].script- assert client.closed is True+ assert layer.runtime_state.session_id == "deadbeefdeadbeef"+ assert layer.runtime_state.workspace_cwd == "~/workspace/deadbeefdeadbeef"-def test_shell_layer_suspend_leaves_client_open_until_resource_context_exits() -> None:+def test_shell_layer_suspend_closes_client_before_resource_context_exits() -> None:client = FakeShellctlClient()- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")async def scenario() -> None:async with layer.resource_context():+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )await layer.on_context_suspend()- assert client.closed is False+ assert client.closed is Trueasyncio.run(scenario())- assert client.closed is True-def test_shell_layer_suspend_and_resume_reuse_state_with_fresh_clients() -> None:first_client = FakeShellctlClient(@@ -317,15 +315,31 @@ def test_shell_layer_suspend_and_resume_reuse_state_with_fresh_clients() -> Noneexit_code=0,))- second_client = FakeShellctlClient()- created_entrypoints: list[str] = []+ second_client = FakeShellctlClient(+ run_handler=lambda _script, _cwd, _env, _timeout: _job_result(+ "cleanup-job",+ status=JobStatusName.EXITED,+ done=True,+ exit_code=0,+ )+ )clients = iter([first_client, second_client])- def factory(entrypoint: str) -> FakeShellctlClient:- created_entrypoints.append(entrypoint)+ def factory() -> FakeShellctlClient:return next(clients)- compositor = Compositor([LayerNode("shell", _shell_provider(client_factory=factory))])+ provisioner = ShellctlProvisioner(client_factory=factory)++ def make_provider(c: FakeShellctlClient) -> LayerProvider[DifyShellLayer]:+ return LayerProvider.from_factory(+ layer_type=DifyShellLayer,+ create=lambda config: DifyShellLayer.from_config_with_settings(+ DifyShellLayerConfig.model_validate(config),+ shell_provisioner=provisioner,+ ),+ )++ compositor = Compositor([LayerNode("shell", make_provider(first_client))])async def scenario() -> None:async with compositor.enter(configs={"shell": DifyShellLayerConfig()}) as run:@@ -353,57 +367,44 @@ def test_shell_layer_suspend_and_resume_reuse_state_with_fresh_clients() -> Noneassert second_client.closed is Falseassert resumed_shell.runtime_state.session_id == initial_session_idassert resumed_shell.runtime_state.workspace_cwd == f"~/workspace/{initial_session_id}"- assert set(resumed_shell.runtime_state.job_ids) == {"mkdir-job", "user-job"}- assert resumed_shell.runtime_state.job_offsets == {"mkdir-job": 0, "user-job": 42}+ assert set(resumed_shell.runtime_state.job_ids) == {"user-job"}+ assert resumed_shell.runtime_state.job_offsets == {"user-job": 42}resumed_run.suspend_layer_on_exit("shell")assert second_client.closed is Trueasyncio.run(scenario())- assert created_entrypoints == ["http://shellctl", "http://shellctl"]--def test_shell_layer_delete_removes_workspace_then_force_deletes_tracked_jobs_and_closes_client() -> None:+def test_shell_layer_delete_force_deletes_tracked_jobs_then_destroys_workspace() -> None:def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:- assert script == 'rm -rf -- "$HOME/workspace/abc12ff"'- assert cwd is None- assert env is None- assert timeout == 30.0- return _job_result("cleanup-job", status=JobStatusName.RUNNING, done=False, offset=3)+ del cwd, env, timeout+ return _job_result("cleanup-job", status=JobStatusName.EXITED, done=True, exit_code=0)- def wait_handler(job_id: str, offset: int, timeout: float) -> JobResult:- assert job_id == "cleanup-job"- assert offset == 3- assert timeout == 30.0- return _job_result("cleanup-job", status=JobStatusName.EXITED, done=True, exit_code=0, offset=5)-- client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ client = FakeShellctlClient(run_handler=run_handler)+ layer = _shell_layer(client=client)async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")layer.runtime_state.job_ids = ["user-job", "mkdir-job"]layer.runtime_state.job_offsets = {"user-job": 9, "mkdir-job": 1}+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )await layer.on_context_delete()- assert client.closed is Falseasyncio.run(scenario())- assert client.events[:2] == [("run", 'rm -rf -- "$HOME/workspace/abc12ff"'), ("wait", "cleanup-job")]- assert {call.job_id for call in client.delete_calls} == {"user-job", "mkdir-job", "cleanup-job"}- assert all(- client.events.index(("delete", call.job_id)) > client.events.index(("wait", "cleanup-job"))- for call in client.delete_calls- )+ deleted_job_ids = {call.job_id for call in client.delete_calls}+ assert {"user-job", "mkdir-job"}.issubset(deleted_job_ids)assert all(call.force is True for call in client.delete_calls)assert layer.runtime_state.job_ids == []assert layer.runtime_state.job_offsets == {}assert client.closed is True-def test_shell_layer_create_failure_force_deletes_internal_jobs_before_reraising() -> None:+def test_shell_layer_create_failure_destroys_provisioned_workspace() -> None:client = FakeShellctlClient(run_handler=lambda _script, _cwd, _env, _timeout: _job_result("mkdir-failed",@@ -412,32 +413,26 @@ def test_shell_layer_create_failure_force_deletes_internal_jobs_before_reraisingexit_code=1,))- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)async def scenario() -> None:- with pytest.raises(RuntimeError, match="Failed to create shell workspace"):+ with pytest.raises(ShellProvisionError, match="Failed to create shell workspace"):async with layer.resource_context():await layer.on_context_create()asyncio.run(scenario())- assert [call.job_id for call in client.delete_calls] == ["mkdir-failed"]- assert all(call.force is True for call in client.delete_calls)- assert layer.runtime_state.job_ids == []- assert layer.runtime_state.job_offsets == {}assert client.closed is Truedef test_shell_layer_create_bootstraps_agent_soul_shell_config(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(time, "time", lambda: 0xABC12)- monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "ff")+ monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "abc12ffabc12ff")def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:assert env is Noneif cwd is None:- assert timeout == 30.0return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)- assert cwd == "~/workspace/abc12ff"+ assert cwd == "~/workspace/abc12ffabc12ff"assert "export PROJECT_NAME='demo project'" in scriptassert "export QUOTED='it'\\''s ok'" in scriptassert 'export OPENAI_API_KEY="${OPENAI_API_KEY:-}"' in script@@ -450,7 +445,7 @@ def test_shell_layer_create_bootstraps_agent_soul_shell_config(monkeypatch: pyteclient = FakeShellctlClient(run_handler=run_handler)layer = _shell_layer(- client_factory=lambda _entrypoint: client,+ client=client,config=DifyShellLayerConfig(cli_tools=[DifyShellCliToolConfig(@@ -475,17 +470,11 @@ def test_shell_layer_create_bootstraps_agent_soul_shell_config(monkeypatch: pyteasyncio.run(scenario())- assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ff"]- assert layer.runtime_state.job_ids == ["mkdir-job", "bootstrap-job"]+ assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ffabc12ff"]def test_shell_layer_injects_agent_soul_env_without_workspace_env_file(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(time, "time", lambda: 0xABC12)-- def token_hex(_nbytes: int) -> str:- return "ff"-- monkeypatch.setattr(secrets, "token_hex", token_hex)+ monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "abc12ffabc12ff")def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:del timeout@@ -493,7 +482,7 @@ def test_shell_layer_injects_agent_soul_env_without_workspace_env_file(monkeypatif cwd is None:return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)- assert cwd == "~/workspace/abc12ff"+ assert cwd == "~/workspace/abc12ffabc12ff"assert "export PROJECT_NAME='demo project'" in scriptassert 'export OPENAI_API_KEY="${OPENAI_API_KEY:-}"' in scriptassert "export DIFY_SANDBOX_PROVIDER='independent'" in script@@ -503,7 +492,7 @@ def test_shell_layer_injects_agent_soul_env_without_workspace_env_file(monkeypatclient = FakeShellctlClient(run_handler=run_handler)layer = _shell_layer(- client_factory=lambda _entrypoint: client,+ client=client,config=DifyShellLayerConfig(env=[DifyShellEnvVarConfig(name="PROJECT_NAME", value="demo project")],secret_refs=[DifyShellSecretRefConfig(name="OPENAI_API_KEY", ref="secret-1")],@@ -526,8 +515,7 @@ def test_shell_layer_injects_agent_soul_env_without_workspace_env_file(monkeypatasyncio.run(scenario())- assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ff"]- assert layer.runtime_state.job_ids == ["mkdir-job", "user-job"]+ assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ffabc12ff"]def test_shell_layer_tools_map_inputs_to_shellctl_calls_and_maintain_offsets() -> None:@@ -587,12 +575,15 @@ def test_shell_layer_tools_map_inputs_to_shellctl_calls_and_maintain_offsets() -input_handler=input_handler,terminate_handler=terminate_handler,)- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)tools = {tool.name: tool for tool in layer.tools}async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )run_tool_def = await tools["shell_run"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]wait_tool_def = await tools["shell_wait"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]@@ -642,7 +633,7 @@ def test_shell_layer_tools_map_inputs_to_shellctl_calls_and_maintain_offsets() -assert layer.runtime_state.job_ids == ["user-job"]assert layer.runtime_state.job_offsets == {"user-job": 22}- assert client.closed is True+ assert client.closed is Falsedef test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() -> None:@@ -657,8 +648,7 @@ def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() ->client = FakeShellctlClient(run_handler=run_handler)layer = DifyShellLayer.from_config_with_settings(DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"@@ -720,11 +710,14 @@ def test_run_remote_script_uses_workspace_cwd_accumulates_output_and_deletes_job)client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )result = await layer.run_remote_script("printf 'hello world'", timeout=7.5)assert result.output == "hello world"assert result.exit_code == 0@@ -753,11 +746,14 @@ def test_run_remote_script_deletes_job_even_when_command_exits_non_zero() -> Non)client = FakeShellctlClient(run_handler=run_handler)- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )result = await layer.run_remote_script("exit 17", timeout=3.0)assert result.exit_code == 17assert result.output == "failed\n"@@ -785,8 +781,7 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()client = FakeShellctlClient(run_handler=run_handler)layer = DifyShellLayer.from_config_with_settings(DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"@@ -797,6 +792,9 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )_ = await layer.run_remote_script("dify-agent file upload report.txt", inject_agent_stub_env=True)asyncio.run(scenario())@@ -815,8 +813,7 @@ def test_run_remote_script_raises_when_agent_stub_env_is_unavailable() -> None:)layer = DifyShellLayer.from_config_with_settings(DifyShellLayerConfig(),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"@@ -826,6 +823,9 @@ def test_run_remote_script_raises_when_agent_stub_env_is_unavailable() -> None:async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )with pytest.raises(RuntimeError, match="Agent Stub environment injection is not available"):await layer.run_remote_script("dify-agent file upload report.txt", inject_agent_stub_env=True)@@ -845,8 +845,7 @@ def test_shell_layer_skips_agent_stub_env_without_execution_context_dependency())layer = DifyShellLayer.from_config_with_settings(DifyShellLayerConfig(),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"@@ -857,6 +856,9 @@ def test_shell_layer_skips_agent_stub_env_without_execution_context_dependency()async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )_ = await tools["shell_run"].function_schema.call({"script": "pwd"},None, # pyright: ignore[reportArgumentType]@@ -869,12 +871,15 @@ def test_shell_layer_skips_agent_stub_env_without_execution_context_dependency()def test_shell_layer_tools_reject_untracked_job_ids_without_shellctl_calls() -> None:client = FakeShellctlClient()- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)tools = {tool.name: tool for tool in layer.tools}async def scenario() -> None:async with layer.resource_context():layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")+ layer._shell_handle = ShellctlHandle(+ client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"+ )wait_result = await tools["shell_wait"].function_schema.call({"job_id": "missing-job"},@@ -902,19 +907,16 @@ def test_shell_layer_tools_reject_untracked_job_ids_without_shellctl_calls() ->def test_shell_layer_hooks_and_tools_fail_clearly_outside_active_resource_context() -> None:client = FakeShellctlClient()- layer = _shell_layer(client_factory=lambda _entrypoint: client)+ layer = _shell_layer(client=client)layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")tools = {tool.name: tool for tool in layer.tools}async def scenario() -> None:- with pytest.raises(RuntimeError, match="resource_context"):- await layer.on_context_suspend()-run_result = await tools["shell_run"].function_schema.call({"script": "pwd"},None, # pyright: ignore[reportArgumentType])- _assert_error_observation(run_result, includes="resource_context")+ _assert_error_observation(run_result, includes="shell handle")asyncio.run(scenario())@@ -922,7 +924,7 @@ def test_shell_layer_hooks_and_tools_fail_clearly_outside_active_resource_contexdef test_shell_runtime_state_rejects_unsafe_resumed_workspace_identity() -> None:- with pytest.raises(ValueError, match="session_id must match"):+ with pytest.raises(ValueError, match="session_id must be 7 or 16 lowercase hex characters"):_ = DifyShellRuntimeState.model_validate({"session_id": "../../tmp",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 87582e654e8..2482c635d74 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@@ -1,6 +1,10 @@+from typing import cast+import pytestimport dify_agent.runtime.compositor_factory as compositor_factory_module+from dify_agent.adapters.shell.config import ShellAdapterSettings+from dify_agent.adapters.shell.protocols import ShellProvisionProtocolfrom dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodecfrom dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfigfrom dify_agent.layers.execution_context import DifyExecutionContextLayerConfig@@ -8,30 +12,30 @@ from dify_agent.layers.shell.layer import DifyShellLayerfrom dify_agent.runtime.compositor_factory import create_default_layer_providers-class FakeFactoryClient:- async def close(self) -> None:- return None+class FakeProvisioner:+ """No-op provisioner for tests that never actually provision a workspace."""++ async def provision(self) -> object:+ raise AssertionError("provision should not be called by these tests")++ async def reattach(self, descriptor: object) -> object:+ raise AssertionError("reattach should not be called by these tests")++ async def destroy(self, handle: object) -> None:+ raise AssertionError("destroy should not be called by these tests")def test_default_layer_providers_register_shell_layer_with_configured_token_factory(monkeypatch: pytest.MonkeyPatch,) -> None:- captured_tokens: list[str] = []- captured_entrypoints: list[str] = []- fake_client = FakeFactoryClient()-- def fake_create_shellctl_client_factory(*, token: str):- captured_tokens.append(token)+ captured_settings: list[ShellAdapterSettings] = []+ fake_provisioner = FakeProvisioner()- def factory(entrypoint: str) -> FakeFactoryClient:- captured_entrypoints.append(entrypoint)- return fake_client+ def fake_create_shell_provisioner(settings: ShellAdapterSettings) -> ShellProvisionProtocol:+ captured_settings.append(settings)+ return cast(ShellProvisionProtocol, fake_provisioner)- return factory-- monkeypatch.setattr(- compositor_factory_module, "create_shellctl_client_factory", fake_create_shellctl_client_factory- )+ monkeypatch.setattr(compositor_factory_module, "create_shell_provisioner", fake_create_shell_provisioner)providers = create_default_layer_providers(shellctl_entrypoint="http://shellctl.example",@@ -41,34 +45,29 @@ def test_default_layer_providers_register_shell_layer_with_configured_token_factshell_layer = shell_provider.create_layer(DifyShellLayerConfig())assert isinstance(shell_layer, DifyShellLayer)- assert shell_layer.shellctl_entrypoint == "http://shellctl.example"- assert captured_tokens == ["shell-secret"]- assert shell_layer.shellctl_client_factory(shell_layer.shellctl_entrypoint) is fake_client- assert captured_entrypoints == ["http://shellctl.example"]+ assert shell_layer.shell_provisioner is fake_provisioner+ 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_tokens: list[str] = []-- def fake_create_shellctl_client_factory(*, token: str):- captured_tokens.append(token)+ captured_settings: list[ShellAdapterSettings] = []- def factory(_entrypoint: str) -> FakeFactoryClient:- return FakeFactoryClient()+ def fake_create_shell_provisioner(settings: ShellAdapterSettings) -> ShellProvisionProtocol:+ captured_settings.append(settings)+ return cast(ShellProvisionProtocol, FakeProvisioner())- return factory-- monkeypatch.setattr(- compositor_factory_module, "create_shellctl_client_factory", fake_create_shellctl_client_factory- )+ monkeypatch.setattr(compositor_factory_module, "create_shell_provisioner", fake_create_shell_provisioner)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 captured_tokens == [""]+ assert len(captured_settings) == 1+ assert captured_settings[0].shellctl_auth_token is Nonedef test_shell_provider_rejects_blank_settings_entrypoint_only_when_shell_layer_is_created() -> None:diff --git a/dify-agent/tests/local/dify_agent/runtime/test_runner.py b/dify-agent/tests/local/dify_agent/runtime/test_runner.pyindex 4a64fe9090d..6730624fdca 100644--- a/dify-agent/tests/local/dify_agent/runtime/test_runner.py+++ b/dify-agent/tests/local/dify_agent/runtime/test_runner.py@@ -29,6 +29,7 @@ from agenton_collections.layers.plain import PromptLayerConfig, ToolsLayerfrom dify_agent.layers.ask_human import DIFY_ASK_HUMAN_LAYER_TYPE_ID, DifyAskHumanLayerConfigfrom dify_agent.layers.execution_context import DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID, DifyExecutionContextLayerConfigfrom dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig+from dify_agent.adapters.shell.shellctl import ShellctlProvisionerfrom dify_agent.layers.shell.layer import DifyShellLayerfrom dify_agent.layers.dify_plugin.configs import (DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID,@@ -1346,8 +1347,7 @@ def test_runner_rejects_duplicate_tool_names_between_shell_and_other_layers(layer_type=DifyShellLayer,create=lambda config: DifyShellLayer.from_config_with_settings(DifyShellLayerConfig.model_validate(config),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: shell_client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: shell_client),),)layer_providers = tuple(@@ -2342,7 +2342,7 @@ def test_runner_treats_missing_shell_entrypoint_as_validation_error() -> None:async def scenario() -> None:async with httpx.AsyncClient() as client:- with pytest.raises(AgentRunValidationError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):+ with pytest.raises(AgentRunValidationError, match="non-null shell provisioner"):await AgentRunRunner(sink=sink,request=request,diff --git a/dify-agent/tests/local/dify_agent/server/test_app.py b/dify-agent/tests/local/dify_agent/server/test_app.pyindex ea0bc3b2977..ea83ec30080 100644--- a/dify-agent/tests/local/dify_agent/server/test_app.py+++ b/dify-agent/tests/local/dify_agent/server/test_app.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport base64import timefrom typing import ClassVar@@ -8,7 +7,8 @@ from typing import ClassVarimport httpximport pytestfrom fastapi.testclient import TestClient-from shell_session_manager.shellctl.client import ShellctlClient++from dify_agent.adapters.shell.shellctl import ShellctlProvisionerimport dify_agent.server.app as app_modulefrom dify_agent.layers.execution_context import DifyExecutionContextLayerConfig@@ -246,12 +246,8 @@ def test_create_app_creates_scheduler_and_closes_after_shutdown(monkeypatch: pytassert isinstance(knowledge_layer, DifyKnowledgeBaseLayer)assert knowledge_layer.inner_api_url == "http://dify-api"assert knowledge_layer.inner_api_key == "inner-secret"- assert shell_layer.shellctl_entrypoint == "http://shellctl"+ assert isinstance(shell_layer.shell_provisioner, ShellctlProvisioner)assert shell_layer.agent_stub_api_base_url == "https://agent.example.com/agent-stub"- shellctl_client = shell_layer.shellctl_client_factory("http://shellctl")- assert isinstance(shellctl_client, ShellctlClient)- assert shellctl_client.token == "shell-secret"- asyncio.run(shellctl_client.close())http_client = scheduler.plugin_daemon_http_clientassert http_client is fake_http_clientassert http_client.is_closed is Falsediff --git a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.pyindex 939e28f5309..72d70940a83 100644--- a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py+++ b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py@@ -19,6 +19,7 @@ from dify_agent.layers.execution_context import DifyExecutionContextLayerConfigfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.shell import DifyShellLayerConfigfrom dify_agent.layers.shell.layer import DifyShellLayer+from dify_agent.adapters.shell.shellctl import ShellctlProvisionerfrom dify_agent.protocol import (CreateRunRequest,RunComposition,@@ -38,7 +39,7 @@ from dify_agent.server.sandbox_files import ()from fastapi import FastAPIfrom fastapi.testclient import TestClient-from shell_session_manager.shellctl.shared import DeleteJobResponse, JobResult, JobStatusName+from shell_session_manager.shellctl.shared import JobResult, JobStatusName@dataclass(slots=True)@@ -71,7 +72,7 @@ class FakeShellctlClient:return self.run_handler(script, cwd, env, timeout)async def wait(self, job_id: str, *, offset: int, timeout: float = 10.0) -> JobResult:- raise AssertionError(f"Unexpected wait() call for {job_id} offset={offset} timeout={timeout}")+ return self.run_handler("", None, None, timeout)async def input(self, job_id: str, text: str, *, offset: int, timeout: float = 10.0) -> JobResult:raise AssertionError(f"Unexpected input() call for {job_id} text={text!r}")@@ -84,11 +85,10 @@ class FakeShellctlClient:job_id: str,*,force: bool = False,- grace_seconds: float | None = None,- ) -> DeleteJobResponse:- del force, grace_seconds+ ) -> object:+ del forceself.delete_calls.append(job_id)- return DeleteJobResponse(job_id=job_id)+ return Noneasync def close(self) -> None:return None@@ -191,8 +191,7 @@ def _service(layer_type=DifyShellLayer,create=lambda config: DifyShellLayer.from_config_with_settings(DifyShellLayerConfig.model_validate(config),- shellctl_entrypoint="http://shellctl",- shellctl_client_factory=lambda _entrypoint: client,+ shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"