lithe-cli 0.6.5__tar.gz → 0.6.7__tar.gz

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.

Potentially problematic release.


This version of lithe-cli might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.6.5
3
+ Version: 0.6.7
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -39,7 +39,7 @@ Classifier: Typing :: Typed
39
39
  Requires-Python: >=3.10
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
- Requires-Dist: lithe>=0.9.11
42
+ Requires-Dist: lithe>=0.9.13
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Provides-Extra: dev
45
45
  Requires-Dist: pytest>=8; extra == "dev"
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.6.5"
3
+ __version__ = "0.6.7"
@@ -26,6 +26,8 @@ from __future__ import annotations
26
26
 
27
27
  import json
28
28
  import os
29
+ import shutil
30
+ import subprocess
29
31
  from dataclasses import dataclass, field
30
32
  from pathlib import Path
31
33
  from typing import Any
@@ -139,16 +141,54 @@ def load_saved_endpoint() -> dict:
139
141
  }
140
142
 
141
143
 
144
+ def _restrict_to_owner(path: Path, directory: bool = False) -> None:
145
+ if os.name != "nt":
146
+ try:
147
+ path.chmod(0o700 if directory else 0o600)
148
+ except OSError:
149
+ pass
150
+ return
151
+ icacls = shutil.which("icacls")
152
+ if not icacls:
153
+ raise OSError("icacls is required to protect the saved API key on Windows")
154
+ account = os.environ.get("USERDOMAIN")
155
+ username = os.environ.get("USERNAME")
156
+ owner = f"{account}\\{username}" if account and username else username
157
+ if not owner:
158
+ raise OSError("unable to determine current Windows account for API key ACL")
159
+ permissions = f"{owner}:(OI)(CI)(F)" if directory else f"{owner}:(F)"
160
+ try:
161
+ reset = subprocess.run(
162
+ [icacls, str(path), "/reset"],
163
+ stdout=subprocess.DEVNULL,
164
+ stderr=subprocess.DEVNULL,
165
+ check=False,
166
+ timeout=10,
167
+ )
168
+ if reset.returncode:
169
+ raise OSError(f"failed to reset access to {path}")
170
+ result = subprocess.run(
171
+ [icacls, str(path), "/inheritance:r", "/grant:r", permissions],
172
+ stdout=subprocess.DEVNULL,
173
+ stderr=subprocess.DEVNULL,
174
+ check=False,
175
+ timeout=10,
176
+ )
177
+ except (OSError, subprocess.SubprocessError) as exc:
178
+ raise OSError(f"failed to restrict access to {path}") from exc
179
+ if result.returncode:
180
+ raise OSError(f"failed to restrict access to {path}")
181
+
182
+
142
183
  def save_endpoint(api_key: str, base_url: str, model: str) -> Path:
143
- """Write the config file; 0600 because it holds the API key."""
184
+ """Write the config file with owner-only access where supported."""
144
185
  path = config_file()
145
186
  fresh_dir = not path.parent.exists()
146
187
  path.parent.mkdir(parents=True, exist_ok=True)
147
188
  if fresh_dir:
148
- try:
149
- path.parent.chmod(0o700)
150
- except OSError:
151
- pass
189
+ _restrict_to_owner(path.parent, directory=True)
190
+ path.touch(exist_ok=True)
191
+ _restrict_to_owner(path)
152
192
  payload = {
153
193
  k: v
154
194
  for k, v in (("api_key", api_key), ("base_url", base_url), ("model", model))
@@ -156,10 +196,6 @@ def save_endpoint(api_key: str, base_url: str, model: str) -> Path:
156
196
  path.write_text(
157
197
  json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
158
198
  )
159
- try:
160
- path.chmod(0o600)
161
- except OSError:
162
- pass
163
199
  return path
164
200
 
165
201
 
@@ -92,8 +92,12 @@ _SCROLL_STEP = 3
92
92
 
93
93
 
94
94
  def screen_supported() -> bool:
95
- """The TUI needs a real terminal (never pipes, CI or dumb terms)."""
96
- return sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
95
+ """The TUI needs interactive input and output, never pipes or dumb terms."""
96
+ return (
97
+ sys.stdin.isatty()
98
+ and sys.stdout.isatty()
99
+ and os.environ.get("TERM") != "dumb"
100
+ )
97
101
 
98
102
 
99
103
  class TuiState:
@@ -118,11 +122,13 @@ class TuiState:
118
122
  self.input_tokens = 0
119
123
  self.output_tokens = 0
120
124
  self.cached_tokens = 0
125
+ self.last_turn_cost = 0.0
121
126
  self._turn_tokens = 0
122
127
  self._turn_cost = 0.0
123
128
  self._turn_input_tokens = 0
124
129
  self._turn_output_tokens = 0
125
130
  self._turn_cached_tokens = 0
131
+ self._done_seen = True
126
132
  self.context_tokens = None
127
133
  self.context_window = None
128
134
  self.context_percent = None
@@ -140,10 +146,24 @@ class TuiState:
140
146
 
141
147
  # -- feed ---------------------------------------------------------------
142
148
 
149
+ def _conversation_width(self) -> int | None:
150
+ if self._app is None or not self._app.is_running:
151
+ return None
152
+ cols, rows = _term_size(self._app)
153
+ (width, _), _ = body_layout(self, cols, rows - 3)
154
+ return max(1, width - 4)
155
+
156
+ def _wrapped_rows(self, text: str) -> int:
157
+ width = self._conversation_width()
158
+ if width is None:
159
+ return len(text.splitlines() or [""])
160
+ return len(wrap_text(text, width))
161
+
143
162
  def say(self, cls: str, text: str) -> None:
144
- for line in str(text).splitlines() or [""]:
145
- self.feed.append((cls, line))
146
- del self.feed[:-400]
163
+ lines = str(text).splitlines() or [""]
164
+ self.feed.extend((cls, line) for line in lines)
165
+ if self.scroll:
166
+ self.scroll += sum(self._wrapped_rows(line) for line in lines)
147
167
  self.invalidate()
148
168
 
149
169
  def invalidate(self) -> None:
@@ -158,26 +178,43 @@ class TuiState:
158
178
  self.input_tokens = 0
159
179
  self.output_tokens = 0
160
180
  self.cached_tokens = 0
181
+ self.last_turn_cost = 0.0
161
182
  self._turn_tokens = 0
162
183
  self._turn_cost = 0.0
163
184
  self._turn_input_tokens = 0
164
185
  self._turn_output_tokens = 0
165
186
  self._turn_cached_tokens = 0
187
+ self._done_seen = True
166
188
  self.context_tokens = None
167
189
  self.context_window = None
168
190
  self.context_percent = None
169
191
 
192
+ def _fold_turn(self) -> None:
193
+ """Fold the current turn's usage into session totals and clear it."""
194
+ self.input_tokens += self._turn_input_tokens
195
+ self.output_tokens += self._turn_output_tokens
196
+ self.cached_tokens += self._turn_cached_tokens
197
+ self.tokens += self._turn_tokens
198
+ self.cost += self._turn_cost
199
+ self.last_turn_cost = self._turn_cost
200
+ self._turn_tokens = 0
201
+ self._turn_cost = 0.0
202
+ self._turn_input_tokens = 0
203
+ self._turn_output_tokens = 0
204
+ self._turn_cached_tokens = 0
205
+
170
206
  def on_event(self, ev: dict) -> None:
171
207
  kind = ev.get("type")
172
208
  if kind == "run_start":
173
209
  self.status = "思考中"
174
210
  self.step = 0
175
211
  self.scroll = 0
176
- self._turn_tokens = 0
177
- self._turn_cost = 0.0
178
- self._turn_input_tokens = 0
179
- self._turn_output_tokens = 0
180
- self._turn_cached_tokens = 0
212
+ # A previous round that died without a done event (host-level
213
+ # failure) still burned tokens: keep its measured usage instead
214
+ # of silently dropping it when the accumulators reset.
215
+ if not self._done_seen:
216
+ self._fold_turn()
217
+ self._done_seen = False
181
218
  self.context_tokens = None
182
219
  self.context_window = None
183
220
  self.context_percent = None
@@ -187,11 +224,23 @@ class TuiState:
187
224
  self.step = int(ev.get("step") or 0)
188
225
  self.status = "思考中"
189
226
  elif kind == "assistant_delta":
190
- self.streaming += str(ev.get("text") or "")
227
+ text = str(ev.get("text") or "")
228
+ if self.scroll and text:
229
+ self.scroll += (
230
+ self._wrapped_rows(self.streaming + text)
231
+ - self._wrapped_rows(self.streaming)
232
+ )
233
+ self.streaming += text
191
234
  elif kind == "assistant":
192
235
  text = str(ev.get("text") or "")
193
- if text and not self.streaming:
194
- self.say("assistant", text)
236
+ final_text = text or self.streaming
237
+ streamed_rows = self._wrapped_rows(self.streaming) if self.streaming else 0
238
+ if final_text:
239
+ lines = final_text.splitlines() or [""]
240
+ self.feed.extend(("assistant", line) for line in lines)
241
+ if self.scroll:
242
+ final_rows = sum(self._wrapped_rows(line) for line in lines)
243
+ self.scroll += final_rows - streamed_rows
195
244
  self.streaming = ""
196
245
  elif kind == "tool_call":
197
246
  name = str(ev.get("name") or "tool")
@@ -254,16 +303,8 @@ class TuiState:
254
303
  self._turn_tokens = int(ev["tokens"])
255
304
  if ev.get("cost") is not None:
256
305
  self._turn_cost = float(ev["cost"])
257
- self.input_tokens += self._turn_input_tokens
258
- self.output_tokens += self._turn_output_tokens
259
- self.cached_tokens += self._turn_cached_tokens
260
- self.tokens += self._turn_tokens
261
- self.cost += self._turn_cost
262
- self._turn_tokens = 0
263
- self._turn_cost = 0.0
264
- self._turn_input_tokens = 0
265
- self._turn_output_tokens = 0
266
- self._turn_cached_tokens = 0
306
+ self._done_seen = True
307
+ self._fold_turn()
267
308
  if ev.get("context_tokens") is not None:
268
309
  self.context_tokens = int(ev["context_tokens"])
269
310
  if ev.get("context_window") is not None:
@@ -464,6 +505,10 @@ def _sidebar_lines(state: TuiState) -> list[tuple[str, str]]:
464
505
  cached_tokens = state.cached_tokens + state._turn_cached_tokens
465
506
  tokens = state.tokens + state._turn_tokens
466
507
  cost = state.cost + state._turn_cost
508
+ if state.running or not state._done_seen:
509
+ turn_cost = state._turn_cost
510
+ else:
511
+ turn_cost = state.last_turn_cost
467
512
  context = "—"
468
513
  if state.context_tokens is not None:
469
514
  context = f"{state.context_tokens:,}"
@@ -474,9 +519,12 @@ def _sidebar_lines(state: TuiState) -> list[tuple[str, str]]:
474
519
  lines.extend(
475
520
  [
476
521
  ("dim", "◆ 会话用量"),
477
- ("", f"输入 {input_tokens:,} · 输出 {output_tokens:,}"),
522
+ ("", f"输入 {input_tokens:,}"),
523
+ ("", f"输出 {output_tokens:,}"),
478
524
  ("", f"缓存输入 {cached_tokens:,}"),
479
- ("", f"合计 {tokens:,} · ${cost:.4f}"),
525
+ ("", f"合计 {tokens:,}"),
526
+ ("", f"本轮费用 ${turn_cost:.4f}"),
527
+ ("", f"累计费用 ${cost:.4f}"),
480
528
  ("", f"上下文 {context}"),
481
529
  ]
482
530
  )
@@ -625,7 +673,10 @@ def build_app(state: TuiState, mode: str, version: str, on_line) -> tuple[Applic
625
673
  conversation_lexer.lines = styled_lines
626
674
  text = "\n".join("".join(value for _, value in row) for row in styled_lines)
627
675
  if conversation_buffer.text != text:
628
- conversation_buffer.set_document(Document(text), bypass_readonly=True)
676
+ conversation_buffer.set_document(
677
+ Document(text, cursor_position=len(text)),
678
+ bypass_readonly=True,
679
+ )
629
680
 
630
681
  def _side_text():
631
682
  cols, rows = _term_size(state._app)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.6.5
3
+ Version: 0.6.7
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -39,7 +39,7 @@ Classifier: Typing :: Typed
39
39
  Requires-Python: >=3.10
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
- Requires-Dist: lithe>=0.9.11
42
+ Requires-Dist: lithe>=0.9.13
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Provides-Extra: dev
45
45
  Requires-Dist: pytest>=8; extra == "dev"
@@ -1,4 +1,4 @@
1
- lithe>=0.9.11
1
+ lithe>=0.9.13
2
2
  prompt-toolkit>=3.0.38
3
3
 
4
4
  [dev]
@@ -9,7 +9,7 @@ description = "Command-line interface for the lithe agent kernel: chat, one-shot
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
11
11
  requires-python = ">=3.10"
12
- dependencies = ["lithe>=0.9.11", "prompt-toolkit>=3.0.38"]
12
+ dependencies = ["lithe>=0.9.13", "prompt-toolkit>=3.0.38"]
13
13
  keywords = ["agent", "llm", "react", "cli", "tool-calling"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import os
6
7
 
7
8
  import pytest
8
9
  from lithe_cli import __version__
@@ -329,14 +330,66 @@ def test_run_dashboard_shows_tools_todos_and_usage():
329
330
  assert state.tokens == 180 and state.cost == pytest.approx(0.003)
330
331
  assert state.input_tokens == 150 and state.output_tokens == 30
331
332
  assert state.cached_tokens == 85 and state.context_tokens == 50
333
+ assert state.last_turn_cost == pytest.approx(0.002)
332
334
  from lithe_cli.tui import _sidebar_lines
333
335
 
334
336
  usage_text = "\n".join(text for _, text in _sidebar_lines(state))
335
- assert "输入 150 · 输出 30" in usage_text
336
- assert "缓存输入 85" in usage_text
337
+ assert "输入 150" in usage_text and "输出 30" in usage_text
338
+ assert "缓存输入 85" in usage_text and "合计 180" in usage_text
339
+ assert "本轮费用 $0.0020" in usage_text
340
+ assert "累计费用 $0.0030" in usage_text
337
341
  assert "50 / 500 (10.0%)" in usage_text
338
342
 
339
343
 
344
+ def test_sidebar_usage_is_one_metric_per_line():
345
+ from lithe_cli.tui import TuiState, _sidebar_lines
346
+
347
+ state = TuiState("模型", "/ws", 5)
348
+ state.on_event({"type": "run_start"})
349
+ state.on_event({
350
+ "type": "usage",
351
+ "prompt_tokens": 1200,
352
+ "completion_tokens": 340,
353
+ "cached_tokens": 900,
354
+ "total_tokens": 1540,
355
+ "cost": 0.0123,
356
+ })
357
+ lines = [text for _, text in _sidebar_lines(state)]
358
+ labels = ("输入 ", "输出 ", "缓存输入 ", "合计 ", "本轮费用 ", "累计费用 ")
359
+ usage = [line for line in lines if line.startswith(labels)]
360
+ for line in usage:
361
+ assert sum(line.startswith(label) for label in labels) == 1
362
+ assert len(usage) == 6
363
+ assert "输入 1,200" in lines and "输出 340" in lines
364
+ assert "缓存输入 900" in lines and "合计 1,540" in lines
365
+ assert "本轮费用 $0.0123" in lines and "累计费用 $0.0123" in lines
366
+
367
+
368
+ def test_usage_from_a_round_that_died_without_done_is_kept():
369
+ from lithe_cli.tui import TuiState
370
+
371
+ state = TuiState("模型", "/ws", 5)
372
+ state.on_event({"type": "run_start"})
373
+ state.on_event({
374
+ "type": "usage",
375
+ "prompt_tokens": 100,
376
+ "completion_tokens": 20,
377
+ "total_tokens": 120,
378
+ "cost": 0.001,
379
+ })
380
+ state.on_event({"type": "error", "message": "host blew up before done"})
381
+ state.on_event({"type": "run_start"})
382
+ assert state.cost == pytest.approx(0.001)
383
+ assert state.input_tokens == 100 and state.tokens == 120
384
+ state.on_event({
385
+ "type": "done", "status": "done", "steps": 1,
386
+ "tokens": 60, "prompt_tokens": 50, "completion_tokens": 10,
387
+ "cost": 0.002,
388
+ })
389
+ assert state.cost == pytest.approx(0.003)
390
+ assert state.last_turn_cost == pytest.approx(0.002)
391
+
392
+
340
393
  def test_system_prompt_prefers_localized_file_edits_and_limits_todo_planning():
341
394
  from lithe_cli.agent import SYSTEM_PROMPT_BASE
342
395
 
@@ -463,21 +516,57 @@ def test_conversation_pane_scrolls_back_and_clamps():
463
516
  text = "\n".join("".join(f[1] for f in row) for row in rows)
464
517
  assert "第 29 行" in text and "第 0 行" not in text
465
518
 
466
- state.scroll = 10**9 # Home: clamp to the very top
519
+ state.scroll = 10**9
467
520
  rows = conversation_rows(state, 60, 12)
468
521
  text = "\n".join("".join(f[1] for f in row) for row in rows)
469
522
  assert "第 0 行" in text and "第 29 行" not in text
470
523
  assert state.scroll == 30 - 10
471
524
 
472
- state.scroll = 5 # mid viewport: last visible line is 10 lines above the tail
525
+ state.scroll = 5
473
526
  rows = conversation_rows(state, 60, 12)
474
527
  text = "\n".join("".join(f[1] for f in row) for row in rows)
475
528
  assert "第 15 行" in text and "第 24 行" in text and "第 29 行" not in text
476
529
 
477
- state.on_event({"type": "run_start"}) # a new turn resumes following the tail
530
+ state.say("assistant", "追加内容")
531
+ rows = conversation_rows(state, 60, 12)
532
+ text = "\n".join("".join(f[1] for f in row) for row in rows)
533
+ assert "第 15 行" in text and "追加内容" not in text
534
+ assert state.scroll == 6
535
+
536
+ state.on_event({"type": "run_start"})
478
537
  assert state.scroll == 0
479
538
 
480
539
 
540
+ def test_screen_supported_requires_interactive_input_and_output(monkeypatch):
541
+ from lithe_cli import tui
542
+
543
+ class Terminal:
544
+ def __init__(self, interactive):
545
+ self.interactive = interactive
546
+
547
+ def isatty(self):
548
+ return self.interactive
549
+
550
+ monkeypatch.setattr(tui.sys, "stdin", Terminal(False))
551
+ monkeypatch.setattr(tui.sys, "stdout", Terminal(True))
552
+ assert tui.screen_supported() is False
553
+ monkeypatch.setattr(tui.sys, "stdin", Terminal(True))
554
+ assert tui.screen_supported() is True
555
+
556
+
557
+ def test_conversation_retains_more_than_four_hundred_feed_lines():
558
+ from lithe_cli.tui import TuiState, conversation_rows
559
+
560
+ state = TuiState("模型", "/工作区", 5)
561
+ for i in range(450):
562
+ state.say("assistant", f"历史行 {i}")
563
+ rows = conversation_rows(state, 60, 12)
564
+ text = "\n".join("".join(fragment[1] for fragment in row) for row in rows)
565
+ assert "历史行 0" not in text
566
+ assert "历史行 449" in text
567
+ assert len(state.feed) == 450
568
+
569
+
481
570
  def test_wrap_text_is_cjk_aware():
482
571
  from lithe_cli.ui import wrap_text
483
572
 
@@ -599,8 +688,19 @@ def test_saved_config_file_fills_endpoint(tmp_path, monkeypatch):
599
688
  "base_url": "https://file.example/api",
600
689
  "model": "file-model",
601
690
  }
602
- st = path.stat()
603
- assert st.st_mode & 0o777 == 0o600 # holds the key → private
691
+ if os.name == "nt":
692
+ import subprocess
693
+
694
+ result = subprocess.run(
695
+ ["icacls", str(path)], capture_output=True, text=True, check=True
696
+ )
697
+ acl = result.stdout.casefold()
698
+ owner = os.environ.get("USERNAME", "").casefold()
699
+ assert owner and f"{owner}:(f)" in acl
700
+ assert "everyone:" not in acl and "authenticated users:" not in acl
701
+ else:
702
+ st = path.stat()
703
+ assert st.st_mode & 0o777 == 0o600
604
704
 
605
705
  class Args:
606
706
  api_key = base_url = model = store = workspace = user = None
@@ -688,9 +788,10 @@ def test_wizard_saves_and_reports_cancel(tmp_path, monkeypatch, capsys):
688
788
 
689
789
 
690
790
  def _pty_run(code: str, feed: list[bytes], settle: float = 0.25):
691
- """Fork a PTY, run `code`, feed byte chunks, return (output, exit_code)."""
791
+ """Fork a POSIX PTY, run `code`, feed byte chunks, return output and status."""
792
+ if os.name == "nt":
793
+ pytest.skip("POSIX PTY tests are unavailable on Windows")
692
794
  import fcntl
693
- import os
694
795
  import pty
695
796
  import struct
696
797
  import sys
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes