lithe-cli 0.8.6__tar.gz → 0.8.8__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.

Files changed (32) hide show
  1. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/PKG-INFO +18 -8
  2. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/README.md +17 -7
  3. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/profiles.py +48 -22
  5. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/sessions.py +3 -0
  6. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/ttui.py +38 -5
  7. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/tui.py +0 -18
  8. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/PKG-INFO +18 -8
  9. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_cli_sessions.py +13 -0
  10. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_profiles.py +53 -0
  11. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_ttui.py +126 -0
  12. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/LICENSE +0 -0
  13. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/__main__.py +0 -0
  14. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/agent.py +0 -0
  15. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/commands.py +0 -0
  16. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/config.py +0 -0
  17. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/main.py +0 -0
  18. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/prompts.py +0 -0
  19. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/py.typed +0 -0
  20. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/setup.py +0 -0
  21. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/ui.py +0 -0
  22. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli/workbench.py +0 -0
  23. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/SOURCES.txt +0 -0
  24. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/dependency_links.txt +0 -0
  25. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/entry_points.txt +0 -0
  26. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/requires.txt +0 -0
  27. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/lithe_cli.egg-info/top_level.txt +0 -0
  28. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/pyproject.toml +0 -0
  29. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/setup.cfg +0 -0
  30. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_cli.py +0 -0
  31. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_tui_v2.py +0 -0
  32. {lithe_cli-0.8.6 → lithe_cli-0.8.8}/tests/test_workbench.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.8.6
3
+ Version: 0.8.8
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
 
@@ -146,7 +146,9 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
146
146
 
147
147
  `--stream` streams tokens as they generate; `-v` adds per-call
148
148
  usage/context gauges; `--max-steps` caps the tool loop;
149
- `--context-window` enables fullness gauges.
149
+ `--context-window` enables fullness gauges; `--reasoning-effort LEVEL`
150
+ sets the reasoning intensity for one invocation (flag > profile field;
151
+ `/reasoning` adjusts it in-session).
150
152
 
151
153
  ### Full-screen interface
152
154
 
@@ -158,7 +160,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
158
160
  工具/待办、用量:
159
161
 
160
162
  ```text
161
- lithe 0.8.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
163
+ lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
162
164
  ╭──────────────────────────────────────╮╭──────────────────────────╮
163
165
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
164
166
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -171,7 +173,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
171
173
  ╰──────────────────────────────────────╯╰──────────────────────────╯
172
174
  Tab 采纳 → /model /models /new
173
175
  lithe ❯ _
174
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · /help
176
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
175
177
  ```
176
178
 
177
179
  **Switch without leaving the screen**: `F3` opens the session picker
@@ -183,7 +185,11 @@ cancel it — its badge stays lit and the pane rebuilds from the store when
183
185
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
184
186
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
185
187
  and `↑`/`↓` recall the persistent input history. `Ctrl+C` cancels the
186
- current turn and exits when idle.
188
+ current turn (a second press during the same turn force-exits) and exits
189
+ when idle. Typing plain text mid-turn returns it to the input box with a
190
+ note instead of dropping it; slash commands work while a turn runs. The
191
+ transcript follows new output only while you're at the bottom — scroll
192
+ up to re-read and your position sticks.
187
193
 
188
194
  Text selection uses the terminal's native `Shift+drag` (hide the sidebar
189
195
  with F2 first if it grabs both panes). Pipes and CI keep the plain
@@ -213,8 +219,9 @@ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
213
219
 
214
220
  The per-turn knobs don't need a restart: `/set` (or `F5`) opens a picker
215
221
  where `Enter` toggles a capability, and typed forms set anything —
216
- `/set shell on`, `/set code off`, `/set vision`, `/set max-steps 50`,
217
- `/set timeout 240`, `/set attempts 3`, `/set stream on`, `/set verbose`.
222
+ `/set shell on`, `/set code off`, `/set vision`, `/set document on`,
223
+ `/set max-steps 50`, `/set timeout 240`, `/set attempts 3`,
224
+ `/set stream on`, `/set verbose`.
218
225
  Settings apply to the **next turn** (the running turn keeps its own tool
219
226
  set), stay session-scoped (nothing is written to the profile), and
220
227
  turning `shell` on restates its trust warning. `/tools` re-derives the
@@ -240,10 +247,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
240
247
  | `--skills DIR` | `load_skill` | markdown skill library; defaults to `$LITHE_HOME/skills` when it exists, `--skills ""` disables |
241
248
  | `--download` | `download_file` | SSRF-guarded, size-capped network fetch |
242
249
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
250
+ | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
251
+ | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
243
252
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
244
253
 
245
254
  ```bash
246
255
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
256
+ $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
247
257
  $ lithe run --shell "检查当前目录的项目状态"
248
258
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
249
259
  ```
@@ -312,7 +322,7 @@ keys, inline wizard validation, and persistent history.
312
322
  | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
313
323
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
314
324
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
315
- | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; Up/Ctrl+R recall) |
325
+ | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; `↑`/`↓` recall in the TUI, Ctrl+R search in the plain REPL) |
316
326
 
317
327
  ## Design notes
318
328
 
@@ -97,7 +97,9 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
97
97
 
98
98
  `--stream` streams tokens as they generate; `-v` adds per-call
99
99
  usage/context gauges; `--max-steps` caps the tool loop;
100
- `--context-window` enables fullness gauges.
100
+ `--context-window` enables fullness gauges; `--reasoning-effort LEVEL`
101
+ sets the reasoning intensity for one invocation (flag > profile field;
102
+ `/reasoning` adjusts it in-session).
101
103
 
102
104
  ### Full-screen interface
103
105
 
@@ -109,7 +111,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
109
111
  工具/待办、用量:
110
112
 
111
113
  ```text
112
- lithe 0.8.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
114
+ lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
113
115
  ╭──────────────────────────────────────╮╭──────────────────────────╮
114
116
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
115
117
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -122,7 +124,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
122
124
  ╰──────────────────────────────────────╯╰──────────────────────────╯
123
125
  Tab 采纳 → /model /models /new
124
126
  lithe ❯ _
125
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · /help
127
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
126
128
  ```
127
129
 
128
130
  **Switch without leaving the screen**: `F3` opens the session picker
@@ -134,7 +136,11 @@ cancel it — its badge stays lit and the pane rebuilds from the store when
134
136
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
135
137
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
136
138
  and `↑`/`↓` recall the persistent input history. `Ctrl+C` cancels the
137
- current turn and exits when idle.
139
+ current turn (a second press during the same turn force-exits) and exits
140
+ when idle. Typing plain text mid-turn returns it to the input box with a
141
+ note instead of dropping it; slash commands work while a turn runs. The
142
+ transcript follows new output only while you're at the bottom — scroll
143
+ up to re-read and your position sticks.
138
144
 
139
145
  Text selection uses the terminal's native `Shift+drag` (hide the sidebar
140
146
  with F2 first if it grabs both panes). Pipes and CI keep the plain
@@ -164,8 +170,9 @@ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
164
170
 
165
171
  The per-turn knobs don't need a restart: `/set` (or `F5`) opens a picker
166
172
  where `Enter` toggles a capability, and typed forms set anything —
167
- `/set shell on`, `/set code off`, `/set vision`, `/set max-steps 50`,
168
- `/set timeout 240`, `/set attempts 3`, `/set stream on`, `/set verbose`.
173
+ `/set shell on`, `/set code off`, `/set vision`, `/set document on`,
174
+ `/set max-steps 50`, `/set timeout 240`, `/set attempts 3`,
175
+ `/set stream on`, `/set verbose`.
169
176
  Settings apply to the **next turn** (the running turn keeps its own tool
170
177
  set), stay session-scoped (nothing is written to the profile), and
171
178
  turning `shell` on restates its trust warning. `/tools` re-derives the
@@ -191,10 +198,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
191
198
  | `--skills DIR` | `load_skill` | markdown skill library; defaults to `$LITHE_HOME/skills` when it exists, `--skills ""` disables |
192
199
  | `--download` | `download_file` | SSRF-guarded, size-capped network fetch |
193
200
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
201
+ | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
202
+ | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
194
203
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
195
204
 
196
205
  ```bash
197
206
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
207
+ $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
198
208
  $ lithe run --shell "检查当前目录的项目状态"
199
209
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
200
210
  ```
@@ -263,7 +273,7 @@ keys, inline wizard validation, and persistent history.
263
273
  | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
264
274
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
265
275
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
266
- | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; Up/Ctrl+R recall) |
276
+ | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; `↑`/`↓` recall in the TUI, Ctrl+R search in the plain REPL) |
267
277
 
268
278
  ## Design notes
269
279
 
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.8.6"
3
+ __version__ = "0.8.8"
@@ -39,6 +39,7 @@ user typed into the wizard or wrote by hand.
39
39
  from __future__ import annotations
40
40
 
41
41
  import json
42
+ import os
42
43
  import re
43
44
  from pathlib import Path
44
45
  from typing import Any
@@ -89,26 +90,34 @@ def _clean_endpoint(data: dict) -> dict:
89
90
 
90
91
 
91
92
  class ProfileStore:
92
- """Read/modify the profile file; every mutation rewrites it atomically
93
- enough for a CLI (write-in-place with owner-only perms, like the wizard
94
- always did)."""
93
+ """Read/modify the profile file; every mutation rewrites it via an
94
+ atomic temp-file replace (the previous version survives as ``.bak``)
95
+ with owner-only perms — the file holds every saved API key."""
95
96
 
96
97
  def __init__(self, path: Path | None = None):
97
98
  self.path = path or config_file()
98
99
 
99
100
  # -- load / save ----------------------------------------------------------
100
101
 
102
+ def _read_json(self, path: Path):
103
+ """Parsed JSON at *path*, or None when unreadable/corrupt."""
104
+ try:
105
+ return json.loads(path.read_text(encoding="utf-8"))
106
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
107
+ return None
108
+
101
109
  def load(self) -> dict:
102
110
  """Normalized ``{"active": str | None, "profiles": {name: endpoint}}``.
103
111
 
104
- Corrupt files and foreign shapes read as empty — a bad edit costs one
105
- re-prompt, not a broken CLI (same policy as the old flat loader).
112
+ A corrupt main file falls back to the ``.bak`` left by the last
113
+ atomic save before degrading to empty — a bad edit or a torn write
114
+ costs the edit, not every saved profile.
106
115
  """
107
- try:
108
- data = json.loads(self.path.read_text(encoding="utf-8"))
109
- except (OSError, json.JSONDecodeError):
110
- return {"active": None, "profiles": {}}
111
- if not isinstance(data, dict):
116
+ data = self._read_json(self.path)
117
+ if data is None:
118
+ data = self._read_json(
119
+ self.path.parent / (self.path.name + ".bak"))
120
+ if data is None or not isinstance(data, dict):
112
121
  return {"active": None, "profiles": {}}
113
122
  if "profiles" not in data: # legacy flat triple → profile "default"
114
123
  endpoint = _clean_endpoint(data)
@@ -135,13 +144,23 @@ class ProfileStore:
135
144
  self.path.parent.mkdir(parents=True, exist_ok=True)
136
145
  if fresh_dir:
137
146
  _restrict_to_owner(self.path.parent, directory=True)
138
- self.path.touch(exist_ok=True)
139
- _restrict_to_owner(self.path)
140
147
  payload = {"version": 2, "active": active, "profiles": profiles}
141
- self.path.write_text(
142
- json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
143
- encoding="utf-8",
144
- )
148
+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
149
+ # Atomic replace: a crash mid-write must never destroy every saved
150
+ # profile (API keys included). The old file survives as .bak for the
151
+ # load-time fallback; a failed rename chain leaves one of the two
152
+ # intact on disk.
153
+ tmp = self.path.parent / (self.path.name + ".tmp")
154
+ bak = self.path.parent / (self.path.name + ".bak")
155
+ tmp.write_text(text, encoding="utf-8")
156
+ _restrict_to_owner(tmp)
157
+ if self.path.exists():
158
+ try:
159
+ os.replace(self.path, bak)
160
+ _restrict_to_owner(bak) # the backup holds keys too
161
+ except OSError:
162
+ pass # best effort; the main replace below is what matters
163
+ os.replace(tmp, self.path)
145
164
  return self.path
146
165
 
147
166
  # -- queries --------------------------------------------------------------
@@ -196,18 +215,25 @@ class ProfileStore:
196
215
  f"档案名 {name!r} 不合法(仅限字母、数字、点、下划线、连字符)"
197
216
  )
198
217
  data = self.load()
199
- endpoint = {"api_key": api_key.strip(), "base_url": base_url.strip(),
200
- "model": model.strip()}
218
+ # Start from the existing endpoint so fields the caller doesn't
219
+ # know about — provider, reasoning_effort, document_format, a
220
+ # hand-tuned context_window — survive a re-config instead of being
221
+ # silently erased. The caller's triple always overwrites.
222
+ endpoint = dict(data["profiles"].get(name) or {})
223
+ endpoint.update({"api_key": api_key.strip(),
224
+ "base_url": base_url.strip(),
225
+ "model": model.strip()})
201
226
  if context_window:
202
227
  endpoint["context_window"] = int(context_window)
203
228
  if provider and provider.strip():
204
229
  endpoint["provider"] = provider.strip()
205
230
  if document_format and document_format.strip():
206
231
  endpoint["document_format"] = document_format.strip()
207
- # keep a previously cached model list when the base_url is unchanged
208
- old = data["profiles"].get(name) or {}
209
- if old.get("cached_models") and old.get("base_url") == endpoint["base_url"]:
210
- endpoint["cached_models"] = old["cached_models"]
232
+ # a cached model list is only meaningful for the same endpoint
233
+ if endpoint.get("cached_models") \
234
+ and data["profiles"].get(name, {}).get("base_url") \
235
+ != endpoint["base_url"]:
236
+ endpoint.pop("cached_models", None)
211
237
  data["profiles"][name] = {k: v for k, v in endpoint.items() if v}
212
238
  if data["active"] is None:
213
239
  data["active"] = name
@@ -46,6 +46,9 @@ class SessionManager:
46
46
  def resolve(self, ident: str | int) -> dict | None:
47
47
  """Numeric id or unique title prefix → conversation row."""
48
48
  text = str(ident).strip()
49
+ # The TUI's completion suggests ids as "#12" — accept that shape.
50
+ if text.startswith("#") and text[1:].isdigit():
51
+ text = text[1:]
49
52
  if not text:
50
53
  return None
51
54
  if text.isdigit():
@@ -380,6 +380,7 @@ class LitheApp(App):
380
380
  self.mode = mode
381
381
  self.args = args
382
382
  self._shown = 0 # feed lines already mounted
383
+ self._cancel_asked = False # first Ctrl+C cancels, second exits
383
384
 
384
385
  # -- composition ----------------------------------------------------------
385
386
 
@@ -497,6 +498,10 @@ class LitheApp(App):
497
498
  def _sync_feed(self) -> None:
498
499
  conv = self.query_one("#conv", VerticalScroll)
499
500
  streaming = self.query_one("#streaming", Static)
501
+ # Follow the feed only when the reader is already at (or near) the
502
+ # bottom: scrolling up to re-read earlier output mid-run must stick,
503
+ # not be yanked back to the bottom on every event.
504
+ at_bottom = conv.scroll_y >= conv.max_scroll_y - 1
500
505
  feed = self.state.feed
501
506
  while self._shown < len(feed):
502
507
  cls, text = feed[self._shown]
@@ -510,7 +515,14 @@ class LitheApp(App):
510
515
  streaming.update(self.state.streaming)
511
516
  else:
512
517
  streaming.update("")
513
- conv.scroll_end(animate=False)
518
+ if at_bottom:
519
+ conv.scroll_end(animate=False)
520
+ # The pane's extent only grows once the newly mounted lines lay
521
+ # out (next refresh). Anchoring again after that refresh keeps
522
+ # the follow exact: otherwise the scroll lands one refresh short
523
+ # of the bottom and the next event's at-bottom check mis-reads
524
+ # "still reading up there" and stops following for good.
525
+ conv.call_after_refresh(conv.scroll_end, animate=False)
514
526
 
515
527
  def _refresh_chrome(self) -> None:
516
528
  self.query_one("#top", Static).update(
@@ -529,7 +541,6 @@ class LitheApp(App):
529
541
  if t == "session_busy":
530
542
  if cid == self._current_cid():
531
543
  self.state.running = True
532
- self.state.scroll = 0
533
544
  handle = self.wb.turns.get(cid) or {}
534
545
  self.state.stop = handle.get("stop")
535
546
  self._refresh_meta()
@@ -539,6 +550,7 @@ class LitheApp(App):
539
550
  if cid == self._current_cid():
540
551
  self.state.running = False
541
552
  self.state.stop = None
553
+ self._cancel_asked = False
542
554
  self._refresh_meta()
543
555
  self._refresh_chrome()
544
556
  return
@@ -589,7 +601,17 @@ class LitheApp(App):
589
601
  event.input.value = ""
590
602
  self.query_one("#suggest", Static).display = False
591
603
  self.query_one("#prompt", HistoryInput).record(line)
592
- if not line or self.state.running:
604
+ if not line:
605
+ return
606
+ if self.state.running and not line.startswith("/"):
607
+ # Plain text mid-turn is not silently discarded: it goes back
608
+ # into the input box for resubmitting when the turn ends.
609
+ # Slash commands still dispatch below — the workbench supports
610
+ # them while a turn runs (/model, /resume, ...), matching the
611
+ # plain REPL.
612
+ self.query_one("#prompt", HistoryInput).value = line
613
+ self.state.say("warn", "本轮还在进行中,未发送;文本已放回输入框,命令仍可用")
614
+ self._sync_feed()
593
615
  return
594
616
  if not line.startswith("/"):
595
617
  self.state.say("user", line)
@@ -864,8 +886,18 @@ class LitheApp(App):
864
886
 
865
887
  def action_cancel_or_exit(self) -> None:
866
888
  if self.state.running:
867
- self.wb.cancel(self._current_cid())
868
- self.state.say("warn", "(正在取消本轮…)")
889
+ if not self.wb.cancel(self._current_cid()):
890
+ # One-shot run mode drives no workbench turn, so wb.cancel
891
+ # has nothing to stop — fall back to the run's own stop
892
+ # handle (the README's "Ctrl+C cancels the current turn").
893
+ stop = getattr(self.state, "stop", None)
894
+ if stop is not None:
895
+ stop.set()
896
+ if self._cancel_asked:
897
+ self.exit() # second Ctrl+C during the same turn: force exit
898
+ return
899
+ self._cancel_asked = True
900
+ self.state.say("warn", "(正在取消本轮,再按一次 Ctrl+C 退出)")
869
901
  self._sync_feed()
870
902
  else:
871
903
  self.exit()
@@ -890,6 +922,7 @@ class LitheApp(App):
890
922
  finally:
891
923
  self.state.running = False
892
924
  self.state.stop = None
925
+ self._cancel_asked = False
893
926
  self._sync_feed()
894
927
  self._refresh_chrome()
895
928
  self.query_one("#prompt", Input).disabled = False
@@ -86,7 +86,6 @@ class TuiState:
86
86
  self.tools: list[dict] = []
87
87
  self.feed: list[tuple[str, str]] = []
88
88
  self.streaming = ""
89
- self.scroll = 0
90
89
  self.show_sidebar = True
91
90
  self.started: float | None = None
92
91
  self.last_status: str | None = None
@@ -94,16 +93,9 @@ class TuiState:
94
93
 
95
94
  # -- feed ---------------------------------------------------------------
96
95
 
97
- def _wrapped_rows(self, text: str) -> int:
98
- # Row count without a terminal width: the Textual front-end wraps
99
- # text itself, so this only feeds the scroll bookkeeping.
100
- return len(text.splitlines() or [""])
101
-
102
96
  def say(self, cls: str, text: str) -> None:
103
97
  lines = str(text).splitlines() or [""]
104
98
  self.feed.extend((cls, line) for line in lines)
105
- if self.scroll:
106
- self.scroll += sum(self._wrapped_rows(line) for line in lines)
107
99
  self.invalidate()
108
100
 
109
101
  def invalidate(self) -> None:
@@ -151,7 +143,6 @@ class TuiState:
151
143
  if kind == "run_start":
152
144
  self.status = "思考中"
153
145
  self.step = 0
154
- self.scroll = 0
155
146
  # A previous round that died without a done event (host-level
156
147
  # failure) still burned tokens: keep its measured usage instead
157
148
  # of silently dropping it when the accumulators reset.
@@ -168,22 +159,13 @@ class TuiState:
168
159
  self.status = "思考中"
169
160
  elif kind == "assistant_delta":
170
161
  text = str(ev.get("text") or "")
171
- if self.scroll and text:
172
- self.scroll += (
173
- self._wrapped_rows(self.streaming + text)
174
- - self._wrapped_rows(self.streaming)
175
- )
176
162
  self.streaming += text
177
163
  elif kind == "assistant":
178
164
  text = str(ev.get("text") or "")
179
165
  final_text = text or self.streaming
180
- streamed_rows = self._wrapped_rows(self.streaming) if self.streaming else 0
181
166
  if final_text:
182
167
  lines = final_text.splitlines() or [""]
183
168
  self.feed.extend(("assistant", line) for line in lines)
184
- if self.scroll:
185
- final_rows = sum(self._wrapped_rows(line) for line in lines)
186
- self.scroll += final_rows - streamed_rows
187
169
  self.streaming = ""
188
170
  elif kind == "tool_call":
189
171
  name = str(ev.get("name") or "tool")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.8.6
3
+ Version: 0.8.8
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
 
@@ -146,7 +146,9 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
146
146
 
147
147
  `--stream` streams tokens as they generate; `-v` adds per-call
148
148
  usage/context gauges; `--max-steps` caps the tool loop;
149
- `--context-window` enables fullness gauges.
149
+ `--context-window` enables fullness gauges; `--reasoning-effort LEVEL`
150
+ sets the reasoning intensity for one invocation (flag > profile field;
151
+ `/reasoning` adjusts it in-session).
150
152
 
151
153
  ### Full-screen interface
152
154
 
@@ -158,7 +160,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
158
160
  工具/待办、用量:
159
161
 
160
162
  ```text
161
- lithe 0.8.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
163
+ lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
162
164
  ╭──────────────────────────────────────╮╭──────────────────────────╮
163
165
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
164
166
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -171,7 +173,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
171
173
  ╰──────────────────────────────────────╯╰──────────────────────────╯
172
174
  Tab 采纳 → /model /models /new
173
175
  lithe ❯ _
174
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · /help
176
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
175
177
  ```
176
178
 
177
179
  **Switch without leaving the screen**: `F3` opens the session picker
@@ -183,7 +185,11 @@ cancel it — its badge stays lit and the pane rebuilds from the store when
183
185
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
184
186
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
185
187
  and `↑`/`↓` recall the persistent input history. `Ctrl+C` cancels the
186
- current turn and exits when idle.
188
+ current turn (a second press during the same turn force-exits) and exits
189
+ when idle. Typing plain text mid-turn returns it to the input box with a
190
+ note instead of dropping it; slash commands work while a turn runs. The
191
+ transcript follows new output only while you're at the bottom — scroll
192
+ up to re-read and your position sticks.
187
193
 
188
194
  Text selection uses the terminal's native `Shift+drag` (hide the sidebar
189
195
  with F2 first if it grabs both panes). Pipes and CI keep the plain
@@ -213,8 +219,9 @@ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
213
219
 
214
220
  The per-turn knobs don't need a restart: `/set` (or `F5`) opens a picker
215
221
  where `Enter` toggles a capability, and typed forms set anything —
216
- `/set shell on`, `/set code off`, `/set vision`, `/set max-steps 50`,
217
- `/set timeout 240`, `/set attempts 3`, `/set stream on`, `/set verbose`.
222
+ `/set shell on`, `/set code off`, `/set vision`, `/set document on`,
223
+ `/set max-steps 50`, `/set timeout 240`, `/set attempts 3`,
224
+ `/set stream on`, `/set verbose`.
218
225
  Settings apply to the **next turn** (the running turn keeps its own tool
219
226
  set), stay session-scoped (nothing is written to the profile), and
220
227
  turning `shell` on restates its trust warning. `/tools` re-derives the
@@ -240,10 +247,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
240
247
  | `--skills DIR` | `load_skill` | markdown skill library; defaults to `$LITHE_HOME/skills` when it exists, `--skills ""` disables |
241
248
  | `--download` | `download_file` | SSRF-guarded, size-capped network fetch |
242
249
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
250
+ | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
251
+ | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
243
252
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
244
253
 
245
254
  ```bash
246
255
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
256
+ $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
247
257
  $ lithe run --shell "检查当前目录的项目状态"
248
258
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
249
259
  ```
@@ -312,7 +322,7 @@ keys, inline wizard validation, and persistent history.
312
322
  | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
313
323
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
314
324
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
315
- | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; Up/Ctrl+R recall) |
325
+ | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; `↑`/`↓` recall in the TUI, Ctrl+R search in the plain REPL) |
316
326
 
317
327
  ## Design notes
318
328
 
@@ -27,6 +27,19 @@ def _make_sessions(tmp_path, n=2):
27
27
  return wb, ids
28
28
 
29
29
 
30
+ def test_resume_accepts_hash_prefixed_id(tmp_path):
31
+ """The TUI completion suggests "#12"; dispatching that token must route."""
32
+ wb, ids = _make_sessions(tmp_path, n=3)
33
+ wb.open() # a fresh current session to switch away from
34
+ r = wb.dispatch(f"/resume #{ids[0]}")
35
+ assert wb.current["id"] == ids[0]
36
+ assert not any(cls == "err" for cls, _ in r.messages)
37
+
38
+ # resolve() itself accepts both shapes
39
+ assert wb.sessions.resolve(f"#{ids[1]}")["id"] == ids[1]
40
+ assert wb.sessions.resolve(str(ids[2]))["id"] == ids[2]
41
+
42
+
30
43
  def test_sessions_subcommand_lists_renames_deletes(tmp_path, capsys):
31
44
  from lithe_cli.main import main
32
45
 
@@ -208,6 +208,59 @@ def test_corrupt_profile_file_reads_empty(tmp_path, monkeypatch):
208
208
  assert ProfileStore().endpoint() == {}
209
209
 
210
210
 
211
+ def test_upsert_preserves_fields_the_caller_does_not_know(tmp_path, monkeypatch):
212
+ """A wizard-era save must not erase provider/reasoning/context fields."""
213
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path))
214
+ store = ProfileStore()
215
+ # hand-tuned profile with every preserved-field flavor
216
+ (tmp_path / "config.json").write_text(
217
+ '{"version": 2, "active": "zai", "profiles": {"zai": {'
218
+ '"api_key": "sk-old", "base_url": "https://z.example/api", '
219
+ '"model": "glm-4.6", "provider": "zai", '
220
+ '"reasoning_effort": "high", "document_format": "none", '
221
+ '"context_window": 128000, "cached_models": ["glm-4.6"]}}}',
222
+ encoding="utf-8")
223
+
224
+ # the wizard triple re-config: same base_url, new key/model
225
+ store.upsert("zai", "https://z.example/api", "sk-new", "glm-4.7")
226
+ ep = store.endpoint("zai")
227
+ assert ep["api_key"] == "sk-new" and ep["model"] == "glm-4.7"
228
+ assert ep["provider"] == "zai"
229
+ assert ep["reasoning_effort"] == "high"
230
+ assert ep["document_format"] == "none"
231
+ assert ep["context_window"] == 128000
232
+ assert ep["cached_models"] == ["glm-4.6"] # same endpoint → list kept
233
+
234
+
235
+ def test_save_is_atomic_and_leaves_recoverable_bak(tmp_path, monkeypatch):
236
+ """Crash-safety: the previous file survives as .bak and serves as the
237
+ load-time fallback when the main file is torn/corrupt."""
238
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path))
239
+ store = ProfileStore()
240
+ store.upsert("a", "https://a.example/api", "sk-a", "m-a")
241
+ store.upsert("b", "https://b.example/api", "sk-b", "m-b")
242
+ store.set_active("a") # third save: .bak now holds both profiles
243
+
244
+ bak = tmp_path / "config.json.bak"
245
+ assert bak.exists(), "previous version must survive as .bak"
246
+ import json as _json
247
+ bak_profiles = _json.loads(bak.read_text(encoding="utf-8"))["profiles"]
248
+ assert "sk-a" in bak_profiles["a"]["api_key"]
249
+ assert "sk-b" in bak_profiles["b"]["api_key"]
250
+
251
+ # a torn main write (crash mid-save) falls back to the .bak content
252
+ (tmp_path / "config.json").write_text('{"version": 2, "act', encoding="utf-8")
253
+ recovered = ProfileStore()
254
+ assert sorted(recovered.names()) == ["a", "b"]
255
+ assert recovered.endpoint("b")["api_key"] == "sk-b"
256
+
257
+ # a corrupt main file with no usable .bak still reads empty, not raises
258
+ bak.unlink()
259
+ assert ProfileStore().names() == []
260
+ # no temp litter left behind
261
+ assert not (tmp_path / "config.json.tmp").exists()
262
+
263
+
211
264
  # --- provider presets -------------------------------------------------------
212
265
 
213
266
  class _PresetArgs:
@@ -10,6 +10,8 @@ from conftest import _tc, make_config
10
10
 
11
11
  textual = pytest.importorskip("textual")
12
12
 
13
+ from textual.containers import VerticalScroll # noqa: E402
14
+
13
15
  from lithe_cli.ttui import ( # noqa: E402
14
16
  LitheApp,
15
17
  PickerModal,
@@ -211,6 +213,130 @@ def test_run_mode_one_shot(tmp_path):
211
213
  asyncio.run(scenario())
212
214
 
213
215
 
216
+ def test_run_mode_ctrl_c_cancels_one_shot_turn(tmp_path):
217
+ """One-shot mode has no workbench turn; Ctrl+C must still cancel via the
218
+ run's own stop handle (the README promise), not be a silent no-op."""
219
+ async def scenario():
220
+ release = asyncio.Event()
221
+
222
+ class _Hang:
223
+ async def complete(self, client, **kw):
224
+ await release.wait()
225
+ return {"content": "late", "tool_calls": [], "usage": {}}
226
+
227
+ cfg = make_config(tmp_path, [])
228
+ cfg.transport = _Hang()
229
+ app = LitheApp(cfg, "长任务", "run")
230
+ async with app.run_test(size=(100, 30)) as pilot:
231
+ await pilot.pause(0.2)
232
+ assert app.state.running, "one-shot turn should be in flight"
233
+ stop = app.state.stop
234
+ assert stop is not None
235
+ await pilot.press("ctrl+c")
236
+ assert stop.is_set(), "Ctrl+C must reach the run's stop handle"
237
+ assert "正在取消" in _conv_text(app)
238
+ assert app.is_running, "first Ctrl+C cancels, not exits"
239
+ # let the hung call return; the run then ends cancelled
240
+ release.set()
241
+ for _ in range(100):
242
+ await pilot.pause(0.05)
243
+ if not app.state.running:
244
+ break
245
+ assert not app.state.running
246
+ assert app.state.last_status in ("cancelled", "done")
247
+
248
+ asyncio.run(scenario())
249
+
250
+
251
+ def test_mid_turn_text_restored_and_commands_still_work(tmp_path):
252
+ """Plain text typed mid-turn is not silently dropped (it returns to the
253
+ input box); slash commands dispatch while a turn runs, as in the REPL."""
254
+ async def scenario():
255
+ release = asyncio.Event()
256
+
257
+ class _Hang:
258
+ async def complete(self, client, **kw):
259
+ await release.wait()
260
+ return {"content": "ok", "tool_calls": [], "usage": {}}
261
+
262
+ cfg = make_config(tmp_path, [])
263
+ cfg.transport = _Hang()
264
+ app = LitheApp(cfg, None, "chat")
265
+ async with app.run_test(size=(100, 30)) as pilot:
266
+ await pilot.pause()
267
+ inp = app.query_one("#prompt")
268
+ inp.value = "第一个任务"
269
+ await pilot.press("enter")
270
+ await pilot.pause(0.2)
271
+ assert app.state.running
272
+ # plain text mid-turn: warned and restored, not sent
273
+ inp.value = "补充说明"
274
+ await pilot.press("enter")
275
+ await pilot.pause(0.1)
276
+ assert "未发送" in _conv_text(app)
277
+ assert app.query_one("#prompt").value == "补充说明"
278
+ # slash command mid-turn: dispatches normally
279
+ inp.value = "/help"
280
+ await pilot.press("enter")
281
+ await pilot.pause(0.1)
282
+ text = _conv_text(app)
283
+ assert "命令" in text or "/model" in text
284
+ release.set()
285
+ for _ in range(100):
286
+ await pilot.pause(0.05)
287
+ if not app.state.running:
288
+ break
289
+ assert not app.state.running
290
+
291
+ asyncio.run(scenario())
292
+
293
+
294
+ async def _settle_bottom(pilot, conv):
295
+ """Give the follow anchor cycles to land: mounting grows the pane's
296
+ extent only after a layout refresh, so scroll position converges over
297
+ a few pauses (robust on slow CI)."""
298
+ import time
299
+
300
+ deadline = time.monotonic() + 2.0
301
+ while time.monotonic() < deadline:
302
+ await pilot.pause(0.02)
303
+ if conv.scroll_y >= conv.max_scroll_y - 1:
304
+ return
305
+
306
+
307
+ def test_sync_feed_follows_only_when_at_bottom(tmp_path):
308
+ """Scrolling up to re-read earlier output sticks; new events must not
309
+ yank the reader back to the bottom."""
310
+ async def scenario():
311
+ app = _app(tmp_path, [])
312
+ async with app.run_test(size=(100, 30)) as pilot:
313
+ await pilot.pause()
314
+ for i in range(60):
315
+ app.state.say("dim", f"line {i}")
316
+ app._sync_feed()
317
+ await pilot.pause()
318
+ conv = app.query_one("#conv", VerticalScroll)
319
+ assert conv.max_scroll_y > 0
320
+ await _settle_bottom(pilot, conv)
321
+ assert conv.scroll_y >= conv.max_scroll_y - 1 # followed down
322
+ conv.scroll_to(y=0, animate=False)
323
+ await pilot.pause()
324
+ assert conv.scroll_y == 0
325
+ for i in range(10):
326
+ app.state.say("dim", f"more {i}")
327
+ app._sync_feed()
328
+ await pilot.pause()
329
+ assert conv.scroll_y == 0, "reading position must stick"
330
+ conv.scroll_end(animate=False)
331
+ await _settle_bottom(pilot, conv)
332
+ app.state.say("dim", "tail")
333
+ app._sync_feed()
334
+ await _settle_bottom(pilot, conv)
335
+ assert conv.scroll_y >= conv.max_scroll_y - 1 # follows again
336
+
337
+ asyncio.run(scenario())
338
+
339
+
214
340
  def test_completion_suggestions_commands_and_args():
215
341
  from lithe_cli.commands import COMMANDS
216
342
  from lithe_cli.ttui import completion_suggestions
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