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/client.py ADDED
@@ -0,0 +1,256 @@
1
+ """Thin wrapper over the Perplexity Agent API. The only module that knows the SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, AsyncIterator, Callable, Iterable, Iterator
7
+
8
+ from .config import Settings
9
+
10
+
11
+ @dataclass
12
+ class Source:
13
+ id: int
14
+ url: str
15
+ title: str = ""
16
+ date: str | None = None
17
+
18
+
19
+ @dataclass
20
+ class TextDelta:
21
+ text: str
22
+
23
+
24
+ @dataclass
25
+ class Searching:
26
+ queries: list[str]
27
+
28
+
29
+ @dataclass
30
+ class SourcesFound:
31
+ sources: list[Source]
32
+
33
+
34
+ @dataclass
35
+ class Done:
36
+ text: str
37
+ sources: dict[int, Source]
38
+ cost: float | None
39
+ model: str | None = None
40
+ effort: str | None = None # the effort version that ran, e.g. "fast@2026-11-11.0"
41
+
42
+
43
+ Event = TextDelta | Searching | SourcesFound | Done
44
+
45
+
46
+ class TurnFailed(Exception):
47
+ """The API reported a failure mid-stream (response.failed)."""
48
+
49
+
50
+ def _get(obj: Any, name: str, default: Any = None) -> Any:
51
+ """`obj.name` or `obj[name]`. Stream events arrive as SDK models, but fields the SDK doesn't
52
+ type yet (`effort`, the `response.reasoning.*` events) can come through as plain dicts."""
53
+ if isinstance(obj, dict):
54
+ return obj.get(name, default)
55
+ return getattr(obj, name, default)
56
+
57
+
58
+ def _sources(results: Iterable[Any] | None) -> list[Source]:
59
+ out = []
60
+ for r in results or ():
61
+ rid, url = _get(r, "id"), _get(r, "url")
62
+ if rid is None or not url:
63
+ continue
64
+ out.append(Source(id=int(rid), url=url, title=_get(r, "title") or "", date=_get(r, "date")))
65
+ return out
66
+
67
+
68
+ def build_request(history: list[dict], settings: Settings) -> dict:
69
+ """Keyword arguments for `client.responses.create`."""
70
+ req: dict[str, Any] = {
71
+ "input": history,
72
+ "instructions": settings.instructions,
73
+ "stream": True,
74
+ }
75
+ extra: dict[str, Any] = {}
76
+ if not settings.is_preset:
77
+ req["model"] = settings.model
78
+ req["max_steps"] = settings.max_steps
79
+ if settings.reasoning:
80
+ extra["reasoning"] = {"effort": settings.reasoning}
81
+ if settings.search:
82
+ req["tools"] = [{"type": "web_search"}]
83
+ else:
84
+ # The API takes the preset as `effort`. Sent through extra_body, which works whether or
85
+ # not the installed SDK version has `effort` as a typed parameter.
86
+ extra["effort"] = settings.effort
87
+ if not settings.search:
88
+ # Preset tools can't be removed; this stops the model from calling them.
89
+ extra["max_tool_calls"] = 0
90
+ if extra:
91
+ req["extra_body"] = extra
92
+ return req
93
+
94
+
95
+ class StreamParser:
96
+ """Feeds raw SDK stream events, returns plex events. `done` is set once finished."""
97
+
98
+ def __init__(self) -> None:
99
+ self.streamed: list[str] = []
100
+ self.sources: dict[int, Source] = {}
101
+ self.done: Done | None = None
102
+
103
+ def _add(self, found: list[Source]) -> list[Event]:
104
+ new = [s for s in found if s.id not in self.sources]
105
+ for s in found:
106
+ self.sources[s.id] = s
107
+ return [SourcesFound(new)] if new else []
108
+
109
+ def feed(self, ev: Any) -> list[Event]:
110
+ kind = _get(ev, "type")
111
+ if kind == "response.output_text.delta":
112
+ if delta := _get(ev, "delta") or "":
113
+ self.streamed.append(delta)
114
+ return [TextDelta(delta)]
115
+ elif kind == "response.reasoning.search_queries":
116
+ return [Searching(list(_get(ev, "queries") or []))]
117
+ elif kind == "response.reasoning.search_results":
118
+ return self._add(_sources(_get(ev, "results")))
119
+ elif kind in ("response.output_item.added", "response.output_item.done"):
120
+ item = _get(ev, "item")
121
+ if _get(item, "type") == "search_results":
122
+ return self._add(_sources(_get(item, "results")))
123
+ elif kind == "response.failed":
124
+ raise TurnFailed(_get(_get(ev, "error"), "message") or "response failed")
125
+ elif kind == "response.completed":
126
+ self.done = self._completed(_get(ev, "response"))
127
+ return [self.done]
128
+ return []
129
+
130
+ def finish(self) -> Done:
131
+ """Called when the stream closes; synthesizes Done if none arrived."""
132
+ if self.done is None:
133
+ self.done = Done("".join(self.streamed), self.sources, None)
134
+ return self.done
135
+
136
+ def _completed(self, resp: Any) -> Done:
137
+ if _get(resp, "status") == "failed":
138
+ raise TurnFailed(_get(_get(resp, "error"), "message") or "response failed")
139
+ text_parts: list[str] = []
140
+ for item in _get(resp, "output") or ():
141
+ t = _get(item, "type")
142
+ if t == "search_results":
143
+ for s in _sources(_get(item, "results")):
144
+ self.sources[s.id] = s
145
+ elif t == "message":
146
+ for part in _get(item, "content") or ():
147
+ if _get(part, "type") == "output_text":
148
+ text_parts.append(_get(part, "text") or "")
149
+ usage = _get(resp, "usage")
150
+ cost = _get(_get(usage, "cost"), "total_cost")
151
+ return Done(
152
+ text="".join(text_parts) or "".join(self.streamed),
153
+ sources=self.sources,
154
+ cost=float(cost) if cost is not None else None,
155
+ model=_get(resp, "model"),
156
+ effort=_get(resp, "effort") or _get(resp, "preset"),
157
+ )
158
+
159
+
160
+ def parse_stream(stream: Iterable[Any]) -> Iterator[Event]:
161
+ """Translate raw SDK stream events into plex events. Ends with exactly one Done."""
162
+ p = StreamParser()
163
+ for ev in stream:
164
+ yield from p.feed(ev)
165
+ if p.done:
166
+ return
167
+ yield p.finish()
168
+
169
+
170
+ async def aparse_stream(stream: Any) -> AsyncIterator[Event]:
171
+ p = StreamParser()
172
+ async for ev in stream:
173
+ for out in p.feed(ev):
174
+ yield out
175
+ if p.done:
176
+ return
177
+ yield p.finish()
178
+
179
+
180
+ class Client:
181
+ """Synchronous client (one-shot mode)."""
182
+
183
+ def __init__(self, api_key: str, create: Callable[..., Iterable[Any]] | None = None):
184
+ if create is None:
185
+ from perplexity import Perplexity
186
+
187
+ create = Perplexity(api_key=api_key, max_retries=2).responses.create
188
+ self._create = create
189
+
190
+ def stream_turn(self, history: list[dict], settings: Settings) -> Iterator[Event]:
191
+ stream = self._create(**build_request(history, settings))
192
+ try:
193
+ yield from parse_stream(stream)
194
+ finally:
195
+ if callable(close := getattr(stream, "close", None)):
196
+ close()
197
+
198
+
199
+ class AsyncClient:
200
+ """Async client (TUI). `create` may be injected for tests."""
201
+
202
+ def __init__(self, api_key: str, create: Callable[..., Any] | None = None,
203
+ models: Callable[..., Any] | None = None):
204
+ sdk = None
205
+ if create is None or models is None:
206
+ from perplexity import AsyncPerplexity
207
+
208
+ sdk = AsyncPerplexity(api_key=api_key, max_retries=2)
209
+ self._create = create or sdk.responses.create
210
+ self._models = models or sdk.models.list
211
+
212
+ async def list_models(self) -> list[str]:
213
+ """Ids of the models this key can use in direct-model mode, sorted."""
214
+ resp = await self._models()
215
+ return sorted(i for m in _get(resp, "data") or () if (i := _get(m, "id")))
216
+
217
+ async def stream_turn(self, history: list[dict], settings: Settings) -> AsyncIterator[Event]:
218
+ stream = await self._create(**build_request(history, settings))
219
+ try:
220
+ async for ev in aparse_stream(stream):
221
+ yield ev
222
+ finally:
223
+ if callable(close := getattr(stream, "close", None)):
224
+ res = close()
225
+ if hasattr(res, "__await__"):
226
+ await res
227
+
228
+
229
+ def is_auth_error(e: BaseException) -> bool:
230
+ """The API rejected the key (401)."""
231
+ try:
232
+ import perplexity
233
+ except ImportError: # pragma: no cover
234
+ return False
235
+ return isinstance(e, perplexity.AuthenticationError)
236
+
237
+
238
+ def api_error_message(e: BaseException) -> str | None:
239
+ """Human message for SDK errors; None if `e` isn't one."""
240
+ try:
241
+ import perplexity
242
+ except ImportError: # pragma: no cover
243
+ return None
244
+ if isinstance(e, perplexity.AuthenticationError):
245
+ return "Authentication failed (401). Run `plex auth login` or use /login."
246
+ if isinstance(e, perplexity.RateLimitError):
247
+ return "Rate limited (429). Wait a moment and try again."
248
+ if isinstance(e, perplexity.APIStatusError):
249
+ if e.status_code == 402:
250
+ return "Out of API credits (402). Top up at https://www.perplexity.ai/account/api"
251
+ return f"API error {e.status_code}: {getattr(e, 'message', None) or e}"
252
+ if isinstance(e, perplexity.APIConnectionError):
253
+ detail = str(e).rstrip(".")
254
+ return "Connection error — check your network." + (
255
+ f" ({detail})" if detail.lower() != "connection error" else "")
256
+ return None
plex_cli/config.py ADDED
@@ -0,0 +1,223 @@
1
+ """Settings and persisted UI state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ import tomllib
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Iterable
12
+
13
+ from .files import atomic_write_json
14
+
15
+ EFFORTS = ("fast", "low", "medium", "high", "xhigh", "ultra")
16
+
17
+ EFFORT_INFO = {
18
+ "fast": "single quick search · cheapest (~$0.002)",
19
+ "low": "a few research steps",
20
+ "medium": "more thorough research",
21
+ "high": "deep research, slower",
22
+ "xhigh": "long multi-step research · expensive",
23
+ "ultra": "maximum effort · most expensive",
24
+ }
25
+
26
+ # Reasoning effort for a manually selected model (`reasoning.effort` in the API).
27
+ REASONING = ("minimal", "low", "medium", "high", "xhigh", "max")
28
+
29
+ REASONING_INFO = {
30
+ "minimal": "barely thinks · fastest",
31
+ "low": "light reasoning",
32
+ "medium": "balanced",
33
+ "high": "thinks longer",
34
+ "xhigh": "extended reasoning · slower",
35
+ "max": "maximum reasoning · slowest",
36
+ }
37
+
38
+ DEFAULT_THEME = "terminal"
39
+
40
+ # Saved conversations not updated for this many days are deleted at startup; 0 keeps them.
41
+ DEFAULT_KEEP_DAYS = 64
42
+
43
+ DEFAULT_INSTRUCTIONS = (
44
+ "You are a helpful research assistant answering in a terminal chat. "
45
+ "Be concise and use Markdown. When you use web sources, cite them inline "
46
+ "with square brackets containing the source index, e.g. [1] or [2]; "
47
+ "never group them like [1, 2] or [1-2]."
48
+ )
49
+
50
+
51
+ def _xdg(var: str, fallback: str) -> Path:
52
+ return Path(os.environ.get(var) or Path.home() / fallback)
53
+
54
+
55
+ CONFIG_FILE = _xdg("XDG_CONFIG_HOME", ".config") / "plex" / "config.toml"
56
+ DATA_DIR = _xdg("XDG_DATA_HOME", ".local/share") / "plex"
57
+ SESSIONS_DIR = DATA_DIR / "sessions"
58
+ STATE_FILE = DATA_DIR / "state.json"
59
+
60
+
61
+ # Settings fields kept in state.json between launches. The mode fields are saved together,
62
+ # since a reasoning level belongs to the model it was set for.
63
+ MODE_KEYS = ("effort", "model", "reasoning")
64
+ STATE_KEYS = (*MODE_KEYS, "search", "theme")
65
+
66
+
67
+ class ConfigError(Exception):
68
+ pass
69
+
70
+
71
+ @dataclass
72
+ class Settings:
73
+ """Per-request settings. `model` set means direct-model mode, else `effort` preset."""
74
+
75
+ effort: str = "fast"
76
+ model: str | None = None
77
+ reasoning: str | None = None # model mode only; None leaves it to the model's default
78
+ search: bool = True
79
+ instructions: str = DEFAULT_INSTRUCTIONS
80
+ max_steps: int = 5
81
+ theme: str = DEFAULT_THEME
82
+ keep_days: int = DEFAULT_KEEP_DAYS
83
+ # Last model seen serving each effort level: {level: {"model", "version", "at"}}.
84
+ seen: dict[str, dict] = field(default_factory=dict)
85
+
86
+ # --- mode transitions: the rules for preset mode vs direct-model mode live here ---
87
+
88
+ @property
89
+ def is_preset(self) -> bool:
90
+ """Perplexity picks the model for `effort`; otherwise `model` is used directly."""
91
+ return not self.model
92
+
93
+ def use_preset(self, effort: str) -> None:
94
+ """Switch to an effort preset; drops a selected model."""
95
+ if effort not in EFFORTS:
96
+ raise ValueError(f"unknown effort {effort!r}")
97
+ self.effort, self.model = effort, None
98
+
99
+ def use_model(self, model: str | None) -> None:
100
+ """Select a model directly (None goes back to presets). A new model starts from its
101
+ default reasoning level, since not every model supports every level."""
102
+ model = model or None
103
+ if model != self.model:
104
+ self.reasoning = None
105
+ self.model = model
106
+
107
+ def set_reasoning(self, level: str | None) -> None:
108
+ """Reasoning effort for the selected model; None leaves it to the model."""
109
+ if level is not None:
110
+ if level not in REASONING:
111
+ raise ValueError(f"unknown reasoning level {level!r}")
112
+ if self.is_preset:
113
+ raise ValueError("reasoning effort needs a selected model")
114
+ self.reasoning = level
115
+
116
+ def note_seen(self, effort: str | None, model: str | None, now: float | None = None) -> bool:
117
+ """Record which model served an effort level. `effort` is as the API reports it,
118
+ e.g. "fast@2026-11-11.0". Returns whether anything was recorded."""
119
+ level, _, version = (effort or "").partition("@")
120
+ if level not in EFFORTS or not model:
121
+ return False
122
+ self.seen[level] = {"model": model, "version": version or None, "at": now or time.time()}
123
+ return True
124
+
125
+ @property
126
+ def seen_model(self) -> str | None:
127
+ """In preset mode, the model last seen serving the current effort level."""
128
+ if not self.is_preset:
129
+ return None
130
+ return (self.seen.get(self.effort) or {}).get("model")
131
+
132
+ @property
133
+ def label(self) -> str:
134
+ if self.is_preset:
135
+ mode = self.effort
136
+ else:
137
+ mode = f"{self.model}:{self.reasoning}" if self.reasoning else self.model
138
+ return mode if self.search else f"{mode} · no search"
139
+
140
+
141
+ def load_file_config(path: Path = CONFIG_FILE) -> dict:
142
+ if not path.exists():
143
+ return {}
144
+ try:
145
+ return tomllib.loads(path.read_text())
146
+ except (OSError, tomllib.TOMLDecodeError) as e:
147
+ raise ConfigError(f"Cannot read {path}: {e}") from e
148
+
149
+
150
+ def _apply(s: Settings, cfg: dict, source: str) -> None:
151
+ if (e := cfg.get("effort")) is not None:
152
+ if e not in EFFORTS:
153
+ raise ConfigError(f"Invalid effort {e!r} in {source}; choose from {', '.join(EFFORTS)}")
154
+ s.effort = e
155
+ if "model" in cfg:
156
+ s.model = cfg["model"] or None
157
+ if "reasoning" in cfg:
158
+ r = cfg["reasoning"] or None
159
+ if r is not None and r not in REASONING:
160
+ raise ConfigError(f"Invalid reasoning {r!r} in {source}; choose from {', '.join(REASONING)}")
161
+ s.reasoning = r
162
+ if "search" in cfg:
163
+ if not isinstance(cfg["search"], bool):
164
+ raise ConfigError(f"Invalid search {cfg['search']!r} in {source}; use true or false")
165
+ s.search = cfg["search"]
166
+ if cfg.get("instructions"):
167
+ s.instructions = cfg["instructions"]
168
+ if "max_steps" in cfg:
169
+ try:
170
+ s.max_steps = int(cfg["max_steps"])
171
+ except (TypeError, ValueError):
172
+ raise ConfigError(f"Invalid max_steps {cfg['max_steps']!r} in {source}; use a whole number") from None
173
+ if cfg.get("theme"):
174
+ s.theme = str(cfg["theme"])
175
+ if "keep_days" in cfg:
176
+ k = cfg["keep_days"]
177
+ if isinstance(k, bool) or not isinstance(k, int) or k < 0:
178
+ raise ConfigError(f"Invalid keep_days {k!r} in {source}; use a whole number of days (0 keeps everything)")
179
+ s.keep_days = k
180
+
181
+
182
+ def settings_from(file_cfg: dict, state: dict | None = None) -> Settings:
183
+ """config.toml defaults, then last-used UI state on top."""
184
+ s = Settings()
185
+ _apply(s, file_cfg, "config")
186
+ if state:
187
+ for k in STATE_KEYS: # one by one, so a corrupt value doesn't drop the valid ones
188
+ if k in state:
189
+ try:
190
+ _apply(s, {k: state[k]}, "state")
191
+ except ConfigError:
192
+ pass
193
+ s.seen = _valid_seen(state.get("seen"))
194
+ return s
195
+
196
+
197
+ def _valid_seen(raw: object) -> dict[str, dict]:
198
+ if not isinstance(raw, dict):
199
+ return {}
200
+ return {k: v for k, v in raw.items()
201
+ if k in EFFORTS and isinstance(v, dict) and isinstance(v.get("model"), str)
202
+ and isinstance(v.get("at"), (int, float))}
203
+
204
+
205
+ def load_state(path: Path | None = None) -> dict:
206
+ try:
207
+ data = json.loads((path or STATE_FILE).read_text())
208
+ return data if isinstance(data, dict) else {}
209
+ except (OSError, ValueError):
210
+ return {}
211
+
212
+
213
+ def save_state(s: Settings, keys: Iterable[str] = STATE_KEYS, path: Path | None = None) -> None:
214
+ """Write the `keys` fields of `s` into the state file, keeping everything else in it.
215
+
216
+ Callers name only what the user just changed, so one-launch overrides from command-line
217
+ flags (`plex -m ...`, `--no-search`) are not saved along with it.
218
+ """
219
+ path = path or STATE_FILE
220
+ try: # in the private data folder, see Store.save
221
+ atomic_write_json(path, {**load_state(path), **{k: getattr(s, k) for k in keys}}, private=True)
222
+ except OSError:
223
+ pass # remembering the last-used settings is best effort
plex_cli/files.py ADDED
@@ -0,0 +1,33 @@
1
+ """Writing plex's own JSON files (auth, state, conversations) safely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ # What "private" means for plex's data: only the user can read the file or open its folder.
11
+ PRIVATE_FILE = 0o600
12
+ PRIVATE_DIR = 0o700
13
+
14
+
15
+ def atomic_write_json(path: Path, data: Any, private: bool = False) -> None:
16
+ """Write `data` to a temp file next to `path`, then rename it over `path`.
17
+
18
+ A crash mid-write leaves the old file intact. A `private` file gets PRIVATE_FILE
19
+ permissions, and its folder PRIVATE_DIR if it has to be created; otherwise both follow
20
+ the umask. Folders further up are always created with the umask.
21
+ """
22
+ path.parent.mkdir(parents=True, exist_ok=True, mode=PRIVATE_DIR if private else 0o777)
23
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") # per process: two plex instances may write at once
24
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, PRIVATE_FILE if private else 0o666)
25
+ try:
26
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
27
+ json.dump(data, f, ensure_ascii=False, indent=2)
28
+ if private:
29
+ os.chmod(tmp, PRIVATE_FILE) # O_CREAT's mode is masked by the umask, and ignored for an existing file
30
+ os.replace(tmp, path)
31
+ except BaseException:
32
+ tmp.unlink(missing_ok=True)
33
+ raise
plex_cli/render.py ADDED
@@ -0,0 +1,150 @@
1
+ """Terminal output: live Markdown for TTYs, plain text for pipes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+
8
+ from rich.console import Console, Group
9
+ from rich.live import Live
10
+ from rich.markdown import Markdown
11
+ from rich.spinner import Spinner
12
+ from rich.text import Text
13
+
14
+ from .citations import for_display
15
+ from .client import Done, Source
16
+ from .turn import searching_status
17
+
18
+
19
+ # C0/C1 control characters except tab and newline. Answers and source titles come from the
20
+ # API and from web pages; written raw, an ESC or OSC sequence would reach the terminal.
21
+ _CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
22
+
23
+
24
+ def plain(text: str) -> str:
25
+ """`text` without terminal control characters, for raw output."""
26
+ return _CONTROL.sub("", text)
27
+
28
+
29
+ def plural(n: int, word: str) -> str:
30
+ return f"{n} {word}" if n == 1 else f"{n} {word}s"
31
+
32
+
33
+ def fmt_cost(cost: float | None) -> str:
34
+ if cost is None:
35
+ return "?"
36
+ if cost == 0:
37
+ return "$0"
38
+ return f"${cost:.4f}" if cost < 1 else f"${cost:.2f}"
39
+
40
+
41
+ class Renderer:
42
+ """One instance per process; `begin()`..`finish()` per turn."""
43
+
44
+ def __init__(self, raw: bool | None = None):
45
+ self.console = Console(highlight=False)
46
+ self.err = Console(stderr=True, highlight=False)
47
+ self.raw = (not sys.stdout.isatty()) if raw is None else raw
48
+ self._live: Live | None = None
49
+ self._text = ""
50
+ self._status = "Thinking…"
51
+
52
+ # --- per-turn lifecycle ------------------------------------------------
53
+
54
+ def begin(self) -> None:
55
+ self._text, self._status = "", "Thinking…"
56
+ if not self.raw:
57
+ self._live = Live(
58
+ self._view(), console=self.console, transient=True,
59
+ refresh_per_second=12, vertical_overflow="crop",
60
+ )
61
+ self._live.start()
62
+
63
+ def searching(self, queries: list[str]) -> None:
64
+ self._status = searching_status(queries) + ("" if any(queries) else "…")
65
+ self._refresh()
66
+
67
+ def sources_found(self, sources: list[Source]) -> None:
68
+ if not self._text:
69
+ self._status = f"Reading {len(sources)} sources…"
70
+ self._refresh()
71
+
72
+ def delta(self, text: str) -> None:
73
+ self._text += text
74
+ if self.raw:
75
+ sys.stdout.write(plain(text))
76
+ sys.stdout.flush()
77
+ else:
78
+ self._refresh()
79
+
80
+ def finish(self, done: Done, session_total: float | None = None) -> None:
81
+ self._stop()
82
+ text, srcs = for_display(done.text, done.sources)
83
+ if self.raw:
84
+ if not self._text: # nothing streamed (e.g. text only in final response)
85
+ sys.stdout.write(plain(text))
86
+ sys.stdout.write("\n")
87
+ if srcs:
88
+ sys.stdout.write("\nSources:\n")
89
+ for s in srcs:
90
+ sys.stdout.write(plain(f"[{s.id}] {s.title} {s.url}").replace(" ", " ") + "\n")
91
+ sys.stdout.flush()
92
+ return
93
+ self.console.print(Markdown(text or "_(empty answer)_"))
94
+ if srcs:
95
+ self.print_sources(srcs)
96
+ meta = f"{fmt_cost(done.cost)}"
97
+ if session_total is not None:
98
+ meta += f" · session {fmt_cost(session_total)}"
99
+ if done.model:
100
+ meta += f" · {done.model}"
101
+ self.console.print(Text(meta, style="dim"))
102
+
103
+ def interrupted(self) -> None:
104
+ partial = self._text
105
+ self._stop()
106
+ if self.raw:
107
+ sys.stdout.write("\n[interrupted]\n")
108
+ return
109
+ if partial:
110
+ self.console.print(Markdown(partial))
111
+ self.console.print(Text("[interrupted]", style="yellow"))
112
+
113
+ def error(self, msg: str) -> None:
114
+ self._stop()
115
+ self.err.print(Text(f"error: {msg}", style="bold red"))
116
+
117
+ def warning(self, msg: str) -> None:
118
+ self.err.print(Text(f"warning: {msg}", style="yellow"))
119
+
120
+ def print_sources(self, srcs: list[Source]) -> None:
121
+ """Sources below a formatted answer (raw output lists them in `finish`)."""
122
+ self.console.print(Text("Sources", style="bold"))
123
+ for s in srcs:
124
+ line = Text(f" [{s.id}] ", style="cyan")
125
+ line.append(s.title or s.url)
126
+ if s.title:
127
+ line.append(f" {s.url}", style=f"dim link {s.url}")
128
+ self.console.print(line, overflow="ellipsis", no_wrap=True)
129
+
130
+ # --- internals ---------------------------------------------------------
131
+
132
+ def _view(self):
133
+ parts = []
134
+ if self._text:
135
+ # Show only the tail while streaming; the full answer is printed at the end.
136
+ height = max(self.console.size.height - 3, 5)
137
+ tail = "\n".join(self._text.splitlines()[-height:])
138
+ parts.append(Markdown(tail))
139
+ else:
140
+ parts.append(Spinner("dots", text=Text(self._status, style="dim")))
141
+ return Group(*parts)
142
+
143
+ def _refresh(self) -> None:
144
+ if self._live:
145
+ self._live.update(self._view())
146
+
147
+ def _stop(self) -> None:
148
+ if self._live:
149
+ self._live.stop()
150
+ self._live = None