diff --git a/backend/packages/harness/deerflow/agents/AGENTS.md b/backend/packages/harness/deerflow/agents/AGENTS.md index c9f4155045..2a752f30ce 100644 --- a/backend/packages/harness/deerflow/agents/AGENTS.md +++ b/backend/packages/harness/deerflow/agents/AGENTS.md @@ -18,6 +18,10 @@ python -m pytest tests -q -k "lead_agent or thread_state or assembly or prompt" Keep its signature and its bare-graph return type. The Gateway calls `assemble_lead_agent`, which also returns the descriptor and the effective model. +- **Injected skill storage uses the configured sandbox mount.** The lead's + catalog, activation and thread sandbox projection share the supplied storage. + An embedding host supplies a provider with thread skill isolation and + serializes lead runs for the same user and thread. - **A consumer unwraps through `runtime/runs/worker.py::_agent_graph`**, because a third-party factory can return a bare graph. - **The graph and the assembly descriptor receive the same rendered prompt and diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index 8c1014dd27..6adfd44f11 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -77,6 +77,7 @@ from deerflow.runtime.checkpoint_mode import ( ) from deerflow.runtime.context_keys import MCP_BROWSER_USER_CONTEXT_KEY from deerflow.scheduler.runtime import SCHEDULER_CAPABILITY_CONTEXT_KEY, is_scheduler_capability +from deerflow.skills.storage.skill_storage import SkillStorage, validate_injected_skill_storage from deerflow.skills.types import Skill from deerflow.subagents.capacity import configured_subagent_max_running from deerflow.tracing import build_tracing_callbacks @@ -493,6 +494,7 @@ def build_middlewares( memory_enabled: bool = True, owns_agent_skill_projection: bool = True, app_config: AppConfig | None = None, + skill_storage: SkillStorage | None = None, deferred_setup=None, mcp_routing_middleware: AgentMiddleware | None = None, user_id: str | None = None, @@ -519,6 +521,10 @@ def build_middlewares( thread's physical skill projection. Prompt-only bootstrap agents do not; their narrow skill set must not replace the thread view. app_config: Explicit AppConfig; falls back to ``get_app_config()`` when omitted. + skill_storage: Optional storage instance for skill resolution. It is + shared by slash activation, skill-read canonicalization and the + lead-owned sandbox projection. Its container root must match + ``app_config.skills.container_path``. deferred_setup: Optional deferred-MCP-tool setup that attaches ``DeferredToolFilterMiddleware`` when ``tool_search`` is enabled. mcp_routing_middleware: Compatibility middleware for advisory MCP @@ -559,9 +565,12 @@ def build_middlewares( # skill-file-load stamp on the same skill:activate decision the # activation middleware enforces for slash commands). runtime_middleware_kwargs["skill_authorization"] = skill_authorization + if skill_storage is not None: + validate_injected_skill_storage(skill_storage, container_root=resolved_app_config.skills.container_path, user_id=user_id) + runtime_middleware_kwargs["skill_storage"] = skill_storage if user_id is not None: - # ToolErrorHandlingMiddleware canonicalizes skill-read paths through - # the same user-scoped registry the activation/policy middlewares use. + # User-scoped fallback for hosts that do not inject a request-scoped + # storage instance. runtime_middleware_kwargs["user_id"] = user_id if authorization_provider is not None and deferred_setup is not None: runtime_middleware_kwargs["deferred_setup"] = deferred_setup @@ -592,6 +601,7 @@ def build_middlewares( user_id=user_id, slash_source_owner_token=slash_source_owner_token, skill_authorization=skill_authorization, + skill_storage=skill_storage, ) ) @@ -853,11 +863,17 @@ def _insert_hitl_approval_middleware(middlewares: list, final_tools: list, app_c middlewares.insert(index, ToolApprovalMiddleware(hitl_config, app_config=app_config, supports_resume=supports_resume, model_name=model_name)) -def _load_enabled_available_skills(available_skills: set[str] | None, *, app_config: AppConfig, user_id: str | None = None) -> list[Skill]: +def _load_enabled_available_skills( + available_skills: set[str] | None, + *, + app_config: AppConfig, + user_id: str | None = None, + skill_storage: SkillStorage | None = None, +) -> list[Skill]: try: from deerflow.agents.lead_agent.prompt import get_enabled_skills_for_config - skills = get_enabled_skills_for_config(app_config, user_id=user_id) + skills = get_enabled_skills_for_config(app_config, user_id=user_id, skill_storage=skill_storage) except Exception: logger.exception("Failed to load enabled skills") raise @@ -876,6 +892,7 @@ def assemble_lead_agent( config: RunnableConfig, *, app_config: AppConfig | None = None, + skill_storage: SkillStorage | None = None, ) -> LeadAgentAssembly: """Return the compiled lead graph together with its assembly descriptor. @@ -883,6 +900,11 @@ def assemble_lead_agent( built from does not have to be recovered from LangGraph private runtime keys or mutable graph attributes. ``make_lead_agent`` remains the graph-only LangGraph Server ABI declared in ``langgraph.json``. + + ``skill_storage`` lets an embedding host supply request-scoped skill + storage for skill discovery, activation, skill reads and the lead-owned + sandbox projection. Use the configured sandbox skills mount as the storage's + container root. The sandbox provider must support thread skill projections. """ runtime_config = _get_runtime_config(config) runtime_app_config = app_config or runtime_config.get("app_config") @@ -910,7 +932,7 @@ def assemble_lead_agent( # configurable key must not recompile the channel table either). freeze_checkpoint_snapshot_frequency(runtime_app_config.database.checkpoint_delta.snapshot_frequency) inject_checkpoint_mode(config, mode) - return _assemble_lead_agent(config, app_config=runtime_app_config) + return _assemble_lead_agent(config, app_config=runtime_app_config, skill_storage=skill_storage) def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig): @@ -989,7 +1011,12 @@ def _complete_assembly( return LeadAgentAssembly(graph=graph, descriptor=descriptor, effective_model=effective_model) -def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> LeadAgentAssembly: +def _assemble_lead_agent( + config: RunnableConfig, + *, + app_config: AppConfig, + skill_storage: SkillStorage | None = None, +) -> LeadAgentAssembly: # Lazy import to avoid circular dependency from deerflow.tools import get_available_tools from deerflow.tools.builtins import setup_agent, update_agent @@ -1009,6 +1036,8 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le from deerflow.runtime.user_context import resolve_config_user_id resolved_user_id = resolve_config_user_id(config) + if skill_storage is not None: + validate_injected_skill_storage(skill_storage, container_root=resolved_app_config.skills.container_path, user_id=resolved_user_id) requested_model_name: str | None = cfg.get("model_name") or cfg.get("model") is_plan_mode = cfg.get("is_plan_mode", False) @@ -1075,7 +1104,14 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le try: from deerflow.agents.lead_agent.prompt import get_enabled_skills_for_config - candidate_skill_names = [s.name for s in get_enabled_skills_for_config(resolved_app_config, user_id=resolved_user_id)] + candidate_skill_names = [ + s.name + for s in get_enabled_skills_for_config( + resolved_app_config, + user_id=resolved_user_id, + skill_storage=skill_storage, + ) + ] except Exception: logger.warning("Failed to pre-load enabled skills for authorization candidates", exc_info=True) # Leave None: the filter resolves candidates itself and applies @@ -1189,7 +1225,12 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le existing = list(existing) config["callbacks"] = [*existing, *tracing_callbacks] - enabled_skills = _load_enabled_available_skills(available_skills, app_config=resolved_app_config, user_id=resolved_user_id) + enabled_skills = _load_enabled_available_skills( + available_skills, + app_config=resolved_app_config, + user_id=resolved_user_id, + skill_storage=skill_storage, + ) # Build skill search setup (deferred skill discovery). # Controlled by skills.deferred_discovery — independent from tool_search.enabled. @@ -1273,6 +1314,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le # the full-metadata rendering advertise a policy-denied skill. available_skills=available_skills, app_config=resolved_app_config, + skill_storage=skill_storage, deferred_names=setup.deferred_names, user_id=resolved_user_id, # Preserve the (possibly empty) index when deferred discovery is @@ -1414,6 +1456,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le available_skills=available_skills, memory_enabled=memory_enabled, app_config=resolved_app_config, + skill_storage=skill_storage, deferred_setup=setup, mcp_routing_middleware=mcp_routing_middleware, user_id=resolved_user_id, @@ -1437,6 +1480,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le agent_soul=agent_authority.soul if pinned_agent else None, available_skills=available_skills, app_config=resolved_app_config, + skill_storage=skill_storage, deferred_names=setup.deferred_names, mcp_routing_hints_section=mcp_routing_hints_section, user_id=resolved_user_id, diff --git a/backend/packages/harness/deerflow/agents/lead_agent/prompt.py b/backend/packages/harness/deerflow/agents/lead_agent/prompt.py index ed05e46008..affb5b106e 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/prompt.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/prompt.py @@ -28,6 +28,7 @@ from deerflow.tools.builtins.tool_search import get_deferred_tools_prompt_sectio if TYPE_CHECKING: from deerflow.config.app_config import AppConfig + from deerflow.skills.storage.skill_storage import SkillStorage logger = logging.getLogger(__name__) @@ -270,7 +271,11 @@ def get_cached_enabled_skills() -> list[Skill]: return [] -def get_enabled_skills_for_config(app_config: AppConfig | None = None, user_id: str | None = None) -> list[Skill]: +def get_enabled_skills_for_config( + app_config: AppConfig | None = None, + user_id: str | None = None, + skill_storage: SkillStorage | None = None, +) -> list[Skill]: """Return enabled skills using the caller's config source and user scope. When a concrete ``app_config`` is supplied, cache the loaded skills by that @@ -281,9 +286,17 @@ def get_enabled_skills_for_config(app_config: AppConfig | None = None, user_id: When ``user_id`` is provided, uses :func:`get_or_new_user_skill_storage` to load public + user-level custom skills. Otherwise falls back to the global storage (public + global custom fallback). + + When ``skill_storage`` is provided, load from that request-scoped instance + directly and bypass the process cache. """ from deerflow.skills.mutations.guard import owner_is_managed + if skill_storage is not None: + # An injected storage is request-scoped; bypass the process cache so a + # later request with the same app_config cannot observe this tree. + return list(skill_storage.load_skills(enabled_only=True)) + if user_id is not None and (app_config is None or owner_is_managed(user_id)): # Without an explicit config, resolve the user storage on each call. # Enrolled owners also bypass the process-local LRU. The guarded loader @@ -909,6 +922,7 @@ def get_skills_prompt_section( *, app_config: AppConfig | None = None, user_id: str | None = None, + skill_storage: SkillStorage | None = None, skill_names: frozenset[str] | None = None, ) -> str: """Generate the skills prompt section. @@ -916,7 +930,8 @@ def get_skills_prompt_section( When *skill_names* is provided, renders a compact ```` (names only) so the LLM can discover skills via ``describe_skill``. When omitted, falls back to the legacy full-metadata ```` rendering for - backward compatibility. + backward compatibility. When *skill_storage* is provided, both the enabled + and disabled skill lists come from that request-scoped instance. """ if app_config is None: try: @@ -938,6 +953,8 @@ def get_skills_prompt_section( container_base_path = app_config.skills.container_path skill_evolution_enabled = app_config.skill_evolution.enabled + if skill_storage is not None: + container_base_path = skill_storage.get_container_root() skill_evolution_section = _build_skill_evolution_section(skill_evolution_enabled) # ── Deferred discovery path — storage not needed (caller supplies names) ─ @@ -951,14 +968,16 @@ def get_skills_prompt_section( ) # ── Legacy full-metadata path — load ALL skills for disabled-skill section - if user_id: + if skill_storage is not None: + storage = skill_storage + elif user_id: storage = get_or_new_user_skill_storage(user_id, app_config=app_config) else: storage = get_or_new_skill_storage(app_config=app_config) all_skills = storage.load_skills(enabled_only=False) disabled_skills = [s for s in all_skills if not s.enabled] - skills = get_enabled_skills_for_config(app_config, user_id=user_id) + skills = get_enabled_skills_for_config(app_config, user_id=user_id, skill_storage=skill_storage) if not skills and not disabled_skills and not skill_evolution_enabled: return "" @@ -1112,6 +1131,7 @@ def apply_prompt_template( agent_soul: str | None = None, available_skills: set[str] | None = None, app_config: AppConfig | None = None, + skill_storage: SkillStorage | None = None, deferred_names: frozenset[str] = frozenset(), mcp_routing_hints_section: str = "", user_id: str | None = None, @@ -1182,6 +1202,7 @@ def apply_prompt_template( available_skills, app_config=app_config, user_id=user_id, + skill_storage=skill_storage, skill_names=skill_names, ) diff --git a/backend/packages/harness/deerflow/agents/middlewares/skill_activation_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/skill_activation_middleware.py index 6b07db293a..67028a78c7 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/skill_activation_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/skill_activation_middleware.py @@ -126,6 +126,7 @@ class SkillActivationMiddleware(AgentMiddleware): user_id: str | None = None, slash_source_owner_token: str, skill_authorization: ResolvedSkillAuthorization | None = None, + skill_storage: SkillStorage | None = None, ) -> None: super().__init__() if not isinstance(slash_source_owner_token, str) or not slash_source_owner_token: @@ -135,6 +136,7 @@ class SkillActivationMiddleware(AgentMiddleware): self._user_id = user_id self._slash_source_owner_token = slash_source_owner_token self._skill_authorization = skill_authorization + self._skill_storage = skill_storage def _activation_allowed(self, skill_name: str, *, activation_decisions: ActivationDecisions | None = None) -> bool: """Action-scoped ``skill:activate`` check for explicit slash activation. @@ -272,6 +274,8 @@ class SkillActivationMiddleware(AgentMiddleware): } def _storage(self) -> SkillStorage: + if self._skill_storage is not None: + return self._skill_storage if self._user_id is not None: return get_or_new_user_skill_storage(self._user_id, app_config=self._app_config) if self._app_config is not None: diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py index 169dc531ad..cf7d587abc 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py @@ -33,6 +33,7 @@ from deerflow.agents.middlewares.tool_result_meta import ( from deerflow.config.app_config import AppConfig from deerflow.config.summarization_config import DEFAULT_SKILL_FILE_READ_TOOL_NAMES from deerflow.constants import DEFAULT_SKILLS_CONTAINER_PATH +from deerflow.skills.storage.skill_storage import SkillStorage from deerflow.subagents.status_contract import ( format_subagent_result_message, make_subagent_additional_kwargs, @@ -93,11 +94,19 @@ def _stamp_task_exception_status(message: ToolMessage, *, tool_name: str, error: class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]): """Convert tool exceptions into error ToolMessages so the run can continue.""" - def __init__(self, *, app_config: AppConfig | None = None, skill_authorization=None, user_id: str | None = None) -> None: + def __init__( + self, + *, + app_config: AppConfig | None = None, + skill_authorization=None, + user_id: str | None = None, + skill_storage: SkillStorage | None = None, + ) -> None: super().__init__() self._app_config = app_config self._skill_authorization = skill_authorization self._user_id = user_id + self._skill_storage = skill_storage if app_config is None: self._skill_read_tool_names = frozenset(DEFAULT_SKILL_FILE_READ_TOOL_NAMES) self._skills_root = DEFAULT_SKILLS_CONTAINER_PATH @@ -133,6 +142,8 @@ class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]): # or per-user custom skills would never resolve to their Skill.name. from deerflow.skills.storage import get_or_new_skill_storage, get_or_new_user_skill_storage + if self._skill_storage is not None: + return self._skill_storage if self._user_id is not None: return get_or_new_user_skill_storage(self._user_id, app_config=self._app_config) if self._app_config is not None: @@ -409,6 +420,7 @@ def _build_runtime_middlewares( owns_agent_skill_projection: bool = True, skill_authorization=None, user_id: str | None = None, + skill_storage: SkillStorage | None = None, ) -> list[AgentMiddleware]: """Build shared base middlewares for agent execution.""" from deerflow.agents.middlewares.input_sanitization_middleware import InputSanitizationMiddleware @@ -457,6 +469,7 @@ def _build_runtime_middlewares( lazy_init=lazy_init, available_skills=available_skills, owns_agent_skill_projection=owns_agent_skill_projection, + skill_storage=skill_storage, ) ) @@ -569,7 +582,14 @@ def _build_runtime_middlewares( tail.append(ToolProgressMiddleware.from_config(tool_progress_config)) - tail.append(ToolErrorHandlingMiddleware(app_config=app_config, skill_authorization=skill_authorization, user_id=user_id)) + tail.append( + ToolErrorHandlingMiddleware( + app_config=app_config, + skill_authorization=skill_authorization, + user_id=user_id, + skill_storage=skill_storage, + ) + ) # Artifact capture is a `before_model` hook that reads state messages, so # its position in the tool-execution wrap chain is functionally irrelevant: # it always sees the normalized results stored in state, and error results @@ -602,6 +622,7 @@ def build_lead_runtime_middlewares( owns_agent_skill_projection: bool = True, skill_authorization=None, user_id: str | None = None, + skill_storage: SkillStorage | None = None, ) -> list[AgentMiddleware]: """Middlewares shared by lead agent runtime before lead-only middlewares.""" return _build_runtime_middlewares( @@ -618,6 +639,7 @@ def build_lead_runtime_middlewares( authorization_infrastructure_tools=((deferred_setup.tool_search_tool,) if authorization_provider is not None and deferred_setup is not None and deferred_setup.tool_search_tool is not None else ()), skill_authorization=skill_authorization, user_id=user_id, + skill_storage=skill_storage, ) @@ -634,13 +656,24 @@ def build_subagent_runtime_middlewares( authorization_provider=None, skill_authorization=None, extensions=None, + skill_storage: SkillStorage | None = None, ) -> list[AgentMiddleware]: - """Middlewares shared by subagent runtime before subagent-only middlewares.""" + """Middlewares shared by subagent runtime before subagent-only middlewares. + + ``skill_storage`` is available to callers that build a subagent chain + directly. The built-in ``task`` tool does not forward the lead's injected + storage yet, so its subagent activation keeps the user-scoped default. + """ if app_config is None: from deerflow.config import get_app_config app_config = get_app_config() + if skill_storage is not None: + from deerflow.skills.storage.skill_storage import validate_injected_skill_storage + + validate_injected_skill_storage(skill_storage, container_root=app_config.skills.container_path, user_id=user_id) + from deerflow.extensions import get_agent_build_extensions resolved_extensions = extensions if extensions is not None else get_agent_build_extensions() @@ -658,6 +691,7 @@ def build_subagent_runtime_middlewares( owns_agent_skill_projection=False, skill_authorization=skill_authorization, user_id=user_id, + skill_storage=skill_storage, ) # Enabled/configured skills are discoverable metadata, not authority over @@ -674,6 +708,7 @@ def build_subagent_runtime_middlewares( user_id=user_id, slash_source_owner_token=slash_source_owner_token, skill_authorization=skill_authorization, + skill_storage=skill_storage, ) ) if deferred_setup is not None and deferred_setup.deferred_names: diff --git a/backend/packages/harness/deerflow/sandbox/middleware.py b/backend/packages/harness/deerflow/sandbox/middleware.py index fbf33cd485..e21f51b026 100644 --- a/backend/packages/harness/deerflow/sandbox/middleware.py +++ b/backend/packages/harness/deerflow/sandbox/middleware.py @@ -2,7 +2,7 @@ import asyncio import logging from collections.abc import Awaitable, Callable, Mapping from dataclasses import replace as dc_replace -from typing import NotRequired, override +from typing import TYPE_CHECKING, NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware @@ -36,6 +36,9 @@ from deerflow.sandbox.prewarm import close_sandbox_prewarm, start_sandbox_prewar from deerflow.sandbox.sandbox_provider import get_initialized_sandbox_provider from deerflow.utils.file_io import await_drained +if TYPE_CHECKING: + from deerflow.skills.storage.skill_storage import SkillStorage + logger = logging.getLogger(__name__) NETWORK_POLICY_HUMAN_INPUT_SOURCE = "sandbox_network" @@ -72,6 +75,7 @@ class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]): *, available_skills: set[str] | None = None, owns_agent_skill_projection: bool = True, + skill_storage: "SkillStorage | None" = None, ): """Initialize sandbox middleware. @@ -83,11 +87,13 @@ class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]): rebuild the thread's physical skill projection. Delegated subagents share the lead thread sandbox and must preserve the lead-owned view instead of applying their discovery policy to it. + skill_storage: Explicit catalog for the lead-owned thread projection. """ super().__init__() self._lazy_init = lazy_init self._available_skills = set(available_skills) if available_skills is not None else None self._owns_agent_skill_projection = owns_agent_skill_projection + self._skill_storage = skill_storage def _prepare_agent_skill_projection(self, thread_id: str, *, user_id: str): """Build the run's physical skill view before any sandbox is reused.""" @@ -103,12 +109,12 @@ class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]): # Preserve the zero-copy shared view for ordinary threads. A thread # that previously used a restricted Agent keeps its stable mount root; # an unrestricted run repopulates that root with all enabled skills. - if self._available_skills is None and not get_paths().thread_skills_view_dir(thread_id, user_id=user_id).exists(): + if self._skill_storage is None and self._available_skills is None and not get_paths().thread_skills_view_dir(thread_id, user_id=user_id).exists(): return None provider = get_sandbox_provider() if not provider.supports_agent_skill_isolation: - if self._available_skills is not None: + if self._available_skills is not None or self._skill_storage is not None: raise SandboxRuntimeError(f"Sandbox provider {provider.__class__.__name__} cannot enforce per-Agent skill filesystem isolation") # The thread projection may have been created under a different # provider. An unrestricted run does not need that policy view and @@ -120,6 +126,11 @@ class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]): from deerflow.skills.storage import get_or_new_user_skill_storage app_config = get_app_config() + if self._skill_storage is not None: + from deerflow.skills.storage.skill_storage import validate_injected_skill_storage + + validate_injected_skill_storage(self._skill_storage, container_root=app_config.skills.container_path, user_id=user_id) + return ensure_thread_skill_projection(self._skill_storage, thread_id, self._available_skills, projection_user_id=user_id) storage = get_or_new_user_skill_storage(user_id, app_config=app_config) return ensure_thread_skill_projection(storage, thread_id, self._available_skills) diff --git a/backend/packages/harness/deerflow/skills/projection.py b/backend/packages/harness/deerflow/skills/projection.py index bb367c11f0..886cec5a1b 100644 --- a/backend/packages/harness/deerflow/skills/projection.py +++ b/backend/packages/harness/deerflow/skills/projection.py @@ -71,15 +71,19 @@ def get_skill_projection_paths(storage: SkillStorage) -> SkillProjectionPaths: ) -def get_thread_skill_projection_paths(storage: SkillStorage, thread_id: str) -> SkillProjectionPaths: +def get_thread_skill_projection_paths(storage: SkillStorage, thread_id: str, *, projection_user_id: str | None = None) -> SkillProjectionPaths: """Return stable category roots for one user's thread policy view.""" from deerflow.config.paths import get_paths - paths = getattr(storage, "_paths", None) or get_paths() - user_id = getattr(storage, "user_id", None) - if user_id is None: - raise ValueError("Thread skill projections require user-scoped skill storage") - root = paths.thread_skills_view_dir(thread_id, user_id=user_id) + if projection_user_id is None: + projection_user_id = getattr(storage, "user_id", None) + if projection_user_id is None: + raise ValueError("Thread skill projections require user-scoped skill storage") + paths = getattr(storage, "_paths", None) or get_paths() + else: + # Providers find a request projection at the run user's thread path. + paths = get_paths() + root = paths.thread_skills_view_dir(thread_id, user_id=projection_user_id) return SkillProjectionPaths( public=root / SkillCategory.PUBLIC.value, custom=root / SkillCategory.CUSTOM.value, @@ -517,8 +521,16 @@ def _thread_source_signature( """Sign every input that changes a thread's effective skill view.""" digest = hashlib.sha256() digest.update(f"policy-version:{_THREAD_PROJECTION_POLICY_VERSION}\0".encode()) - digest.update(f"public:{_source_signature(storage, 'public')}\0".encode()) - digest.update(f"user:{_source_signature(storage, 'user')}\0".encode()) + host_root = storage.get_skills_root_path() + digest.update(f"host-root:{host_root}\0".encode()) + if getattr(storage, "user_id", None) is None: + # Local request catalogs keep every category under their own host root. + for category in SkillCategory: + _update_tree_digest(digest, host_root / category.value, category.value, follow_package_directory_symlinks=True) + digest.update(json.dumps(_extensions_state(), sort_keys=True, separators=(",", ":")).encode()) + else: + digest.update(f"public:{_source_signature(storage, 'public')}\0".encode()) + digest.update(f"user:{_source_signature(storage, 'user')}\0".encode()) policy = None if allowed_skills is None else sorted(allowed_skills) digest.update(json.dumps(policy, separators=(",", ":"), ensure_ascii=True).encode()) return digest.hexdigest() @@ -703,30 +715,35 @@ def ensure_thread_skill_projection( storage: SkillStorage, thread_id: str, allowed_skills: set[str] | None, + *, + projection_user_id: str | None = None, ) -> SkillProjectionPaths | None: from deerflow.skills.mutations.guard import managed_global_read, managed_read # Global -> owner -> thread. No fresh-view fast path bypasses recovery. with managed_global_read(storage): with managed_read(storage): - return _ensure_thread_skill_projection(storage, thread_id, allowed_skills) + return _ensure_thread_skill_projection(storage, thread_id, allowed_skills, projection_user_id=projection_user_id) def _ensure_thread_skill_projection( storage: SkillStorage, thread_id: str, allowed_skills: set[str] | None, + *, + projection_user_id: str | None = None, ) -> SkillProjectionPaths | None: """Ensure the filesystem view for one run's effective Agent skill policy. ``None`` keeps the existing shared projection for threads that have never needed policy isolation. Once a thread has a scoped view, later unrestricted runs rebuild that same stable mount with all enabled skills so switching - agents cannot leave the thread accidentally restricted. + agents cannot leave the thread accidentally restricted. An explicit + projection owner selects the request catalog even without an allowlist. """ - paths = get_thread_skill_projection_paths(storage, thread_id) + paths = get_thread_skill_projection_paths(storage, thread_id, projection_user_id=projection_user_id) scope_root = paths.public.parent - if allowed_skills is None and not scope_root.exists(): + if projection_user_id is None and allowed_skills is None and not scope_root.exists(): return None try: diff --git a/backend/packages/harness/deerflow/skills/storage/skill_storage.py b/backend/packages/harness/deerflow/skills/storage/skill_storage.py index f1a23241e6..c0ef51640f 100644 --- a/backend/packages/harness/deerflow/skills/storage/skill_storage.py +++ b/backend/packages/harness/deerflow/skills/storage/skill_storage.py @@ -20,6 +20,17 @@ logger = logging.getLogger(__name__) _SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") +def validate_injected_skill_storage(storage: SkillStorage, *, container_root: str, user_id: str | None = None) -> None: + """Keep an injected catalog within the configured mount and owner scope.""" + from deerflow.config.paths import make_safe_user_id + + if storage.get_container_root() != container_root: + raise ValueError("Injected skill storage container root must match skills.container_path") + storage_owner = getattr(storage, "user_id", None) + if storage_owner is not None and user_id is not None and storage_owner != make_safe_user_id(user_id): + raise ValueError("Injected skill storage owner must match the run user") + + def walk_skill_directories(root: Path) -> Iterable[tuple[str, list[str], list[str]]]: """Follow directory links, but prune links back to the current ancestors. diff --git a/backend/tests/test_checkpoint_mode.py b/backend/tests/test_checkpoint_mode.py index a3ee0d17ce..b7906ccf2d 100644 --- a/backend/tests/test_checkpoint_mode.py +++ b/backend/tests/test_checkpoint_mode.py @@ -173,7 +173,7 @@ def test_yaml_mode_change_is_rejected_when_graph_is_reconstructed(tmp_path, monk write_config("full") monkeypatch.setenv("DEER_FLOW_CONFIG_PATH", str(config_path)) monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None) - monkeypatch.setattr(lead_agent, "_assemble_lead_agent", lambda config, *, app_config: SimpleNamespace(graph=object())) + monkeypatch.setattr(lead_agent, "_assemble_lead_agent", lambda config, *, app_config, skill_storage=None: SimpleNamespace(graph=object())) reset_app_config() try: lead_agent.make_lead_agent({"configurable": {}}) @@ -215,7 +215,7 @@ def test_yaml_snapshot_frequency_change_is_rejected_when_graph_is_reconstructed( monkeypatch.setenv("DEER_FLOW_CONFIG_PATH", str(config_path)) monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None) monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_snapshot_frequency", None) - monkeypatch.setattr(lead_agent, "_assemble_lead_agent", lambda config, *, app_config: SimpleNamespace(graph=object())) + monkeypatch.setattr(lead_agent, "_assemble_lead_agent", lambda config, *, app_config, skill_storage=None: SimpleNamespace(graph=object())) reset_app_config() try: lead_agent.make_lead_agent({"configurable": {}}) @@ -317,7 +317,7 @@ def test_direct_langgraph_request_cannot_select_delta_in_full_process( monkeypatch.setattr( lead_agent, "_assemble_lead_agent", - lambda config, *, app_config: SimpleNamespace(graph=object()), + lambda config, *, app_config, skill_storage=None: SimpleNamespace(graph=object()), ) lead_agent.make_lead_agent(config) @@ -344,7 +344,7 @@ def test_make_lead_agent_freezes_delta_snapshot_frequency_from_app_config( monkeypatch.setattr( lead_agent, "_assemble_lead_agent", - lambda config, *, app_config: SimpleNamespace(graph=object()), + lambda config, *, app_config, skill_storage=None: SimpleNamespace(graph=object()), ) lead_agent.make_lead_agent({"configurable": {}}) @@ -380,7 +380,7 @@ def test_gateway_runtime_app_config_can_supply_its_frozen_internal_mode( monkeypatch.setattr( lead_agent, "_assemble_lead_agent", - lambda config, *, app_config: SimpleNamespace(graph=object()), + lambda config, *, app_config, skill_storage=None: SimpleNamespace(graph=object()), ) lead_agent.make_lead_agent(config) diff --git a/backend/tests/test_lead_agent_model_resolution.py b/backend/tests/test_lead_agent_model_resolution.py index 82e67f3d1b..00c8455374 100644 --- a/backend/tests/test_lead_agent_model_resolution.py +++ b/backend/tests/test_lead_agent_model_resolution.py @@ -177,7 +177,7 @@ def test_make_lead_agent_uses_server_auth_identity_for_all_user_scoped_inputs(mo captured["agent_config_user_id"] = user_id return AgentConfig(name=name) - def _load_skills(available_skills, *, app_config, user_id=None): + def _load_skills(available_skills, *, app_config, user_id=None, skill_storage=None): captured["skills_user_id"] = user_id return [] @@ -232,7 +232,7 @@ def test_make_lead_agent_applies_custom_agent_memory_opt_out(monkeypatch): "load_agent_config", lambda name, *, user_id=None: AgentConfig(name=name, memory_enabled=False), ) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: []) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: []) def _build_middlewares(*args, **kwargs): captured["middleware_memory_enabled"] = kwargs.get("memory_enabled") @@ -491,9 +491,10 @@ def test_public_make_lead_agent_does_not_take_mode_from_runtime_context(monkeypa monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None) - def _capture(config, *, app_config): + def _capture(config, *, app_config, skill_storage=None): captured["config"] = config captured["app_config"] = app_config + captured["skill_storage"] = skill_storage return lead_agent_module.LeadAgentAssembly(graph=object(), descriptor=object()) monkeypatch.setattr(lead_agent_module, "_assemble_lead_agent", _capture) @@ -511,6 +512,60 @@ def test_public_make_lead_agent_does_not_take_mode_from_runtime_context(monkeypa assert captured["app_config"] is app_config +def test_assemble_lead_agent_threads_skill_storage_to_build_middlewares(model_control_assembly, monkeypatch, tmp_path): + """The public embedding entrypoint must preserve the injected storage through + both assembly hops, not only in `build_middlewares`.""" + from deerflow.runtime import checkpoint_mode + from deerflow.skills.storage.local_skill_storage import LocalSkillStorage + + app_config, *_ = model_control_assembly + captured: dict[str, object] = {} + + def _capture(*args, **kwargs): + captured["skill_storage"] = kwargs.get("skill_storage") + return [] + + monkeypatch.setattr(lead_agent_module, "build_middlewares", _capture) + monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None) + monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_snapshot_frequency", None) + + app_config.skills.container_path = "/mnt/request-skills" + app_config.skills.deferred_discovery = True + skill_file = tmp_path / "public" / "request-only" / "SKILL.md" + skill_file.parent.mkdir(parents=True) + skill_file.write_text("---\nname: request-only\ndescription: Request-only skill\n---\n\nSkill body.\n", encoding="utf-8") + monkeypatch.setattr(ExtensionsConfig, "from_file", lambda: ExtensionsConfig()) + injected = LocalSkillStorage(host_path=str(tmp_path), container_path=app_config.skills.container_path) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda *args, **kwargs: kwargs["skill_storage"].load_skills(enabled_only=True)) + result = lead_agent_module.assemble_lead_agent( + {"context": {"model_name": "default"}}, + app_config=app_config, + skill_storage=injected, + ) + + assert captured["skill_storage"] is injected + describe = next(tool for tool in result.graph["tools"] if tool.name == "describe_skill") + result = describe.invoke({"args": {"name": "select:request-only"}, "name": "describe_skill", "type": "tool_call", "id": "describe-request"}) + assert "/mnt/request-skills/public/request-only/SKILL.md" in result.update["messages"][0].content + + +def test_assemble_lead_agent_rejects_mismatched_skill_mount(model_control_assembly, monkeypatch, tmp_path): + from deerflow.runtime import checkpoint_mode + from deerflow.skills.storage.local_skill_storage import LocalSkillStorage + + app_config, *_ = model_control_assembly + monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None) + monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_snapshot_frequency", None) + storage = LocalSkillStorage(host_path=str(tmp_path), container_path="/mnt/request-skills") + + with pytest.raises(ValueError, match=r"skills\.container_path"): + lead_agent_module.assemble_lead_agent( + {"context": {"model_name": "default"}}, + app_config=app_config, + skill_storage=storage, + ) + + def test_make_lead_agent_uses_runtime_app_config_from_context_without_global_read(monkeypatch): app_config = _make_app_config([_make_model("context-model", supports_thinking=False)]) diff --git a/backend/tests/test_lead_agent_skills.py b/backend/tests/test_lead_agent_skills.py index 0857b56657..00d7f067bf 100644 --- a/backend/tests/test_lead_agent_skills.py +++ b/backend/tests/test_lead_agent_skills.py @@ -265,7 +265,7 @@ def test_make_lead_agent_empty_skills_passed_correctly(monkeypatch): monkeypatch.setattr(lead_agent_module, "_resolve_model_name", lambda x=None, **kwargs: "default-model") monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: "model") monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: []) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: []) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: []) monkeypatch.setattr(lead_agent_module, "build_middlewares", lambda *args, **kwargs: []) monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) @@ -314,7 +314,7 @@ def test_make_lead_agent_custom_skill_allowlist_does_not_activate_tool_policy(mo monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=["restricted", "legacy"])) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("restricted", ["read_file", "web_search"]), _make_skill("legacy", None)]) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: [_make_skill("restricted", ["read_file", "web_search"]), _make_skill("legacy", None)]) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [NamedTool("task"), NamedTool("bash"), NamedTool("read_file"), NamedTool("web_search")]) mock_app_config = MagicMock() @@ -348,7 +348,7 @@ def test_make_lead_agent_all_legacy_skills_preserve_all_tools(monkeypatch): monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=None)) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("legacy", None)]) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: [_make_skill("legacy", None)]) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [NamedTool("bash"), NamedTool("read_file")]) mock_app_config = MagicMock() @@ -449,7 +449,7 @@ def test_default_lead_agent_does_not_apply_installed_skill_allowlists(monkeypatc monkeypatch.setattr( lead_agent_module, "_load_enabled_available_skills", - lambda available_skills, *, app_config, user_id=None: [_make_skill("skill-reviewer", ["review_skill_package"])], + lambda available_skills, *, app_config, user_id=None, skill_storage=None: [_make_skill("skill-reviewer", ["review_skill_package"])], ) monkeypatch.setattr( "deerflow.tools.get_available_tools", @@ -533,7 +533,7 @@ def test_make_lead_agent_drops_update_agent_on_github_channel(monkeypatch): monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=None)) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("legacy", None)]) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: [_make_skill("legacy", None)]) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [NamedTool("bash"), NamedTool("read_file")]) mock_app_config = MagicMock() @@ -572,7 +572,7 @@ def test_make_lead_agent_keeps_update_agent_on_non_webhook_channels(monkeypatch) monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=None)) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("legacy", None)]) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: [_make_skill("legacy", None)]) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [NamedTool("bash")]) mock_app_config = MagicMock() diff --git a/backend/tests/test_memory_tools.py b/backend/tests/test_memory_tools.py index c3d1a4f295..39a0b178d7 100644 --- a/backend/tests/test_memory_tools.py +++ b/backend/tests/test_memory_tools.py @@ -524,7 +524,7 @@ class TestModeGating: "load_agent_config", lambda name, *, user_id=None: SimpleNamespace(model=None, skills=None, tool_groups=None), ) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: []) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: []) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [_NamedTool("memory_search"), _NamedTool("bash")]) app_config = SimpleNamespace( @@ -560,7 +560,7 @@ class TestModeGating: "load_agent_config", lambda name, *, user_id=None: SimpleNamespace(model=None, skills=None, tool_groups=None), ) - monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: []) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None, skill_storage=None: []) monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [_NamedTool("bash"), _NamedTool("bash")]) app_config = SimpleNamespace( diff --git a/backend/tests/test_skill_projection.py b/backend/tests/test_skill_projection.py index a3d382480f..5ae295848b 100644 --- a/backend/tests/test_skill_projection.py +++ b/backend/tests/test_skill_projection.py @@ -398,6 +398,71 @@ def test_unrestricted_run_reuses_existing_thread_mount_with_full_enabled_view(pr assert {category: getattr(projected, category).stat().st_ino for category in ("public", "custom", "legacy", "integrations")} == category_inodes +@pytest.mark.parametrize("available_skills", [{"request-only"}, None], ids=["allowlist", "unrestricted"]) +@pytest.mark.parametrize("user_scoped", [True, False], ids=["user-scoped", "local"]) +def test_lead_projects_injected_skills_into_the_sandbox(projection_env, monkeypatch, available_skills, user_scoped) -> None: + from deerflow.agents.lead_agent.agent import build_middlewares + from deerflow.config.app_config import AppConfig + from deerflow.config.sandbox_config import SandboxConfig + from deerflow.sandbox.local.local_sandbox_provider import LocalSandboxProvider + from deerflow.skills.storage.local_skill_storage import LocalSkillStorage + + env = projection_env + _write_skill(env.skills_root / "public", "default-only") + app_config = AppConfig(sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider", allow_host_bash=False)) + app_config.skills.path = str(env.skills_root) + request_root = env.root / "request-skills" + skill = _write_skill(request_root / "public", "request-only") + (skill.parent / "info.txt").write_text("request support file", encoding="utf-8") + _write_skill(request_root / "public", "another-skill") + _write_skill(request_root / "public", "disabled-skill") + env.extensions.skills["disabled-skill"] = SkillStateConfig(enabled=False) + kwargs = {"host_path": str(request_root), "app_config": app_config} + storage = UserScopedSkillStorage("alice", **kwargs) if user_scoped else LocalSkillStorage(**kwargs) + + monkeypatch.setattr("deerflow.config.get_app_config", lambda: app_config) + monkeypatch.setattr("deerflow.sandbox.security.get_app_config", lambda: app_config) + provider = LocalSandboxProvider() + monkeypatch.setattr("deerflow.sandbox.middleware.get_sandbox_provider", lambda: provider) + middlewares = build_middlewares( + {"configurable": {}}, + app_config=app_config, + model_name=None, + user_id="alice", + available_skills=available_skills, + skill_storage=storage, + ) + sandbox_middleware = next(m for m in middlewares if isinstance(m, SandboxMiddleware)) + thread_id = "thread-injected" + projection = sandbox_middleware._prepare_agent_skill_projection(thread_id, user_id="alice") + assert projection is not None + + sandbox = provider.get(provider.acquire(thread_id, user_id="alice")) + assert sandbox is not None + assert sandbox.read_file("/mnt/skills/public/request-only/SKILL.md") == skill.read_text(encoding="utf-8") + assert sandbox.read_file("/mnt/skills/public/request-only/info.txt") == "request support file" + assert (projection.public / "another-skill").exists() == (available_skills is None) + assert not (projection.public / "default-only").exists() + assert not (projection.public / "disabled-skill").exists() + + restored = SandboxMiddleware()._prepare_agent_skill_projection(thread_id, user_id="alice") + assert restored == projection + assert not (projection.public / "request-only").exists() + assert (projection.public / "default-only" / "SKILL.md").is_file() + + +def test_lead_rejects_projection_from_another_users_storage(projection_env, monkeypatch) -> None: + env = projection_env + monkeypatch.setattr("deerflow.config.get_app_config", lambda: env.config) + monkeypatch.setattr("deerflow.sandbox.middleware.get_sandbox_provider", lambda: SimpleNamespace(supports_agent_skill_isolation=True)) + middleware = SandboxMiddleware(skill_storage=env.storage) + + with pytest.raises(ValueError, match="storage owner"): + middleware._prepare_agent_skill_projection("thread-wrong-owner", user_id="bob") + + assert not env.paths.thread_skills_view_dir("thread-wrong-owner", user_id="alice").exists() + + def test_subagent_non_owner_preserves_restricted_lead_projection( projection_env, monkeypatch, diff --git a/backend/tests/test_skills_authorization.py b/backend/tests/test_skills_authorization.py index 3d5f471fbd..3daa7a05be 100644 --- a/backend/tests/test_skills_authorization.py +++ b/backend/tests/test_skills_authorization.py @@ -2582,6 +2582,97 @@ def test_lead_chain_wires_durable_render_filter(): assert middlewares.index(activations[0]) < middlewares.index(durables[0]), "activation must wrap outside durable so the per-step decisions are published before the renderer reads them" +def test_lead_chain_prefers_injected_skill_storage_over_user_scoped_storage(): + """Embedding hosts can supply request-scoped storage; it must win over the + user-scoped default even when a user_id is present.""" + from deerflow.agents.lead_agent.agent import build_middlewares + from deerflow.agents.middlewares.skill_activation_middleware import SkillActivationMiddleware + + injected = SimpleNamespace(get_container_root=lambda: "/mnt/skills") + middlewares = build_middlewares( + {"configurable": {}}, + app_config=_make_app_config(), + model_name="gpt-4", + user_id="user-123", + skill_storage=injected, + ) + + activation = next(m for m in middlewares if isinstance(m, SkillActivationMiddleware)) + assert activation._storage() is injected + + +def test_tool_error_handling_prefers_injected_skill_storage(): + """Skill-read canonicalization must use the same request-scoped tree.""" + from deerflow.agents.middlewares.tool_error_handling_middleware import ToolErrorHandlingMiddleware + + injected = SimpleNamespace(get_container_root=lambda: "/mnt/skills") + middleware = ToolErrorHandlingMiddleware( + app_config=_make_app_config(), + user_id="user-123", + skill_storage=injected, + ) + + assert middleware._storage() is injected + + +def test_subagent_chain_accepts_injected_skill_storage(): + """Direct subagent-chain builders can keep the same request-scoped tree.""" + from deerflow.agents.middlewares.skill_activation_middleware import SkillActivationMiddleware + from deerflow.agents.middlewares.tool_error_handling_middleware import build_subagent_runtime_middlewares + + injected = SimpleNamespace(get_container_root=lambda: "/mnt/skills") + middlewares = build_subagent_runtime_middlewares( + app_config=_make_app_config(), + user_id="user-456", + skill_storage=injected, + ) + + activation = next(m for m in middlewares if isinstance(m, SkillActivationMiddleware)) + assert activation._storage() is injected + + +def test_skills_prompt_section_uses_injected_skill_storage(): + """Prompt-side skill discovery must read the same request-scoped tree.""" + from deerflow.agents.lead_agent.prompt import get_skills_prompt_section + + calls: list[bool] = [] + + def _load_skills(*, enabled_only: bool): + calls.append(enabled_only) + return [] + + storage = SimpleNamespace(load_skills=_load_skills, get_container_root=lambda: "/mnt/skills") + + section = get_skills_prompt_section( + app_config=_make_app_config(), + user_id="user-123", + skill_storage=storage, + ) + + assert section == "" + assert calls == [False, True] + + +def test_prompt_renders_paths_from_the_injected_skill_storage(tmp_path, monkeypatch): + from deerflow.agents.lead_agent.prompt import get_skills_prompt_section + from deerflow.agents.middlewares.skill_activation_middleware import SkillActivationMiddleware + from deerflow.config.extensions_config import ExtensionsConfig + from deerflow.skills.storage.local_skill_storage import LocalSkillStorage + + monkeypatch.setattr(ExtensionsConfig, "from_file", lambda: ExtensionsConfig()) + skill_dir = tmp_path / "public" / "request-only" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("---\nname: request-only\ndescription: Request-only skill\n---\n\nSkill body.\n", encoding="utf-8") + app_config = _make_app_config() + storage = LocalSkillStorage(host_path=str(tmp_path), container_path="/mnt/request-skills") + section = get_skills_prompt_section(app_config=app_config, skill_storage=storage) + activation = SkillActivationMiddleware(app_config=app_config, skill_storage=storage, slash_source_owner_token="test") + resolved = activation._resolve_activation("/request-only") + + assert resolved.activation is not None + assert resolved.activation.container_file_path in section + + def test_subagent_chain_wires_durable_render_filter(): """Same wiring contract for the subagent builder's DurableContextMiddleware.""" from deerflow.agents.middlewares.durable_context_middleware import DurableContextMiddleware diff --git a/backend/tests/test_tool_error_handling_middleware.py b/backend/tests/test_tool_error_handling_middleware.py index 04819d8e5e..7a5f67b097 100644 --- a/backend/tests/test_tool_error_handling_middleware.py +++ b/backend/tests/test_tool_error_handling_middleware.py @@ -455,6 +455,7 @@ def test_lead_runtime_middlewares_pass_agent_skills_to_sandbox( "lazy_init": True, "available_skills": {"allowed-skill"}, "owns_agent_skill_projection": True, + "skill_storage": None, } @@ -484,6 +485,7 @@ def test_lead_runtime_middlewares_can_delegate_skill_projection_ownership( "lazy_init": True, "available_skills": {"bootstrap"}, "owns_agent_skill_projection": False, + "skill_storage": None, }