lithe-cli 0.6.5__tar.gz → 0.6.6__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.6
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.6"
@@ -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:
@@ -140,10 +144,24 @@ class TuiState:
140
144
 
141
145
  # -- feed ---------------------------------------------------------------
142
146
 
147
+ def _conversation_width(self) -> int | None:
148
+ if self._app is None or not self._app.is_running:
149
+ return None
150
+ cols, rows = _term_size(self._app)
151
+ (width, _), _ = body_layout(self, cols, rows - 3)
152
+ return max(1, width - 4)
153
+
154
+ def _wrapped_rows(self, text: str) -> int:
155
+ width = self._conversation_width()
156
+ if width is None:
157
+ return len(text.splitlines() or [""])
158
+ return len(wrap_text(text, width))
159
+
143
160
  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]
161
+ lines = str(text).splitlines() or [""]
162
+ self.feed.extend((cls, line) for line in lines)
163
+ if self.scroll:
164
+ self.scroll += sum(self._wrapped_rows(line) for line in lines)
147
165
  self.invalidate()
148
166
 
149
167
  def invalidate(self) -> None:
@@ -187,11 +205,23 @@ class TuiState:
187
205
  self.step = int(ev.get("step") or 0)
188
206
  self.status = "思考中"
189
207
  elif kind == "assistant_delta":
190
- self.streaming += str(ev.get("text") or "")
208
+ text = str(ev.get("text") or "")
209
+ if self.scroll and text:
210
+ self.scroll += (
211
+ self._wrapped_rows(self.streaming + text)
212
+ - self._wrapped_rows(self.streaming)
213
+ )
214
+ self.streaming += text
191
215
  elif kind == "assistant":
192
216
  text = str(ev.get("text") or "")
193
- if text and not self.streaming:
194
- self.say("assistant", text)
217
+ final_text = text or self.streaming
218
+ streamed_rows = self._wrapped_rows(self.streaming) if self.streaming else 0
219
+ if final_text:
220
+ lines = final_text.splitlines() or [""]
221
+ self.feed.extend(("assistant", line) for line in lines)
222
+ if self.scroll:
223
+ final_rows = sum(self._wrapped_rows(line) for line in lines)
224
+ self.scroll += final_rows - streamed_rows
195
225
  self.streaming = ""
196
226
  elif kind == "tool_call":
197
227
  name = str(ev.get("name") or "tool")
@@ -625,7 +655,10 @@ def build_app(state: TuiState, mode: str, version: str, on_line) -> tuple[Applic
625
655
  conversation_lexer.lines = styled_lines
626
656
  text = "\n".join("".join(value for _, value in row) for row in styled_lines)
627
657
  if conversation_buffer.text != text:
628
- conversation_buffer.set_document(Document(text), bypass_readonly=True)
658
+ conversation_buffer.set_document(
659
+ Document(text, cursor_position=len(text)),
660
+ bypass_readonly=True,
661
+ )
629
662
 
630
663
  def _side_text():
631
664
  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.6
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__
@@ -463,21 +464,57 @@ def test_conversation_pane_scrolls_back_and_clamps():
463
464
  text = "\n".join("".join(f[1] for f in row) for row in rows)
464
465
  assert "第 29 行" in text and "第 0 行" not in text
465
466
 
466
- state.scroll = 10**9 # Home: clamp to the very top
467
+ state.scroll = 10**9
467
468
  rows = conversation_rows(state, 60, 12)
468
469
  text = "\n".join("".join(f[1] for f in row) for row in rows)
469
470
  assert "第 0 行" in text and "第 29 行" not in text
470
471
  assert state.scroll == 30 - 10
471
472
 
472
- state.scroll = 5 # mid viewport: last visible line is 10 lines above the tail
473
+ state.scroll = 5
473
474
  rows = conversation_rows(state, 60, 12)
474
475
  text = "\n".join("".join(f[1] for f in row) for row in rows)
475
476
  assert "第 15 行" in text and "第 24 行" in text and "第 29 行" not in text
476
477
 
477
- state.on_event({"type": "run_start"}) # a new turn resumes following the tail
478
+ state.say("assistant", "追加内容")
479
+ rows = conversation_rows(state, 60, 12)
480
+ text = "\n".join("".join(f[1] for f in row) for row in rows)
481
+ assert "第 15 行" in text and "追加内容" not in text
482
+ assert state.scroll == 6
483
+
484
+ state.on_event({"type": "run_start"})
478
485
  assert state.scroll == 0
479
486
 
480
487
 
488
+ def test_screen_supported_requires_interactive_input_and_output(monkeypatch):
489
+ from lithe_cli import tui
490
+
491
+ class Terminal:
492
+ def __init__(self, interactive):
493
+ self.interactive = interactive
494
+
495
+ def isatty(self):
496
+ return self.interactive
497
+
498
+ monkeypatch.setattr(tui.sys, "stdin", Terminal(False))
499
+ monkeypatch.setattr(tui.sys, "stdout", Terminal(True))
500
+ assert tui.screen_supported() is False
501
+ monkeypatch.setattr(tui.sys, "stdin", Terminal(True))
502
+ assert tui.screen_supported() is True
503
+
504
+
505
+ def test_conversation_retains_more_than_four_hundred_feed_lines():
506
+ from lithe_cli.tui import TuiState, conversation_rows
507
+
508
+ state = TuiState("模型", "/工作区", 5)
509
+ for i in range(450):
510
+ state.say("assistant", f"历史行 {i}")
511
+ rows = conversation_rows(state, 60, 12)
512
+ text = "\n".join("".join(fragment[1] for fragment in row) for row in rows)
513
+ assert "历史行 0" not in text
514
+ assert "历史行 449" in text
515
+ assert len(state.feed) == 450
516
+
517
+
481
518
  def test_wrap_text_is_cjk_aware():
482
519
  from lithe_cli.ui import wrap_text
483
520
 
@@ -599,8 +636,19 @@ def test_saved_config_file_fills_endpoint(tmp_path, monkeypatch):
599
636
  "base_url": "https://file.example/api",
600
637
  "model": "file-model",
601
638
  }
602
- st = path.stat()
603
- assert st.st_mode & 0o777 == 0o600 # holds the key → private
639
+ if os.name == "nt":
640
+ import subprocess
641
+
642
+ result = subprocess.run(
643
+ ["icacls", str(path)], capture_output=True, text=True, check=True
644
+ )
645
+ acl = result.stdout.casefold()
646
+ owner = os.environ.get("USERNAME", "").casefold()
647
+ assert owner and f"{owner}:(f)" in acl
648
+ assert "everyone:" not in acl and "authenticated users:" not in acl
649
+ else:
650
+ st = path.stat()
651
+ assert st.st_mode & 0o777 == 0o600
604
652
 
605
653
  class Args:
606
654
  api_key = base_url = model = store = workspace = user = None
@@ -688,9 +736,10 @@ def test_wizard_saves_and_reports_cancel(tmp_path, monkeypatch, capsys):
688
736
 
689
737
 
690
738
  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)."""
739
+ """Fork a POSIX PTY, run `code`, feed byte chunks, return output and status."""
740
+ if os.name == "nt":
741
+ pytest.skip("POSIX PTY tests are unavailable on Windows")
692
742
  import fcntl
693
- import os
694
743
  import pty
695
744
  import struct
696
745
  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