from __future__ import annotations import json import os from datetime import UTC, datetime from pathlib import Path from typing import Any LOG_FILES = { "mcp": Path("logs/mcp_calls.jsonl"), "rest": Path("logs/rest_calls.jsonl"), "gui_test": Path("logs/gui_test_calls.jsonl"), } LOG_PROTOCOL_ALIASES = { "monitor": "gui_test", } ACTIVE_CALLS_PATH = Path("runs/active_calls.json") def _utc_now() -> str: return datetime.now(UTC).isoformat() def write_call_log(entry: dict[str, Any], protocol: str) -> None: normalized_protocol = LOG_PROTOCOL_ALIASES.get(protocol, protocol) path = LOG_FILES.get(normalized_protocol, LOG_FILES["rest"]) path.parent.mkdir(parents=True, exist_ok=True) sanitized = { "timestamp": _utc_now(), "protocol": normalized_protocol, **entry, } with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(sanitized, ensure_ascii=False) + "\n") def _read_active_calls() -> dict[str, dict[str, Any]]: if not ACTIVE_CALLS_PATH.exists(): return {} try: return json.loads(ACTIVE_CALLS_PATH.read_text(encoding="utf-8")) except json.JSONDecodeError: return {} def register_active_call(call_id: str, entry: dict[str, Any]) -> None: ACTIVE_CALLS_PATH.parent.mkdir(parents=True, exist_ok=True) active_calls = _read_active_calls() active_calls[call_id] = { "call_id": call_id, "started_at": _utc_now(), "pid": os.getpid(), **entry, } ACTIVE_CALLS_PATH.write_text(json.dumps(active_calls, indent=2), encoding="utf-8") def unregister_active_call(call_id: str) -> None: active_calls = _read_active_calls() active_calls.pop(call_id, None) ACTIVE_CALLS_PATH.parent.mkdir(parents=True, exist_ok=True) ACTIVE_CALLS_PATH.write_text(json.dumps(active_calls, indent=2), encoding="utf-8") def read_active_calls() -> list[dict[str, Any]]: return sorted(_read_active_calls().values(), key=lambda entry: entry.get("started_at", ""), reverse=True) def clear_active_calls() -> None: ACTIVE_CALLS_PATH.parent.mkdir(parents=True, exist_ok=True) ACTIVE_CALLS_PATH.write_text("{}", encoding="utf-8") def read_recent_logs(limit: int = 50) -> dict[str, list[dict[str, Any]]]: result: dict[str, list[dict[str, Any]]] = {} for name, path in { "mcp": LOG_FILES["mcp"], "gui_test": LOG_FILES["gui_test"], "rest": LOG_FILES["rest"], }.items(): if not path.exists(): result[name] = [] continue parsed_lines = [] for line in path.read_text(encoding="utf-8").splitlines()[-limit:]: if not line.strip(): continue try: parsed_lines.append(json.loads(line)) except json.JSONDecodeError: parsed_lines.append({"parse_error": "Invalid JSON log line", "raw": line[:500]}) result[name] = parsed_lines return result