46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .output import redact, short_id
|
|
|
|
|
|
def trace_enabled() -> bool:
|
|
return os.environ.get("MEMORY_GATEWAY_PLUGIN_TRACE_HOOKS", "").strip().lower() in {"1", "true", "yes", "on"}
|
|
|
|
|
|
def trace_path() -> Path:
|
|
return Path(__file__).resolve().parents[1] / ".tmp" / "hook_trace.log"
|
|
|
|
|
|
def trace_hook(
|
|
hook_name: str,
|
|
*,
|
|
session_id: str = "",
|
|
gateway_action: str = "",
|
|
gateway_called: bool = False,
|
|
ok: bool | None = None,
|
|
audit_delta: int | None = None,
|
|
reason: str = "",
|
|
) -> None:
|
|
if not trace_enabled():
|
|
return
|
|
path = trace_path()
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
payload: dict[str, Any] = {
|
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
"hook": hook_name,
|
|
"session_id": short_id(session_id),
|
|
"gateway_action": gateway_action,
|
|
"gateway_called": gateway_called,
|
|
"ok": ok,
|
|
"audit_delta": audit_delta,
|
|
"reason": reason[:160] if reason else "",
|
|
}
|
|
with path.open("a", encoding="utf-8") as handle:
|
|
handle.write(json.dumps(redact(payload), ensure_ascii=False, default=str) + "\n")
|