File size: 13,965 Bytes
d1a28b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5fcb2d
d1a28b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5fcb2d
d1a28b0
 
e5fcb2d
 
d1a28b0
e5fcb2d
d1a28b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""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]]]


@dataclass(frozen=True)
class QuantSupportRuntimeResult:
    record: QuantRunRecord
    output: VizAgentOutput | PortfolioMonitorOutput | None


@dataclass(frozen=True)
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