router.py
1"""Owner routing over a persistent tools process; no local formatting worker."""23from __future__ import annotations45from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Union, cast67from sim_platform.domain.json_values import copy_json8from sim_platform.agents.tools.protocol.contracts import (9 validate_request,10 TRADE_TOOLS,11 CONTROL_TOOLS,12 ToolError,13)14from sim_platform.agents.tools.reads.capture import capture_read15from sim_platform.agents.tools.protocol.responses import error_response16from sim_platform.agents.tools.worker.host import ToolProcessHost17from sim_platform.agents.tools.server.result_history import ToolResultHistory1819if TYPE_CHECKING: # Annotation only.20 from sim_platform.agents.tools.reads.capture import CapturedRead21 from sim_platform.agents.tools.trading.commands import TradingTools22 from sim_platform.agents.tools.trading.financial import FinancialCapture2324# A tool's eventual result: a response, or a DeferredResult resolved on output.25ToolOutcome = Any262728# Captures what a market-route tool may see: (tool, cutoff time, arguments) to values.29MarketCapture = Callable[[str, int, Dict[str, Any]], Mapping[str, Any]]303132class AgentTools:33 """The App-side tool router for one Agent run, called on the financial owner.3435 Assembly creates it with the run's tool binding, owner capture and trading36 tools; it starts and owns the tools process, and close() stops it. ``controls``37 is the run's RuntimeBinding, set after construction.3839 Args:40 binding: Tool binding: run/work identity, symbol, grants, limits, references.41 capture: Captures detached owner values for a tool name.42 receipt_index: Returns the current command's receipt index.43 trading: Financial tool commands for the run.44 """4546 def __init__(47 self,48 binding: Dict[str, Any],49 capture: Any,50 receipt_index: Callable[[], str],51 trading: TradingTools,52 ) -> None:53 self.binding = copy_json(binding)54 self._capture, self._receipt_index = capture, receipt_index55 self._trading = trading56 self._worker = ToolProcessHost(binding)57 # The run's RuntimeBinding (application package, which agents may not import);58 # None until assembly binds it.59 self.controls: Any = None60 self._market_capture: Optional[MarketCapture] = None61 self._history = ToolResultHistory(62 binding['limits']['tool_request_bytes'], binding['limits']['tool_response_bytes']63 )6465 def validate(self, request: Any) -> Dict[str, Any]:66 """Ingress only: validate schema/grants before touching owner capabilities."""67 return validate_request(request, self.binding, check_work=False)6869 def has_retained_request(self, request: Dict[str, Any]) -> bool:70 """Owner replay checks exact content; existing IDs never cause new effects."""71 return self._history.contains(request['request_id'])7273 def delivered(self, request_id: str, result: Any) -> None:74 self._history.delivered(request_id, result)7576 def bind_market_capture(self, capture: MarketCapture) -> None:77 if self._market_capture is not None:78 raise ToolError('INVALID_ARGUMENT', 'market read capture already bound')79 self._market_capture = capture8081 def _capture_market(82 self, request: Dict[str, Any], position: Dict[str, str], receipt_index: str83 ) -> ToolOutcome:84 from sim_platform.agents.tools.reads.capture import CapturedRead85 from types import MappingProxyType8687 # market_read checks that the capture is bound before calling this.88 values = cast(MarketCapture, self._market_capture)(89 request['tool'], int(position['time_ns']), request['arguments']90 )91 captured = CapturedRead(92 request,93 MappingProxyType(dict(position)),94 values['market'],95 values['execution'],96 values['history'],97 MappingProxyType({}),98 receipt_index,99 )100 return self._worker.submit(captured)101102 def market_read(103 self, request: Dict[str, Any], position: Dict[str, str], receipt_index: str104 ) -> ToolOutcome:105 """Capture a granted immutable query; preserve normal tool error envelopes."""106107 def failed(error: ToolError) -> Dict[str, Any]:108 return error_response(request, receipt_index, position, error)109110 try:111 if self._market_capture is None:112 raise ToolError('TOOL_UNAVAILABLE', 'prepared market reads are not bound')113 if self.controls is not None:114 self.controls.validate_identity(request)115 return self._history.capture(116 request,117 lambda: self._capture_market(request, position, receipt_index),118 failed,119 release_on_failure=True,120 )121 except ToolError as error:122 return failed(error)123124 def dispatch(self, request: Dict[str, Any], position: Dict[str, str]) -> ToolOutcome:125 return self.capture_and_submit(request, position)126127 def _perform(self, request: Dict[str, Any], position: Dict[str, str]) -> ToolOutcome:128 """Owner routing only: controls, raw financial capture, or read capture."""129 if self.controls is not None:130 self.controls.validate_identity(request)131 if request['tool'] in CONTROL_TOOLS:132 return self.controls.execute(request, position, self._receipt_index())133 self._worker.require_available()134 captured: Union[CapturedRead, FinancialCapture]135 if request['tool'] in TRADE_TOOLS or self._trading.has_request(request['request_id']):136 captured = self._trading.execute(request, position)137 else:138 captured = capture_read(request, position, self._capture, self._receipt_index())139 return self._worker.submit(captured)140141 def _tool_error(142 self, request: Dict[str, Any], position: Dict[str, str], error: ToolError143 ) -> ToolOutcome:144 retained = (145 self._trading.has_request(request['request_id']) or request['tool'] == 'requests.get'146 )147 if error.code == 'TOOL_UNAVAILABLE' and retained:148 from sim_platform.agents.tools.trading.financial import financial_fallback149150 return financial_fallback(self._trading.execute(request, position), self.binding)151 return error_response(request, self._receipt_index(), position, error)152153 def capture_and_submit(self, request: Dict[str, Any], position: Dict[str, str]) -> ToolOutcome:154 """Replay or reserve → perform → retain; owner never waits for process IO."""155 return self._history.capture(156 request,157 lambda: self._perform(request, position),158 lambda error: self._tool_error(request, position, error),159 )160161 def snapshot(self) -> Dict[str, Any]:162 return self._worker.snapshot()163164 def play(self) -> Dict[str, Any]:165 return self._worker.play()166167 def pause(self) -> Dict[str, Any]:168 return self._worker.pause()169170 def cancel_pending(self) -> None:171 self._worker.cancel_pending()172173 def close(self) -> None:174 self._worker.close()