Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge upstream/main into upstream-pr/08-hardening-docs

Mirandaa9835776ade6
diff --cc agent/src/api/runs_routes.py
index 000000000,bf7e62533..e45676f19
mode 000000,100644..100644
--- a/agent/src/api/runs_routes.py
+++ b/agent/src/api/runs_routes.py
@@@ -1,0 -1,437 +1,444 @@@
+ """Run listing and detail HTTP routes.
+
+ Mounted by ``agent/api_server.py`` via ``register_runs_routes(app, ...)``.
+ """
+
+ from __future__ import annotations
+
+ import csv
+ import json
+ from datetime import datetime
+ from pathlib import Path
+ from typing import Any, Awaitable, Callable, Dict, List, Optional
+
+ from fastapi import Depends, FastAPI, HTTPException, Query, status
+ from fastapi.responses import JSONResponse
+
+
+ # ---------------------------------------------------------------------------
+ # Helper functions (module-level; host Pydantic models resolved via sys.modules)
+ # ---------------------------------------------------------------------------
+
+
+ def _load_json_file(path: Path) -> Optional[Dict[str, Any]]:
+ """Load JSON from disk if present."""
+ try:
+ if path.exists():
+ return json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ pass
+ return None
+
+
+ def _load_csv_to_dict(path: Path, limit: Optional[int] = None) -> List[Dict[str, Any]]:
+ """Load CSV rows into a list of dictionaries."""
+ try:
+ if not path.exists():
+ return []
+ with path.open("r", encoding="utf-8", newline="") as handle:
+ rows = [dict(row) for row in csv.DictReader(handle)]
+ if limit is not None:
+ rows = rows[:limit]
+ return rows
+ except Exception:
+ return []
+
+
+ def _run_response_payload(response: Any) -> Dict[str, Any]:
+ """Return a JSON-ready payload for opt-in run response variants."""
+ return response.model_dump(mode="json")
+
+
+ def _build_response_from_run_dir(
+ run_dir: Path,
+ elapsed: float,
+ *,
+ include_analysis: bool = False,
+ chart_symbol: Optional[str] = None,
+ chart_payload: str = "full",
+ chart_symbols_out: Optional[List[str]] = None,
+ ):
+ """Build a run response from a persisted run directory."""
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ RunResponse = host.RunResponse
+ BacktestMetrics = host.BacktestMetrics
+ RAGSelection = host.RAGSelection
+ Artifact = host.Artifact
+
+ run_id = run_dir.name
+
+ response = RunResponse(
+ status="unknown",
+ run_id=run_id,
+ elapsed_seconds=elapsed,
+ run_directory=str(run_dir),
+ )
+
+ state_data = _load_json_file(run_dir / "state.json")
+ if state_data:
+ state_status = str(state_data.get("status") or "").lower()
+ if state_status == "success":
+ response.status = "success"
+ elif state_status == "failed":
+ response.status = "failed"
+ response.reason = state_data.get("reason", "")
+ else:
+ response.status = state_status or "unknown"
+ else:
+ response.status = "unknown"
+
+ planner_path = run_dir / "planner_output.json"
+ response.planner_output = _load_json_file(planner_path)
+
+ design_path = run_dir / "design_spec.json"
+ response.strategy_spec = _load_json_file(design_path)
+
+ rag_path = run_dir / "rag_metadata.json"
+ rag_data = _load_json_file(rag_path)
+ if rag_data:
+ response.rag_selection = RAGSelection(
+ selected_api=rag_data.get("selected_api") or rag_data.get("api_code", ""),
+ selected_name=rag_data.get("selected_name") or rag_data.get("api_name", ""),
+ selected_score=float(rag_data.get("selected_score") or rag_data.get("score", 0.0)),
+ )
+
+ metrics_path = run_dir / "artifacts" / "metrics.csv"
+ if metrics_path.exists():
+ metrics_dict_list = _load_csv_to_dict(metrics_path, limit=1)
+ if metrics_dict_list:
+ row = metrics_dict_list[0]
+ try:
+ # Pass ALL CSV columns to BacktestMetrics (extra="allow")
+ parsed: dict = {}
+ for k, v in row.items():
+ if not k or not v:
+ continue
+ try:
+ parsed[k] = int(float(v)) if k == "trade_count" or k == "max_consecutive_loss" else float(v)
+ except (ValueError, TypeError):
+ continue
+ if "final_value" in parsed:
+ response.metrics = BacktestMetrics(**parsed)
+ except (ValueError, TypeError):
+ pass
+
+ artifacts_dir = run_dir / "artifacts"
+ if artifacts_dir.exists():
+ for file_path in artifacts_dir.iterdir():
+ if file_path.is_file():
+ file_type = file_path.suffix.lstrip(".")
+ response.artifacts.append(
+ Artifact(
+ name=file_path.name,
+ path=str(file_path),
+ type=file_type if file_type else "unknown",
+ size=file_path.stat().st_size,
+ exists=True,
+ )
+ )
+
+ equity_path = run_dir / "artifacts" / "equity.csv"
+ if equity_path.exists():
+ response.artifacts_equity_csv = _load_csv_to_dict(equity_path)
+
+ metrics_csv_path = run_dir / "artifacts" / "metrics.csv"
+ if metrics_csv_path.exists():
+ response.artifacts_metrics_csv = _load_csv_to_dict(metrics_csv_path)
+
+ run_card_path = run_dir / "run_card.json"
+ if run_card_path.exists():
+ try:
+ response.run_card = json.loads(run_card_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ pass
+
++ research_card_path = run_dir / "research_card.json"
++ if research_card_path.exists():
++ try:
++ response.research_card = json.loads(research_card_path.read_text(encoding="utf-8"))
++ except (json.JSONDecodeError, OSError):
++ pass
++
+ llm_usage_path = run_dir / "llm_usage.json"
+ if llm_usage_path.exists():
+ try:
+ response.llm_usage = json.loads(llm_usage_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ trades_path = run_dir / "artifacts" / "trades.csv"
+ if trades_path.exists():
+ response.artifacts_trades_csv = _load_csv_to_dict(trades_path)
+
+ validation_path = run_dir / "artifacts" / "validation.json"
+ if validation_path.exists():
+ try:
+ response.validation = json.loads(validation_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ if response.artifacts_equity_csv:
+ filtered_equity = []
+ for row in response.artifacts_equity_csv[:1000]:
+ filtered_row: Dict[str, Any] = {}
+ if "timestamp" in row:
+ filtered_row["time"] = row["timestamp"]
+ if "equity" in row:
+ filtered_row["equity"] = row["equity"]
+ if "drawdown" in row:
+ filtered_row["drawdown"] = row["drawdown"]
+ filtered_equity.append(filtered_row)
+ response.equity_curve = filtered_equity
+
+ if response.artifacts_trades_csv:
+ response.trade_log = response.artifacts_trades_csv[:500]
+
+ if include_analysis:
+ from src.ui_services import build_run_analysis
+
+ analysis = build_run_analysis(
+ run_dir,
+ symbols=[chart_symbol] if chart_symbol else None,
+ include_payload=chart_payload != "summary" or bool(chart_symbol),
+ include_symbol_list=chart_symbols_out is not None,
+ )
+ if chart_symbols_out is not None:
+ chart_symbols_out.extend(analysis.get("chart_symbols") or [])
+ response.run_stage = analysis.get("run_stage")
+ response.run_context = analysis.get("run_context")
+ response.price_series = analysis.get("price_series")
+ response.indicator_series = analysis.get("indicator_series")
+ response.trade_markers = analysis.get("trade_markers")
+ response.run_logs = analysis.get("run_logs")
+
+ return response
+
+
+ # ---------------------------------------------------------------------------
+ # Registration
+ # ---------------------------------------------------------------------------
+
+ AuthDep = Callable[..., Awaitable[Any] | Any]
+
+
+ def register_runs_routes(
+ app: FastAPI,
+ require_auth: AuthDep | None = None,
+ ) -> None:
+ """Mount the runs routes onto ``app``.
+
+ Resolves ``require_auth`` from the host ``api_server`` module via
+ ``sys.modules`` when not passed explicitly.
+ """
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host is None:
+ raise RuntimeError(
+ "register_runs_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ if require_auth is None:
+ require_auth = host.require_auth
+
+ # Late-access closures for shared host symbols (monkeypatch-safe)
+ def _host_validate_path_param(value: str, kind: str) -> None:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._validate_path_param(value, kind)
+
+ def _host_RUNS_DIR() -> Path:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h.RUNS_DIR
+
+ # Pydantic models for response_model (resolved at registration time)
+ RunResponse = host.RunResponse
+ RunInfo = host.RunInfo
+
+ # --- Routes ---
+
+ @app.get("/runs/{run_id}/code", dependencies=[Depends(require_auth)])
+ async def get_run_code(run_id: str):
+ """Return strategy source files for a run.
+
+ Args:
+ run_id: Run identifier.
+
+ Returns:
+ Map filename -> source text.
+ """
+ _host_validate_path_param(run_id, "run_id")
+ run_dir = _host_RUNS_DIR() / run_id / "code"
+ if not run_dir.exists():
+ raise HTTPException(status_code=404, detail=f"Code directory for run {run_id} not found")
+ result = {}
+ for f in ["signal_engine.py"]:
+ p = run_dir / f
+ if p.exists():
+ result[f] = p.read_text(encoding="utf-8")
+ return result
+
+ @app.get("/runs/{run_id}/pine", dependencies=[Depends(require_auth)])
+ async def get_run_pine(run_id: str):
+ """Return Pine Script file for a run.
+
+ Args:
+ run_id: Run identifier.
+
+ Returns:
+ Object with pine script content and exists flag.
+ """
+ _host_validate_path_param(run_id, "run_id")
+ pine_path = _host_RUNS_DIR() / run_id / "artifacts" / "strategy.pine"
+ if not pine_path.exists():
+ return {"exists": False, "content": None}
+ return {
+ "exists": True,
+ "content": pine_path.read_text(encoding="utf-8"),
+ }
+
+ @app.get("/runs/{run_id}", response_model=RunResponse, dependencies=[Depends(require_auth)])
+ async def get_run_result(
+ run_id: str,
+ chart_symbol: Optional[str] = Query(None, description="Opt in to chart payloads for a single symbol"),
+ chart_payload: Optional[str] = Query(
+ None,
+ description="Optional chart payload mode. Use 'summary' to omit chart rows and trade markers.",
+ ),
+ ):
+ """Fetch details for a historical run by ``run_id``.
+
+ The default response stays unchanged for existing consumers. Chart-heavy
+ optimizations are opt-in via query parameters.
+ """
+ _host_validate_path_param(run_id, "run_id")
+ if chart_payload not in (None, "summary"):
+ raise HTTPException(status_code=400, detail="invalid chart_payload")
+ run_dir = _host_RUNS_DIR() / run_id
+
+ if not run_dir.exists():
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Run {run_id} not found"
+ )
+
+ wants_chart_meta = bool(chart_payload or chart_symbol)
+ chart_symbols: List[str] = []
+ response = _build_response_from_run_dir(
+ run_dir,
+ elapsed=0.0,
+ include_analysis=True,
+ chart_symbol=chart_symbol,
+ chart_payload=chart_payload or "full",
+ chart_symbols_out=chart_symbols if wants_chart_meta else None,
+ )
+
+ if wants_chart_meta:
+ payload = _run_response_payload(response)
+ payload["chart_symbols"] = chart_symbols
+ return JSONResponse(payload)
+
+ return response
+
+ @app.get("/runs", response_model=List[RunInfo], dependencies=[Depends(require_auth)])
+ async def list_runs(limit: int = 20):
+ """List recent runs with summary fields."""
+ from src.ui_services import load_run_context
+
+ limit = min(max(1, limit), 100)
+ runs_dir = _host_RUNS_DIR()
+
+ if not runs_dir.exists():
+ return []
+
+ run_dirs = sorted(
+ [d for d in runs_dir.iterdir() if d.is_dir()],
+ key=lambda x: x.name,
+ reverse=True
+ )
+
+ results = []
+ for d in run_dirs[:limit]:
+ run_id = d.name
+
+ # Status from state.json or artifacts
+ status_val = "unknown"
+ state_file = _load_json_file(d / "state.json")
+ if state_file:
+ status_val = str(state_file.get("status") or "unknown").lower()
+ elif (d / "artifacts" / "equity.csv").exists():
+ status_val = "success"
+ elif (d / "review_report.json").exists():
+ status_val = "success"
+
+ # Parse created_at from run_id (YYYYMMDD_HHMMSS or run_YYYYMMDD_HHMMSS)
+ created_at = "Unknown"
+ if run_id.startswith("run_"):
+ parts = run_id.split('_')
+ if len(parts) >= 3:
+ d_str, t_str = parts[1], parts[2]
+ if len(d_str) == 8 and len(t_str) == 6:
+ created_at = f"{d_str[:4]}-{d_str[4:6]}-{d_str[6:8]} {t_str[:2]}:{t_str[2:4]}:{t_str[4:6]}"
+ elif "_" in run_id:
+ parts = run_id.split('_')
+ if len(parts) >= 2:
+ d_str, t_str = parts[0], parts[1]
+ if len(d_str) == 8 and len(t_str) == 6:
+ created_at = f"{d_str[:4]}-{d_str[4:6]}-{d_str[6:8]} {t_str[:2]}:{t_str[2:4]}:{t_str[4:6]}"
+
+ if created_at == "Unknown":
+ mtime = datetime.fromtimestamp(d.stat().st_mtime)
+ created_at = mtime.strftime("%Y-%m-%d %H:%M:%S")
+
+ prompt = None
+ req_file = d / "req.json"
+ planner_file = d / "planner_output.json"
+ if req_file.exists():
+ try:
+ req_data = json.loads(req_file.read_text(encoding="utf-8"))
+ prompt = req_data.get("prompt")
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ if not prompt and planner_file.exists():
+ try:
+ planner_data = json.loads(planner_file.read_text(encoding="utf-8"))
+ prompt = planner_data.get("user_goal") or planner_data.get("goal")
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ if not prompt:
+ prompt_file = d / "user_prompt.txt"
+ if prompt_file.exists():
+ prompt = prompt_file.read_text(encoding="utf-8").strip()
+
+ total_return = None
+ sharpe = None
+ metrics_file = d / "artifacts" / "metrics.csv"
+ if metrics_file.exists():
+ try:
+ with open(metrics_file, 'r', encoding='utf-8') as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ total_return = float(row.get('total_return', 0) or 0)
+ sharpe = float(row.get('sharpe', 0) or 0)
+ break
+ except (OSError, ValueError):
+ pass
+
+ run_context = load_run_context(d)
+ results.append(RunInfo(
+ run_id=run_id,
+ status=status_val,
+ created_at=created_at,
+ prompt=prompt or "Manual Analysis",
+ total_return=total_return,
+ sharpe=sharpe,
+ codes=run_context.get("codes") or [],
+ start_date=run_context.get("start_date"),
+ end_date=run_context.get("end_date"),
+ ))
+
+ return results
diff --cc agent/src/api/scheduled_routes.py
index 000000000,6ba2907da..8a55eed77
mode 000000,100644..100644
--- a/agent/src/api/scheduled_routes.py
+++ b/agent/src/api/scheduled_routes.py
@@@ -1,0 -1,241 +1,243 @@@
+ """Scheduled research HTTP routes.
+
+ Mounted by ``agent/api_server.py`` via ``register_scheduled_routes(app, ...)``.
+ """
+
+ from __future__ import annotations
+
+ import logging
+ import os
+ import sys as _sys
+ import time
+ import uuid
+ from typing import Any, Awaitable, Callable, Dict, List, Optional
+
+ from fastapi import Depends, FastAPI, HTTPException, Query, status
+ from pydantic import BaseModel, Field
+
+ logger = logging.getLogger(__name__)
+
+
+ # ---------------------------------------------------------------------------
+ # Constants
+ # ---------------------------------------------------------------------------
+
+ _SCHEDULED_RESEARCH_SCHEDULER_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"
+ _SCHEDULED_RESEARCH_TRUE_VALUES = {"1", "true", "yes", "on"}
+
+
+ # ---------------------------------------------------------------------------
+ # Module-level state
+ # ---------------------------------------------------------------------------
+
+ _scheduled_research_store: Any = None
+ _scheduled_research_executor: Any = None
+
+
+ def _scheduled_research_scheduler_enabled() -> bool:
+ """Return whether scheduled research execution is enabled."""
+ return (
+ os.getenv(_SCHEDULED_RESEARCH_SCHEDULER_ENV, "").strip().lower()
+ in _SCHEDULED_RESEARCH_TRUE_VALUES
+ )
+
+
+ def _get_scheduled_research_store():
+ """Return the singleton ScheduledResearchJobStore, creating it on first call."""
+ global _scheduled_research_store
+ if _scheduled_research_store is None:
+ from src.scheduled_research.store import ScheduledResearchJobStore
+
+ _scheduled_research_store = ScheduledResearchJobStore()
+ return _scheduled_research_store
+
+
+ async def _dispatch_scheduled_research_job(job) -> None:
+ """Enqueue one scheduled research job through the session runtime.
+
+ ``send_message`` queues the agent attempt and returns once accepted; it
+ does not wait for that agent run to reach a terminal status. The executor's
+ ``COMPLETED`` state for this dispatch path means "successfully enqueued."
+ """
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ svc = host._get_session_service()
+ if not svc:
+ raise RuntimeError("Session runtime not enabled")
+ # Pass a copy so the session runtime's internal config writes (e.g.
+ # include_shell_tools) do not mutate the persisted scheduled-run config.
++ job_config = dict(job.config)
++ job_config["governance_surface"] = "scheduler"
+ session = svc.create_session(
- title=f"scheduled-research:{job.id}", config=dict(job.config)
++ title=f"scheduled-research:{job.id}", config=job_config
+ )
+ logger.info(
+ "dispatching scheduled research job %s via session %s",
+ job.id,
+ session.session_id,
+ )
+ await svc.send_message(session.session_id, job.prompt)
+
+
+ def _get_scheduled_research_executor():
+ """Return the singleton scheduled research executor."""
+ global _scheduled_research_executor
+ if _scheduled_research_executor is None:
+ from src.scheduled_research.executor import ScheduledResearchExecutor
+
+ _scheduled_research_executor = ScheduledResearchExecutor(
+ _get_scheduled_research_store(),
+ _dispatch_scheduled_research_job,
+ enabled=_scheduled_research_scheduler_enabled(),
+ )
+ return _scheduled_research_executor
+
+
+ def _start_scheduled_research_executor() -> None:
+ """Start scheduled research execution when explicitly enabled."""
+ if not _scheduled_research_scheduler_enabled():
+ return
+ _get_scheduled_research_executor().start()
+
+
+ async def _stop_scheduled_research_executor() -> None:
+ """Stop scheduled research execution if it was started."""
+ executor = _scheduled_research_executor
+ if executor is not None:
+ await executor.stop()
+
+
+ # ---------------------------------------------------------------------------
+ # Pydantic models
+ # ---------------------------------------------------------------------------
+
+
+ class CreateScheduledRunRequest(BaseModel):
+ """Request body for POST /scheduled-runs."""
+
+ id: Optional[str] = Field(
+ None, description="Job id; auto-generated UUID when omitted"
+ )
+ prompt: str = Field(
+ ..., min_length=1, description="Research prompt or backtest description"
+ )
+ schedule: str = Field(
+ ..., min_length=1, description="Interval-ms or 5-field cron expression"
+ )
+ next_run_at: Optional[int] = Field(
+ None, description="Epoch-ms for next run; defaults to now"
+ )
+ config: Dict[str, Any] = Field(
+ default_factory=dict, description="Optional backtest parameters"
+ )
+
+
+ class ScheduledRunResponse(BaseModel):
+ """API response for a single scheduled job."""
+
+ id: str
+ prompt: str
+ schedule: str
+ next_run_at: int
+ status: str
+ created_at: int
+ config: Dict[str, Any] = Field(default_factory=dict)
+
+
+ # ---------------------------------------------------------------------------
+ # Registration
+ # ---------------------------------------------------------------------------
+
+ AuthDep = Callable[..., Awaitable[Any] | Any]
+
+
+ def register_scheduled_routes(
+ app: FastAPI,
+ require_auth: AuthDep | None = None,
+ ) -> None:
+ """Mount the scheduled routes onto ``app``.
+
+ Resolves ``require_auth`` from the host ``api_server`` module via
+ ``sys.modules`` when not passed explicitly.
+ """
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+
+ if host is None:
+ raise RuntimeError(
+ "register_scheduled_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ if require_auth is None:
+ require_auth = host.require_auth
+
+ def _host_validate_path_param(value: str, kind: str) -> None:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ h._validate_path_param(value, kind)
+
+ # --- Routes ---
+
+ @app.post(
+ "/scheduled-runs",
+ response_model=ScheduledRunResponse,
+ status_code=status.HTTP_201_CREATED,
+ dependencies=[Depends(require_auth)],
+ )
+ async def create_scheduled_run(
+ request: CreateScheduledRunRequest,
+ ) -> ScheduledRunResponse:
+ """Create (or replace) a scheduled research job.
+
+ The job is persisted immediately. No execution is triggered.
+ """
+ from src.scheduled_research.models import (
+ JobStatus,
+ ScheduledResearchJob,
+ validate_schedule,
+ )
+
+ try:
+ validate_schedule(request.schedule)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ now_ms = int(time.time() * 1000)
+ job = ScheduledResearchJob(
+ id=request.id or str(uuid.uuid4()),
+ prompt=request.prompt,
+ schedule=request.schedule,
+ next_run_at=request.next_run_at if request.next_run_at is not None else now_ms,
+ status=JobStatus.PENDING,
+ created_at=now_ms,
+ config=request.config,
+ )
+ _get_scheduled_research_store().upsert(job)
+ return ScheduledRunResponse(**job.to_dict())
+
+ @app.get(
+ "/scheduled-runs",
+ response_model=List[ScheduledRunResponse],
+ dependencies=[Depends(require_auth)],
+ )
+ async def list_scheduled_runs(
+ status_filter: Optional[str] = Query(None, alias="status"),
+ limit: int = Query(50, ge=1, le=200),
+ ) -> List[ScheduledRunResponse]:
+ """List scheduled research jobs, optionally filtered by status."""
+ jobs = _get_scheduled_research_store().list_jobs(
+ status=status_filter, limit=limit
+ )
+ return [ScheduledRunResponse(**j.to_dict()) for j in jobs]
+
+ @app.delete(
+ "/scheduled-runs/{job_id}",
+ status_code=status.HTTP_204_NO_CONTENT,
+ dependencies=[Depends(require_auth)],
+ )
+ async def delete_scheduled_run(job_id: str) -> None:
+ """Cancel (delete) a scheduled research job by id."""
+ _host_validate_path_param(job_id, "job_id")
+ removed = _get_scheduled_research_store().delete(job_id)
+ if not removed:
+ raise HTTPException(
+ status_code=404, detail=f"scheduled run {job_id} not found"
+ )
diff --cc agent/src/api/sessions_routes.py
index 000000000,00352dfec..3a9826ad0
mode 000000,100644..100644
--- a/agent/src/api/sessions_routes.py
+++ b/agent/src/api/sessions_routes.py
@@@ -1,0 -1,716 +1,721 @@@
+ """Session and goal HTTP routes.
+
+ Mounted by ``agent/api_server.py`` via ``register_sessions_routes(app)``.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import re
+ from typing import Any, Dict, List, Optional
+
+ from fastapi import Depends, FastAPI, HTTPException, Query, Request, status
+ from fastapi.responses import StreamingResponse
+ from pydantic import BaseModel, Field
+
+ logger = logging.getLogger(__name__)
+
+
+ # ============================================================================
+ # Pydantic Models
+ # ============================================================================
+
+ class CreateSessionRequest(BaseModel):
+ """Create session request body."""
+ title: str = Field("", description="Session title")
+ config: Optional[Dict[str, Any]] = Field(None, description="Session config")
+
+
+ class SessionResponse(BaseModel):
+ """Session record."""
+ session_id: str
+ title: str
+ status: str
+ created_at: str
+ updated_at: str
+ last_attempt_id: Optional[str] = None
+
+
+ class SendMessageRequest(BaseModel):
+ """Send chat message: natural-language strategy description."""
+ content: str = Field(..., description="Natural language strategy description", min_length=1, max_length=5000)
+
+
+ class MessageResponse(BaseModel):
+ """Stored chat message."""
+ message_id: str
+ session_id: str
+ role: str
+ content: str
+ created_at: str
+ linked_attempt_id: Optional[str] = None
+ metadata: Optional[Dict[str, Any]] = None
+
+
+ class CreateGoalRequest(BaseModel):
+ """Create or replace a finance research goal."""
+
+ objective: str = Field(..., min_length=1, max_length=5000)
+ criteria: List[str] = Field(default_factory=list)
+ ui_summary: str = ""
+ protocol: str = "thesis_review"
+ risk_tier: str = "research_general"
+ token_budget: Optional[int] = Field(None, ge=1)
+ turn_budget: Optional[int] = Field(None, ge=1)
+ time_budget_seconds: Optional[int] = Field(None, ge=1)
+
+
+ class UpdateGoalRequest(BaseModel):
+ """Edit mutable finance research goal fields."""
+
+ goal_id: str = Field(..., min_length=1)
+ expected_goal_id: str = Field(..., min_length=1)
+ objective: Optional[str] = Field(None, min_length=1, max_length=5000)
+ ui_summary: Optional[str] = Field(None, max_length=500)
+
+
+ class AddGoalEvidenceRequest(BaseModel):
+ """Append evidence to a finance research goal."""
+
+ goal_id: str = Field(..., min_length=1)
+ expected_goal_id: str = Field(..., min_length=1)
+ text: str = Field(..., min_length=1, max_length=10000)
+ criterion_id: Optional[str] = None
+ claim_id: Optional[str] = None
+ evidence_type: str = "evidence"
+ tool_call_id: Optional[str] = None
+ run_id: Optional[str] = None
+ source_provider: Optional[str] = None
+ source_type: Optional[str] = None
+ source_uri: Optional[str] = None
+ symbol_universe: List[str] = Field(default_factory=list)
+ benchmark: List[str] = Field(default_factory=list)
+ timeframe: Optional[str] = None
+ method: Optional[str] = None
+ assumptions: Dict[str, Any] = Field(default_factory=dict)
+ artifact_path: Optional[str] = None
+ artifact_hash: Optional[str] = None
+ data_as_of: Optional[str] = None
+ confidence: Optional[str] = None
+ caveat: Optional[str] = None
+ contradicts_claim_ids: List[str] = Field(default_factory=list)
+
+
+ class GoalSnapshotResponse(BaseModel):
+ """Finance research goal snapshot."""
+
+ goal: Dict[str, Any]
+ claims: List[Dict[str, Any]]
+ criteria: List[Dict[str, Any]]
+ evidence: List[Dict[str, Any]]
+ evidence_count: int = 0
+
+
+ class AddGoalEvidenceResponse(BaseModel):
+ """Response after appending goal evidence."""
+
+ evidence: Dict[str, Any]
+ snapshot: GoalSnapshotResponse
+
+
+ class GoalAuditRowRequest(BaseModel):
+ """One criterion row for goal status audits."""
+
+ criterion_id: str = Field(..., min_length=1)
+ result: str = Field(..., min_length=1)
+ evidence_ids: List[str] = Field(default_factory=list)
+ notes: str = ""
+
+
+ class UpdateGoalStatusRequest(BaseModel):
+ """Update a finance research goal status."""
+
+ goal_id: str = Field(..., min_length=1)
+ expected_goal_id: str = Field(..., min_length=1)
+ status: str = Field(..., min_length=1)
+ audit: List[GoalAuditRowRequest] = Field(default_factory=list)
+ recap: Optional[str] = None
+
+
+ class UpdateGoalStatusResponse(BaseModel):
+ """Response after changing a goal status."""
+
+ goal: Dict[str, Any]
+ snapshot: GoalSnapshotResponse
+
+
+ class UpdateGoalResponse(BaseModel):
+ """Response after editing a goal."""
+
+ goal: Dict[str, Any]
+ snapshot: GoalSnapshotResponse
+
+
+ class UpdateSessionRequest(BaseModel):
+ """Session update fields."""
+ title: Optional[str] = None
+
+
+ # ============================================================================
+ # State variables
+ # ============================================================================
+
+ _goal_store = None
+
+
+ # ============================================================================
+ # Helper Functions
+ # ============================================================================
+
+ def _get_goal_store():
+ """Return the shared finance goal store."""
+ global _goal_store
+ if _goal_store is None:
+ from src.goal import GoalStore
+
+ _goal_store = GoalStore()
+ return _goal_store
+
+ # ============================================================================
+ # SSE frame helpers for session events (module-level for re-export)
+ # ============================================================================
+
+ _PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
+ _PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-f]{32})"')
+
+
+ def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
+ """Reload a persisted mandate proposal by id, broker-agnostic."""
+ try:
+ from src.live.paths import live_root
+
+ for proposal_path in live_root().glob(f"*/proposals/{proposal_id}.json"):
+ try:
+ data = json.loads(proposal_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if isinstance(data, dict) and data.get("type") == "mandate.proposal":
+ return data
+ except Exception: # pragma: no cover - relay must never break the stream
+ logger.debug("mandate.proposal reload failed for %s", proposal_id, exc_info=True)
+ return None
+
+
+ def _mandate_proposal_frame_from_tool_result(event: Any) -> Optional[str]:
+ """Build a mandate.proposal SSE frame from a propose-tool tool_result."""
+ data = getattr(event, "data", None)
+ if getattr(event, "event_type", None) != "tool_result" or not isinstance(data, dict):
+ return None
+ if data.get("tool") != _PROPOSAL_TOOL_NAME or data.get("status") != "ok":
+ return None
+ match = _PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
+ if not match:
+ return None
+ proposal = _load_full_proposal(match.group(1))
+ if proposal is None:
+ return None
+
+ from src.session.events import SSEEvent
+
+ frame = SSEEvent(
+ event_type="mandate.proposal",
+ data=proposal,
+ session_id=getattr(event, "session_id", "") or "",
+ )
+ return frame.to_sse()
+
+
+ _LIVE_ACTION_ID_RE = re.compile(r'"audit_id"\s*:\s*"(la_[0-9a-zA-Z]+)"')
+
+
+ def _load_live_action_record(audit_id: str) -> Optional[Dict[str, Any]]:
+ """Reload a redacted live-action record from the ledger by audit_id."""
+ try:
+ from src.live.paths import live_root
+
+ ledger = live_root() / "audit.jsonl"
+ if not ledger.exists():
+ return None
+ for line in reversed(ledger.read_text(encoding="utf-8").splitlines()):
+ if audit_id not in line:
+ continue
+ try:
+ record = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(record, dict) and record.get("audit_id") == audit_id:
+ return record
+ except Exception: # pragma: no cover - relay must never break the stream
+ logger.debug("live.action reload failed for %s", audit_id, exc_info=True)
+ return None
+
+
+ def _live_action_frame_from_tool_result(event: Any) -> Optional[str]:
+ """Build a live.action SSE frame from an order-guard tool_result."""
+ data = getattr(event, "data", None)
+ if getattr(event, "event_type", None) != "tool_result" or not isinstance(data, dict):
+ return None
+ preview = str(data.get("preview") or "")
+ if '"live_action"' not in preview:
+ return None
+ match = _LIVE_ACTION_ID_RE.search(preview)
+ if not match:
+ return None
+ record = _load_live_action_record(match.group(1))
+ if record is None:
+ return None
+
+ from src.session.events import SSEEvent
+
+ frame = SSEEvent(
+ event_type="live.action",
+ data=record,
+ session_id=getattr(event, "session_id", "") or "",
+ )
+ return frame.to_sse()
+
+
+
+ # ============================================================================
+ # Registration
+ # ============================================================================
+
+ def register_sessions_routes(app: FastAPI) -> None:
+ """Mount the session/goal routes onto ``app``.
+
+ Resolves shared dependencies from the host ``api_server`` module via
+ ``sys.modules``.
+ """
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host is None:
+ raise RuntimeError(
+ "register_sessions_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ # Auth dependencies
+ require_auth = host.require_auth
+ require_event_stream_auth = host.require_event_stream_auth
+
+ # Late-access closures for shared host symbols (monkeypatch-safe)
+ def _host_get_session_service():
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._get_session_service()
+
+ def _host_validate_path_param(value: str, kind: str) -> None:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._validate_path_param(value, kind)
+
+ def _host_shell_tools_enabled_for_request(request: Request) -> bool:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._shell_tools_enabled_for_request(request)
+
++ def _host_governance_surface_for_request(request: Request) -> str:
++ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
++ return "local_api" if h._is_local_client(request) else "remote_api"
++
+ def _get_existing_session_or_404(session_id: str):
+ """Return (service, session) or raise 404."""
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ session = svc.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
+ return svc, session
+
+ # -----------------------------------------------------------------------
+ # Session CRUD routes
+ # -----------------------------------------------------------------------
+
+ @app.post("/sessions", response_model=SessionResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_auth)])
+ async def create_session(request: CreateSessionRequest):
+ """Create a chat session."""
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ session = svc.create_session(title=request.title, config=request.config)
+ return SessionResponse(
+ session_id=session.session_id,
+ title=session.title,
+ status=session.status.value,
+ created_at=session.created_at,
+ updated_at=session.updated_at,
+ last_attempt_id=session.last_attempt_id,
+ )
+
+ @app.get("/sessions", response_model=List[SessionResponse], dependencies=[Depends(require_auth)])
+ async def list_sessions(limit: int = Query(50, ge=1, le=200)):
+ """List sessions."""
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ sessions = svc.list_sessions(limit=limit)
+ return [
+ SessionResponse(
+ session_id=s.session_id,
+ title=s.title,
+ status=s.status.value,
+ created_at=s.created_at,
+ updated_at=s.updated_at,
+ last_attempt_id=s.last_attempt_id,
+ )
+ for s in sessions
+ ]
+
+ @app.get("/sessions/{session_id}", response_model=SessionResponse, dependencies=[Depends(require_auth)])
+ async def get_session(session_id: str):
+ """Get one session by id."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ session = svc.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
+ return SessionResponse(
+ session_id=session.session_id,
+ title=session.title,
+ status=session.status.value,
+ created_at=session.created_at,
+ updated_at=session.updated_at,
+ last_attempt_id=session.last_attempt_id,
+ )
+
+ # -----------------------------------------------------------------------
+ # Goal sub-group routes
+ # -----------------------------------------------------------------------
+
+ @app.post(
+ "/sessions/{session_id}/goal",
+ response_model=GoalSnapshotResponse,
+ status_code=status.HTTP_201_CREATED,
+ dependencies=[Depends(require_auth)],
+ )
+ async def create_session_goal(session_id: str, req: CreateGoalRequest):
+ """Create or replace the current finance research goal for a session."""
+ _host_validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from src.goal import RiskTier
+ from src.goal.context import default_goal_criteria
+
+ criteria = [item.strip() for item in req.criteria if item.strip()]
+ if not criteria:
+ criteria = default_goal_criteria()
+ try:
+ risk_tier = RiskTier(req.risk_tier)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=f"invalid risk_tier: {req.risk_tier}") from exc
+ if risk_tier is RiskTier.LIVE_TRADING_OR_EXECUTION:
+ raise HTTPException(status_code=400, detail="live trading or execution goals are not supported")
+
+ goal_store = _get_goal_store()
+ try:
+ goal = goal_store.replace_goal(
+ session_id=session_id,
+ objective=req.objective,
+ criteria=criteria,
+ ui_summary=req.ui_summary,
+ source="api",
+ protocol=req.protocol,
+ risk_tier=risk_tier,
+ token_budget=req.token_budget,
+ turn_budget=req.turn_budget,
+ time_budget_seconds=req.time_budget_seconds,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal created but could not be reloaded")
+ svc.event_bus.emit(session_id, "goal.created", {"goal": snapshot["goal"]})
+ return snapshot
+
+ @app.get(
+ "/sessions/{session_id}/goal",
+ response_model=GoalSnapshotResponse,
+ dependencies=[Depends(require_auth)],
+ )
+ async def get_session_goal(session_id: str):
+ """Return the current finance research goal snapshot for a session."""
+ _host_validate_path_param(session_id, "session_id")
+ _get_existing_session_or_404(session_id)
+ snapshot = _get_goal_store().get_current_snapshot(session_id)
+ if snapshot is None:
+ raise HTTPException(status_code=404, detail="No current goal")
+ return snapshot
+
+ @app.patch(
+ "/sessions/{session_id}/goal",
+ response_model=UpdateGoalResponse,
+ dependencies=[Depends(require_auth)],
+ )
+ async def update_session_goal(session_id: str, req: UpdateGoalRequest):
+ """Edit the current finance research goal without replacing the session."""
+ _host_validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from src.goal import StaleGoalError
+
+ if req.objective is None and req.ui_summary is None:
+ raise HTTPException(status_code=400, detail="objective or ui_summary is required")
+
+ goal_store = _get_goal_store()
+ try:
+ goal = goal_store.update_goal(
+ session_id=session_id,
+ goal_id=req.goal_id,
+ expected_goal_id=req.expected_goal_id,
+ objective=req.objective,
+ ui_summary=req.ui_summary,
+ )
+ except StaleGoalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")
+ svc.event_bus.emit(session_id, "goal.updated", {"goal": snapshot["goal"], "snapshot": snapshot})
+ return {"goal": snapshot["goal"], "snapshot": snapshot}
+
+ @app.post(
+ "/sessions/{session_id}/goal/evidence",
+ response_model=AddGoalEvidenceResponse,
+ status_code=status.HTTP_201_CREATED,
+ dependencies=[Depends(require_auth)],
+ )
+ async def add_session_goal_evidence(session_id: str, req: AddGoalEvidenceRequest):
+ """Append traceable evidence to the current finance research goal."""
+ _host_validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from dataclasses import asdict
+ from src.goal import EvidenceInput, StaleGoalError
+
+ goal_store = _get_goal_store()
+ try:
+ evidence = goal_store.append_evidence(
+ session_id=session_id,
+ goal_id=req.goal_id,
+ expected_goal_id=req.expected_goal_id,
+ evidence=EvidenceInput(
+ criterion_id=req.criterion_id,
+ claim_id=req.claim_id,
+ evidence_type=req.evidence_type,
+ text=req.text,
+ tool_call_id=req.tool_call_id,
+ run_id=req.run_id,
+ source_provider=req.source_provider,
+ source_type=req.source_type,
+ source_uri=req.source_uri,
+ symbol_universe=req.symbol_universe,
+ benchmark=req.benchmark,
+ timeframe=req.timeframe,
+ method=req.method,
+ assumptions=req.assumptions,
+ artifact_path=req.artifact_path,
+ artifact_hash=req.artifact_hash,
+ data_as_of=req.data_as_of,
+ confidence=req.confidence,
+ caveat=req.caveat,
+ contradicts_claim_ids=req.contradicts_claim_ids,
+ ),
+ )
+ except StaleGoalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ snapshot = goal_store.get_goal_snapshot(req.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")
+ svc.event_bus.emit(
+ session_id,
+ "goal.evidence",
+ {"evidence": asdict(evidence), "goal_id": req.goal_id},
+ )
+ return {"evidence": asdict(evidence), "snapshot": snapshot}
+
+ @app.patch(
+ "/sessions/{session_id}/goal/status",
+ response_model=UpdateGoalStatusResponse,
+ dependencies=[Depends(require_auth)],
+ )
+ async def update_session_goal_status(session_id: str, req: UpdateGoalStatusRequest):
+ """Update the current finance research goal status."""
+ _host_validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from src.goal import AuditRow, GoalStatus, StaleGoalError
+
+ try:
+ next_status = GoalStatus(req.status)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=f"invalid goal status: {req.status}") from exc
+
+ goal_store = _get_goal_store()
+ try:
+ goal = goal_store.update_status(
+ session_id=session_id,
+ goal_id=req.goal_id,
+ expected_goal_id=req.expected_goal_id,
+ status=next_status,
+ audit=[
+ AuditRow(
+ criterion_id=row.criterion_id,
+ result=row.result,
+ evidence_ids=row.evidence_ids,
+ notes=row.notes,
+ )
+ for row in req.audit
+ ],
+ recap=req.recap,
+ )
+ except StaleGoalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")
+ svc.event_bus.emit(session_id, "goal.updated", {"goal": snapshot["goal"], "snapshot": snapshot})
+ return {"goal": snapshot["goal"], "snapshot": snapshot}
+
+ # -----------------------------------------------------------------------
+ # Session action routes
+ # -----------------------------------------------------------------------
+
+ @app.delete("/sessions/{session_id}", dependencies=[Depends(require_auth)])
+ async def delete_session(session_id: str):
+ """Delete a session."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ deleted = svc.delete_session(session_id)
+ if not deleted:
+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
+ _get_goal_store().delete_session_goals(session_id)
+ return {"status": "deleted", "session_id": session_id}
+
+ @app.patch("/sessions/{session_id}", dependencies=[Depends(require_auth)])
+ async def update_session(session_id: str, req: UpdateSessionRequest):
+ """Update session fields (e.g. title)."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ session = svc.store.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
+ if req.title is not None:
+ session.title = req.title
+ from datetime import datetime
+ session.updated_at = datetime.now().isoformat()
+ svc.store.update_session(session)
+ return {"status": "updated", "session_id": session_id}
+
+ @app.post("/sessions/{session_id}/messages", dependencies=[Depends(require_auth)])
+ async def send_message(session_id: str, payload: SendMessageRequest, http_request: Request):
+ """Send a user message and start the agent loop (natural language strategy)."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ try:
+ result = await svc.send_message(
+ session_id=session_id,
+ content=payload.content,
+ include_shell_tools=_host_shell_tools_enabled_for_request(http_request),
++ governance_surface=_host_governance_surface_for_request(http_request),
+ )
+ return result
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc))
+
+ @app.post("/sessions/{session_id}/cancel", dependencies=[Depends(require_auth)])
+ async def cancel_session(session_id: str):
+ """Cancel the in-flight agent loop for this session."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ cancelled = svc.cancel_current(session_id)
+ if not cancelled:
+ return {"status": "no_active_loop"}
+ return {"status": "cancelled"}
+
+ @app.get("/sessions/{session_id}/messages", response_model=List[MessageResponse], dependencies=[Depends(require_auth)])
+ async def get_messages(session_id: str, limit: int = Query(100, ge=1, le=1000)):
+ """List messages for a session."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ messages = svc.get_messages(session_id, limit=limit)
+ return [
+ MessageResponse(
+ message_id=m.message_id,
+ session_id=m.session_id,
+ role=m.role,
+ content=m.content,
+ created_at=m.created_at,
+ linked_attempt_id=m.linked_attempt_id,
+ metadata=m.metadata if m.metadata else None,
+ )
+ for m in messages
+ ]
+
+ @app.get("/sessions/{session_id}/events", dependencies=[Depends(require_event_stream_auth)])
+ async def session_events(
+ session_id: str,
+ request: Request,
+ last_event_id: Optional[str] = Query(None, alias="Last-Event-ID"),
+ replay: Optional[str] = Query(None),
+ ):
+ """SSE stream for agent events."""
+ _host_validate_path_param(session_id, "session_id")
+ svc = _host_get_session_service()
+ if not svc:
+ raise HTTPException(status_code=501, detail="Session runtime not enabled")
+ session = svc.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
+
+ header_id = request.headers.get("Last-Event-ID")
+ event_id = header_id or last_event_id
+ replay_active = (replay or "").lower() == "active"
+ replay_all = False
+ if replay_active and not event_id and session.last_attempt_id:
+ attempt = svc.store.get_attempt(session_id, session.last_attempt_id)
+ attempt_status = getattr(attempt.status, "value", attempt.status) if attempt else None
+ replay_all = attempt_status == "running"
+
+ async def event_generator():
+ async for event in svc.event_bus.subscribe(
+ session_id,
+ last_event_id=event_id,
+ replay_all=replay_all,
+ ):
+ if await request.is_disconnected():
+ break
+ yield event.to_sse()
+ relayed = _mandate_proposal_frame_from_tool_result(event)
+ if relayed is not None:
+ yield relayed
+ live_action = _live_action_frame_from_tool_result(event)
+ if live_action is not None:
+ yield live_action
+
+ return StreamingResponse(
+ event_generator(),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "Connection": "keep-alive",
+ "X-Accel-Buffering": "no",
+ },
+ )