lithe-cli 0.8.5__tar.gz → 0.8.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.

Potentially problematic release.


This version of lithe-cli might be problematic. Click here for more details.

Files changed (34) hide show
  1. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/PKG-INFO +25 -15
  2. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/README.md +23 -13
  3. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/agent.py +20 -1
  5. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/config.py +21 -3
  6. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/main.py +21 -27
  7. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/profiles.py +65 -23
  8. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/sessions.py +3 -0
  9. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/ttui.py +44 -21
  10. lithe_cli-0.8.7/lithe_cli/tui.py +290 -0
  11. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/workbench.py +3 -2
  12. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/PKG-INFO +25 -15
  13. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/requires.txt +1 -1
  14. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/pyproject.toml +1 -1
  15. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/tests/test_cli.py +55 -180
  16. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/tests/test_cli_sessions.py +13 -0
  17. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/tests/test_profiles.py +134 -0
  18. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/tests/test_ttui.py +111 -18
  19. lithe_cli-0.8.7/tests/test_tui_v2.py +124 -0
  20. lithe_cli-0.8.5/lithe_cli/tui.py +0 -1458
  21. lithe_cli-0.8.5/tests/test_tui_v2.py +0 -232
  22. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/LICENSE +0 -0
  23. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/__main__.py +0 -0
  24. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/commands.py +0 -0
  25. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/prompts.py +0 -0
  26. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/py.typed +0 -0
  27. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/setup.py +0 -0
  28. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli/ui.py +0 -0
  29. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/SOURCES.txt +0 -0
  30. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/dependency_links.txt +0 -0
  31. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/entry_points.txt +0 -0
  32. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/lithe_cli.egg-info/top_level.txt +0 -0
  33. {lithe_cli-0.8.5 → lithe_cli-0.8.7}/setup.cfg +0 -0
  34. {lithe_cli-0.8.5 → lithe_cli-0.8.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.8.5
3
+ Version: 0.8.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.9.18
42
+ Requires-Dist: lithe>=0.9.19
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -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.7 · ▣ #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,13 +185,16 @@ 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
- with F2 first if it grabs both panes). The earlier prompt_toolkit screen —
190
- which adds in-app mouse selection and OSC 52 copy — remains available with
191
- `--ui prompt` / `LITHE_UI=prompt`. Pipes and CI keep the plain per-line
192
- output unchanged.
195
+ with F2 first if it grabs both panes). Pipes and CI keep the plain
196
+ per-line output unchanged; the legacy prompt_toolkit full-screen was
197
+ removed — the Textual UI is the only full-screen front-end.
193
198
 
194
199
  ### Sessions
195
200
 
@@ -214,8 +219,9 @@ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
214
219
 
215
220
  The per-turn knobs don't need a restart: `/set` (or `F5`) opens a picker
216
221
  where `Enter` toggles a capability, and typed forms set anything —
217
- `/set shell on`, `/set code off`, `/set vision`, `/set max-steps 50`,
218
- `/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`.
219
225
  Settings apply to the **next turn** (the running turn keeps its own tool
220
226
  set), stay session-scoped (nothing is written to the profile), and
221
227
  turning `shell` on restates its trust warning. `/tools` re-derives the
@@ -241,10 +247,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
241
247
  | `--skills DIR` | `load_skill` | markdown skill library; defaults to `$LITHE_HOME/skills` when it exists, `--skills ""` disables |
242
248
  | `--download` | `download_file` | SSRF-guarded, size-capped network fetch |
243
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 |
244
252
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
245
253
 
246
254
  ```bash
247
255
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
256
+ $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
248
257
  $ lithe run --shell "检查当前目录的项目状态"
249
258
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
250
259
  ```
@@ -313,7 +322,7 @@ keys, inline wizard validation, and persistent history.
313
322
  | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
314
323
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
315
324
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
316
- | `~/.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) |
317
326
 
318
327
  ## Design notes
319
328
 
@@ -325,8 +334,9 @@ keys, inline wizard validation, and persistent history.
325
334
  from lithe.
326
335
  - The Textual screen is tested headlessly with `App.run_test()` pilots
327
336
  (turns, F2/F3/F4, history, completion) — real interaction tests that
328
- also run on Windows; the legacy prompt_toolkit screen keeps its pure
329
- row-builder tests plus POSIX-only PTY tests.
337
+ also run on Windows; its pure builders (sidebar/header/footer markup,
338
+ completion suggestions) and the shared `TuiState` event folding have
339
+ direct unit tests.
330
340
  - `python -m lithe_cli` works alongside the `lithe` console script.
331
341
 
332
342
  ## License
@@ -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.7 · ▣ #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,13 +136,16 @@ 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
- with F2 first if it grabs both panes). The earlier prompt_toolkit screen —
141
- which adds in-app mouse selection and OSC 52 copy — remains available with
142
- `--ui prompt` / `LITHE_UI=prompt`. Pipes and CI keep the plain per-line
143
- output unchanged.
146
+ with F2 first if it grabs both panes). Pipes and CI keep the plain
147
+ per-line output unchanged; the legacy prompt_toolkit full-screen was
148
+ removed — the Textual UI is the only full-screen front-end.
144
149
 
145
150
  ### Sessions
146
151
 
@@ -165,8 +170,9 @@ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
165
170
 
166
171
  The per-turn knobs don't need a restart: `/set` (or `F5`) opens a picker
167
172
  where `Enter` toggles a capability, and typed forms set anything —
168
- `/set shell on`, `/set code off`, `/set vision`, `/set max-steps 50`,
169
- `/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`.
170
176
  Settings apply to the **next turn** (the running turn keeps its own tool
171
177
  set), stay session-scoped (nothing is written to the profile), and
172
178
  turning `shell` on restates its trust warning. `/tools` re-derives the
@@ -192,10 +198,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
192
198
  | `--skills DIR` | `load_skill` | markdown skill library; defaults to `$LITHE_HOME/skills` when it exists, `--skills ""` disables |
193
199
  | `--download` | `download_file` | SSRF-guarded, size-capped network fetch |
194
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 |
195
203
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
196
204
 
197
205
  ```bash
198
206
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
207
+ $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
199
208
  $ lithe run --shell "检查当前目录的项目状态"
200
209
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
201
210
  ```
@@ -264,7 +273,7 @@ keys, inline wizard validation, and persistent history.
264
273
  | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
265
274
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
266
275
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
267
- | `~/.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) |
268
277
 
269
278
  ## Design notes
270
279
 
@@ -276,8 +285,9 @@ keys, inline wizard validation, and persistent history.
276
285
  from lithe.
277
286
  - The Textual screen is tested headlessly with `App.run_test()` pilots
278
287
  (turns, F2/F3/F4, history, completion) — real interaction tests that
279
- also run on Windows; the legacy prompt_toolkit screen keeps its pure
280
- row-builder tests plus POSIX-only PTY tests.
288
+ also run on Windows; its pure builders (sidebar/header/footer markup,
289
+ completion suggestions) and the shared `TuiState` event folding have
290
+ direct unit tests.
281
291
  - `python -m lithe_cli` works alongside the `lithe` console script.
282
292
 
283
293
  ## License
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.8.5"
3
+ __version__ = "0.8.7"
@@ -9,7 +9,9 @@ Everything here maps lithe's host contract onto CLI defaults:
9
9
  - tools — the workspace bundle (read/write/edit/list/search/glob +
10
10
  apply_patch) and todos, plus opt-in capabilities: ``--code`` (sandboxed
11
11
  Python), ``--shell`` (native host commands), ``--skills`` (markdown skill
12
- library), ``--vision`` (image probe/analysis), ``--download`` (SSRF-guarded
12
+ library), ``--vision`` (image probe/analysis), ``--document``
13
+ (PDF/OOXML probe/analysis — dialect from ``--document-format`` > profile
14
+ ``document_format`` > provider preset), ``--download`` (SSRF-guarded
13
15
  network fetch) and ``--mcp`` (external MCP servers);
14
16
  - undo — the bundled tools register reverters, so ``lithe undo`` works with
15
17
  zero configuration.
@@ -82,6 +84,9 @@ def build_system_prompt(cfg: Config) -> str:
82
84
  extras.append("可以用 download_file 下载网络文件到工作区。")
83
85
  if cfg.skills_dir is not None:
84
86
  extras.append("可以先 load_skill 查看可用技能并按需加载规范。")
87
+ if cfg.document:
88
+ extras.append("可以用 analyze_document 直接阅读 PDF/DOCX/XLSX/PPTX 文档并回答关于它的具体问题;"
89
+ "确定元信息(格式/页数)先用 document_info。")
85
90
  if not extras:
86
91
  return SYSTEM_PROMPT_BASE
87
92
  return SYSTEM_PROMPT_BASE + "".join(extras)
@@ -101,6 +106,9 @@ def build_llm(cfg: Config) -> LLMConfig:
101
106
  "stream": cfg.stream,
102
107
  "context_window": cfg.context_window,
103
108
  "reasoning_effort": cfg.reasoning_effort,
109
+ # Explicit dialect (flag/profile) overrides the preset default;
110
+ # apply_preset skips the None override so the preset fills in.
111
+ "document_format": cfg.document_format,
104
112
  }
105
113
  # The CLI's transport field defaults to "chat" and is only overridden by
106
114
  # offline tests (custom transports); the default must not clobber a
@@ -152,6 +160,17 @@ def build_registry(cfg: Config) -> ToolRegistry:
152
160
  from lithe.bundles.images import register_image_tools
153
161
 
154
162
  register_image_tools(reg, workspace_for, llm_config=build_llm(cfg))
163
+ if cfg.document:
164
+ from lithe.bundles.documents import register_document_tools
165
+
166
+ try:
167
+ register_document_tools(
168
+ reg, workspace_for, llm_config=build_llm(cfg),
169
+ document_format=cfg.document_format)
170
+ except ValueError as exc:
171
+ raise SystemExit(
172
+ f"{exc}。请修正 --document-format 或档案里的 document_format "
173
+ f"字段。") from exc
155
174
  return reg
156
175
 
157
176
 
@@ -19,7 +19,11 @@ Capability flags (all off unless asked for):
19
19
  - ``--mcp SPEC`` external MCP servers (JSON array/object, or ``@file``);
20
20
  env ``LITHE_MCP`` holds the same spec;
21
21
  - ``--vision`` ``image_info`` + ``analyze_image`` (one vision call on
22
- the main endpoint, memoized per file hash).
22
+ the main endpoint, memoized per file hash);
23
+ - ``--document`` ``document_info`` + ``analyze_document`` (PDF/OOXML
24
+ reading on the main endpoint; the content-block dialect
25
+ comes from ``--document-format`` > the profile's
26
+ ``document_format`` field > the provider preset).
23
27
  """
24
28
 
25
29
  from __future__ import annotations
@@ -57,6 +61,12 @@ class Config:
57
61
  # fills base_url when unset and contributes LLMConfig defaults (transport,
58
62
  # extra_body, ...) under the user's explicit values. See lithe.bundles.providers.
59
63
  provider: str | None = None
64
+ # Explicit document-block dialect for analyze_document:
65
+ # --document-format flag > this field; the provider preset's
66
+ # document_format fills in when neither is set (inside build_llm, so
67
+ # in-session profile switches re-resolve it). None = not explicit.
68
+ document_format: str | None = None
69
+ document: bool = False
60
70
  store_dir: Path = field(default_factory=lambda: default_store_dir())
61
71
  workspace_dir: Path = field(default_factory=lambda: Path.cwd())
62
72
  user_id: str = DEFAULT_USER
@@ -139,7 +149,7 @@ def config_file() -> Path:
139
149
 
140
150
 
141
151
  def load_saved_endpoint() -> dict:
142
- """Read the active profile's {api_key, base_url, model, provider}; {} if none.
152
+ """Read the active profile's endpoint fields; {} if none.
143
153
 
144
154
  A corrupt file is treated as absent — a bad edit should cost the user
145
155
  one re-prompt, not a broken CLI.
@@ -147,7 +157,7 @@ def load_saved_endpoint() -> dict:
147
157
  from .profiles import ProfileStore
148
158
 
149
159
  endpoint = ProfileStore().endpoint()
150
- keys = (*_ENDPOINT_KEYS, "provider")
160
+ keys = (*_ENDPOINT_KEYS, "provider", "document_format")
151
161
  return {k: endpoint[k] for k in keys if endpoint.get(k)}
152
162
 
153
163
 
@@ -269,6 +279,10 @@ def load_config(args: Any) -> Config:
269
279
  effort = g("reasoning_effort", None) or saved.get("reasoning_effort")
270
280
  if effort is not None and effort.strip().lower() == "off":
271
281
  effort = None
282
+ # Document dialect for analyze_document: flag > profile field. The
283
+ # provider preset's default fills in inside build_llm (apply_preset
284
+ # skips the None override), so in-session profile switches re-resolve.
285
+ document_format = g("document_format", None) or saved.get("document_format")
272
286
  return Config(
273
287
  api_key=(
274
288
  g("api_key", None) or os.environ.get(ENV_API_KEY) or saved.get("api_key")
@@ -277,6 +291,10 @@ def load_config(args: Any) -> Config:
277
291
  model=(g("model", None) or os.environ.get(ENV_MODEL) or saved.get("model")),
278
292
  profile=active,
279
293
  provider=provider,
294
+ document_format=(document_format.strip()
295
+ if isinstance(document_format, str)
296
+ and document_format.strip() else None),
297
+ document=g("document", False),
280
298
  reasoning_effort=(effort.strip() if isinstance(effort, str) and effort.strip()
281
299
  else None),
282
300
  store_dir=store_dir,
@@ -27,7 +27,6 @@ from __future__ import annotations
27
27
 
28
28
  import argparse
29
29
  import asyncio
30
- import os
31
30
  import sys
32
31
  from typing import Any
33
32
 
@@ -99,6 +98,22 @@ def build_parser() -> argparse.ArgumentParser:
99
98
  action="store_true",
100
99
  help="grant image_info/analyze_image (vision on the main endpoint)",
101
100
  )
101
+ sp.add_argument(
102
+ "--document",
103
+ action="store_true",
104
+ help="grant document_info/analyze_document "
105
+ "(PDF/OOXML reading on the main endpoint)",
106
+ )
107
+ sp.add_argument(
108
+ "--document-format",
109
+ metavar="DIALECT",
110
+ default=None,
111
+ choices=["inline-file", "files-api", "none"],
112
+ help="document block dialect for analyze_document: "
113
+ "inline-file = OpenRouter family (incl. self-built same-format "
114
+ "routers), files-api = strict OpenAI two-step upload "
115
+ "(default: profile field document_format, else provider preset)",
116
+ )
102
117
  color = sp.add_mutually_exclusive_group()
103
118
  color.add_argument("--color", action="store_true", help="force colored output")
104
119
  color.add_argument(
@@ -113,13 +128,6 @@ def build_parser() -> argparse.ArgumentParser:
113
128
  sp.add_argument(
114
129
  "--stream", action="store_true", help="stream tokens as they generate"
115
130
  )
116
- sp.add_argument(
117
- "--ui",
118
- choices=["textual", "prompt"],
119
- default=None,
120
- help="full-screen frontend (env LITHE_UI; default: textual; "
121
- "'prompt' is the legacy prompt_toolkit screen)",
122
- )
123
131
  sp.add_argument(
124
132
  "--no-setup",
125
133
  action="store_true",
@@ -493,6 +501,8 @@ def _cmd_config(args: Any) -> int:
493
501
  print(ui.kv("profile", str(store.active_name() or "—")))
494
502
  if saved.get("provider"):
495
503
  print(ui.kv("provider", saved["provider"]))
504
+ if saved.get("document_format"):
505
+ print(ui.kv("document_format", saved["document_format"]))
496
506
  print(ui.kv("base_url", saved["base_url"]))
497
507
  print(ui.kv("api_key", masked))
498
508
  print(ui.kv("model", saved["model"]))
@@ -603,20 +613,12 @@ def _chat_loop(
603
613
  return 0
604
614
 
605
615
 
606
- def _resolve_ui(args: Any) -> str:
607
- """Which full-screen frontend: 'textual' (default) or 'prompt'."""
608
- ui = getattr(args, "ui", None) or os.environ.get("LITHE_UI") or ""
609
- ui = ui.strip().lower()
610
- return ui if ui in ("prompt", "textual") else "textual"
611
-
612
-
613
616
  def _run_textual(cfg: Any, task: str | None, mode: str, args: Any) -> int:
614
617
  try:
615
618
  from .ttui import run_textual_screen
616
619
  except ImportError as exc: # pragma: no cover - depends on install
617
620
  raise SystemExit(
618
- f"Textual 前端不可用({exc})。pip install textual,"
619
- "或用 --ui prompt 走旧版界面。"
621
+ f"Textual 前端不可用({exc})。请 pip install textual 后重试。"
620
622
  ) from exc
621
623
  # run_textual_screen is sync: it drives its own asyncio.run inside.
622
624
  return run_textual_screen(cfg, task, mode, args)
@@ -632,20 +634,12 @@ def main(argv: list[str] | None = None) -> int:
632
634
  if args.command == "run":
633
635
  require_endpoint(cfg, interactive=not args.no_setup)
634
636
  if screen_supported():
635
- if _resolve_ui(args) == "textual":
636
- return _run_textual(cfg, args.task, "run", args)
637
- from .tui import run_screen
638
-
639
- return asyncio.run(run_screen(cfg, args.task, "run"))
637
+ return _run_textual(cfg, args.task, "run", args)
640
638
  return _cmd_run(cfg, args.task)
641
639
  if args.command == "chat":
642
640
  require_endpoint(cfg, interactive=not args.no_setup)
643
641
  if screen_supported():
644
- if _resolve_ui(args) == "textual":
645
- return _run_textual(cfg, None, "chat", args)
646
- from .tui import run_screen
647
-
648
- return asyncio.run(run_screen(cfg, None, "chat", args))
642
+ return _run_textual(cfg, None, "chat", args)
649
643
  return _chat_loop(
650
644
  cfg,
651
645
  resume=args.resume,
@@ -9,10 +9,20 @@ holds keys) grows from the original flat triple to a profile map::
9
9
  "profiles": {
10
10
  "zhipu": {"base_url": "...", "api_key": "...", "model": "glm-4.6",
11
11
  "context_window": 128000, "cached_models": ["glm-4.6"]},
12
- "openrouter": {"base_url": "...", "api_key": "...", "model": "..."}
12
+ "openrouter": {"base_url": "...", "api_key": "...", "model": "...",
13
+ "provider": "openrouter"},
14
+ "selfhost": {"base_url": "https://my-router/api/v1", "api_key": "...",
15
+ "model": "...", "provider": "openrouter",
16
+ "document_format": "inline-file"}
13
17
  }
14
18
  }
15
19
 
20
+ ``provider`` names a vendor preset (format family) and only fills values
21
+ left unset — an explicit ``base_url`` always wins, so a self-built router
22
+ speaking the OpenRouter format keeps its own URL. ``document_format``
23
+ overrides the preset's document-block dialect for ``analyze_document``
24
+ (see lithe.bundles.documents).
25
+
16
26
  A legacy flat ``{api_key, base_url, model}`` file is translated in memory to
17
27
  the single profile ``default`` and is never rewritten until an explicit save
18
28
  (a mutation through this module) — old installs keep working untouched.
@@ -29,6 +39,7 @@ user typed into the wizard or wrote by hand.
29
39
  from __future__ import annotations
30
40
 
31
41
  import json
42
+ import os
32
43
  import re
33
44
  from pathlib import Path
34
45
  from typing import Any
@@ -65,6 +76,9 @@ def _clean_endpoint(data: dict) -> dict:
65
76
  effort = data.get("reasoning_effort")
66
77
  if isinstance(effort, str) and effort.strip():
67
78
  out["reasoning_effort"] = effort.strip()
79
+ dfmt = data.get("document_format")
80
+ if isinstance(dfmt, str) and dfmt.strip():
81
+ out["document_format"] = dfmt.strip()
68
82
  for k in ("context_window",):
69
83
  v = data.get(k)
70
84
  if isinstance(v, int) and v > 0:
@@ -76,26 +90,34 @@ def _clean_endpoint(data: dict) -> dict:
76
90
 
77
91
 
78
92
  class ProfileStore:
79
- """Read/modify the profile file; every mutation rewrites it atomically
80
- enough for a CLI (write-in-place with owner-only perms, like the wizard
81
- 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."""
82
96
 
83
97
  def __init__(self, path: Path | None = None):
84
98
  self.path = path or config_file()
85
99
 
86
100
  # -- load / save ----------------------------------------------------------
87
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
+
88
109
  def load(self) -> dict:
89
110
  """Normalized ``{"active": str | None, "profiles": {name: endpoint}}``.
90
111
 
91
- Corrupt files and foreign shapes read as empty — a bad edit costs one
92
- 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.
93
115
  """
94
- try:
95
- data = json.loads(self.path.read_text(encoding="utf-8"))
96
- except (OSError, json.JSONDecodeError):
97
- return {"active": None, "profiles": {}}
98
- 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):
99
121
  return {"active": None, "profiles": {}}
100
122
  if "profiles" not in data: # legacy flat triple → profile "default"
101
123
  endpoint = _clean_endpoint(data)
@@ -122,13 +144,23 @@ class ProfileStore:
122
144
  self.path.parent.mkdir(parents=True, exist_ok=True)
123
145
  if fresh_dir:
124
146
  _restrict_to_owner(self.path.parent, directory=True)
125
- self.path.touch(exist_ok=True)
126
- _restrict_to_owner(self.path)
127
147
  payload = {"version": 2, "active": active, "profiles": profiles}
128
- self.path.write_text(
129
- json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
130
- encoding="utf-8",
131
- )
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)
132
164
  return self.path
133
165
 
134
166
  # -- queries --------------------------------------------------------------
@@ -176,22 +208,32 @@ class ProfileStore:
176
208
  model: str,
177
209
  context_window: int | None = None,
178
210
  provider: str | None = None,
211
+ document_format: str | None = None,
179
212
  ) -> Path:
180
213
  if not valid_name(name):
181
214
  raise SystemExit(
182
215
  f"档案名 {name!r} 不合法(仅限字母、数字、点、下划线、连字符)"
183
216
  )
184
217
  data = self.load()
185
- endpoint = {"api_key": api_key.strip(), "base_url": base_url.strip(),
186
- "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()})
187
226
  if context_window:
188
227
  endpoint["context_window"] = int(context_window)
189
228
  if provider and provider.strip():
190
229
  endpoint["provider"] = provider.strip()
191
- # keep a previously cached model list when the base_url is unchanged
192
- old = data["profiles"].get(name) or {}
193
- if old.get("cached_models") and old.get("base_url") == endpoint["base_url"]:
194
- endpoint["cached_models"] = old["cached_models"]
230
+ if document_format and document_format.strip():
231
+ endpoint["document_format"] = document_format.strip()
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)
195
237
  data["profiles"][name] = {k: v for k, v in endpoint.items() if v}
196
238
  if data["active"] is None:
197
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():