m/market labResearch, with a record.
Source on GitHub ↗

projects.py

1"""Connect static project inspection, private files and the existing Agent revisions."""23from __future__ import annotations45from pathlib import Path6from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast78from sim_platform.agents.projects.inspection import inspect_project9from sim_platform.domain.models import ContractError10from sim_platform.domain.json_values import copy_json11from sim_platform.application.identifiers import identifier12from sim_platform.resources import cleanup_after_error1314if TYPE_CHECKING:  # Annotation only.15    from os import PathLike1617    from sim_platform.application.api_types import AgentRevisionDetails18    from sim_platform.application.operations import DatabaseOperations19    from sim_platform.persistence.agents.projects import ProjectFiles2021# Tools an imported Agent may use when the caller does not list them.22DEFAULT_REQUIRES = ['market.quote', 'control.finish', 'model.request']23# Default prompt and schedule for an imported strategy.24DEFAULT_INITIAL_PROMPT = 'Evaluate trading opportunities; no trade is required.'25DEFAULT_INTERVAL_SECONDS = '30'262728class AgentProjects:29    """Imports Agent source projects as private snapshots plus Agent revisions.3031    Platform creates one with its database operations and project files; it holds32    no other state.33    """3435    def __init__(self, operations: DatabaseOperations, files: ProjectFiles) -> None:36        self.operations, self.files = operations, files3738    def check(self, source: Union[str, PathLike[str]]) -> Dict[str, Any]:39        """Inspect a project without saving it; includes the excluded file list."""40        files, excluded = self.files.capture(source)41        return dict(inspect_project(files), excluded=excluded)4243    def import_project(44        self,45        profile: str,46        source: Union[str, PathLike[str]],47        *,48        name: Optional[str] = None,49        agent_id: Optional[str] = None,50        expected_revision: Optional[int] = None,51        integration: str = 'python_strategy',52        initial_prompt: str = DEFAULT_INITIAL_PROMPT,53        parameters: Optional[Dict[str, Any]] = None,54        requires: Optional[List[str]] = None,55        model_profile_ref: str = 'user-model',56        schedule: Optional[Dict[str, Any]] = None,57    ) -> AgentRevisionDetails:58        """Publish files first, then append one Agent revision in a short existing SQL UOW."""59        if integration not in ('python_strategy', 'python_carrier'):60            raise ContractError('imported source requires python_strategy or python_carrier')61        if expected_revision is not None:62            if agent_id is None:63                raise ContractError('an update needs agent_id and expected_revision')64            self.operations.agent(profile, agent_id, expected_revision)65        captured, excluded = self.files.capture(source)66        report = dict(inspect_project(captured), excluded=excluded)67        snapshot = self.files.save(captured, dict(report, profile_id=profile))68        try:69            definition = dict(70                agent_id=identifier() if agent_id is None else agent_id,71                revision=str(1 if expected_revision is None else expected_revision + 1),72                name=Path(source).stem if name is None else name,73                integration=integration,74                carrier='custom' if integration == 'python_carrier' else 'platform',75                initial_prompt=initial_prompt,76                parameters={} if parameters is None else parameters,77                requires=(list(DEFAULT_REQUIRES) if requires is None else requires),78                model_profile_ref=model_profile_ref,79                package=dict(project_ref=snapshot['project_ref']),80            )81            if integration == 'python_strategy':82                definition['schedule'] = (83                    schedule84                    if schedule is not None85                    else dict(86                        mode='interval',87                        interval_seconds=DEFAULT_INTERVAL_SECONDS,88                        busy_event_policy='preserve_interval',89                        events=[],90                    )91                )92            elif schedule is not None:93                raise ContractError('resident carriers do not accept a platform schedule')94            if expected_revision is None:95                return self.operations.create_agent(profile, definition)96            # An update was checked above to name its agent_id.97            return self.operations.update_agent(98                profile, cast(str, agent_id), expected_revision, definition99            )100        except Exception as exc:101            cleanup_after_error(exc, lambda: self.files.discard(snapshot['project_ref']))102            raise103104    def project(105        self, profile: str, agent_id: str, revision: Optional[int] = None106    ) -> Tuple[Dict[str, str], Dict[str, Any]]:107        """Resolve ownership through SQL before accessing a private project snapshot."""108        saved = self.operations.agent(profile, agent_id, revision)109        package = cast(Optional[Dict[str, Any]], saved['definition'].get('package'))110        if not package:111            raise ContractError('this Agent uses the built-in template and has no source project')112        files, report = self.files.read(package['project_ref'], profile)113        inspected = inspect_project(files, default_python=report['python'])114        if any(report.get(key) != value for key, value in inspected.items()):115            raise ContractError('saved Agent project inspection differs from its metadata')116        return files, dict(copy_json(report), agent_id=agent_id, revision=saved['revision'])