lithe-cli 0.1.1__tar.gz → 0.1.3__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 (37) hide show
  1. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/PKG-INFO +1 -1
  2. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/agent.py +116 -4
  4. lithe_cli-0.1.3/lithe_cli/clipboard.py +123 -0
  5. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/commands.py +9 -0
  6. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/main.py +49 -0
  7. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/ttui.py +163 -11
  8. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/tui.py +147 -2
  9. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/ui.py +34 -0
  10. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/workbench.py +9 -0
  11. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/PKG-INFO +1 -1
  12. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/SOURCES.txt +2 -0
  13. lithe_cli-0.1.3/tests/test_cli_clipboard.py +179 -0
  14. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_cli_sessions.py +46 -0
  15. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_cli_subagents.py +112 -0
  16. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_ttui.py +197 -1
  17. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_tui_v2.py +60 -1
  18. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/LICENSE +0 -0
  19. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/README.md +0 -0
  20. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/__main__.py +0 -0
  21. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/config.py +0 -0
  22. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/profiles.py +0 -0
  23. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/prompts.py +0 -0
  24. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/py.typed +0 -0
  25. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/sessions.py +0 -0
  26. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli/setup.py +0 -0
  27. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/dependency_links.txt +0 -0
  28. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/entry_points.txt +0 -0
  29. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/requires.txt +0 -0
  30. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/lithe_cli.egg-info/top_level.txt +0 -0
  31. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/pyproject.toml +0 -0
  32. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/setup.cfg +0 -0
  33. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_cli.py +0 -0
  34. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_cli_budget_steer.py +0 -0
  35. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_cli_guard.py +0 -0
  36. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/tests/test_profiles.py +0 -0
  37. {lithe_cli-0.1.1 → lithe_cli-0.1.3}/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.1
3
+ Version: 0.1.3
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.1"
3
+ __version__ = "0.1.3"
@@ -46,7 +46,20 @@ from lithe.bundles.workspace import register_file_tools
46
46
  from lithe.bundles.todos import register_todo_tools
47
47
 
48
48
  from .config import Config
49
- from .ui import CYAN, GREEN, YELLOW, ui
49
+ from .ui import (
50
+ BOLD,
51
+ CYAN,
52
+ DIM,
53
+ GREEN,
54
+ MAGENTA,
55
+ RED,
56
+ SUBAGENT_STATUS,
57
+ YELLOW,
58
+ display_width,
59
+ truncate,
60
+ tool_call_label,
61
+ ui,
62
+ )
50
63
 
51
64
  SYSTEM_PROMPT_BASE = (
52
65
  "你是运行在命令行里的助理,工作区是用户的当前目录。"
@@ -238,12 +251,18 @@ _OPERATOR_PROMPT = (
238
251
  )
239
252
 
240
253
 
241
- def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry):
254
+ def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry,
255
+ on_event=None):
242
256
  """Register delegate/delegate_parallel over the CLI's default roster.
243
257
 
244
258
  Must run after ``build_host`` (the engine shares the host's registry,
245
259
  store and LLM config — children inherit the endpoint, retry policy and
246
260
  budgets; parallel siblings share one live cost ceiling, kernel ≥0.1.0).
261
+ ``on_event`` is the caller's event channel (the TUI's state folder, the
262
+ workbench emitter); the kernel's ``on_subagent_event`` progress hook is
263
+ wired onto it so live subagent heartbeats reach the same front-end as
264
+ the orchestrator's own events. Without a channel (plain `lithe run`),
265
+ they render through ``render_event`` directly.
247
266
  Returns the engine (roster inspection for hosts and tests).
248
267
  """
249
268
  from lithe.bundles.subagents import (
@@ -284,7 +303,22 @@ def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry):
284
303
  # A spec whose tool list filtered to nothing can do nothing meaningful;
285
304
  # researcher/coder always keep the ever-present file tools.
286
305
  specs = [s for s in specs if s.tools]
287
- engine = SubagentEngine(host, SubagentRoster(specs))
306
+ roster = SubagentRoster(specs)
307
+
308
+ async def forward_progress(_sub_ctx, ev: dict) -> None:
309
+ # The kernel emits {"type": "subagent_progress", "agent": id,
310
+ # "event": <thin runtime event>}; enrich it with the roster's
311
+ # display name so front-ends can label lines without roster access.
312
+ spec = roster.get(str(ev.get("agent") or ""))
313
+ enriched = dict(ev)
314
+ if spec is not None:
315
+ enriched["display"] = spec.display
316
+ if on_event is not None:
317
+ on_event(enriched)
318
+ else:
319
+ render_event(enriched)
320
+
321
+ engine = SubagentEngine(host, roster, on_subagent_event=forward_progress)
288
322
  register_delegate_tools(reg, engine, parallel=True)
289
323
  return engine
290
324
 
@@ -298,6 +332,58 @@ def tool_names(cfg: Config) -> list[str]:
298
332
  return names
299
333
 
300
334
 
335
+ def _render_subagent_progress(ev: dict) -> None:
336
+ """Render one live subagent heartbeat: ``[检索员] ⚒ read_file · …``.
337
+
338
+ The kernel's progress hook caps text (300) and dumps ``tool_call`` args
339
+ to a capped JSON string, so parse them back for the label. ``step``
340
+ events are skipped — per-step chatter from every parallel worker is
341
+ noise, the tool lines carry the substance.
342
+ """
343
+ who = str(ev.get("display") or ev.get("agent") or "?")
344
+ tag = ui.s(f"[{who}]", MAGENTA)
345
+ inner = ev.get("event") or {}
346
+ t = inner.get("type")
347
+ room = max(8, ui.width - display_width(f" [{who}] "))
348
+ if t == "tool_call":
349
+ name = str(inner.get("name") or "")
350
+ args = inner.get("args")
351
+ if isinstance(args, str):
352
+ try:
353
+ args = json.loads(args)
354
+ except ValueError:
355
+ args = {}
356
+ args = args if isinstance(args, dict) else {}
357
+ label = tool_call_label(name, args)
358
+ detail = label[len(name):].strip(" ·") if label.startswith(name) else label
359
+ shown = truncate(detail, max(8, room - display_width(name) - 4))
360
+ print(f" {tag} {ui.s('⚒', CYAN)} {ui.s(name, CYAN, BOLD)} "
361
+ f"{ui.s(shown, DIM)}")
362
+ elif t == "tool_result":
363
+ ok = bool(inner.get("ok"))
364
+ summary = str(inner.get("summary") or "").replace("\n", " ")
365
+ if not ok and inner.get("error"):
366
+ # Same rule as the orchestrator's failed calls: a bare
367
+ # "参数错误" summary without the diagnostic tells nothing.
368
+ detail = str(inner["error"]).replace("\n", " ")
369
+ if detail and summary and (detail in summary or summary in detail):
370
+ summary = detail if len(detail) > len(summary) else summary
371
+ elif detail:
372
+ summary = f"{summary} · {detail}" if summary else detail
373
+ mark = ui.s("✓", GREEN) if ok else ui.s("✗", RED)
374
+ print(f" {tag} {mark} "
375
+ f"{ui.s(truncate(summary, max(8, room - 4)), GREEN if ok else RED)}")
376
+ elif t == "assistant":
377
+ text = str(inner.get("text") or "").replace("\n", " ").strip()
378
+ if text:
379
+ print(f" {tag} {ui.s(truncate(text, max(8, room - 2)), DIM)}")
380
+ elif t == "error":
381
+ msg = str(inner.get("message") or "").replace("\n", " ")
382
+ print(f" {tag} {ui.s('!', RED)} {ui.s(truncate(msg, max(8, room - 4)), RED)}")
383
+ elif t == "cancelled":
384
+ print(f" {tag} {ui.s('~ 已取消', YELLOW)}")
385
+
386
+
301
387
  def render_event(
302
388
  ev: dict,
303
389
  verbose: bool = False,
@@ -345,6 +431,32 @@ def render_event(
345
431
  # update_todos replaced the list; print what it now contains —
346
432
  # the tool's own result line only reports the item count.
347
433
  ui.todo_change(ev.get("new") or [])
434
+ elif t == "subagent_progress":
435
+ # Live heartbeat from a running subagent (kernel on_subagent_event,
436
+ # wired in register_subagents): each worker's tool calls and
437
+ # outputs, labeled with its display name.
438
+ _render_subagent_progress(ev)
439
+ elif t == "subagent_start":
440
+ # Emitted in ToolResult.ui after the delegation finished: the
441
+ # per-agent record of what it was tasked with.
442
+ who = str(ev.get("display") or ev.get("agent") or "?")
443
+ task = str(ev.get("task") or "").replace("\n", " ").strip()
444
+ line = f"{who}:{truncate(task, max(8, ui.width - 14))}" if task else who
445
+ print(f" {ui.s('▸', MAGENTA)} {ui.s(line, MAGENTA)}")
446
+ elif t == "subagent_end":
447
+ who = str(ev.get("display") or ev.get("agent") or "?")
448
+ status = str(ev.get("status") or "")
449
+ zh = SUBAGENT_STATUS.get(status, status or "?")
450
+ color = (GREEN if status == "done"
451
+ else YELLOW if status in ("cancelled", "max_steps")
452
+ else RED) if status else None
453
+ bits = [ui.s(zh, color) if color else zh]
454
+ if ev.get("steps") is not None:
455
+ bits.append(f"{ev['steps']} 步")
456
+ if ev.get("changes"):
457
+ bits.append(f"{ev['changes']} 处改动")
458
+ print(f" {ui.s('▪', MAGENTA)} {ui.s(who, MAGENTA, BOLD)} · "
459
+ f"{' · '.join(bits)}")
348
460
  elif t == "error":
349
461
  ui.error(str(ev.get("message", "")))
350
462
  elif t == "cancelled":
@@ -408,7 +520,7 @@ async def execute(
408
520
  reg = build_registry(cfg, approver)
409
521
  host = build_host(cfg, reg)
410
522
  if cfg.subagents:
411
- register_subagents(cfg, host, reg)
523
+ register_subagents(cfg, host, reg, on_event=on_event)
412
524
  rid = run_id or uuid.uuid4().hex[:12]
413
525
  extra = {"conversation_id": conversation_id} if conversation_id is not None else {}
414
526
  ctx = AgentContext(run_id=rid, user_id=cfg.user_id, extra=extra)
@@ -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:
@@ -12,9 +12,13 @@ Input niceties: ``/``-commands complete inline (suggestions above the
12
12
  prompt, Tab accepts the first), and ↑/↓ recall the persistent chat history
13
13
  (shared with the plain REPL through prompt_toolkit's FileHistory store).
14
14
 
15
- No in-app mouse-drag selection / OSC 52 copy — use the terminal's native
16
- Shift+drag selection instead (hide the sidebar with F2 first if it gets
17
- in the way).
15
+ Copying: mouse reporting means the terminal's own drag-select and menu
16
+ never reach it, so the app brings its own — right-click opens a copy menu,
17
+ ``/copy`` takes the whole conversation (or the last answer, the user's
18
+ lines, the tool output), and ``Ctrl+C`` copies a Textual text selection
19
+ when there is one before it falls back to cancel/exit. Delivery is
20
+ layered (platform tool → OSC 52 → file) in :mod:`lithe_cli.clipboard`;
21
+ Shift+drag still works in terminals that keep native selection.
18
22
  """
19
23
 
20
24
  from __future__ import annotations
@@ -30,7 +34,16 @@ from textual.message import Message
30
34
  from textual.screen import ModalScreen
31
35
  from textual.widgets import Input, Label, ListItem, ListView, Static
32
36
 
33
- from .tui import TuiState, transcript_feed_lines
37
+ from .clipboard import deliver_clipboard, write_clipboard_file
38
+ from .config import lithe_home
39
+ from .tui import (
40
+ COPY_SCOPE_LABELS,
41
+ COPY_SCOPES,
42
+ TuiState,
43
+ describe_copy,
44
+ feed_text,
45
+ transcript_feed_lines,
46
+ )
34
47
  from .ui import fmt_duration
35
48
 
36
49
  _MAX_FEED = 400 # mounted conversation lines before trimming the oldest
@@ -269,6 +282,47 @@ class WbEvent(Message):
269
282
  self.ev = ev
270
283
 
271
284
 
285
+ # -- clipboard hooks -------------------------------------------------------------
286
+
287
+ def selected_text(screen: Any, app: Any = None) -> str:
288
+ """The current Textual text selection, if this release has one.
289
+
290
+ The selection API moved names between Textual releases (and is absent
291
+ in the headless test driver), so every candidate is probed and a miss
292
+ simply means "no selection" — callers keep their old behaviour.
293
+ """
294
+ for holder in (screen, app):
295
+ if holder is None:
296
+ continue
297
+ getter = getattr(holder, "get_selected_text", None)
298
+ if not callable(getter):
299
+ continue
300
+ try:
301
+ text = getter()
302
+ except Exception: # noqa: BLE001 — no selection model: not fatal
303
+ continue
304
+ if isinstance(text, str) and text.strip():
305
+ return text
306
+ return ""
307
+
308
+
309
+ class ConversationPane(VerticalScroll):
310
+ """The conversation pane.
311
+
312
+ Right-click is handled here rather than on the app: mouse reporting is
313
+ on, so the terminal's own context menu never opens inside the screen,
314
+ and the pane is where a reader aims when they want text out of it.
315
+ """
316
+
317
+ def on_mouse_down(self, event) -> None:
318
+ if getattr(event, "button", 0) != 3:
319
+ return
320
+ stop = getattr(event, "stop", None)
321
+ if callable(stop): # keep the app's own handler from firing twice
322
+ stop()
323
+ self.app.open_copy_menu()
324
+
325
+
272
326
  # -- pickers ---------------------------------------------------------------------
273
327
 
274
328
  class PickerModal(ModalScreen):
@@ -423,19 +477,21 @@ class LitheApp(App):
423
477
  self.args = args
424
478
  self._shown = 0 # feed lines already mounted
425
479
  self._cancel_asked = False # first Ctrl+C cancels, second exits
480
+ self._pending_selection = "" # selection captured at right-click time
426
481
 
427
482
  # -- composition ----------------------------------------------------------
428
483
 
429
484
  def compose(self) -> ComposeResult:
430
- yield Static("", id="top")
485
+ yield Static("", id="top", markup=False)
431
486
  with Horizontal(id="body"):
432
- with VerticalScroll(id="conv"):
433
- yield Static("", id="streaming", classes="assistant")
487
+ with ConversationPane(id="conv"):
488
+ yield Static("", id="streaming", classes="assistant",
489
+ markup=False)
434
490
  with VerticalScroll(id="side-wrap"):
435
491
  yield Static("", id="side", markup=True)
436
492
  yield Static("", id="suggest")
437
493
  yield HistoryInput(placeholder="输入任务,/help 查看命令", id="prompt")
438
- yield Static("", id="foot")
494
+ yield Static("", id="foot", markup=False)
439
495
 
440
496
  def on_mount(self) -> None:
441
497
  from lithe.bundles import JsonTodoStore
@@ -540,7 +596,7 @@ class LitheApp(App):
540
596
  self.states[cid] = st
541
597
  self.state = self.states[cid]
542
598
  self._shown = 0
543
- conv = self.query_one("#conv", VerticalScroll)
599
+ conv = self.query_one("#conv", ConversationPane)
544
600
  for child in list(conv.children):
545
601
  if child.id != "streaming":
546
602
  child.remove()
@@ -551,7 +607,7 @@ class LitheApp(App):
551
607
  # -- conversation rendering (pure render-from-state) ----------------------
552
608
 
553
609
  def _sync_feed(self) -> None:
554
- conv = self.query_one("#conv", VerticalScroll)
610
+ conv = self.query_one("#conv", ConversationPane)
555
611
  streaming = self.query_one("#streaming", Static)
556
612
  # Follow the feed only when the reader is already at (or near) the
557
613
  # bottom: scrolling up to re-read earlier output mid-run must stick,
@@ -561,7 +617,10 @@ class LitheApp(App):
561
617
  while self._shown < len(feed):
562
618
  cls, text = feed[self._shown]
563
619
  self._shown += 1
564
- conv.mount(Static(text, classes=cls or "dim"),
620
+ # markup=False: model/tool text is data, not Textual markup —
621
+ # a "[x]" in an answer must render, not parse (and it is what
622
+ # /copy sends to the clipboard verbatim).
623
+ conv.mount(Static(text, classes=cls or "dim", markup=False),
565
624
  before=streaming)
566
625
  non_stream = [c for c in conv.children if c.id != "streaming"]
567
626
  for stale in non_stream[:max(0, len(non_stream) - _MAX_FEED)]:
@@ -695,6 +754,11 @@ class LitheApp(App):
695
754
  from .tui import _CHAT_KEYS
696
755
 
697
756
  self.state.say("dim", _CHAT_KEYS)
757
+ self._sync_feed()
758
+ if r.copy_scope:
759
+ # /copy: the front-end owns the text (the workbench only
760
+ # resolved the scope), so the copy happens here.
761
+ await self._copy_scope(r.copy_scope)
698
762
  self._sync_feed()
699
763
  if r.toggle_sidebar:
700
764
  self.state.show_sidebar = not self.state.show_sidebar
@@ -945,6 +1009,86 @@ class LitheApp(App):
945
1009
  def _picker_fetch_models(self, payload) -> None:
946
1010
  asyncio.create_task(self.wb._fetch_and_report())
947
1011
 
1012
+ # -- copy ----------------------------------------------------------------------
1013
+
1014
+ def _scope_text(self, scope: str) -> str:
1015
+ """The feed slice /copy hands to the clipboard (streaming included)."""
1016
+ return feed_text(self.state.feed, scope, extra=self.state.streaming)
1017
+
1018
+ async def _copy_text(self, text: str, label: str) -> bool:
1019
+ """One copy through the layered channels (see lithe_cli.clipboard)."""
1020
+ ok, channel = await deliver_clipboard(text, app=self, home=lithe_home())
1021
+ if ok:
1022
+ self.state.say("ok", f"已复制{label}"
1023
+ f"({describe_copy(text)} → {channel})")
1024
+ else:
1025
+ self.state.say("err", f"复制{label}失败:{channel}")
1026
+ self._sync_feed()
1027
+ return ok
1028
+
1029
+ async def _copy_scope(self, scope: str) -> bool:
1030
+ label = COPY_SCOPE_LABELS.get(scope, scope)
1031
+ text = self._scope_text(scope)
1032
+ if not text.strip():
1033
+ self.state.say("warn", f"没有可复制的{label}(对话还是空的)")
1034
+ self._sync_feed()
1035
+ return False
1036
+ return await self._copy_text(text, label)
1037
+
1038
+ async def _copy_file(self) -> bool:
1039
+ """Export the whole conversation under $LITHE_HOME (no clipboard)."""
1040
+ text = self._scope_text("all")
1041
+ path = write_clipboard_file(text, lithe_home())
1042
+ if path is None:
1043
+ self.state.say("err", "导出失败:无法写入 $LITHE_HOME")
1044
+ else:
1045
+ self.state.say("ok", "已导出整段对话"
1046
+ f"({describe_copy(text)})→ {path}")
1047
+ self._sync_feed()
1048
+ return path is not None
1049
+
1050
+ def open_copy_menu(self) -> None:
1051
+ """The right-click copy menu (also the app-level right-click hook)."""
1052
+ selection = selected_text(self.screen, self)
1053
+ items: list[tuple[dict, str]] = []
1054
+ if selection:
1055
+ items.append(({"selection": True},
1056
+ f"复制选中文本({describe_copy(selection)})"))
1057
+ for scope in COPY_SCOPES:
1058
+ items.append(({"scope": scope}, f"复制{COPY_SCOPE_LABELS[scope]}"))
1059
+ items.append(({"file": True}, "整段对话存为文件($LITHE_HOME)"))
1060
+ # The modal takes the selection with it, so keep it here for the
1061
+ # callback instead of re-reading it after the dismiss.
1062
+ self._pending_selection = selection
1063
+ self.push_screen(
1064
+ PickerModal("复制", items, "Enter 复制 · Esc 关闭"),
1065
+ self._copy_picked,
1066
+ )
1067
+
1068
+ def _copy_picked(self, result) -> None:
1069
+ if not result or result[0] != "select" or not result[1]:
1070
+ return
1071
+ payload = result[1]
1072
+ if payload.get("selection"):
1073
+ if self._pending_selection:
1074
+ asyncio.create_task(
1075
+ self._copy_text(self._pending_selection, "选中文本"))
1076
+ return
1077
+ if payload.get("file"):
1078
+ asyncio.create_task(self._copy_file())
1079
+ return
1080
+ asyncio.create_task(self._copy_scope(payload.get("scope") or "last"))
1081
+
1082
+ def on_mouse_down(self, event) -> None:
1083
+ """Right-click outside the conversation pane (header, sidebar,
1084
+ footer) gets the same copy menu — mouse reporting leaves the
1085
+ terminal's own menu unreachable in here."""
1086
+ if getattr(event, "button", 0) != 3:
1087
+ return
1088
+ if isinstance(self.screen, PickerModal):
1089
+ return
1090
+ self.open_copy_menu()
1091
+
948
1092
  # -- keys -----------------------------------------------------------------------
949
1093
 
950
1094
  def action_toggle_sidebar(self) -> None:
@@ -952,6 +1096,14 @@ class LitheApp(App):
952
1096
  self._refresh_chrome()
953
1097
 
954
1098
  def action_cancel_or_exit(self) -> None:
1099
+ text = selected_text(self.screen, self)
1100
+ if text:
1101
+ # A native-Ctrl+C reflex over a drag selection: copy it instead
1102
+ # of cancelling the turn (press again with nothing selected to
1103
+ # cancel/exit). Absent a selection API this is a no-op and the
1104
+ # documented cancel/exit behaviour stands.
1105
+ asyncio.create_task(self._copy_text(text, "选中文本"))
1106
+ return
955
1107
  if self.state.running:
956
1108
  if not self.wb.cancel(self._current_cid()):
957
1109
  # One-shot run mode drives no workbench turn, so wb.cancel