PolyHedra / src /polyhedra /core /template_builder.py
yf176
fix: bound downstream options prompts
7ba97b7
Raw History Blame Contribute Delete
13.8 kB
"""TemplateBuilder β€” input template generation and command registry.
Extracted from CoordinatorService as part of STRUCT-1 (V4.4).
STRUCT-4 CommandEntry / COMMAND_REGISTRY also live here (FR-S4.2).
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from string import Formatter
from typing import Any, Callable, Generic, TypeVar
from pydantic import BaseModel
from polyhedra.core.quant_contracts import AgentName
InputModel = TypeVar("InputModel", bound=BaseModel)
OutputModel = TypeVar("OutputModel", bound=BaseModel)
@dataclass(frozen=True)
class AgentIOTemplate(Generic[InputModel, OutputModel]):
"""Bind one agent's schemas to its prompt and human-readable renderer.
The caller supplies an ACL-filtered typed input. This binding neither reads
files nor grants permissions. Concrete bindings are added during migration.
"""
agent: AgentName
input_schema: type[InputModel]
output_schema: type[OutputModel]
prompt_template: str
markdown_renderer: Callable[[OutputModel], str]
prompt_projector: Callable[[InputModel], BaseModel | dict[str, Any]] | None = None
def __post_init__(self) -> None:
from typing import get_args
if self.agent not in get_args(AgentName):
raise ValueError("unknown quant agent")
fields = []
for _, field, spec, conversion in Formatter().parse(self.prompt_template):
if field is not None:
if field != "input_json" or spec or conversion:
raise ValueError("prompt accepts only the input_json placeholder")
fields.append(field)
if fields != ["input_json"]:
raise ValueError("prompt requires exactly one input_json placeholder")
def build_prompt(self, inputs: InputModel) -> str:
if type(inputs) is not self.input_schema:
raise TypeError("input does not match this agent's concrete schema")
snapshot = self.input_schema.model_validate_json(inputs.model_dump_json(), strict=True)
prompt_input = self.prompt_projector(snapshot) if self.prompt_projector else snapshot
if isinstance(prompt_input, BaseModel):
input_json = prompt_input.model_dump_json(indent=2)
else:
input_json = json.dumps(prompt_input, indent=2, ensure_ascii=True, allow_nan=False)
return self.prompt_template.format(input_json=input_json)
def render_markdown(self, output: OutputModel) -> str:
if type(output) is not self.output_schema:
raise TypeError("output does not match this agent's concrete schema")
validated = self.output_schema.model_validate_json(output.model_dump_json(), strict=True)
return self.markdown_renderer(validated)
# --------------------------------------------------------------------------- #
# STRUCT-4 β€” Command registry (FR-S4.2 / FR-S4.3)
# --------------------------------------------------------------------------- #
@dataclass
class CommandEntry:
"""Single entry in the Polyhedra command registry."""
group: str
slash: str
mention: str
cli: str
description: str
COMMAND_REGISTRY: list[CommandEntry] = [
# Session
CommandEntry("Session", '/poly init "<goal>"', '@coordinator init "<goal>"', "poly init", "Start a new session"),
CommandEntry("Session", '/poly init "<goal>" --force', "β€”", "β€”", "Force replace active session"),
CommandEntry("Session", '/poly goal "<text>"', '@coordinator goal "<text>"', 'poly goal "<text>"', "Update session goal"),
CommandEntry("Session", "/poly state", "@coordinator state", "poly state", "Print current ResearchState"),
CommandEntry("Session", "/poly resume", "@coordinator resume", "poly resume", "Resume after a checkpoint"),
CommandEntry("Session", "/poly stop", "@coordinator stop", "β€”", "End the current chain"),
CommandEntry("Session", "/poly export", "@coordinator export", "poly export", "Export artifacts to zip"),
# Quant
CommandEntry("Quant", "/poly quant", "@PolyTest quant", "β€”", "Run the governed quant workflow"),
CommandEntry("Quant", "/poly quant <ticker>", "@PolyTest quant <ticker>", "β€”", "Run the governed workflow for a ticker"),
CommandEntry("Quant", "/poly yolo <ticker>", "@PolyTest yolo <ticker>", "β€”", "Run baseline or session-delta YOLO"),
CommandEntry("Quant", "/poly chart <type> [ticker]", "@PolyTest chart <type> [ticker]", "β€”", "Render a typed chart from a completed run"),
CommandEntry("Quant", "/poly watchlist", "@coordinator watchlist", "β€”", "Show current watchlist"),
CommandEntry("Quant", "/poly watchlist add <tickers>", "@coordinator watchlist add <tickers>", "β€”", "Add tickers to watchlist"),
CommandEntry("Quant", "/poly watchlist remove <tickers>", "@coordinator watchlist remove <tickers>", "β€”", "Remove tickers from watchlist"),
# Portfolio
CommandEntry("Portfolio", "/poly portfolio", "@coordinator portfolio", "β€”", "Show paper portfolio and P&L"),
CommandEntry("Portfolio", "/poly trade approve <id>", "@coordinator trade approve <id>", "β€”", "Approve a trade proposal"),
CommandEntry("Portfolio", "/poly trade reject <id>", "@coordinator trade reject <id>", "β€”", "Reject a trade proposal"),
CommandEntry("Portfolio", "/poly trade revise <id>", "@coordinator trade revise <id>", "β€”", "Send proposal back for revision"),
CommandEntry("Portfolio", "/poly trade close <id>", "@coordinator trade close <id>", "β€”", "Close a paper position"),
# Monitor
CommandEntry("Monitor", "/poly monitor pause", "@coordinator monitor pause", "β€”", "Pause scheduled monitoring"),
CommandEntry("Monitor", "/poly monitor resume", "@coordinator monitor resume", "β€”", "Resume scheduled monitoring"),
CommandEntry("Monitor", "/poly monitor interval <min>", "@coordinator monitor interval <min>", "β€”", "Change monitor interval"),
# System
CommandEntry("System", "/poly trace", "@coordinator trace", "poly trace", "Show last 10 trace entries"),
CommandEntry("System", "/poly tokens", "@coordinator tokens", "poly tokens", "Show token usage and cost"),
CommandEntry("System", "/poly cache clear", "@coordinator cache clear", "poly cache stats", "Flush session cache"),
CommandEntry("System", "/poly cache status", "@coordinator cache status", "β€”", "Show cache hit/miss stats"),
CommandEntry("System", "/poly role <name> human|agent", "@coordinator role <name> human|agent", "poly role take|release", "Take over or reinstate a role"),
CommandEntry("System", "/poly help", "@coordinator help", "poly help", "Show this menu"),
]
def render_help_slack() -> str:
"""Render ``COMMAND_REGISTRY`` as a Slack-formatted command menu (FR-S4.4)."""
from itertools import groupby
lines = ["πŸ“‹ *Polyhedra β€” Commands*\n"]
groups = groupby(COMMAND_REGISTRY, key=lambda e: e.group)
for group_name, entries in groups:
lines.append(f"*{group_name.upper()}*")
for entry in entries:
lines.append(f" `{entry.slash:<45}` `{entry.mention:<50}` _{entry.description}_")
lines.append("")
return "\n".join(lines)
def render_help_cli() -> str:
"""Render ``COMMAND_REGISTRY`` as a plain-text table for CLI output (FR-S4.5).
Callers that import ``rich`` can pass the string through ``rich.Markdown``
for coloured output.
"""
from itertools import groupby
lines = ["Polyhedra β€” Commands\n"]
groups = groupby(COMMAND_REGISTRY, key=lambda e: e.group)
for group_name, entries in groups:
lines.append(group_name.upper())
for entry in entries:
lines.append(
f" {entry.slash:<45} {entry.mention:<50} {entry.cli:<25} {entry.description}"
)
lines.append("")
return "\n".join(lines)
# --------------------------------------------------------------------------- #
# STRUCT-1 β€” TemplateBuilder (FR-S1.2)
# --------------------------------------------------------------------------- #
_STOP = "/poly stop"
_QUANT_REPORT = "/poly quant report"
# Import at class level to avoid circular imports at module load
def _alt_agent_map() -> dict[str, str]:
from polyhedra.core.agent_router import ALT_AGENT_MAP
return ALT_AGENT_MAP
class TemplateBuilder:
"""Generates ranked, pre-filled input templates for human touchpoints.
Rule-based β€” no LLM call (FR-1.4). Stateless.
"""
def build(
self,
touchpoint: str,
*,
next_role: str | None = None,
proposal_id: str | None = None,
session_id: str | None = None,
) -> str:
"""Return a formatted Slack/CLI string of suggested next messages."""
options = self._options(
touchpoint,
next_role=next_role,
proposal_id=proposal_id,
session_id=session_id,
)
if not options:
return ""
lines = ["\nπŸ’¬ *Suggested next messages:*\n"]
for i, (msg, desc) in enumerate(options, 1):
lines.append(f"{i}. > `{msg}`")
lines.append(f" _{desc}_")
lines.append("")
return "\n".join(lines)
def _options(
self,
touchpoint: str,
*,
next_role: str | None,
proposal_id: str | None,
session_id: str | None,
) -> list[tuple[str, str]]:
builders = {
"checkpoint": self._opts_checkpoint,
"trade_proposals": self._opts_trade_proposals,
"agent_blocked": self._opts_agent_blocked,
"uncertainty": self._opts_uncertainty,
"resume": self._opts_resume,
}
builder = builders.get(touchpoint)
if builder is None:
return [(_STOP, "Stop the pipeline.")]
return builder(next_role=next_role, proposal_id=proposal_id, session_id=session_id)
def _opts_checkpoint(
self, *, next_role: str | None, **_: Any
) -> list[tuple[str, str]]:
alt = _alt_agent_map().get(next_role or "") if next_role else None
opts: list[tuple[str, str]] = []
if next_role:
opts.append((f"@PolyTest @{next_role} continue", f"Recommended β€” continue to @{next_role}."))
if alt and alt != next_role and alt != "human":
opts.append((f"@PolyTest @{alt} continue", f"Skip to @{alt} if you've already reviewed."))
opts.append((_STOP, "Stop and review artifacts before continuing."))
return opts
def _opts_trade_proposals(
self, *, proposal_id: str | None, **_: Any
) -> list[tuple[str, str]]:
pid = proposal_id or "<proposal_id>"
return [
(f"/poly trade approve {pid}", "Approve and add to the paper portfolio."),
(f"/poly trade reject {pid} <reason>", "Reject the proposal with an optional reason."),
(f"/poly trade revise {pid}", "Send back to QuantStrategist for revision."),
(_STOP, "Stop and review before deciding."),
]
def _opts_agent_blocked(
self, *, next_role: str | None, **_: Any
) -> list[tuple[str, str]]:
opts: list[tuple[str, str]] = []
if next_role:
opts.append((
f"@PolyTest @{next_role} continue",
f"Dispatch @{next_role} to produce missing data.",
))
opts += [
(_QUANT_REPORT, "Check which artifacts are available."),
(_STOP, "Stop and investigate manually."),
]
return opts
def _opts_uncertainty(
self, *, next_role: str | None, **_: Any
) -> list[tuple[str, str]]:
opts: list[tuple[str, str]] = []
if next_role:
opts.append((
f"@PolyTest @{next_role} continue",
"Proceed β€” agent flagged uncertainty, not a hard block.",
))
opts += [
(_QUANT_REPORT, "Review current state before proceeding."),
(_STOP, "Stop and reassess."),
]
return opts
def _opts_resume(
self, *, session_id: str | None, **_: Any
) -> list[tuple[str, str]]:
sid = session_id or "<session_id>"
return [
(f"/poly resume {sid}", "Resume the session from where it left off."),
(_QUANT_REPORT, "See a summary of the last quant run before resuming."),
(_STOP, "Do not resume β€” end the pipeline here."),
]