"""Agent base class and shared data models for Polyhedra v4.3.""" from __future__ import annotations import logging from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime, timezone from typing import TYPE_CHECKING, Any from pydantic import BaseModel if TYPE_CHECKING: from polyhedra.core.eventbus import EventBus from polyhedra.core.token_budget import TokenBudget from polyhedra.core.trace_logger import TraceLogger from polyhedra.services.file_writer import FileWriter @dataclass class Mention: """Represents an @mention directed at an agent.""" mentioned_role: str # e.g. "scout", "strategist" from_role: str # who sent it — role name or "human" content: str # full text of the message thread_message_id: str = "" timestamp: datetime = field(default_factory=lambda: datetime.now(tz=timezone.utc)) metadata: dict[str, Any] = field(default_factory=dict) @dataclass class AgentResponse: """Structured response produced by an agent.""" agent_role: str content: str # markdown-formatted message to post in thread mentions: list[str] = field(default_factory=list) # roles this response should @mention artifact_path: str | None = None # V4.1: relative path of artifact written this invocation artifact_mode: str = "overwrite" # V4.1: "overwrite" or "append" updates_state: bool = False # True if Coordinator should refresh Research State state_patch: dict[str, Any] = field(default_factory=dict) # V4.1: partial state fields checkpoint_required: bool = False # True if a human checkpoint should be triggered checkpoint_summary: str = "" # Summary shown in checkpoint message error: str | None = None metadata: dict[str, Any] = field(default_factory=dict) # deprecated — use output instead output: BaseModel | None = None # V4.4 STRUCT-2: typed per-agent output (FR-S2.3) class Agent(ABC): """ Abstract base class for all Polyhedra agents. Every concrete agent implements ``handle()`` and ``can_handle()``. The Coordinator calls ``can_handle`` to decide routing, then ``handle`` to produce a response. V4.1: ``files`` (FileWriter) is injected by the Coordinator before each ``handle()`` call and is the only I/O tool available to agents. """ name: str # Human-readable name, e.g. "Scout" role: str # Lowercase key used in @mentions, e.g. "scout" role_title: str # Display title, e.g. "Literature Researcher" system_prompt: str # Role definition injected into every LLM call # V4.1: injected by Coordinator before handle() — do not set in agent __init__ files: FileWriter # type: ignore[name-defined] # V4.3: injected by Coordinator before handle() bus: "EventBus | None" = None # EventBus for publishing completion events token_budget: "TokenBudget | None" = None # per-agent budget; None = use DEFAULT_BUDGET trace: "TraceLogger | None" = None # V4.4 STRUCT-3: trace logger (FR-S3.2) def __init__(self) -> None: self.logger = logging.getLogger(f"polyhedra.agents.{self.role}") @abstractmethod async def handle( self, mention: Mention, thread_context: list[dict[str, Any]], research_state: dict[str, Any], ) -> AgentResponse: """ Process an @mention and produce a response. Args: mention: The incoming @mention. thread_context: Recent thread messages (capped, serialised dicts). research_state: Current Research State document. Returns: AgentResponse with content and any follow-up @mentions. """ @abstractmethod async def can_handle(self, mention: Mention) -> bool: """Return True if this agent should handle the given mention.""" # ------------------------------------------------------------------ # Helpers shared across agents # ------------------------------------------------------------------ def _format_thread_context(self, thread_context: list[dict[str, Any]], max_messages: int = 10) -> str: """Convert recent thread messages to a compact string for prompt injection.""" recent = thread_context[-max_messages:] lines: list[str] = [] for msg in recent: sender = msg.get("from_role", "unknown") text = msg.get("content", "") lines.append(f"[{sender}]: {text}") return "\n".join(lines) def _format_research_state(self, research_state: dict[str, Any]) -> str: """Render the Research State as compact markdown for prompt injection.""" if not research_state: return "(no research state yet)" lines = [ f"**Goal:** {research_state.get('goal', 'not set')}", f"**Field:** {research_state.get('field', 'not set')}", ] gaps = research_state.get("gaps", []) if gaps: lines.append("**Gaps:** " + "; ".join(str(g) for g in gaps)) hyp = research_state.get("active_hypothesis") if hyp: lines.append(f"**Hypothesis:** {hyp}") papers = research_state.get("key_papers", []) if papers: lines.append(f"**Key papers ({len(papers)}):** " + "; ".join(p.get("title", "") for p in papers[:5])) open_q = research_state.get("open_questions", []) if open_q: lines.append("**Open questions:** " + "; ".join(str(q) for q in open_q)) return "\n".join(lines) def _log_token_usage( self, research_state: dict[str, Any], prompt_tokens: int, completion_tokens: int, *, cache_hit: bool = False, estimated_cost_usd: float = 0.0, ) -> None: """ Append a TokenUsageEntry to QuantState.token_log (V4.3 FR-4.4). No-op if the research state has no quant_state. """ from datetime import datetime, timezone from polyhedra.core.research_state import TokenUsageEntry qs_dict = research_state.get("quant_state") if not isinstance(qs_dict, dict): return entry = TokenUsageEntry( agent_role=self.role, timestamp=datetime.now(tz=timezone.utc).isoformat(), prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, estimated_cost_usd=estimated_cost_usd, cache_hit=cache_hit, ) token_log = qs_dict.setdefault("token_log", []) from dataclasses import asdict as _asdict token_log.append(_asdict(entry))