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/app.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
"""The plex full-screen chat app."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
from functools import partial
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Callable, Iterable
|
|
10
|
+
|
|
11
|
+
from textual import on, work
|
|
12
|
+
from textual.app import App, ComposeResult, SystemCommand
|
|
13
|
+
from textual.binding import Binding
|
|
14
|
+
from textual.containers import Horizontal, Vertical, VerticalScroll
|
|
15
|
+
from textual.content import Content
|
|
16
|
+
from textual.screen import Screen
|
|
17
|
+
from textual.widgets import Markdown, OptionList, Static
|
|
18
|
+
from textual.widgets.option_list import Option
|
|
19
|
+
from textual.worker import Worker
|
|
20
|
+
|
|
21
|
+
from .. import auth
|
|
22
|
+
from ..citations import footer_sources, for_display, normalize
|
|
23
|
+
from .. import turn
|
|
24
|
+
from ..client import AsyncClient, Source, api_error_message
|
|
25
|
+
from ..config import DEFAULT_THEME, EFFORTS, MODE_KEYS, SESSIONS_DIR, Settings, save_state
|
|
26
|
+
from ..render import fmt_cost, plural
|
|
27
|
+
from ..session import Session, Store, ago
|
|
28
|
+
from .screens import (ApiKeyScreen, ConfirmScreen, EffortScreen, HelpScreen,
|
|
29
|
+
ModelPalette, ReasoningScreen, ThemePalette, parse_reasoning)
|
|
30
|
+
from .commands import COMMANDS, lookup
|
|
31
|
+
from .backdrop import Backdrop
|
|
32
|
+
from .effects import BackdropScroll, BackdropVertical
|
|
33
|
+
from .themes import load_themes
|
|
34
|
+
from .widgets import AssistantMessage, CommandMenu, PromptInput, UserMessage, Welcome
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class StreamingView:
|
|
38
|
+
"""Shows a streaming answer in an AssistantMessage (a `turn.TurnView`)."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, msg: AssistantMessage) -> None:
|
|
41
|
+
self.msg = msg
|
|
42
|
+
# Created on the first chunk: stopping a never-run MarkdownStream raises CancelledError.
|
|
43
|
+
self.stream = None
|
|
44
|
+
|
|
45
|
+
async def delta(self, text: str) -> None:
|
|
46
|
+
if self.stream is None:
|
|
47
|
+
self.msg.answering()
|
|
48
|
+
self.stream = Markdown.get_stream(self.msg.markdown)
|
|
49
|
+
await asyncio.sleep(0) # let the stream task start
|
|
50
|
+
await self.stream.write(text)
|
|
51
|
+
|
|
52
|
+
def searching(self, queries: list[str]) -> None:
|
|
53
|
+
self.msg.set_status(turn.searching_status(queries))
|
|
54
|
+
|
|
55
|
+
def sources_found(self, sources: list[Source]) -> None:
|
|
56
|
+
if self.stream is None:
|
|
57
|
+
self.msg.set_status(f"Reading {len(sources)} sources")
|
|
58
|
+
|
|
59
|
+
async def stop(self) -> None:
|
|
60
|
+
if self.stream is not None:
|
|
61
|
+
await self.stream.stop()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PlexApp(App):
|
|
65
|
+
CSS_PATH = Path(__file__).with_name("app.tcss")
|
|
66
|
+
TITLE = "plex"
|
|
67
|
+
ENABLE_COMMAND_PALETTE = True
|
|
68
|
+
BINDINGS = [
|
|
69
|
+
Binding("ctrl+n", "new_chat", "New chat", priority=True),
|
|
70
|
+
Binding("ctrl+s", "toggle_sidebar", "History", priority=True),
|
|
71
|
+
Binding("ctrl+e", "pick_effort", "Preset", priority=True),
|
|
72
|
+
Binding("escape", "cancel", "Cancel", show=False),
|
|
73
|
+
Binding("f1", "help", "Help", show=False),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
def __init__(self, settings: Settings, api_key: str | None,
|
|
77
|
+
session: Session | None = None, store: Store | None = None,
|
|
78
|
+
client_factory=AsyncClient) -> None:
|
|
79
|
+
super().__init__()
|
|
80
|
+
self.settings = settings
|
|
81
|
+
self.store = store or Store(SESSIONS_DIR)
|
|
82
|
+
self.session = session or Session()
|
|
83
|
+
self._client_factory = client_factory
|
|
84
|
+
self.client = client_factory(api_key) if api_key else None
|
|
85
|
+
self._worker: Worker | None = None
|
|
86
|
+
self.is_busy = False # an answer is being written
|
|
87
|
+
self._links: list[str] = []
|
|
88
|
+
self._pending: str | None = None # question waiting for an API key
|
|
89
|
+
self._models: list[str] | None = None # /v1/models, fetched on first /model
|
|
90
|
+
self.backdrop = Backdrop(self, "#main, #chat, Welcome") # the theme's animated background
|
|
91
|
+
|
|
92
|
+
# --- layout --------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def compose(self) -> ComposeResult:
|
|
95
|
+
with Horizontal(id="body"):
|
|
96
|
+
with Vertical(id="sidebar"):
|
|
97
|
+
yield Static(Content.from_markup("[b]History[/] [dim]ctrl+s[/]"), id="sidebar-title")
|
|
98
|
+
yield OptionList(id="sessions")
|
|
99
|
+
with BackdropVertical(id="main"):
|
|
100
|
+
yield BackdropScroll(id="chat")
|
|
101
|
+
yield CommandMenu(id="menu")
|
|
102
|
+
with Vertical(id="prompt-box"):
|
|
103
|
+
yield PromptInput(id="prompt", placeholder="Ask anything… (/ for commands)")
|
|
104
|
+
with Horizontal(id="statusbar"):
|
|
105
|
+
yield Static(id="status-left")
|
|
106
|
+
yield Static(id="status-right")
|
|
107
|
+
|
|
108
|
+
async def on_mount(self) -> None:
|
|
109
|
+
self.backdrop.start()
|
|
110
|
+
self.setup_themes()
|
|
111
|
+
self.backdrop.apply(self.current_theme)
|
|
112
|
+
self.theme_changed_signal.subscribe(self, self._on_theme_changed)
|
|
113
|
+
prompt = self.query_one(PromptInput)
|
|
114
|
+
prompt.menu = self.query_one(CommandMenu)
|
|
115
|
+
prompt.past_messages = lambda: [t.user for t in self.session.turns]
|
|
116
|
+
self.query_one(CommandMenu).display = False
|
|
117
|
+
self.query_one("#sidebar").display = False
|
|
118
|
+
self.query_one("#chat").anchor()
|
|
119
|
+
await self.show_session(self.session)
|
|
120
|
+
prompt.focus()
|
|
121
|
+
if self.client is None:
|
|
122
|
+
self.ask_for_key()
|
|
123
|
+
|
|
124
|
+
def setup_themes(self) -> None:
|
|
125
|
+
"""Offer only the themes from theme files (see themes.py), in their order."""
|
|
126
|
+
themes, problems = load_themes()
|
|
127
|
+
if themes: # without any, Textual's own themes stay
|
|
128
|
+
for name in list(self.available_themes):
|
|
129
|
+
self.unregister_theme(name)
|
|
130
|
+
for theme in themes:
|
|
131
|
+
self.register_theme(theme)
|
|
132
|
+
names = list(self.available_themes)
|
|
133
|
+
self.theme = next(n for n in (self.settings.theme, DEFAULT_THEME, *names) if n in names)
|
|
134
|
+
if problems:
|
|
135
|
+
self.notify("\n".join(problems), title="Some themes were skipped",
|
|
136
|
+
severity="warning", timeout=15)
|
|
137
|
+
|
|
138
|
+
def watch_app_focus(self, focused: bool) -> None:
|
|
139
|
+
self.backdrop.focus_changed()
|
|
140
|
+
|
|
141
|
+
def _on_theme_changed(self, theme) -> None:
|
|
142
|
+
# Text styled with theme colors ($accent etc.) keeps the old colors until redrawn.
|
|
143
|
+
for widget in self.screen_stack[0].query("*"):
|
|
144
|
+
widget.refresh()
|
|
145
|
+
self.backdrop.apply(theme)
|
|
146
|
+
if isinstance(self.screen, ThemePalette):
|
|
147
|
+
return # previewing; saved once the picker closes
|
|
148
|
+
self.save_theme()
|
|
149
|
+
|
|
150
|
+
def save_theme(self) -> None:
|
|
151
|
+
if self.settings.theme != self.theme:
|
|
152
|
+
self.settings.theme = self.theme
|
|
153
|
+
save_state(self.settings, ("theme",))
|
|
154
|
+
|
|
155
|
+
def action_change_theme(self) -> None:
|
|
156
|
+
self.push_screen(ThemePalette(), lambda _: self.save_theme())
|
|
157
|
+
|
|
158
|
+
# --- status / sidebar ------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
def refresh_status(self) -> None:
|
|
161
|
+
s = self.settings
|
|
162
|
+
# Distinct glyphs: ◆ effort preset, ● manually selected model (as model:reasoning).
|
|
163
|
+
if s.is_preset:
|
|
164
|
+
mode = Content.from_markup("[$accent b]◆[/] [b]$e[/]", e=s.effort)
|
|
165
|
+
if s.seen_model: # the model that last served this preset, from past answers
|
|
166
|
+
mode += Content.from_markup(" [dim]($m)[/]", m=s.seen_model)
|
|
167
|
+
else:
|
|
168
|
+
mode = Content.from_markup("[$accent b]●[/] [b]$m[/]", m=s.model)
|
|
169
|
+
if s.reasoning:
|
|
170
|
+
mode += Content.from_markup("[dim]:[/][b]$r[/]", r=s.reasoning)
|
|
171
|
+
mode += Content.from_markup(" [dim]search[/] $v", v="on" if s.search else "off")
|
|
172
|
+
title = self.session.title or "New chat"
|
|
173
|
+
mode += Content.from_markup(" [dim]│[/] $t", t=title)
|
|
174
|
+
self.query_one("#status-left", Static).update(mode)
|
|
175
|
+
for welcome in self.query(Welcome):
|
|
176
|
+
welcome.refresh()
|
|
177
|
+
right = Content.from_markup(
|
|
178
|
+
"[dim]$c · $n ctrl+s history · / commands[/]",
|
|
179
|
+
c=fmt_cost(self.session.total_cost), n=plural(len(self.session.turns), "turn"))
|
|
180
|
+
if self.is_busy:
|
|
181
|
+
right = Content.from_markup("[$warning]esc[/] [dim]cancel[/] ") + right
|
|
182
|
+
self.query_one("#status-right", Static).update(right)
|
|
183
|
+
|
|
184
|
+
def refresh_sidebar(self) -> None:
|
|
185
|
+
lst = self.query_one("#sessions", OptionList)
|
|
186
|
+
lst.clear_options()
|
|
187
|
+
infos = self.store.list()
|
|
188
|
+
for info in infos:
|
|
189
|
+
label = Content.from_markup("$t\n[dim]$a · $n · $c[/]", t=info.title,
|
|
190
|
+
a=ago(info.updated_at), n=plural(info.turns, "turn"),
|
|
191
|
+
c=fmt_cost(info.cost))
|
|
192
|
+
lst.add_option(Option(label, id=info.id))
|
|
193
|
+
if not infos:
|
|
194
|
+
lst.add_option(Option(Content.from_markup("[dim]No conversations yet[/]"), disabled=True))
|
|
195
|
+
else:
|
|
196
|
+
ids = [i.id for i in infos]
|
|
197
|
+
lst.highlighted = ids.index(self.session.id) if self.session.id in ids else 0
|
|
198
|
+
|
|
199
|
+
async def show_session(self, session: Session) -> None:
|
|
200
|
+
self.session = session
|
|
201
|
+
self.query_one(PromptInput).reset_recall()
|
|
202
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
203
|
+
await chat.remove_children()
|
|
204
|
+
self._links.clear()
|
|
205
|
+
# On the welcome screen the slash menu floats over the chat (see app.tcss)
|
|
206
|
+
# instead of shrinking it, so the centered logo stays put.
|
|
207
|
+
self.query_one("#main").set_class(not session.turns, "-welcome")
|
|
208
|
+
if not session.turns:
|
|
209
|
+
await chat.mount(Welcome(self.settings))
|
|
210
|
+
for t in session.turns:
|
|
211
|
+
text, srcs = for_display(t.assistant, t.sources)
|
|
212
|
+
msg = AssistantMessage(t.model or "", text)
|
|
213
|
+
await chat.mount_all([UserMessage(t.user), msg])
|
|
214
|
+
msg.finish(srcs, fmt_cost(t.cost), self._register_links(srcs))
|
|
215
|
+
chat.scroll_end(animate=False)
|
|
216
|
+
self.refresh_status()
|
|
217
|
+
self.refresh_sidebar()
|
|
218
|
+
|
|
219
|
+
def _register_links(self, sources) -> list[int]:
|
|
220
|
+
ids = []
|
|
221
|
+
for s in sources:
|
|
222
|
+
self._links.append(s.url)
|
|
223
|
+
ids.append(len(self._links) - 1)
|
|
224
|
+
return ids
|
|
225
|
+
|
|
226
|
+
def action_open_link(self, index: int) -> None:
|
|
227
|
+
if 0 <= index < len(self._links):
|
|
228
|
+
self.open_url(self._links[index])
|
|
229
|
+
|
|
230
|
+
# --- prompt ------------------------------------------------------------------
|
|
231
|
+
|
|
232
|
+
@on(PromptInput.Changed, "#prompt")
|
|
233
|
+
def _prompt_changed(self, event: PromptInput.Changed) -> None:
|
|
234
|
+
text = event.text_area.text
|
|
235
|
+
menu = self.query_one(CommandMenu)
|
|
236
|
+
if text.startswith("/") and " " not in text and "\n" not in text:
|
|
237
|
+
menu.display = menu.filter(text[1:])
|
|
238
|
+
else:
|
|
239
|
+
menu.display = False
|
|
240
|
+
|
|
241
|
+
@on(CommandMenu.OptionSelected, "#menu")
|
|
242
|
+
def _menu_clicked(self, event: CommandMenu.OptionSelected) -> None:
|
|
243
|
+
prompt = self.query_one(PromptInput)
|
|
244
|
+
prompt.text = f"/{event.option.id} "
|
|
245
|
+
prompt.move_cursor(prompt.document.end)
|
|
246
|
+
prompt.focus()
|
|
247
|
+
|
|
248
|
+
@on(PromptInput.Submitted)
|
|
249
|
+
async def _submitted(self, event: PromptInput.Submitted) -> None:
|
|
250
|
+
text = event.text.strip()
|
|
251
|
+
prompt = self.query_one(PromptInput)
|
|
252
|
+
self.query_one(CommandMenu).display = False
|
|
253
|
+
if not text:
|
|
254
|
+
return
|
|
255
|
+
if text.startswith("/"):
|
|
256
|
+
prompt.text = ""
|
|
257
|
+
await self.run_command(text)
|
|
258
|
+
return
|
|
259
|
+
if self.is_busy:
|
|
260
|
+
self.notify("Still answering — press esc to cancel.", severity="warning")
|
|
261
|
+
return
|
|
262
|
+
prompt.text = ""
|
|
263
|
+
prompt.reset_recall()
|
|
264
|
+
if self.client is None:
|
|
265
|
+
self._pending = text
|
|
266
|
+
self.ask_for_key()
|
|
267
|
+
return
|
|
268
|
+
self._worker = self.ask(text)
|
|
269
|
+
|
|
270
|
+
# --- asking ------------------------------------------------------------------
|
|
271
|
+
|
|
272
|
+
@work(exclusive=True, group="chat")
|
|
273
|
+
async def ask(self, question: str) -> None:
|
|
274
|
+
session, settings = self.session, self.settings
|
|
275
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
276
|
+
for w in chat.query(Welcome):
|
|
277
|
+
await w.remove()
|
|
278
|
+
self.query_one("#main").remove_class("-welcome")
|
|
279
|
+
msg = AssistantMessage(settings.label)
|
|
280
|
+
self.is_busy = True
|
|
281
|
+
try:
|
|
282
|
+
await self._ask(question, session, settings, chat, msg)
|
|
283
|
+
finally:
|
|
284
|
+
self.is_busy = False
|
|
285
|
+
self.refresh_status()
|
|
286
|
+
|
|
287
|
+
async def _ask(self, question: str, session: Session, settings: Settings,
|
|
288
|
+
chat: VerticalScroll, msg: AssistantMessage) -> None:
|
|
289
|
+
await chat.mount_all([UserMessage(question), msg])
|
|
290
|
+
chat.scroll_end(animate=False)
|
|
291
|
+
msg.start()
|
|
292
|
+
self.refresh_status()
|
|
293
|
+
|
|
294
|
+
view = StreamingView(msg)
|
|
295
|
+
try:
|
|
296
|
+
done = await turn.arun(self.client.stream_turn(session.input_for(question), settings), view)
|
|
297
|
+
except asyncio.CancelledError:
|
|
298
|
+
await view.stop()
|
|
299
|
+
msg.interrupted()
|
|
300
|
+
raise
|
|
301
|
+
except Exception as e: # the API failed the turn, or SDK / network errors
|
|
302
|
+
await view.stop()
|
|
303
|
+
err = turn.turn_error(e) or turn.TurnError(f"{type(e).__name__}: {e}")
|
|
304
|
+
msg.fail(err.message)
|
|
305
|
+
self.refresh_status()
|
|
306
|
+
if err.auth:
|
|
307
|
+
self._pending = question
|
|
308
|
+
self.ask_for_key("That key was rejected (401).")
|
|
309
|
+
return
|
|
310
|
+
await view.stop()
|
|
311
|
+
|
|
312
|
+
text, srcs = for_display(done.text, done.sources)
|
|
313
|
+
if text != msg.markdown.source:
|
|
314
|
+
await msg.markdown.update(text)
|
|
315
|
+
meta = " · ".join(x for x in (fmt_cost(done.cost), f"{msg.elapsed:.1f}s", done.model) if x)
|
|
316
|
+
msg.finish(srcs, meta, self._register_links(srcs))
|
|
317
|
+
turn.complete(session, settings, question, done)
|
|
318
|
+
try:
|
|
319
|
+
self.store.save(session)
|
|
320
|
+
except OSError as e:
|
|
321
|
+
self.notify(f"Could not save conversation: {e}", severity="error")
|
|
322
|
+
self.refresh_status()
|
|
323
|
+
self.refresh_sidebar()
|
|
324
|
+
|
|
325
|
+
def action_cancel(self) -> None:
|
|
326
|
+
if self.query_one(CommandMenu).display:
|
|
327
|
+
self.query_one(CommandMenu).display = False
|
|
328
|
+
elif self.is_busy:
|
|
329
|
+
self._worker.cancel()
|
|
330
|
+
elif self.query_one("#sidebar").display:
|
|
331
|
+
self.action_toggle_sidebar()
|
|
332
|
+
|
|
333
|
+
# --- API key -------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
def ask_for_key(self, reason: str = "") -> None:
|
|
336
|
+
def done(key: str | None) -> None:
|
|
337
|
+
if not key:
|
|
338
|
+
if self.client is None:
|
|
339
|
+
self.notify("No API key — use /login to add one.", severity="warning")
|
|
340
|
+
return
|
|
341
|
+
try:
|
|
342
|
+
path = auth.set_key(key)
|
|
343
|
+
except (OSError, ValueError) as e:
|
|
344
|
+
self.notify(f"Could not save key: {e}", severity="error")
|
|
345
|
+
return
|
|
346
|
+
self.client = self._client_factory(key)
|
|
347
|
+
self._models = None # another key may see other models
|
|
348
|
+
self.notify(f"Key saved to {path}")
|
|
349
|
+
if self._pending:
|
|
350
|
+
q, self._pending = self._pending, None
|
|
351
|
+
self._worker = self.ask(q)
|
|
352
|
+
|
|
353
|
+
self.push_screen(ApiKeyScreen(reason), done)
|
|
354
|
+
|
|
355
|
+
# --- actions & commands ------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
async def action_new_chat(self) -> None:
|
|
358
|
+
if self.is_busy:
|
|
359
|
+
self._worker.cancel()
|
|
360
|
+
await self.show_session(Session())
|
|
361
|
+
self.query_one(PromptInput).focus()
|
|
362
|
+
|
|
363
|
+
def action_toggle_sidebar(self) -> None:
|
|
364
|
+
bar = self.query_one("#sidebar")
|
|
365
|
+
bar.display = not bar.display
|
|
366
|
+
if bar.display:
|
|
367
|
+
self.refresh_sidebar()
|
|
368
|
+
self.query_one("#sessions").focus()
|
|
369
|
+
else:
|
|
370
|
+
self.query_one(PromptInput).focus()
|
|
371
|
+
|
|
372
|
+
@on(OptionList.OptionSelected, "#sessions")
|
|
373
|
+
async def _session_picked(self, event: OptionList.OptionSelected) -> None:
|
|
374
|
+
if event.option.id is None:
|
|
375
|
+
return
|
|
376
|
+
if self.is_busy:
|
|
377
|
+
self.notify("Wait for the answer to finish (or press esc).", severity="warning")
|
|
378
|
+
return
|
|
379
|
+
if event.option.id != self.session.id:
|
|
380
|
+
try:
|
|
381
|
+
await self.show_session(self.store.load(event.option.id))
|
|
382
|
+
except (OSError, ValueError, KeyError, TypeError) as e:
|
|
383
|
+
self.notify(f"Could not open conversation: {e}", severity="error")
|
|
384
|
+
return
|
|
385
|
+
self.query_one("#sidebar").display = False
|
|
386
|
+
self.query_one(PromptInput).focus()
|
|
387
|
+
|
|
388
|
+
def action_pick_model_effort(self) -> None:
|
|
389
|
+
"""Reasoning effort picker for the manually selected model."""
|
|
390
|
+
if not self._pick_model_first(self.action_pick_model_effort):
|
|
391
|
+
self.push_screen(ReasoningScreen(self.settings.model, self.settings.reasoning, self.set_reasoning))
|
|
392
|
+
|
|
393
|
+
def _pick_model_first(self, then: Callable[[], None]) -> bool:
|
|
394
|
+
"""In preset mode there is no model to set a reasoning effort for: open the model
|
|
395
|
+
list, run `then` once a model is picked, and return True."""
|
|
396
|
+
if not self.settings.is_preset:
|
|
397
|
+
return False
|
|
398
|
+
self.notify("Pick a model first; model effort applies to a specific model.")
|
|
399
|
+
self.action_pick_model(then=then)
|
|
400
|
+
return True
|
|
401
|
+
|
|
402
|
+
def action_pick_effort(self) -> None:
|
|
403
|
+
"""Effort presets; choosing one drops a manually selected model."""
|
|
404
|
+
def chosen(effort: str | None) -> None:
|
|
405
|
+
if effort:
|
|
406
|
+
self.set_effort(effort)
|
|
407
|
+
|
|
408
|
+
self.push_screen(EffortScreen(self.settings.effort, self.settings.seen), chosen)
|
|
409
|
+
|
|
410
|
+
def set_effort(self, effort: str) -> None:
|
|
411
|
+
self.settings.use_preset(effort)
|
|
412
|
+
save_state(self.settings, MODE_KEYS)
|
|
413
|
+
self.refresh_status()
|
|
414
|
+
self.notify(f"Effort: {effort}")
|
|
415
|
+
|
|
416
|
+
def set_reasoning(self, level: str | None) -> None:
|
|
417
|
+
self.settings.set_reasoning(level)
|
|
418
|
+
save_state(self.settings, MODE_KEYS)
|
|
419
|
+
self.refresh_status()
|
|
420
|
+
self.notify(f"Reasoning: {level or 'model default'}")
|
|
421
|
+
|
|
422
|
+
@work(exclusive=True, group="models")
|
|
423
|
+
async def action_pick_model(self, then: Callable[[], None] | None = None) -> None:
|
|
424
|
+
"""Model list; `then` runs once a model (not the preset entry) is picked."""
|
|
425
|
+
if self.client is None:
|
|
426
|
+
self.ask_for_key("Set an API key to list models.")
|
|
427
|
+
return
|
|
428
|
+
if self._models is None:
|
|
429
|
+
try:
|
|
430
|
+
self._models = await self.client.list_models()
|
|
431
|
+
except Exception as e: # SDK/network errors
|
|
432
|
+
msg = api_error_message(e) or f"{type(e).__name__}: {e}"
|
|
433
|
+
self.notify(f"Could not load models. {msg}", severity="error")
|
|
434
|
+
return
|
|
435
|
+
self.push_screen(ModelPalette(self._models, self.settings.model, then))
|
|
436
|
+
|
|
437
|
+
def set_model(self, model: str | None) -> None:
|
|
438
|
+
self.settings.use_model(model)
|
|
439
|
+
save_state(self.settings, MODE_KEYS)
|
|
440
|
+
self.refresh_status()
|
|
441
|
+
self.notify(f"Model: {model or 'preset ' + self.settings.effort}")
|
|
442
|
+
|
|
443
|
+
def action_help(self) -> None:
|
|
444
|
+
self.push_screen(HelpScreen())
|
|
445
|
+
|
|
446
|
+
async def run_command(self, line: str) -> None:
|
|
447
|
+
name, _, arg = line[1:].partition(" ")
|
|
448
|
+
command = lookup(name)
|
|
449
|
+
if command is None:
|
|
450
|
+
self.notify(f"Unknown command /{name.lower()}. Type / to see commands.", severity="error")
|
|
451
|
+
return
|
|
452
|
+
result = getattr(self, command.handler)(arg.strip())
|
|
453
|
+
if inspect.isawaitable(result):
|
|
454
|
+
await result
|
|
455
|
+
|
|
456
|
+
# One handler per entry in commands.COMMANDS; each gets the text after the command.
|
|
457
|
+
|
|
458
|
+
def cmd_quit(self, arg: str) -> None:
|
|
459
|
+
self.exit()
|
|
460
|
+
|
|
461
|
+
async def cmd_new(self, arg: str) -> None:
|
|
462
|
+
await self.action_new_chat()
|
|
463
|
+
|
|
464
|
+
def cmd_history(self, arg: str) -> None:
|
|
465
|
+
self.action_toggle_sidebar()
|
|
466
|
+
|
|
467
|
+
def cmd_effort(self, arg: str) -> None:
|
|
468
|
+
if not arg:
|
|
469
|
+
self.action_pick_model_effort()
|
|
470
|
+
return
|
|
471
|
+
try:
|
|
472
|
+
level = parse_reasoning(arg)
|
|
473
|
+
except ValueError as e:
|
|
474
|
+
self.notify(str(e), severity="error")
|
|
475
|
+
return
|
|
476
|
+
if not self._pick_model_first(lambda: self.set_reasoning(level)):
|
|
477
|
+
self.set_reasoning(level)
|
|
478
|
+
|
|
479
|
+
def cmd_preset(self, arg: str) -> None:
|
|
480
|
+
if arg in EFFORTS:
|
|
481
|
+
self.set_effort(arg)
|
|
482
|
+
elif arg:
|
|
483
|
+
self.notify(f"Unknown effort. Choose: {', '.join(EFFORTS)}", severity="error")
|
|
484
|
+
else:
|
|
485
|
+
self.action_pick_effort()
|
|
486
|
+
|
|
487
|
+
def cmd_model(self, arg: str) -> None:
|
|
488
|
+
if arg:
|
|
489
|
+
self.set_model(None if arg in ("off", "none", "preset") else arg)
|
|
490
|
+
else:
|
|
491
|
+
self.action_pick_model()
|
|
492
|
+
|
|
493
|
+
def cmd_search(self, arg: str) -> None:
|
|
494
|
+
s = self.settings
|
|
495
|
+
s.search = (arg == "on") if arg in ("on", "off") else not s.search
|
|
496
|
+
save_state(s, ("search",))
|
|
497
|
+
self.refresh_status()
|
|
498
|
+
self.notify(f"Web search {'on' if s.search else 'off'}")
|
|
499
|
+
|
|
500
|
+
def cmd_sources(self, arg: str) -> None:
|
|
501
|
+
last = self.session.last
|
|
502
|
+
if not last or not last.sources:
|
|
503
|
+
self.notify("No sources for the last answer.")
|
|
504
|
+
return
|
|
505
|
+
lines = [f"[{x.id}] {x.title or x.url}\n {x.url}" for x in footer_sources(last.assistant, last.sources)]
|
|
506
|
+
self.notify("\n".join(lines), title="Sources", timeout=15)
|
|
507
|
+
|
|
508
|
+
def cmd_copy(self, arg: str) -> None:
|
|
509
|
+
last = self.session.last
|
|
510
|
+
if not last:
|
|
511
|
+
self.notify("Nothing to copy yet.")
|
|
512
|
+
return
|
|
513
|
+
self.copy_to_clipboard(normalize(last.assistant, last.sources))
|
|
514
|
+
self.notify("Copied the last answer.")
|
|
515
|
+
|
|
516
|
+
def cmd_rename(self, arg: str) -> None:
|
|
517
|
+
if not arg:
|
|
518
|
+
self.notify("Usage: /rename <title>")
|
|
519
|
+
elif not self.session.turns:
|
|
520
|
+
self.notify("Send a message first.")
|
|
521
|
+
else:
|
|
522
|
+
old, self.session.title = self.session.title, arg
|
|
523
|
+
try:
|
|
524
|
+
self.store.save(self.session)
|
|
525
|
+
except OSError as e:
|
|
526
|
+
self.session.title = old
|
|
527
|
+
self.notify(f"Could not rename: {e}", severity="error")
|
|
528
|
+
return
|
|
529
|
+
self.refresh_status()
|
|
530
|
+
self.refresh_sidebar()
|
|
531
|
+
|
|
532
|
+
def cmd_delete(self, arg: str) -> None:
|
|
533
|
+
if not self.session.turns:
|
|
534
|
+
self.notify("Nothing to delete.")
|
|
535
|
+
return
|
|
536
|
+
|
|
537
|
+
async def confirmed(yes: bool | None) -> None:
|
|
538
|
+
if yes:
|
|
539
|
+
try:
|
|
540
|
+
self.store.delete(self.session.id)
|
|
541
|
+
except OSError as e:
|
|
542
|
+
self.notify(f"Could not delete: {e}", severity="error")
|
|
543
|
+
return
|
|
544
|
+
if self.is_busy: # the answer being written belongs to this conversation
|
|
545
|
+
self._worker.cancel()
|
|
546
|
+
await self.show_session(Session())
|
|
547
|
+
self.notify("Conversation deleted.")
|
|
548
|
+
|
|
549
|
+
self.push_screen(ConfirmScreen(f"Delete “{self.session.title}”?"), confirmed)
|
|
550
|
+
|
|
551
|
+
def cmd_theme(self, arg: str) -> None:
|
|
552
|
+
self.action_change_theme()
|
|
553
|
+
|
|
554
|
+
def cmd_login(self, arg: str) -> None:
|
|
555
|
+
self.ask_for_key()
|
|
556
|
+
|
|
557
|
+
def cmd_help(self, arg: str) -> None:
|
|
558
|
+
self.action_help()
|
|
559
|
+
|
|
560
|
+
def get_system_commands(self, screen: Screen) -> Iterable[SystemCommand]:
|
|
561
|
+
for c in COMMANDS:
|
|
562
|
+
if c.palette:
|
|
563
|
+
title, help = c.palette
|
|
564
|
+
yield SystemCommand(title, help, partial(self.call_later, self.run_command, f"/{c.name}"))
|
|
565
|
+
yield from super().get_system_commands(screen)
|