client.py
1"""Keep work identities and IPC envelopes behind the agent-facing tool/model client."""23from __future__ import annotations45from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, cast67from sim_platform.agents.tools.protocol.contracts import validate_request8from sim_platform.domain.json_values import copy_json9from sim_platform.domain.models import ContractError10from .task import Task1112if TYPE_CHECKING: # Annotation only.13 from sim_platform.agents.hosting.client import AgentProcessClient14 from sim_platform.experiments.scheduling.client import RuntimeClient151617class AgentClient:18 """Use existing process capabilities without exposing request bookkeeping to tools.1920 One client belongs to one agent execution. next_task() binds each Runtime work21 identity before the Agent runs it. Tools send a name and arguments; this client22 supplies the run/work/request IDs, validates the request and sends it once.23 It never retries financial operations or reads platform storage directly.24 """2526 def __init__(27 self,28 transport: AgentProcessClient,29 configuration: Dict[str, Any],30 *,31 preparing: bool = False,32 ) -> None:33 self._transport = transport34 self._run_id = configuration['run_id']35 self._settings = copy_json(configuration['template'])36 self._preparing = preparing37 self._work: Optional[Dict[str, Any]] = None38 self._request_number = 03940 @property41 def limits(self) -> Dict[str, Any]:42 return copy_json(self._settings['limits'])4344 def allows(self, name: str) -> bool:45 return name == 'environment.describe' or name in self._settings['granted_tools']4647 def activate(self) -> None:48 """Open capabilities after process Play; initialization must be side-effect free."""49 self._preparing = False5051 def _require_active(self) -> None:52 if self._preparing:53 raise ContractError('AGENT_INITIALIZING: capabilities are unavailable before Play')5455 def prepare_model(self) -> None:56 self._require_active()57 self._transport.prepare_model()5859 def next_task(self, instruction: str) -> Task:60 """Wait for Runtime, then attach its notification to the task's objective.6162 Work IDs stay on this client. A notification explains why the task is being63 run now; it does not replace the objective or provide a current price quote.64 """65 self._require_active()66 work: Dict[str, Any] = copy_json(self._transport.next_work())67 self._work = work68 notification = {k: v for k, v in work.items() if k not in ('work_id', 'epoch')}69 return Task(instruction, notification)7071 def _require_work(self) -> Dict[str, Any]:72 self._require_active()73 if self._work is None:74 raise ContractError('receive a task before using agent tools or model')75 return self._work7677 def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:78 """Validate and send one tool call under the active task, without automatic retry."""79 work = self._require_work()80 self._request_number += 181 request = dict(82 run_id=self._run_id,83 work_id=work['work_id'],84 epoch=work['epoch'],85 request_id='template-' + str(self._request_number),86 tool=name,87 arguments=arguments,88 )89 binding = dict(90 self._settings, run_id=self._run_id, work_id=work['work_id'], epoch=work['epoch']91 )92 request = validate_request(request, binding)93 return self._transport.request_tool(request)9495 def request_model(96 self,97 payload: Dict[str, Any],98 *,99 validate_response: Callable[[Any], object],100 label: Optional[str] = None,101 ) -> Any:102 """Ask the model; ``label`` names the role whose usage this request counts toward."""103 if label is None:104 return self._transport.request_model(105 self._require_work(), payload, validate_response=validate_response106 )107 return self._transport.request_model(108 self._require_work(), payload, validate_response=validate_response, label=label109 )110111 def fail(self, code: str) -> None:112 # The Agent process always has a Runtime work client when it can fail work.113 cast('RuntimeClient', self._transport.work_client).fail(code)114 self._transport.wait_stopped()115116 @property117 def stopping(self) -> bool:118 return self._transport.stopping