lithe-cli 0.1.2__tar.gz → 0.1.4__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.
Files changed (38) hide show
  1. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/PKG-INFO +1 -1
  2. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/agent.py +16 -6
  4. lithe_cli-0.1.4/lithe_cli/clipboard.py +123 -0
  5. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/commands.py +9 -0
  6. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/main.py +49 -0
  7. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/ttui.py +166 -256
  8. lithe_cli-0.1.4/lithe_cli/ttui_widgets.py +287 -0
  9. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/tui.py +84 -1
  10. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/workbench.py +11 -1
  11. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/PKG-INFO +1 -1
  12. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/SOURCES.txt +3 -0
  13. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_cli.py +58 -0
  14. lithe_cli-0.1.4/tests/test_cli_clipboard.py +179 -0
  15. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_cli_sessions.py +46 -0
  16. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_ttui.py +253 -1
  17. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_tui_v2.py +60 -1
  18. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/LICENSE +0 -0
  19. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/README.md +0 -0
  20. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/__main__.py +0 -0
  21. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/config.py +0 -0
  22. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/profiles.py +0 -0
  23. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/prompts.py +0 -0
  24. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/py.typed +0 -0
  25. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/sessions.py +0 -0
  26. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/setup.py +0 -0
  27. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli/ui.py +0 -0
  28. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/dependency_links.txt +0 -0
  29. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/entry_points.txt +0 -0
  30. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/requires.txt +0 -0
  31. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/lithe_cli.egg-info/top_level.txt +0 -0
  32. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/pyproject.toml +0 -0
  33. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/setup.cfg +0 -0
  34. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_cli_budget_steer.py +0 -0
  35. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_cli_guard.py +0 -0
  36. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_cli_subagents.py +0 -0
  37. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_profiles.py +0 -0
  38. {lithe_cli-0.1.2 → lithe_cli-0.1.4}/tests/test_workbench.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.2
3
+ Version: 0.1.4
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
 
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.2"
3
+ __version__ = "0.1.4"
@@ -75,10 +75,14 @@ SYSTEM_PROMPT_BASE = (
75
75
  )
76
76
 
77
77
 
78
- def todo_store_path(cfg: Config) -> Path:
78
+ def todo_store_path(cfg: Config, conversation_id: int | None = None) -> Path:
79
+ """Path for one conversation's task list (None is the non-session scope)."""
79
80
  workspace = str(cfg.workspace_dir.expanduser().resolve())
81
+ scope_data = {"user_id": str(cfg.user_id), "workspace": workspace}
82
+ if conversation_id is not None:
83
+ scope_data["conversation_id"] = conversation_id
80
84
  scope = json.dumps(
81
- {"user_id": str(cfg.user_id), "workspace": workspace},
85
+ scope_data,
82
86
  ensure_ascii=False,
83
87
  sort_keys=True,
84
88
  separators=(",", ":"),
@@ -159,7 +163,11 @@ def build_llm(cfg: Config) -> LLMConfig:
159
163
  return LLMConfig(**overrides)
160
164
 
161
165
 
162
- def build_registry(cfg: Config, approver: Callable[[str], Awaitable[bool]] | None = None) -> ToolRegistry:
166
+ def build_registry(
167
+ cfg: Config,
168
+ approver: Callable[[str], Awaitable[bool]] | None = None,
169
+ conversation_id: int | None = None,
170
+ ) -> ToolRegistry:
163
171
  """Register the CLI's tool set against the configured workspace.
164
172
 
165
173
  ``approver`` is the human-confirmation channel for destructive
@@ -173,7 +181,7 @@ def build_registry(cfg: Config, approver: Callable[[str], Awaitable[bool]] | Non
173
181
 
174
182
  register_file_tools(reg, workspace_for)
175
183
  register_apply_patch_tool(reg, workspace_for)
176
- todo_store = JsonTodoStore(todo_store_path(cfg))
184
+ todo_store = JsonTodoStore(todo_store_path(cfg, conversation_id))
177
185
  register_todo_tools(reg, lambda ctx: todo_store)
178
186
  if cfg.download:
179
187
  register_download_tools(reg, workspace_for)
@@ -517,7 +525,7 @@ async def execute(
517
525
  the steering channel: a queue of user texts the kernel drains at step
518
526
  boundaries and injects as user messages (see AgentRuntime.run).
519
527
  """
520
- reg = build_registry(cfg, approver)
528
+ reg = build_registry(cfg, approver, conversation_id=conversation_id)
521
529
  host = build_host(cfg, reg)
522
530
  if cfg.subagents:
523
531
  register_subagents(cfg, host, reg, on_event=on_event)
@@ -560,7 +568,9 @@ async def execute(
560
568
 
561
569
  async def undo(cfg: Config, run_id: str, quiet: bool = False) -> int:
562
570
  """Revert a run's mutations; returns how many actions were reverted."""
563
- reg = build_registry(cfg)
571
+ run = JsonlRunStore(cfg.store_dir).get_run(run_id, cfg.user_id)
572
+ conversation_id = run.conversation_id if run is not None else None
573
+ reg = build_registry(cfg, conversation_id=conversation_id)
564
574
  host = build_host(cfg, reg)
565
575
  report = await undo_run(host, run_id, cfg.user_id)
566
576
  if not quiet:
@@ -0,0 +1,123 @@
1
+ """System-clipboard delivery for the CLI's copy commands.
2
+
3
+ Deliberately dependency-free and front-end-free: the Textual screen, the
4
+ plain per-line REPL and the tests all go through
5
+ :func:`deliver_clipboard`, which tries three channels in order —
6
+
7
+ 1. the platform's own tool (``pbcopy`` / ``clip`` / ``wl-copy`` /
8
+ ``xclip`` / ``xsel``): the only channel that writes the *real* system
9
+ clipboard no matter what the terminal implements;
10
+ 2. OSC 52 through the caller's app (Textual's ``copy_to_clipboard``):
11
+ covers terminals without those tools, including remote sessions —
12
+ ``app`` is optional because only a full-screen front-end has one;
13
+ 3. a plain file under ``$LITHE_HOME`` (``clipboard-<ts>.txt``), so a copy
14
+ is never a silent no-op on a terminal where neither works.
15
+
16
+ Everything is best-effort: failures come back as a reason string instead
17
+ of an exception, because a copy the user cannot find is worth reporting,
18
+ not crashing on.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import inspect
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import time
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from .config import lithe_home
33
+
34
+ _TIMEOUT = 5 # seconds: a wedged clipboard helper must not freeze the UI
35
+
36
+
37
+ def native_clipboard_command() -> list[str] | None:
38
+ """The installed platform clipboard tool, if any (a pure PATH lookup)."""
39
+ if sys.platform == "darwin":
40
+ candidates = [["pbcopy"]]
41
+ elif os.name == "nt":
42
+ candidates = [["clip"]]
43
+ else:
44
+ candidates = [
45
+ ["wl-copy"],
46
+ ["xclip", "-selection", "clipboard"],
47
+ ["xsel", "-i", "--clipboard"],
48
+ ]
49
+ for argv in candidates:
50
+ if shutil.which(argv[0]):
51
+ return argv
52
+ return None
53
+
54
+
55
+ def pipe_to_clipboard(text: str, argv: list[str]) -> bool:
56
+ """Feed *text* to a clipboard tool over stdin; ``False`` on any failure.
57
+
58
+ ``clip.exe`` reads UTF-16LE from a pipe (cmd's convention), the Unix
59
+ helpers UTF-8.
60
+ """
61
+ name = Path(argv[0]).name.lower()
62
+ encoding = "utf-16-le" if name.startswith("clip") else "utf-8"
63
+ try:
64
+ proc = subprocess.run(
65
+ argv, input=text.encode(encoding), capture_output=True,
66
+ timeout=_TIMEOUT,
67
+ )
68
+ except (OSError, ValueError, subprocess.SubprocessError):
69
+ return False
70
+ return proc.returncode == 0
71
+
72
+
73
+ def write_clipboard_file(text: str, home: Path | None = None) -> Path | None:
74
+ """Last-resort copy: the text as ``$LITHE_HOME/clipboard-<ts>.txt``."""
75
+ base = Path(home) if home is not None else lithe_home()
76
+ try:
77
+ base.mkdir(parents=True, exist_ok=True)
78
+ path = base / f"clipboard-{time.strftime('%Y%m%d-%H%M%S')}.txt"
79
+ path.write_text(text if text.endswith("\n") else text + "\n",
80
+ encoding="utf-8")
81
+ except OSError:
82
+ return None
83
+ return path
84
+
85
+
86
+ async def deliver_clipboard(
87
+ text: str, *, app: Any = None, home: Path | None = None
88
+ ) -> tuple[bool, str]:
89
+ """Copy *text* by the best available channel; returns ``(ok, channel)``.
90
+
91
+ ``channel`` is what the user should be told: the tool that took it
92
+ (``pbcopy``), ``OSC 52``, or the fallback file's path — and when
93
+ nothing worked, the reason.
94
+ """
95
+ argv = native_clipboard_command()
96
+ if argv is not None and pipe_to_clipboard(text, argv):
97
+ return True, argv[0]
98
+ if app is not None and await _osc52(app, text):
99
+ return True, "OSC 52"
100
+ path = write_clipboard_file(text, home)
101
+ if path is not None:
102
+ return True, str(path)
103
+ return False, ("系统剪贴板不可用(未找到 pbcopy/clip/wl-copy/xclip,"
104
+ "终端也不接受 OSC 52,且写入 $LITHE_HOME 失败)")
105
+
106
+
107
+ async def _osc52(app: Any, text: str) -> bool:
108
+ """Textual's clipboard write, tolerant of sync or coroutine flavours.
109
+
110
+ The release-switch that renamed pieces of the selection API is exactly
111
+ why this goes through ``getattr``: an app that cannot copy must fall
112
+ through to the next channel, not raise out of a key handler.
113
+ """
114
+ copy = getattr(app, "copy_to_clipboard", None)
115
+ if not callable(copy):
116
+ return False
117
+ try:
118
+ result = copy(text)
119
+ if inspect.isawaitable(result):
120
+ await result
121
+ except Exception: # noqa: BLE001 — no driver/headless: try the next channel
122
+ return False
123
+ return True
@@ -13,6 +13,10 @@ from dataclasses import dataclass, field
13
13
  from typing import Any
14
14
  from collections.abc import Callable
15
15
 
16
+ # The /copy scope vocabulary lives with the feed it extracts from, so the
17
+ # completion hint, the help line and the parser can never drift apart.
18
+ from .tui import COPY_SCOPE_HELP
19
+
16
20
  # name → (args hint, one-line description); order is the help order.
17
21
  COMMANDS: dict[str, tuple[str, str]] = {
18
22
  "help": ("", "显示这条帮助"),
@@ -26,6 +30,7 @@ COMMANDS: dict[str, tuple[str, str]] = {
26
30
  "profile": ("[名称]", "查看/切换 provider 档案"),
27
31
  "set": ("[名称] [值]", "查看/调整运行设置(F5 同效);面板内空格连切不关闭、Enter 切换并关闭,下一轮生效"),
28
32
  "tools": ("", "列出已注册的工具"),
33
+ "copy": (f"[{COPY_SCOPE_HELP}]", "复制对话文本到系统剪贴板(右键同效);默认最后一条回答"),
29
34
  "undo": ("[run]", "撤销当前会话最近一轮(或指定 run)的文件改动"),
30
35
  "sidebar": ("", "显示/隐藏右侧状态栏(F2 同效)"),
31
36
  "exit": ("", "退出(等同 /quit)"),
@@ -52,6 +57,10 @@ class ActionResult:
52
57
  overlay: str | None = None # TUI picker: "sessions" | "model" | "set"
53
58
  toggle_sidebar: bool = False
54
59
  changed: bool = False # model/session changed → refresh banner/sidebar
60
+ # /copy: which slice of the feed the front-end should put on the
61
+ # clipboard. The workbench only parses it — the text itself lives in
62
+ # the front-end (feed in the TUI, store transcript in the plain REPL).
63
+ copy_scope: str | None = None
55
64
  # Zero-arg coroutine the frontend must run: plain → asyncio.run,
56
65
  # TUI → create_task (so /models fetches never block the screen).
57
66
  awaitable: Callable[[], Any] | None = None
@@ -224,6 +224,11 @@ def build_parser() -> argparse.ArgumentParser:
224
224
  sessions_p.add_argument("--limit", type=int, default=30)
225
225
  sessions_p.add_argument("--rename", nargs=2, metavar=("ID", "TITLE"))
226
226
  sessions_p.add_argument("--delete", metavar="ID")
227
+ sessions_p.add_argument(
228
+ "--export", metavar="ID|标题",
229
+ help="print a conversation as plain text (pipe it: lithe sessions "
230
+ "--export 12 | pbcopy)",
231
+ )
227
232
 
228
233
  models_p = sub.add_parser(
229
234
  "models", help="list the endpoint's models (GET /models)"
@@ -344,6 +349,23 @@ def _cmd_sessions(cfg: Any, args: Any) -> int:
344
349
  from .sessions import SessionManager, format_session_rows
345
350
 
346
351
  mgr = SessionManager(JsonlRunStore(cfg.store_dir), cfg.user_id)
352
+ if args.export:
353
+ # Plain text on stdout, so a copy-and-paste workflow works outside
354
+ # the full-screen UI too: `lithe sessions --export 12 | pbcopy`.
355
+ from .tui import feed_text, transcript_feed_lines
356
+
357
+ row, err = mgr.resolve_exact(args.export)
358
+ if row is None:
359
+ print(ui.s(err, RED))
360
+ return 1
361
+ text = feed_text(
362
+ transcript_feed_lines(mgr.history(row["id"])), "all"
363
+ )
364
+ if not text.strip():
365
+ print(ui.s(f"会话 #{row['id']} 没有可导出的文本", YELLOW))
366
+ return 1
367
+ print(text)
368
+ return 0
347
369
  if args.rename:
348
370
  ident, new_title = args.rename
349
371
  row, err = mgr.resolve_exact(ident)
@@ -608,6 +630,31 @@ def _print_result_messages(messages) -> None:
608
630
  print(ui.s(text, style) if style else text)
609
631
 
610
632
 
633
+ def _copy_plain(wb: Any, scope: str) -> None:
634
+ """``/copy`` outside the full-screen UI: the store holds the text.
635
+
636
+ The TUI copies from its live feed; the plain REPL rebuilds the same
637
+ rows from the session transcript, so both frontends send identical
638
+ text through the same layered :mod:`lithe_cli.clipboard` channels.
639
+ """
640
+ from .clipboard import deliver_clipboard
641
+ from .tui import COPY_SCOPE_LABELS, describe_copy, feed_text, \
642
+ transcript_feed_lines
643
+
644
+ label = COPY_SCOPE_LABELS.get(scope, scope)
645
+ cid = wb.current["id"] if wb.current else None
646
+ rows = wb.sessions.transcript(cid) if cid is not None else []
647
+ text = feed_text(transcript_feed_lines(rows), scope)
648
+ if not text.strip():
649
+ print(ui.s(f"没有可复制的{label}(对话还是空的)", YELLOW))
650
+ return
651
+ ok, channel = asyncio.run(deliver_clipboard(text))
652
+ if ok:
653
+ print(ui.s(f"✓ 已复制{label}({describe_copy(text)} → {channel})", GREEN))
654
+ else:
655
+ print(ui.s(f"复制{label}失败:{channel}", RED))
656
+
657
+
611
658
  def _chat_loop(
612
659
  cfg: Any,
613
660
  resume: str | None = None,
@@ -673,6 +720,8 @@ def _chat_loop(
673
720
  _print_result_messages(r.messages)
674
721
  if r.toggle_sidebar:
675
722
  print(ui.s("(纯文本模式没有侧栏;交互终端里按 F2)", YELLOW))
723
+ if r.copy_scope:
724
+ _copy_plain(wb, r.copy_scope)
676
725
  if r.action == "exit":
677
726
  break
678
727
  if r.awaitable is not None: