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,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-plex
3
+ Version: 0.9.0
4
+ Summary: Chat with Perplexity from your terminal (Agent API).
5
+ Author-email: Ilia Petrov-Komotskii <ilia@inkedkettle.games>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ManeFunction/agent-plex
8
+ Project-URL: Repository, https://github.com/ManeFunction/agent-plex
9
+ Project-URL: Issues, https://github.com/ManeFunction/agent-plex/issues
10
+ Project-URL: Changelog, https://github.com/ManeFunction/agent-plex/blob/main/CHANGELOG.md
11
+ Keywords: perplexity,chat,cli,tui,terminal,ai
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Environment :: Console
15
+ Classifier: Topic :: Utilities
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: perplexityai>=0.47
20
+ Requires-Dist: rich>=13
21
+ Requires-Dist: textual<9,>=8
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8; extra == "dev"
24
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # agent-plex
28
+
29
+ A fast, good-looking [Perplexity](https://www.perplexity.ai/) chat for your terminal: researched answers with sources, streamed live, with chat history.
30
+
31
+ It uses Perplexity's [Agent API](https://docs.perplexity.ai/) (`/v1/agent`). Perplexity subscription plan is **not** required. The package is called `agent-plex`; the command it installs is `plex`.
32
+
33
+ > The API is billed per use with an API key. A Perplexity Pro subscription doesn't cover it. A typical `fast` answer costs about $0.002, and plex shows the cost under every answer.
34
+
35
+ You can use it as a full-featured shell with a familiar UI and commands, similar to other popular agentic CLIs like Claude Code or OpenCode.
36
+ ![](https://raw.githubusercontent.com/wiki/ManeFunction/agent-plex/shell-ui.png)
37
+
38
+ Or you can get quick answers right in the terminal, without interrupting your work or switching tools.
39
+ ![](https://raw.githubusercontent.com/wiki/ManeFunction/agent-plex/in-place-answer.png)
40
+
41
+ The main difference with plex is that it's built for quick use, spending minimal time and tokens.
42
+ Big harnesses use more than 10K tokens on every first message just to "set up" the model.
43
+ Perplexity is mainly a search-and-summarize engine, and plex is your door to it with nothing in between.
44
+
45
+ > [!IMPORTANT]
46
+ > Because of this design, Perplexity doesn't store your context on the server side,
47
+ > and every new message in a chat resends the whole history, which increases the cost.
48
+ > It's not meant for long conversations.
49
+
50
+ ## Features
51
+
52
+ - Chat UI with streamed answers, inline source citations and the cost of every answer.
53
+ - One-shot mode for scripts: `plex "question"`, and piped input is appended to the question.
54
+ - Effort presets from `fast` to `ultra`, or pick a specific model and its reasoning effort.
55
+ - Saved conversations: reopen the last one, search by id or title, rename, delete, or clear everything.
56
+ - History sidebar, command palette, `/commands` with tab completion, copy the last answer.
57
+ - Themes: ones that keep your terminal's own colors, a few full-color ones, and your own as a small TOML file.
58
+ - Your API key is stored in a file only you can read, or taken from `PERPLEXITY_API_KEY`.
59
+
60
+ ## Installation
61
+
62
+ **agent-plex** is available from a variety of sources.
63
+ `pip` or `brew` is recommended, because they have a convenient way to manage updates automatically.
64
+ It needs Python 3.11 or newer.
65
+
66
+ 1) **pip (Recommended for everyone with a Python environment)**
67
+ - You can check if you have Python installed by running `python --version` in the Terminal or cmd.
68
+ - For Mac and Linux users, there is a high chance that you already have Python installed on your system.
69
+ - For Windows users, you can download Python from the [official website](https://www.python.org/downloads/).
70
+ - After confirmation, install **agent-plex** through the [PyPI](https://pypi.org/project/agent-plex) package
71
+ manager, typing `pip install agent-plex` in the Terminal. For Mac users, you may need to use `pip3`
72
+ instead of `pip`. The package is called `agent-plex`; the command it installs is `plex`.
73
+ - Verify the installation with `plex --version`.
74
+ - You are perfect, you can use the app with `plex` from any folder in your system.
75
+ 2) **brew (Recommended for Mac and Linux users)**
76
+ - Type `brew tap manefunction/tap` in your Terminal to add my custom tap (app source) to your brew sources,
77
+ if you haven't already.
78
+ - Type `brew install agent-plex` to install the application itself.
79
+ - Verify the installation with `plex --version`.
80
+ - You are perfect, you can use the app with `plex` from any folder in your system.
81
+ 3) **Python package (manual installation, for advanced users)**
82
+ - Clone the repository or download the source code from GitHub.
83
+ - Go to the folder with the code in your Terminal.
84
+ - Run `pip install .` to install `agent-plex` to your system.
85
+ - Run `plex --version` to verify the install.
86
+
87
+ ## Usage
88
+
89
+ ### Log in
90
+
91
+ ```sh
92
+ plex auth login # paste a key from https://www.perplexity.ai/account/api
93
+ ```
94
+
95
+ This works like opencode: the key is stored in `~/.local/share/plex/auth.json` with mode `600`. You can also just start `plex`, and it will ask for a key the first time. `PERPLEXITY_API_KEY` in the environment takes precedence over the stored key.
96
+
97
+ | Command | |
98
+ |---|---|
99
+ | `plex auth status` | shows which key is in use (masked) |
100
+ | `plex auth logout` | removes the stored key |
101
+
102
+ ### Chat
103
+
104
+ ```sh
105
+ plex # open the chat
106
+ plex -r # reopen the last conversation
107
+ plex -o "python" # reopen a conversation by id or title text
108
+ plex --history # list saved conversations
109
+ plex --clear # delete all saved conversations (asks y/n first)
110
+
111
+ plex "what's new in Python 3.15?" # one-shot: print the answer and exit
112
+ git diff | plex "review this" # piped input is appended to the question
113
+ plex -p high "compare uv and pip" # pick an effort preset
114
+ plex -m openai/gpt-6-luna -e high "…" # a specific model and its effort
115
+ ```
116
+
117
+ ### Keys
118
+
119
+ | Key | Action |
120
+ |---|---|
121
+ | `enter` | send |
122
+ | `shift+enter` / `alt+enter` / `ctrl+j` | new line |
123
+ | `↑` / `↓` on an empty prompt | recall earlier questions |
124
+ | `esc` | cancel the answer being written |
125
+ | `ctrl+n` | new chat |
126
+ | `ctrl+s` | history sidebar |
127
+ | `ctrl+e` | effort preset picker |
128
+ | `ctrl+p` | command palette |
129
+ | `ctrl+q` | quit |
130
+
131
+ ### Commands
132
+
133
+ Type `/` to see suggestions, then press `tab` to complete.
134
+
135
+ | Command | |
136
+ |---|---|
137
+ | `/new`, `/clear` | new conversation |
138
+ | `/history` | browse history |
139
+ | `/preset [level]` | effort preset: `fast` · `low` · `medium` · `high` · `xhigh` · `ultra` (drops a selected model) |
140
+ | `/effort [level]` | effort for the selected model: `minimal` · `low` · `medium` · `high` · `xhigh` · `max` · `default` (in preset mode, asks for a model first) |
141
+ | `/model [id]` / `/model off` | pick a model from the list your key can use, or give an id (e.g. `perplexity/sonar`) / go back to presets |
142
+ | `/search [on\|off]` | toggle web search |
143
+ | `/sources` | sources of the last answer |
144
+ | `/copy` | copy the last answer |
145
+ | `/rename <title>` | rename this conversation |
146
+ | `/delete` | delete this conversation |
147
+ | `/theme` | change the theme |
148
+ | `/login` | set the API key |
149
+ | `/help` | keys and commands |
150
+ | `/quit`, `/exit` | exit |
151
+
152
+ ### Files
153
+
154
+ | Path | |
155
+ |---|---|
156
+ | `~/.local/share/plex/auth.json` | API key (0600) |
157
+ | `~/.local/share/plex/sessions/*.json` | conversations, saved after every answer; ones not updated in 64 days (`keep_days`) are deleted when plex starts |
158
+ | `~/.local/share/plex/state.json` | last used effort, model, reasoning effort, search and theme, plus the model last seen for each effort level |
159
+ | `~/.config/plex/config.toml` | optional defaults (see below) |
160
+
161
+ ```toml
162
+ # ~/.config/plex/config.toml
163
+ effort = "fast"
164
+ # model = "perplexity/sonar"
165
+ # reasoning = "medium" # reasoning effort in model mode: minimal … max
166
+ # search = true
167
+ # theme = "terminal"
168
+ # max_steps = 5 # research steps in model mode
169
+ # keep_days = 64 # delete conversations not updated in this many days; 0 keeps them forever
170
+ # instructions = "..." # custom system prompt
171
+ ```
172
+
173
+ ### Themes
174
+
175
+ `terminal` (the default), `terminal-coral`, `terminal-green` and `terminal-violet` keep your terminal's own background, text and palette and add a single accent color. `terminal` takes its accent from the terminal palette too, so it fits any color scheme, light or dark. `matrix` is `terminal-green` with dim digital rain falling behind the chat. The rain never runs through text and pauses while the terminal window is in the background. The others are `tokyo-night`, `catppuccin-mocha`, `dracula` and `gruvbox`.
176
+
177
+ Each theme is one TOML file, named after the theme. The bundled ones live in [`src/plex_cli/themes/`](https://github.com/ManeFunction/agent-plex/tree/main/src/plex_cli/themes). To add your own, put a file in `~/.config/plex/themes/` (`$XDG_CONFIG_HOME/plex/themes/` if that's set, on Linux and macOS alike). plex creates this folder the first time you open the chat UI (one-shot questions don't), with an empty `PUT_YOUR_THEMES_HERE` file in it. Your themes are loaded alongside the bundled ones and show up in `/theme` the next time plex starts. A file with the same name as a bundled theme replaces it. Files with mistakes are skipped, and plex tells you why at startup.
178
+
179
+ A terminal-style theme needs just an accent:
180
+
181
+ ```toml
182
+ # ~/.config/plex/themes/terminal-teal.toml
183
+ terminal = true # use the terminal's own background, text and palette
184
+ accent = "#2AA198" # any hex color, or a terminal color like "ansi_cyan"
185
+ # effect = "rain" # optional animated background (the one `matrix` uses)
186
+ ```
187
+
188
+ A full-color theme sets its own colors (`primary` is required, the rest are optional):
189
+
190
+ ```toml
191
+ # ~/.config/plex/themes/my-theme.toml
192
+ primary = "#88C0D0" # highlights
193
+ secondary = "#81A1C1" # your messages, key hints
194
+ accent = "#EBCB8B" # answer bar, focused input
195
+ warning = "#EBCB8B"
196
+ error = "#BF616A"
197
+ success = "#A3BE8C"
198
+ foreground = "#D8DEE9" # text
199
+ background = "#2E3440"
200
+ surface = "#3B4252" # sidebar, menus, dialogs
201
+ panel = "#434C5E" # borders
202
+ dark = true # false for light themes
203
+
204
+ [variables] # optional fine-tuning with Textual theme variables
205
+ border = "#88C0D0"
206
+ ```
207
+
208
+ ## Credits
209
+
210
+ Built on the [Perplexity Python SDK](https://github.com/perplexityai/perplexity-py), [Textual](https://textual.textualize.io/) and [Rich](https://github.com/Textualize/rich).
211
+ This is an unofficial client and is not affiliated with Perplexity AI.
212
+
213
+ ## Repository info
214
+
215
+ This repo follows the [Conventional Commits](https://www.conventionalcommits.org/) specification.
216
+
217
+ [![GitHub release (latest by date)](https://img.shields.io/github/v/release/ManeFunction/agent-plex)](https://github.com/ManeFunction/agent-plex/releases/latest)
218
+ [![GitHub All Releases](https://img.shields.io/github/downloads/ManeFunction/agent-plex/total)](https://github.com/ManeFunction/agent-plex/releases)
219
+ [![PyPI version](https://img.shields.io/pypi/v/agent-plex)](https://pypi.org/project/agent-plex/)
220
+ [![PyPI downloads](https://img.shields.io/pypi/dm/agent-plex)](https://pypi.org/project/agent-plex/)
221
+ [![GitHub Sponsors](https://img.shields.io/github/sponsors/ManeFunction?label=Sponsor&logo=GitHubSponsors&style=flat)](https://github.com/sponsors/ManeFunction)
@@ -0,0 +1,34 @@
1
+ agent_plex-0.9.0.dist-info/licenses/LICENSE,sha256=4ns8nl0KWTDY69GjkDm3TnKKnec1MeAGioDzBPi-HNw,1105
2
+ plex_cli/__init__.py,sha256=H9NWRZb7NbeRRPLP_V1fARmLNXranorVM-OOY-8_2ug,22
3
+ plex_cli/auth.py,sha256=gD3DCLo2WwsjxPj5XFhLpMrkKuIlkpJD4ipmnnCxcaw,2250
4
+ plex_cli/citations.py,sha256=z2Bvj90CzyytviLxZ9ytv9o4rpLeawpZThsHAfz_Ucw,1334
5
+ plex_cli/cli.py,sha256=3pTI7aH-KkZWO-ah6AsGMG6WRwnPKlxEXgHSp1m7CY0,8869
6
+ plex_cli/client.py,sha256=QPmko6AhjAvmzHLNcNj072WxsPPjZkVXFfK7J7caZQs,8959
7
+ plex_cli/config.py,sha256=Fs9e1Jx3CWe55M8xzg2FNEDLIvY6ZLDSXDbQ9YDgBq8,8277
8
+ plex_cli/files.py,sha256=bNC1ZJsltxTH86JivOFw5opFFx5efbtcM8ddWD34rRs,1393
9
+ plex_cli/render.py,sha256=IH2a2n-bW-j9qP13c06tf1y-97hlMU_K7EQ7_q3bzxI,5119
10
+ plex_cli/session.py,sha256=FfADyFrwXPUeaJ73jLsdabrEBhREU5Gv3Dwvgbj8FKs,9510
11
+ plex_cli/turn.py,sha256=JI6fP2Hw9jGI-TTH_78ozTY-DGbWoYg1ZaR5D_Bq2wQ,3146
12
+ plex_cli/themes/catppuccin-mocha.toml,sha256=rWXBet3xC5gACrI7JN5qAM6YCtu-4g_bTS_TDgpn2oQ,558
13
+ plex_cli/themes/dracula.toml,sha256=dIGwQ0YVWdsa3dNTL_RLLFmdrbVUP2pxWI8Z_LDFOgE,291
14
+ plex_cli/themes/gruvbox.toml,sha256=fOq8c9MGYX6vv-3Gp1LHi5yGSF4GEBBZ8r4NstAmFvk,385
15
+ plex_cli/themes/matrix.toml,sha256=syfrdkSTHQNa2Ak9CfEPrCtuoPA_lrOL_jFZXzsTEYw,257
16
+ plex_cli/themes/terminal-coral.toml,sha256=9KrXqoW9n10UVQDN6zTgQWBnsIAmMjpFcVu_-kidb30,108
17
+ plex_cli/themes/terminal-green.toml,sha256=wi68vNvEJn-FCfgcn2iPKSCWec2K6SFs-ZEsjBqf34A,206
18
+ plex_cli/themes/terminal-violet.toml,sha256=RbJi48dVv1AlrX3Zwjxe4vZs9av5-WIWQh37U_oxUIA,109
19
+ plex_cli/themes/terminal.toml,sha256=t0tCarh8VmoRxkYHdxpehpSvLAc5gVfSU58ICDuq5h4,172
20
+ plex_cli/themes/tokyo-night.toml,sha256=xo9W8I95kZBu6nsn3BXSCJFZPVFwlOggOILXy3pu4Fc,320
21
+ plex_cli/tui/__init__.py,sha256=qZC3TtcVfjegaWicdmHXv8mXKgDHBRiMlvibK2bIj4I,48
22
+ plex_cli/tui/app.py,sha256=XR457NIwErHONNdutivc3jede2sIpxExE66q7u2pFnA,23208
23
+ plex_cli/tui/app.tcss,sha256=Zif8zqdFCV7eGC_UY2lPoSeEZ99o37JXqouojm98PqI,4708
24
+ plex_cli/tui/backdrop.py,sha256=HsLOXXu7oqDE64b5S2BZdt32W45T0Bx0JaNsaKaDmos,2211
25
+ plex_cli/tui/commands.py,sha256=AMv5xI6DMqwLjneC-94RmpjYT6ofBnX7xq_JYd4MgnU,2534
26
+ plex_cli/tui/effects.py,sha256=9lvWxr8NkehVKm6Ic57PHZHwrIh225uoFiI0h1k7ln8,7174
27
+ plex_cli/tui/screens.py,sha256=GzKNdznOzM34AQJNrRyIxyIVpHbQknUQi78pHtKtTI0,11701
28
+ plex_cli/tui/themes.py,sha256=V8EkjecXSxLWNmGfHWWbtGEoD3Cjy0FQcG0VhsvJrGk,5663
29
+ plex_cli/tui/widgets.py,sha256=RrS4nVwssxTMF_XcCCuygrwQcFt67beLNUXtD5hnz_U,9850
30
+ agent_plex-0.9.0.dist-info/METADATA,sha256=x34Lx3f9Rzw4kX6ExMc4Z-85CI8elOWqZCeMaNdcfJ4,11418
31
+ agent_plex-0.9.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
32
+ agent_plex-0.9.0.dist-info/entry_points.txt,sha256=yJRpT9xCUQXYI1XC6I_g5D3VYb0Kc-yL1aWE-_pdcis,43
33
+ agent_plex-0.9.0.dist-info/top_level.txt,sha256=aRQ9XWJUUNLFdLUxfmYZtQYkFsBJL0x90-V9ZUtIcpE,9
34
+ agent_plex-0.9.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ plex = plex_cli.cli:main
@@ -0,0 +1,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2026 Ilia Petrov-Komotskii (Mane Function)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ plex_cli
plex_cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.9.0"
plex_cli/auth.py ADDED
@@ -0,0 +1,80 @@
1
+ """API keys: which one plex uses, and storing one opencode-style in a 0600 JSON file.
2
+
3
+ ~/.local/share/plex/auth.json
4
+ {"perplexity": {"type": "api", "key": "pplx-..."}}
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+
13
+ from .config import DATA_DIR
14
+ from .files import atomic_write_json
15
+
16
+ AUTH_FILE = DATA_DIR / "auth.json"
17
+ PROVIDER = "perplexity"
18
+
19
+
20
+ def _path(path: Path | None) -> Path:
21
+ return path if path is not None else AUTH_FILE
22
+
23
+
24
+ def _read(path: Path) -> dict:
25
+ try:
26
+ data = json.loads(path.read_text())
27
+ return data if isinstance(data, dict) else {}
28
+ except (OSError, ValueError):
29
+ return {}
30
+
31
+
32
+ def get_key(path: Path | None = None) -> str | None:
33
+ path = _path(path)
34
+ entry = _read(path).get(PROVIDER) or {}
35
+ key = entry.get("key") if isinstance(entry, dict) else None
36
+ return key or None
37
+
38
+
39
+ def set_key(key: str, path: Path | None = None) -> Path:
40
+ path = _path(path)
41
+ key = key.strip()
42
+ if not key:
43
+ raise ValueError("empty API key")
44
+ data = _read(path)
45
+ data[PROVIDER] = {"type": "api", "key": key}
46
+ atomic_write_json(path, data, private=True)
47
+ return path
48
+
49
+
50
+ def remove_key(path: Path | None = None) -> bool:
51
+ path = _path(path)
52
+ data = _read(path)
53
+ if PROVIDER not in data:
54
+ return False
55
+ del data[PROVIDER]
56
+ if data: # keep other providers untouched
57
+ atomic_write_json(path, data, private=True)
58
+ else:
59
+ path.unlink(missing_ok=True)
60
+ return True
61
+
62
+
63
+ def mask(key: str) -> str:
64
+ return key[:5] + "…" + key[-4:] if len(key) > 12 else "…" * 3
65
+
66
+
67
+ def api_key_source(file_cfg: dict) -> tuple[str, str] | None:
68
+ """(key, source) for the key plex will use, or None. Sources, in order of precedence:
69
+ "env" (PERPLEXITY_API_KEY), "auth" (auth.json, `plex auth login`), "config" (config.toml)."""
70
+ for source, key in (("env", lambda: os.environ.get("PERPLEXITY_API_KEY")),
71
+ ("auth", get_key),
72
+ ("config", lambda: file_cfg.get("api_key"))):
73
+ if k := key():
74
+ return k, source
75
+ return None
76
+
77
+
78
+ def resolve_api_key(file_cfg: dict) -> str | None:
79
+ found = api_key_source(file_cfg)
80
+ return found[0] if found else None
plex_cli/citations.py ADDED
@@ -0,0 +1,42 @@
1
+ """Inline citation markers ([1], [web:1]) -> sources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .client import Source
8
+
9
+ MARKER = re.compile(r"\[(?:web:)?(\d+)\]")
10
+
11
+
12
+ def cited_ids(text: str) -> list[int]:
13
+ """Ids in order of first appearance."""
14
+ seen: dict[int, None] = {}
15
+ for m in MARKER.finditer(text):
16
+ seen.setdefault(int(m.group(1)), None)
17
+ return list(seen)
18
+
19
+
20
+ def normalize(text: str, sources: dict[int, Source]) -> str:
21
+ """Rewrite [web:N] to [N] for known sources; leave everything else untouched."""
22
+
23
+ def sub(m: re.Match) -> str:
24
+ n = int(m.group(1))
25
+ return f"[{n}]" if n in sources else m.group(0)
26
+
27
+ return MARKER.sub(sub, text)
28
+
29
+
30
+ def footer_sources(text: str, sources: dict[int, Source]) -> list[Source]:
31
+ """Sources to list under the answer: cited ones first (in citation order);
32
+ if the answer cites none, all sources sorted by id."""
33
+ cited = [sources[i] for i in cited_ids(text) if i in sources]
34
+ if cited:
35
+ return cited
36
+ return [sources[i] for i in sorted(sources)]
37
+
38
+
39
+ def for_display(text: str, sources: dict[int, Source]) -> tuple[str, list[Source]]:
40
+ """An answer as it is shown: its text with markers normalized, and the sources listed under it."""
41
+ text = normalize(text, sources)
42
+ return text, footer_sources(text, sources)
plex_cli/cli.py ADDED
@@ -0,0 +1,243 @@
1
+ """`plex` entry point: TUI (default), one-shot questions, `plex auth ...`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import getpass
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__, auth
11
+ from . import turn
12
+ from .client import Client
13
+ from .config import (
14
+ EFFORTS, REASONING, SESSIONS_DIR, ConfigError, Settings,
15
+ load_file_config, load_state, settings_from,
16
+ )
17
+ from .render import Renderer
18
+ from .session import Session, Store, ago
19
+
20
+
21
+ def run_turn(client: Client, session: Session, settings: Settings,
22
+ r: Renderer, question: str) -> bool:
23
+ """Ask one question, stream the answer, commit it on success."""
24
+ r.begin()
25
+ try:
26
+ done = turn.run(client.stream_turn(session.input_for(question), settings), r)
27
+ except KeyboardInterrupt:
28
+ r.interrupted()
29
+ return False
30
+ except Exception as e: # the API failed the turn, or SDK / network errors
31
+ if (err := turn.turn_error(e)) is None:
32
+ raise
33
+ r.error(err.message)
34
+ return False
35
+ turn.complete(session, settings, question, done)
36
+ r.finish(done, session.total_cost if len(session.turns) > 1 else None)
37
+ return True
38
+
39
+
40
+ # --- plex auth ----------------------------------------------------------------
41
+
42
+ def cmd_auth(argv: list[str]) -> int:
43
+ p = argparse.ArgumentParser(prog="plex auth", description="Manage the stored Perplexity API key.")
44
+ sub = p.add_subparsers(dest="action", required=True)
45
+ sub.add_parser("login", help="store an API key")
46
+ sub.add_parser("logout", help="remove the stored key")
47
+ sub.add_parser("status", help="show which key is used")
48
+ a = p.parse_args(argv)
49
+
50
+ if a.action == "login":
51
+ print("Get a key at https://www.perplexity.ai/account/api")
52
+ try:
53
+ key = getpass.getpass("API key: ") if sys.stdin.isatty() else sys.stdin.readline()
54
+ except (EOFError, KeyboardInterrupt):
55
+ print()
56
+ return 1
57
+ try:
58
+ path = auth.set_key(key)
59
+ except (OSError, ValueError) as e:
60
+ print(f"error: {e}", file=sys.stderr)
61
+ return 1
62
+ print(f"Saved {auth.mask(key.strip())} to {path}")
63
+ return 0
64
+ if a.action == "logout":
65
+ print("Removed stored key." if auth.remove_key() else "No stored key.")
66
+ return 0
67
+ # status
68
+ try:
69
+ found = auth.api_key_source(load_file_config())
70
+ except ConfigError as e:
71
+ print(f"error: {e}", file=sys.stderr)
72
+ return 2
73
+ if found is None:
74
+ print("No API key. Run `plex auth login`.")
75
+ return 1
76
+ k, source = found
77
+ print({
78
+ "env": f"Using PERPLEXITY_API_KEY from environment: {auth.mask(k)}",
79
+ "auth": f"Using stored key {auth.mask(k)} ({auth.AUTH_FILE})",
80
+ "config": f"Using api_key from config.toml: {auth.mask(k)}",
81
+ }[source])
82
+ return 0
83
+
84
+
85
+ def cmd_history() -> int:
86
+ infos = Store(SESSIONS_DIR).list()
87
+ if not infos:
88
+ print("No conversations yet.")
89
+ for i in infos:
90
+ print(f"{i.id} {ago(i.updated_at):>9} {i.turns:>3} turns {i.title}")
91
+ return 0
92
+
93
+
94
+ def cmd_clear(store: Store | None = None) -> int:
95
+ store = store or Store(SESSIONS_DIR)
96
+ n = store.count()
97
+ if not n:
98
+ print("No conversations yet.")
99
+ return 0
100
+ try:
101
+ answer = input(f"Delete all {n} conversation{'s' if n != 1 else ''}? This cannot be undone. (y/n) ")
102
+ except (EOFError, KeyboardInterrupt):
103
+ print()
104
+ answer = ""
105
+ if answer.strip().lower() not in ("y", "yes"):
106
+ print("Cancelled.")
107
+ return 1
108
+ try:
109
+ removed = store.clear()
110
+ except OSError as e:
111
+ print(f"error: {e}", file=sys.stderr)
112
+ return 1
113
+ print(f"Deleted {removed} conversation{'s' if removed != 1 else ''}.")
114
+ return 0
115
+
116
+
117
+ def _newer_unreadable(store: Store, sid: str | None) -> Path | None:
118
+ """The newest file `store.list()` skipped, if it is newer than conversation `sid`."""
119
+ def mtime(p: Path) -> float:
120
+ try:
121
+ return p.stat().st_mtime
122
+ except OSError:
123
+ return 0.0
124
+
125
+ if not store.unreadable:
126
+ return None
127
+ newest = max(store.unreadable, key=mtime)
128
+ return newest if sid is None or mtime(newest) > mtime(store.path(sid)) else None
129
+
130
+
131
+ # --- main -------------------------------------------------------------------------
132
+
133
+ def parse_args(argv: list[str] | None) -> argparse.Namespace:
134
+ p = argparse.ArgumentParser(
135
+ prog="plex",
136
+ description="Chat with Perplexity in your terminal. Run without arguments for the chat UI.",
137
+ epilog="Other commands: `plex auth login|logout|status`.",
138
+ )
139
+ p.add_argument("question", nargs="*", help="ask once, print the answer and exit (piped stdin is appended)")
140
+ p.add_argument("-p", "--preset", choices=EFFORTS, help="research effort preset (drops a selected model)")
141
+ p.add_argument("-e", "--effort", choices=(*REASONING, "default"), metavar="LEVEL",
142
+ help=f"reasoning effort for the selected model: {', '.join(REASONING)}, default")
143
+ p.add_argument("-m", "--model", help="specific model, e.g. perplexity/sonar")
144
+ p.add_argument("-s", "--system", help="custom system instructions")
145
+ p.add_argument("--no-search", action="store_true", help="disable web search")
146
+ p.add_argument("--raw", action="store_true", help="plain text output in one-shot mode")
147
+ p.add_argument("-r", "--resume", action="store_true", help="reopen the last conversation")
148
+ p.add_argument("-o", "--open", metavar="ID|TEXT", help="reopen a conversation by id or title")
149
+ p.add_argument("--history", action="store_true", help="list saved conversations")
150
+ p.add_argument("--clear", action="store_true", help="delete all saved conversations (asks first)")
151
+ p.add_argument("-V", "--version", action="version", version=f"plex v{__version__}")
152
+ return p.parse_args(argv)
153
+
154
+
155
+ def main(argv: list[str] | None = None) -> int:
156
+ argv = sys.argv[1:] if argv is None else argv
157
+ if argv[:1] == ["auth"]:
158
+ return cmd_auth(argv[1:])
159
+
160
+ args = parse_args(argv)
161
+ if args.history:
162
+ return cmd_history()
163
+ if args.clear:
164
+ return cmd_clear()
165
+ r = Renderer(raw=True if args.raw else None)
166
+ try:
167
+ file_cfg = load_file_config()
168
+ settings = settings_from(file_cfg, load_state())
169
+ except ConfigError as e:
170
+ r.error(str(e))
171
+ return 2
172
+ api_key = auth.resolve_api_key(file_cfg)
173
+
174
+ if args.preset and args.model:
175
+ r.error("-p picks a preset and -m a model; use -e to set the model's effort")
176
+ return 2
177
+ if args.model:
178
+ settings.use_model(args.model)
179
+ if args.preset:
180
+ settings.use_preset(args.preset)
181
+ if args.effort:
182
+ try:
183
+ settings.set_reasoning(None if args.effort == "default" else args.effort)
184
+ except ValueError as e:
185
+ r.error(f"--effort: {e} (add -m <id>)")
186
+ return 2
187
+ if args.system:
188
+ settings.instructions = args.system
189
+ if args.no_search:
190
+ settings.search = False
191
+
192
+ store = Store(SESSIONS_DIR)
193
+ store.prune(settings.keep_days)
194
+ session = Session()
195
+ if args.resume or args.open:
196
+ if args.resume:
197
+ infos = store.list()
198
+ sid = infos[0].id if infos else None
199
+ if newer := _newer_unreadable(store, sid):
200
+ r.warning(f"skipped {newer.name}, which can't be read; "
201
+ + ("resuming the newest readable conversation" if sid else "nothing else to resume"))
202
+ else:
203
+ sid = store.find(args.open)
204
+ if not sid:
205
+ r.error("no matching conversation" if args.open else "no conversations yet")
206
+ return 2
207
+ try:
208
+ session = store.load(sid)
209
+ except (OSError, ValueError, KeyError, TypeError) as e:
210
+ r.error(f"cannot load {sid!r}: {e}")
211
+ return 2
212
+
213
+ question = " ".join(args.question).strip()
214
+ if not sys.stdin.isatty():
215
+ piped = sys.stdin.read().strip()
216
+ if piped:
217
+ question = f"{question}\n\n{piped}" if question else piped
218
+
219
+ if question: # one-shot
220
+ if not api_key:
221
+ r.error("No API key. Run `plex auth login` or set PERPLEXITY_API_KEY.")
222
+ return 2
223
+ ok = run_turn(Client(api_key), session, settings, r, question)
224
+ if ok and (args.resume or args.open):
225
+ try:
226
+ store.save(session)
227
+ except OSError as e:
228
+ r.error(f"could not save the conversation: {e}")
229
+ return 1
230
+ return 0 if ok else 1
231
+
232
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
233
+ r.error("no question given (the chat UI needs a terminal)")
234
+ return 2
235
+
236
+ from .tui import PlexApp
237
+
238
+ PlexApp(settings, api_key, session=session, store=store).run()
239
+ return 0
240
+
241
+
242
+ if __name__ == "__main__":
243
+ sys.exit(main())