Download src/polyhedra/core/session.py from polyHedra/PolyHedra: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/session.py
- Command line
-
hf download hf://spaces/polyHedra/PolyHedra/src/polyhedra/core/session.py
-
curl -L -o session.py https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/session.py
10.5 kB
| """Session management for Polyhedra v3.0. | |
| A Session captures all mutable state for a single research collaboration: | |
| - which agents are active | |
| - the role registry | |
| - the thread message log | |
| - a reference to the Research State manager | |
| Sessions are persisted under ``~/.polyhedra/sessions/<session_id>/``. | |
| V4.4 additions: | |
| - ``SessionManager.active_sessions_with_positions()`` — returns session IDs | |
| that have open paper positions, used by the PortfolioMonitor scheduler. | |
| - ``SessionManager`` persists an active sessions registry to | |
| ``~/.polyhedra/sessions/registry.json`` (FR-2.5). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import os | |
| import uuid | |
| from dataclasses import asdict, dataclass, field | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| from polyhedra.core.research_state import ResearchState, ResearchStateManager | |
| from polyhedra.core.role_registry import RoleRegistry, RoleEntry, HELD_BY_AGENT | |
| logger = logging.getLogger(__name__) | |
| _SESSIONS_DIR = Path.home() / ".polyhedra" / "sessions" | |
| class ThreadMessage: | |
| """A single message in the session thread.""" | |
| from_role: str # "human" | agent role name | |
| content: str | |
| message_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8]) | |
| timestamp: datetime = field(default_factory=lambda: datetime.now(tz=timezone.utc)) | |
| metadata: dict[str, Any] = field(default_factory=dict) | |
| def to_dict(self) -> dict[str, Any]: | |
| return { | |
| "from_role": self.from_role, | |
| "content": self.content, | |
| "message_id": self.message_id, | |
| "timestamp": self.timestamp.isoformat(), | |
| "metadata": self.metadata, | |
| } | |
| def from_dict(cls, d: dict[str, Any]) -> "ThreadMessage": | |
| return cls( | |
| from_role=d.get("from_role", "unknown"), | |
| content=d.get("content", ""), | |
| message_id=d.get("message_id", ""), | |
| timestamp=datetime.fromisoformat(d["timestamp"]) if d.get("timestamp") else datetime.now(tz=timezone.utc), | |
| metadata=d.get("metadata", {}), | |
| ) | |
| class Session: | |
| """ | |
| All mutable state for a single Polyhedra session. | |
| The session directory layout:: | |
| ~/.polyhedra/sessions/<session_id>/ | |
| session.json # goal, active_roles, created_at, etc. | |
| research_state.json # Research State (managed by ResearchStateManager) | |
| thread.jsonl # append-only thread log | |
| artifacts/ # exported draft sections, .bib, etc. | |
| """ | |
| def __init__(self, session_id: str, session_dir: Path) -> None: | |
| self.session_id = session_id | |
| self.session_dir = session_dir | |
| self.session_dir.mkdir(parents=True, exist_ok=True) | |
| self.state_manager = ResearchStateManager(session_dir) | |
| self.registry = RoleRegistry() | |
| self._thread_path = session_dir / "thread.jsonl" | |
| self._meta_path = session_dir / "session.json" | |
| self.goal: str = "" | |
| self.active_roles: list[str] = [] | |
| self.created_at: datetime = datetime.now(tz=timezone.utc) | |
| self.platform: str = "cli" # "cli" | "slack" | "teams" | "spark" | |
| # ------------------------------------------------------------------ # | |
| # Thread management | |
| # ------------------------------------------------------------------ # | |
| def post(self, from_role: str, content: str, metadata: dict[str, Any] | None = None) -> ThreadMessage: | |
| """Append a message to the thread and return it.""" | |
| msg = ThreadMessage(from_role=from_role, content=content, metadata=metadata or {}) | |
| with self._thread_path.open("a", encoding="utf-8") as fh: | |
| fh.write(json.dumps(msg.to_dict()) + "\n") | |
| return msg | |
| def thread_history(self, last_n: int = 20) -> list[dict[str, Any]]: | |
| """Return the last N thread messages as plain dicts.""" | |
| if not self._thread_path.exists(): | |
| return [] | |
| lines = self._thread_path.read_text(encoding="utf-8").splitlines() | |
| recent = lines[-last_n:] | |
| messages = [] | |
| for line in recent: | |
| try: | |
| messages.append(json.loads(line)) | |
| except json.JSONDecodeError: | |
| pass | |
| return messages | |
| def full_thread(self) -> list[ThreadMessage]: | |
| """Return all thread messages.""" | |
| if not self._thread_path.exists(): | |
| return [] | |
| messages = [] | |
| for line in self._thread_path.read_text(encoding="utf-8").splitlines(): | |
| try: | |
| messages.append(ThreadMessage.from_dict(json.loads(line))) | |
| except Exception: | |
| pass | |
| return messages | |
| # ------------------------------------------------------------------ # | |
| # Research State convenience | |
| # ------------------------------------------------------------------ # | |
| def research_state(self) -> ResearchState: | |
| return self.state_manager.load() | |
| # ------------------------------------------------------------------ # | |
| # Persistence | |
| # ------------------------------------------------------------------ # | |
| def save_meta(self) -> None: | |
| meta = { | |
| "session_id": self.session_id, | |
| "goal": self.goal, | |
| "active_roles": self.active_roles, | |
| "created_at": self.created_at.isoformat(), | |
| "platform": self.platform, | |
| "role_registry": self.registry.to_dict(), | |
| } | |
| self._meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8") | |
| def load_meta(self) -> None: | |
| if not self._meta_path.exists(): | |
| return | |
| try: | |
| meta = json.loads(self._meta_path.read_text(encoding="utf-8")) | |
| self.goal = meta.get("goal", "") | |
| self.active_roles = meta.get("active_roles", []) | |
| self.platform = meta.get("platform", "cli") | |
| created = meta.get("created_at") | |
| if created: | |
| self.created_at = datetime.fromisoformat(created) | |
| except Exception as exc: | |
| logger.error("Failed to load session meta for %s: %s", self.session_id, exc) | |
| class SessionManager: | |
| """Create, list, and resume sessions.""" | |
| def __init__(self, sessions_dir: Path | None = None) -> None: | |
| configured_dir = os.environ.get("POLYHEDRA_SESSIONS_DIR", "").strip() | |
| self._dir = sessions_dir or ( | |
| Path(configured_dir).expanduser() if configured_dir else _SESSIONS_DIR | |
| ) | |
| self._dir.mkdir(parents=True, exist_ok=True) | |
| def create(self, goal: str = "", platform: str = "cli", roles: list[str] | None = None) -> Session: | |
| session_id = str(uuid.uuid4())[:8] | |
| session_dir = self._dir / session_id | |
| session = Session(session_id=session_id, session_dir=session_dir) | |
| session.goal = goal | |
| session.platform = platform | |
| session.active_roles = roles or [] | |
| session.save_meta() | |
| return session | |
| def resume(self, session_id: str) -> Session | None: | |
| session_dir = self._dir / session_id | |
| if not session_dir.exists(): | |
| logger.error("Session %s not found.", session_id) | |
| return None | |
| session = Session(session_id=session_id, session_dir=session_dir) | |
| session.load_meta() | |
| return session | |
| def list_sessions(self) -> list[dict[str, Any]]: | |
| sessions = [] | |
| for path in sorted(self._dir.iterdir()): | |
| if path.is_dir(): | |
| meta_file = path / "session.json" | |
| if meta_file.exists(): | |
| try: | |
| sessions.append(json.loads(meta_file.read_text(encoding="utf-8"))) | |
| except Exception: | |
| pass | |
| return sessions | |
| def export(self, session_id: str, output_dir: Path) -> Path: | |
| """ | |
| Export all session artifacts (Research State, thread log, drafts, .bib) | |
| into a zip archive at ``output_dir/<session_id>.zip``. | |
| """ | |
| import zipfile | |
| session_dir = self._dir / session_id | |
| if not session_dir.exists(): | |
| raise FileNotFoundError(f"Session {session_id} not found.") | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| zip_path = output_dir / f"{session_id}.zip" | |
| with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: | |
| for file in session_dir.rglob("*"): | |
| if file.is_file(): | |
| zf.write(file, file.relative_to(session_dir)) | |
| return zip_path | |
| # ------------------------------------------------------------------ # | |
| # V4.4 FIX-2: Active session registry for PortfolioMonitor scheduler | |
| # ------------------------------------------------------------------ # | |
| def active_sessions_with_positions(self) -> list[str]: | |
| """Return session_ids where QuantState.portfolio has open PaperPositions. | |
| Used by the PortfolioMonitor scheduler to know which sessions to | |
| check on each tick (FR-2.1). Sessions with ``monitor_paused=True`` | |
| are excluded (FR-2.3). | |
| """ | |
| from polyhedra.core.research_state import ResearchStateManager | |
| active: list[str] = [] | |
| for path in sorted(self._dir.iterdir()): | |
| if not path.is_dir(): | |
| continue | |
| meta_file = path / "session.json" | |
| if not meta_file.exists(): | |
| continue | |
| try: | |
| manager = ResearchStateManager(path) | |
| state = manager.load() | |
| qs = state.quant_state | |
| if qs is None: | |
| continue | |
| if qs.monitor_paused: | |
| continue | |
| open_positions = [p for p in qs.portfolio if p.status == "open"] | |
| if open_positions: | |
| active.append(path.name) | |
| except Exception: | |
| pass | |
| return active | |
| def _registry_path(self) -> Path: | |
| return self._dir / "registry.json" | |
| def _save_registry(self, session_ids: list[str]) -> None: | |
| """Persist active session IDs to registry.json so it survives restarts (FR-2.5).""" | |
| try: | |
| self._registry_path().write_text( | |
| json.dumps({"active_sessions": session_ids}, indent=2), | |
| encoding="utf-8", | |
| ) | |
| except Exception as exc: | |
| logger.warning("Failed to persist session registry: %s", exc) | |