agent-plex 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plex_cli/session.py ADDED
@@ -0,0 +1,259 @@
1
+ """Conversations: replayed history, cost tracking, auto-saved JSON files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import secrets
8
+ import time
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from .client import Source
13
+ from .files import PRIVATE_DIR, atomic_write_json
14
+
15
+ MAX_TURNS = 20 # user+assistant pairs kept in the replayed input
16
+ TITLE_LEN = 60
17
+
18
+
19
+ @dataclass
20
+ class Turn:
21
+ user: str
22
+ assistant: str
23
+ sources: dict[int, Source] = field(default_factory=dict)
24
+ cost: float | None = None
25
+ model: str | None = None
26
+ created_at: float = field(default_factory=time.time)
27
+
28
+
29
+ def new_id() -> str:
30
+ return time.strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(3)
31
+
32
+
33
+ def make_title(text: str) -> str:
34
+ line = " ".join(text.split())
35
+ return line if len(line) <= TITLE_LEN else line[: TITLE_LEN - 1].rstrip() + "…"
36
+
37
+
38
+ def _header(data: dict, fallback_id: str, fallback_time: float) -> tuple[str, str, float, float]:
39
+ """(id, title, created_at, updated_at) of a saved conversation, filling in what older
40
+ (v1) files or hand-edited ones leave out."""
41
+ title = data.get("title")
42
+ if not (title and isinstance(title, str)):
43
+ users = (t["user"] for t in _turns(data) if isinstance(t, dict) and isinstance(t.get("user"), str))
44
+ title = make_title(next(users, ""))
45
+ created = float(data.get("created_at") or data.get("saved_at") or fallback_time)
46
+ updated = float(data.get("updated_at") or data.get("saved_at") or fallback_time)
47
+ sid = data.get("id")
48
+ return sid if sid and isinstance(sid, str) else fallback_id, title, created, updated
49
+
50
+
51
+ def _turns(data: dict) -> list:
52
+ turns = data.get("turns")
53
+ return turns if isinstance(turns, list) else []
54
+
55
+
56
+ @dataclass
57
+ class Session:
58
+ id: str = field(default_factory=new_id)
59
+ title: str = ""
60
+ turns: list[Turn] = field(default_factory=list)
61
+ total_cost: float = 0.0
62
+ created_at: float = field(default_factory=time.time)
63
+ updated_at: float = field(default_factory=time.time)
64
+ max_turns: int = MAX_TURNS
65
+
66
+ def input_for(self, question: str) -> list[dict]:
67
+ items: list[dict] = []
68
+ for t in self.turns[-self.max_turns :]:
69
+ items.append({"type": "message", "role": "user", "content": t.user})
70
+ items.append({"type": "message", "role": "assistant", "content": t.assistant})
71
+ items.append({"type": "message", "role": "user", "content": question})
72
+ return items
73
+
74
+ def commit(self, turn: Turn) -> None:
75
+ self.turns.append(turn)
76
+ if turn.cost:
77
+ self.total_cost += turn.cost
78
+ if not self.title:
79
+ self.title = make_title(turn.user)
80
+ self.updated_at = time.time()
81
+
82
+ @property
83
+ def last(self) -> Turn | None:
84
+ return self.turns[-1] if self.turns else None
85
+
86
+ # --- persistence -------------------------------------------------------
87
+
88
+ def to_json(self) -> dict:
89
+ return {
90
+ "version": 2,
91
+ "id": self.id,
92
+ "title": self.title,
93
+ "created_at": self.created_at,
94
+ "updated_at": self.updated_at,
95
+ "total_cost": self.total_cost,
96
+ "turns": [
97
+ {
98
+ "user": t.user,
99
+ "assistant": t.assistant,
100
+ "cost": t.cost,
101
+ "model": t.model,
102
+ "created_at": t.created_at,
103
+ "sources": [vars(s) for s in t.sources.values()],
104
+ }
105
+ for t in self.turns
106
+ ],
107
+ }
108
+
109
+ @classmethod
110
+ def from_json(cls, data: dict, fallback_id: str | None = None) -> "Session":
111
+ """Raises ValueError for a file that isn't a conversation; turns and sources that
112
+ are malformed (hand-edited, or a partial write) are skipped."""
113
+ if not isinstance(data, dict):
114
+ raise ValueError("not a conversation file")
115
+ sid, title, created, updated = _header(data, fallback_id or new_id(), time.time())
116
+ s = cls(id=sid, title=title, total_cost=float(data.get("total_cost") or 0.0),
117
+ created_at=created, updated_at=updated)
118
+ for t in _turns(data):
119
+ if turn := _turn_from_json(t, s.created_at):
120
+ s.turns.append(turn)
121
+ return s
122
+
123
+
124
+ def _turn_from_json(t: object, fallback_time: float) -> Turn | None:
125
+ if not (isinstance(t, dict) and isinstance(t.get("user"), str) and isinstance(t.get("assistant"), str)):
126
+ return None
127
+ srcs = {}
128
+ for x in t.get("sources") or []:
129
+ if src := _source_from_json(x):
130
+ srcs[src.id] = src
131
+ try:
132
+ created = float(t.get("created_at") or fallback_time)
133
+ except (TypeError, ValueError):
134
+ created = fallback_time
135
+ cost = t.get("cost")
136
+ return Turn(t["user"], t["assistant"], srcs,
137
+ float(cost) if isinstance(cost, (int, float)) else None,
138
+ t.get("model") if isinstance(t.get("model"), str) else None, created)
139
+
140
+
141
+ def _source_from_json(x: object) -> Source | None:
142
+ if not isinstance(x, dict) or not isinstance(x.get("url"), str):
143
+ return None
144
+ try:
145
+ sid = int(x["id"])
146
+ except (KeyError, TypeError, ValueError):
147
+ return None
148
+ title, date = x.get("title"), x.get("date")
149
+ return Source(sid, x["url"], title if isinstance(title, str) else "", date if isinstance(date, str) else None)
150
+
151
+
152
+ @dataclass
153
+ class SessionInfo:
154
+ id: str
155
+ title: str
156
+ updated_at: float
157
+ turns: int
158
+ cost: float
159
+
160
+
161
+ class Store:
162
+ """Directory of `<id>.json` conversation files."""
163
+
164
+ def __init__(self, directory: Path):
165
+ self.dir = directory
166
+ self.unreadable: list[Path] = [] # files the last `list()` had to skip
167
+
168
+ def path(self, sid: str) -> Path:
169
+ safe = re.sub(r"[^A-Za-z0-9._-]+", "-", sid).strip("-.")
170
+ if not safe:
171
+ raise ValueError("invalid session id")
172
+ return self.dir / f"{safe}.json"
173
+
174
+ def save(self, s: Session) -> Path:
175
+ if not s.turns:
176
+ return self.path(s.id)
177
+ p = self.path(s.id)
178
+ # Conversations are private, like auth.json: 0600 files in 0700 folders. The data
179
+ # folder above is created here too, since a chat may be saved before any key is.
180
+ self.dir.parent.mkdir(parents=True, exist_ok=True, mode=PRIVATE_DIR)
181
+ atomic_write_json(p, s.to_json(), private=True)
182
+ return p
183
+
184
+ def load(self, sid: str) -> Session:
185
+ p = self.path(sid)
186
+ return Session.from_json(json.loads(p.read_text()), fallback_id=p.stem)
187
+
188
+ def delete(self, sid: str) -> None:
189
+ self.path(sid).unlink(missing_ok=True)
190
+
191
+ def count(self) -> int:
192
+ """How many conversation files there are (readable or not, like `clear` deletes)."""
193
+ return sum(1 for _ in self.dir.glob("*.json")) if self.dir.exists() else 0
194
+
195
+ def clear(self) -> int:
196
+ """Delete every saved conversation; returns how many files were removed."""
197
+ if not self.dir.exists():
198
+ return 0
199
+ n = 0
200
+ for p in [*self.dir.glob("*.json"), *self.dir.glob("*.tmp")]:
201
+ p.unlink(missing_ok=True)
202
+ n += p.suffix == ".json"
203
+ return n
204
+
205
+ def prune(self, keep_days: int, now: float | None = None) -> int:
206
+ """Delete conversations not updated in the last `keep_days` days (0 keeps them all);
207
+ returns how many were removed. Files that can't be read are left alone."""
208
+ if keep_days <= 0 or not self.dir.exists():
209
+ return 0
210
+ cutoff = (now or time.time()) - keep_days * 86400
211
+ n = 0
212
+ for p in self.dir.glob("*.json"):
213
+ try:
214
+ d = json.loads(p.read_text())
215
+ if not isinstance(d, dict):
216
+ continue
217
+ if _header(d, p.stem, p.stat().st_mtime)[3] < cutoff:
218
+ p.unlink(missing_ok=True)
219
+ n += 1
220
+ except (OSError, ValueError, TypeError):
221
+ continue
222
+ return n
223
+
224
+ def list(self) -> list[SessionInfo]:
225
+ self.unreadable = []
226
+ if not self.dir.exists():
227
+ return []
228
+ out = []
229
+ for p in self.dir.glob("*.json"):
230
+ try:
231
+ d = json.loads(p.read_text())
232
+ if not isinstance(d, dict):
233
+ raise ValueError("not a conversation file")
234
+ sid, title, _, updated = _header(d, p.stem, p.stat().st_mtime)
235
+ out.append(SessionInfo(sid, title or p.stem, updated, len(_turns(d)),
236
+ float(d.get("total_cost") or 0)))
237
+ except (OSError, ValueError, KeyError, TypeError):
238
+ self.unreadable.append(p)
239
+ return sorted(out, key=lambda i: i.updated_at, reverse=True)
240
+
241
+ def find(self, query: str) -> str | None:
242
+ """Exact id, else most recent session whose title contains `query`."""
243
+ try:
244
+ if self.path(query).exists():
245
+ return query
246
+ except ValueError: # not usable as an id (e.g. only punctuation); still a title search
247
+ pass
248
+ q = query.lower()
249
+ return next((i.id for i in self.list() if q in i.title.lower()), None)
250
+
251
+
252
+ def ago(ts: float, now: float | None = None) -> str:
253
+ d = max(0, (now or time.time()) - ts)
254
+ if d < 60:
255
+ return "just now"
256
+ for unit, sec in (("y", 31536000), ("mo", 2592000), ("d", 86400), ("h", 3600), ("m", 60)):
257
+ if d >= sec:
258
+ return f"{int(d // sec)}{unit} ago"
259
+ return "just now"
@@ -0,0 +1,22 @@
1
+ # Catppuccin Mocha — https://catppuccin.com
2
+ primary = "#F5C2E7"
3
+ secondary = "#cba6f7"
4
+ accent = "#fab387"
5
+ warning = "#FAE3B0"
6
+ error = "#F28FAD"
7
+ success = "#ABE9B3"
8
+ foreground = "#cdd6f4"
9
+ background = "#181825"
10
+ surface = "#313244"
11
+ panel = "#45475a"
12
+
13
+ [variables]
14
+ input-cursor-foreground = "#11111b"
15
+ input-cursor-background = "#f5e0dc"
16
+ input-selection-background = "#9399b2 30%"
17
+ border = "#b4befe"
18
+ border-blurred = "#585b70"
19
+ footer-background = "#45475a"
20
+ block-cursor-foreground = "#1e1e2e"
21
+ block-cursor-text-style = "none"
22
+ button-color-foreground = "#181825"
@@ -0,0 +1,14 @@
1
+ # Dracula — https://draculatheme.com
2
+ primary = "#BD93F9"
3
+ secondary = "#6272A4"
4
+ accent = "#FF79C6"
5
+ warning = "#FFB86C"
6
+ error = "#FF5555"
7
+ success = "#50FA7B"
8
+ foreground = "#F8F8F2"
9
+ background = "#282A36"
10
+ surface = "#2B2E3B"
11
+ panel = "#313442"
12
+
13
+ [variables]
14
+ button-color-foreground = "#282A36"
@@ -0,0 +1,16 @@
1
+ # Gruvbox (dark) — https://github.com/morhetz/gruvbox
2
+ primary = "#85A598"
3
+ secondary = "#A89A85"
4
+ accent = "#fabd2f"
5
+ warning = "#fe8019"
6
+ error = "#fb4934"
7
+ success = "#b8bb26"
8
+ foreground = "#fbf1c7"
9
+ background = "#282828"
10
+ surface = "#3c3836"
11
+ panel = "#504945"
12
+
13
+ [variables]
14
+ block-cursor-foreground = "#fbf1c7"
15
+ input-selection-background = "#689d6a40"
16
+ button-color-foreground = "#282828"
@@ -0,0 +1,5 @@
1
+ # terminal-green plus dim digital rain falling in the background.
2
+ terminal = true
3
+ accent = "#00FF41" # bright code green
4
+ secondary = "#008F11" # dimmer green: your messages, key hints
5
+ effect = "rain" # animated background; see tui/effects.py
@@ -0,0 +1,3 @@
1
+ # Your terminal's own background, text and palette, with a coral accent.
2
+ terminal = true
3
+ accent = "#D97757"
@@ -0,0 +1,4 @@
1
+ # Your terminal's own background and text, in the green of falling digital rain.
2
+ terminal = true
3
+ accent = "#00FF41" # bright code green
4
+ secondary = "#008F11" # dimmer green: your messages, key hints
@@ -0,0 +1,3 @@
1
+ # Your terminal's own background, text and palette, with a violet accent.
2
+ terminal = true
3
+ accent = "#9D7CD8"
@@ -0,0 +1,4 @@
1
+ # Your terminal's own background, text and palette. The accent is the
2
+ # terminal's blue, so this fits any color scheme, light or dark.
3
+ terminal = true
4
+ accent = "ansi_blue"
@@ -0,0 +1,14 @@
1
+ # Tokyo Night — https://github.com/enkia/tokyo-night-vscode-theme
2
+ primary = "#BB9AF7"
3
+ secondary = "#7AA2F7"
4
+ accent = "#FF9E64"
5
+ warning = "#E0AF68"
6
+ error = "#F7768E"
7
+ success = "#9ECE6A"
8
+ foreground = "#a9b1d6"
9
+ background = "#1A1B26"
10
+ surface = "#24283B"
11
+ panel = "#414868"
12
+
13
+ [variables]
14
+ button-color-foreground = "#24283B"
@@ -0,0 +1,3 @@
1
+ from .app import PlexApp
2
+
3
+ __all__ = ["PlexApp"]