Download src/polyhedra/services/quant_support_runtime.py from polyHedra/PolyHedra: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/services/quant_support_runtime.py
- Command line
-
hf download hf://spaces/polyHedra/PolyHedra/src/polyhedra/services/quant_support_runtime.py
-
curl -L -o quant_support_runtime.py https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/services/quant_support_runtime.py
14 kB
| """Governed V8 execution for visualization and portfolio-monitor contexts.""" | |
| from __future__ import annotations | |
| import inspect | |
| from collections.abc import Awaitable, Callable, Mapping | |
| from dataclasses import dataclass | |
| from datetime import datetime, timezone | |
| from typing import Any | |
| from pydantic import BaseModel | |
| from polyhedra.agents.base import AgentResponse | |
| from polyhedra.agents.quant.io_registry import quant_artifact_schema, quant_io_binding | |
| from polyhedra.agents.quant.product_contracts import ( | |
| ChartType, | |
| MarketHoursState, | |
| MonitorThresholds, | |
| PaperPosition, | |
| PortfolioMonitorOutput, | |
| QuoteProviderConfiguration, | |
| VizAgentOutput, | |
| ) | |
| from polyhedra.core.active_routing import ActiveAgentPlan, build_active_routing_plan | |
| from polyhedra.core.artifacts import JsonArtifactRef, RunMode | |
| from polyhedra.core.dependency_executor import ( | |
| AgentCompletion, | |
| AgentExecutionState, | |
| DependencyExecutor, | |
| ) | |
| from polyhedra.core.quant_contracts import AgentName, ExecutionContext, load_quant_contracts | |
| from polyhedra.core.research_state import ResearchStateManager | |
| from polyhedra.core.state_patcher import StatePatcher | |
| from polyhedra.core.trace_logger import TraceLogger | |
| from polyhedra.services.artifact_publisher import ArtifactPublisher | |
| from polyhedra.services.evidence_ledger import write_typed_evidence_ledger | |
| from polyhedra.services.error_sanitizer import sanitize_exception | |
| from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter | |
| from polyhedra.services.quant_run_record import ( | |
| QuantRunRecord, | |
| QuantSupportRunRecordStore, | |
| build_quant_run_record, | |
| ) | |
| ProgressFn = Callable[[AgentName, AgentExecutionState, str], Awaitable[None]] | |
| BeforeAgentFn = Callable[[AgentName, str], Awaitable[None]] | |
| QuoteFetcher = Callable[[list[str]], Awaitable[dict[str, float | None]]] | |
| class QuantSupportRuntimeResult: | |
| record: QuantRunRecord | |
| output: VizAgentOutput | PortfolioMonitorOutput | None | |
| class _Activation: | |
| inputs: BaseModel | |
| files: ScopedFileWriter | |
| class QuantSupportRuntime: | |
| """Run one support-context agent through the same routing and ACL authority.""" | |
| def __init__( | |
| self, | |
| *, | |
| session_dir, | |
| session_id: str, | |
| agents: Mapping[AgentName, Any], | |
| writer: FileWriter, | |
| trace: TraceLogger, | |
| progress: ProgressFn | None = None, | |
| before_agent: BeforeAgentFn | None = None, | |
| ) -> None: | |
| self._session_dir = session_dir | |
| self._session_id = session_id | |
| self._agents = dict(agents) | |
| self._writer = writer | |
| self._trace = trace | |
| self._progress = progress | |
| self._before_agent = before_agent | |
| self._publications = PublicationRegistry() | |
| self._publisher: ArtifactPublisher | None = None | |
| self._output: VizAgentOutput | PortfolioMonitorOutput | None = None | |
| self._research_state: dict[str, Any] = {} | |
| self._quote_fetcher: QuoteFetcher | None = None | |
| self._source_run_id: str | None = None | |
| self._inputs: BaseModel | None = None | |
| async def run_visualization( | |
| self, | |
| *, | |
| run_id: str, | |
| ticker_scope: list[str], | |
| source_run_id: str, | |
| source_artifacts: list[JsonArtifactRef], | |
| chart_type: ChartType, | |
| ticker: str | None, | |
| started_at: datetime | None = None, | |
| ) -> QuantSupportRuntimeResult: | |
| if not source_artifacts: | |
| raise ValueError("visualization requires at least one typed source artifact") | |
| if {ref.run_id for ref in source_artifacts} != {source_run_id}: | |
| raise ValueError("visualization source references contradict the frozen source run") | |
| for reference in source_artifacts: | |
| self._publications.publish(reference.path, reference) | |
| self._source_run_id = source_run_id | |
| as_of = started_at or datetime.now(tz=timezone.utc) | |
| self._inputs = quant_io_binding("VizAgent").input_schema.model_validate({ | |
| "run_id": run_id, | |
| "session_id": self._session_id, | |
| "run_mode": RunMode.DELTA, | |
| "as_of": as_of, | |
| "ticker_scope": ticker_scope, | |
| "dependencies": {}, | |
| "optional_context": { | |
| "requested_chart_type": chart_type, | |
| "requested_ticker": ticker, | |
| "source_artifacts": source_artifacts, | |
| }, | |
| "baseline_refs": source_artifacts, | |
| }) | |
| return await self._run( | |
| run_id=run_id, | |
| tickers=ticker_scope, | |
| context=ExecutionContext.VISUALIZATION, | |
| run_mode=RunMode.DELTA, | |
| baseline_run_id=source_run_id, | |
| started_at=as_of, | |
| ) | |
| async def run_portfolio_monitor( | |
| self, | |
| *, | |
| run_id: str, | |
| ticker_scope: list[str], | |
| positions: list[PaperPosition], | |
| thresholds: MonitorThresholds, | |
| paused: bool, | |
| market_hours: MarketHoursState, | |
| quote_provider: QuoteProviderConfiguration, | |
| quote_fetcher: QuoteFetcher | None = None, | |
| started_at: datetime | None = None, | |
| ) -> QuantSupportRuntimeResult: | |
| as_of = started_at or datetime.now(tz=timezone.utc) | |
| self._quote_fetcher = quote_fetcher | |
| self._inputs = quant_io_binding("PortfolioMonitor").input_schema.model_validate({ | |
| "run_id": run_id, | |
| "session_id": self._session_id, | |
| "run_mode": RunMode.BASELINE, | |
| "as_of": as_of, | |
| "ticker_scope": ticker_scope, | |
| "dependencies": {}, | |
| "optional_context": { | |
| "open_positions": positions, | |
| "thresholds": thresholds, | |
| "paused": paused, | |
| "market_hours": market_hours, | |
| "quote_provider": quote_provider, | |
| }, | |
| "baseline_refs": [], | |
| }) | |
| return await self._run( | |
| run_id=run_id, | |
| tickers=ticker_scope, | |
| context=ExecutionContext.PORTFOLIO_MONITOR, | |
| run_mode=RunMode.BASELINE, | |
| baseline_run_id=None, | |
| started_at=as_of, | |
| ) | |
| async def _run( | |
| self, | |
| *, | |
| run_id: str, | |
| tickers: list[str], | |
| context: ExecutionContext, | |
| run_mode: RunMode, | |
| baseline_run_id: str | None, | |
| started_at: datetime, | |
| ) -> QuantSupportRuntimeResult: | |
| plan = build_active_routing_plan( | |
| run_id=run_id, | |
| execution_context=context, | |
| tickers=tickers, | |
| ) | |
| if len(plan.active_agents) != 1: | |
| raise RuntimeError(f"{context.value} must activate exactly one support agent") | |
| item = plan.active_agents[0] | |
| if item.agent not in self._agents: | |
| raise RuntimeError(f"active support agent is not registered: {item.agent}") | |
| self._publisher = ArtifactPublisher( | |
| self._writer, session_id=self._session_id, run_id=run_id, | |
| ) | |
| self._research_state = ResearchStateManager(self._session_dir).load().to_dict() | |
| executor = DependencyExecutor( | |
| plan, | |
| session_id=self._session_id, | |
| runner=self._run_agent, | |
| input_capture=self._capture_input, | |
| ) | |
| execution = await executor.run() | |
| completed_at = datetime.now(tz=timezone.utc) | |
| input_path = f"quant/runs/{run_id}/inputs/{item.agent}.json" | |
| input_paths = {item.agent: input_path} if self._writer.exists(input_path) else {} | |
| additional = [ | |
| reference for reference in self._publications.references() | |
| if reference.run_id == run_id and reference.path != ( | |
| execution.for_agent(item.agent).artifact_ref.path | |
| if execution.for_agent(item.agent).artifact_ref is not None else "" | |
| ) | |
| ] | |
| record = build_quant_run_record( | |
| plan=plan, | |
| execution=execution, | |
| session_id=self._session_id, | |
| run_mode=run_mode, | |
| baseline_run_id=baseline_run_id, | |
| started_at=started_at, | |
| completed_at=completed_at, | |
| input_snapshot_paths=input_paths, | |
| permission_templates=_permission_templates(plan), | |
| permission_snapshots=_permission_snapshots( | |
| plan, source_run_id=self._source_run_id, baseline_run_id=baseline_run_id, | |
| ), | |
| additional_artifacts=additional, | |
| ) | |
| write_typed_evidence_ledger(self._session_dir, record) | |
| QuantSupportRunRecordStore( | |
| self._session_dir, session_id=self._session_id, | |
| ).save(record) | |
| quant = self._research_state.get("quant_state") or {} | |
| patch = {"token_log": quant.get("token_log", [])} | |
| if context == ExecutionContext.PORTFOLIO_MONITOR: | |
| patch["last_monitor_run"] = completed_at.isoformat() | |
| StatePatcher().apply(self._session_dir, patch) | |
| return QuantSupportRuntimeResult(record=record, output=self._output) | |
| def _capture_input(self, item: ActiveAgentPlan, _dependencies) -> _Activation: | |
| if self._inputs is None: | |
| raise RuntimeError("support input is not initialized") | |
| files = ScopedFileWriter( | |
| self._writer, | |
| agent=item.agent, | |
| run_id=self._inputs.run_id, | |
| ticker_scope=list(item.effective_ticker_scope), | |
| baseline_run_id=self._source_run_id, | |
| source_run_id=self._source_run_id, | |
| publications=self._publications, | |
| ) | |
| return _Activation(inputs=self._inputs, files=files) | |
| async def _run_agent(self, item: ActiveAgentPlan, activation: _Activation) -> AgentCompletion: | |
| if self._publisher is None: | |
| raise RuntimeError("support publisher is not initialized") | |
| agent = self._agents[item.agent] | |
| if self._before_agent is not None: | |
| prompt = quant_io_binding(item.agent).build_prompt(activation.inputs) | |
| await self._before_agent(item.agent, prompt) | |
| await self._notify(item.agent, AgentExecutionState.RUNNING, "") | |
| role = getattr(agent, "role", item.agent) | |
| trace_id = self._trace.start_run( | |
| role, | |
| prompt=activation.inputs.model_dump_json(), | |
| session_id=self._session_id, | |
| ) | |
| try: | |
| kwargs: dict[str, Any] = { | |
| "files": activation.files, | |
| "publisher": self._publisher, | |
| } | |
| signature = inspect.signature(agent.execute_typed) | |
| if "research_state" in signature.parameters: | |
| kwargs["research_state"] = self._research_state | |
| if item.agent == "PortfolioMonitor" and self._quote_fetcher is not None: | |
| kwargs["quote_fetcher"] = self._quote_fetcher | |
| completion = await agent.execute_typed(activation.inputs, **kwargs) | |
| raw = self._writer.read(completion.artifact_ref.path) | |
| if raw is None: | |
| raise FileNotFoundError(completion.artifact_ref.path) | |
| output = quant_artifact_schema(item.agent).model_validate_json(raw, strict=True) | |
| if isinstance(output, (VizAgentOutput, PortfolioMonitorOutput)): | |
| self._output = output | |
| response = AgentResponse( | |
| agent_role=role, | |
| content=output.model_dump_json(), | |
| artifact_path=completion.artifact_ref.path, | |
| output=output, | |
| ) | |
| self._trace.end_run(trace_id, response) | |
| await self._notify(item.agent, AgentExecutionState.COMPLETED, completion.result_status) | |
| return completion | |
| except BaseException as exc: | |
| safe_error = sanitize_exception(exc) | |
| self._trace.end_run(trace_id, AgentResponse( | |
| agent_role=role, | |
| content=safe_error, | |
| error=safe_error, | |
| )) | |
| await self._notify(item.agent, AgentExecutionState.FAILED, safe_error) | |
| raise | |
| async def _notify(self, agent: AgentName, state: AgentExecutionState, detail: Any) -> None: | |
| if self._progress is not None: | |
| await self._progress(agent, state, str(detail or "")) | |
| def _permission_templates(plan) -> dict[AgentName, dict[str, list[str]]]: | |
| contracts = load_quant_contracts() | |
| return { | |
| item.agent: contracts.for_agent(item.agent).permissions.model_dump(mode="json") | |
| for item in plan.active_agents | |
| } | |
| def _permission_snapshots( | |
| plan, | |
| *, | |
| source_run_id: str | None, | |
| baseline_run_id: str | None, | |
| ) -> dict[AgentName, dict[str, list[str]]]: | |
| contracts = load_quant_contracts() | |
| snapshots: dict[AgentName, dict[str, list[str]]] = {} | |
| for item in plan.active_agents: | |
| permissions = contracts.for_agent(item.agent).permissions.model_dump(mode="json") | |
| resolved: dict[str, list[str]] = {} | |
| for operation, templates in permissions.items(): | |
| if operation.startswith("baseline_"): | |
| selected_run = baseline_run_id | |
| elif operation in {"read", "list"} and source_run_id: | |
| selected_run = source_run_id | |
| else: | |
| selected_run = plan.run_id | |
| paths: list[str] = [] | |
| for template in templates: | |
| if selected_run is None: | |
| continue | |
| path = template.replace("{run_id}", selected_run).replace( | |
| "{baseline_run_id}", selected_run, | |
| ) | |
| if "{ticker}" in path: | |
| paths.extend( | |
| path.replace("{ticker}", ticker) | |
| for ticker in item.effective_ticker_scope | |
| ) | |
| else: | |
| paths.append(path) | |
| resolved[operation] = paths | |
| snapshots[item.agent] = resolved | |
| return snapshots | |