AQIT 0.1.0
Loading...
Searching...
No Matches
session_memory_store.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2# This file is part of the Aquin Engine. Unauthorized copying, modification,
3# distribution, or use of this file, via any medium, is strictly prohibited.
4# Proprietary and confidential. See LICENSE for terms.
5
6"""Session memory — local disk + cloud (with event replay fallback)."""
7from __future__ import annotations
8
9import json
10from pathlib import Path
11from typing import Any
12
13_MEMORY_DIR = Path.home() / ".aquin" / "session_memory"
14
15
16def _memory_path(session_id: str) -> Path:
17 safe = session_id.replace("/", "_")
18 return _MEMORY_DIR / f"{safe}.json"
19
21def load_local_memory(session_id: str) -> dict[str, Any]:
22 if not session_id:
23 return {}
24 path = _memory_path(session_id)
25 if not path.is_file():
26 return {}
27 try:
28 data = json.loads(path.read_text(encoding="utf-8"))
29 return data if isinstance(data, dict) else {}
30 except Exception:
31 return {}
32
33
34def save_local_memory(session_id: str, memory: dict[str, Any]) -> None:
35 if not session_id:
36 return
37 _MEMORY_DIR.mkdir(parents=True, exist_ok=True)
38 _memory_path(session_id).write_text(
39 json.dumps(memory, ensure_ascii=False, default=str),
40 encoding="utf-8",
41 )
42
43
44def patch_local_memory(session_id: str, key: str, value: Any) -> dict[str, Any]:
45 mem = load_local_memory(session_id)
46 mem[key] = value
47 save_local_memory(session_id, mem)
48 return mem
49
50
51def memory_from_sync_events(events: list[Any]) -> dict[str, Any]:
52 """Replay session.meta memory patches from stored sync events."""
53 mem: dict[str, Any] = {}
54 for ev in events:
55 if not isinstance(ev, dict):
56 continue
57 event_type = ev.get("event_type") or ev.get("type")
58 if event_type != "session.meta":
59 continue
60 payload = ev.get("payload") or {}
61 patch = payload.get("patch") if isinstance(payload, dict) else {}
62 if not isinstance(patch, dict):
63 continue
64 chunk = patch.get("memory")
65 if isinstance(chunk, dict):
66 mem.update(chunk)
67 return mem
None save_local_memory(str session_id, dict[str, Any] memory)
dict[str, Any] patch_local_memory(str session_id, str key, Any value)
dict[str, Any] memory_from_sync_events(list[Any] events)
dict[str, Any] load_local_memory(str session_id)