platform_agents.py
1"""Agent projects, Python environments and saved Agent revisions for Platform."""23from __future__ import annotations4from typing import (5 TYPE_CHECKING,6 Any,7 Dict,8 List,9 Optional,10 Union,11)12from .api_types import (13 AgentExperimentDetails,14 AgentRevisionDetails,15 JsonObject,16)17from sim_platform.domain.models import ContractError1819if TYPE_CHECKING:20 from sim_platform.agents.environments.preparation import EnvironmentPreparation21 from sim_platform.agents.runtimes.manager import RuntimePreparation22 from sim_platform.execution.models import ExecutionConfig23 from sim_platform.market.playback import MarketPlayback24 from sim_platform.market.prepared.session import PreparedSession2526 MarketInput = Union[MarketPlayback, PreparedSession]2728from .platform_base import PlatformBase, PathInput293031class PlatformAgents(PlatformBase):32 """Agent projects, Python environments and saved Agent revisions for Platform."""3334 def check_agent_project(self, source: PathInput) -> JsonObject:35 """Check Agent source without saving it, importing it or running its code.3637 Accept a Python file or a folder containing agent.py. The factory must be38 create_agent(context). Check Python syntax, requirements.txt and optional39 agent.json (python major.minor only). Private/generated files are excluded;40 symlinks, special files, oversized inputs and unsupported requirements fail.4142 Args:43 source: Local Python file or Agent project folder selected by the user.4445 Returns:46 JsonObject: entrypoint, python, requirements, files inventory and excluded paths.47 This is a static check; it does not prove that imports or Agent.run succeed.4849 Raises:50 ContractError: Invalid project, syntax, entrypoint, settings or dependency format.51 OSError: The selected source cannot be read.5253 Example:54 report = app.check_agent_project('/absolute/path/my_agent.py')55 print(report['requirements'])56 """57 self._resources.check_open()58 return self._agent_projects.check(source)5960 def agent_journal(self, profile_id: str, run_id: str) -> List[JsonObject]:61 """Read the notes an Agent wrote with journal.write during a finished run.6263 Use it to see why an Agent decided as it did, or to carry an Agent's beliefs into64 its next run (the manager_analyst reference Agent writes them each round).6566 Returns:67 list: Notes in order, each with ``text`` and the market ``time_ns`` it was68 written at; empty without an archived log.6970 Example:71 notes = app.agent_journal(profile_id, run_id)72 """73 archive: Dict[str, Any] = dict(self.agent_log_archive(profile_id, run_id) or {})74 notes: List[JsonObject] = []75 for record in archive.get('records') or []:76 request = record.get('request') or {}77 if record.get('kind') == 'tool' and request.get('tool') == 'journal.write':78 position = record.get('position') or {}79 notes.append(80 dict(81 text=str((request.get('arguments') or {}).get('text', '')),82 time_ns=int(position.get('time_ns', 0)),83 )84 )85 return notes8687 def decision_timeline(self, profile_id: str, run_id: str) -> JsonObject:88 """Link each order of an Agent run to the reads, model replies and notes before it.8990 Lays out every round of Agent work (one per scheduled turn) step by step from the91 archived Agent log and, for each order, lists the data the Agent read and the92 model replies it received earlier in the same round, the journal notes written93 before and after it in that round, and the order's fills. Attribution is by94 order of events within a round: a read listed before an order shows the Agent95 had that information, not that it used it.9697 Args:98 profile_id: Profile ID returned by create_profile(); selects whose data to access.99 run_id: A finished Agent run owned by the profile.100101 Returns:102 JsonObject: ``rounds`` (``work_id``, ``started_ns``, ``reason``, ``steps``)103 and ``orders`` (``order_id``, ``time_ns``, ``summary``, ``reads``,104 ``model_replies``, ``notes_before``, ``notes_after``, ``fills``); both empty105 without an archived log. See research.attribution.decision_timeline.106107 Raises:108 ContractError: If the profile or run does not exist or the profile does not own it.109110 Example:111 timeline = app.decision_timeline(profile_id, run_id)112 for order in timeline['orders']:113 print(order['summary'], [read['summary'] for read in order['reads']])114 """115 from sim_platform.research.attribution import decision_timeline116117 archive = self.agent_log_archive(profile_id, run_id)118 return decision_timeline(archive, self._operations.run_events(profile_id, run_id))119120 def reference_agents(self) -> List[JsonObject]:121 """List the built-in reference Agents that follow published architectures.122123 Each record has ``key``, ``name``, ``paper``, ``url``, ``summary``, default124 ``parameters`` and the platform tools it ``requires``. Pass a key to125 import_reference_agent() to save one as an ordinary Agent.126127 Returns:128 list: Detached catalogue records; reading it changes nothing.129130 Example:131 keys = [entry['key'] for entry in app.reference_agents()]132 """133 from sim_platform.reference_agents import reference_agents134135 return [{k: v for k, v in entry.items() if k != 'path'} for entry in reference_agents()]136137 def import_reference_agent(138 self,139 profile_id: str,140 key: str,141 *,142 name: Optional[str] = None,143 parameters: Optional[JsonObject] = None,144 model_profile_ref: str = 'user-model',145 initial_prompt: str = 'Evaluate trading opportunities; no trade is required.',146 schedule: Optional[JsonObject] = None,147 ) -> AgentRevisionDetails:148 """Save a built-in reference Agent so it can be selected for experiments.149150 This is import_agent() with the reference project's source, tools and default151 parameters filled in. The saved revision then needs environment preparation and152 a model, like any imported Agent.153154 Args:155 profile_id: Existing owner profile.156 key: A key from reference_agents(), such as 'trading_agents'.157 name: Display name; None uses the catalogue name.158 parameters: Replaces the catalogue's default parameters when given.159 model_profile_ref: Saved model reference used by the Agent.160 initial_prompt: The task framing passed to the Agent.161 schedule: Platform schedule; None uses a 30-second interval. Each decision162 makes several model calls, so a longer interval is usually wiser.163164 Returns:165 AgentRevisionDetails: The saved revision, as import_agent() returns it.166167 Raises:168 ContractError: If the key is unknown or the import is refused.169170 Example:171 saved = app.import_reference_agent(profile_id, 'trading_agents')172 """173 from sim_platform.reference_agents import reference_agent174175 entry = reference_agent(key)176 return self.import_agent(177 profile_id,178 entry['path'],179 name=name or entry['name'],180 parameters=entry['parameters'] if parameters is None else parameters,181 requires=list(entry['requires']),182 model_profile_ref=model_profile_ref,183 initial_prompt=initial_prompt,184 schedule=schedule,185 )186187 def import_agent(188 self,189 profile_id: str,190 source: PathInput,191 *,192 name: Optional[str] = None,193 agent_id: Optional[str] = None,194 expected_revision: Optional[int] = None,195 integration: str = 'python_strategy',196 initial_prompt: str = 'Evaluate trading opportunities; no trade is required.',197 parameters: Optional[JsonObject] = None,198 requires: Optional[List[str]] = None,199 model_profile_ref: str = 'user-model',200 schedule: Optional[JsonObject] = None,201 ) -> AgentRevisionDetails:202 """Copy Agent source into private storage and save an immutable Agent revision.203204 The caller edits their own file/folder and imports it again for an update.205 The saved copy is independent of the original path. Use agent_id together206 with expected_revision to append an update. Earlier source and experiments207 remain unchanged. No Agent program or dependency build hook is executed.208209 Args:210 profile_id: Existing owner profile.211 source: Python file, or folder with agent.py exporting create_agent(context).212 name: Display name; None uses the selected source's filename stem.213 agent_id: Omit for a new generated ID; supply for an update or chosen new ID.214 expected_revision: Latest revision expected when updating; None creates revision 1.215 integration: python_strategy for run(task), python_carrier for resident run().216 initial_prompt: Original system instructions available to the Agent factory.217 parameters: Agent-specific finite JSON; None uses an empty object.218 requires: Platform capabilities required by this Agent. None uses quote, finish219 and model.request. Local tools belong in source and need no platform grant.220 model_profile_ref: Saved model reference; credentials are never copied into settings.221 schedule: Platform schedule for python_strategy; None uses a 30-second interval.222 A resident python_carrier must omit it.223224 Returns:225 AgentRevisionDetails: The existing saved-Agent shape, with package.project_ref226 pointing to its source snapshot. This does not prepare or execute an experiment.227228 Raises:229 ContractError: Invalid project/configuration, ownership or revision conflict.230 OSError: Copy/publication fails; unsuccessful candidates are removed.231232 Example:233 saved = app.import_agent(profile_id, '/absolute/path/strategy', name='My Agent')234 print(saved['agent_id'], saved['revision'])235 """236 self._resources.check_open()237 return self._agent_projects.import_project(238 profile_id,239 source,240 name=name,241 agent_id=agent_id,242 expected_revision=expected_revision,243 integration=integration,244 initial_prompt=initial_prompt,245 parameters=parameters,246 requires=requires,247 model_profile_ref=model_profile_ref,248 schedule=schedule,249 )250251 def agent_project(252 self, profile_id: str, agent_id: str, revision: Optional[int] = None253 ) -> JsonObject:254 """Read the owned source inventory and dependency specification of an imported Agent.255256 Args:257 profile_id: Owner profile.258 agent_id: Saved imported Agent ID.259 revision: Specific immutable revision, or None for latest.260261 Returns:262 JsonObject: project_ref, entrypoint, python, requirements, files, excluded,263 agent_id and revision. No future-market paths, credentials or executable objects.264265 Raises:266 ContractError: Wrong owner, built-in template or inconsistent snapshot.267 OSError: Project files are missing or unreadable.268269 Example:270 project = app.agent_project(profile_id, saved['agent_id'])271 print(project['files'])272 """273 self._resources.check_open()274 return self._agent_projects.project(profile_id, agent_id, revision)[1]275276 def agent_project_file(277 self, profile_id: str, agent_id: str, path: str, revision: Optional[int] = None278 ) -> str:279 """Read one saved UTF-8 source/configuration file for display or editing elsewhere.280281 Args:282 profile_id: Owner profile.283 agent_id: Saved imported Agent ID.284 path: Exact relative inventory path, for example agent.py or tools/math.py.285 revision: Specific revision, or None for latest.286287 Returns:288 str: A detached text copy. Changing it does not edit the saved revision.289290 Raises:291 ContractError: Wrong owner or a path absent from the saved inventory.292 OSError: Saved files cannot be read.293294 Example:295 text = app.agent_project_file(profile_id, saved['agent_id'], 'agent.py')296 """297 self._resources.check_open()298 files, _ = self._agent_projects.project(profile_id, agent_id, revision)299 if not isinstance(path, str) or path not in files:300 raise ContractError('file is not in this Agent project')301 return files[path]302303 def export_agent_sdk(self, output: PathInput) -> JsonObject:304 """Write an installable SDK wheel for developing Agents outside the platform repo.305306 Args:307 output: Absolute wheel file path. Its filename must match the returned SDK308 distribution filename; existing output is replaced.309310 Returns:311 JsonObject: path, name and version of the pure-Python SDK wheel. No project,312 environment, credentials or experiment is created. This writes synchronously.313314 Raises:315 ContractError: Platform closed or output filename/path is invalid.316 OSError: SDK source, bundled wheel or destination is unavailable.317318 Example:319 result = app.export_agent_sdk('/tmp/sim_platform_agent_sdk-0.1.0-py3-none-any.whl')320 # Install result['path'] with pip in your development environment.321 """322 self._resources.check_open()323 from sim_platform.sdk.distribution import identity324325 return dict(identity(), path=str(self._agent_sdk.export(output)))326327 def python_runtimes(self) -> List[JsonObject]:328 """List successfully prepared native CPython runtimes without starting an Agent.329330 Returns:331 List[JsonObject]: Runtime references, exact versions, executable/base paths,332 implementation, CPU/OS and origin. In-progress candidates are excluded.333334 Raises:335 ContractError: Platform is closed.336337 Example:338 for runtime in app.python_runtimes():339 print(runtime['version'], runtime['origin'])340 """341 self._resources.check_open()342 return self._python_runtimes.available()343344 def prepare_python_runtime(345 self,346 python: str = '3.12',347 *,348 allow_download: bool = False,349 archive: Optional[PathInput] = None,350 ) -> RuntimePreparation:351 """Prepare or reuse an Agent interpreter independently of a project or App Python.352353 Args:354 python: CPython minor/patch or version range. The Agent default is 3.12.355 allow_download: Permit uv to obtain a missing native standalone runtime.356 archive: Optional trusted offline standalone .tar.gz archive; imports it privately.357358 Returns:359 RuntimePreparation: Owned cancellable job. A ready snapshot includes runtime360 with its exact version/executable and reused. Runtime readiness is not Agent readiness.361362 Raises:363 ContractError: Platform closed or invalid download option. Request, download and364 archive errors are returned as named failures in the job snapshot.365366 Example:367 job = app.prepare_python_runtime('3.12', allow_download=True)368 status = job.wait(60)369 job.close()370 """371 self._resources.check_open()372 if type(allow_download) is not bool:373 raise ContractError('allow_download must be boolean')374 if allow_download:375 from sim_platform.network import require_network376377 require_network('downloading a Python runtime')378 from sim_platform.agents.runtimes.manager import RuntimePreparation379380 job = RuntimePreparation(381 self._python_runtimes, python, allow_download=allow_download, archive=archive382 )383 job.on_close(lambda: self._resources.remove(job))384 return self._resources.add(job, shutdown_first=True)385386 def prepare_agent_environment(387 self,388 profile_id: str,389 agent_id: str,390 revision: Optional[int] = None,391 *,392 wheelhouse: Optional[PathInput] = None,393 allow_download: bool = False,394 allow_python_download: bool = False,395 python_archive: Optional[PathInput] = None,396 ) -> EnvironmentPreparation:397 """Start a cancellable background job preparing reusable wheel-only dependencies.398399 No user module, setup script or source build is run. The managed interpreter400 is selected separately from the App according to the saved project request. The returned job exposes401 snapshot(), wait(), cancel() and close(); Platform also owns and closes it.402403 Args:404 profile_id: Owner profile.405 agent_id: Saved imported Agent ID.406 revision: Specific revision, or None for latest; bound before the job starts.407 wheelhouse: Optional local directory of prebuilt dependency wheels for offline use.408 allow_download: Explicitly permit public PyPI wheel downloads when no wheelhouse409 is supplied. False by default. Source distributions/build hooks are rejected.410411 allow_python_download: Permit downloading a missing native standalone CPython runtime.412 Independent of the dependency download choice; False by default.413 python_archive: Optional explicitly trusted offline standalone .tar.gz distribution.414 It is imported privately and probed before project inspection or dependency install.415416 Returns:417 EnvironmentPreparation: A job in preparing state, later ready, failed or cancelled.418 snapshot includes phase, environment metadata, reused and a named error.419 A ready environment contains the matching SDK and dependencies. It does not420 start an Agent; open an experiment to load the saved source.421422 Raises:423 ContractError: Invalid owner/project/options or closed Platform. Installation and424 Python compatibility failures appear in the job's snapshot instead.425426 Example:427 job = app.prepare_agent_environment(profile_id, saved['agent_id'])428 status = job.wait(30)429 job.close()430 """431 self._resources.check_open()432 if allow_download or allow_python_download:433 from sim_platform.network import require_network434435 require_network('downloading Agent dependencies or Python')436 job = self._agent_environments.prepare(437 profile_id,438 agent_id,439 revision,440 wheelhouse=wheelhouse,441 allow_download=allow_download,442 allow_python_download=allow_python_download,443 python_archive=python_archive,444 )445 job.on_close(lambda: self._resources.remove(job))446 return self._resources.add(job, shutdown_first=True)447448 def prepare_model_environment(449 self,450 source: PathInput,451 *,452 wheelhouse: Optional[PathInput] = None,453 allow_download: bool = False,454 allow_python_download: bool = False,455 python_archive: Optional[PathInput] = None,456 ) -> EnvironmentPreparation:457 """Start preparing the Python environment a model file needs, such as torch.458459 Use this before a model-method experiment whose model imports packages. It uses460 the same wheel-only preparation as Agent projects. source is the model's folder:461 its requirements.txt lists the packages and an optional model.json such as462 {"python": "3.12"} selects the interpreter version. No model code runs. When the463 job is ready, pass model_environment(source) as the experiment's model_python.464 A model that needs only the standard library can skip this step.465466 Args:467 source: The model project folder, or a single .py file (no packages).468 wheelhouse: Optional local directory of prebuilt dependency wheels for offline use.469 allow_download: Permit public PyPI wheel downloads when no wheelhouse is given.470 allow_python_download: Permit downloading a missing standalone CPython runtime.471 python_archive: Optional trusted offline standalone .tar.gz distribution.472473 Returns:474 EnvironmentPreparation: A background job with snapshot(), wait(), cancel() and475 close(). Platform also owns and closes it. A ready environment is reused by476 later calls with the same requirements and Python request.477478 Raises:479 ContractError: Invalid folder, requirements, model.json or options.480 OSError: The source cannot be read.481482 Example:483 job = app.prepare_model_environment('/models/lstm', wheelhouse='/wheels')484 job.wait(600)485 python = app.model_environment('/models/lstm')486 """487 self._resources.check_open()488 if allow_download or allow_python_download:489 from sim_platform.network import require_network490491 require_network('downloading model dependencies or Python')492 job = self._agent_environments.prepare_model(493 source,494 wheelhouse=wheelhouse,495 allow_download=allow_download,496 allow_python_download=allow_python_download,497 python_archive=python_archive,498 )499 job.on_close(lambda: self._resources.remove(job))500 return self._resources.add(job, shutdown_first=True)501502 def model_environment(self, source: PathInput) -> Optional[str]:503 """Find the interpreter of a model project's prepared environment.504505 Use this after prepare_model_environment() has finished, and pass the result as506 the model_python setting of a model-method experiment. It reads metadata only.507508 Args:509 source: The same model folder or file given to prepare_model_environment().510511 Returns:512 Optional[str]: Absolute path of the environment's Python, or None when no513 environment matching the folder's requirements is ready.514515 Raises:516 ContractError: Invalid folder, requirements or model.json.517 OSError: The source cannot be read.518519 Example:520 python = app.model_environment('/models/lstm')521 """522 self._resources.check_open()523 return self._agent_environments.model_python(source)524525 def agent_environment(526 self, profile_id: str, agent_id: str, revision: Optional[int] = None527 ) -> Optional[JsonObject]:528 """Find an already prepared dependency environment compatible with this saved Agent.529530 Args:531 profile_id: Owner profile.532 agent_id: Saved imported Agent ID.533 revision: Specific revision, or None for latest.534535 Returns:536 Optional[JsonObject]: Ready environment_ref, exact specification and installed537 wheel package inventory, or None. This reads metadata without executing Python.538539 Raises:540 ContractError: Invalid owner or project.541 OSError: Project files cannot be read.542543 Example:544 ready = app.agent_environment(profile_id, saved['agent_id'])545 """546 self._resources.check_open()547 return self._agent_environments.ready(profile_id, agent_id, revision)548549 def create_agent(self, profile_id: str, definition: JsonObject) -> AgentRevisionDetails:550 """Save a new agent definition so it can be selected for experiments.551552 The definition describes the agent's configuration, not a running process. It must553 pass the agent configuration rules and contain revision "1" as a string. Its agent_id554 must be unused. The returned record identifies the saved first revision.555556 Saving does not execute uploaded code, create an environment, load a key or call a557 model. Use the saved agent ID and revision when preparing an experiment.558559 Args:560 profile_id: Profile ID returned by create_profile(); selects whose data to access.561 definition: Complete finite-JSON Agent manifest accepted by validate_definition().562563 Returns:564 AgentRevisionDetails: agent_id, integer revision=1, profile_id and validated565 definition.566567 Raises:568 ContractError: If an identity, configuration or lifecycle precondition is invalid.569570 Example:571 saved = app.create_agent(profile_id, definition)572 assert saved['revision'] == 1573 """574 return self._operations.create_agent(profile_id, definition)575576 def update_agent(577 self, profile_id: str, agent_id: str, expected_revision: int, definition: JsonObject578 ) -> AgentRevisionDetails:579 """Save an edited agent definition as a new revision, keeping the old one.580581 Pass the revision you edited as expected_revision. The platform checks that nobody582 has saved another edit since then. The new definition must keep the same agent_id583 and use the next revision number as a decimal string.584585 If the edit is out of date, nothing is written and AgentConfigurationError reports586 REVISION_CONFLICT. Reload the latest definition before deciding how to combine edits.587588 Args:589 profile_id: Profile ID returned by create_profile(); selects whose data to access.590 agent_id: Registered Agent definition ID, not a maker or run ID.591 expected_revision: Latest saved integer revision the caller expects to edit.592 definition: Complete finite-JSON Agent manifest accepted by validate_definition().593594 Returns:595 AgentRevisionDetails: The newly saved revision; earlier revisions remain.596597 Raises:598 ContractError: If an identity, configuration or lifecycle precondition is invalid.599600 Example:601 updated = app.update_agent(profile_id, agent_id, current_revision, next_definition)602 assert updated['revision'] == current_revision + 1603 """604 return self._operations.update_agent(profile_id, agent_id, expected_revision, definition)605606 def agent(607 self, profile_id: str, agent_id: str, revision: Optional[int] = None608 ) -> AgentRevisionDetails:609 """Read the configuration of one saved agent revision.610611 Use this to display or edit an agent definition. Omit revision to get the latest612 saved revision, or supply a number to inspect an older one. The agent must belong613 to profile_id. This returns saved data; it does not start an agent or load its model.614615 Args:616 profile_id: Profile ID returned by create_profile(); selects whose data to access.617 agent_id: Registered Agent definition ID, not a maker or run ID.618 revision: Saved integer revision, or None to read the latest revision.619620 Returns:621 AgentRevisionDetails: A dictionary with agent_id, revision, profile_id and622 definition. Changing this result does not update the saved agent.623624 Raises:625 ContractError: If an identity, configuration or lifecycle precondition is invalid.626627 Example:628 saved = app.agent(profile_id, agent_id)629 manifest = saved['definition']630 """631 return self._operations.agent(profile_id, agent_id, revision)632633 def agents(634 self, profile_id: str, *, limit: int = 100, after_id: Optional[str] = None635 ) -> List[AgentRevisionDetails]:636 """List the latest saved definitions of a profile's agents.637638 Use this for the agent selection page. It returns one revision per agent, rather639 than every revision ever saved. Request 1 to 100 entries with limit. To read the next640 page, pass the last agent_id as after_id; entries begin after that ID. An empty list641 means there are no more entries. Listing agents does not run them.642643 Args:644 profile_id: Profile ID returned by create_profile(); selects whose data to access.645 limit: Page size from 1 to 100.646 after_id: Exclusive opaque-ID pagination cursor, not a row offset.647648 Returns:649 list[AgentRevisionDetails]: At most limit entries ordered by agent_id.650651 Raises:652 ContractError: If an identity, configuration or lifecycle precondition is invalid.653654 Example:655 page = app.agents(profile_id, limit=20)656 if page:657 following = app.agents(profile_id, limit=20, after_id=page[-1]['agent_id'])658 """659 return self._operations.agents(profile_id, limit, after_id)660661 def prepare_agent_experiment(662 self,663 profile_id: str,664 account_id: str,665 agent_id: str,666 revision: int,667 settings: JsonObject,668 execution_config: Optional[ExecutionConfig] = None,669 ) -> AgentExperimentDetails:670 """Save the choices for an agent experiment without starting its runtime.671672 Use this when an experiment draft must be saved before its market and processes are673 prepared. It saves the selected agent revision, settings, trading rules and starting674 account state together. The account must have no active run or unfinished orders.675 Credential and other references stay as references; they are not loaded here.676677 The returned dictionary is a saved draft. Its state='prepared' does not mean it can678 Play: there is still no run, market or child process. Use open_agent_run() to connect679 a manually prepared market later. For normal complete setup use open_experiment().680681 Args:682 profile_id: Profile ID returned by create_profile(); selects whose data to access.683 account_id: Account ID returned by create_account(); it must belong to this profile.684 agent_id: Registered Agent definition ID, not a maker or run ID.685 revision: Positive saved Agent revision number.686 settings: Caller-owned experiment settings; policy methods allow defaults, Agent687 requires a complete settings object.688 execution_config: Rules for order validation and fills. None uses the default689 ExecutionConfig.690691 Returns:692 AgentExperimentDetails: state="prepared", readiness="requires_runtime_binding",693 config, starting snapshots and references to resources still needed for execution.694695 Raises:696 ContractError: If an identity, configuration or lifecycle precondition is invalid.697698 Example:699 draft = app.prepare_agent_experiment(profile_id, account_id, agent_id, revision, agent_settings)700 assert draft['state'] == 'prepared'701 draft_id = draft['id']702 """703 return self._operations.prepare_agent_experiment(704 profile_id, account_id, agent_id, revision, settings, execution_config705 )706707 def agent_experiment(self, profile_id: str, experiment_id: str) -> AgentExperimentDetails:708 """Read the saved choices and starting account state for an agent experiment.709710 This is the draft created during preparation. It stays unchanged even when a run is711 later created from it, so it does not tell you whether that run is playing or paused.712 Use run() for the saved run record and the controller for current execution state.713714 Args:715 profile_id: Profile ID returned by create_profile(); selects whose data to access.716 experiment_id: Saved Agent experiment draft ID owned by the profile.717718 Returns:719 AgentExperimentDetails: The saved draft dictionary. state="prepared" and720 readiness="requires_runtime_binding" mean its choices are saved but721 execution resources still need to be connected.722723 Raises:724 ContractError: If an identity, configuration or lifecycle precondition is invalid.725726 Example:727 draft = app.agent_experiment(profile_id, experiment_id)728 references = draft['bindings_required']729 """730 return self._operations.agent_experiment(profile_id, experiment_id)731732 def agent_experiments(733 self, profile_id: str, *, limit: int = 100, after_id: Optional[str] = None734 ) -> List[AgentExperimentDetails]:735 """List a profile's saved agent experiment drafts.736737 Use this to browse previously saved experiment choices. These entries are drafts,738 not live experiment controls. Request 1 to 100 entries with limit and use the last739 experiment ID as after_id for the next page. Use runs() to list actual run records.740741 Args:742 profile_id: Profile ID returned by create_profile(); selects whose data to access.743 limit: Page size from 1 to 100.744 after_id: Exclusive opaque-ID pagination cursor, not a row offset.745746 Returns:747 list[AgentExperimentDetails]: Saved draft dictionaries ordered by experiment ID.748 They do not update as their runs execute.749750 Raises:751 ContractError: If an identity, configuration or lifecycle precondition is invalid.752753 Example:754 drafts = app.agent_experiments(profile_id, limit=20)755 """756 return self._operations.agent_experiments(profile_id, limit, after_id)757758 def agent_log_archive(self, profile_id: str, run_id: str) -> Optional[JsonObject]:759 """Read the agent activity log already archived in a run's database record.760761 Use this to inspect a finished agent run. It does not read the local JSON file that762 may still be growing during execution. Reading the archive does not replay tools,763 call a model or change the run. If no archive has been saved, the result is None.764765 Args:766 profile_id: Profile ID returned by create_profile(); selects whose data to access.767 run_id: Existing run ID owned by the selected profile.768769 Returns:770 Optional[JsonObject]: header/records/end archive, or None if none was saved.771772 Raises:773 ContractError: If an identity, configuration or lifecycle precondition is invalid.774775 Example:776 archive = app.agent_log_archive(profile_id, run_id)777 if archive is not None:778 records = archive['records']779 """780 return self._operations.agent_log_archive(profile_id, run_id)