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.
- agent_plex-0.9.0.dist-info/METADATA +221 -0
- agent_plex-0.9.0.dist-info/RECORD +34 -0
- agent_plex-0.9.0.dist-info/WHEEL +5 -0
- agent_plex-0.9.0.dist-info/entry_points.txt +2 -0
- agent_plex-0.9.0.dist-info/licenses/LICENSE +22 -0
- agent_plex-0.9.0.dist-info/top_level.txt +1 -0
- plex_cli/__init__.py +1 -0
- plex_cli/auth.py +80 -0
- plex_cli/citations.py +42 -0
- plex_cli/cli.py +243 -0
- plex_cli/client.py +256 -0
- plex_cli/config.py +223 -0
- plex_cli/files.py +33 -0
- plex_cli/render.py +150 -0
- plex_cli/session.py +259 -0
- plex_cli/themes/catppuccin-mocha.toml +22 -0
- plex_cli/themes/dracula.toml +14 -0
- plex_cli/themes/gruvbox.toml +16 -0
- plex_cli/themes/matrix.toml +5 -0
- plex_cli/themes/terminal-coral.toml +3 -0
- plex_cli/themes/terminal-green.toml +4 -0
- plex_cli/themes/terminal-violet.toml +3 -0
- plex_cli/themes/terminal.toml +4 -0
- plex_cli/themes/tokyo-night.toml +14 -0
- plex_cli/tui/__init__.py +3 -0
- plex_cli/tui/app.py +565 -0
- plex_cli/tui/app.tcss +264 -0
- plex_cli/tui/backdrop.py +65 -0
- plex_cli/tui/commands.py +49 -0
- plex_cli/tui/effects.py +174 -0
- plex_cli/tui/screens.py +290 -0
- plex_cli/tui/themes.py +150 -0
- plex_cli/tui/widgets.py +259 -0
- plex_cli/turn.py +94 -0
plex_cli/tui/widgets.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Chat widgets: messages, prompt, command menu, welcome banner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Callable
|
|
7
|
+
from urllib.parse import urlparse
|
|
8
|
+
|
|
9
|
+
from textual import events
|
|
10
|
+
from textual.app import ComposeResult
|
|
11
|
+
from textual.containers import Vertical
|
|
12
|
+
from textual.content import Content
|
|
13
|
+
from textual.message import Message
|
|
14
|
+
from textual.widgets import Markdown, OptionList, Static, TextArea
|
|
15
|
+
from textual.widgets.option_list import Option
|
|
16
|
+
|
|
17
|
+
from ..client import Source
|
|
18
|
+
from ..config import Settings
|
|
19
|
+
from .commands import COMMANDS, lookup
|
|
20
|
+
from .effects import RainBackdrop
|
|
21
|
+
|
|
22
|
+
SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
|
|
23
|
+
|
|
24
|
+
LOGO = """\
|
|
25
|
+
█▀█ █ █▀▀ ▀▄▀
|
|
26
|
+
█▀▀ █▄▄ ██▄ █ █"""
|
|
27
|
+
|
|
28
|
+
def domain(url: str) -> str:
|
|
29
|
+
host = urlparse(url).netloc or url
|
|
30
|
+
return host.removeprefix("www.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Welcome(RainBackdrop, Static):
|
|
34
|
+
def __init__(self, settings: Settings) -> None:
|
|
35
|
+
super().__init__(id="welcome")
|
|
36
|
+
self.settings = settings # read on each render, so it follows /preset and /model
|
|
37
|
+
|
|
38
|
+
def render(self) -> Content:
|
|
39
|
+
hints = [
|
|
40
|
+
("enter", "send"), ("shift+enter", "new line"), ("/", "commands"),
|
|
41
|
+
("ctrl+s", "history"), ("ctrl+n", "new chat"), ("ctrl+p", "palette"),
|
|
42
|
+
]
|
|
43
|
+
body = Content.from_markup(f"[$accent b]{LOGO}[/]\n\n")
|
|
44
|
+
body += Content.from_markup("[dim]Ask anything — answers are researched on the web.[/]\n\n")
|
|
45
|
+
body += self._hint_lines(
|
|
46
|
+
[Content.from_markup("[$secondary b]$k[/] [dim]$w[/]", k=key, w=what) for key, what in hints]
|
|
47
|
+
)
|
|
48
|
+
kind = "effort" if self.settings.is_preset else "model"
|
|
49
|
+
body += Content.from_markup("\n\n[dim]$k[/] [b]$l[/]", k=kind, l=self.settings.label)
|
|
50
|
+
return body
|
|
51
|
+
|
|
52
|
+
def _hint_lines(self, hints: list[Content], gap: int = 3) -> Content:
|
|
53
|
+
"""Pack hints into lines that fit the width, wrapping only between whole hints.
|
|
54
|
+
|
|
55
|
+
Soft wrapping would split a hint, leaving its key at one line's end and its
|
|
56
|
+
description at the next one's start. Gaps only go between hints: a trailing
|
|
57
|
+
gap would push each centered line left.
|
|
58
|
+
"""
|
|
59
|
+
width = self.content_size.width or sum(h.cell_length for h in hints) + gap * len(hints)
|
|
60
|
+
lines: list[list[Content]] = [[]]
|
|
61
|
+
used = 0
|
|
62
|
+
for hint in hints:
|
|
63
|
+
need = hint.cell_length + (gap if lines[-1] else 0)
|
|
64
|
+
if lines[-1] and used + need > width:
|
|
65
|
+
lines.append([])
|
|
66
|
+
used, need = 0, hint.cell_length
|
|
67
|
+
lines[-1].append(hint)
|
|
68
|
+
used += need
|
|
69
|
+
return Content("\n").join(Content(" " * gap).join(line) for line in lines)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class UserMessage(Static):
|
|
73
|
+
def __init__(self, text: str) -> None:
|
|
74
|
+
super().__init__(Content(text), classes="user")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AssistantMessage(Vertical):
|
|
78
|
+
"""Header, live status/spinner, markdown body, sources, meta line."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, label: str, text: str = "") -> None:
|
|
81
|
+
super().__init__(classes="assistant")
|
|
82
|
+
self.label = label
|
|
83
|
+
self._initial = text
|
|
84
|
+
self._status = "Thinking"
|
|
85
|
+
self._frame = 0
|
|
86
|
+
self._started = time.monotonic()
|
|
87
|
+
self._timer = None
|
|
88
|
+
|
|
89
|
+
def compose(self) -> ComposeResult:
|
|
90
|
+
yield Static(Content.from_markup("[$accent b]◆ plex[/] [dim]$l[/]", l=self.label), classes="who")
|
|
91
|
+
yield Static(classes="status")
|
|
92
|
+
yield Markdown(self._initial, classes="answer")
|
|
93
|
+
yield Static(classes="sources")
|
|
94
|
+
yield Static(classes="meta")
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def markdown(self) -> Markdown:
|
|
98
|
+
return self.query_one(".answer", Markdown)
|
|
99
|
+
|
|
100
|
+
# --- live state ----------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
def start(self) -> None:
|
|
103
|
+
self._started = time.monotonic()
|
|
104
|
+
self.query_one(".status").display = True
|
|
105
|
+
self._timer = self.set_interval(0.08, self._tick)
|
|
106
|
+
self._tick()
|
|
107
|
+
|
|
108
|
+
def set_status(self, text: str) -> None:
|
|
109
|
+
self._status = text
|
|
110
|
+
self._tick()
|
|
111
|
+
|
|
112
|
+
def answering(self) -> None:
|
|
113
|
+
self._stop_spinner()
|
|
114
|
+
|
|
115
|
+
def _tick(self) -> None:
|
|
116
|
+
self._frame = (self._frame + 1) % len(SPINNER)
|
|
117
|
+
elapsed = time.monotonic() - self._started
|
|
118
|
+
self.query_one(".status", Static).update(Content.from_markup(
|
|
119
|
+
"[$accent]$s[/] [dim]$t · $e[/]", s=SPINNER[self._frame], t=self._status, e=f"{elapsed:.1f}s"))
|
|
120
|
+
|
|
121
|
+
def _stop_spinner(self) -> None:
|
|
122
|
+
if self._timer:
|
|
123
|
+
self._timer.stop()
|
|
124
|
+
self._timer = None
|
|
125
|
+
self.query_one(".status").display = False
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def elapsed(self) -> float:
|
|
129
|
+
return time.monotonic() - self._started
|
|
130
|
+
|
|
131
|
+
# --- final states --------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
def finish(self, sources: list[Source], meta: str, link_ids: list[int]) -> None:
|
|
134
|
+
self._stop_spinner()
|
|
135
|
+
self.show_sources(sources, link_ids)
|
|
136
|
+
self.query_one(".meta", Static).update(Content.from_markup("[dim]$m[/]", m=meta))
|
|
137
|
+
|
|
138
|
+
def show_sources(self, sources: list[Source], link_ids: list[int]) -> None:
|
|
139
|
+
box = self.query_one(".sources", Static)
|
|
140
|
+
if not sources:
|
|
141
|
+
box.display = False
|
|
142
|
+
return
|
|
143
|
+
lines = Content.from_markup("[dim]Sources[/]")
|
|
144
|
+
for s, lid in zip(sources, link_ids):
|
|
145
|
+
lines += Content("\n") + Content.from_markup(
|
|
146
|
+
f"[$accent]$n[/] [@click=app.open_link({lid})]$t[/] [dim]$d[/]",
|
|
147
|
+
n=f"{s.id:>2}", t=s.title or domain(s.url), d=domain(s.url))
|
|
148
|
+
box.update(lines)
|
|
149
|
+
box.display = True
|
|
150
|
+
|
|
151
|
+
def fail(self, msg: str) -> None:
|
|
152
|
+
self._stop_spinner()
|
|
153
|
+
self.add_class("failed")
|
|
154
|
+
self.query_one(".meta", Static).update(Content.from_markup("[$error]✗ $m[/]", m=msg))
|
|
155
|
+
|
|
156
|
+
def interrupted(self) -> None:
|
|
157
|
+
self._stop_spinner()
|
|
158
|
+
self.query_one(".meta", Static).update(Content.from_markup("[$warning]◼ interrupted[/]"))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class CommandMenu(OptionList):
|
|
162
|
+
"""Slash-command suggestions shown above the prompt."""
|
|
163
|
+
|
|
164
|
+
def filter(self, prefix: str) -> bool:
|
|
165
|
+
prefix = prefix.lower()
|
|
166
|
+
matches = [(c.name, c.help) for c in COMMANDS if c.name.startswith(prefix)]
|
|
167
|
+
self.clear_options()
|
|
168
|
+
for n, d in matches:
|
|
169
|
+
self.add_option(Option(Content.from_markup("[b]/$n[/] [dim]$d[/]", n=n, d=d), id=n))
|
|
170
|
+
if matches:
|
|
171
|
+
self.highlighted = 0
|
|
172
|
+
return bool(matches)
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def selected_command(self) -> str | None:
|
|
176
|
+
if self.highlighted is None or not self.option_count:
|
|
177
|
+
return None
|
|
178
|
+
return self.get_option_at_index(self.highlighted).id
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class PromptInput(TextArea):
|
|
182
|
+
"""Enter submits; shift/alt+enter or ctrl+j insert a newline."""
|
|
183
|
+
|
|
184
|
+
class Submitted(Message):
|
|
185
|
+
def __init__(self, text: str) -> None:
|
|
186
|
+
super().__init__()
|
|
187
|
+
self.text = text
|
|
188
|
+
|
|
189
|
+
NEWLINE_KEYS = {"shift+enter", "alt+enter", "ctrl+j", "newline", "ctrl+enter"}
|
|
190
|
+
|
|
191
|
+
def __init__(self, **kwargs) -> None:
|
|
192
|
+
super().__init__(soft_wrap=True, show_line_numbers=False, compact=True,
|
|
193
|
+
highlight_cursor_line=False, **kwargs)
|
|
194
|
+
self.menu: CommandMenu | None = None
|
|
195
|
+
self.past_messages: Callable[[], list[str]] = lambda: [] # oldest first, for ↑/↓ recall
|
|
196
|
+
self._recall_index: int | None = None
|
|
197
|
+
self._recalling = False # the text is a recalled message, so ↑/↓ keep browsing
|
|
198
|
+
|
|
199
|
+
def reset_recall(self) -> None:
|
|
200
|
+
self._recall_index = None
|
|
201
|
+
self._recalling = False
|
|
202
|
+
|
|
203
|
+
def _recall(self, direction: int) -> None:
|
|
204
|
+
past = self.past_messages()
|
|
205
|
+
if not past:
|
|
206
|
+
return
|
|
207
|
+
if self._recall_index is None:
|
|
208
|
+
if direction > 0:
|
|
209
|
+
return
|
|
210
|
+
self._recall_index = len(past)
|
|
211
|
+
self._recall_index += direction
|
|
212
|
+
if self._recall_index >= len(past):
|
|
213
|
+
self.reset_recall()
|
|
214
|
+
self.text = ""
|
|
215
|
+
return
|
|
216
|
+
self._recall_index = max(0, self._recall_index)
|
|
217
|
+
self.text = past[self._recall_index]
|
|
218
|
+
self.move_cursor(self.document.end)
|
|
219
|
+
self._recalling = True
|
|
220
|
+
|
|
221
|
+
def _menu_open(self) -> bool:
|
|
222
|
+
return bool(self.menu and self.menu.display and self.menu.option_count)
|
|
223
|
+
|
|
224
|
+
async def _on_key(self, event: events.Key) -> None:
|
|
225
|
+
key = event.key
|
|
226
|
+
if self._menu_open():
|
|
227
|
+
if key in ("up", "down"):
|
|
228
|
+
event.prevent_default(); event.stop()
|
|
229
|
+
(self.menu.action_cursor_up if key == "up" else self.menu.action_cursor_down)()
|
|
230
|
+
return
|
|
231
|
+
if key in ("tab", "enter"):
|
|
232
|
+
event.prevent_default(); event.stop()
|
|
233
|
+
cmd = self.menu.selected_command
|
|
234
|
+
if cmd:
|
|
235
|
+
if key == "tab" or lookup(cmd).fill_on_enter:
|
|
236
|
+
self.text = f"/{cmd} "
|
|
237
|
+
self.move_cursor(self.document.end)
|
|
238
|
+
else:
|
|
239
|
+
self.post_message(self.Submitted(f"/{cmd}"))
|
|
240
|
+
return
|
|
241
|
+
if key == "escape":
|
|
242
|
+
event.prevent_default(); event.stop()
|
|
243
|
+
self.menu.display = False
|
|
244
|
+
return
|
|
245
|
+
if key == "enter":
|
|
246
|
+
event.prevent_default(); event.stop()
|
|
247
|
+
self.post_message(self.Submitted(self.text))
|
|
248
|
+
return
|
|
249
|
+
if key in self.NEWLINE_KEYS:
|
|
250
|
+
event.prevent_default(); event.stop()
|
|
251
|
+
self.insert("\n")
|
|
252
|
+
return
|
|
253
|
+
# ↑ on an empty prompt starts browsing past messages; while browsing, ↑/↓ move through them.
|
|
254
|
+
if (key == "up" and not self.text) or (key in ("up", "down") and self._recalling):
|
|
255
|
+
event.prevent_default(); event.stop()
|
|
256
|
+
self._recall(-1 if key == "up" else 1)
|
|
257
|
+
return
|
|
258
|
+
self._recalling = False
|
|
259
|
+
await super()._on_key(event)
|
plex_cli/turn.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""One question-and-answer turn, shared by the one-shot CLI and the TUI.
|
|
2
|
+
|
|
3
|
+
A frontend only displays the turn: it hands `run`/`arun` a view with `delta`,
|
|
4
|
+
`searching` and `sources_found`, and calls `turn_error` and `complete` around it.
|
|
5
|
+
Which errors are worth showing, when a turn counts, and what gets remembered
|
|
6
|
+
afterwards are decided here, once for both.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import inspect
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, AsyncIterable, Iterable, Protocol
|
|
14
|
+
|
|
15
|
+
from .client import Done, Event, Searching, Source, SourcesFound, TextDelta, TurnFailed, api_error_message, \
|
|
16
|
+
is_auth_error
|
|
17
|
+
from .config import Settings, save_state
|
|
18
|
+
from .session import Session, Turn
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TurnView(Protocol):
|
|
22
|
+
"""Where a streaming answer is shown. Methods may be sync or async."""
|
|
23
|
+
|
|
24
|
+
def delta(self, text: str) -> Any: ...
|
|
25
|
+
|
|
26
|
+
def searching(self, queries: list[str]) -> Any: ...
|
|
27
|
+
|
|
28
|
+
def sources_found(self, sources: list[Source]) -> Any: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def searching_status(queries: list[str]) -> str:
|
|
32
|
+
q = " · ".join(x for x in queries if x)
|
|
33
|
+
return f"Searching: {q}" if q else "Searching"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _route(ev: Event, view: TurnView) -> Any:
|
|
37
|
+
if isinstance(ev, TextDelta):
|
|
38
|
+
return view.delta(ev.text)
|
|
39
|
+
if isinstance(ev, Searching):
|
|
40
|
+
return view.searching(ev.queries)
|
|
41
|
+
if isinstance(ev, SourcesFound):
|
|
42
|
+
return view.sources_found(ev.sources)
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _no_answer() -> TurnFailed:
|
|
47
|
+
return TurnFailed("No answer received.")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def run(events: Iterable[Event], view: TurnView) -> Done:
|
|
51
|
+
"""Feed a turn's events to `view`; returns the final Done. Errors propagate."""
|
|
52
|
+
done: Done | None = None
|
|
53
|
+
for ev in events:
|
|
54
|
+
if isinstance(ev, Done):
|
|
55
|
+
done = ev
|
|
56
|
+
else:
|
|
57
|
+
_route(ev, view)
|
|
58
|
+
if done is None:
|
|
59
|
+
raise _no_answer()
|
|
60
|
+
return done
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def arun(events: AsyncIterable[Event], view: TurnView) -> Done:
|
|
64
|
+
"""`run` for async event streams; awaits view methods that are coroutines."""
|
|
65
|
+
done: Done | None = None
|
|
66
|
+
async for ev in events:
|
|
67
|
+
if isinstance(ev, Done):
|
|
68
|
+
done = ev
|
|
69
|
+
elif inspect.isawaitable(res := _route(ev, view)):
|
|
70
|
+
await res
|
|
71
|
+
if done is None:
|
|
72
|
+
raise _no_answer()
|
|
73
|
+
return done
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class TurnError:
|
|
78
|
+
message: str
|
|
79
|
+
auth: bool = False # the API key was rejected: ask for another one
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def turn_error(e: BaseException) -> TurnError | None:
|
|
83
|
+
"""What to tell the user about a failed turn; None if `e` isn't an API failure."""
|
|
84
|
+
if isinstance(e, TurnFailed):
|
|
85
|
+
return TurnError(str(e) or "The request failed.")
|
|
86
|
+
msg = api_error_message(e)
|
|
87
|
+
return TurnError(msg, auth=is_auth_error(e)) if msg is not None else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def complete(session: Session, settings: Settings, question: str, done: Done) -> None:
|
|
91
|
+
"""Commit an answered turn and remember which model served the effort preset."""
|
|
92
|
+
session.commit(Turn(question, done.text, done.sources, done.cost, done.model))
|
|
93
|
+
if settings.is_preset and settings.note_seen(done.effort, done.model):
|
|
94
|
+
save_state(settings, ("seen",)) # only `seen`: one-shot flags must not be saved
|