File size: 16,500 Bytes
748cf22
891fe52
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
748cf22
891fe52
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
 
 
 
 
 
 
891fe52
 
 
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
891fe52
748cf22
891fe52
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
748cf22
891fe52
 
 
 
 
748cf22
891fe52
 
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
 
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc23e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a526b57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"""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()