lithe-cli 0.6.7__tar.gz → 0.7.0__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 (30) hide show
  1. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/PKG-INFO +92 -48
  2. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/README.md +90 -46
  3. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/agent.py +11 -7
  5. lithe_cli-0.7.0/lithe_cli/commands.py +58 -0
  6. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/config.py +41 -31
  7. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/main.py +252 -47
  8. lithe_cli-0.7.0/lithe_cli/profiles.py +247 -0
  9. lithe_cli-0.7.0/lithe_cli/sessions.py +154 -0
  10. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/tui.py +587 -84
  11. lithe_cli-0.7.0/lithe_cli/workbench.py +494 -0
  12. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/PKG-INFO +92 -48
  13. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/SOURCES.txt +9 -1
  14. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/requires.txt +1 -1
  15. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/pyproject.toml +1 -1
  16. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/tests/test_cli.py +1 -1
  17. lithe_cli-0.7.0/tests/test_cli_sessions.py +192 -0
  18. lithe_cli-0.7.0/tests/test_profiles.py +208 -0
  19. lithe_cli-0.7.0/tests/test_tui_v2.py +199 -0
  20. lithe_cli-0.7.0/tests/test_workbench.py +273 -0
  21. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/LICENSE +0 -0
  22. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/__main__.py +0 -0
  23. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/prompts.py +0 -0
  24. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/py.typed +0 -0
  25. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/setup.py +0 -0
  26. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli/ui.py +0 -0
  27. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/dependency_links.txt +0 -0
  28. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/entry_points.txt +0 -0
  29. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/lithe_cli.egg-info/top_level.txt +0 -0
  30. {lithe_cli-0.6.7 → lithe_cli-0.7.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.6.7
3
+ Version: 0.7.0
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.13
42
+ Requires-Dist: lithe>=0.9.14
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Provides-Extra: dev
45
45
  Requires-Dist: pytest>=8; extra == "dev"
@@ -72,6 +72,28 @@ interactive terminal prompts for the three essentials and saves them to
72
72
  `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
73
73
  connectivity probe catches typos before your first turn.
74
74
 
75
+ The config file holds **named profiles** — several endpoints, one active:
76
+
77
+ ```json
78
+ {
79
+ "version": 2,
80
+ "active": "zhipu",
81
+ "profiles": {
82
+ "zhipu": {"base_url": "https://…", "api_key": "…", "model": "glm-4.6",
83
+ "context_window": 128000, "cached_models": ["glm-4.6"]},
84
+ "openrouter": {"base_url": "https://…", "api_key": "…", "model": "…"}
85
+ }
86
+ }
87
+ ```
88
+
89
+ ```bash
90
+ lithe config # wizard (edits the active profile)
91
+ lithe config --list # profiles, key masked
92
+ lithe config --use openrouter # switch active profile (script-friendly)
93
+ lithe config --model glm-4.5 # set the active profile's default model
94
+ lithe models # GET {base_url}/models, cached into the profile
95
+ ```
96
+
75
97
  To configure by hand instead, point the CLI at any OpenAI-compatible
76
98
  endpoint:
77
99
 
@@ -82,10 +104,11 @@ export LITHE_MODEL=your-model
82
104
  ```
83
105
 
84
106
  Resolution order is flag (`--api-key`, `--base-url`, `--model`) >
85
- environment > saved config file, per key. The wizard never runs without
86
- a TTY on both ends, so pipes and CI keep the hard refusal; `--no-setup`
87
- restores that fail-fast behavior on terminals too. `lithe config --show`
88
- peeks at the saved values with a masked key.
107
+ environment > the selected profile's fields, per key; `--profile NAME`
108
+ (or `LITHE_PROFILE`) selects a profile for one invocation. The wizard
109
+ never runs without a TTY on both ends, so pipes and CI keep the hard
110
+ refusal; `--no-setup` restores that fail-fast behavior on terminals
111
+ too. `lithe config --show` peeks at the saved values with a masked key.
89
112
 
90
113
  `LITHE_HOME` (default `~/.lithe`) locates the run store; the agent's
91
114
  workspace defaults to the current directory (`--workspace` to change).
@@ -119,49 +142,63 @@ usage/context gauges; `--max-steps` caps the tool loop;
119
142
 
120
143
  On an interactive terminal, `lithe chat` and `lithe run TASK` open a
121
144
  persistent full-screen interface instead of scribbling one-line events
122
- into the console:
145
+ into the console. The left pane is the conversation; the right sidebar
146
+ is five fixed sections — 会话(current + recent ones, `●` marks sessions
147
+ with a turn still running)、模型、运行、工具/待办、用量:
123
148
 
124
149
  ```text
125
- lithe 0.6.2 · your-model · /home/me/my-project ● 完成 · 0.2s
150
+ lithe 0.7.0 · zhipu · glm-4.6 │ ▣ #12 重构计划 │ ~/myproj ● 运行中
126
151
  ╭─ 对话 ──────────────────────────────╮╭─ 运行状态 ─────────╮
127
- │ 把 a.txt 改成三行待办清单 ││ ● 完成 · 0.2s │
128
- │ ◆ update_todos ││ 步骤 2/35 · 0.2s │
129
- │ ✓ 任务清单已更新(3 条) 0.0s ││ ✓ update_todos 0.0s│
130
- │ ◆ edit_file · 局部修改 a.txt ││ ✓ edit_file 0.0s │
131
- │ ✓ 编辑 a.txt(+3 -1 行) 0.0s ││ ◆ 待办 1/3 │
132
- │ 已完成。 ││ [~] 修改 a.txt │
133
- │ ││ ◆ 会话用量 │
134
- │ ││ 输入 1,024 · 输出 216│
135
- │ ││ 缓存输入 768 │
136
- │ ││ 合计 1,240 · $0.0021│
137
- │ ││ 上下文 1,024 / 128,000 (0.8%)│
138
- ╰─────────────────────────────────────╯╰────────────────────╯
152
+ │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
153
+ │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
154
+ │ ✓ 编辑 a.txt(+3 -1 行) 0.0s ││ #11 bugfix ✓ 7轮 │
155
+ │ 已完成。 ││ F3 切换 · /new 新建│
156
+ │ ││ ◆ 模型 │
157
+ │ ││ zhipu · glm-4.6 │
158
+ │ ││ ◆ 会话用量 │
159
+ │ ││ 输入 1,024 · 输出 216│
160
+ ╰──────────────────────────────────────╯╰─────────────────────╯
139
161
  lithe ❯ _
140
- ● 完成 · 0.2s Enter 发送 · F2 侧栏 · /help 命令
162
+ ● 运行中 · 步骤 2/35 Enter 发送 · F3 会话 · F4 模型 · /help
163
+ ```
164
+
165
+ **Switch without leaving the screen**: `F3` opens the session picker
166
+ (`Enter` switch, `n` new, `d` delete, `r` rename), `F4` the model picker
167
+ (grouped by profile; `Enter` switch, `s` save as the profile's default,
168
+ `r` fetch `/models`). Switching away from a running session does **not**
169
+ cancel it — its badge stays lit and the pane rebuilds from the store when
170
+ you come back. Typing `/` pops an inline completion menu (commands, then
171
+ model/profile names as arguments). `Ctrl+C` cancels the current turn,
172
+ copies when a conversation selection is active, and exits when idle.
173
+
174
+ The conversation has an application-managed mouse selection: drag across
175
+ its text and press `Ctrl+C` to copy only the selected conversation,
176
+ without sidebar content. `Shift+drag` bypasses the application and uses
177
+ the terminal's native selection, which can cross both panes; hide the
178
+ sidebar with F2 or `/sidebar` before using native selection. The
179
+ conversation scrolls with the mouse wheel, PageUp/PageDown and Home/End
180
+ (a new turn jumps back to the output). Layout, wrapping and alignment
181
+ are East-Asian-width aware; narrower terminals stack the two panes
182
+ vertically. Pipes and CI keep the plain per-line output unchanged.
183
+
184
+ ### Sessions
185
+
186
+ Every chat conversation persists as a kernel conversation (one run per
187
+ turn, messages written incrementally):
188
+
189
+ ```bash
190
+ lithe chat -c # continue the most recent session
191
+ lithe chat --resume 12 # by id (or unique title prefix)
192
+ lithe sessions # list; newest activity first
193
+ lithe sessions --rename 12 规划 # rename
194
+ lithe sessions --delete 12 # soft delete (runs stay: log/undo work)
141
195
  ```
142
196
 
143
- The left pane is the conversation (task, compact tool-call summaries
144
- and outcomes — file edits land with `+N -M 行` counts — and the
145
- streaming assistant reply). The right sidebar shows run status, recent
146
- tools, todos, session-wide cumulative input/output/cached tokens and
147
- cost, plus the latest model-call context length and window percentage;
148
- usage numbers live only there, the bottom bar keeps status and key
149
- hints. The conversation has an application-managed mouse selection: drag across
150
- its text and press `Ctrl+C` to copy only the selected conversation, without
151
- sidebar content. `Shift+drag` bypasses the application and uses the terminal's
152
- native selection, which can cross both panes; hide the sidebar with F2 or
153
- `/sidebar` before using native selection. The conversation scrolls with the
154
- mouse wheel, PageUp/PageDown and Home/End (a new turn jumps back to the output).
155
- `Ctrl+C` cancels the current turn when there is no conversation selection and
156
- exits when idle. In `lithe run` mode the result stays on screen until you press
157
- `q`. Layout, wrapping and alignment are East-Asian-width aware; narrower
158
- terminals stack the two panes vertically. Pipes and CI keep the plain per-line
159
- output unchanged.
160
-
161
- History carries across turns within a session (each turn is its own run
162
- in the store, replayed as context for the next). `/new` clears the
163
- conversation history and session usage totals; `/tools` lists the
164
- registered tools, `/help` lists the commands.
197
+ A session remembers its last profile and model and restores them on
198
+ resume (unless `--model`/env pinned). Inside chat, the same operations
199
+ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
200
+ `/rename 标题`, `/model glm-4.5 [--save]`, `/profile zhipu`,
201
+ `/models`, `/undo`, `/tools`, `/sidebar`, `/help`, `/exit`.
165
202
 
166
203
  ### Extra capabilities
167
204
 
@@ -204,7 +241,9 @@ the model.)
204
241
 
205
242
  ```bash
206
243
  $ lithe runs # stored runs (newest last)
244
+ $ lithe sessions # stored conversations (newest first)
207
245
  $ lithe log abc123def456 # messages + actions of one run
246
+ $ lithe models # what the endpoint offers (cached)
208
247
  $ lithe doctor # config + capability status
209
248
  ```
210
249
 
@@ -240,18 +279,23 @@ keys, inline wizard validation, and persistent history.
240
279
  | Path | Contents |
241
280
  | --- | --- |
242
281
  | current dir (or `--workspace`) | the agent's sandboxed workspace — every tool path resolves strictly inside it |
243
- | `~/.lithe/runs` (or `--store`) | JSONL run store: messages, actions, undo records |
282
+ | `~/.lithe/config.json` (or `LITHE_HOME`) | endpoint profiles: `{version, active, profiles}` (0600 — it holds keys) |
283
+ | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
244
284
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
245
285
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
246
286
  | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; Up/Ctrl+R recall) |
247
287
 
248
288
  ## Design notes
249
289
 
250
- - The CLI is a thin host: it supplies tools, a system prompt, and the
251
- kernel's `JsonlRunStore`; everything else (ReAct loop, streaming, budgets,
252
- replay, undo engine) is reused from lithe.
290
+ - The CLI is a thin host over a `Workbench`: the workbench owns the
291
+ endpoint view (profile + model), the session manager and the running
292
+ turns; the plain REPL and the full-screen TUI are both just
293
+ subscribers to its event bus and callers of one dispatcher. Everything
294
+ else (ReAct loop, streaming, budgets, replay, undo engine) is reused
295
+ from lithe.
253
296
  - End-to-end behavior is tested offline against a scripted transport — no
254
- test spends tokens.
297
+ test spends tokens. The TUI's row builders are pure functions tested
298
+ headless; only key handling needs a real PTY (POSIX CI).
255
299
  - `python -m lithe_cli` works alongside the `lithe` console script.
256
300
 
257
301
  ## License
@@ -24,6 +24,28 @@ interactive terminal prompts for the three essentials and saves them to
24
24
  `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
25
25
  connectivity probe catches typos before your first turn.
26
26
 
27
+ The config file holds **named profiles** — several endpoints, one active:
28
+
29
+ ```json
30
+ {
31
+ "version": 2,
32
+ "active": "zhipu",
33
+ "profiles": {
34
+ "zhipu": {"base_url": "https://…", "api_key": "…", "model": "glm-4.6",
35
+ "context_window": 128000, "cached_models": ["glm-4.6"]},
36
+ "openrouter": {"base_url": "https://…", "api_key": "…", "model": "…"}
37
+ }
38
+ }
39
+ ```
40
+
41
+ ```bash
42
+ lithe config # wizard (edits the active profile)
43
+ lithe config --list # profiles, key masked
44
+ lithe config --use openrouter # switch active profile (script-friendly)
45
+ lithe config --model glm-4.5 # set the active profile's default model
46
+ lithe models # GET {base_url}/models, cached into the profile
47
+ ```
48
+
27
49
  To configure by hand instead, point the CLI at any OpenAI-compatible
28
50
  endpoint:
29
51
 
@@ -34,10 +56,11 @@ export LITHE_MODEL=your-model
34
56
  ```
35
57
 
36
58
  Resolution order is flag (`--api-key`, `--base-url`, `--model`) >
37
- environment > saved config file, per key. The wizard never runs without
38
- a TTY on both ends, so pipes and CI keep the hard refusal; `--no-setup`
39
- restores that fail-fast behavior on terminals too. `lithe config --show`
40
- peeks at the saved values with a masked key.
59
+ environment > the selected profile's fields, per key; `--profile NAME`
60
+ (or `LITHE_PROFILE`) selects a profile for one invocation. The wizard
61
+ never runs without a TTY on both ends, so pipes and CI keep the hard
62
+ refusal; `--no-setup` restores that fail-fast behavior on terminals
63
+ too. `lithe config --show` peeks at the saved values with a masked key.
41
64
 
42
65
  `LITHE_HOME` (default `~/.lithe`) locates the run store; the agent's
43
66
  workspace defaults to the current directory (`--workspace` to change).
@@ -71,49 +94,63 @@ usage/context gauges; `--max-steps` caps the tool loop;
71
94
 
72
95
  On an interactive terminal, `lithe chat` and `lithe run TASK` open a
73
96
  persistent full-screen interface instead of scribbling one-line events
74
- into the console:
97
+ into the console. The left pane is the conversation; the right sidebar
98
+ is five fixed sections — 会话(current + recent ones, `●` marks sessions
99
+ with a turn still running)、模型、运行、工具/待办、用量:
75
100
 
76
101
  ```text
77
- lithe 0.6.2 · your-model · /home/me/my-project ● 完成 · 0.2s
102
+ lithe 0.7.0 · zhipu · glm-4.6 │ ▣ #12 重构计划 │ ~/myproj ● 运行中
78
103
  ╭─ 对话 ──────────────────────────────╮╭─ 运行状态 ─────────╮
79
- │ 把 a.txt 改成三行待办清单 ││ ● 完成 · 0.2s │
80
- │ ◆ update_todos ││ 步骤 2/35 · 0.2s │
81
- │ ✓ 任务清单已更新(3 条) 0.0s ││ ✓ update_todos 0.0s│
82
- │ ◆ edit_file · 局部修改 a.txt ││ ✓ edit_file 0.0s │
83
- │ ✓ 编辑 a.txt(+3 -1 行) 0.0s ││ ◆ 待办 1/3 │
84
- │ 已完成。 ││ [~] 修改 a.txt │
85
- │ ││ ◆ 会话用量 │
86
- │ ││ 输入 1,024 · 输出 216│
87
- │ ││ 缓存输入 768 │
88
- │ ││ 合计 1,240 · $0.0021│
89
- │ ││ 上下文 1,024 / 128,000 (0.8%)│
90
- ╰─────────────────────────────────────╯╰────────────────────╯
104
+ │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
105
+ │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
106
+ │ ✓ 编辑 a.txt(+3 -1 行) 0.0s ││ #11 bugfix ✓ 7轮 │
107
+ │ 已完成。 ││ F3 切换 · /new 新建│
108
+ │ ││ ◆ 模型 │
109
+ │ ││ zhipu · glm-4.6 │
110
+ │ ││ ◆ 会话用量 │
111
+ │ ││ 输入 1,024 · 输出 216│
112
+ ╰──────────────────────────────────────╯╰─────────────────────╯
91
113
  lithe ❯ _
92
- ● 完成 · 0.2s Enter 发送 · F2 侧栏 · /help 命令
114
+ ● 运行中 · 步骤 2/35 Enter 发送 · F3 会话 · F4 模型 · /help
115
+ ```
116
+
117
+ **Switch without leaving the screen**: `F3` opens the session picker
118
+ (`Enter` switch, `n` new, `d` delete, `r` rename), `F4` the model picker
119
+ (grouped by profile; `Enter` switch, `s` save as the profile's default,
120
+ `r` fetch `/models`). Switching away from a running session does **not**
121
+ cancel it — its badge stays lit and the pane rebuilds from the store when
122
+ you come back. Typing `/` pops an inline completion menu (commands, then
123
+ model/profile names as arguments). `Ctrl+C` cancels the current turn,
124
+ copies when a conversation selection is active, and exits when idle.
125
+
126
+ The conversation has an application-managed mouse selection: drag across
127
+ its text and press `Ctrl+C` to copy only the selected conversation,
128
+ without sidebar content. `Shift+drag` bypasses the application and uses
129
+ the terminal's native selection, which can cross both panes; hide the
130
+ sidebar with F2 or `/sidebar` before using native selection. The
131
+ conversation scrolls with the mouse wheel, PageUp/PageDown and Home/End
132
+ (a new turn jumps back to the output). Layout, wrapping and alignment
133
+ are East-Asian-width aware; narrower terminals stack the two panes
134
+ vertically. Pipes and CI keep the plain per-line output unchanged.
135
+
136
+ ### Sessions
137
+
138
+ Every chat conversation persists as a kernel conversation (one run per
139
+ turn, messages written incrementally):
140
+
141
+ ```bash
142
+ lithe chat -c # continue the most recent session
143
+ lithe chat --resume 12 # by id (or unique title prefix)
144
+ lithe sessions # list; newest activity first
145
+ lithe sessions --rename 12 规划 # rename
146
+ lithe sessions --delete 12 # soft delete (runs stay: log/undo work)
93
147
  ```
94
148
 
95
- The left pane is the conversation (task, compact tool-call summaries
96
- and outcomes — file edits land with `+N -M 行` counts — and the
97
- streaming assistant reply). The right sidebar shows run status, recent
98
- tools, todos, session-wide cumulative input/output/cached tokens and
99
- cost, plus the latest model-call context length and window percentage;
100
- usage numbers live only there, the bottom bar keeps status and key
101
- hints. The conversation has an application-managed mouse selection: drag across
102
- its text and press `Ctrl+C` to copy only the selected conversation, without
103
- sidebar content. `Shift+drag` bypasses the application and uses the terminal's
104
- native selection, which can cross both panes; hide the sidebar with F2 or
105
- `/sidebar` before using native selection. The conversation scrolls with the
106
- mouse wheel, PageUp/PageDown and Home/End (a new turn jumps back to the output).
107
- `Ctrl+C` cancels the current turn when there is no conversation selection and
108
- exits when idle. In `lithe run` mode the result stays on screen until you press
109
- `q`. Layout, wrapping and alignment are East-Asian-width aware; narrower
110
- terminals stack the two panes vertically. Pipes and CI keep the plain per-line
111
- output unchanged.
112
-
113
- History carries across turns within a session (each turn is its own run
114
- in the store, replayed as context for the next). `/new` clears the
115
- conversation history and session usage totals; `/tools` lists the
116
- registered tools, `/help` lists the commands.
149
+ A session remembers its last profile and model and restores them on
150
+ resume (unless `--model`/env pinned). Inside chat, the same operations
151
+ are slash commands: `/sessions`, `/resume 12`, `/new [标题]`,
152
+ `/rename 标题`, `/model glm-4.5 [--save]`, `/profile zhipu`,
153
+ `/models`, `/undo`, `/tools`, `/sidebar`, `/help`, `/exit`.
117
154
 
118
155
  ### Extra capabilities
119
156
 
@@ -156,7 +193,9 @@ the model.)
156
193
 
157
194
  ```bash
158
195
  $ lithe runs # stored runs (newest last)
196
+ $ lithe sessions # stored conversations (newest first)
159
197
  $ lithe log abc123def456 # messages + actions of one run
198
+ $ lithe models # what the endpoint offers (cached)
160
199
  $ lithe doctor # config + capability status
161
200
  ```
162
201
 
@@ -192,18 +231,23 @@ keys, inline wizard validation, and persistent history.
192
231
  | Path | Contents |
193
232
  | --- | --- |
194
233
  | current dir (or `--workspace`) | the agent's sandboxed workspace — every tool path resolves strictly inside it |
195
- | `~/.lithe/runs` (or `--store`) | JSONL run store: messages, actions, undo records |
234
+ | `~/.lithe/config.json` (or `LITHE_HOME`) | endpoint profiles: `{version, active, profiles}` (0600 — it holds keys) |
235
+ | `~/.lithe/runs` (or `--store`) | JSONL run store: conversations, runs, messages, actions, undo records |
196
236
  | `~/.lithe/runs/todos-<scope-hash>.json` | the agent's task list, isolated by user and resolved workspace |
197
237
  | `~/.lithe/skills` (or `--skills`) | the markdown skill library, when enabled |
198
238
  | `~/.lithe/history` | chat input history (prompt_toolkit `FileHistory`; Up/Ctrl+R recall) |
199
239
 
200
240
  ## Design notes
201
241
 
202
- - The CLI is a thin host: it supplies tools, a system prompt, and the
203
- kernel's `JsonlRunStore`; everything else (ReAct loop, streaming, budgets,
204
- replay, undo engine) is reused from lithe.
242
+ - The CLI is a thin host over a `Workbench`: the workbench owns the
243
+ endpoint view (profile + model), the session manager and the running
244
+ turns; the plain REPL and the full-screen TUI are both just
245
+ subscribers to its event bus and callers of one dispatcher. Everything
246
+ else (ReAct loop, streaming, budgets, replay, undo engine) is reused
247
+ from lithe.
205
248
  - End-to-end behavior is tested offline against a scripted transport — no
206
- test spends tokens.
249
+ test spends tokens. The TUI's row builders are pure functions tested
250
+ headless; only key handling needs a real PTY (POSIX CI).
207
251
  - `python -m lithe_cli` works alongside the `lithe` console script.
208
252
 
209
253
  ## License
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.6.7"
3
+ __version__ = "0.7.0"
@@ -207,6 +207,7 @@ async def execute(
207
207
  run_id: str | None = None,
208
208
  on_event=None,
209
209
  stop=None,
210
+ conversation_id: int | None = None,
210
211
  ) -> tuple[str, dict, Any]:
211
212
  """Run one task end-to-end; returns (run_id, done_event, host).
212
213
 
@@ -214,12 +215,14 @@ async def execute(
214
215
  event and silences the line-oriented printing below, including the
215
216
  footer — the caller renders from the events instead. ``stop`` is the
216
217
  kernel's cancellation handle, surfaced so Ctrl+C can cancel a turn
217
- without killing the process.
218
+ without killing the process. ``conversation_id`` attaches the run to a
219
+ stored session (kernel host already consumes ctx.extra).
218
220
  """
219
221
  reg = build_registry(cfg)
220
222
  host = build_host(cfg, reg)
221
223
  rid = run_id or uuid.uuid4().hex[:12]
222
- ctx = AgentContext(run_id=rid, user_id=cfg.user_id)
224
+ extra = {"conversation_id": conversation_id} if conversation_id is not None else {}
225
+ ctx = AgentContext(run_id=rid, user_id=cfg.user_id, extra=extra)
223
226
  manager = None
224
227
  if cfg.mcp_servers:
225
228
  from lithe.bundles.mcp import MCPManager
@@ -253,11 +256,12 @@ async def execute(
253
256
  return rid, ev, host
254
257
 
255
258
 
256
- async def undo(cfg: Config, run_id: str) -> int:
257
- """Revert a run's mutations with the bundled tools' reverters."""
259
+ async def undo(cfg: Config, run_id: str, quiet: bool = False) -> int:
260
+ """Revert a run's mutations; returns how many actions were reverted."""
258
261
  reg = build_registry(cfg)
259
262
  host = build_host(cfg, reg)
260
263
  report = await undo_run(host, run_id, cfg.user_id)
261
- mark = ui.s("✓", GREEN) if report.reverted else ui.s("·", YELLOW)
262
- print(f"{mark} 已撤销 {report.reverted} 个操作(run {run_id})")
263
- return 0
264
+ if not quiet:
265
+ mark = ui.s("✓", GREEN) if report.reverted else ui.s("·", YELLOW)
266
+ print(f"{mark} 已撤销 {report.reverted} 个操作(run {run_id})")
267
+ return report.reverted
@@ -0,0 +1,58 @@
1
+ """Slash commands: one registry, two frontends.
2
+
3
+ ``Workbench.dispatch`` returns an :class:`ActionResult`; the plain REPL prints
4
+ ``messages`` and runs ``awaitable`` synchronously, the TUI prints the same
5
+ messages into the conversation feed, opens ``overlay`` pickers and schedules
6
+ the awaitable as a task. Help text and completion words come from
7
+ :data:`COMMANDS`, so the two frontends can never drift apart.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+ from collections.abc import Callable
15
+
16
+ # name → (args hint, one-line description); order is the help order.
17
+ COMMANDS: dict[str, tuple[str, str]] = {
18
+ "help": ("", "显示这条帮助"),
19
+ "new": ("[标题]", "开始新会话(当前会话保留,可随时 /resume 回来)"),
20
+ "sessions": ("", "列出会话(F3 同效)"),
21
+ "resume": ("[编号|标题]", "切换会话;不带参数等同 /sessions"),
22
+ "rename": ("标题", "重命名当前会话"),
23
+ "model": ("[名称|--save]", "查看/切换模型(F4 同效);--save 同时存为档案默认"),
24
+ "models": ("", "从端点拉取模型列表并缓存"),
25
+ "profile": ("[名称]", "查看/切换 provider 档案"),
26
+ "tools": ("", "列出已注册的工具"),
27
+ "undo": ("[run]", "撤销当前会话最近一轮(或指定 run)的文件改动"),
28
+ "sidebar": ("", "显示/隐藏右侧状态栏(F2 同效)"),
29
+ "exit": ("", "退出(等同 /quit)"),
30
+ }
31
+
32
+
33
+ def help_text() -> list[tuple[str, str]]:
34
+ lines = ["可用命令:"]
35
+ width = max(len(name) for name in COMMANDS)
36
+ for name, (args, desc) in COMMANDS.items():
37
+ lines.append(f" /{name:<{width}} {args:<12} {desc}")
38
+ lines.append("")
39
+ lines.append("会话内随时可切模型/切会话,下一轮生效;运行中的轮次不受影响。")
40
+ return [("dim", ln) for ln in lines]
41
+
42
+
43
+ @dataclass
44
+ class ActionResult:
45
+ """What a dispatched line means to the calling frontend."""
46
+
47
+ action: str = "none" # none | submit | exit
48
+ text: str = "" # submit payload
49
+ messages: list[tuple[str, str]] = field(default_factory=list)
50
+ overlay: str | None = None # TUI picker: "sessions" | "model"
51
+ toggle_sidebar: bool = False
52
+ changed: bool = False # model/session changed → refresh banner/sidebar
53
+ # Zero-arg coroutine the frontend must run: plain → asyncio.run,
54
+ # TUI → create_task (so /models fetches never block the screen).
55
+ awaitable: Callable[[], Any] | None = None
56
+
57
+ def say(self, cls: str, text: str) -> None:
58
+ self.messages.append((cls, text))
@@ -37,6 +37,7 @@ ENV_BASE_URL = "LITHE_BASE_URL"
37
37
  ENV_MODEL = "LITHE_MODEL"
38
38
  ENV_HOME = "LITHE_HOME"
39
39
  ENV_MCP = "LITHE_MCP"
40
+ ENV_PROFILE = "LITHE_PROFILE"
40
41
 
41
42
  DEFAULT_USER = "cli"
42
43
 
@@ -48,6 +49,9 @@ class Config:
48
49
  api_key: str | None = None
49
50
  base_url: str | None = None
50
51
  model: str | None = None
52
+ # Which saved profile the endpoint came from (display / doctor / TUI);
53
+ # None when the endpoint is env/flag-only or nothing is saved.
54
+ profile: str | None = None
51
55
  store_dir: Path = field(default_factory=lambda: default_store_dir())
52
56
  workspace_dir: Path = field(default_factory=lambda: Path.cwd())
53
57
  user_id: str = DEFAULT_USER
@@ -65,6 +69,9 @@ class Config:
65
69
  mcp_servers: list = field(default_factory=list)
66
70
  vision: bool = False
67
71
  color: bool | None = None
72
+ # Keys fixed by flag/env this invocation: in-session profile switching
73
+ # must not clobber them (CI pinning LITHE_MODEL stays pinned).
74
+ pinned_keys: frozenset = frozenset()
68
75
  # Wire protocol ("chat" | "responses") or a custom LLMTransport instance.
69
76
  # Not exposed as a flag: the injection point for offline tests.
70
77
  transport: Any = "chat"
@@ -118,27 +125,20 @@ _ENDPOINT_KEYS = ("api_key", "base_url", "model")
118
125
 
119
126
 
120
127
  def config_file() -> Path:
121
- """Where the wizard-saved endpoint lives."""
128
+ """Where the wizard-saved profiles live (see :mod:`lithe_cli.profiles`)."""
122
129
  return lithe_home() / "config.json"
123
130
 
124
131
 
125
132
  def load_saved_endpoint() -> dict:
126
- """Read {api_key, base_url, model} from the config file; {} if none.
133
+ """Read the active profile's {api_key, base_url, model}; {} if none.
127
134
 
128
135
  A corrupt file is treated as absent — a bad edit should cost the user
129
136
  one re-prompt, not a broken CLI.
130
137
  """
131
- try:
132
- data = json.loads(config_file().read_text(encoding="utf-8"))
133
- except (OSError, json.JSONDecodeError):
134
- return {}
135
- if not isinstance(data, dict):
136
- return {}
137
- return {
138
- k: data[k].strip()
139
- for k in _ENDPOINT_KEYS
140
- if isinstance(data.get(k), str) and data[k].strip()
141
- }
138
+ from .profiles import ProfileStore
139
+
140
+ endpoint = ProfileStore().endpoint()
141
+ return {k: endpoint[k] for k in _ENDPOINT_KEYS if endpoint.get(k)}
142
142
 
143
143
 
144
144
  def _restrict_to_owner(path: Path, directory: bool = False) -> None:
@@ -181,22 +181,13 @@ def _restrict_to_owner(path: Path, directory: bool = False) -> None:
181
181
 
182
182
 
183
183
  def save_endpoint(api_key: str, base_url: str, model: str) -> Path:
184
- """Write the config file with owner-only access where supported."""
185
- path = config_file()
186
- fresh_dir = not path.parent.exists()
187
- path.parent.mkdir(parents=True, exist_ok=True)
188
- if fresh_dir:
189
- _restrict_to_owner(path.parent, directory=True)
190
- path.touch(exist_ok=True)
191
- _restrict_to_owner(path)
192
- payload = {
193
- k: v
194
- for k, v in (("api_key", api_key), ("base_url", base_url), ("model", model))
195
- }
196
- path.write_text(
197
- json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
198
- )
199
- return path
184
+ """Write the endpoint into the active profile (creating ``default`` when
185
+ no profile exists), preserving every other saved profile."""
186
+ from .profiles import DEFAULT_PROFILE, ProfileStore
187
+
188
+ store = ProfileStore()
189
+ name = store.active_name() or DEFAULT_PROFILE
190
+ return store.upsert(name, base_url, api_key, model)
200
191
 
201
192
 
202
193
  def load_config(args: Any) -> Config:
@@ -221,7 +212,23 @@ def load_config(args: Any) -> Config:
221
212
  skills_dir = cand if cand.is_dir() else None
222
213
 
223
214
  mcp_raw = g("mcp", None) or os.environ.get(ENV_MCP)
224
- saved = load_saved_endpoint() # flag > env > config file, per key
215
+ # Endpoint layer: flag > env > selected profile's fields, per key.
216
+ # --profile / LITHE_PROFILE pick the profile (unknown name → hard exit).
217
+ from .profiles import ProfileStore
218
+
219
+ selected = g("profile", None) or os.environ.get(ENV_PROFILE)
220
+ store = ProfileStore()
221
+ saved = store.endpoint(selected) if (selected or store.names()) else {}
222
+ active = store.active_name(selected) if selected else store.active_name()
223
+ pinned = frozenset(
224
+ k
225
+ for k, flag, env in (
226
+ ("api_key", g("api_key", None), ENV_API_KEY),
227
+ ("base_url", g("base_url", None), ENV_BASE_URL),
228
+ ("model", g("model", None), ENV_MODEL),
229
+ )
230
+ if flag or os.environ.get(env)
231
+ )
225
232
  return Config(
226
233
  api_key=(
227
234
  g("api_key", None) or os.environ.get(ENV_API_KEY) or saved.get("api_key")
@@ -230,12 +237,13 @@ def load_config(args: Any) -> Config:
230
237
  g("base_url", None) or os.environ.get(ENV_BASE_URL) or saved.get("base_url")
231
238
  ),
232
239
  model=(g("model", None) or os.environ.get(ENV_MODEL) or saved.get("model")),
240
+ profile=active,
233
241
  store_dir=store_dir,
234
242
  workspace_dir=workspace_dir,
235
243
  user_id=g("user", None) or DEFAULT_USER,
236
244
  stream=g("stream", False),
237
245
  max_steps=g("max_steps", 35),
238
- context_window=g("context_window", None),
246
+ context_window=g("context_window", None) or saved.get("context_window"),
239
247
  timeout=g("timeout", 180.0),
240
248
  attempts=g("attempts", 2),
241
249
  download=g("download", False),
@@ -247,6 +255,7 @@ def load_config(args: Any) -> Config:
247
255
  mcp_servers=load_mcp_spec(mcp_raw) if mcp_raw else [],
248
256
  vision=g("vision", False),
249
257
  color=(True if g("color", False) else False if g("no_color", False) else None),
258
+ pinned_keys=pinned,
250
259
  )
251
260
 
252
261
 
@@ -272,6 +281,7 @@ def require_endpoint(cfg: Config, interactive: bool = False) -> None:
272
281
  "缺少模型端点配置。两种方式任选:\n"
273
282
  " 1) 交互式(推荐):运行 lithe-cli config,按提示输入后保存到\n"
274
283
  f" {config_file()}\n"
284
+ " 可保存多个档案(provider),用 lithe-cli config --use 切换。\n"
275
285
  " 2) 环境变量(或对应flag):\n"
276
286
  f" export {ENV_API_KEY}=sk-...\n"
277
287
  f" export {ENV_BASE_URL}=https://your-endpoint/api/v1\n"