Репозитории /
AiRouter /
airouter/storage.py
storage.py
| 1 | """Per-session persistence on disk. |
| 2 | |
| 3 | Layout: |
| 4 | .airouter/sessions/<id>/ |
| 5 | session.json metadata, main usage, worker metadata |
| 6 | main.messages.json full lead context |
| 7 | events.jsonl event log (no token deltas) |
| 8 | workers/w1/messages.json |
| 9 | workers/w1/meta.json |
| 10 | workers/w1/task.md |
| 11 | workers/w1/report.md |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import json |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | from typing import Any |
| 20 | |
| 21 | from .utils import ( |
| 22 | append_jsonl, |
| 23 | atomic_write_json, |
| 24 | atomic_write_text, |
| 25 | new_session_id, |
| 26 | read_json, |
| 27 | ) |
| 28 | |
| 29 | |
| 30 | class StorageError(RuntimeError): |
| 31 | pass |
| 32 | |
| 33 | |
| 34 | class SessionStore: |
| 35 | def __init__(self, sessions_root: Path, session_id: str) -> None: |
| 36 | self.sessions_root = sessions_root |
| 37 | self.id = session_id |
| 38 | self.dir = sessions_root / session_id |
| 39 | self.session_file = self.dir / "session.json" |
| 40 | self.main_messages_file = self.dir / "main.messages.json" |
| 41 | self.events_file = self.dir / "events.jsonl" |
| 42 | self.workers_dir = self.dir / "workers" |
| 43 | |
| 44 | def ensure(self) -> None: |
| 45 | self.dir.mkdir(parents=True, exist_ok=True) |
| 46 | self.workers_dir.mkdir(parents=True, exist_ok=True) |
| 47 | |
| 48 | @classmethod |
| 49 | def create(cls, sessions_root: Path) -> SessionStore: |
| 50 | for _ in range(20): |
| 51 | store = cls(sessions_root, new_session_id()) |
| 52 | if not store.dir.exists(): |
| 53 | store.ensure() |
| 54 | return store |
| 55 | raise StorageError("Не удалось создать уникальный id сессии") |
| 56 | |
| 57 | @classmethod |
| 58 | def open(cls, sessions_root: Path, session_id: str) -> SessionStore: |
| 59 | if not session_id or Path(session_id).name != session_id or session_id in {".", ".."}: |
| 60 | raise StorageError(f"Некорректный id сессии: {session_id!r}") |
| 61 | store = cls(sessions_root, session_id) |
| 62 | if not store.session_file.is_file(): |
| 63 | raise StorageError(f"Сессия не найдена: {session_id}") |
| 64 | return store |
| 65 | |
| 66 | @classmethod |
| 67 | def latest(cls, sessions_root: Path) -> SessionStore | None: |
| 68 | if not sessions_root.is_dir(): |
| 69 | return None |
| 70 | candidates: list[tuple[float, Path]] = [] |
| 71 | for child in sessions_root.iterdir(): |
| 72 | if not child.is_dir(): |
| 73 | continue |
| 74 | meta = read_json(child / "session.json", {}) or {} |
| 75 | updated = float(meta.get("updated_at") or 0) |
| 76 | if not updated: |
| 77 | try: |
| 78 | updated = child.stat().st_mtime |
| 79 | except OSError: |
| 80 | updated = 0 |
| 81 | candidates.append((updated, child)) |
| 82 | if not candidates: |
| 83 | return None |
| 84 | candidates.sort(key=lambda item: item[0], reverse=True) |
| 85 | return cls(sessions_root, candidates[0][1].name) |
| 86 | |
| 87 | @classmethod |
| 88 | def list(cls, sessions_root: Path) -> list[dict[str, Any]]: |
| 89 | out: list[dict[str, Any]] = [] |
| 90 | if not sessions_root.is_dir(): |
| 91 | return out |
| 92 | for child in sessions_root.iterdir(): |
| 93 | meta = read_json(child / "session.json") |
| 94 | if not isinstance(meta, dict): |
| 95 | continue |
| 96 | main = read_json(child / "main.messages.json", []) or [] |
| 97 | out.append( |
| 98 | { |
| 99 | "id": meta.get("id", child.name), |
| 100 | "updated_at": meta.get("updated_at", 0), |
| 101 | "cwd": meta.get("cwd", ""), |
| 102 | "model": meta.get("model", ""), |
| 103 | "messages": len(main) if isinstance(main, list) else 0, |
| 104 | "goal": meta.get("goal", ""), |
| 105 | } |
| 106 | ) |
| 107 | out.sort(key=lambda item: item.get("updated_at", 0), reverse=True) |
| 108 | return out |
| 109 | |
| 110 | def save_meta(self, meta: dict[str, Any]) -> None: |
| 111 | self.ensure() |
| 112 | atomic_write_json(self.session_file, meta) |
| 113 | |
| 114 | def load_meta(self) -> dict[str, Any]: |
| 115 | meta = read_json(self.session_file) |
| 116 | if not isinstance(meta, dict): |
| 117 | raise StorageError(f"Повреждён session.json: {self.session_file}") |
| 118 | return meta |
| 119 | |
| 120 | def save_main_messages(self, messages: list[dict[str, Any]]) -> None: |
| 121 | self.ensure() |
| 122 | atomic_write_json(self.main_messages_file, messages) |
| 123 | |
| 124 | def load_main_messages(self) -> list[dict[str, Any]]: |
| 125 | data = read_json(self.main_messages_file, []) |
| 126 | return data if isinstance(data, list) else [] |
| 127 | |
| 128 | def log_event(self, payload: dict[str, Any]) -> None: |
| 129 | self.ensure() |
| 130 | append_jsonl(self.events_file, payload) |
| 131 | |
| 132 | def worker_dir(self, worker_id: str) -> Path: |
| 133 | path = self.workers_dir / worker_id |
| 134 | path.mkdir(parents=True, exist_ok=True) |
| 135 | return path |
| 136 | |
| 137 | def save_worker( |
| 138 | self, |
| 139 | worker_id: str, |
| 140 | meta: dict[str, Any], |
| 141 | messages: list[dict[str, Any]], |
| 142 | task: str | None = None, |
| 143 | report: str | None = None, |
| 144 | ) -> None: |
| 145 | directory = self.worker_dir(worker_id) |
| 146 | atomic_write_json(directory / "meta.json", meta) |
| 147 | atomic_write_json(directory / "messages.json", messages) |
| 148 | if task is not None: |
| 149 | atomic_write_text(directory / "task.md", task) |
| 150 | if report is not None: |
| 151 | atomic_write_text(directory / "report.md", report) |
| 152 | |
| 153 | def load_worker_messages(self, worker_id: str) -> list[dict[str, Any]]: |
| 154 | data = read_json(self.worker_dir(worker_id) / "messages.json", []) |
| 155 | return data if isinstance(data, list) else [] |
| 156 | |
| 157 | def load_worker_meta(self, worker_id: str) -> dict[str, Any]: |
| 158 | data = read_json(self.worker_dir(worker_id) / "meta.json", {}) |
| 159 | return data if isinstance(data, dict) else {} |
| 160 | |
| 161 | def touch(self) -> None: |
| 162 | now = time.time() |
| 163 | try: |
| 164 | import os |
| 165 | |
| 166 | os.utime(self.dir, (now, now)) |
| 167 | except OSError: |
| 168 | pass |
| 169 | |
| 170 | def read_events(self) -> list[dict[str, Any]]: |
| 171 | if not self.events_file.exists(): |
| 172 | return [] |
| 173 | out: list[dict[str, Any]] = [] |
| 174 | with open(self.events_file, "r", encoding="utf-8", errors="replace") as fh: |
| 175 | for line in fh: |
| 176 | line = line.strip() |
| 177 | if not line: |
| 178 | continue |
| 179 | try: |
| 180 | out.append(json.loads(line)) |
| 181 | except json.JSONDecodeError: |
| 182 | continue |
| 183 | return out |