PolyHedra / src /polyhedra /cli /main.py
yf176
refactor: make quant runtime the product path
748cf22
Raw History Blame Contribute Delete
16.5 kB
"""Polyhedra quant command-line interface.
Commands
--------
poly init Start a new quant session
poly state Print the current Research State
poly resume Rejoin an existing session by ID
poly export Export all session artifacts as a zip
poly role Take over or release an agent role
poly mcp Start the MCP server (IDE integrations)
poly sessions List all saved sessions
Usage examples
--------------
poly init "SPY analysis"
poly state
poly resume abc12345
poly export --output ./my_exports
poly role trendanalyst human
poly mcp
"""
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
from typing import Annotated, Optional
import typer
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.table import Table
from polyhedra.agents.coordinator import CoordinatorService, CheckpointResult
from polyhedra.agents.coordinator import CoordinatorAgent
from polyhedra.agents.quant import (
BacktesterAgent, BTCAnalyst, DataFetcherAgent, EventRouter, GLDAnalyst,
MacroContextWatcher, MarketEventWatcher, OptionsFlowWatcher,
PortfolioMonitorAgent, PublisherAgent, QQQAnalyst, QuantResearcherAgent,
QuantStrategistAgent, RiskAnalystAgent, SentimentAnalystAgent, SPYAnalyst,
TrendAnalystAgent, UnusualEventDetector, VizAgent,
)
from polyhedra.core.role_registry import RoleEntry
from polyhedra.core.session import SessionManager
app = typer.Typer(
name="poly",
help="Polyhedra collaborative multi-agent quant team.",
no_args_is_help=True,
rich_markup_mode="markdown",
)
console = Console()
err_console = Console(stderr=True)
_sm = SessionManager()
# --------------------------------------------------------------------------- #
# Shared helpers
# --------------------------------------------------------------------------- #
_QUANT_AGENTS = (
(DataFetcherAgent, "datafetcher"),
(TrendAnalystAgent, "trendanalyst"),
(SentimentAnalystAgent, "sentimentanalyst"),
(MarketEventWatcher, "marketeventwatcher"),
(OptionsFlowWatcher, "optionsflowwatcher"),
(MacroContextWatcher, "macrocontextwatcher"),
(UnusualEventDetector, "unusualeventdetector"),
(EventRouter, "eventrouter"),
(BTCAnalyst, "btcanalyst"),
(SPYAnalyst, "spyanalyst"),
(QQQAnalyst, "qqqanalyst"),
(GLDAnalyst, "gldanalyst"),
(QuantResearcherAgent, "quantresearcher"),
(BacktesterAgent, "backtester"),
(RiskAnalystAgent, "riskanalyst"),
(QuantStrategistAgent, "quantstrategist"),
(VizAgent, "vizagent"),
(PortfolioMonitorAgent, "portfoliomonitor"),
(PublisherAgent, "publisher"),
)
def _register_quant_agents(session) -> None:
for agent_cls, role in _QUANT_AGENTS:
session.registry.register(RoleEntry(role=role, agent=agent_cls()))
def _build_full_session(goal: str = "", platform: str = "cli", human_roles: list[str] | None = None) -> tuple:
"""Create a new session with the current quant agents registered."""
human_roles = human_roles or []
session = _sm.create(goal=goal, platform=platform)
_register_quant_agents(session)
for r in human_roles:
session.registry.take_over(r)
def _post(from_role: str, content: str) -> None:
label = from_role.upper()
console.print(f"\n[bold cyan]@{label}[/bold cyan]")
console.print(Markdown(content))
async def post_fn(from_role: str, content: str) -> None: # noqa: RUF029
_post(from_role, content)
async def checkpoint_fn(summary: str) -> CheckpointResult: # noqa: RUF029
console.print(
Panel(
f"[bold yellow]⏸ Checkpoint[/bold yellow]\n\n{summary}\n\n"
"[dim]Proceed? \\[yes / adjust / stop][/dim]",
border_style="yellow",
)
)
response = typer.prompt("", default="yes").strip().lower()
approved = response in ("yes", "y", "")
return CheckpointResult(approved=approved, response=response)
service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
return session, service
# --------------------------------------------------------------------------- #
# Commands
# --------------------------------------------------------------------------- #
@app.command()
def init(
goal: Annotated[str, typer.Argument(help="One-sentence quant analysis goal.")],
roles: Annotated[
Optional[str],
typer.Option("--roles", "-r", help="Comma-separated roles to activate (default: all)."),
] = None,
human: Annotated[
Optional[str],
typer.Option("--human", "-H", help="Comma-separated roles you will hold yourself."),
] = None,
) -> None:
"""Start a new collaborative quant session."""
human_roles = [r.strip().lower() for r in (human or "").split(",") if r.strip()]
selected_roles = (
[r.strip().lower() for r in roles.split(",") if r.strip()]
if roles
else [role for _, role in _QUANT_AGENTS]
)
session, service = _build_full_session(goal=goal, human_roles=human_roles)
console.print(Panel(f"[bold green]Polyhedra Quant[/bold green] — Session [bold]{session.session_id}[/bold]", border_style="green"))
asyncio.run(
service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=human_roles)
)
console.print(f"\n[dim]Session ID: {session.session_id}[/dim]")
console.print("[dim]Type a message with @agent-name to start, or run `poly resume` later.[/dim]\n")
# Interactive loop
while True:
try:
user_input = typer.prompt("you")
except (EOFError, KeyboardInterrupt):
console.print("\n[dim]Session paused. Resume with:[/dim] poly resume " + session.session_id)
break
if user_input.strip().lower() in ("/quit", "/exit", "exit", "quit"):
console.print(f"[dim]Session saved. Resume with:[/dim] poly resume {session.session_id}")
break
asyncio.run(service.dispatch(from_role="human", text=user_input))
@app.command()
def state(
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
) -> None:
"""Print the current Research State."""
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No sessions found. Start one with: poly init[/red]")
raise typer.Exit(1)
session = _sm.resume(sid)
if not session:
err_console.print(f"[red]Session {sid} not found.[/red]")
raise typer.Exit(1)
console.print(Markdown(session.research_state.to_markdown()))
@app.command()
def resume(
session_id: Annotated[str, typer.Argument(help="Session ID to rejoin.")],
) -> None:
"""Rejoin an existing session."""
session = _sm.resume(session_id)
if not session:
err_console.print(f"[red]Session {session_id} not found.[/red]")
raise typer.Exit(1)
_register_quant_agents(session)
console.print(Panel(
f"[bold green]Resuming session[/bold green] [bold]{session_id}[/bold]\n"
f"Goal: [italic]{session.goal}[/italic]",
border_style="green",
))
_ = [e.role for e in session.registry.human_roles()] # retained for future use
# Re-attach post/checkpoint functions
def _post(from_role: str, content: str) -> None:
console.print(f"\n[bold cyan]@{from_role.upper()}[/bold cyan]")
console.print(Markdown(content))
async def post_fn(from_role: str, content: str) -> None: # noqa: RUF029
_post(from_role, content)
async def checkpoint_fn(summary: str) -> CheckpointResult: # noqa: RUF029
console.print(Panel(f"[bold yellow]⏸ Checkpoint[/bold yellow]\n\n{summary}", border_style="yellow"))
response = typer.prompt("Proceed?", default="yes").strip().lower()
return CheckpointResult(approved=response in ("yes", "y", ""), response=response)
service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
while True:
try:
user_input = typer.prompt("you")
except (EOFError, KeyboardInterrupt):
console.print(f"\n[dim]Session paused. Resume with: poly resume {session_id}[/dim]")
break
if user_input.strip().lower() in ("/quit", "/exit", "exit", "quit"):
break
asyncio.run(service.dispatch(from_role="human", text=user_input))
@app.command()
def export(
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
output: Annotated[
Path,
typer.Option("--output", "-o", help="Directory to write the zip file."),
] = Path("./exports"),
) -> None:
"""Export all session state, run records, inputs, and artifacts as a zip."""
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No sessions found.[/red]")
raise typer.Exit(1)
try:
zip_path = _sm.export(sid, output)
console.print(f"[green]✓[/green] Exported to: [bold]{zip_path}[/bold]")
except FileNotFoundError as exc:
err_console.print(f"[red]{exc}[/red]")
raise typer.Exit(1)
@app.command()
def role(
name: Annotated[str, typer.Argument(help="Role name, e.g. critic")],
holder: Annotated[str, typer.Argument(help='"human" or "agent"')],
session_id: Annotated[Optional[str], typer.Option("--session", "-s", help="Session ID.")] = None,
) -> None:
"""Take over (human) or release (agent) an agent role mid-session."""
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No active session.[/red]")
raise typer.Exit(1)
session = _sm.resume(sid)
if not session:
err_console.print(f"[red]Session {sid} not found.[/red]")
raise typer.Exit(1)
role_name = name.lower()
if holder == "human":
ok = session.registry.take_over(role_name)
msg = f"✅ You are now holding the [bold]{role_name.title()}[/bold] role."
elif holder == "agent":
ok = session.registry.reinstate(role_name)
msg = f"✅ [bold]{role_name.title()}[/bold] role returned to AI agent."
else:
err_console.print("[red]Holder must be 'human' or 'agent'.[/red]")
raise typer.Exit(1)
if ok:
session.save_meta()
console.print(msg)
else:
err_console.print(f"[red]Role '{role_name}' not found in session.[/red]")
raise typer.Exit(1)
@app.command(name="sessions")
def list_sessions() -> None:
"""List all saved sessions."""
all_sessions = _sm.list_sessions()
if not all_sessions:
console.print("[dim]No sessions found. Start one with: poly init[/dim]")
return
table = Table(title="Polyhedra Sessions", show_header=True, header_style="bold cyan")
table.add_column("ID", style="bold")
table.add_column("Goal")
table.add_column("Platform")
table.add_column("Created")
for s in all_sessions:
table.add_row(
s.get("session_id", "?"),
(s.get("goal", "") or "")[:60],
s.get("platform", "cli"),
(s.get("created_at", "") or "")[:16],
)
console.print(table)
@app.command()
def mcp() -> None:
"""Start the Polyhedra MCP server (for IDE integrations)."""
from polyhedra.server import main as _mcp_main
console.print("[bold]Starting Polyhedra MCP server…[/bold]")
_mcp_main()
@app.command()
def cache(
action: Annotated[str, typer.Argument(help='"clear" or "status"')],
session_id: Annotated[Optional[str], typer.Option("--session", "-s", help="Session ID (uses latest if omitted).")] = None,
) -> None:
"""Manage the session SharedCache.
\b
poly cache clear — flush all cached entries for the session
poly cache status — show cache stats (hit rate, entry count, size)
"""
if action not in ("clear", "status"):
err_console.print("[red]action must be 'clear' or 'status'[/red]")
raise typer.Exit(1)
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No sessions found. Start one with: poly init[/red]")
raise typer.Exit(1)
session = _sm.resume(sid)
if not session:
err_console.print(f"[red]Session {sid} not found.[/red]")
raise typer.Exit(1)
output_lines: list[str] = []
async def post_fn(from_role: str, content: str) -> None: # noqa: RUF029
output_lines.append(content)
async def checkpoint_fn(summary: str) -> CheckpointResult: # noqa: RUF029
return CheckpointResult(approved=True, response="yes")
service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
asyncio.run(service.dispatch(from_role="human", text=f"/poly cache {action}"))
for line in output_lines:
console.print(Markdown(line))
@app.command()
def tokens(
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
) -> None:
"""Print the token usage summary for a session."""
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No sessions found. Start one with: poly init[/red]")
raise typer.Exit(1)
session = _sm.resume(sid)
if not session:
err_console.print(f"[red]Session {sid} not found.[/red]")
raise typer.Exit(1)
output_lines: list[str] = []
async def post_fn(from_role: str, content: str) -> None: # noqa: RUF029
output_lines.append(content)
async def checkpoint_fn(summary: str) -> CheckpointResult: # noqa: RUF029
return CheckpointResult(approved=True, response="yes")
service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
asyncio.run(service.dispatch(from_role="human", text="/poly tokens"))
for line in output_lines:
console.print(Markdown(line))
@app.command()
def trace(
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
) -> None:
"""Print the last 10 trace entries for a session (STRUCT-3 FR-S3.5)."""
sid = session_id or _latest_session_id()
if not sid:
err_console.print("[red]No sessions found. Start one with: poly init[/red]")
raise typer.Exit(1)
session = _sm.resume(sid)
if not session:
err_console.print(f"[red]Session {sid} not found.[/red]")
raise typer.Exit(1)
output_lines: list[str] = []
async def post_fn(from_role: str, content: str) -> None: # noqa: RUF029
output_lines.append(content)
async def checkpoint_fn(summary: str) -> CheckpointResult: # noqa: RUF029
return CheckpointResult(approved=True, response="yes")
service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
asyncio.run(service.dispatch(from_role="human", text="/poly trace"))
for line in output_lines:
console.print(Markdown(line))
@app.command(name="help")
def help_command() -> None:
"""Show all available Polyhedra commands (STRUCT-4 FR-S4.5)."""
from polyhedra.core.template_builder import COMMAND_REGISTRY, render_help_cli
from rich.table import Table
table = Table(title="Polyhedra — Commands", show_header=True, header_style="bold cyan")
table.add_column("Group", style="bold")
table.add_column("Slash command")
table.add_column("@mention")
table.add_column("CLI")
table.add_column("Description")
current_group = ""
for entry in COMMAND_REGISTRY:
group = entry.group if entry.group != current_group else ""
current_group = entry.group
table.add_row(group, entry.slash, entry.mention, entry.cli, entry.description)
console.print(table)
# --------------------------------------------------------------------------- #
# Helpers
# --------------------------------------------------------------------------- #
def _latest_session_id() -> str | None:
"""Return the most recently created session ID, or None."""
sessions = _sm.list_sessions()
if not sessions:
return None
# Sessions are sorted by directory name (UUID prefix); last = most recent
return sessions[-1].get("session_id")
def main() -> None:
app()
if __name__ == "__main__":
main()