-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsession_state.py
More file actions
75 lines (58 loc) · 1.9 KB
/
session_state.py
File metadata and controls
75 lines (58 loc) · 1.9 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
"""Track the active Cortex session for resume across Claude Code turns.
Every `cortex --input-format stream-json` invocation emits a session_id in its
init event. Persisting that id lets follow-up turns run `cortex --resume <id>`
so Cortex sees prior conversation -- real multi-turn instead of one-shot
batches per prompt.
"""
import json
import os
import tempfile
import time
from pathlib import Path
from typing import Optional
STATE_DIR = Path.home() / ".cache" / "cortex-router"
STATE_FILE_NAME = "active-session.json"
STALE_AFTER_SECONDS = 30 * 60
def _state_path() -> Path:
return STATE_DIR / STATE_FILE_NAME
def load_active_session() -> Optional[dict]:
"""Return the persisted active session dict, or None if missing/stale."""
path = _state_path()
if not path.exists():
return None
try:
data = json.loads(path.read_text())
except (json.JSONDecodeError, OSError):
return None
if time.time() - data.get("timestamp", 0) > STALE_AFTER_SECONDS:
return None
if not data.get("session_id"):
return None
return data
def save_active_session(session_id: str) -> None:
"""Persist the session id so subsequent turns can resume."""
if not session_id:
return
payload = {"session_id": session_id, "timestamp": time.time()}
path = _state_path()
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=".active-", suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(payload, f)
os.replace(tmp_name, path)
os.chmod(path, 0o600)
except Exception:
try:
os.unlink(tmp_name)
except OSError:
pass
raise
def clear_active_session() -> None:
path = _state_path()
if path.exists():
try:
path.unlink()
except OSError:
pass