worker.py
1"""Agent child entrypoint: initialize once, wait for Play, then run the carrier."""23from __future__ import annotations4import logging56from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, cast78from sim_platform.domain.models import ContractError9from sim_platform.agents.hosting.client import AgentProcessClient10from .lifecycle import AgentStartupError11from sim_platform.agents.tools.protocol.errors import ToolError1213_log = logging.getLogger(__name__)1415if TYPE_CHECKING: # Annotation only.16 from multiprocessing.connection import Connection1718 from sim_platform.experiments.scheduling.client import RuntimeClient19 from sim_platform.experiments.scheduling.signals import ProcessSignal20 from .protocol import TransportLimits2122# Poll interval while waiting for the launch signal.23LAUNCH_POLL_SECONDS = 0.05242526def idle_program(client: AgentProcessClient, configuration: Dict[str, Any]) -> None:27 """Remain resident until stopped; no default decision loop is installed."""28 client.wait_stopped()293031def run_program(32 outgoing: Connection,33 incoming: Connection,34 ready: ProcessSignal,35 stop: ProcessSignal,36 running: ProcessSignal,37 limits: TransportLimits,38 program: Callable[[AgentProcessClient, Dict[str, Any]], None],39 configuration: Dict[str, Any],40 work_client: Optional[RuntimeClient] = None,41 model_setup: Optional[Connection] = None,42 startup: Optional[Connection] = None,43 family_ready: Optional[ProcessSignal] = None,44 launch: Optional[ProcessSignal] = None,45) -> None:46 """Agent child entry point: join the process family, prepare, then run after Play.4748 The optional arguments are always supplied by the host; they default to None only49 in the signature.50 """51 client = AgentProcessClient(outgoing, incoming, limits, stop, running)52 client.work_client = work_client53 client.model_setup = model_setup54 try:55 from .processes import enter_process_family5657 enter_process_family()58 # The host always supplies startup, family_ready and launch.59 cast('ProcessSignal', family_ready).set()60 while not cast('ProcessSignal', launch).wait(LAUNCH_POLL_SECONDS):61 if stop.is_set():62 return63 from sim_platform.agents.carrier.program import ConfiguredAgentProgram6465 prepared = None66 try:67 if isinstance(program, ConfiguredAgentProgram):68 prepared = program.prepare(client, configuration)69 except Exception as error:70 _log.warning('Handled failure in run_program', exc_info=True)71 code = 'AGENT_INITIALIZATION_FAILED'72 if isinstance(error, AgentStartupError):73 code = error.code74 elif isinstance(error, ToolError) and error.code == 'TOOL_UNAVAILABLE':75 code = 'AGENT_TOOL_UNAVAILABLE'76 cast('Connection', startup).send(code)77 ready.set()78 return79 cast('Connection', startup).send(None)80 cast('Connection', startup).close()81 ready.set()82 client.wait_running()83 if prepared is not None:84 prepared.run()85 else:86 program(client, configuration)87 except ContractError:88 if not client.stopping:89 # Uploaded code can raise ContractError with private content too.90 # Report the failed process without copying that content to stderr.91 raise SystemExit(1) from None92 except Exception:93 # User exceptions may contain prompts/keys. Report a nonzero exit, not their text.94 raise SystemExit(1) from None95 finally:96 cast('Connection', startup).close()97 outgoing.close()98 incoming.close()99 if model_setup is not None:100 model_setup.close()