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.
@@ -0,0 +1,290 @@
1
+ """Modal dialogs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import partial
6
+ from typing import Callable
7
+
8
+ from textual import on
9
+ from textual.app import ComposeResult
10
+ from textual.binding import Binding
11
+ from textual.command import CommandInput, CommandPalette, DiscoveryHit, Hit, Hits, Provider
12
+ from textual.containers import Vertical
13
+ from textual.content import Content
14
+ from textual.screen import ModalScreen
15
+ from textual.widgets import Input, OptionList, Static
16
+ from textual.widgets.option_list import Option
17
+
18
+ from ..auth import AUTH_FILE
19
+ from ..config import EFFORT_INFO, EFFORTS, REASONING, REASONING_INFO
20
+ from ..session import ago
21
+ from .commands import COMMANDS
22
+
23
+
24
+ class Dialog(ModalScreen):
25
+ BINDINGS = [Binding("escape", "dismiss_none", "Close", show=False)]
26
+
27
+ def action_dismiss_none(self) -> None:
28
+ self.dismiss(None)
29
+
30
+
31
+ class ApiKeyScreen(Dialog):
32
+ def __init__(self, reason: str = "") -> None:
33
+ super().__init__()
34
+ self.reason = reason
35
+
36
+ def compose(self) -> ComposeResult:
37
+ with Vertical(classes="dialog"):
38
+ yield Static(Content.from_markup("[b]Connect to Perplexity[/]"), classes="title")
39
+ if self.reason:
40
+ yield Static(Content.from_markup("[$warning]$r[/]", r=self.reason))
41
+ yield Static(Content.from_markup(
42
+ "[dim]Paste an API key from[/] [@click=app.open_url('https://www.perplexity.ai/account/api')]"
43
+ "perplexity.ai/account/api[/]"))
44
+ yield Input(placeholder="pplx-…", password=True, id="key")
45
+ yield Static(Content.from_markup("[dim]Saved to $p (mode 600) · enter to save · esc to cancel[/]",
46
+ p=str(AUTH_FILE).replace(str(AUTH_FILE.home()), "~")),
47
+ classes="hint")
48
+
49
+ def on_mount(self) -> None:
50
+ self.query_one(Input).focus()
51
+
52
+ def on_input_submitted(self, event: Input.Submitted) -> None:
53
+ value = event.value.strip()
54
+ if value:
55
+ self.dismiss(value)
56
+
57
+
58
+ def effort_option(effort: str, seen: dict | None) -> Content:
59
+ """Two lines: the level and what it does, then the model last seen serving it."""
60
+ body = Content.from_markup("[b]$e[/] [dim]$d[/]\n ", e=f"{effort:<7}", d=EFFORT_INFO[effort])
61
+ if seen:
62
+ body += Content.from_markup("[$secondary]$m[/] [dim]· seen $a[/]", m=seen["model"], a=ago(seen["at"]))
63
+ else:
64
+ body += Content.from_markup("[dim]model shown after first use[/]")
65
+ return body
66
+
67
+
68
+ class EffortScreen(Dialog):
69
+ def __init__(self, current: str, seen: dict[str, dict] | None = None) -> None:
70
+ super().__init__()
71
+ self.current = current
72
+ self.seen = seen or {}
73
+
74
+ def compose(self) -> ComposeResult:
75
+ with Vertical(classes="dialog"):
76
+ yield Static(Content.from_markup("[b]Research effort[/]"), classes="title")
77
+ opts = OptionList(*[Option(effort_option(e, self.seen.get(e)), id=e) for e in EFFORTS])
78
+ yield opts
79
+ yield Static(Content.from_markup(
80
+ "[dim]Perplexity picks each level's model and may change it.\n"
81
+ "enter to choose · esc to cancel[/]"), classes="hint")
82
+
83
+ def on_mount(self) -> None:
84
+ opts = self.query_one(OptionList)
85
+ opts.highlighted = EFFORTS.index(self.current) if self.current in EFFORTS else 0
86
+ opts.focus()
87
+
88
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
89
+ self.dismiss(event.option.id)
90
+
91
+
92
+ DEFAULT_REASONING = "default" # what `/effort` and the picker call "let the model decide"
93
+
94
+
95
+ def parse_reasoning(word: str) -> str | None:
96
+ """A model reasoning level as the user names it; "default" is None (the model decides)."""
97
+ if word == DEFAULT_REASONING:
98
+ return None
99
+ if word not in REASONING:
100
+ raise ValueError(f"Unknown model effort. Choose: {', '.join(REASONING)}, {DEFAULT_REASONING}")
101
+ return word
102
+
103
+
104
+ class ReasoningScreen(Dialog):
105
+ """Reasoning effort for a manually selected model. Choosing one calls `on_pick` with
106
+ the level (None for the model's default); esc closes without calling it."""
107
+
108
+ def __init__(self, model: str, current: str | None, on_pick: Callable[[str | None], None]) -> None:
109
+ super().__init__()
110
+ self.model = model
111
+ self.current = current or DEFAULT_REASONING
112
+ self.on_pick = on_pick
113
+
114
+ def compose(self) -> ComposeResult:
115
+ with Vertical(classes="dialog"):
116
+ yield Static(Content.from_markup("[b]Reasoning effort[/] [dim]for[/] $m", m=self.model),
117
+ classes="title")
118
+ levels = [(DEFAULT_REASONING, "the model's own default")]
119
+ levels += [(r, REASONING_INFO[r]) for r in REASONING]
120
+ yield OptionList(*[Option(Content.from_markup("[b]$r[/] [dim]$d[/]", r=f"{r:<8}", d=d), id=r)
121
+ for r, d in levels])
122
+ yield Static(Content.from_markup(
123
+ "[dim]Not every model supports every level.\n"
124
+ "/preset goes back to presets · enter to choose · esc to cancel[/]"), classes="hint")
125
+
126
+ def on_mount(self) -> None:
127
+ opts = self.query_one(OptionList)
128
+ opts.highlighted = opts.get_option_index(self.current)
129
+ opts.focus()
130
+
131
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
132
+ self.dismiss()
133
+ self.on_pick(parse_reasoning(event.option.id))
134
+
135
+
136
+ class ConfirmScreen(Dialog):
137
+ BINDINGS = [Binding("y", "yes", "Yes"), Binding("n", "dismiss_none", "No"),
138
+ Binding("escape", "dismiss_none", "No", show=False)]
139
+
140
+ def __init__(self, question: str) -> None:
141
+ super().__init__()
142
+ self.question = question
143
+
144
+ def compose(self) -> ComposeResult:
145
+ with Vertical(classes="dialog"):
146
+ yield Static(Content(self.question), classes="title")
147
+ yield Static(Content.from_markup("[b]y[/] [dim]yes ·[/] [b]n[/] [dim]no[/]"), classes="hint")
148
+
149
+ def action_yes(self) -> None:
150
+ self.dismiss(True)
151
+
152
+
153
+ KEYS = [
154
+ ("enter", "send message"),
155
+ ("shift+enter · alt+enter · ctrl+j", "new line"),
156
+ ("↑ / ↓ (empty prompt)", "recall previous messages"),
157
+ ("esc", "cancel the answer being written"),
158
+ ("ctrl+n", "new conversation"),
159
+ ("ctrl+s", "toggle history sidebar"),
160
+ ("ctrl+e", "change effort preset"),
161
+ ("ctrl+p", "command palette"),
162
+ ("ctrl+q", "quit"),
163
+ ]
164
+
165
+
166
+ class HelpScreen(Dialog):
167
+ def compose(self) -> ComposeResult:
168
+ body = Content.from_markup("[b]Keys[/]\n")
169
+ for k, d in KEYS:
170
+ body += Content.from_markup(" [$secondary]$k[/] [dim]$d[/]\n", k=f"{k:<34}", d=d)
171
+ body += Content.from_markup("\n[b]Commands[/]\n")
172
+ for c in COMMANDS:
173
+ body += Content.from_markup(" [$secondary]$n[/] [dim]$d[/]\n", n=f"/{c.name:<33}", d=c.help)
174
+ with Vertical(classes="dialog wide"):
175
+ yield Static(body)
176
+ yield Static(Content.from_markup("[dim]esc to close[/]"), classes="hint")
177
+
178
+
179
+ class ThemeProvider(Provider):
180
+ """Lists themes; every hit carries the theme name as `text` for live preview."""
181
+
182
+ def _themes(self) -> list[str]:
183
+ return list(self.app.available_themes) # plex's own order, see themes.py
184
+
185
+ def _pick(self, name: str) -> None:
186
+ self.app.theme = name
187
+
188
+ async def discover(self) -> Hits:
189
+ for name in self._themes():
190
+ yield DiscoveryHit(name, partial(self._pick, name), text=name)
191
+
192
+ async def search(self, query: str) -> Hits:
193
+ matcher = self.matcher(query)
194
+ for name in self._themes():
195
+ if (score := matcher.match(name)) > 0:
196
+ yield Hit(score, matcher.highlight(name), partial(self._pick, name), text=name)
197
+
198
+
199
+ class PickerPalette(CommandPalette):
200
+ """A searchable list that opens on the hit whose `text` equals `initial`."""
201
+
202
+ initial: str | None = None
203
+
204
+ # Private Textual hook (checked against Textual 8.2). If it stops being called the list
205
+ # opens on the first entry; test_model_picker_lists_and_selects catches that.
206
+ def _refresh_command_list(self, command_list, commands, clear_current) -> None:
207
+ super()._refresh_command_list(command_list, commands, clear_current)
208
+ # Open on the current choice rather than jumping to the first one in the list.
209
+ if not self.query_one(CommandInput).value:
210
+ for index, command in enumerate(command_list.options):
211
+ if command.hit.text == self.initial:
212
+ command_list.highlighted = index
213
+ break
214
+
215
+
216
+ PRESET = "preset" # the model-list entry that goes back to effort presets
217
+
218
+
219
+ class ModelProvider(Provider):
220
+ """Lists the preset entry, then the palette's models; every hit carries its id as `text`."""
221
+
222
+ models: list[str]
223
+ then: Callable[[], None] | None
224
+
225
+ async def startup(self) -> None:
226
+ # Runs while the palette is open and on top (`self.screen` is the screen it was opened
227
+ # from). Copied here because a pick runs after the palette has closed.
228
+ palette = self.app.screen
229
+ assert isinstance(palette, ModelPalette)
230
+ self.models, self.then = palette.models, palette.then
231
+
232
+ def _entries(self) -> list[tuple[str, str, str]]:
233
+ """(text, label, help) per entry."""
234
+ preset = (PRESET, f"preset · {self.app.settings.effort}",
235
+ "Let Perplexity pick the model for the effort level")
236
+ return [preset] + [(m, m, "") for m in self.models]
237
+
238
+ def _pick(self, text: str) -> None:
239
+ self.app.set_model(None if text == PRESET else text)
240
+ if text != PRESET and self.then:
241
+ self.then()
242
+
243
+ async def discover(self) -> Hits:
244
+ for text, label, help in self._entries():
245
+ yield DiscoveryHit(label, partial(self._pick, text), text=text, help=help or None)
246
+
247
+ async def search(self, query: str) -> Hits:
248
+ matcher = self.matcher(query)
249
+ for text, label, help in self._entries():
250
+ if (score := matcher.match(label)) > 0:
251
+ yield Hit(score, matcher.highlight(label), partial(self._pick, text),
252
+ text=text, help=help or None)
253
+
254
+
255
+ class ModelPalette(PickerPalette):
256
+ """Model search; enter switches to direct-model mode, the preset entry switches back.
257
+
258
+ `then`, if set, runs after a model (not the preset entry) is picked.
259
+ """
260
+
261
+ def __init__(self, models: list[str], current: str | None,
262
+ then: Callable[[], None] | None = None) -> None:
263
+ super().__init__(providers=[ModelProvider], placeholder="Search for models…")
264
+ self.models = models
265
+ self.then = then
266
+ self.initial = current or PRESET
267
+
268
+
269
+ class ThemePalette(PickerPalette):
270
+ """Theme search that applies each theme as it's highlighted; esc restores the original."""
271
+
272
+ def __init__(self) -> None:
273
+ super().__init__(providers=[ThemeProvider], placeholder="Search for themes…")
274
+ self.original_theme: str | None = None
275
+
276
+ def on_mount(self) -> None:
277
+ self.original_theme = self.initial = self.app.theme
278
+
279
+ @on(OptionList.OptionHighlighted)
280
+ def _preview(self, event: OptionList.OptionHighlighted) -> None:
281
+ name = getattr(getattr(event.option, "hit", None), "text", None)
282
+ if name in self.app.available_themes:
283
+ self.app.theme = name
284
+
285
+ # Private Textual action behind esc (checked against Textual 8.2); if it stops being
286
+ # called, test_theme_picker_previews_and_reverts sees the preview stick.
287
+ def _action_escape(self) -> None:
288
+ if self.original_theme:
289
+ self.app.theme = self.original_theme
290
+ super()._action_escape()
plex_cli/tui/themes.py ADDED
@@ -0,0 +1,150 @@
1
+ """Load color themes from TOML files: the bundled ones plus the user's own.
2
+
3
+ Each `<name>.toml` file is one theme, named after the file. Files in the user's
4
+ theme folder (~/.config/plex/themes) are loaded after the bundled ones, so a
5
+ user file with the same name replaces a bundled theme.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import tomllib
11
+ from dataclasses import dataclass, fields
12
+ from pathlib import Path
13
+
14
+ from textual.theme import Theme
15
+
16
+ from ..config import CONFIG_FILE
17
+ from .effects import EFFECTS
18
+
19
+ BUNDLED_THEMES_DIR = Path(__file__).parent.parent / "themes"
20
+ USER_THEMES_DIR = CONFIG_FILE.parent / "themes"
21
+ USER_THEMES_PLACEHOLDER = "PUT_YOUR_THEMES_HERE"
22
+
23
+
24
+
25
+ @dataclass
26
+ class PlexTheme(Theme):
27
+ effect: str | None = None
28
+ """An animated background from effects.py, e.g. "rain"."""
29
+
30
+
31
+ _THEME_KEYS = {f.name for f in fields(PlexTheme)} - {"name", "ansi"}
32
+
33
+ # `terminal = true` themes start from these: the terminal's own background and
34
+ # text show through, lines are dim gray, and only the accent carries color.
35
+ _TERMINAL_BASE = {
36
+ "ansi": True,
37
+ "secondary": "ansi_bright_black",
38
+ "accent": "ansi_blue",
39
+ "warning": "ansi_yellow",
40
+ "error": "ansi_red",
41
+ "success": "ansi_green",
42
+ "foreground": "ansi_default",
43
+ "background": "ansi_default",
44
+ "surface": "ansi_default",
45
+ "panel": "ansi_default",
46
+ "boost": "ansi_default",
47
+ "dark": True,
48
+ }
49
+
50
+ _TERMINAL_VARIABLES = {
51
+ "ansi-background": "ansi_default",
52
+ "ansi-foreground": "ansi_default",
53
+ "border-blurred": "ansi_bright_black",
54
+ "input-cursor-background": "ansi_default",
55
+ "input-cursor-foreground": "ansi_default",
56
+ "input-cursor-text-style": "reverse",
57
+ "input-selection-background": "ansi_bright_black",
58
+ "input-selection-foreground": "ansi_default",
59
+ "screen-selection-background": "ansi_bright_black",
60
+ "screen-selection-foreground": "ansi_default",
61
+ "scrollbar": "ansi_bright_black",
62
+ "scrollbar-hover": "ansi_bright_black",
63
+ "scrollbar-active": "ansi_bright_black",
64
+ "scrollbar-background": "ansi_default",
65
+ "scrollbar-background-hover": "ansi_default",
66
+ "scrollbar-background-active": "ansi_default",
67
+ "scrollbar-corner-color": "ansi_default",
68
+ "footer-background": "ansi_default",
69
+ # Highlighted rows: accent-colored bold text instead of a filled bar.
70
+ "block-cursor-foreground": "$accent",
71
+ "block-cursor-background": "ansi_default",
72
+ "block-cursor-text-style": "bold",
73
+ "block-cursor-blurred-foreground": "$accent",
74
+ "block-cursor-blurred-background": "ansi_default",
75
+ "block-cursor-blurred-text-style": "none",
76
+ "block-hover-background": "ansi_default",
77
+ }
78
+
79
+
80
+ class ThemeError(Exception):
81
+ pass
82
+
83
+
84
+ def parse_theme(name: str, data: dict) -> PlexTheme:
85
+ """Build a Theme from the contents of one theme file."""
86
+ data = dict(data)
87
+ terminal = data.pop("terminal", False)
88
+ if not isinstance(terminal, bool):
89
+ raise ThemeError("`terminal` must be true or false")
90
+ unknown = set(data) - _THEME_KEYS
91
+ if unknown:
92
+ raise ThemeError(f"unknown key(s): {', '.join(sorted(unknown))}")
93
+ variables = data.pop("variables", {})
94
+ if not isinstance(variables, dict):
95
+ raise ThemeError("[variables] must be a table")
96
+ if data.get("effect") is not None and data["effect"] not in EFFECTS:
97
+ raise ThemeError(f"unknown effect {data['effect']!r}; available: {', '.join(sorted(EFFECTS))}")
98
+
99
+ values = {**_TERMINAL_BASE, **data} if terminal else data
100
+ if terminal:
101
+ variables = {**_TERMINAL_VARIABLES, **variables}
102
+ values.setdefault("primary", values.get("accent"))
103
+ if not values.get("primary"):
104
+ raise ThemeError("set `primary` or `accent`")
105
+ # "$accent" in the terminal defaults stands for the theme's accent color.
106
+ accent = values.get("accent") or values["primary"]
107
+ variables = {k: accent if v == "$accent" else str(v) for k, v in variables.items()}
108
+
109
+ try:
110
+ theme = PlexTheme(name=name, variables=variables, **values)
111
+ theme.to_color_system().generate() # rejects bad colors now, not mid-render
112
+ except Exception as e:
113
+ raise ThemeError(str(e)) from None
114
+ return theme
115
+
116
+
117
+ def ensure_user_themes_dir(folder: Path) -> None:
118
+ """Create the user's theme folder with a blank placeholder file that shows
119
+ where themes go. The placeholder is only added when the folder is new, so
120
+ deleting it sticks. A read-only home is not an error: plex just runs with
121
+ the bundled themes."""
122
+ if folder.is_dir():
123
+ return
124
+ try:
125
+ folder.mkdir(parents=True, exist_ok=True)
126
+ (folder / USER_THEMES_PLACEHOLDER).touch()
127
+ except OSError:
128
+ pass
129
+
130
+
131
+ def load_themes(user_dir: Path | None = None) -> tuple[list[PlexTheme], list[str]]:
132
+ """Return (themes, problems). Terminal themes first, then the rest, each A–Z;
133
+ themes with an animated effect go last. With no `user_dir`, the user's theme
134
+ folder is created first if it doesn't exist yet."""
135
+ if user_dir is None:
136
+ user_dir = USER_THEMES_DIR
137
+ ensure_user_themes_dir(user_dir)
138
+ found: dict[str, PlexTheme] = {}
139
+ problems: list[str] = []
140
+ for folder in (BUNDLED_THEMES_DIR, user_dir):
141
+ if not folder.is_dir():
142
+ continue
143
+ for path in sorted(folder.glob("*.toml")):
144
+ try:
145
+ with path.open("rb") as f:
146
+ found[path.stem] = parse_theme(path.stem, tomllib.load(f))
147
+ except (OSError, tomllib.TOMLDecodeError, ThemeError) as e:
148
+ problems.append(f"{path}: {e}")
149
+ themes = sorted(found.values(), key=lambda t: (t.effect is not None, not t.ansi, t.name))
150
+ return themes, problems