process.py
1"""Tools child entrypoint: format captured values without mutable financial access."""23from __future__ import annotations4import logging56from typing import TYPE_CHECKING, Any, Callable, Dict78from sim_platform.domain.json_values import encode9from sim_platform.agents.tools.reads.capture import CapturedRead10from sim_platform.agents.tools.trading.financial import format_financial11from sim_platform.agents.tools.protocol.responses import response_size, error_response12from sim_platform.agents.tools.protocol.contracts import ToolError13from sim_platform.agents.tools.protocol.transport import decode_job, MAX_JOB_BYTES1415_log = logging.getLogger(__name__)1617if TYPE_CHECKING: # Annotation only.18 from multiprocessing.connection import Connection19 from multiprocessing.synchronize import Event2021 from sim_platform.agents.tools.reads.formatter import ReadFormatter2223# How long one wait for a job lasts before the stop flag is checked again.24POLL_SECONDS = 0.0525# Longest fault text returned for an unexpected formatter error.26FAULT_TEXT_LIMIT = 256272829def run_tools(30 incoming: Connection,31 outgoing: Connection,32 ready: Event,33 stop: Any,34 binding: Dict[str, Any],35 formatter_factory: Callable[[Dict[str, Any]], ReadFormatter],36) -> None:37 """Spawn entrypoint: trusted factory only; no user manifest/import resolution.3839 ``stop`` is a shared ctypes byte; a nonzero value ends the loop.40 """41 try:42 formatter = formatter_factory(binding)43 ready.set()44 while not stop.value:45 if not incoming.poll(POLL_SECONDS):46 continue47 identity, captured = decode_job(incoming.recv_bytes(MAX_JOB_BYTES))48 try:49 result = (50 formatter.execute(captured)51 if isinstance(captured, CapturedRead)52 else format_financial(captured, binding['source_manifest_ref'])53 )54 response_size(result, binding['limits']['tool_response_bytes'])55 reply = dict(identity=identity, result=result, fault=None)56 except ToolError as error:57 reply = dict(58 identity=identity,59 result=error_response(60 captured.request, captured.receipt_index, dict(captured.position), error61 ),62 fault=None,63 )64 except Exception as error:65 _log.warning('Handled failure in run_tools', exc_info=True)66 reply = dict(67 identity=identity,68 result=None,69 fault=type(error).__name__ + ': ' + str(error)[:FAULT_TEXT_LIMIT],70 )71 outgoing.send_bytes(encode(reply).encode())72 finally:73 incoming.close()74 outgoing.close()