lithe-cli 0.1.6__tar.gz → 0.1.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.
Files changed (40) hide show
  1. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/PKG-INFO +2 -2
  2. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/sessions.py +10 -3
  4. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/ttui.py +94 -18
  5. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/ttui_widgets.py +103 -3
  6. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/tui.py +110 -28
  7. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/PKG-INFO +2 -2
  8. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/requires.txt +1 -1
  9. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/pyproject.toml +1 -1
  10. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli_sessions.py +20 -0
  11. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli_subagents.py +48 -9
  12. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_ttui.py +85 -0
  13. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/LICENSE +0 -0
  14. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/README.md +0 -0
  15. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/__main__.py +0 -0
  16. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/agent.py +0 -0
  17. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/cli_parser.py +0 -0
  18. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/clipboard.py +0 -0
  19. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/commands.py +0 -0
  20. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/config.py +0 -0
  21. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/main.py +0 -0
  22. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/profiles.py +0 -0
  23. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/prompts.py +0 -0
  24. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/py.typed +0 -0
  25. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/setup.py +0 -0
  26. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/ttui_render.py +0 -0
  27. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/ui.py +0 -0
  28. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli/workbench.py +0 -0
  29. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/SOURCES.txt +0 -0
  30. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/dependency_links.txt +0 -0
  31. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/entry_points.txt +0 -0
  32. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/lithe_cli.egg-info/top_level.txt +0 -0
  33. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/setup.cfg +0 -0
  34. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli.py +0 -0
  35. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli_budget_steer.py +0 -0
  36. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli_clipboard.py +0 -0
  37. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_cli_guard.py +0 -0
  38. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_profiles.py +0 -0
  39. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/tests/test_tui_v2.py +0 -0
  40. {lithe_cli-0.1.6 → lithe_cli-0.1.7}/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.6
3
+ Version: 0.1.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.1.4
42
+ Requires-Dist: lithe>=0.1.5
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.6"
3
+ __version__ = "0.1.7"
@@ -101,9 +101,16 @@ class SessionManager:
101
101
  conversation_id, self.user_id
102
102
  )
103
103
 
104
- def transcript(self, conversation_id: int, last: int = 200) -> list[dict]:
105
- """Recent messages for display (TUI rebuild), oldest first."""
106
- rows = self.history(conversation_id)
104
+ def transcript(self, conversation_id: int, last: int = 200, *,
105
+ include_subagents: bool = False) -> list[dict]:
106
+ """Recent messages for display (TUI rebuild), oldest first.
107
+
108
+ The default remains the orchestrator-only view used by /copy and
109
+ existing callers. Rich UIs can request instance-tagged worker rows.
110
+ """
111
+ rows = self.store.messages_for_conversation(
112
+ conversation_id, self.user_id, exclude_subagent=not include_subagents
113
+ )
107
114
  return rows[-last:] if last else rows
108
115
 
109
116
  def usage_snapshot(self, conversation_id: int) -> dict:
@@ -29,7 +29,7 @@ from typing import Any
29
29
 
30
30
  from textual.app import App, ComposeResult
31
31
  from textual.binding import Binding
32
- from textual.containers import Horizontal, VerticalScroll
32
+ from textual.containers import Horizontal, Vertical, VerticalScroll
33
33
  from textual.widgets import Input, Static
34
34
 
35
35
  from .clipboard import deliver_clipboard, write_clipboard_file
@@ -45,8 +45,8 @@ from .tui import (
45
45
  from .ui import fmt_duration as fmt_duration # noqa: F401 — legacy re-export
46
46
  from . import ttui_widgets as _widgets
47
47
  from .ttui_widgets import (
48
- ConfirmModal, ConversationPane, HistoryInput, PickerModal, WbEvent,
49
- completion_suggestions, selected_text,
48
+ ConfirmModal, ConversationPane, HistoryInput, PickerModal, SubagentCard,
49
+ WbEvent, completion_suggestions, selected_text,
50
50
  )
51
51
  from .ttui_render import footer_text, header_text, sidebar_markup
52
52
 
@@ -58,7 +58,13 @@ class LitheApp(App):
58
58
  CSS = """
59
59
  #top { height: 1; background: #172033; color: #e2e8f0; }
60
60
  #body { height: 1fr; }
61
- #conv { width: 1fr; border: round #475569; padding: 0 1; }
61
+ #main-column { width: 1fr; height: 1fr; }
62
+ #conv { width: 1fr; height: 1fr; border: round #475569; padding: 0 1; }
63
+ #subagents { height: auto; max-height: 14; overflow-y: auto; }
64
+ .subagent-card { height: auto; border: round #334155; padding: 0 1; margin: 0 0 1 0; }
65
+ .subagent-heading { width: 1fr; height: auto; min-height: 1; color: #fbbf24; text-align: left; }
66
+ .subagent-search { height: 3; margin: 0 0 1 0; }
67
+ .subagent-output { height: auto; color: #cbd5e1; }
62
68
  #side-wrap { width: 44; border: round #475569; padding: 0 1; }
63
69
  #prompt { border: round #475569; }
64
70
  #foot { height: 1; background: #111827; color: #cbd5e1; }
@@ -95,6 +101,7 @@ class LitheApp(App):
95
101
  self.mode = mode
96
102
  self.args = args
97
103
  self._shown = 0 # feed lines already mounted
104
+ self._subagent_signature = ()
98
105
  self._cancel_asked = False # first Ctrl+C cancels, second exits
99
106
  self._pending_selection = "" # selection captured at right-click time
100
107
 
@@ -103,9 +110,12 @@ class LitheApp(App):
103
110
  def compose(self) -> ComposeResult:
104
111
  yield Static("", id="top", markup=False)
105
112
  with Horizontal(id="body"):
106
- with ConversationPane(id="conv"):
107
- yield Static("", id="streaming", classes="assistant",
108
- markup=False)
113
+ with Vertical(id="main-column"):
114
+ with ConversationPane(id="conv"):
115
+ yield Static("", id="streaming", classes="assistant",
116
+ markup=False)
117
+ with VerticalScroll(id="subagents"):
118
+ pass
109
119
  with VerticalScroll(id="side-wrap"):
110
120
  yield Static("", id="side", markup=True)
111
121
  yield Static("", id="suggest")
@@ -140,7 +150,10 @@ class LitheApp(App):
140
150
  self.state = self._base_state(self._current_cid())
141
151
  self.states: dict[int, TuiState] = {}
142
152
  if self._current_cid() is not None:
143
- self.states[self._current_cid()] = self.state
153
+ cid = self._current_cid()
154
+ self._load_session_history(self.state, cid)
155
+ self.states[cid] = self.state
156
+ self._initial_history_loaded = True
144
157
  for cls, text in opening:
145
158
  self.state.say(cls, text)
146
159
  self.wb.subscribe(
@@ -184,6 +197,34 @@ class LitheApp(App):
184
197
  st.max_total_tokens = self.cfg.max_total_tokens
185
198
  return st
186
199
 
200
+ def _load_session_history(self, state: TuiState, cid: int) -> None:
201
+ """Load both the orchestrator feed and subagent cards on first open."""
202
+ history = self.wb.sessions.transcript(
203
+ cid, last=0, include_subagents=True
204
+ )
205
+ main_rows = [row for row in history if not row.get("subagent")]
206
+ state.feed.extend(transcript_feed_lines(main_rows[-200:]))
207
+ state.restore_subagents(history)
208
+ usage = self.wb.sessions.usage_snapshot(cid)
209
+ if usage.get("known"):
210
+ state.input_tokens = usage["prompt_tokens"]
211
+ state.output_tokens = usage["completion_tokens"]
212
+ state.cached_tokens = usage["cached_tokens"]
213
+ state.tokens = usage["total_tokens"]
214
+ state.cost = usage["cost"]
215
+
216
+ def action_refresh_session_history(self) -> None:
217
+ """Reload durable transcript for the active session."""
218
+ cid = self._current_cid()
219
+ if cid is None:
220
+ return
221
+ self.state.feed.clear()
222
+ self.state.subagents.clear()
223
+ self._load_session_history(self.state, cid)
224
+ self._shown = 0
225
+ self._subagent_signature = ()
226
+ self._sync_feed()
227
+
187
228
  def _refresh_meta(self) -> None:
188
229
  st = self.state
189
230
  st.model = self.cfg.model or "(scripted)"
@@ -206,16 +247,7 @@ class LitheApp(App):
206
247
 
207
248
  if cid not in self.states:
208
249
  st = self._base_state(cid)
209
- st.feed.extend(
210
- transcript_feed_lines(self.wb.sessions.transcript(cid))
211
- )
212
- usage = self.wb.sessions.usage_snapshot(cid)
213
- if usage.get("known"):
214
- st.input_tokens = usage["prompt_tokens"]
215
- st.output_tokens = usage["completion_tokens"]
216
- st.cached_tokens = usage["cached_tokens"]
217
- st.tokens = usage["total_tokens"]
218
- st.cost = usage["cost"]
250
+ self._load_session_history(st, cid)
219
251
  self.states[cid] = st
220
252
  # Reload from the conversation's persisted store when returning to it:
221
253
  # a background turn or /undo may have changed its todos meanwhile.
@@ -224,6 +256,10 @@ class LitheApp(App):
224
256
  ).list()
225
257
  self.state = self.states[cid]
226
258
  self._shown = 0
259
+ self._subagent_signature = ()
260
+ subagents = self.query_one("#subagents", VerticalScroll)
261
+ for card in list(subagents.children):
262
+ card.remove()
227
263
  conv = self.query_one("#conv", ConversationPane)
228
264
  for child in list(conv.children):
229
265
  if child.id != "streaming":
@@ -237,6 +273,7 @@ class LitheApp(App):
237
273
  def _sync_feed(self) -> None:
238
274
  conv = self.query_one("#conv", ConversationPane)
239
275
  streaming = self.query_one("#streaming", Static)
276
+ subagents = self.query_one("#subagents", VerticalScroll)
240
277
  # Follow the feed only when the reader is already at (or near) the
241
278
  # bottom: scrolling up to re-read earlier output mid-run must stick,
242
279
  # not be yanked back to the bottom on every event.
@@ -257,6 +294,31 @@ class LitheApp(App):
257
294
  streaming.update(self.state.streaming)
258
295
  else:
259
296
  streaming.update("")
297
+ for child in subagents.children:
298
+ if isinstance(child, SubagentCard):
299
+ child._block["expanded"] = child._expanded
300
+ child._block["search"] = child._search
301
+ signature = tuple(
302
+ (key, block.get("status"), block.get("task"),
303
+ bool(block.get("expanded")), str(block.get("search") or ""))
304
+ for key, block in self.state.subagents.items()
305
+ )
306
+ if signature != self._subagent_signature:
307
+ self._subagent_signature = signature
308
+ cards = {child.instance: child for child in subagents.children
309
+ if isinstance(child, SubagentCard)}
310
+ for instance, card in cards.items():
311
+ if instance not in self.state.subagents:
312
+ card.remove()
313
+ for instance, block in self.state.subagents.items():
314
+ card = cards.get(instance)
315
+ if card is None:
316
+ card = SubagentCard(instance, block)
317
+ subagents.mount(card)
318
+ card.call_after_refresh(card.set_data, block)
319
+ else:
320
+ card.set_data(block)
321
+ self.call_after_refresh(self._refresh_subagent_lines)
260
322
  if at_bottom:
261
323
  conv.scroll_end(animate=False)
262
324
  # The pane's extent only grows once the newly mounted lines lay
@@ -266,6 +328,18 @@ class LitheApp(App):
266
328
  # "still reading up there" and stops following for good.
267
329
  conv.call_after_refresh(conv.scroll_end, animate=False)
268
330
 
331
+ def _refresh_subagent_lines(self) -> None:
332
+ """Refresh mounted card transcripts after each event, preserving UI."""
333
+ try:
334
+ container = self.query_one("#subagents", VerticalScroll)
335
+ except Exception:
336
+ return
337
+ for card in container.children:
338
+ if isinstance(card, SubagentCard):
339
+ block = self.state.subagents.get(card.instance)
340
+ if block is not None:
341
+ card.set_data(block)
342
+
269
343
  def _refresh_chrome(self) -> None:
270
344
  self.query_one("#top", Static).update(
271
345
  header_text(self.state, getattr(self, "version", ""))
@@ -295,6 +369,8 @@ class LitheApp(App):
295
369
  return
296
370
  if t == "session_idle":
297
371
  if cid == self._current_cid():
372
+ if self._initial_history_loaded:
373
+ self.action_refresh_session_history()
298
374
  self.state.running = False
299
375
  self.state.stop = None
300
376
  self._cancel_asked = False
@@ -9,7 +9,7 @@ from textual.binding import Binding
9
9
  from textual.containers import Vertical, VerticalScroll
10
10
  from textual.message import Message
11
11
  from textual.screen import ModalScreen
12
- from textual.widgets import Input, Label, ListItem, ListView, Static
12
+ from textual.widgets import Button, Input, Label, ListItem, ListView, Static
13
13
 
14
14
  # -- input: completion + persistent history ------------------------------------
15
15
 
@@ -172,6 +172,108 @@ class ConversationPane(VerticalScroll):
172
172
  self.app.open_copy_menu()
173
173
 
174
174
 
175
+ class SubagentCard(Vertical):
176
+ """A collapsible, independently searchable subagent transcript."""
177
+
178
+ def __init__(self, instance: str, block: dict | None = None, **kwargs) -> None:
179
+ safe_id = "subagent-" + "".join(
180
+ c if c.isalnum() or c in "-_" else "-" for c in instance
181
+ )
182
+ super().__init__(id=safe_id, classes="subagent-card", **kwargs)
183
+ self.instance = instance
184
+ self._expanded = bool((block or {}).get("expanded"))
185
+ self._search = str((block or {}).get("search") or "")
186
+ self._lines: list[tuple[str, str]] = []
187
+ self._block: dict = {}
188
+ self._heading = ""
189
+ if block:
190
+ self.update_data(block)
191
+
192
+ def compose(self) -> ComposeResult:
193
+ yield Button("", classes="subagent-heading", variant="default")
194
+ yield Input(placeholder="搜索此子任务…", classes="subagent-search")
195
+ yield Static("", classes="subagent-output", markup=False)
196
+
197
+ def update_data(self, block: dict) -> None:
198
+ same_block = self._block is block
199
+ if self.is_mounted and same_block:
200
+ block["expanded"] = self._expanded
201
+ block["search"] = self._search
202
+ self._block = block
203
+ self._lines = list(block.get("lines") or [])
204
+ if not (self.is_mounted and same_block):
205
+ self._expanded = bool(block.get("expanded"))
206
+ self._search = str(block.get("search") or "")
207
+
208
+ def set_data(self, block: dict) -> None:
209
+ self.update_data(block)
210
+ display = str(block.get("display") or block.get("agent") or "子代理")
211
+ suffix = str(block.get("instance") or "").rsplit(":", 1)[-1][:4]
212
+ task = str(block.get("task") or "(任务描述载入中)").replace("\n", " ")
213
+ status = str(block.get("status") or "running")
214
+ status_label = {
215
+ "running": "运行中", "done": "完成", "max_steps": "步数上限",
216
+ "failed": "失败", "cancelled": "已取消", "budget_exceeded": "预算超限",
217
+ }.get(status, status)
218
+ details = []
219
+ if block.get("steps") is not None:
220
+ details.append(f"{block['steps']} 步")
221
+ if block.get("changes"):
222
+ details.append(f"{block['changes']} 处改动")
223
+ detail = " · " + " · ".join(details) if details else ""
224
+ heading = self.query_one(".subagent-heading", Button)
225
+ self._heading = f"{display}·{suffix} · {status_label}{detail} · {task}"
226
+ heading.label = f"{'▾' if self._expanded else '▸'} {self._heading}"
227
+ search = self.query_one(".subagent-search", Input)
228
+ output = self.query_one(".subagent-output", Static)
229
+ if search.value != self._search:
230
+ search.value = self._search
231
+ search.display = self._expanded
232
+ output.display = self._expanded
233
+ if self._expanded:
234
+ self._render_lines(search.value, output)
235
+
236
+ def refresh_lines(self) -> None:
237
+ """Refresh transcript text without resetting UI-local search state."""
238
+ if not self.is_mounted:
239
+ return
240
+ self._lines = list(self._block.get("lines") or [])
241
+ search = self.query_one(".subagent-search", Input)
242
+ output = self.query_one(".subagent-output", Static)
243
+ if self._expanded:
244
+ self._render_lines(search.value, output)
245
+
246
+ def _render_lines(self, query: str, output: Static) -> None:
247
+ needle = query.casefold().strip()
248
+ lines = [text for _cls, text in self._lines
249
+ if not needle or needle in text.casefold()]
250
+ output.update("\n".join(lines) if lines else ("(没有匹配内容)" if needle else "(暂无子任务输出)"))
251
+
252
+ def on_mount(self) -> None:
253
+ self.set_data(self._block)
254
+
255
+ def on_button_pressed(self, event: Button.Pressed) -> None:
256
+ if "subagent-heading" not in event.button.classes:
257
+ return
258
+ self._expanded = not self._expanded
259
+ self._block["expanded"] = self._expanded
260
+ heading = self.query_one(".subagent-heading", Button)
261
+ heading.label = f"{'▾' if self._expanded else '▸'} {self._heading}"
262
+ search = self.query_one(".subagent-search", Input)
263
+ output = self.query_one(".subagent-output", Static)
264
+ search.display = self._expanded
265
+ output.display = self._expanded
266
+ if self._expanded:
267
+ self._render_lines(search.value, output)
268
+
269
+ def on_input_changed(self, event: Input.Changed) -> None:
270
+ if "subagent-search" in event.input.classes:
271
+ self._search = event.value
272
+ self._block["search"] = event.value
273
+ self._render_lines(event.value,
274
+ self.query_one(".subagent-output", Static))
275
+
276
+
175
277
  # -- pickers ---------------------------------------------------------------------
176
278
 
177
279
  class PickerModal(ModalScreen):
@@ -283,5 +385,3 @@ class ConfirmModal(ModalScreen):
283
385
 
284
386
  def action_refuse(self) -> None:
285
387
  self.dismiss(False)
286
-
287
-
@@ -26,8 +26,7 @@ import os
26
26
  import sys
27
27
  import time
28
28
 
29
- from .agent import _agent_label
30
- from .ui import SUBAGENT_STATUS, fmt_duration, tool_call_label, truncate
29
+ from .ui import fmt_duration, tool_call_label, truncate
31
30
 
32
31
  _STATUS_DONE = "done"
33
32
 
@@ -94,6 +93,9 @@ class TuiState:
94
93
  self.max_total_tokens: int | None = None
95
94
  self.tools: list[dict] = []
96
95
  self.feed: list[tuple[str, str]] = []
96
+ # One independently searchable transcript per delegation instance.
97
+ # The kernel already gives each parallel invocation a unique tag.
98
+ self.subagents: dict[str, dict] = {}
97
99
  self.streaming = ""
98
100
  self.show_sidebar = True
99
101
  self.started: float | None = None
@@ -107,6 +109,67 @@ class TuiState:
107
109
  self.feed.extend((cls, line) for line in lines)
108
110
  self.invalidate()
109
111
 
112
+ def _subagent(self, instance: str, *, agent: str = "?",
113
+ display: str = "", task: str = "") -> dict:
114
+ """Return/create one delegation card, keyed by its unique instance."""
115
+ key = str(instance or agent or "unknown")
116
+ return self.subagents.setdefault(key, {
117
+ "instance": key, "agent": agent, "display": display or agent,
118
+ "task": task, "status": "running", "steps": None,
119
+ "changes": 0, "lines": [], "expanded": False, "search": "",
120
+ })
121
+
122
+ def add_subagent_line(self, instance: str, cls: str, text: str,
123
+ **identity) -> None:
124
+ block = self._subagent(instance, **identity)
125
+ block["lines"].append((cls, str(text)))
126
+ self.invalidate()
127
+
128
+ def restore_subagents(self, rows: list[dict]) -> None:
129
+ """Rebuild delegation cards from instance-tagged persisted messages."""
130
+ self.subagents.clear()
131
+ for row in rows:
132
+ instance = str(row.get("subagent") or "")
133
+ if not instance:
134
+ continue
135
+ meta = row.get("meta")
136
+ if isinstance(meta, str):
137
+ try:
138
+ meta = json.loads(meta)
139
+ except (ValueError, TypeError):
140
+ meta = None
141
+ task_info = meta.get("subagent_task") if isinstance(meta, dict) else None
142
+ if isinstance(task_info, dict):
143
+ self._subagent(
144
+ instance, agent=str(task_info.get("agent") or "?"),
145
+ display=str(task_info.get("display") or ""),
146
+ task=str(task_info.get("task") or ""),
147
+ ).update({k: task_info[k] for k in
148
+ ("status", "steps", "changes") if k in task_info})
149
+ continue
150
+ block = self._subagent(instance)
151
+ role = row.get("role")
152
+ content = str(row.get("content") or "").strip()
153
+ if role == "assistant":
154
+ calls = row.get("tool_calls")
155
+ if isinstance(calls, str):
156
+ try:
157
+ calls = json.loads(calls)
158
+ except (ValueError, TypeError):
159
+ calls = None
160
+ if isinstance(calls, list):
161
+ for call in calls:
162
+ fn = call.get("function") if isinstance(call, dict) else None
163
+ if isinstance(fn, dict):
164
+ name = str(fn.get("name") or "tool")
165
+ block["lines"].append(("tool", f"◆ {name}"))
166
+ if content:
167
+ block["lines"].append(("assistant", content))
168
+ elif role == "tool" and content:
169
+ name = str(row.get("tool_name") or "工具")
170
+ block["lines"].append(("dim", f"{name}:{content}"))
171
+ self.invalidate()
172
+
110
173
  def invalidate(self) -> None:
111
174
  """Presentation refresh hook. The Textual front-end repaints on its
112
175
  own event loop, so this is deliberately a no-op here."""
@@ -246,29 +309,33 @@ class TuiState:
246
309
  # shows why the model's course changed.
247
310
  self.say("user", str(ev.get("text") or ""))
248
311
  elif kind == "subagent_start":
249
- # Per-delegation record (ToolResult.ui): which worker got what
250
- # task — the group's feed line, labeled with the display name
251
- # (plus the instance suffix that keeps same-agent parallel
252
- # delegations distinguishable).
253
- who = _agent_label(ev)
254
- task = str(ev.get("task") or "").replace("\n", " ").strip()
255
- self.say("tool", f"▸ {who}:{task[:120]}" if task else f"▸ {who}")
312
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
313
+ block = self._subagent(
314
+ instance, agent=str(ev.get("agent") or "?"),
315
+ display=str(ev.get("display") or ""),
316
+ task=str(ev.get("task") or ""),
317
+ )
318
+ block.update({"agent": str(ev.get("agent") or block["agent"]),
319
+ "display": str(ev.get("display") or block["display"]),
320
+ "task": str(ev.get("task") or block["task"])})
321
+ self.invalidate()
256
322
  elif kind == "subagent_end":
257
- who = _agent_label(ev)
323
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
324
+ block = self._subagent(
325
+ instance, agent=str(ev.get("agent") or "?"),
326
+ display=str(ev.get("display") or ""),
327
+ )
258
328
  status = str(ev.get("status") or "")
259
- bits = [SUBAGENT_STATUS.get(status, status or "?")]
260
- if ev.get("steps") is not None:
261
- bits.append(f"{ev['steps']} 步")
262
- if ev.get("changes"):
263
- bits.append(f"{ev['changes']} 处改动")
264
- cls = ("ok" if ev.get("ok")
265
- else "warn" if status == "cancelled" else "err")
266
- self.say(cls, f"▪ {who} · " + " · ".join(bits))
329
+ block.update(status=status or block["status"],
330
+ steps=ev.get("steps"), changes=ev.get("changes", 0))
331
+ self.invalidate()
267
332
  elif kind == "subagent_progress":
268
- # Live heartbeat (kernel on_subagent_event, wired in
269
- # register_subagents): each worker's tool calls and outputs,
270
- # prefixed so parallel workers stay distinguishable.
271
- who = _agent_label(ev)
333
+ # Live worker output belongs to its independent instance block.
334
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
335
+ block = self._subagent(
336
+ instance, agent=str(ev.get("agent") or "?"),
337
+ display=str(ev.get("display") or ""),
338
+ )
272
339
  inner = ev.get("event") or {}
273
340
  t = inner.get("type")
274
341
  if t == "tool_call":
@@ -280,7 +347,10 @@ class TuiState:
280
347
  except (ValueError, TypeError):
281
348
  args = {}
282
349
  args = args if isinstance(args, dict) else {}
283
- self.say("tool", f"[{who}] ◆ {tool_call_label(name, args)}")
350
+ label = f"◆ {tool_call_label(name, args)}"
351
+ self.add_subagent_line(instance, "tool", label,
352
+ agent=block["agent"],
353
+ display=block["display"])
284
354
  elif t == "tool_result":
285
355
  ok = bool(inner.get("ok"))
286
356
  label = str(inner.get("summary") or "").replace("\n", " ")
@@ -290,17 +360,25 @@ class TuiState:
290
360
  label = detail if len(detail) > len(label) else label
291
361
  elif detail:
292
362
  label = f"{label} · {detail}" if label else detail
293
- self.say("ok" if ok else "err",
294
- f"[{who}] {'✓' if ok else '✗'} {label}")
363
+ self.add_subagent_line(instance, "ok" if ok else "err",
364
+ f"{'✓' if ok else '✗'} {label}",
365
+ agent=block["agent"],
366
+ display=block["display"])
295
367
  elif t == "assistant":
296
368
  text = str(inner.get("text") or "").replace("\n", " ").strip()
297
369
  if text:
298
- self.say("dim", f"[{who}] {text[:200]}")
370
+ self.add_subagent_line(instance, "dim", text[:200],
371
+ agent=block["agent"],
372
+ display=block["display"])
299
373
  elif t == "error":
300
374
  msg = str(inner.get("message") or "出错").replace("\n", " ")
301
- self.say("err", f"[{who}] {msg[:200]}")
375
+ self.add_subagent_line(instance, "err", msg[:200],
376
+ agent=block["agent"],
377
+ display=block["display"])
302
378
  elif t == "cancelled":
303
- self.say("warn", f"[{who}] 已取消")
379
+ self.add_subagent_line(instance, "warn", "已取消",
380
+ agent=block["agent"],
381
+ display=block["display"])
304
382
  elif kind == "done":
305
383
  status = str(ev.get("status") or _STATUS_DONE)
306
384
  self.last_status = status
@@ -461,6 +539,10 @@ def transcript_feed_lines(rows):
461
539
 
462
540
  out = []
463
541
  for m in rows:
542
+ # Subagent transcripts are rendered in their instance cards, never
543
+ # folded into the orchestrator's shared conversation stream.
544
+ if m.get("subagent"):
545
+ continue
464
546
  role = m.get("role")
465
547
  content = (m.get("content") or "").strip()
466
548
  if role == "user" and content:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.6
3
+ Version: 0.1.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.1.4
42
+ Requires-Dist: lithe>=0.1.5
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -1,4 +1,4 @@
1
- lithe>=0.1.4
1
+ lithe>=0.1.5
2
2
  prompt-toolkit>=3.0.38
3
3
  textual>=1.0
4
4
 
@@ -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.1.4", "prompt-toolkit>=3.0.38", "textual>=1.0"]
12
+ dependencies = ["lithe>=0.1.5", "prompt-toolkit>=3.0.38", "textual>=1.0"]
13
13
  keywords = ["agent", "llm", "react", "cli", "tool-calling"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
@@ -86,6 +86,26 @@ def test_plain_repl_copy_command_reaches_the_clipboard(
86
86
  assert "已复制最后一条回答" in out and "pbcopy" in out
87
87
 
88
88
 
89
+ def test_transcript_can_include_subagent_instance_rows(tmp_path):
90
+ wb = Workbench(make_config(tmp_path, []))
91
+ wb.open(title="有子任务的会话")
92
+ cid = wb.current["id"]
93
+ rid = "subagent-history-test"
94
+ wb.store.create_run(rid, wb.cfg.user_id, "任务", conversation_id=cid)
95
+ from lithe.bundles.store.protocol import StoredMessage
96
+
97
+ wb.store.add_message(StoredMessage(
98
+ role="user", content="主任务", run_id=rid, user_id=wb.cfg.user_id
99
+ ))
100
+ wb.store.add_message(StoredMessage(
101
+ role="user", content="子任务", run_id=rid, user_id=wb.cfg.user_id,
102
+ subagent="researcher:abcd",
103
+ ))
104
+ assert [r["content"] for r in wb.sessions.transcript(cid)] == ["主任务"]
105
+ all_rows = wb.sessions.transcript(cid, last=0, include_subagents=True)
106
+ assert [r.get("subagent") for r in all_rows] == [None, "researcher:abcd"]
107
+
108
+
89
109
  def test_sessions_subcommand_lists_renames_deletes(tmp_path, capsys):
90
110
  from lithe_cli.main import main
91
111
 
@@ -179,7 +179,7 @@ def test_delegation_renders_live_progress_and_records(tmp_path, capsys):
179
179
  # same-agent parallel delegations distinguishable
180
180
  assert re.search(r"\[检索员·[0-9a-f]{4}\]", out)
181
181
  assert "a.md 的内容是待办清单" in out
182
- # per-agent start/end records follow the delegation's tool_result
182
+ # the plain REPL still renders task lifecycle records after the live output
183
183
  assert re.search(r"▸ 检索员·[0-9a-f]{4}:找一下 a\.md 里写了什么", out)
184
184
  assert re.search(r"▪ 检索员·[0-9a-f]{4} · 完成", out)
185
185
  # the footer carries the delegation footprint
@@ -251,23 +251,62 @@ def test_tui_folds_subagent_events():
251
251
 
252
252
  state = TuiState("m", "/ws", 5)
253
253
  state.on_event({"type": "subagent_start", "agent": "researcher",
254
- "display": "检索员", "task": "查 a.md"})
254
+ "display": "检索员", "task": "查 a.md",
255
+ "instance": "researcher:a111"})
255
256
  state.on_event({"type": "subagent_progress", "agent": "researcher",
256
- "display": "检索员", "event": {
257
+ "display": "检索员", "instance": "researcher:a111",
258
+ "event": {
257
259
  "type": "tool_call", "name": "read_file",
258
260
  "args": '{"path": "a.md"}'}})
259
261
  state.on_event({"type": "subagent_progress", "agent": "researcher",
260
- "display": "检索员", "event": {
262
+ "display": "检索员", "instance": "researcher:a111",
263
+ "event": {
261
264
  "type": "tool_result", "ok": True,
262
265
  "summary": "读取 a.md"}})
263
266
  state.on_event({"type": "subagent_end", "agent": "researcher",
264
- "display": "检索员", "status": "done", "steps": 2,
267
+ "display": "检索员", "instance": "researcher:a111",
268
+ "status": "done", "steps": 2,
265
269
  "changes": 0, "ok": True})
266
270
  state.on_event({"type": "done", "status": "done", "steps": 2,
267
271
  "subagent_delegations": 1, "subagent_cost": 0.01})
272
+ assert len(state.subagents) == 1
273
+ block = state.subagents["researcher:a111"]
274
+ assert block["task"] == "查 a.md"
275
+ assert block["status"] == "done" and block["steps"] == 2
276
+ lines = "\n".join(text for _, text in block["lines"])
277
+ assert "read_file" in lines and "a.md" in lines
278
+ assert "✓ 读取 a.md" in lines
268
279
  feed = "\n".join(text for _, text in state.feed)
269
- assert "▸ 检索员:查 a.md" in feed
270
- assert "[检索员] ◆ read_file · 读取 a.md" in feed
271
- assert "[检索员] ✓ 读取 a.md" in feed
272
- assert "▪ 检索员 · 完成 · 2 步" in feed
273
280
  assert "委派 1 次" in feed and "子代理花费 $0.0100" in feed
281
+ assert not any("检索员" in text for _, text in state.feed)
282
+
283
+
284
+ def test_tui_subagent_instances_and_history_restore():
285
+ from lithe_cli.tui import TuiState, transcript_feed_lines
286
+
287
+ state = TuiState("m", "/ws", 5)
288
+ rows = [
289
+ {"role": "user", "content": "检查 alpha", "subagent": "researcher:a111",
290
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
291
+ "task": "检查 alpha", "status": "running"}}},
292
+ {"role": "assistant", "content": "发现 alpha", "subagent": "researcher:a111"},
293
+ {"role": "tool", "tool_name": "read_file", "content": "读取 alpha.txt",
294
+ "subagent": "researcher:a111"},
295
+ {"role": "assistant", "content": None, "subagent": "researcher:a111",
296
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
297
+ "task": "检查 alpha", "status": "done",
298
+ "steps": 2}}},
299
+ {"role": "user", "content": "检查 beta", "subagent": "researcher:b222",
300
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
301
+ "task": "检查 beta", "status": "failed"}}},
302
+ ]
303
+ state.feed.extend(transcript_feed_lines(rows))
304
+ state.restore_subagents(rows)
305
+ assert len(state.subagents) == 2
306
+ assert state.subagents["researcher:a111"]["status"] == "done"
307
+ assert state.subagents["researcher:a111"]["steps"] == 2
308
+ assert "发现 alpha" in " ".join(
309
+ text for _, text in state.subagents["researcher:a111"]["lines"]
310
+ )
311
+ assert state.subagents["researcher:b222"]["status"] == "failed"
312
+ assert not any("alpha" in text or "beta" in text for _, text in state.feed)
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ from types import SimpleNamespace
6
7
 
7
8
  import pytest
8
9
 
@@ -18,6 +19,7 @@ from lithe_cli.ttui import ( # noqa: E402
18
19
  ConfirmModal,
19
20
  LitheApp,
20
21
  PickerModal,
22
+ SubagentCard,
21
23
  footer_text,
22
24
  header_text,
23
25
  sidebar_markup,
@@ -394,6 +396,89 @@ async def _settle_bottom(pilot, conv):
394
396
  return
395
397
 
396
398
 
399
+ def test_subagent_cards_mount_and_search_independently(tmp_path):
400
+ async def scenario():
401
+ app = _app(tmp_path, [])
402
+ async with app.run_test() as pilot:
403
+ state = app.state
404
+ state.on_event({"type": "subagent_start", "agent": "researcher",
405
+ "display": "检索员", "task": "找 alpha",
406
+ "instance": "researcher:a111"})
407
+ state.on_event({"type": "subagent_progress", "agent": "researcher",
408
+ "display": "检索员", "instance": "researcher:a111",
409
+ "event": {"type": "tool_result", "ok": True,
410
+ "summary": "发现 alpha.txt"}})
411
+ state.on_event({"type": "subagent_start", "agent": "coder",
412
+ "display": "编码员", "task": "实现 beta",
413
+ "instance": "coder:b222"})
414
+ state.on_event({"type": "subagent_progress", "agent": "coder",
415
+ "display": "编码员", "instance": "coder:b222",
416
+ "event": {"type": "tool_result", "ok": True,
417
+ "summary": "修改 beta.py"}})
418
+ app._sync_feed()
419
+ await pilot.pause()
420
+ cards = list(app.query(SubagentCard))
421
+ assert len(cards) == 2
422
+ assert {card.instance for card in cards} == {
423
+ "researcher:a111", "coder:b222"
424
+ }
425
+ card = next(c for c in cards if c.instance == "researcher:a111")
426
+ card._expanded = True
427
+ card.set_data(state.subagents[card.instance])
428
+ await pilot.pause()
429
+ search = card.query_one(".subagent-search")
430
+ search.value = "alpha"
431
+ await pilot.pause()
432
+ output = str(card.query_one(".subagent-output").content)
433
+ assert "alpha" in output
434
+ assert "beta" not in output
435
+ other = next(c for c in cards if c.instance == "coder:b222")
436
+ assert other._search == ""
437
+
438
+ asyncio.run(scenario())
439
+
440
+
441
+ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
442
+ from lithe.bundles.store.protocol import StoredMessage
443
+ from lithe_cli.workbench import Workbench
444
+
445
+ cfg = make_config(tmp_path, [])
446
+ wb = Workbench(cfg)
447
+ session = wb.new_session(title="恢复子任务")
448
+ cid = session["id"]
449
+ run_id = "persisted-subagent-run"
450
+ wb.store.create_run(run_id, cfg.user_id, "检查项目",
451
+ conversation_id=cid)
452
+ wb.store.add_message(StoredMessage(
453
+ role="user", content="检查 README", run_id=run_id,
454
+ user_id=cfg.user_id, subagent="researcher:abcd",
455
+ meta={"subagent_task": {"agent": "researcher", "display": "检索员",
456
+ "task": "检查 README", "instance": "researcher:abcd",
457
+ "status": "done", "steps": 3}},
458
+ ))
459
+ wb.store.add_message(StoredMessage(
460
+ role="assistant", content="README 包含使用说明", run_id=run_id,
461
+ user_id=cfg.user_id, subagent="researcher:abcd",
462
+ ))
463
+ app = LitheApp(cfg, None, "chat",
464
+ args=SimpleNamespace(resume=str(cid), cont=False, title=None))
465
+
466
+ async def scenario():
467
+ async with app.run_test() as pilot:
468
+ await pilot.pause()
469
+ cards = list(app.query(SubagentCard))
470
+ assert len(cards) == 1
471
+ card = cards[0]
472
+ assert card.instance == "researcher:abcd"
473
+ assert "检查 README" in str(card.query_one(".subagent-heading").label)
474
+ assert app.state.subagents[card.instance]["status"] == "done"
475
+ assert any("README 包含使用说明" in line
476
+ for _cls, line in app.state.subagents[card.instance]["lines"])
477
+ assert not any("检查 README" in line for _cls, line in app.state.feed)
478
+
479
+ asyncio.run(scenario())
480
+
481
+
397
482
  def test_sync_feed_follows_only_when_at_bottom(tmp_path):
398
483
  """Scrolling up to re-read earlier output sticks; new events must not
399
484
  yank the reader back to the bottom."""
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes