Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
Feature/remote pipe func (#1036)
Thomas Hebrard851a40855426
diff --git a/.drift/acks/config-docs.toml b/.drift/acks/config-docs.tomlindex 0181d769a..6f3ff9966 100644--- a/.drift/acks/config-docs.toml+++ b/.drift/acks/config-docs.toml@@ -1,19 +1,20 @@contract = "config-docs"-digest = "sha256:452d8805882407ae15c3f0f977b6a1ef4dd61b1282d354a8c14bb2fa9387e7f0"-reviewed_by = "Louis Choquel"-reviewed_at = "2026-07-11T15:46:20Z"-rationale = "The trigger change is dev's Python-3.10 drop (StrEnum import swap in img_gen_job_components.py), merged in via the Phase-M dev merge — no config field, default, or documented behavior changed; reviewed, no doc change needed."+digest = "sha256:5edb794b698cc0513be0e904c3a2f82a1a7ff470e86d05df5e710dd30368ee25"+reviewed_by = "Claude (Fable 5)"+reviewed_at = "2026-07-16T09:45:00Z"+rationale = "Trigger diff is comment-only wording in pipelex.toml + pipe_func_config.py: removed the stale claim of a core 'local_sandbox' execution mode (nobody registers it; core ships only 'direct', our Daytona plugin ships 'daytona') and switched plugin mentions to the 'our Daytona sandbox plugin' style. No field, type, or default changed. Reviewed docs/configuration: pipe_func_config still deliberately has no page (like its internal siblings), library-config.md's @pipe_func registration prose is unaffected, and no configuration doc mentions local_sandbox — nothing to update."[trigger_files]"pipelex/cogt/config_cogt.py" = "blob:fca7b96f9147122b6b8300471cac637b05fed1ee""pipelex/cogt/img_gen/img_gen_job_components.py" = "blob:084985080413fd8d6c3b1b9b0747020cb0161858"-"pipelex/pipelex.toml" = "blob:8952bf3f4367ce4c761fa24aeda35e5aba0ea24a"+"pipelex/pipelex.toml" = "blob:e646e431b5db2e467bc962b738be7bc9f3b3ffb8""pipelex/system/configuration/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc""pipelex/system/configuration/config_check.py" = "blob:12cf96754989b59ffced39521e3fe11606058d8f""pipelex/system/configuration/config_loader.py" = "blob:af3ba71ed4e589cec42cb197d7d11539cea50ecd""pipelex/system/configuration/config_model.py" = "blob:83b29dc6e93393c9b98c4353636caf0135c80339""pipelex/system/configuration/config_root.py" = "blob:c7d43851270912d17413cfc6a511247d3c7cc160"-"pipelex/system/configuration/configs.py" = "blob:8f0fc7f74b3762f2d517da49bf8f0ee8ad0b941d"+"pipelex/system/configuration/configs.py" = "blob:281f0674f4403d636ad4a99d1954004849939157"+"pipelex/system/configuration/pipe_func_config.py" = "blob:df1cbd3698d51c96d8fa8a8c6fdf1c6be57e5771""pipelex/system/telemetry/telemetry_config.py" = "blob:b6912e8be8932b65213dab23ac66372b8b45ca58""pipelex/tools/aws/aws_config.py" = "blob:4c0b30c6f500aaf0f4c25395fc361a20d2e7f828""pipelex/tools/log/log_config.py" = "blob:7b6d032ffea29d6ce60e8af7106f2d935bc18348"diff --git a/pipelex/config.py b/pipelex/config.pyindex a933bb033..bee2698b4 100644--- a/pipelex/config.py+++ b/pipelex/config.py@@ -1,4 +1,5 @@-from pipelex.hub import get_required_config+from pipelex.hub import get_optional_config, get_required_config+from pipelex.plugins.pipe_func_executor_registry import DIRECT_PIPE_FUNC_EXECUTION_MODEfrom pipelex.system.configuration.configs import PipelexConfig@@ -8,3 +9,30 @@ def get_config() -> PipelexConfig:msg = f"Expected {PipelexConfig}, but got {type(singleton_config)}"raise TypeError(msg)return singleton_config+++def get_pipe_func_execution_mode() -> str:+ """The selected PipeFunc execution mode in this process (non-raising; defaults to ``direct``).++ Read from the optional config (``pipelex.pipe_func_config.execution_mode``) so it is safe to call+ from pydantic validators that may run before the global config is set (e.g. very early boot or+ isolated unit tests). When no config is set, or it is not a PipelexConfig, the answer is+ ``direct`` — the in-process mode, which keeps the default path byte-identical to the pre-seam+ behavior. Selecting a sandbox backend is a deployment CONFIG concern (the hosted runner and the+ worker set it in their ``.pipelex`` overrides), not an env var.+ """+ optional_config = get_optional_config()+ if not isinstance(optional_config, PipelexConfig):+ return DIRECT_PIPE_FUNC_EXECUTION_MODE+ return optional_config.pipelex.pipe_func_config.execution_mode+++def is_pipe_func_sandbox_hosted() -> bool:+ """Whether PipeFunc runs out-of-process in this process (non-raising; defaults to local).++ Derived from the selected execution mode: core owns ``direct`` as the one in-process mode, and by+ the seam's invariant every other mode (``daytona``, …) is a remote/sandbox+ backend that transports the customer's source rather than importing it here. So library loading+ and the PipeFunc validators gate on this: ``True`` ⇒ capture source + skip callable inspection.+ """+ return get_pipe_func_execution_mode() != DIRECT_PIPE_FUNC_EXECUTION_MODEdiff --git a/pipelex/hub.py b/pipelex/hub.pyindex e32f9b331..17fca8ddc 100644--- a/pipelex/hub.py+++ b/pipelex/hub.py@@ -29,6 +29,7 @@ from pipelex.libraries.library import Libraryfrom pipelex.libraries.library_manager_abstract import LibraryManagerAbstractfrom pipelex.libraries.pipe.pipe_library_abstract import PipeLibraryAbstractfrom pipelex.observer.observer_protocol import ObserverProtocol+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocolfrom pipelex.pipeline.pipeline import Pipelinefrom pipelex.pipeline.pipeline_manager_abstract import PipelineManagerAbstractfrom pipelex.plugins.sdk_client_manager import SdkClientManager@@ -53,6 +54,7 @@ if TYPE_CHECKING:from pipelex.plugins.inference_backend_registry import InferenceBackendRegistryfrom pipelex.plugins.model_lister_registry import ModelListerRegistryfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistry+ from pipelex.plugins.pipe_func_executor_registry import PipeFuncExecutorRegistryfrom pipelex.plugins.secrets_provider_registry import SecretsProviderRegistryfrom pipelex.plugins.storage_provider_registry import StorageProviderRegistryfrom pipelex.tracing.event_log_protocol import EventLogProtocol@@ -93,9 +95,11 @@ class PipelexHub:self._bundle_validator_registry: BundleValidatorRegistry | None = Noneself._storage_provider_registry: StorageProviderRegistry | None = Noneself._secrets_provider_registry: SecretsProviderRegistry | None = None+ self._pipe_func_executor_registry: PipeFuncExecutorRegistry | None = Noneself._inference_manager: InferenceManagerProtocolself._report_delegate: ReportingProtocolself._content_generator: ContentGeneratorProtocol | None = None+ self._pipe_func_executor: PipeFuncExecutorProtocol | None = None# Keyless boot (``Pipelex.make(needs_inference=False)``) forces every run to DRY (eng# review D4): the backend still picks inline vs in-workflow on its own; the leaf mocks.# Consumed by ``PipeRunParamsFactory.make_run_params`` (the single writer of run_mode).@@ -222,6 +226,9 @@ class PipelexHub:def set_secrets_provider_registry(self, secrets_provider_registry: "SecretsProviderRegistry"):self._secrets_provider_registry = secrets_provider_registry+ def set_pipe_func_executor_registry(self, pipe_func_executor_registry: "PipeFuncExecutorRegistry"):+ self._pipe_func_executor_registry = pipe_func_executor_registry+def set_inference_manager(self, inference_manager: InferenceManagerProtocol):self._inference_manager = inference_manager@@ -231,6 +238,9 @@ class PipelexHub:def set_content_generator(self, content_generator: ContentGeneratorProtocol):self._content_generator = content_generator+ def set_pipe_func_executor(self, pipe_func_executor: PipeFuncExecutorProtocol):+ self._pipe_func_executor = pipe_func_executor+def set_dry_run_forced(self, *, is_forced: bool) -> None:self._is_dry_run_forced = is_forced@@ -375,6 +385,12 @@ class PipelexHub:raise RuntimeError(msg)return self._secrets_provider_registry+ def get_pipe_func_executor_registry(self) -> "PipeFuncExecutorRegistry":+ if self._pipe_func_executor_registry is None:+ msg = "PipeFuncExecutorRegistry is not initialized"+ raise RuntimeError(msg)+ return self._pipe_func_executor_registry+def get_inference_manager(self) -> InferenceManagerProtocol:return self._inference_manager@@ -387,6 +403,12 @@ class PipelexHub:raise RuntimeError(msg)return self._content_generator+ def get_required_pipe_func_executor(self) -> PipeFuncExecutorProtocol:+ if self._pipe_func_executor is None:+ msg = "PipeFuncExecutor is not initialized"+ raise RuntimeError(msg)+ return self._pipe_func_executor+# pipelexdef get_required_domain_library(self) -> DomainLibraryAbstract:@@ -491,6 +513,10 @@ def get_required_config() -> ConfigRoot:return get_pipelex_hub().get_required_config()+def get_optional_config() -> ConfigRoot | None:+ return get_pipelex_hub().get_optional_config()++def get_secrets_provider() -> SecretsProviderAbstract:return get_pipelex_hub().get_required_secrets_provider()@@ -564,6 +590,10 @@ def get_secrets_provider_registry() -> "SecretsProviderRegistry":return get_pipelex_hub().get_secrets_provider_registry()+def get_pipe_func_executor_registry() -> "PipeFuncExecutorRegistry":+ return get_pipelex_hub().get_pipe_func_executor_registry()++def get_inference_manager() -> InferenceManagerProtocol:return get_pipelex_hub().get_inference_manager()@@ -630,6 +660,34 @@ def get_content_generator() -> ContentGeneratorProtocol:return get_pipelex_hub().get_required_content_generator()+_pipe_func_executor_override: ContextVar[PipeFuncExecutorProtocol | None] = ContextVar("pipe_func_executor_override", default=None)+++@contextmanager+def scoped_pipe_func_executor(pipe_func_executor: PipeFuncExecutorProtocol) -> Generator[None, None, None]:+ """Set ``pipe_func_executor`` as the active executor for the scope, then restore the prior value on exit.++ The PipeFunc counterpart of :func:`scoped_content_generator`: in a process whose hub default+ executor dispatches PipeFunc steps out-of-process (a distributed-orchestrator worker), this scope+ lets an in-process run force a specific executor — e.g. the local one, so its PipeFunc steps run+ here instead of being re-dispatched. ContextVar-scoped like :func:`scoped_pipe_router`, so+ concurrent runs never cross-contaminate.+ """+ prev = _pipe_func_executor_override.get()+ _pipe_func_executor_override.set(pipe_func_executor)+ try:+ yield+ finally:+ _pipe_func_executor_override.set(prev)+++def get_pipe_func_executor() -> PipeFuncExecutorProtocol:+ override = _pipe_func_executor_override.get()+ if override is not None:+ return override+ return get_pipelex_hub().get_required_pipe_func_executor()++# pipelex@@ -810,7 +868,7 @@ def scoped_pipe_router(pipe_router: "PipeRouterProtocol") -> Generator[None, NonPrefer this over the raw ``set_pipe_router`` / ``teardown_current_pipe_router``pair internally: the raw teardown unconditionally resets the override to``None`` and so does not restore an outer override. The raw pair is kept- because the external ``pipelex-mistralai-workflows`` plugin depends on it.+ because our Mistral Workflows plugin depends on it."""prev = _current_pipe_router.get()_current_pipe_router.set(pipe_router)diff --git a/pipelex/libraries/library_crate.py b/pipelex/libraries/library_crate.pyindex 36d61bd1c..cdc41ffec 100644--- a/pipelex/libraries/library_crate.py+++ b/pipelex/libraries/library_crate.py@@ -35,8 +35,18 @@ class LibraryCrate(BaseModel):source_map: dict[str, str] = Field(default_factory=dict)"""concept_ref or pipe_ref -> source file path (for error reporting)"""+ python_sources: dict[str, str] = Field(default_factory=dict)+ """relpath (within the library dir) -> Python source text, captured WITHOUT importing.++ Carries the customer's PipeFunc and structure-class .py source alongside the method so it can+ travel to a sandbox and be registered + executed there. Populated only in sandbox-hosted load+ mode; empty for local/direct loads. Deliberately EXCLUDED from the fingerprint (see+ compute_fingerprint_from_content): the fingerprint represents library structure for dedupe, and+ folding source into it would break the structural-idempotency contract in load_from_crate.+ """+fingerprint: str = ""- """SHA-256 hex digest of the crate content (see compute_fingerprint_from_content / compute_normalized_fingerprint)."""+ """SHA-256 hex digest of the serialized concepts + pipes content (source is intentionally excluded)."""@staticmethoddef compute_fingerprint_from_content(diff --git a/pipelex/libraries/library_crate_factory.py b/pipelex/libraries/library_crate_factory.pyindex 94fdfa847..f48921689 100644--- a/pipelex/libraries/library_crate_factory.py+++ b/pipelex/libraries/library_crate_factory.py@@ -33,6 +33,8 @@ class LibraryCrateFactory:def make_from_blueprints(cls,blueprints: list[PipelexBundleBlueprint],+ *,+ python_sources: dict[str, str] | None = None,) -> LibraryCrate:"""Build a LibraryCrate from parsed bundle blueprints.@@ -47,6 +49,9 @@ class LibraryCrateFactory:Args:blueprints: List of parsed MTHDS bundle blueprints+ python_sources: Optional relpath -> Python source text captured (without importing) in+ sandbox-hosted load mode. Attached verbatim to the crate; intentionally NOT folded+ into the fingerprint (the fingerprint represents library structure for dedupe).Returns:A LibraryCrate with all content merged and fingerprinted@@ -151,6 +156,7 @@ class LibraryCrateFactory:pipes=pipes,domains=domains,source_map=source_map,+ python_sources=python_sources or {},fingerprint=fingerprint,)diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex d577544c3..2264b3d56 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -15,6 +15,7 @@ from typing_extensions import overrideimport pipelex.builder as builder_pkg # package import — used for __file__ pathfrom pipelex import logfrom pipelex.cli.installed_methods import find_method_by_full_address+from pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprintfrom pipelex.core.concepts.concept_factory import ConceptFactory@@ -102,6 +103,11 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints: dict[str, list[PipelexBundleBlueprint]] = {} # library_id -> accumulated blueprintsself._crate_cache: dict[str, LibraryCrate] = {} # library_id -> cached crate from get_crate()self._loaded_fingerprints: dict[str, set[str]] = {} # library_id -> set of loaded crate fingerprints+ # library_id -> {relpath: source}. Customer Python source captured (without importing) in+ # sandbox-hosted load mode, threaded into get_crate() so the crate can carry it to a sandbox.+ # Empty in local/direct mode. Per-library side-state because get_crate() rebuilds from+ # blueprints only and cannot see the original .py text otherwise.+ self._library_sources: dict[str, dict[str, str]] = {}############################################################# Manager lifecycle@@ -137,6 +143,7 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints.pop(library_id, None)self._crate_cache.pop(library_id, None)self._loaded_fingerprints.pop(library_id, None)+ self._library_sources.pop(library_id, None)return True@override@@ -158,6 +165,7 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints = {}self._crate_cache = {}self._loaded_fingerprints = {}+ self._library_sources = {}with ExitStack() as teardown_stack:for library in libraries:teardown_stack.callback(library.teardown)@@ -265,7 +273,10 @@ class LibraryManager(LibraryManagerAbstract):accumulated = self._blueprints.get(library_id)if not accumulated:return None- crate = LibraryCrateFactory.make_from_blueprints(blueprints=accumulated)+ crate = LibraryCrateFactory.make_from_blueprints(+ blueprints=accumulated,+ python_sources=self._library_sources.get(library_id),+ )self._crate_cache[library_id] = cratereturn crate@@ -317,18 +328,41 @@ class LibraryManager(LibraryManagerAbstract):# Import modules and register in global registries# Import from user directories+ is_sandbox_hosted = is_pipe_func_sandbox_hosted()for library_dir in all_dirs:- # Only import files that contain StructuredContent subclasses (uses AST pre-check)+ # Only import files that contain StructuredContent subclasses (uses AST pre-check).+ # Kept in hosted mode too: concepts declared as `structure = "ClassName"` resolve that+ # class from the registry at load time, so the structure classes must be present. These+ # are pydantic data classes, not the arbitrary PipeFunc bodies the hosted invariant guards.ClassRegistryUtils.import_modules_in_folder(folder_path=library_dir,base_class_names=[StructuredContent.__name__],force_include_dirs=[Path(builder_pkg.__file__).parent],)- # Only import files that contain @pipe_func decorated functions (uses AST pre-check)- FuncRegistryUtils.register_funcs_in_folder(- folder_path=library_dir,- force_include_dirs=[Path(builder_pkg.__file__).parent],- )+ if is_sandbox_hosted:+ # Sandbox-hosted mode: never import/register the customer's PipeFunc bodies in this+ # process. Capture every .py as source text (no import) so it can travel to the+ # sandbox, where it is registered and executed instead. Accumulate across dirs, but+ # fail loud on a relpath collision: the sandbox writes sources flat by relpath, so two+ # dirs sharing a path would otherwise silently clobber one customer's code and run the+ # wrong PipeFunc body.+ captured_sources = self._library_sources.setdefault(library_id, {})+ for relpath, source in FuncRegistryUtils.read_py_sources(folder_path=library_dir).items():+ if relpath in captured_sources and captured_sources[relpath] != source:+ msg = (+ f"Duplicate PipeFunc source path '{relpath}' across library dirs while loading library "+ f"'{library_id}'. Sandbox sources are keyed by relative path, so two dirs sharing a path "+ f"would clobber each other — give them distinct relative paths."+ )+ raise LibraryError(msg)+ captured_sources[relpath] = source+ else:+ # Local/direct mode (unchanged): import files that contain @pipe_func decorated+ # functions (uses AST pre-check) and register them in the process-global func_registry.+ FuncRegistryUtils.register_funcs_in_folder(+ folder_path=library_dir,+ force_include_dirs=[Path(builder_pkg.__file__).parent],+ )# Auto-discover and register all StructuredContent classes from sys.modulesnum_registered = ClassRegistryUtils.auto_register_all_subclasses(@@ -363,6 +397,14 @@ class LibraryManager(LibraryManagerAbstract):# factories resolve concepts and the class registry through the ambient current library,# so a load into a non-current library must not read the caller's binding.with scoped_current_library(library_id=library_id):+ # Cache the crate for a DIRECT crate-load (the transported-crate path used by the Temporal+ # workflow, which never populates _blueprints). This lets get_crate() hand the crate — with+ # its python_sources — to the sandbox executor. The blueprint-derived path (load_libraries ->+ # load_from_blueprints) leaves _blueprints populated and rebuilds from it instead, so it must+ # NOT be shadowed by a cached crate here.+ if library_id not in self._blueprints:+ self._crate_cache[library_id] = crate+# Fingerprint idempotency: skip if this crate was already loaded into this libraryfingerprint = crate.fingerprintloaded_set = self._loaded_fingerprints.setdefault(library_id, set())diff --git a/pipelex/pipe_operators/func/direct_pipe_func_executor.py b/pipelex/pipe_operators/func/direct_pipe_func_executor.pynew file mode 100644index 000000000..544cf1d4a--- /dev/null+++ b/pipelex/pipe_operators/func/direct_pipe_func_executor.py@@ -0,0 +1,153 @@+import asyncio+import inspect+import sys+import tempfile+from pathlib import Path+from typing import cast++from typing_extensions import override++from pipelex import log+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.stuffs.list_content import ListContent+from pipelex.core.stuffs.structured_content import StructuredContent+from pipelex.core.stuffs.stuff_content import StuffContent+from pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.core.stuffs.text_content import TextContent+from pipelex.hub import get_library_manager+from pipelex.pipe_operators.func.exceptions import PipeFuncExecutionError+from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest, PipeFuncExecutionResponse+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutionResult, PipeFuncExecutorProtocol+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipeline.job_metadata import JobMetadata+from pipelex.runtime_bridge.primitives.rehydration import rehydrate_library_and_memory+from pipelex.system.registries.class_registry_utils import ClassRegistryUtils+from pipelex.system.registries.func_registry import func_registry+from pipelex.system.registries.func_registry_utils import FuncRegistryUtils++# The library id the transported run rebuilds under. Internal to one process (a fresh sandbox box or a+# one-shot subprocess), so a fixed id is safe — there is no other library to collide with.+_TRANSPORTED_LIBRARY_ID = "pipe_func_transported_lib"+++class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):+ """The ``direct`` execution mode: resolve the function from the process-global registry and run it here.++ The free, in-process, trusted mode core owns (mirrors ``DirectOrchestrator`` on the orchestration+ axis). This is the pre-existing PipeFunc behavior, extracted verbatim from ``_live_run_operator_pipe``:+ async vs sync dispatch, and str/list -> StuffContent coercion. It is used for local runs and inside+ a sandbox box (where the real function IS registered); a sandbox-dispatching executor from the+ out-of-tree plugin runs it out-of-process instead when ``execution_mode`` names a sandbox backend.+ """++ @override+ async def run_pipe_func(+ self,+ *,+ job_metadata: JobMetadata,+ pipe_code: str,+ function_name: str,+ working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,+ ) -> PipeFuncExecutionResult:+ log.verbose(f"Running PipeFunc in-process with function '{function_name}'")+ function = func_registry.get_required_function(function_name)++ # The function is arbitrary user code; its failure surface is not enumerable. We do NOT catch+ # here: the operator wraps this call and decorates the failure with the pipe's inputs/output+ # for a diagnostic PipeRunError (preserving the pre-refactor behavior).+ if inspect.iscoroutinefunction(function):+ func_output_object = await function(working_memory=working_memory)+ else:+ func_output_object = await asyncio.to_thread(function, working_memory=working_memory)++ the_content: StuffContent+ if isinstance(func_output_object, StuffContent):+ the_content = func_output_object+ elif isinstance(func_output_object, list):+ func_result_list = cast("list[StuffContent]", func_output_object)+ the_content = ListContent(items=func_result_list)+ elif isinstance(func_output_object, str):+ the_content = TextContent(text=func_output_object)+ else:+ msg = f"Function '{function_name}' must return a StuffContent or a list, got {type(func_output_object)}"+ raise TypeError(msg)++ return PipeFuncExecutionResult(+ content=the_content,+ function_module=getattr(function, "__module__", None),+ function_qualname=getattr(function, "__qualname__", function_name),+ )++ @override+ async def run_pipe_func_transported(self, *, request: PipeFuncExecutionRequest) -> PipeFuncExecutionResponse:+ """Register the customer's real code from the crate, rebuild the library + memory, run the one PipeFunc, transport the output.++ The far-from-caller half of out-of-process execution, and the single source of truth for it: a+ sandbox box runs exactly this (its entrypoint is a thin shell over this call), and it pulls in+ no sandbox code — pure open core — so a box needs only ``pipelex`` installed. Unlike the+ runner/worker, it deliberately imports and executes customer code, because it runs INSIDE the+ isolation boundary. The output rides back wrapped in a working memory so it round-trips with its+ concept (and thus its dynamic-class identity), rebound against the receiver's registry.+ """+ workdir = Path(tempfile.mkdtemp(prefix="pipelex_pipe_func_"))+ for relpath, source in request.crate.python_sources.items():+ target = workdir / relpath+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(source, encoding="utf-8")++ # Put the bundle's directories on sys.path so a PipeFunc (or structure class) can import a sibling+ # file from the same bundle. This is only reached in-box (transported path): the crate is+ # re-materialized into a throwaway workdir that is NOT on sys.path, and each module is imported by+ # file path (spec_from_file_location), which does NOT add its directory to sys.path either — so a+ # top-level `from helpers import ...` between sibling files raises ModuleNotFoundError, the module+ # never finishes importing, and its @pipe_func never registers. A local direct run does not hit+ # this: its funcs were registered at boot from the real on-disk project already on sys.path. The+ # box is one-shot and disposable, so mutating sys.path is safe: add workdir (resolves+ # `from funcs.helpers import ...`) and every subdirectory holding a .py file (resolves the+ # sibling-relative `from helpers import ...`).+ source_dirs = {workdir} | {py_file.parent for py_file in workdir.rglob("*.py")}+ for source_dir in source_dirs:+ sys.path.insert(0, str(source_dir))++ # Register the customer's structure classes and @pipe_func functions from their real source,+ # before rehydration seeds a per-run registry from the global one and before the function lookup.+ ClassRegistryUtils.import_modules_in_folder(folder_path=workdir, base_class_names=[StructuredContent.__name__])+ ClassRegistryUtils.auto_register_all_subclasses(base_class=StructuredContent)+ FuncRegistryUtils.register_funcs_in_folder(folder_path=workdir)++ working_memory = rehydrate_library_and_memory(+ library_id=_TRANSPORTED_LIBRARY_ID,+ crate=request.crate,+ working_memory_raw=request.working_memory_raw,+ )+ if working_memory is None:+ msg = f"Transported rehydration produced no working memory for pipe '{request.pipe_code}'"+ raise PipeFuncExecutionError(msg)++ # Runaway-code guard: kill the PipeFunc if it runs past the request's (plan-dependent) timeout.+ try:+ execution_result = await asyncio.wait_for(+ self.run_pipe_func(+ job_metadata=request.job_metadata,+ pipe_code=request.pipe_code,+ function_name=request.function_name,+ working_memory=working_memory,+ pipe_run_params=request.pipe_run_params,+ ),+ timeout=request.timeout_seconds,+ )+ except TimeoutError as exc:+ msg = f"PipeFunc '{request.function_name}' exceeded its {request.timeout_seconds}s timeout"+ raise PipeFuncExecutionError(msg) from exc++ # Wrap the output in a memory so it round-trips with its concept (and thus its class identity).+ pipe = get_library_manager().get_library(library_id=_TRANSPORTED_LIBRARY_ID).pipe_library.get_required_pipe(pipe_code=request.pipe_code)+ output_stuff = StuffFactory.make_stuff(concept=pipe.output.concept, content=execution_result.content)+ working_memory.set_new_main_stuff(stuff=output_stuff)++ return PipeFuncExecutionResponse(+ output_memory_raw=working_memory.dump_for_transport(),+ function_module=execution_result.function_module,+ function_qualname=execution_result.function_qualname,+ )diff --git a/pipelex/pipe_operators/func/exceptions.py b/pipelex/pipe_operators/func/exceptions.pynew file mode 100644index 000000000..3b6c5fed9--- /dev/null+++ b/pipelex/pipe_operators/func/exceptions.py@@ -0,0 +1,18 @@+from pipelex.base_exceptions import PipelexError+++class PipeFuncTransportError(PipelexError):+ """A PipeFunc could not be packaged for, or rebound from, out-of-process execution.++ Raised while building the transport request (e.g. no crate is available for the current library,+ so the customer sources cannot travel) or while rehydrating the transported response.+ """+++class PipeFuncExecutionError(PipelexError):+ """A transported PipeFunc failed to run to a usable result out-of-process.++ Raised by the ``direct`` executor's transported run (the code a sandbox box runs internally) when+ rehydration yields no working memory or the function exceeds its (plan-dependent) timeout — as+ opposed to the customer function itself raising, which propagates untouched.+ """diff --git a/pipelex/pipe_operators/func/pipe_func.py b/pipelex/pipe_operators/func/pipe_func.pyindex 17d1f31b1..6fc91ba0b 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -1,11 +1,10 @@-import asyncio-import inspectfrom typing import Any, Literal, cast, get_args, get_origin, get_type_hintsfrom pydantic import field_validatorfrom typing_extensions import overridefrom pipelex import log+from pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundErrorfrom pipelex.core.memory.working_memory import WorkingMemory@@ -15,8 +14,7 @@ from pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.core.stuffs.text_content import TextContent-from pipelex.hub import get_class_registry+from pipelex.hub import get_class_registry, get_pipe_func_executorfrom pipelex.pipe_operators.pipe_operator import PipeOperatorfrom pipelex.pipe_run.exceptions import PipeRunErrorfrom pipelex.pipe_run.pipe_run_params import PipeRunParams@@ -43,6 +41,12 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):@field_validator("function_name", mode="before")@classmethoddef validate_function_name(cls, function_name: str) -> str:+ if is_pipe_func_sandbox_hosted():+ # Sandbox-hosted mode: the customer's function is not registered in this process (its+ # source only travels on the crate), so the registry lookup + return-type inspection+ # cannot run here. The sandbox registers the real function and validates it for real+ # when it loads. Accept the declared name verbatim.+ return function_namefunction = func_registry.get_function(function_name)if not function:# Check if this function was found but is ineligible (e.g., missing return type)@@ -77,6 +81,11 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):@overridedef validate_output_with_library(self):+ if is_pipe_func_sandbox_hosted():+ # Sandbox-hosted mode: the function is not in this process, so its return type cannot be+ # inspected to cross-check against the output concept's structure class. The sandbox does+ # this check for real at registration time. Skip the whole library-output validation here.+ returnfunction = func_registry.get_required_function(self.function_name)return_type: type[StuffContent] | None = get_type_hints(function).get("return")if return_type is None:@@ -181,16 +190,19 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):output_name: str | None = None,) -> PipeFuncOutput:log.verbose(f"Running PipeFunc with function '{self.function_name}'")- function = func_registry.get_required_function(self.function_name)try:- if inspect.iscoroutinefunction(function):- func_output_object = await function(working_memory=working_memory)- else:- func_output_object = await asyncio.to_thread(function, working_memory=working_memory)+ execution_result = await get_pipe_func_executor().run_pipe_func(+ job_metadata=job_metadata,+ pipe_code=self.code,+ function_name=self.function_name,+ working_memory=working_memory,+ pipe_run_params=pipe_run_params,+ )except Exception as exc:- # PipeFunc invokes an arbitrary user-registered function whose failure surface is not enumerable;- # any failure is wrapped into a diagnostic PipeRunError below. Re-raises, never swallows.+ # PipeFunc runs arbitrary user code — in-process, or (in hosted mode) inside a sandbox+ # reached through a Temporal activity — whose failure surface is not enumerable; any+ # failure is wrapped into a diagnostic PipeRunError below. Re-raises, never swallows.# Build informative error message with actual input values from working memoryinputs_lines: list[str] = []for input_name in self.inputs.root:@@ -210,17 +222,7 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):)raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code) from exc- the_content: StuffContent- if isinstance(func_output_object, StuffContent):- the_content = func_output_object- elif isinstance(func_output_object, list):- func_result_list = cast("list[StuffContent]", func_output_object)- the_content = ListContent(items=func_result_list)- elif isinstance(func_output_object, str):- the_content = TextContent(text=func_output_object)- else:- msg = f"Function '{self.function_name}' must return a StuffContent or a list, got {type(func_output_object)}"- raise TypeError(msg)+ the_content = execution_result.contentoutput_stuff = StuffFactory.make_stuff(name=output_name,@@ -236,11 +238,12 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):# Capture execution data for the graph tracer. PipeFunc has no prompts or# models to record, but the sidepanel should still show *what* function ran# and what kind of content it returned — useful for debugging and for- # distinguishing multiple PipeFunc nodes in a graph.+ # distinguishing multiple PipeFunc nodes in a graph. In hosted mode the module/qualname+ # ride back on the execution result (the operator no longer holds the callable).execution_data_dict: dict[str, Any] = {"function_name": self.function_name,- "function_module": getattr(function, "__module__", None),- "function_qualname": getattr(function, "__qualname__", self.function_name),+ "function_module": execution_result.function_module,+ "function_qualname": execution_result.function_qualname or self.function_name,"output_content_type": type(the_content).__name__,}self._register_execution_data(job_metadata=job_metadata, execution_data=execution_data_dict)@@ -259,15 +262,27 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):pipe_run_params: PipeRunParams,output_name: str | None = None,) -> PipeFuncOutput:- function = func_registry.get_required_function(self.function_name)log.info(f"🚨 For your information, the dry run of PipeFunc '{self.code}' is not actually running the python function \but only validating the inputs and return type.")- return_type = get_type_hints(function).get("return")- if return_type is None:- msg = f"Dry run of {self.type} '{self.code}' failed: The return type of the function is None. It should be a subclass of StuffContent."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ # Sandbox-hosted mode: the customer function is not registered in THIS process (its source only+ # travels on the crate to the sandbox), so its return type cannot be inspected here. Build the+ # mock output from the DECLARED output concept's structure class instead — mirroring PipeLLM's+ # dry run — and let the sandbox validate the real function's return type when it registers it.+ function = None if is_pipe_func_sandbox_hosted() else func_registry.get_required_function(self.function_name)+ return_type: type[StuffContent]+ if function is None:+ return_type = get_class_registry().get_required_subclass(+ name=self.output.concept.structure_class_name,+ base_class=StuffContent,+ )+ else:+ hinted_return_type = get_type_hints(function).get("return")+ if hinted_return_type is None:+ msg = f"Dry run of {self.type} '{self.code}' failed: function return type is None; it must be a subclass of StuffContent."+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ return_type = hinted_return_type# TODO: Support PipeFunc returning with multiplicity. Create an equivalent of TypedNamedInputRequirement for outputs.stuff_spec = TypedNamedStuffSpec(@@ -315,6 +330,10 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):async def _validate_before_run(self, *, job_metadata: JobMetadata, working_memory: WorkingMemory, pipe_run_params: PipeRunParams, output_name: str | None = None):+ if is_pipe_func_sandbox_hosted():+ # Sandbox-hosted mode: the function is not registered in this process, so its return type+ # cannot be inspected here. The sandbox validates the real function when it registers it.+ returnfunction = func_registry.get_required_function(self.function_name)return_type = get_type_hints(function).get("return")# TODO: this should not happend ever. The correct way to do this would be to have a unit test making surediff --git a/pipelex/pipe_operators/func/pipe_func_execution_dtos.py b/pipelex/pipe_operators/func/pipe_func_execution_dtos.pynew file mode 100644index 000000000..05206f764--- /dev/null+++ b/pipelex/pipe_operators/func/pipe_func_execution_dtos.py@@ -0,0 +1,58 @@+from typing import Any++from pydantic import BaseModel, ConfigDict, Field++from pipelex.libraries.library_crate import LibraryCrate+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipeline.job_metadata import JobMetadata++# The serialization-only transport DTOs for out-of-process PipeFunc execution. Deliberately a LEAF+# module — it imports only pure data types (no hub, no protocol, no builder), so the executor protocol+# can reference these types for its transported seam without closing an import cycle through the hub.+# The hub-bound builders that produce/consume them live in ``pipe_func_execution_transport``.++# Runaway-code guard: how long a single PipeFunc may run out-of-process before it is killed. Lives on+# the request (not a process-wide setting) so it can vary per run — e.g. by the user's plan. 5s+# default; the caller may raise it for a higher tier.+DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS = 5.0+++class PipeFuncExecutionRequest(BaseModel):+ """Everything needed to run ONE PipeFunc out-of-process, and nothing else.++ The generic transport primitive for out-of-process PipeFunc execution — sibling to the+ runtime-bridge serialization, carrying only open pipelex types. A backend (a sandbox box, a local+ subprocess) runs it and returns a ``PipeFuncExecutionResponse``; a host runtime (a Temporal+ activity) forwards it across its boundary. Carries the crate (which includes ``python_sources`` —+ the customer's .py to register wherever it runs), the transported working memory (the function's+ inputs), and the identity of the pipe/function to run. Deliberately carries NO secrets.+ """++ model_config = ConfigDict(extra="forbid")++ crate: LibraryCrate+ working_memory_raw: dict[str, Any]+ pipe_code: str+ function_name: str+ job_metadata: JobMetadata+ pipe_run_params: PipeRunParams+ timeout_seconds: float = Field(+ default=DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,+ gt=0,+ description="Max wall-clock seconds the PipeFunc may run before it is killed (plan-dependent).",+ )+++class PipeFuncExecutionResponse(BaseModel):+ """The out-of-process outcome: the output as a transported working memory (main stuff = the output).++ Transporting the output *through a working memory* (rather than as a bare StuffContent) is what+ preserves the dynamic-class identity on the way back — the receiver rebinds the class from the+ concept's ``structure_class_name`` against its own registry, exactly like the worker hydration.+ """++ model_config = ConfigDict(extra="forbid")++ output_memory_raw: dict[str, Any]+ function_module: str | None = None+ function_qualname: str | None = Nonediff --git a/pipelex/pipe_operators/func/pipe_func_execution_transport.py b/pipelex/pipe_operators/func/pipe_func_execution_transport.pynew file mode 100644index 000000000..50cc26719--- /dev/null+++ b/pipelex/pipe_operators/func/pipe_func_execution_transport.py@@ -0,0 +1,75 @@+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.hub import get_current_library, get_library_manager+from pipelex.pipe_operators.func.exceptions import PipeFuncTransportError+from pipelex.pipe_operators.func.pipe_func_execution_dtos import (+ DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,+ PipeFuncExecutionRequest,+ PipeFuncExecutionResponse,+)+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutionResult+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipeline.job_metadata import JobMetadata+from pipelex.runtime_bridge.primitives.hydration import hydrate_working_memory++# The transport DTOs (``PipeFuncExecutionRequest`` / ``PipeFuncExecutionResponse``) live in the leaf+# ``pipe_func_execution_dtos`` module so the executor protocol can reference them without a hub cycle;+# they are re-exported here (and genuinely used by the builders below), so existing+# ``from ...pipe_func_execution_transport import PipeFuncExecutionRequest`` imports keep working.+++def build_pipe_func_execution_request(+ *,+ job_metadata: JobMetadata,+ pipe_code: str,+ function_name: str,+ working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,+ timeout_seconds: float = DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,+) -> PipeFuncExecutionRequest:+ """Package one PipeFunc call for out-of-process execution: the current library's crate (with sources) + the transported inputs.++ Shared by every out-of-process executor — the in-process sandbox one and the Temporal in-workflow+ one — so the request shape is defined once. Reads the crate from the current library via the+ library manager; both the ``load_libraries`` (hosted dir-load) and the ``load_from_crate``+ (transported, workflow) paths make it available through ``get_crate``. Building the request is+ pure/deterministic, so it is safe to call inside a Temporal workflow before dispatching.++ ``timeout_seconds`` is the PipeFunc kill-timeout that rides on the request. Callers pass the+ configured ``pipe_func_config.timeout_seconds`` (they live in plugins, outside core's import graph,+ so they can read the config without a cycle); it falls back to the module default otherwise.+ """+ library_id = get_current_library()+ crate = get_library_manager().get_crate(library_id=library_id)+ if crate is None:+ msg = (+ f"Cannot run PipeFunc '{function_name}' out-of-process: no crate is available for the current library "+ f"'{library_id}'. The library must be loaded in sandbox-hosted mode so the customer sources travel on the crate."+ )+ raise PipeFuncTransportError(msg)++ return PipeFuncExecutionRequest(+ crate=crate,+ working_memory_raw=working_memory.dump_for_transport(),+ pipe_code=pipe_code,+ function_name=function_name,+ job_metadata=job_metadata,+ pipe_run_params=pipe_run_params,+ timeout_seconds=timeout_seconds,+ )+++def pipe_func_execution_result_from_response(response: PipeFuncExecutionResponse) -> PipeFuncExecutionResult:+ """Rebind a transported response into a PipeFuncExecutionResult against THIS process's registry.++ The output rode back as a transported working memory whose main stuff is the PipeFunc output;+ hydrating it here rebinds the class from the concept's ``structure_class_name`` (present for+ native and inline-structure concepts; a customer output class shipped only as .py is a known,+ deferred limitation).+ """+ output_memory = hydrate_working_memory(response.output_memory_raw)+ content = output_memory.get_main_stuff().content+ return PipeFuncExecutionResult(+ content=content,+ function_module=response.function_module,+ function_qualname=response.function_qualname,+ )diff --git a/pipelex/pipe_operators/func/pipe_func_executor_protocol.py b/pipelex/pipe_operators/func/pipe_func_executor_protocol.pynew file mode 100644index 000000000..ade57257f--- /dev/null+++ b/pipelex/pipe_operators/func/pipe_func_executor_protocol.py@@ -0,0 +1,67 @@+from typing import TYPE_CHECKING, Protocol++from pydantic import BaseModel, ConfigDict++from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.stuffs.stuff_content import StuffContent+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipeline.job_metadata import JobMetadata++if TYPE_CHECKING:+ # Import from the LEAF dtos module (not the transport builder module, which reaches the hub) so the+ # transported-seam annotation below does not close an import cycle through the hub.+ from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest, PipeFuncExecutionResponse+++class PipeFuncExecutionResult(BaseModel):+ """The outcome of running one PipeFunc, produced by a PipeFuncExecutor.++ Carries the already-coerced output content (str/list results are normalized to StuffContent by+ the executor, so the operator sees one shape regardless of where the function ran) plus the+ trace metadata the operator records for the graph. The operator no longer holds the callable in+ sandbox-hosted mode, so the module/qualname must ride back on this result rather than being read+ off the function object at the call site.++ Serialization-safe on purpose: in sandbox-hosted mode this crosses the Temporal activity+ boundary back from the worker to the workflow (the StuffContent field round-trips via kajson).+ """++ model_config = ConfigDict(frozen=True)++ content: StuffContent+ function_module: str | None = None+ function_qualname: str | None = None+++class PipeFuncExecutorProtocol(Protocol):+ """The execution seam for PipeFunc — the direct mirror of ``ContentGeneratorProtocol``.++ The default in-process implementation runs the customer function in this process. Under a+ Temporal-enabled hub a sandbox-hosted implementation dispatches to an activity that runs the+ function in an isolated sandbox instead. Either way the operator (``_live_run_operator_pipe``)+ stays identical: it calls ``run_pipe_func`` and then builds the output stuff, mutates working+ memory, and records the trace — none of which touches customer code.+ """++ async def run_pipe_func(+ self,+ *,+ job_metadata: JobMetadata,+ pipe_code: str,+ function_name: str,+ working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,+ ) -> PipeFuncExecutionResult: ...++ async def run_pipe_func_transported(self, *, request: "PipeFuncExecutionRequest") -> "PipeFuncExecutionResponse":+ """Run one PipeFunc from a *serialized* request and return a *serialized* response.++ The transported sibling of ``run_pipe_func``: it takes a ``PipeFuncExecutionRequest`` (crate ++ transported working memory) instead of live objects, and returns a ``PipeFuncExecutionResponse``+ (the output as a transported working memory, preserving dynamic-class identity). This is the+ seam a serialized boundary crosses — a distributed orchestrator's worker-side step resolves an+ executor by ``execution_mode`` and calls this, so it never needs live objects. ``direct`` runs+ it in-process (also what a sandbox box runs internally); a sandbox executor forwards the+ request to its box and returns the box's response.+ """+ ...diff --git a/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.py b/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.pynew file mode 100644index 000000000..2090e75c2--- /dev/null+++ b/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.py@@ -0,0 +1,43 @@+"""CLI entrypoint that runs ONE transported PipeFunc request in this process.++Invoked as a subprocess INSIDE an isolated sandbox (a Daytona box or a local subprocess): it reads a+serialized ``PipeFuncExecutionRequest``, runs it via the ``direct`` executor's transported path (which+registers the customer's real code from the crate and runs the one function), and writes the+serialized ``PipeFuncExecutionResponse``.++It lives in open ``pipelex`` and imports no sandbox code, so a box needs only ``pipelex`` installed —+the sandbox *client* (box provisioning, upload/download, teardown) is a worker-side concern that stays+in the out-of-tree plugin. This is the module a sandbox client runs as+``python -m pipelex.pipe_operators.func.pipe_func_transported_entrypoint <request_json> <result_json>``.++On any failure the process exits non-zero with a diagnostic on stderr, which the calling sandbox client+turns into a sandbox error.+"""++import asyncio+import sys+from pathlib import Path++from pipelex.pipe_operators.func.direct_pipe_func_executor import DirectPipeFuncExecutor+from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest+++def main() -> None:+ """argv: <request_json_path> <result_json_path>."""+ request_path = Path(sys.argv[1])+ result_path = Path(sys.argv[2])+ request = PipeFuncExecutionRequest.model_validate_json(request_path.read_text(encoding="utf-8"))++ # Import here so module import (e.g. for tests) stays cheap and free of boot side effects.+ from pipelex.pipelex import Pipelex # noqa: PLC0415++ Pipelex.make(needs_inference=False)+ try:+ result = asyncio.run(DirectPipeFuncExecutor().run_pipe_func_transported(request=request))+ finally:+ Pipelex.teardown_if_needed()+ result_path.write_text(result.model_dump_json(), encoding="utf-8")+++if __name__ == "__main__":+ main()diff --git a/pipelex/pipelex.py b/pipelex/pipelex.pyindex 93283c1cc..a7d8ab389 100644--- a/pipelex/pipelex.py+++ b/pipelex/pipelex.py@@ -32,7 +32,7 @@ from pipelex.cogt.model_backends.backend_credentials import (from pipelex.cogt.model_backends.gateway_config import GatewayConfigfrom pipelex.cogt.models.model_manager import ModelManagerfrom pipelex.cogt.models.model_manager_abstract import ModelManagerAbstract-from pipelex.config import get_config+from pipelex.config import get_config, get_pipe_func_execution_modefrom pipelex.core.registry_models import CoreRegistryModelsfrom pipelex.core.stuffs.stuff_template_set import STUFF_TEMPLATE_SETfrom pipelex.core.validation import report_validation_error@@ -43,6 +43,7 @@ from pipelex.libraries.library_manager import LibraryManagerfrom pipelex.libraries.library_manager_abstract import LibraryManagerAbstractfrom pipelex.observer.multi_observer import MultiObserverfrom pipelex.observer.observer_protocol import ObserverNoOp, ObserverProtocol+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocolfrom pipelex.pipe_run.pipe_router import PipeRouterfrom pipelex.pipe_run.pipe_router_protocol import PipeRouterProtocolfrom pipelex.pipe_run.pipe_run import PipeRun@@ -54,6 +55,7 @@ from pipelex.plugins.exceptions import UnknownBootOrchestratorErrorfrom pipelex.plugins.inference_backend_registry import InferenceBackendRegistryfrom pipelex.plugins.model_lister_registry import ModelListerRegistryfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistry+from pipelex.plugins.pipe_func_executor_registry import PipeFuncExecutorRegistryfrom pipelex.plugins.registrar import HubSlot, PluginRegistrarfrom pipelex.plugins.sdk_client_manager import SdkClientManagerfrom pipelex.plugins.secrets_provider_registry import SecretsProviderRegistry@@ -187,6 +189,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.models_manager: ModelManagerAbstract | None = None,inference_manager: InferenceManager | None = None,content_generator: ContentGeneratorProtocol | None = None,+ pipe_func_executor: PipeFuncExecutorProtocol | None = None,pipeline_manager: PipelineManagerAbstract | None = None,pipe_router: PipeRouterProtocol | None = None,reporting_delegate: ReportingProtocol | None = None,@@ -423,6 +426,8 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.self.pipelex_hub.set_bundle_validator_registry(BundleValidatorRegistry(plugin_registrar.bundle_validators))storage_provider_registry = StorageProviderRegistry(plugin_registrar.storage_providers)self.pipelex_hub.set_storage_provider_registry(storage_provider_registry)+ pipe_func_executor_registry = PipeFuncExecutorRegistry(plugin_registrar.pipe_func_executors)+ self.pipelex_hub.set_pipe_func_executor_registry(pipe_func_executor_registry)# Storage provider precedence: explicit setup() param > config-selected registry factory.# The built-in StoragePlugin supplies every method, so there is no separate core default.# Resolves here (after secrets is on the hub) so the GCP factory's secret read works.@@ -442,6 +447,21 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.)self.pipelex_hub.set_content_generator(content_generator)+ # Injection precedence: explicit setup() param > plugin slot-claim thunk > config-selected+ # registry factory. The PipeFunc execution axis is orthogonal to orchestration: a Temporal+ # worker claims the PIPE_FUNC_EXECUTOR slot to wrap execution in an activity, and inside that+ # activity resolves the real executor through this same registry by execution_mode. Every+ # non-worker boot resolves directly here — pipe_func_config.execution_mode selects the mode+ # ("direct" in-process by default; a sandbox mode like "daytona" runs it out-of-process).+ if pipe_func_executor is None:+ pipe_func_config = get_config().pipelex.pipe_func_config+ execution_mode = get_pipe_func_execution_mode()+ pipe_func_executor = self._resolve_hub_slot(+ slot=HubSlot.PIPE_FUNC_EXECUTOR,+ default=lambda: pipe_func_executor_registry.get_required(mode=execution_mode)(pipe_func_config),+ )+ self.pipelex_hub.set_pipe_func_executor(pipe_func_executor)+self.inference_manager = inference_manager or InferenceManager()self.pipelex_hub.set_inference_manager(self.inference_manager)@@ -587,6 +607,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.models_manager: ModelManagerAbstract | None = None,inference_manager: InferenceManager | None = None,content_generator: ContentGeneratorProtocol | None = None,+ pipe_func_executor: PipeFuncExecutorProtocol | None = None,pipeline_manager: PipelineManager | None = None,pipe_router: PipeRouterProtocol | None = None,reporting_delegate: ReportingProtocol | None = None,@@ -625,6 +646,8 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.models_manager: Custom model configuration managerinference_manager: Custom inference routing managercontent_generator: Custom content generation implementation+ pipe_func_executor: Custom PipeFunc execution seam. Defaults to the in-process executor;+ the Temporal worker claims this slot to dispatch PipeFunc runs to a sandbox activity.pipeline_manager: Custom pipeline managementpipe_router: Custom pipe routing logicreporting_delegate: Custom reporting handler@@ -663,6 +686,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.models_manager=models_manager,inference_manager=inference_manager,content_generator=content_generator,+ pipe_func_executor=pipe_func_executor,pipeline_manager=pipeline_manager,pipe_router=pipe_router,reporting_delegate=reporting_delegate,diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.tomlindex 8952bf3f4..e646e431b 100644--- a/pipelex/pipelex.toml+++ b/pipelex/pipelex.toml@@ -285,6 +285,17 @@ gemini = { tag_style = "xml" }[pipelex.pipe_run_config]pipe_stack_limit = 20+####################################################################################################+# PipeFunc config+####################################################################################################++[pipelex.pipe_func_config]+# PipeFunc execution mode, selected from the PipeFuncExecutorRegistry the plugins populate. "direct"+# (core) imports and runs customer functions in this process; "daytona" (our Daytona sandbox plugin)+# runs them in a remote box. Any non-"direct" mode carries customer PipeFunc code as source text and+# executes it only inside an isolated sandbox, never imported here.+execution_mode = "direct"+##################################################################################################### Pipeline execution config####################################################################################################diff --git a/pipelex/plugins/builtins.py b/pipelex/plugins/builtins.pyindex c00627b63..a2542d43f 100644--- a/pipelex/plugins/builtins.py+++ b/pipelex/plugins/builtins.py@@ -13,6 +13,7 @@ from pipelex.plugins.linkup.linkup_plugin import LinkupPluginfrom pipelex.plugins.mistral.mistral_plugin import MistralPluginfrom pipelex.plugins.openai.openai_plugin import OpenAIPluginfrom pipelex.plugins.openrouter.openrouter_plugin import OpenRouterPlugin+from pipelex.plugins.pipe_func.pipe_func_plugin import PipeFuncPluginfrom pipelex.plugins.portkey.portkey_plugin import PortkeyPluginfrom pipelex.plugins.pypdfium2.pypdfium2_plugin import Pypdfium2Pluginfrom pipelex.plugins.secrets.secrets_plugin import SecretsPlugin@@ -23,6 +24,7 @@ from pipelex.plugins.storage.storage_plugin import StoragePlugin# backend SDK (the SDKs load lazily inside the make_worker closures).BUILTIN_PLUGINS: list[PipelexPlugin] = [DirectOrchestratorPlugin(),+ PipeFuncPlugin(),StoragePlugin(),SecretsPlugin(),OpenAIPlugin(),@@ -45,9 +47,11 @@ BUILTIN_PLUGINS: list[PipelexPlugin] = [# Built-in plugins that core requires unconditionally — naming one in# ``plugins.disabled`` is a configuration error, not a no-op. ``direct`` owns the# DIRECT orchestrator (you cannot boot without an in-process execution mode);+# ``pipe_func`` owns the built-in PipeFunc execution modes (``pipe_func_config.execution_mode`` must+# resolve to a registered factory or boot fails loud — ``direct`` must always be present);# ``storage`` supplies every built-in storage backend (``storage_config.method`` must# resolve to a registered factory or boot fails loud); ``secrets`` supplies the built-in# ``env`` secrets backend (``secrets_config.method`` must likewise resolve or boot fails loud);# ``openai`` is the always-on default inference driver (no optional SDK to avoid), so disabling it# would only break the out-of-the-box experience.-CORE_UNCONDITIONAL_PLUGIN_NAMES: frozenset[str] = frozenset({"direct", "storage", "secrets", "openai"})+CORE_UNCONDITIONAL_PLUGIN_NAMES: frozenset[str] = frozenset({"direct", "pipe_func", "storage", "secrets", "openai"})diff --git a/pipelex/plugins/exceptions.py b/pipelex/plugins/exceptions.pyindex 3e24fd50d..b0a5b2b74 100644--- a/pipelex/plugins/exceptions.py+++ b/pipelex/plugins/exceptions.py@@ -123,6 +123,20 @@ class DuplicateSecretsProviderError(PluginError):super().__init__(message)+class DuplicatePipeFuncExecutorError(PluginError):+ """Two plugins registered a PipeFunc executor for the same execution mode."""++ def __init__(self, *, mode: str, first_plugin: str, second_plugin: str):+ self.mode = mode+ self.first_plugin = first_plugin+ self.second_plugin = second_plugin+ message = (+ f"PipeFunc executor for execution mode '{mode}' is registered by both plugin "+ f"'{first_plugin}' and plugin '{second_plugin}'. Each mode must have a single executor."+ )+ super().__init__(message)++class DuplicateHttpErrorMapperError(PluginError):"""Two plugins registered an HTTP-error mapper for the same exception type."""@@ -222,6 +236,32 @@ class UnknownStorageMethodError(PluginError):super().__init__(message)+class UnknownPipeFuncExecutionModeError(PluginError):+ """A configured PipeFunc execution mode has no registered executor factory.++ ``pipe_func_config.execution_mode`` selects a PipeFunc executor from the registry the built-in+ ``PipeFuncPlugin`` (``direct``) and any external sandbox plugin (e.g.+ our Daytona plugin → ``daytona``) populate. When the token names no registered factory —+ a typo, or a sandbox-backend plugin that is not installed or was disabled via ``plugins.disabled`` —+ boot fails loud here rather than starting with no PipeFunc executor. The message lists the+ registered modes so the fix is obvious.+ """++ # The message describes the caller's own input (the configured execution mode) and lists the+ # registered modes; it is fully actionable, so keep it verbatim under STRICT disclosure.+ _authors_caller_facing_message = True++ def __init__(self, *, mode: str, registered_modes: list[str]):+ self.mode = mode+ self.registered_modes = registered_modes+ available = ", ".join(sorted(registered_modes)) or "(none)"+ message = (+ f"No PipeFunc executor is registered for execution mode '{mode}'. Registered modes: {available}. "+ "Check pipe_func_config.execution_mode, or install/enable the plugin that provides that mode."+ )+ super().__init__(message)++class UnknownSecretsMethodError(PluginError):"""A configured secrets method has no registered provider factory.diff --git a/pipelex/plugins/orchestrator_registry.py b/pipelex/plugins/orchestrator_registry.pyindex 52d905107..809415168 100644--- a/pipelex/plugins/orchestrator_registry.py+++ b/pipelex/plugins/orchestrator_registry.py@@ -13,8 +13,8 @@ class OrchestratorProtocol(Protocol):"""How a pipe job runs under one orchestration mode.An orchestrator plugin registers one of these per ``orchestration_mode`` token it- serves (``"direct"`` in core; ``"temporal"`` from ``pipelex-temporal``,- ``"mistral-workflows"`` from ``pipelex-mistralai-workflows``). The runtime bridge+ serves (``"direct"`` in core; ``"temporal"`` from our Temporal plugin,+ ``"mistral-workflows"`` from our Mistral Workflows plugin). The runtime bridgedispatches by token through the ``OrchestratorRegistry`` instead of branching on a``match``.diff --git a/pipelex/plugins/pipe_func/__init__.py b/pipelex/plugins/pipe_func/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/pipelex/plugins/pipe_func/pipe_func_plugin.py b/pipelex/plugins/pipe_func/pipe_func_plugin.pynew file mode 100644index 000000000..966543646--- /dev/null+++ b/pipelex/plugins/pipe_func/pipe_func_plugin.py@@ -0,0 +1,32 @@+from pipelex.pipe_operators.func.direct_pipe_func_executor import DirectPipeFuncExecutor+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocol+from pipelex.plugins.contract import PLUGIN_API_VERSION+from pipelex.plugins.pipe_func_executor_registry import DIRECT_PIPE_FUNC_EXECUTION_MODE+from pipelex.plugins.registrar import PluginRegistrar+from pipelex.system.configuration.pipe_func_config import PipeFuncConfig+++def _make_direct_pipe_func_executor(config: PipeFuncConfig) -> PipeFuncExecutorProtocol: # noqa: ARG001 — stateless; the mode carries no config+ return DirectPipeFuncExecutor()+++class PipeFuncPlugin:+ """Always-on built-in provider of the ``direct`` (in-process) PipeFunc execution mode.++ Core-unconditional: PipeFunc execution is required infra, so this plugin cannot be disabled into a+ boot with no executor (see ``CORE_UNCONDITIONAL_PLUGIN_NAMES``). It registers the one mode core+ owns — ``direct``, which imports and runs the customer function in this process. Running a PipeFunc+ in a sandbox instead is a commercial capability contributed out of tree by our Daytona+ plugin (mode ``daytona``); core never imports it.++ This is the PipeFunc-execution axis, orthogonal to the orchestration axis: it selects *how* a+ function body runs (here vs in a sandbox), independent of *where* the pipe runs (in-process vs on a+ Temporal worker). A ``temporal`` boot claims the ``PIPE_FUNC_EXECUTOR`` hub slot to wrap execution+ in an activity, and inside that activity resolves the real executor through this same registry.+ """++ name = "pipe_func"+ targets_api = PLUGIN_API_VERSION++ def register(self, registrar: PluginRegistrar) -> None:+ registrar.add_pipe_func_executor(mode=DIRECT_PIPE_FUNC_EXECUTION_MODE, factory=_make_direct_pipe_func_executor)diff --git a/pipelex/plugins/pipe_func_executor_registry.py b/pipelex/plugins/pipe_func_executor_registry.pynew file mode 100644index 000000000..0041d38b3--- /dev/null+++ b/pipelex/plugins/pipe_func_executor_registry.py@@ -0,0 +1,44 @@+from collections.abc import Callable++from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocol+from pipelex.plugins.exceptions import UnknownPipeFuncExecutionModeError+from pipelex.system.configuration.pipe_func_config import PipeFuncConfig++# The one in-process execution mode core always owns. Every other mode is a remote/sandbox backend+# contributed by a plugin (e.g. an out-of-tree ``daytona`` backend) and, by the seam's invariant,+# transports the customer's source to run it out-of-process rather than importing it here.+DIRECT_PIPE_FUNC_EXECUTION_MODE = "direct"++# A plugin's factory for one PipeFunc execution mode: the pipe_func config in, an executor out. The+# whole ``PipeFuncConfig`` (not a pre-resolved value) is passed so a factory can read whatever it+# needs at the boot apply-point, never at registration — mirrors ``StorageProviderFactoryFn``.+PipeFuncExecutorFactoryFn = Callable[[PipeFuncConfig], PipeFuncExecutorProtocol]+++class PipeFuncExecutorRegistry:+ """Read view over the PipeFunc-executor factories contributed by discovered plugins.++ Keyed by the open ``execution_mode`` token (a ``str``; core owns ``direct``, an external plugin+ registers e.g. ``"daytona"``). Built once+ at boot from the registrar's accumulated ``pipe_func_executors`` and stored on the hub; core reads+ ``pipe_func_config.execution_mode`` and calls the looked-up factory to produce the one executor set+ on the hub. This is the config-selected-singleton sibling of ``StorageProviderRegistry`` — the+ PipeFunc execution axis, orthogonal to the orchestration axis (a ``temporal`` boot still resolves+ its executor mode through this registry on the worker side).+ """++ def __init__(self, pipe_func_executors: dict[str, PipeFuncExecutorFactoryFn]):+ self._pipe_func_executors: dict[str, PipeFuncExecutorFactoryFn] = dict(pipe_func_executors)++ def get_required(self, *, mode: str) -> PipeFuncExecutorFactoryFn:+ factory = self._pipe_func_executors.get(mode)+ if factory is None:+ raise UnknownPipeFuncExecutionModeError(mode=mode, registered_modes=self.modes)+ return factory++ def has(self, *, mode: str) -> bool:+ return mode in self._pipe_func_executors++ @property+ def modes(self) -> list[str]:+ return list(self._pipe_func_executors)diff --git a/pipelex/plugins/registrar.py b/pipelex/plugins/registrar.pyindex f837f5160..06e9741d2 100644--- a/pipelex/plugins/registrar.py+++ b/pipelex/plugins/registrar.py@@ -12,6 +12,7 @@ from pipelex.plugins.exceptions import (DuplicateInferenceBackendError,DuplicateModelListerError,DuplicateOrchestratorError,+ DuplicatePipeFuncExecutorError,DuplicateSecretsProviderError,DuplicateStorageProviderError,HubSlotAlreadyClaimedError,@@ -19,6 +20,7 @@ from pipelex.plugins.exceptions import (from pipelex.plugins.inference_backend_registry import InferenceFamily, MakeWorkerFnfrom pipelex.plugins.model_lister_registry import ListModelsFnfrom pipelex.plugins.orchestrator_registry import OrchestratorProtocol+from pipelex.plugins.pipe_func_executor_registry import PipeFuncExecutorFactoryFnfrom pipelex.plugins.secrets_provider_registry import SecretsProviderFactoryFnfrom pipelex.plugins.storage_provider_registry import StorageProviderFactoryFnfrom pipelex.runtime_bridge.orchestration_mode import OrchestrationMode@@ -63,6 +65,7 @@ class HubSlot(StrEnum):"""A process-global capability slot a boot-orchestrator plugin may claim."""CONTENT_GENERATOR = "content_generator"+ PIPE_FUNC_EXECUTOR = "pipe_func_executor"PIPE_ROUTER = "pipe_router"PIPE_RUN = "pipe_run"TASK_MANAGER = "task_manager"@@ -121,6 +124,7 @@ class PluginRegistrar:self.bundle_validators: dict[OrchestrationMode, BundleValidatorProtocol] = {}self.storage_providers: dict[str, StorageProviderFactoryFn] = {}self.secrets_providers: dict[str, SecretsProviderFactoryFn] = {}+ self.pipe_func_executors: dict[str, PipeFuncExecutorFactoryFn] = {}# Ordered list (not a type-keyed dict) because the exception types are# resolved lazily — only ``get_http_error_mappers`` invokes the providers,# so duplicate-by-type detection is deferred to resolution time too.@@ -134,6 +138,7 @@ class PluginRegistrar:self._bundle_validator_sources: dict[OrchestrationMode, str] = {}self._storage_provider_sources: dict[str, str] = {}self._secrets_provider_sources: dict[str, str] = {}+ self._pipe_func_executor_sources: dict[str, str] = {}self._slot_sources: dict[HubSlot, str] = {}# Reassigned per plugin by build_registrar; the floating default keeps the# menu methods safe to call outside a registration loop (e.g. a focused unit test).@@ -243,6 +248,28 @@ class PluginRegistrar:),)+ def add_pipe_func_executor(self, *, mode: str, factory: PipeFuncExecutorFactoryFn) -> None:+ """Contribute a factory for one PipeFunc execution mode, keyed by an open ``mode`` token.++ The built-in ``PipeFuncPlugin`` registers ``direct`` (in-process); an external sandbox plugin+ (e.g. our Daytona plugin) registers its own token+ (e.g. ``"daytona"``). Boot reads ``pipe_func_config.execution_mode`` and calls the looked-up+ factory to produce the one PipeFunc executor set on the hub. ``factory`` is invoked at that boot+ apply-point, never here — so a factory may do heavy work (SDK import, config self-load) while+ ``register`` stays import-light. This is the PipeFunc-execution axis, orthogonal to the+ orchestration axis. Fail-loud on a duplicate mode, naming both plugins.+ """+ self._add(+ store=self.pipe_func_executors,+ sources=self._pipe_func_executor_sources,+ key=mode,+ value=factory,+ contribution=f"pipe_func executor {mode}",+ on_duplicate=lambda first_plugin, second_plugin: DuplicatePipeFuncExecutorError(+ mode=mode, first_plugin=first_plugin, second_plugin=second_plugin+ ),+ )+def add_http_error_mapper(self, *, exc_type_provider: HttpErrorTypeProviderFn, to_error_report: HttpErrorMapperFn) -> None:"""Contribute a mapping from a transport/runtime exception to a structured ``ErrorReport``.@@ -268,6 +295,9 @@ class PluginRegistrar:def claim_content_generator(self, factory: Callable[[], Any]) -> None:self._claim(slot=HubSlot.CONTENT_GENERATOR, factory=factory)+ def claim_pipe_func_executor(self, factory: Callable[[], Any]) -> None:+ self._claim(slot=HubSlot.PIPE_FUNC_EXECUTOR, factory=factory)+def claim_pipe_router(self, factory: Callable[[], Any]) -> None:self._claim(slot=HubSlot.PIPE_ROUTER, factory=factory)diff --git a/pipelex/runtime_bridge/bootstrap.py b/pipelex/runtime_bridge/bootstrap.pyindex ab99275c9..d35a1ee3a 100644--- a/pipelex/runtime_bridge/bootstrap.py+++ b/pipelex/runtime_bridge/bootstrap.py@@ -40,9 +40,7 @@ def ensure_pipelex_booted(``_boot_lock``, so within its setup window ``is_fully_booted()`` is False andthis helper would attempt its own ``make`` and hit``PipelexSetupError("Pipelex is already initialized")``. Standard hosts boot- before bringing up concurrent bridge callers, so this is not reached; the- residual race and a bounded-wait fix are written up in- ``wip/runtime-bridge/bridge-bootstrap-external-race.md``.+ before bringing up concurrent bridge callers, so this is not reached."""if Pipelex.is_fully_booted():returndiff --git a/pipelex/runtime_bridge/direct_orchestrator.py b/pipelex/runtime_bridge/direct_orchestrator.pyindex fc43f915c..37f72ffff 100644--- a/pipelex/runtime_bridge/direct_orchestrator.py+++ b/pipelex/runtime_bridge/direct_orchestrator.py@@ -1,8 +1,7 @@"""The core, always-on DIRECT orchestrator.-Runs a pipe in-process. Extracted verbatim from the bridge's old ``_run_direct``-arm so the bridge dispatches by mode through the ``OrchestratorRegistry`` instead-of a ``match``. Registered unconditionally by the core ``direct`` plugin.+Runs a pipe in-process. Registered unconditionally by the core ``direct``+plugin; dispatch reaches it by mode through the ``OrchestratorRegistry``.Import-light: core pipe-run + the shared serialization helpers; no host-runtime SDK."""diff --git a/pipelex/runtime_bridge/exceptions.py b/pipelex/runtime_bridge/exceptions.pyindex 9d6b4fff4..e25010e22 100644--- a/pipelex/runtime_bridge/exceptions.py+++ b/pipelex/runtime_bridge/exceptions.py@@ -11,7 +11,7 @@ class MissingOrchestratorError(PipelexRuntimeBridgeError):``orchestration_mode`` is an open token: ``"direct"`` is contributed by core, and everyother token by the plugin that owns its orchestrator (``"temporal"`` →- ``pipelex-temporal``, ``"mistral-workflows"`` → ``pipelex-mistralai-workflows``). A+ our Temporal plugin, ``"mistral-workflows"`` → our Mistral Workflows plugin). Alookup miss therefore means *that mode's plugin is not installed* — the message isgeneric and names no orchestrator, so core stays fully decoupled from its plugins. Theone special case is ``"direct"``: its orchestrator is core and always present, so a miss@@ -44,7 +44,7 @@ class MissingBundleValidatorError(PipelexRuntimeBridgeError):def _build_missing_message(*, noun: str, mode: OrchestrationMode) -> str:- """Generic, plugin-decoupled message shared by both Missing* errors (D-F).+ """Generic, plugin-decoupled message shared by both Missing* errors.A plain string compare on ``"direct"`` (not an enum ``match``) — core's one built-intoken — singles out the boot/discovery fault from the missing-plugin case.diff --git a/pipelex/runtime_bridge/orchestration_mode.py b/pipelex/runtime_bridge/orchestration_mode.pyindex ec16cd94f..c302fa650 100644--- a/pipelex/runtime_bridge/orchestration_mode.py+++ b/pipelex/runtime_bridge/orchestration_mode.py@@ -2,8 +2,8 @@``orchestration_mode`` is an **open string token**, not a closed enum. Core ownsonly ``"direct"`` (its single built-in, in-process orchestrator); every other token-is contributed by the plugin that owns the orchestrator — ``pipelex-temporal`` owns-``"temporal"``, ``pipelex-mistralai-workflows`` owns ``"mistral-workflows"``. The+is contributed by the plugin that owns the orchestrator — our Temporal plugin owns+``"temporal"``, our Mistral Workflows plugin owns ``"mistral-workflows"``. Theorchestrator/validator registries are keyed by this token and validation is aregistry lookup (*is this mode registered?* → ``MissingOrchestratorError`` on a miss),never an enum-membership check.@@ -13,8 +13,7 @@ that standard exists to make the linter scream when a *closed* value is added anbranch forgotten, but a plugin-contributed set is genuinely open — exhaustive matchingis impossible, and the dict-lookup-or-raise *is* the correct unknown-handling. It isalso the only choice faithful to "the public base names no orchestrator": a closed-``{DIRECT, TEMPORAL, MISTRAL}`` enum would re-introduce the very core→plugin coupling-the plugin-system externalization removed.+``{DIRECT, TEMPORAL, MISTRAL}`` enum would couple core to its plugins.``OrchestrationMode`` is a plain ``str`` alias (not a ``NewType``) so plugins pass rawstring tokens with no casts at the registry boundary — the registry is the validator,diff --git a/pipelex/runtime_bridge/payloads.py b/pipelex/runtime_bridge/payloads.pyindex fb14329ce..a77fc13db 100644--- a/pipelex/runtime_bridge/payloads.py+++ b/pipelex/runtime_bridge/payloads.py@@ -1,8 +1,8 @@"""JSON-safe boundary payloads for the runtime bridge.The SPI boundary contract between core's ``DirectOrchestrator`` (and the open-``pipelex-api`` runner) and the cross-process dispatch entry-point that now lives-in the closed ``pipelex-transport`` library. Kept import-light and separate from+``pipelex-api`` runner) and the cross-process dispatch entry-point that lives+out of tree with the orchestration plugins. Kept import-light and separate fromany dispatch logic so they can be referenced (e.g. by the orchestrator SPI /``OrchestratorProtocol``) without pulling the bootstrap path — which would form animport cycle: pydantic, the orchestration/delivery types, stdlib typing only.@@ -17,7 +17,7 @@ from pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODEclass PipelexPipeRunInput(BaseModel):- """JSON-safe input crossing the host-runtime / Temporal boundary."""+ """JSON-safe input crossing the host-runtime boundary."""model_config = ConfigDict(extra="forbid")@@ -37,7 +37,7 @@ class PipelexPipeRunInput(BaseModel):class PipelexPipeRunOutput(BaseModel):- """JSON-safe output of a COMPLETED run crossing the host-runtime / Temporal boundary.+ """JSON-safe output of a COMPLETED run crossing the host-runtime boundary.This is the return shape of a blocking dispatch (``OrchestratorProtocol.execute``); afire-and-forget dispatch returns a ``PipelexPipeDispatchAck`` instead — which is whydiff --git a/pipelex/runtime_bridge/primitives/__init__.py b/pipelex/runtime_bridge/primitives/__init__.pyindex fb95709fb..f6d3a03f2 100644--- a/pipelex/runtime_bridge/primitives/__init__.py+++ b/pipelex/runtime_bridge/primitives/__init__.py@@ -1,8 +1,9 @@-"""Hydration helpers for the runtime bridge.+"""Boundary primitives for the runtime bridge.-After the cross-process transport plumbing moved to the closed ``pipelex-transport``-library, this package holds only ``hydration.py`` — the working-memory hydration-helpers used by core's ``delivery_executor`` and the open ``pipelex-api`` runner, and-imported across the boundary by ``pipelex-transport`` (they are on the allowed import-surface). It contains no host-runtime-specific imports — only Pipelex core types.+Working-memory hydration (``hydration.py``) and library + memory rehydration+(``rehydration.py``): the helpers a receiver of a transported payload uses to+rebuild typed state. Used by core's ``delivery_executor``, the transported+PipeFunc path, and the open ``pipelex-api`` runner, and imported by out-of-tree+transport/orchestration plugins (they are on the allowed import surface). No+host-runtime-specific imports — only Pipelex core types."""diff --git a/pipelex/runtime_bridge/primitives/hydration.py b/pipelex/runtime_bridge/primitives/hydration.pyindex adf9a31d2..12a5830dd 100644--- a/pipelex/runtime_bridge/primitives/hydration.py+++ b/pipelex/runtime_bridge/primitives/hydration.py@@ -19,12 +19,12 @@ from pipelex.pipe_run.exceptions import PipeJobErrordef _validate_as_known_class(*, item_class: type[StuffContent], raw_item: StuffContent | dict[str, Any]) -> StuffContent:"""Validate raw_item into item_class, tolerating cross-exec instances.- The Temporal hot path now ships ListContent items as plain dicts with+ The transport format ships ListContent items as plain dicts withpipelex-private ``__pipelex_class__`` / ``__pipelex_module__`` markers(see ``WorkingMemory.dump_for_transport``), so kajson never eagerly rehydratesthem — the ``isinstance(raw_item, StuffContent)`` branch below is defensive,- kept for direct (non-Temporal) callers and for any future path where kajson- might still produce an instance whose class identity drifted across execs.+ kept for callers that pass already-typed instances and for any path where+ kajson might produce an instance whose class identity drifted across execs.In that drift case, ``model_validate`` would reject the old instance because``type(raw_item) is not item_class``, so we round-trip through``smart_dump()`` (serialize_as_any) to let nested subclass fields survive.@@ -49,7 +49,7 @@ def _hydrate_list_item(raw_item: dict[str, Any] | str | StuffContent) -> StuffCoif isinstance(raw_item, str):return TextContent(text=raw_item)- # Already hydrated by kajson via the Temporal data converter. The instance+ # Already hydrated by kajson via a transport data converter. The instance# may come from a previous exec of the dynamic source — normalize through# the registry's current class so downstream type checks stay consistent.if isinstance(raw_item, StuffContent):@@ -65,8 +65,7 @@ def _hydrate_list_item(raw_item: dict[str, Any] | str | StuffContent) -> StuffCoclean_item = {key: val for key, val in raw_item.items() if key not in {"__pipelex_class__", "__pipelex_module__"}}return cast("StuffContent", item_class.model_validate(clean_item))- # No __class__ metadata — fall back to TextContent for simple text dicts.- # This handles legacy payloads serialized before __class__ metadata was added.+ # No __class__ metadata — fall back to TextContent for marker-less simple text dicts.if "text" in raw_item:return TextContent.model_validate(raw_item)@@ -98,7 +97,7 @@ def _hydrate_composite_component(raw_value: Any) -> Any:def hydrate_content(raw_content: list[Any] | dict[str, Any] | str, *, concept: Concept) -> StuffContent:"""Hydrate a single StuffContent from a raw value.- Handles both plain content and ListContent. The Temporal serialization+ Handles both plain content and ListContent. The transport serializationformat (produced by ``WorkingMemory.dump_for_transport()``) encodesListContent as a plain JSON list and single StuffContent as a dict,so the type check is unambiguous — no heuristic required. ListContent@@ -114,7 +113,7 @@ def hydrate_content(raw_content: list[Any] | dict[str, Any] | str, *, concept: Cif item_class_or_none is not None and issubclass(item_class_or_none, StuffContent):# Known content class (e.g. TextContent, PageContent, or a dynamic# structured concept class). Use _validate_as_known_class so that- # cross-exec instances rebuilt by kajson during Temporal transit+ # cross-exec instances rebuilt by kajson during cross-process transit# get normalized through a dict round-trip.items = [_validate_as_known_class(item_class=item_class_or_none, raw_item=raw_item) for raw_item in raw_content]else:diff --git a/pipelex/runtime_bridge/primitives/rehydration.py b/pipelex/runtime_bridge/primitives/rehydration.pynew file mode 100644index 000000000..336efc3d2--- /dev/null+++ b/pipelex/runtime_bridge/primitives/rehydration.py@@ -0,0 +1,50 @@+from typing import Any++from kajson.class_registry import ClassRegistry+from kajson.kajson_manager import KajsonManager++from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.hub import get_library_manager, set_current_library+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.runtime_bridge.primitives.hydration import hydrate_working_memory+++def rehydrate_library_and_memory(+ *,+ library_id: str,+ crate: LibraryCrate,+ working_memory_raw: dict[str, Any] | None,+) -> WorkingMemory | None:+ """Open a fresh library from a transported crate and hydrate a transported working memory.++ This is the canonical rehydration sequence for the far side of a transport boundary: any+ process that receives a ``(crate, working_memory_raw)`` payload — such as the in-sandbox+ PipeFunc entrypoint — must rebuild a live library and typed working memory this way.+ Out-of-tree orchestration backends need the same sequence; keeping it as a core primitive+ gives them one function to call instead of hand-copying the steps.++ Steps, in order (order matters):++ 1. Create a per-run ``ClassRegistry`` pre-seeded from the global one, so this run's dynamically+ generated concept classes register into an isolated registry rather than leaking globally.+ 2. Open a fresh library under ``library_id`` and attach the registry; make it the current library+ so the factory and hydrator resolve classes against it.+ 3. ``load_from_crate`` — rebuilds domains/concepts/pipes and registers the dynamic classes.+ 4. Hydrate the working memory (needs step 3 to have registered the classes it references).++ Returns the hydrated WorkingMemory, or None when there was nothing to hydrate.+ """+ global_registry = KajsonManager.get_class_registry()+ run_registry = ClassRegistry()+ run_registry.register_classes_dict(global_registry.get_classes_dict())++ library_manager = get_library_manager()+ library = library_manager.open_fresh_library(library_id=library_id)+ library.set_class_registry(run_registry)+ set_current_library(library_id=library_id)++ library_manager.load_from_crate(library_id=library_id, crate=crate)++ if working_memory_raw is None:+ return None+ return hydrate_working_memory(working_memory_raw)diff --git a/pipelex/runtime_bridge/serialization.py b/pipelex/runtime_bridge/serialization.pyindex 94eddd467..cf92d750f 100644--- a/pipelex/runtime_bridge/serialization.py+++ b/pipelex/runtime_bridge/serialization.py@@ -1,7 +1,7 @@"""Boundary (de)serialization shared by the orchestrators.-Kept separate from the dispatch entry-point (``run_pipe_via_bridge``, now in the-closed ``pipelex-transport`` library) so the orchestrator implementations (DIRECT+Kept separate from the cross-process dispatch entry-point (which lives out of+tree, with the orchestration plugins) so the orchestrator implementations (DIRECTin core, the distributed modes in the plugins) can serialize their ``PipeOutput``into the JSON-safe ``PipelexPipeRunOutput`` without pulling the bootstrap path(which would form an import cycle). This module is deliberately import-light: core@@ -24,10 +24,10 @@ if TYPE_CHECKING:# Pipe-execution failures an orchestrator converts into PipelexBridgeDispatchError so a host can catch a-# single error type regardless of execution mode. The Temporal orchestrators additionally catch-# WorkflowExecutionError (lazy-imported there to keep temporal off the module import path); wrapping-# it with ``from exc`` loses no signal — the structured ErrorReport stays reachable via ``__cause__``-# and is surfaced by PipelexBridgeDispatchError.to_error_report()'s cause-chain enrichment.+# single error type regardless of execution mode. Distributed orchestrators additionally catch their+# own workflow-level execution errors; wrapping with ``from exc`` loses no signal — the structured+# ErrorReport stays reachable via ``__cause__`` and is surfaced by+# PipelexBridgeDispatchError.to_error_report()'s cause-chain enrichment.PIPE_DISPATCH_ERRORS: tuple[type[PipelexError], ...] = (PipeRunError,PipeJobError,diff --git a/pipelex/system/configuration/configs.py b/pipelex/system/configuration/configs.pyindex 8f0fc7f74..281f0674f 100644--- a/pipelex/system/configuration/configs.py+++ b/pipelex/system/configuration/configs.py@@ -12,6 +12,7 @@ from pipelex.graph.graph_config import GraphConfigfrom pipelex.language.mthds_config import MthdsConfigfrom pipelex.system.configuration.config_model import ConfigModelfrom pipelex.system.configuration.config_root import ConfigRoot+from pipelex.system.configuration.pipe_func_config import PipeFuncConfigfrom pipelex.tools.aws.aws_config import AwsConfigfrom pipelex.tools.log.log_config import LogConfigfrom pipelex.tools.secrets.secrets_config import SecretsProviderConfig@@ -208,6 +209,7 @@ class Pipelex(ConfigModel):dry_run_config: DryRunConfigpipe_run_config: PipeRunConfig+ pipe_func_config: PipeFuncConfigpipeline_execution_config: PipelineExecutionConfigreporting_config: ReportingConfigtracing_config: TracingConfigdiff --git a/pipelex/system/configuration/pipe_func_config.py b/pipelex/system/configuration/pipe_func_config.pynew file mode 100644index 000000000..df1cbd369--- /dev/null+++ b/pipelex/system/configuration/pipe_func_config.py@@ -0,0 +1,20 @@+from pydantic import Field++from pipelex.system.configuration.config_model import ConfigModel+++class PipeFuncConfig(ConfigModel):+ # Which PipeFunc execution mode this process runs, selected from the PipeFuncExecutorRegistry the+ # plugins populate (the config-selected-singleton seam, sibling of storage_config.method). An open+ # string token: "direct" (core, in-process — imports and runs the customer function here) is the+ # default; "daytona" (our Daytona sandbox plugin) runs it out-of-process. Any non-"direct" mode is a remote/sandbox+ # backend: library loading captures the customer .py source as text (onto the crate) instead of+ # registering it in the func_registry, and the PipeFunc validators skip the func_registry lookup ++ # return-type checks — the real function is registered and validated inside the sandbox, not here.+ # "direct" is byte-identical to the pre-existing behavior. This is a hosted-deploy concern, not a+ # client preference, so it is intentionally absent from the .pipelex/ override file.+ #+ # Lives in its own module (not configs.py) so the PipeFuncExecutorRegistry can type its factory+ # against it without importing the heavy configs module, which would close an import cycle through+ # aws_config -> hub. Mirrors how StorageProviderConfig sits in its own module.+ execution_mode: str = Field(strict=False)diff --git a/pipelex/system/registries/func_registry_utils.py b/pipelex/system/registries/func_registry_utils.pyindex 97fa22380..3de481ed8 100644--- a/pipelex/system/registries/func_registry_utils.py+++ b/pipelex/system/registries/func_registry_utils.py@@ -109,6 +109,45 @@ class FuncRegistryUtils:for python_file in python_files:cls._register_funcs_in_file(file_path=python_file)+ @classmethod+ def read_py_sources(+ cls,+ folder_path: Path,+ *,+ is_recursive: bool = True,+ ) -> dict[str, str]:+ """Capture the text of every Python file in a folder WITHOUT importing or executing any of it.++ This is the sandbox-hosted counterpart of ``register_funcs_in_folder``: instead of importing+ the customer's modules and registering ``@pipe_func`` functions in this process, it reads the+ raw source so the code can travel (on the crate) to an isolated sandbox where it is registered+ and run. It performs NO import — ``sys.modules`` is left untouched — which is what keeps the+ runner/worker from ever executing customer code.++ Discovery mirrors ``register_funcs_in_folder`` (same ``find_files_in_dir`` + ``excluded_dirs``)+ so the captured set matches what the local path would have imported. Both PipeFunc bodies and+ structure classes are captured, since the sandbox needs the customer's real classes too.++ Args:+ folder_path: Path to the folder containing Python files.+ is_recursive: Whether to search recursively in subdirectories.++ Returns:+ Mapping of POSIX relpath (relative to ``folder_path``) -> source text.+ """+ python_files = find_files_in_dir(+ dir_path=folder_path,+ pattern="*.py",+ is_recursive=is_recursive,+ excluded_dirs=list(get_config().pipelex.scan_config.excluded_dirs),+ )++ sources: dict[str, str] = {}+ for python_file in python_files:+ relative_path = python_file.relative_to(folder_path).as_posix()+ sources[relative_path] = python_file.read_text(encoding="utf-8")+ return sources+@classmethoddef _register_funcs_in_file(cls,diff --git a/pipelex/test_extras/error_report_parity.py b/pipelex/test_extras/error_report_parity.pyindex 2e6bef1de..82e36cfe9 100644--- a/pipelex/test_extras/error_report_parity.py+++ b/pipelex/test_extras/error_report_parity.py@@ -2,7 +2,7 @@This module is **shipped in the open-core wheel on purpose**. The parity contract spans tworepos: open core asserts that a failing pipe surfaces a fully classified ``ErrorReport`` on the-local execution path, and the closed ``pipelex-temporal`` plugin asserts the *same*+local execution path, and our Temporal plugin asserts the *same*classification survives the activity -> workflow -> submitter boundary. Both arms import thefixtures below, so the classification a failing pipe surfaces cannot silently diverge between thetwo execution paths — there is one definition, not two hand-synced copies.diff --git a/pipelex/tools/typing/module_inspector.py b/pipelex/tools/typing/module_inspector.pyindex 947c7c2d7..bfce74a02 100644--- a/pipelex/tools/typing/module_inspector.py+++ b/pipelex/tools/typing/module_inspector.py@@ -49,6 +49,16 @@ def import_module_from_file(file_path: Path) -> Any:# Add the module to sys.modules to ensure proper imports within the modulesys.modules[module_name] = module+ # Put the file's OWN directory on sys.path so a module imported by path can import its siblings+ # (e.g. `from helpers import ...` between files in the same bundle). Importing via+ # spec_from_file_location does NOT do this automatically — unlike running a script, where the+ # script's directory lands on sys.path[0]. Without it, a top-level sibling import raises+ # ModuleNotFoundError and the module never finishes importing. Deduped, so repeated scans don't+ # grow sys.path unbounded.+ module_dir = str(file_path.resolve().parent)+ if module_dir not in sys.path:+ sys.path.insert(0, module_dir)+# Execute the modulespec.loader.exec_module(module)diff --git a/subject_grants.toml b/subject_grants.tomlindex f0e87d248..2e31695fd 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -3552,6 +3552,14 @@ rationale = "Hub setter: installs the observer; single self-labelling operand."param = "orchestrator_registry"rationale = "Hub setter: installs the orchestrator registry; single self-labelling operand."+["pipelex/hub.py::PipelexHub.set_pipe_func_executor"]+param = "pipe_func_executor"+rationale = "Hub setter: installs the pipe-func executor; single self-labelling operand."++["pipelex/hub.py::PipelexHub.set_pipe_func_executor_registry"]+param = "pipe_func_executor_registry"+rationale = "Hub setter: installs the pipe-func executor registry; single self-labelling operand."+["pipelex/hub.py::PipelexHub.set_pipe_library"]param = "pipe_library"rationale = "Hub setter: installs the pipe library; single self-labelling operand."@@ -3664,6 +3672,10 @@ rationale = "Context manager scoping to the library named by the id; single operparam = "event_log"rationale = "Context manager scoping the given event log; single self-labelling operand."+["pipelex/hub.py::scoped_pipe_func_executor"]+param = "pipe_func_executor"+rationale = "Scoped-binding context manager: binds the pipe-func executor for the block; single self-labelling operand."+["pipelex/hub.py::scoped_pipe_router"]param = "pipe_router"rationale = "Context manager scoping the given pipe router; single self-labelling operand."@@ -4220,6 +4232,10 @@ rationale = "Verb-object: resolves the field blueprint; context stays keyword."param = "item"rationale = "Verb-object: validates the item; expectations stay keyword."+["pipelex/pipe_operators/func/pipe_func_execution_transport.py::pipe_func_execution_result_from_response"]+param = "response"+rationale = "Converter: rebinds a transported response into a result; single self-labelling operand."+["pipelex/pipe_operators/img_gen/img_gen_prompt_blueprint.py::ImgGenPromptBlueprint._extract_direct_image"]param = "image_ref"rationale = "Verb-object: extracts from the image ref; context stays keyword."@@ -5176,6 +5192,14 @@ rationale = "Factory from source: builds the result from the extra_config; singlparam = "registrar"rationale = "Plugin protocol register: the registrar is the sole sink the plugin populates."+["pipelex/plugins/pipe_func/pipe_func_plugin.py::PipeFuncPlugin.register"]+param = "registrar"+rationale = "Plugin entrypoint: registers into the registrar; single self-labelling operand, consistent with sibling plugins."++["pipelex/plugins/pipe_func/pipe_func_plugin.py::_make_direct_pipe_func_executor"]+param = "config"+rationale = "PipeFuncExecutorFactoryFn implementation: the registry invokes factories positionally via the Callable type."+["pipelex/plugins/portkey/portkey_completions_factory.py::PortkeyCompletionsFactory.make_portkey_openai_client_for_completions"]param = "model_handle"rationale = "Factory from source: builds the result from the model_handle; single operand."@@ -5232,6 +5256,10 @@ rationale = "Registers the factory callable as the sole operand."param = "factory"rationale = "Registers the factory callable as the sole operand."+["pipelex/plugins/registrar.py::PluginRegistrar.claim_pipe_func_executor"]+param = "factory"+rationale = "Registrar claim: claims the pipe-func executor hub slot with a factory; single self-labelling operand, consistent with sibling claims."+["pipelex/plugins/registrar.py::PluginRegistrar.claim_pipe_router"]param = "factory"rationale = "Registers the factory callable as the sole operand."@@ -5544,6 +5572,10 @@ rationale = "Derivation from the function; single operand."param = "file_path"rationale = "Verb-object: registers funcs in the file; options stay keyword."+["pipelex/system/registries/func_registry_utils.py::FuncRegistryUtils.read_py_sources"]+param = "folder_path"+rationale = "Folder reader: captures py sources under the folder; single self-labelling operand, consistent with register_funcs_in_folder."+["pipelex/system/registries/func_registry_utils.py::FuncRegistryUtils.register_funcs_in_folder"]param = "folder_path"rationale = "Verb-object: registers funcs under the folder path; options stay keyword."diff --git a/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.py b/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.pynew file mode 100644index 000000000..d42d0ad5f--- /dev/null+++ b/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.py@@ -0,0 +1,119 @@+import tempfile+from collections.abc import Generator+from pathlib import Path++import pytest++from pipelex.config import get_config+from pipelex.hub import get_library_manager, scoped_current_library+from pipelex.libraries.exceptions import LibraryError+from pipelex.system.registries.func_registry import func_registry++HOSTED_DEMO_MTHDS = """\+domain = "hosted_demo"+description = "Hosted PipeFunc demo"++[concept]+Note = "A note produced by customer code"++[pipe.make_note]+type = "PipeFunc"+description = "Build a note via customer-supplied code that lives only in the sandbox"+inputs = {}+output = "Note"+function_name = "make_note_in_sandbox"+"""++CUSTOMER_FUNC_PY = """\+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.stuffs.text_content import TextContent+from pipelex.system.registries.func_registry import pipe_func+++@pipe_func(name="make_note_in_sandbox")+async def make_note_in_sandbox(working_memory: WorkingMemory) -> TextContent:+ return TextContent(text="hello from the sandbox")+"""+++def sandbox_hosted_mode() -> Generator[None, None, None]:+ """Select a non-``direct`` execution mode for the duration of a test, then restore it.++ Flipping config (not monkeypatching the helper) exercises the genuine+ is_pipe_func_sandbox_hosted() read at every call site (loader + validators) together: any+ non-``direct`` mode is sandbox-hosted. The concrete sandbox modes live in the out-of-tree closed+ plugin, so this open-core test uses a neutral ``"sandbox"`` token — it only flips the hosted flag+ (the executor already on the hub is never re-resolved here), so no registered mode is needed.+ """+ pipe_func_config = get_config().pipelex.pipe_func_config+ previous = pipe_func_config.execution_mode+ pipe_func_config.execution_mode = "sandbox"+ try:+ yield+ finally:+ pipe_func_config.execution_mode = previous+++class TestHostedPipeFuncLoad:+ """Sandbox-hosted load: the customer's PipeFunc .py is captured as crate source and is NEVER+ registered/executed in this process, yet the method still loads (validators skip the callable).+ """++ @pytest.mark.usefixtures("sandbox_hosted_mode")+ def test_hosted_load_captures_source_without_registering(self):+ library_manager = get_library_manager()+ function_name = "make_note_in_sandbox"+ # Guard the precondition: the customer function must not already be in the process registry.+ assert func_registry.get_function(function_name) is None++ with tempfile.TemporaryDirectory() as tmp_dir:+ library_dir = Path(tmp_dir)+ (library_dir / "make_note.mthds").write_text(HOSTED_DEMO_MTHDS, encoding="utf-8")+ (library_dir / "customer_func.py").write_text(CUSTOMER_FUNC_PY, encoding="utf-8")++ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ # Loads cleanly even though the function is absent here: hosted-mode validators skip+ # the func_registry lookup and the return-type check.+ pipes = library_manager.load_libraries(library_id=library_id, library_dirs=[library_dir])+ assert any(pipe.code == "make_note" for pipe in pipes)++ # The customer code was NOT imported/registered in this process.+ assert func_registry.get_function(function_name) is None++ # The .py source rode along on the crate, ready to travel to a sandbox.+ crate = library_manager.get_crate(library_id=library_id)+ assert crate is not None+ assert crate.python_sources.get("customer_func.py") == CUSTOMER_FUNC_PY+ # Carrying source leaves the structural fingerprint untouched.+ assert crate.fingerprint == crate.compute_fingerprint()+ finally:+ library_manager.teardown(library_id=library_id)++ # Side-state is cleaned up on teardown: a fresh crate for the same id is gone.+ assert library_manager.get_crate(library_id=library_id) is None++ @pytest.mark.usefixtures("sandbox_hosted_mode")+ def test_hosted_load_rejects_colliding_source_paths(self):+ """Two library dirs sharing a source relpath (with different content) must fail loud, not+ silently overwrite one customer's PipeFunc body — the sandbox writes sources flat by relpath.+ """+ library_manager = get_library_manager()++ with tempfile.TemporaryDirectory() as tmp_dir:+ dir_a = Path(tmp_dir) / "a"+ dir_b = Path(tmp_dir) / "b"+ dir_a.mkdir()+ dir_b.mkdir()+ # Same relative path in both dirs, different content -> a genuine conflict.+ (dir_a / "customer_func.py").write_text(CUSTOMER_FUNC_PY, encoding="utf-8")+ (dir_b / "customer_func.py").write_text(CUSTOMER_FUNC_PY.replace("hello from the sandbox", "a different body"), encoding="utf-8")++ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id), pytest.raises(LibraryError, match="Duplicate PipeFunc source path"):+ library_manager.load_libraries(library_id=library_id, library_dirs=[dir_a, dir_b])+ finally:+ library_manager.teardown(library_id=library_id)diff --git a/tests/integration/pipelex/system/test_hub_slot_injection_precedence.py b/tests/integration/pipelex/system/test_hub_slot_injection_precedence.pyindex 44fd94a2d..de4c8d6c9 100644--- a/tests/integration/pipelex/system/test_hub_slot_injection_precedence.py+++ b/tests/integration/pipelex/system/test_hub_slot_injection_precedence.py@@ -16,7 +16,9 @@ from pytest_mock import MockerFixturefrom pipelex.hub import get_content_generator, get_pipe_routerfrom pipelex.pipelex import Pipelex-from pipelex.plugins.registrar import HubSlot, PluginRegistrar+from pipelex.plugins.contract import PLUGIN_API_VERSION+from pipelex.plugins.pipe_func.pipe_func_plugin import PipeFuncPlugin+from pipelex.plugins.registrar import HubSlot, PluginOrigin, PluginRegistrarfrom pipelex.system.runtime import IntegrationMode, runtime_managerfrom pipelex.tools.secrets.env_secrets_provider import EnvSecretsProviderfrom pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider@@ -40,12 +42,15 @@ def _test_integration_mode() -> IntegrationMode:def _fake_registrar(mocker: MockerFixture) -> PluginRegistrar:"""A registrar with empty registries (boot stores them but doesn't consume them during setup).- Storage and secrets are the exceptions: boot *does* select each provider from the registrar during- setup, so every boot below passes an explicit ``storage_provider`` and ``secrets_provider`` — each- wins ahead of the (empty) registry — keeping this suite focused on hub slots rather than- storage/secrets selection.+ Storage, secrets, and pipe_func are the exceptions: boot *does* select each from the registrar+ during setup. Every boot below passes an explicit ``storage_provider`` and ``secrets_provider``+ (each wins ahead of the empty registry), and the built-in ``PipeFuncPlugin`` is registered here so+ the default ``direct`` execution mode resolves — keeping this suite focused on hub slots rather+ than provider/executor selection."""registrar = PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace(temporal=SimpleNamespace(is_enabled=False))))+ registrar.begin_plugin(name="pipe_func", origin=PluginOrigin.BUILTIN, targets_api=PLUGIN_API_VERSION)+ PipeFuncPlugin().register(registrar)mocker.patch("pipelex.pipelex.build_registrar", return_value=registrar)return registrardiff --git a/tests/unit/pipelex/libraries/test_library_crate_python_sources.py b/tests/unit/pipelex/libraries/test_library_crate_python_sources.pynew file mode 100644index 000000000..ffd3f99ae--- /dev/null+++ b/tests/unit/pipelex/libraries/test_library_crate_python_sources.py@@ -0,0 +1,56 @@+from typing import ClassVar++from pipelex.libraries.library_crate import LibraryCrate+from pipelex.libraries.library_crate_factory import LibraryCrateFactory+from tests.unit.pipelex.libraries.test_library_crate_data import BlueprintSamples+++class TestLibraryCratePythonSources:+ """Sandbox-hosted source capture on the crate: round-trips, but never touches the fingerprint."""++ _SOURCES: ClassVar[dict[str, str]] = {+ "funcs/score.py": "from pipelex.core.memory.working_memory import WorkingMemory\n\n\ndef compute_score(working_memory): ...\n",+ "structures/weighted_score.py": "from pydantic import BaseModel\n\n\nclass WeightedScore(BaseModel):\n value: float\n",+ }++ def test_python_sources_default_empty(self):+ """A crate built without python_sources carries an empty dict (local/direct mode)."""+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE])+ assert crate.python_sources == {}++ def test_python_sources_round_trip(self):+ """python_sources survives a JSON round-trip verbatim, alongside the rest of the crate."""+ crate = LibraryCrateFactory.make_from_blueprints(+ blueprints=[BlueprintSamples.SCORING_BUNDLE],+ python_sources=self._SOURCES,+ )+ assert crate.python_sources == self._SOURCES++ restored = LibraryCrate.model_validate_json(crate.model_dump_json())+ assert restored.python_sources == self._SOURCES+ # The rest of the crate is unaffected by carrying source.+ assert restored.concepts == crate.concepts+ assert restored.pipes == crate.pipes+ assert restored.fingerprint == crate.fingerprint++ def test_fingerprint_excludes_python_sources(self):+ """The structural fingerprint is identical whether or not source travels, and regardless of its content.++ Folding source into the fingerprint would break load_from_crate's structural-dedupe contract,+ so two crates that differ ONLY in python_sources must hash the same.+ """+ bare = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE])+ with_sources = LibraryCrateFactory.make_from_blueprints(+ blueprints=[BlueprintSamples.SCORING_BUNDLE],+ python_sources=self._SOURCES,+ )+ other_sources = LibraryCrateFactory.make_from_blueprints(+ blueprints=[BlueprintSamples.SCORING_BUNDLE],+ python_sources={"funcs/score.py": "def compute_score(working_memory): return 42\n"},+ )++ assert bare.fingerprint != ""+ assert bare.fingerprint == with_sources.fingerprint+ assert with_sources.fingerprint == other_sources.fingerprint+ # And the instance method agrees: source is not part of compute_fingerprint.+ assert with_sources.compute_fingerprint() == bare.compute_fingerprint()diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.pynew file mode 100644index 000000000..c3a133e77--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.py@@ -0,0 +1,33 @@+"""The open PipeFunc-execution transport DTOs: the generic out-of-process request/response primitive.++These moved from the closed sandbox package into open pipelex so a host runtime (the Temporal+activity) can carry a PipeFunc execution across its boundary without importing any sandbox code. The+response must be JSON-serialization-safe (it crosses the Temporal activity boundary), and the request+must forbid extras (it is a wire contract).+"""++from pipelex.pipe_operators.func.pipe_func_execution_transport import (+ DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,+ PipeFuncExecutionRequest,+ PipeFuncExecutionResponse,+)+++class TestPipeFuncExecutionTransport:+ def test_response_round_trips_via_json(self) -> None:+ """The transported response survives a JSON round-trip unchanged (it crosses the activity boundary)."""+ response = PipeFuncExecutionResponse(+ output_memory_raw={"main_stuff_name": "result", "stuffs": {}},+ function_module="my_pkg.funcs",+ function_qualname="compute",+ )+ again = PipeFuncExecutionResponse.model_validate_json(response.model_dump_json())+ assert again == response++ def test_request_is_a_forbid_extra_wire_contract_with_default_timeout(self) -> None:+ """The request forbids unknown fields (wire contract) and defaults the runaway-code timeout."""+ assert PipeFuncExecutionRequest.model_config.get("extra") == "forbid"+ assert "crate" in PipeFuncExecutionRequest.model_fields+ assert "working_memory_raw" in PipeFuncExecutionRequest.model_fields+ assert PipeFuncExecutionRequest.model_fields["timeout_seconds"].default == DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS+ assert DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS == 5.0diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.pynew file mode 100644index 000000000..3c0e71d17--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.py@@ -0,0 +1,62 @@+from typing import Callable++import pytest+from pydantic import ValidationError+from pytest_mock import MockerFixture++from pipelex.core.pipes.pipe_factory import PipeFactory+from pipelex.pipe_operators.func.pipe_func import PipeFunc+from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint++_UNREGISTERED = PipeFuncBlueprint(+ description="Hosted-mode case: function lives only in the sandbox, never in this process.",+ inputs={},+ output="native.Text",+ function_name="a_function_that_is_not_registered_here",+)+++def _make_pipe_func() -> PipeFunc:+ return PipeFactory[PipeFunc].make_from_blueprint(+ domain_code="hosted_test",+ pipe_code="hosted_pipe",+ blueprint=_UNREGISTERED,+ )+++class TestPipeFuncHostedMode:+ """In sandbox-hosted mode the PipeFunc validators accept a function that is absent from this+ process's func_registry; in local/direct mode the same input still raises.+ """++ def test_local_mode_rejects_unregistered_function(self, load_empty_library: Callable[[], str]):+ """Default (local) mode is unchanged: an unregistered function_name fails construction."""+ load_empty_library()+ with pytest.raises(ValidationError, match="not found in registry"):+ _make_pipe_func()++ def test_hosted_mode_accepts_unregistered_function_name(+ self,+ load_empty_library: Callable[[], str],+ mocker: MockerFixture,+ ):+ """Hosted mode skips the func_registry lookup, so the declared name is accepted verbatim."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)++ pipe_func = _make_pipe_func()++ assert pipe_func.function_name == "a_function_that_is_not_registered_here"++ def test_hosted_mode_skips_output_validation(+ self,+ load_empty_library: Callable[[], str],+ mocker: MockerFixture,+ ):+ """validate_output_with_library is a no-op in hosted mode (the sandbox validates for real)."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)++ pipe_func = _make_pipe_func()+ # Must not raise even though the function is not registered and its return type is unknown here.+ pipe_func.validate_output_with_library()diff --git a/tests/unit/pipelex/plugins/test_pipe_func_executor_registry.py b/tests/unit/pipelex/plugins/test_pipe_func_executor_registry.pynew file mode 100644index 000000000..586242f5d--- /dev/null+++ b/tests/unit/pipelex/plugins/test_pipe_func_executor_registry.py@@ -0,0 +1,112 @@+"""The PipeFunc-executor seam: the registrar collects per-mode executor factories into a registry.++Pins the seam independent of the real built-in modes: a factory registered for a mode is the one the+registry hands back; a miss raises ``UnknownPipeFuncExecutionModeError`` listing the registered modes;+a second registration for the same mode fails loud naming both plugins; an empty registry misses every+mode. Also pins that the built-in ``PipeFuncPlugin`` contributes exactly ``direct`` (the one in-process+mode core owns — sandbox modes come from the out-of-tree closed plugin) and that ``direct`` resolves to+the in-process executor.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++import pytest++from pipelex.pipe_operators.func.direct_pipe_func_executor import DirectPipeFuncExecutor+from pipelex.plugins.contract import PLUGIN_API_VERSION+from pipelex.plugins.exceptions import DuplicatePipeFuncExecutorError, UnknownPipeFuncExecutionModeError+from pipelex.plugins.pipe_func.pipe_func_plugin import PipeFuncPlugin+from pipelex.plugins.pipe_func_executor_registry import DIRECT_PIPE_FUNC_EXECUTION_MODE, PipeFuncExecutorRegistry+from pipelex.plugins.registrar import PluginOrigin, PluginRegistrar++if TYPE_CHECKING:+ from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocol+ from pipelex.system.configuration.configs import PipelexConfig+ from pipelex.system.configuration.pipe_func_config import PipeFuncConfig+++def _make_registrar() -> PluginRegistrar:+ return PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace(plugins=SimpleNamespace(disabled=[]))))+++def _fake_factory(_config: PipeFuncConfig) -> PipeFuncExecutorProtocol:+ """Stand-in factory: identity is all the registry tests assert (never actually invoked here)."""+ return DirectPipeFuncExecutor()+++class TestPipeFuncExecutorRegistry:+ def test_registered_factory_is_retrievable_by_mode(self) -> None:+ """A factory registered for a mode is the exact callable the built registry returns for it."""+ registrar = _make_registrar()+ registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION)+ registrar.add_pipe_func_executor(mode="daytona", factory=_fake_factory)++ registry = PipeFuncExecutorRegistry(registrar.pipe_func_executors)+ assert registry.get_required(mode="daytona") is _fake_factory+ assert registry.has(mode="daytona")+ assert registry.modes == ["daytona"]++ def test_contribution_recorded_on_the_active_plugin(self) -> None:+ """Registering an executor records a ``pipe_func executor <mode>`` contribution on the plugin's discovery."""+ registrar = _make_registrar()+ discovery = registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION)++ registrar.add_pipe_func_executor(mode="daytona", factory=_fake_factory)++ assert "pipe_func executor daytona" in discovery.contributions++ def test_get_required_miss_raises_listing_registered_modes(self) -> None:+ """A miss names the requested mode and lists the registered ones (the boot-time actionable error)."""+ registrar = _make_registrar()+ registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION)+ registrar.add_pipe_func_executor(mode="direct", factory=_fake_factory)+ registrar.add_pipe_func_executor(mode="local_sandbox", factory=_fake_factory)+ registry = PipeFuncExecutorRegistry(registrar.pipe_func_executors)++ with pytest.raises(UnknownPipeFuncExecutionModeError) as exc_info:+ registry.get_required(mode="daytona")++ assert exc_info.value.mode == "daytona"+ assert set(exc_info.value.registered_modes) == {"direct", "local_sandbox"}+ message = str(exc_info.value)+ assert "direct" in message+ assert "local_sandbox" in message++ def test_empty_registry_misses_every_mode(self) -> None:+ """A registry with no factories misses every mode — soft via has, loud via get_required."""+ registry = PipeFuncExecutorRegistry({})++ assert not registry.has(mode="direct")+ assert registry.modes == []+ with pytest.raises(UnknownPipeFuncExecutionModeError):+ registry.get_required(mode="direct")++ def test_duplicate_mode_fails_loud_naming_both_plugins(self) -> None:+ """Two plugins registering an executor for the same mode is a fail-loud conflict naming both."""+ registrar = _make_registrar()+ registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION)+ registrar.add_pipe_func_executor(mode="daytona", factory=_fake_factory)+ registrar.begin_plugin(name="beta", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION)++ with pytest.raises(DuplicatePipeFuncExecutorError) as exc_info:+ registrar.add_pipe_func_executor(mode="daytona", factory=_fake_factory)++ assert exc_info.value.first_plugin == "alpha"+ assert exc_info.value.second_plugin == "beta"+ assert exc_info.value.mode == "daytona"++ def test_builtin_plugin_registers_only_direct(self) -> None:+ """The core PipeFuncPlugin contributes exactly ``direct`` (in-process); sandbox modes are out of tree."""+ registrar = _make_registrar()+ registrar.begin_plugin(name="pipe_func", origin=PluginOrigin.BUILTIN, targets_api=PLUGIN_API_VERSION)+ PipeFuncPlugin().register(registrar)++ registry = PipeFuncExecutorRegistry(registrar.pipe_func_executors)+ assert registry.modes == [DIRECT_PIPE_FUNC_EXECUTION_MODE]++ pipe_func_config = cast("PipeFuncConfig", SimpleNamespace(execution_mode=DIRECT_PIPE_FUNC_EXECUTION_MODE))+ direct_executor = registry.get_required(mode=DIRECT_PIPE_FUNC_EXECUTION_MODE)(pipe_func_config)+ assert isinstance(direct_executor, DirectPipeFuncExecutor)diff --git a/tests/unit/pipelex/plugins/test_plugin_discovery.py b/tests/unit/pipelex/plugins/test_plugin_discovery.pyindex 5dc04a1ce..9efa20d7d 100644--- a/tests/unit/pipelex/plugins/test_plugin_discovery.py+++ b/tests/unit/pipelex/plugins/test_plugin_discovery.py@@ -191,9 +191,9 @@ class TestPluginDiscovery:disabled_discovery = next(discovery for discovery in registrar.discoveries if discovery.name == "optional")assert disabled_discovery.status == PluginStatus.DISABLED- @pytest.mark.parametrize("plugin_name", ["direct", "storage", "secrets", "openai"])+ @pytest.mark.parametrize("plugin_name", ["direct", "pipe_func", "storage", "secrets", "openai"])def test_disabling_core_unconditional_plugin_raises(self, plugin_name: str) -> None:- """Denylisting any plugin core requires unconditionally (storage/secrets included) is a startup error."""+ """Denylisting any plugin core requires unconditionally (pipe_func/storage/secrets included) is a startup error."""with pytest.raises(CoreUnconditionalPluginDisabledError) as exc_info:build_registrar(config=_fake_config([plugin_name]))assert plugin_name in str(exc_info.value)diff --git a/tests/unit/pipelex/tools/test_read_py_sources.py b/tests/unit/pipelex/tools/test_read_py_sources.pynew file mode 100644index 000000000..010d895a6--- /dev/null+++ b/tests/unit/pipelex/tools/test_read_py_sources.py@@ -0,0 +1,38 @@+import sys+from pathlib import Path++from pipelex.system.registries.func_registry_utils import FuncRegistryUtils+++class TestReadPySources:+ """read_py_sources captures every .py as text, recursively, WITHOUT ever importing it."""++ def test_captures_nested_sources_without_importing(self, tmp_path: Path):+ """Nested .py files are captured by POSIX relpath, and no file is imported (sys.modules untouched).++ Each fixture file imports a module that does not exist: if read_py_sources imported any of+ them, the import would raise ModuleNotFoundError. It must not — it only reads the bytes.+ """+ top_source = "import this_module_does_not_exist_top # noqa\n\nTOP = 1\n"+ nested_source = "import this_module_does_not_exist_nested # noqa\n\nNESTED = 2\n"+ (tmp_path / "top.py").write_text(top_source, encoding="utf-8")+ nested_dir = tmp_path / "structures"+ nested_dir.mkdir()+ (nested_dir / "item.py").write_text(nested_source, encoding="utf-8")++ modules_before = set(sys.modules)++ sources = FuncRegistryUtils.read_py_sources(folder_path=tmp_path)++ assert sources == {+ "top.py": top_source,+ "structures/item.py": nested_source,+ }+ # No import happened: the phantom modules are absent and sys.modules is unchanged.+ assert "this_module_does_not_exist_top" not in sys.modules+ assert "this_module_does_not_exist_nested" not in sys.modules+ assert set(sys.modules) == modules_before++ def test_empty_folder_returns_empty(self, tmp_path: Path):+ """A folder with no Python files yields an empty mapping."""+ assert FuncRegistryUtils.read_py_sources(folder_path=tmp_path) == {}diff --git a/wip/drift-contracts/dogfood-log.md b/wip/drift-contracts/dogfood-log.mdindex 2fc01d2f3..ecbae5b83 100644--- a/wip/drift-contracts/dogfood-log.md+++ b/wip/drift-contracts/dogfood-log.md@@ -5,3 +5,4 @@ One entry per ack. Verdicts: **real-catch** (the review found actual staleness),- **2026-07-10 · keyword-only-convention · real-catch** — the guard gained the subject-grant registry (new violation kinds, literal-subject ban, symmetric staleness); the convention doc was materially stale and was rewritten as part of the same change — exactly the coupling this contract exists to enforce.- **2026-07-10 · cli-docs · clean-pass** — the keyword-only sweep touched many pipelex/cli files (kwonly'd internal signatures, two escape hatches, call-site keywords); reviewed docs/tools/cli/ and the agent-CLI CLAUDE.md — no command, flag, or output changed, both targets stay accurate.- **2026-07-11 · config-docs · clean-pass** — opened by dev's Python-3.10 drop reaching the branch via the Phase-M merge (StrEnum import swap in `img_gen_job_components.py`); reviewed docs/configuration/ — no config field, default, or documented behavior changed. *(Backfilled 2026-07-12: the ack was recorded during the subject-grants regrind without its mandatory log entry — process slip, not a review slip.)*+- **2026-07-16 · config-docs · clean-pass** — opened by comment-only wording fixes in `pipelex.toml` + `pipe_func_config.py` (dropped the stale core-`local_sandbox` mode claim, "our Daytona plugin" naming); reviewed docs/configuration/ — no field, default, or documented behavior changed, and the stale mode was never documented there. Note: the trigger correctly caught a *comment* fix in the shipped defaults file, which is user-readable surface — not friction.