loader.py
1"""Load a saved project only inside its selected Agent interpreter."""23from __future__ import annotations45import importlib.util6from pathlib import Path7import sys8from typing import TYPE_CHECKING, Any, Union910from .lifecycle import AgentStartupError1112if TYPE_CHECKING: # Annotation only.13 from os import PathLike1415 from sim_platform.sdk.context import AgentContext161718class ProjectFactory:19 """Agent factory that imports a saved project's agent.py inside the Agent child.2021 Created per launch with the project's source folder; calling it imports the22 module once and returns create_agent(context).23 """2425 def __init__(self, directory: Union[str, PathLike[str]]) -> None:26 self.directory = directory2728 def __call__(self, context: AgentContext) -> Any:29 root = Path(self.directory)30 # Project-local imports are allowed. SDK resolution comes from installed site-packages.31 sys.path.insert(0, str(root))32 specification = importlib.util.spec_from_file_location('agent', root / 'agent.py')33 if specification is None or specification.loader is None:34 raise AgentStartupError('AGENT_ENTRYPOINT_INVALID')35 module = importlib.util.module_from_spec(specification)36 sys.modules['agent'] = module37 try:38 specification.loader.exec_module(module)39 except ModuleNotFoundError as exc:40 raise AgentStartupError('AGENT_DEPENDENCY_MISSING') from exc41 factory = getattr(module, 'create_agent', None)42 if not callable(factory):43 raise AgentStartupError('AGENT_ENTRYPOINT_INVALID')44 return factory(context)