File size: 1,777 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Append-only JSONL events with bounded, JSON-safe fields."""

from __future__ import annotations

import json
import time
import uuid
from pathlib import Path
from typing import Any

_MAX_FIELD_CHARS = 2000
_MAX_COLLECTION_ITEMS = 100


def _sanitize(value: Any) -> Any:
    if value is None or isinstance(value, (bool, int, float)):
        return value
    if isinstance(value, str):
        if len(value) <= _MAX_FIELD_CHARS:
            return value
        omitted = len(value) - _MAX_FIELD_CHARS
        return value[:_MAX_FIELD_CHARS] + f"...[clipped {omitted} chars]"
    if isinstance(value, dict):
        return {
            str(key): _sanitize(item)
            for key, item in list(value.items())[:_MAX_COLLECTION_ITEMS]
        }
    if isinstance(value, (list, tuple)):
        return [_sanitize(item) for item in value[:_MAX_COLLECTION_ITEMS]]
    return _sanitize(repr(value))


class EventLogger:
    def __init__(self, workspace_root: Path, session_id: str | None = None) -> None:
        self.session_id = session_id or time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:8]
        sessions_dir = workspace_root / ".nano_agent" / "sessions"
        sessions_dir.mkdir(parents=True, exist_ok=True)
        self.path = sessions_dir / f"{self.session_id}.jsonl"

    def log(self, event_type: str, **fields: Any) -> None:
        record = {"ts": time.time(), "type": event_type}
        record.update({key: _sanitize(value) for key, value in fields.items()})
        with self.path.open("a", encoding="utf-8") as stream:
            stream.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")


class NullEventLogger:
    session_id = "null"
    path = None

    def log(self, event_type: str, **fields: Any) -> None:
        return None