lithe-cli 0.8.9__tar.gz → 0.9.1__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.
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/PKG-INFO +19 -8
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/README.md +17 -6
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/__init__.py +1 -1
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/agent.py +30 -2
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/config.py +31 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/main.py +61 -3
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/profiles.py +19 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/ttui.py +26 -6
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/tui.py +52 -12
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/ui.py +43 -1
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/workbench.py +66 -9
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/PKG-INFO +19 -8
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/SOURCES.txt +1 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/requires.txt +1 -1
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/pyproject.toml +1 -1
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_cli.py +90 -0
- lithe_cli-0.9.1/tests/test_cli_budget_steer.py +272 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_ttui.py +10 -6
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/LICENSE +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/__main__.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/commands.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/prompts.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/py.typed +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/sessions.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli/setup.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/dependency_links.txt +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/entry_points.txt +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/lithe_cli.egg-info/top_level.txt +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/setup.cfg +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_cli_sessions.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_cli_subagents.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_profiles.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_tui_v2.py +0 -0
- {lithe_cli-0.8.9 → lithe_cli-0.9.1}/tests/test_workbench.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lithe-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.1
|
|
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.
|
|
42
|
+
Requires-Dist: lithe>=0.9.22
|
|
43
43
|
Requires-Dist: prompt-toolkit>=3.0.38
|
|
44
44
|
Requires-Dist: textual>=1.0
|
|
45
45
|
Provides-Extra: dev
|
|
@@ -148,7 +148,12 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
|
|
|
148
148
|
usage/context gauges; `--max-steps` caps the tool loop;
|
|
149
149
|
`--context-window` enables fullness gauges; `--reasoning-effort LEVEL`
|
|
150
150
|
sets the reasoning intensity for one invocation (flag > profile field;
|
|
151
|
-
`/reasoning` adjusts it in-session).
|
|
151
|
+
`/reasoning` adjusts it in-session). Run budgets end the turn with
|
|
152
|
+
status `budget_exceeded` once crossed: `--max-cost USD` (needs a
|
|
153
|
+
`pricing` table in the profile on endpoints that report no usage cost)
|
|
154
|
+
and `--max-tokens N` (cumulative); both show progress lines in the
|
|
155
|
+
sidebar and adjust via `/set` (`off` clears). Sampling:
|
|
156
|
+
`--temperature` / `--max-output-tokens` (flag > profile field).
|
|
152
157
|
|
|
153
158
|
### Full-screen interface
|
|
154
159
|
|
|
@@ -160,7 +165,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
|
|
|
160
165
|
工具/待办、用量:
|
|
161
166
|
|
|
162
167
|
```text
|
|
163
|
-
lithe 0.
|
|
168
|
+
lithe 0.9.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
|
|
164
169
|
╭──────────────────────────────────────╮╭──────────────────────────╮
|
|
165
170
|
│ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
|
|
166
171
|
│ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
|
|
@@ -186,10 +191,14 @@ you come back. Typing `/` shows matching commands above the prompt (`Tab`
|
|
|
186
191
|
accepts; `/model`, `/profile`, `/set` complete their arguments too),
|
|
187
192
|
and `↑`/`↓` recall the persistent input history. `Ctrl+C` cancels the
|
|
188
193
|
current turn (a second press during the same turn force-exits) and exits
|
|
189
|
-
when idle.
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
194
|
+
when idle. Plain text typed mid-turn **steers** the running agent: it is
|
|
195
|
+
queued into the kernel's steering inbox and injected as a user message at
|
|
196
|
+
the next step boundary (rendered in the transcript; persistently
|
|
197
|
+
recorded), so you can correct course while it works — texts that cannot
|
|
198
|
+
be injected before the turn ends are honestly reported as dropped. Slash
|
|
199
|
+
commands work while a turn runs. The transcript follows new output only
|
|
200
|
+
while you're at the bottom — scroll up to re-read and your position
|
|
201
|
+
sticks.
|
|
193
202
|
|
|
194
203
|
Text selection uses the terminal's native `Shift+drag` (hide the sidebar
|
|
195
204
|
with F2 first if it grabs both panes). Pipes and CI keep the plain
|
|
@@ -249,6 +258,8 @@ The kernel ships these as bundles; the CLI grants them per flag:
|
|
|
249
258
|
| `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
|
|
250
259
|
| `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
|
|
251
260
|
| `--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 |
|
|
261
|
+
| `--max-cost USD` | (run budget) | the turn ends `budget_exceeded` once cumulative cost crosses it; on endpoints reporting no `usage.cost` add a profile `pricing` table (`{"prompt": 3, "completion": 15}` per 1M) — the preset providers' known prices work too |
|
|
262
|
+
| `--max-tokens N` | (run budget) | cumulative token budget for the turn; `--max-output-tokens N` is the different per-call cap |
|
|
252
263
|
| `--subagents` | `delegate` / `delegate_parallel` | kernel delegation on the default roster — `researcher` (read-only lookup, gains vision/document tools with those flags), `coder` (file edits + `run_code` with `--code`), `operator` (`run_command`/`download_file`, present only with `--shell`/`--download`); children inherit the endpoint and budgets, parallel workers share one live cost ceiling; `/set subagents` toggles in-session |
|
|
253
264
|
| `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
|
|
254
265
|
|
|
@@ -99,7 +99,12 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
|
|
|
99
99
|
usage/context gauges; `--max-steps` caps the tool loop;
|
|
100
100
|
`--context-window` enables fullness gauges; `--reasoning-effort LEVEL`
|
|
101
101
|
sets the reasoning intensity for one invocation (flag > profile field;
|
|
102
|
-
`/reasoning` adjusts it in-session).
|
|
102
|
+
`/reasoning` adjusts it in-session). Run budgets end the turn with
|
|
103
|
+
status `budget_exceeded` once crossed: `--max-cost USD` (needs a
|
|
104
|
+
`pricing` table in the profile on endpoints that report no usage cost)
|
|
105
|
+
and `--max-tokens N` (cumulative); both show progress lines in the
|
|
106
|
+
sidebar and adjust via `/set` (`off` clears). Sampling:
|
|
107
|
+
`--temperature` / `--max-output-tokens` (flag > profile field).
|
|
103
108
|
|
|
104
109
|
### Full-screen interface
|
|
105
110
|
|
|
@@ -111,7 +116,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
|
|
|
111
116
|
工具/待办、用量:
|
|
112
117
|
|
|
113
118
|
```text
|
|
114
|
-
lithe 0.
|
|
119
|
+
lithe 0.9.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
|
|
115
120
|
╭──────────────────────────────────────╮╭──────────────────────────╮
|
|
116
121
|
│ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
|
|
117
122
|
│ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
|
|
@@ -137,10 +142,14 @@ you come back. Typing `/` shows matching commands above the prompt (`Tab`
|
|
|
137
142
|
accepts; `/model`, `/profile`, `/set` complete their arguments too),
|
|
138
143
|
and `↑`/`↓` recall the persistent input history. `Ctrl+C` cancels the
|
|
139
144
|
current turn (a second press during the same turn force-exits) and exits
|
|
140
|
-
when idle.
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
145
|
+
when idle. Plain text typed mid-turn **steers** the running agent: it is
|
|
146
|
+
queued into the kernel's steering inbox and injected as a user message at
|
|
147
|
+
the next step boundary (rendered in the transcript; persistently
|
|
148
|
+
recorded), so you can correct course while it works — texts that cannot
|
|
149
|
+
be injected before the turn ends are honestly reported as dropped. Slash
|
|
150
|
+
commands work while a turn runs. The transcript follows new output only
|
|
151
|
+
while you're at the bottom — scroll up to re-read and your position
|
|
152
|
+
sticks.
|
|
144
153
|
|
|
145
154
|
Text selection uses the terminal's native `Shift+drag` (hide the sidebar
|
|
146
155
|
with F2 first if it grabs both panes). Pipes and CI keep the plain
|
|
@@ -200,6 +209,8 @@ The kernel ships these as bundles; the CLI grants them per flag:
|
|
|
200
209
|
| `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
|
|
201
210
|
| `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
|
|
202
211
|
| `--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 |
|
|
212
|
+
| `--max-cost USD` | (run budget) | the turn ends `budget_exceeded` once cumulative cost crosses it; on endpoints reporting no `usage.cost` add a profile `pricing` table (`{"prompt": 3, "completion": 15}` per 1M) — the preset providers' known prices work too |
|
|
213
|
+
| `--max-tokens N` | (run budget) | cumulative token budget for the turn; `--max-output-tokens N` is the different per-call cap |
|
|
203
214
|
| `--subagents` | `delegate` / `delegate_parallel` | kernel delegation on the default roster — `researcher` (read-only lookup, gains vision/document tools with those flags), `coder` (file edits + `run_code` with `--code`), `operator` (`run_command`/`download_file`, present only with `--shell`/`--download`); children inherit the endpoint and budgets, parallel workers share one live cost ceiling; `/set subagents` toggles in-session |
|
|
204
215
|
| `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
|
|
205
216
|
|
|
@@ -114,6 +114,14 @@ def build_llm(cfg: Config) -> LLMConfig:
|
|
|
114
114
|
# Explicit dialect (flag/profile) overrides the preset default;
|
|
115
115
|
# apply_preset skips the None override so the preset fills in.
|
|
116
116
|
"document_format": cfg.document_format,
|
|
117
|
+
# Sampling + vendor passthrough + pricing: None skips (preset may
|
|
118
|
+
# fill extra_body/default_headers; dict fields merge per key with
|
|
119
|
+
# the explicit value winning per key).
|
|
120
|
+
"temperature": cfg.temperature,
|
|
121
|
+
"max_tokens": cfg.max_tokens,
|
|
122
|
+
"extra_body": cfg.extra_body,
|
|
123
|
+
"default_headers": cfg.default_headers,
|
|
124
|
+
"pricing": cfg.pricing,
|
|
117
125
|
}
|
|
118
126
|
# The CLI's transport field defaults to "chat" and is only overridden by
|
|
119
127
|
# offline tests (custom transports); the default must not clobber a
|
|
@@ -188,6 +196,8 @@ def build_host(cfg: Config, reg: ToolRegistry) -> AgentHost:
|
|
|
188
196
|
build_llm(cfg),
|
|
189
197
|
store,
|
|
190
198
|
max_steps=cfg.max_steps,
|
|
199
|
+
max_cost=cfg.max_cost,
|
|
200
|
+
max_total_tokens=cfg.max_total_tokens,
|
|
191
201
|
build_system_prompt=lambda ctx, mode, anchor: prompt,
|
|
192
202
|
)
|
|
193
203
|
|
|
@@ -304,9 +314,23 @@ def render_event(
|
|
|
304
314
|
pending[ev["id"]] = time.monotonic()
|
|
305
315
|
elif t == "tool_result":
|
|
306
316
|
summary = (ev.get("summary") or "").replace("\n", " ")
|
|
317
|
+
if not ev.get("ok") and ev.get("error"):
|
|
318
|
+
# Failed calls carry the diagnostic in ``error``; the summary
|
|
319
|
+
# alone ("参数错误") tells the user nothing actionable. When one
|
|
320
|
+
# text already contains the other (common: summary is a prefix
|
|
321
|
+
# of the error), show only the longer one instead of echoing.
|
|
322
|
+
detail = str(ev["error"]).replace("\n", " ")
|
|
323
|
+
if detail and summary and (detail in summary or summary in detail):
|
|
324
|
+
summary = detail if len(detail) > len(summary) else summary
|
|
325
|
+
elif detail:
|
|
326
|
+
summary = f"{summary} · {detail}" if summary else detail
|
|
307
327
|
started = pending.pop(ev.get("id"), None) if ev.get("id") else None
|
|
308
328
|
elapsed = (time.monotonic() - started) if started is not None else None
|
|
309
329
|
ui.tool_result(bool(ev.get("ok")), summary, elapsed)
|
|
330
|
+
elif t == "todo_change":
|
|
331
|
+
# update_todos replaced the list; print what it now contains —
|
|
332
|
+
# the tool's own result line only reports the item count.
|
|
333
|
+
ui.todo_change(ev.get("new") or [])
|
|
310
334
|
elif t == "error":
|
|
311
335
|
ui.error(str(ev.get("message", "")))
|
|
312
336
|
elif t == "cancelled":
|
|
@@ -334,6 +358,7 @@ async def execute(
|
|
|
334
358
|
on_event=None,
|
|
335
359
|
stop=None,
|
|
336
360
|
conversation_id: int | None = None,
|
|
361
|
+
inbox=None,
|
|
337
362
|
) -> tuple[str, dict, Any]:
|
|
338
363
|
"""Run one task end-to-end; returns (run_id, done_event, host).
|
|
339
364
|
|
|
@@ -342,7 +367,9 @@ async def execute(
|
|
|
342
367
|
footer — the caller renders from the events instead. ``stop`` is the
|
|
343
368
|
kernel's cancellation handle, surfaced so Ctrl+C can cancel a turn
|
|
344
369
|
without killing the process. ``conversation_id`` attaches the run to a
|
|
345
|
-
stored session (kernel host already consumes ctx.extra).
|
|
370
|
+
stored session (kernel host already consumes ctx.extra). ``inbox`` is
|
|
371
|
+
the steering channel: a queue of user texts the kernel drains at step
|
|
372
|
+
boundaries and injects as user messages (see AgentRuntime.run).
|
|
346
373
|
"""
|
|
347
374
|
reg = build_registry(cfg)
|
|
348
375
|
host = build_host(cfg, reg)
|
|
@@ -369,7 +396,8 @@ async def execute(
|
|
|
369
396
|
ev: dict = {}
|
|
370
397
|
pending: dict[str, float] = {}
|
|
371
398
|
try:
|
|
372
|
-
async for ev in host.run(ctx, task, history=history, stop=stop
|
|
399
|
+
async for ev in host.run(ctx, task, history=history, stop=stop,
|
|
400
|
+
inbox=inbox):
|
|
373
401
|
if on_event is not None:
|
|
374
402
|
on_event(ev)
|
|
375
403
|
else:
|
|
@@ -71,6 +71,26 @@ class Config:
|
|
|
71
71
|
# delegate_parallel on the CLI's default roster. Off by default — each
|
|
72
72
|
# delegation is a full agent run, so token spend multiplies.
|
|
73
73
|
subagents: bool = False
|
|
74
|
+
# Run budgets (kernel AgentHost): the run ends with status
|
|
75
|
+
# "budget_exceeded" once cumulative cost / tokens cross the cap. None
|
|
76
|
+
# disables the cap.
|
|
77
|
+
max_cost: float | None = None
|
|
78
|
+
max_total_tokens: int | None = None
|
|
79
|
+
# Sampling knobs forwarded to LLMConfig (None = endpoint default).
|
|
80
|
+
temperature: float | None = None
|
|
81
|
+
# Per-call output cap (LLMConfig.max_tokens); the run-level budget is
|
|
82
|
+
# max_total_tokens above — different things despite similar names.
|
|
83
|
+
max_tokens: int | None = None
|
|
84
|
+
# Vendor request fields / headers (LLMConfig passthrough). Usually
|
|
85
|
+
# contributed by a provider preset; a profile can carry its own for
|
|
86
|
+
# gateways no preset knows.
|
|
87
|
+
extra_body: dict | None = None
|
|
88
|
+
default_headers: dict | None = None
|
|
89
|
+
# Per-1M-token price table (LLMConfig.pricing): computes call cost on
|
|
90
|
+
# endpoints that report no usage.cost, which is what makes max_cost
|
|
91
|
+
# actually enforceable there. {"prompt": float, "completion": float,
|
|
92
|
+
# "cached_prompt": float?}
|
|
93
|
+
pricing: dict | None = None
|
|
74
94
|
store_dir: Path = field(default_factory=lambda: default_store_dir())
|
|
75
95
|
workspace_dir: Path = field(default_factory=lambda: Path.cwd())
|
|
76
96
|
user_id: str = DEFAULT_USER
|
|
@@ -300,6 +320,17 @@ def load_config(args: Any) -> Config:
|
|
|
300
320
|
and document_format.strip() else None),
|
|
301
321
|
document=g("document", False),
|
|
302
322
|
subagents=g("subagents", False),
|
|
323
|
+
max_cost=g("max_cost", None),
|
|
324
|
+
max_total_tokens=g("max_total_tokens", None),
|
|
325
|
+
temperature=(
|
|
326
|
+
g("temperature", None) if g("temperature", None) is not None
|
|
327
|
+
else saved.get("temperature")),
|
|
328
|
+
max_tokens=(
|
|
329
|
+
g("max_tokens", None) if g("max_tokens", None) is not None
|
|
330
|
+
else saved.get("max_tokens")),
|
|
331
|
+
extra_body=saved.get("extra_body"),
|
|
332
|
+
default_headers=saved.get("default_headers"),
|
|
333
|
+
pricing=saved.get("pricing"),
|
|
303
334
|
reasoning_effort=(effort.strip() if isinstance(effort, str) and effort.strip()
|
|
304
335
|
else None),
|
|
305
336
|
store_dir=store_dir,
|
|
@@ -159,6 +159,36 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
159
159
|
sp.add_argument(
|
|
160
160
|
"--attempts", type=int, default=2, help="per-call retry attempts"
|
|
161
161
|
)
|
|
162
|
+
sp.add_argument(
|
|
163
|
+
"--temperature",
|
|
164
|
+
type=float,
|
|
165
|
+
default=None,
|
|
166
|
+
help="sampling temperature (default: profile field, else endpoint default)",
|
|
167
|
+
)
|
|
168
|
+
sp.add_argument(
|
|
169
|
+
"--max-output-tokens",
|
|
170
|
+
dest="max_tokens",
|
|
171
|
+
type=int,
|
|
172
|
+
default=None,
|
|
173
|
+
help="per-call output token cap (default: profile max_tokens, "
|
|
174
|
+
"else endpoint default); NOT the run budget --max-tokens",
|
|
175
|
+
)
|
|
176
|
+
sp.add_argument(
|
|
177
|
+
"--max-cost",
|
|
178
|
+
type=float,
|
|
179
|
+
default=None,
|
|
180
|
+
help="run cost budget in USD: the run ends with status "
|
|
181
|
+
"budget_exceeded once cumulative cost crosses it (needs a "
|
|
182
|
+
"pricing table on endpoints that report no usage cost)",
|
|
183
|
+
)
|
|
184
|
+
sp.add_argument(
|
|
185
|
+
"--max-tokens",
|
|
186
|
+
dest="max_total_tokens",
|
|
187
|
+
type=int,
|
|
188
|
+
default=None,
|
|
189
|
+
help="run total-token budget: ends with budget_exceeded once "
|
|
190
|
+
"cumulative tokens cross it",
|
|
191
|
+
)
|
|
162
192
|
sp.add_argument(
|
|
163
193
|
"--reasoning-effort",
|
|
164
194
|
metavar="LEVEL",
|
|
@@ -255,15 +285,20 @@ def _cmd_runs(cfg: Any, limit: int) -> int:
|
|
|
255
285
|
if not runs:
|
|
256
286
|
print(ui.s(f"({cfg.store_dir} 下没有 run 记录)", YELLOW))
|
|
257
287
|
return 0
|
|
288
|
+
from .ui import fmt_duration
|
|
289
|
+
|
|
258
290
|
rows = []
|
|
259
291
|
for r in reversed(runs): # newest last, like a log
|
|
260
292
|
task = (r.task or "").replace("\n", " ")
|
|
261
|
-
|
|
293
|
+
duration = (fmt_duration(r.finished_at - r.created_at)
|
|
294
|
+
if r.created_at and r.finished_at else "—")
|
|
295
|
+
rows.append([r.run_id, r.status, str(r.steps), f"{r.cost:.4f}",
|
|
296
|
+
duration, truncate(task, 60)])
|
|
262
297
|
print(
|
|
263
298
|
ui.table(
|
|
264
|
-
["run", "status", "steps", "cost", "task"],
|
|
299
|
+
["run", "status", "steps", "cost", "time", "task"],
|
|
265
300
|
rows,
|
|
266
|
-
cell_styles=[ui.s, ui.status, ui.s, ui.s, ui.s],
|
|
301
|
+
cell_styles=[ui.s, ui.status, ui.s, ui.s, ui.s, ui.s],
|
|
267
302
|
)
|
|
268
303
|
)
|
|
269
304
|
return 0
|
|
@@ -275,9 +310,14 @@ def _cmd_log(cfg: Any, run_id: str) -> int:
|
|
|
275
310
|
if run is None:
|
|
276
311
|
print(ui.s(f"找不到 run {run_id}(user={cfg.user_id})", RED))
|
|
277
312
|
return 1
|
|
313
|
+
from .ui import fmt_duration
|
|
314
|
+
|
|
315
|
+
duration = (fmt_duration(run.finished_at - run.created_at)
|
|
316
|
+
if run.created_at and run.finished_at else None)
|
|
278
317
|
print(
|
|
279
318
|
f"run {ui.s(run.run_id, CYAN)} status={ui.status(run.status)} "
|
|
280
319
|
f"steps={run.steps} model={run.model}"
|
|
320
|
+
+ (f" 耗时={duration}" if duration else "")
|
|
281
321
|
)
|
|
282
322
|
print(f"task: {run.task}")
|
|
283
323
|
if run.final:
|
|
@@ -514,6 +554,24 @@ def _cmd_config(args: Any) -> int:
|
|
|
514
554
|
print(ui.kv("provider", saved["provider"]))
|
|
515
555
|
if saved.get("document_format"):
|
|
516
556
|
print(ui.kv("document_format", saved["document_format"]))
|
|
557
|
+
ep = store.endpoint() # full dict: sampling/vendor/pricing fields
|
|
558
|
+
if ep.get("context_window"):
|
|
559
|
+
print(ui.kv("context_window", f"{ep['context_window']:,}"))
|
|
560
|
+
if ep.get("temperature") is not None:
|
|
561
|
+
print(ui.kv("temperature", ep["temperature"]))
|
|
562
|
+
if ep.get("max_tokens"):
|
|
563
|
+
print(ui.kv("max_tokens", f"{ep['max_tokens']:,}"))
|
|
564
|
+
if ep.get("extra_body"):
|
|
565
|
+
import json as _json
|
|
566
|
+
|
|
567
|
+
print(ui.kv("extra_body",
|
|
568
|
+
_json.dumps(ep["extra_body"], ensure_ascii=False)))
|
|
569
|
+
if ep.get("default_headers"):
|
|
570
|
+
print(ui.kv("default_headers",
|
|
571
|
+
",".join(ep["default_headers"])))
|
|
572
|
+
if ep.get("pricing"):
|
|
573
|
+
print(ui.kv("pricing", "、".join(
|
|
574
|
+
f"{k}=${v}/1M" for k, v in ep["pricing"].items())))
|
|
517
575
|
print(ui.kv("base_url", saved["base_url"]))
|
|
518
576
|
print(ui.kv("api_key", masked))
|
|
519
577
|
print(ui.kv("model", saved["model"]))
|
|
@@ -83,6 +83,25 @@ def _clean_endpoint(data: dict) -> dict:
|
|
|
83
83
|
v = data.get(k)
|
|
84
84
|
if isinstance(v, int) and v > 0:
|
|
85
85
|
out[k] = v
|
|
86
|
+
temperature = data.get("temperature")
|
|
87
|
+
if isinstance(temperature, (int, float)) and not isinstance(temperature, bool):
|
|
88
|
+
out["temperature"] = float(temperature)
|
|
89
|
+
max_tokens = data.get("max_tokens")
|
|
90
|
+
if isinstance(max_tokens, int) and not isinstance(max_tokens, bool) \
|
|
91
|
+
and max_tokens > 0:
|
|
92
|
+
out["max_tokens"] = max_tokens
|
|
93
|
+
extra_body = data.get("extra_body")
|
|
94
|
+
if isinstance(extra_body, dict) and extra_body:
|
|
95
|
+
out["extra_body"] = extra_body
|
|
96
|
+
headers = data.get("default_headers")
|
|
97
|
+
if isinstance(headers, dict) and headers:
|
|
98
|
+
out["default_headers"] = headers
|
|
99
|
+
pricing = data.get("pricing")
|
|
100
|
+
if isinstance(pricing, dict) and pricing:
|
|
101
|
+
# keep numeric entries only; LLMConfig validates the exact contract
|
|
102
|
+
out["pricing"] = {k: v for k, v in pricing.items()
|
|
103
|
+
if isinstance(v, (int, float))
|
|
104
|
+
and not isinstance(v, bool)}
|
|
86
105
|
cm = data.get("cached_models")
|
|
87
106
|
if isinstance(cm, list) and cm:
|
|
88
107
|
out["cached_models"] = [str(m) for m in cm if str(m).strip()]
|
|
@@ -31,6 +31,7 @@ from textual.screen import ModalScreen
|
|
|
31
31
|
from textual.widgets import Input, Label, ListItem, ListView, Static
|
|
32
32
|
|
|
33
33
|
from .tui import TuiState, transcript_feed_lines
|
|
34
|
+
from .ui import fmt_duration
|
|
34
35
|
|
|
35
36
|
_MAX_FEED = 400 # mounted conversation lines before trimming the oldest
|
|
36
37
|
|
|
@@ -82,6 +83,8 @@ def sidebar_markup(state: TuiState) -> str:
|
|
|
82
83
|
status_color = "red"
|
|
83
84
|
out.append(f"[{status_color}]● {state.status}[/]")
|
|
84
85
|
out.append(f"[dim]步骤 {state.step}/{state.max_steps}[/]")
|
|
86
|
+
if not state.running and state.last_turn_duration is not None:
|
|
87
|
+
out.append(f"[dim]本轮耗时 {fmt_duration(state.last_turn_duration)}[/]")
|
|
85
88
|
out.append("[dim]◆ 工具[/]")
|
|
86
89
|
if not state.tools:
|
|
87
90
|
out.append("[dim]暂无调用[/]")
|
|
@@ -124,6 +127,10 @@ def sidebar_markup(state: TuiState) -> str:
|
|
|
124
127
|
out.append(f"合计 {tokens:,}")
|
|
125
128
|
out.append(f"本轮费用 ${turn_cost:.4f}")
|
|
126
129
|
out.append(f"累计费用 ${cost:.4f}")
|
|
130
|
+
if state.max_cost is not None:
|
|
131
|
+
out.append(f"[dim]成本预算 ${cost:.4f} / ${state.max_cost:.2f}[/]")
|
|
132
|
+
if state.max_total_tokens is not None:
|
|
133
|
+
out.append(f"[dim]token 预算 {tokens:,} / {state.max_total_tokens:,}[/]")
|
|
127
134
|
out.append(f"上下文 {context}")
|
|
128
135
|
return "\n".join(out)
|
|
129
136
|
|
|
@@ -447,7 +454,7 @@ class LitheApp(App):
|
|
|
447
454
|
title = ""
|
|
448
455
|
if cid is not None:
|
|
449
456
|
title = (self.wb.sessions.get(cid) or {}).get("title", "")
|
|
450
|
-
|
|
457
|
+
st = TuiState(
|
|
451
458
|
self.cfg.model or "(scripted)",
|
|
452
459
|
str(self.cfg.workspace_dir.resolve()),
|
|
453
460
|
self.cfg.max_steps,
|
|
@@ -456,12 +463,18 @@ class LitheApp(App):
|
|
|
456
463
|
session_id=cid,
|
|
457
464
|
session_title=title,
|
|
458
465
|
)
|
|
466
|
+
st.max_cost = self.cfg.max_cost
|
|
467
|
+
st.max_total_tokens = self.cfg.max_total_tokens
|
|
468
|
+
return st
|
|
459
469
|
|
|
460
470
|
def _refresh_meta(self) -> None:
|
|
461
471
|
st = self.state
|
|
462
472
|
st.model = self.cfg.model or "(scripted)"
|
|
463
473
|
st.profile = self.cfg.profile or ""
|
|
464
474
|
st.reasoning_effort = self.cfg.reasoning_effort
|
|
475
|
+
st.max_steps = self.cfg.max_steps
|
|
476
|
+
st.max_cost = self.cfg.max_cost
|
|
477
|
+
st.max_total_tokens = self.cfg.max_total_tokens
|
|
465
478
|
if self.wb.current is not None:
|
|
466
479
|
st.session_id = self.wb.current["id"]
|
|
467
480
|
st.session_title = self.wb.current.get("title") or ""
|
|
@@ -604,11 +617,18 @@ class LitheApp(App):
|
|
|
604
617
|
if not line:
|
|
605
618
|
return
|
|
606
619
|
if self.state.running and not line.startswith("/"):
|
|
607
|
-
# Plain text mid-turn
|
|
608
|
-
#
|
|
609
|
-
#
|
|
610
|
-
#
|
|
611
|
-
#
|
|
620
|
+
# Plain text mid-turn steers the running turn: queued into the
|
|
621
|
+
# kernel's inbox and injected as a user message at the next
|
|
622
|
+
# step boundary (user_injected event renders the line). When
|
|
623
|
+
# no turn is actually draining (one-shot mode), fall back to
|
|
624
|
+
# putting the text back in the input box. Slash commands still
|
|
625
|
+
# dispatch below — the workbench supports them mid-turn.
|
|
626
|
+
if self.wb.steer(line, self._current_cid()):
|
|
627
|
+
from .ui import truncate
|
|
628
|
+
self.state.say(
|
|
629
|
+
"dim", f"(已排队,将在当前步骤后注入:{truncate(line, 48)})")
|
|
630
|
+
self._sync_feed()
|
|
631
|
+
return
|
|
612
632
|
self.query_one("#prompt", HistoryInput).value = line
|
|
613
633
|
self.state.say("warn", "本轮还在进行中,未发送;文本已放回输入框,命令仍可用")
|
|
614
634
|
self._sync_feed()
|
|
@@ -22,7 +22,7 @@ import os
|
|
|
22
22
|
import sys
|
|
23
23
|
import time
|
|
24
24
|
|
|
25
|
-
from .ui import tool_call_label, truncate
|
|
25
|
+
from .ui import fmt_duration, tool_call_label, truncate
|
|
26
26
|
|
|
27
27
|
_STATUS_DONE = "done"
|
|
28
28
|
|
|
@@ -73,6 +73,7 @@ class TuiState:
|
|
|
73
73
|
self.output_tokens = 0
|
|
74
74
|
self.cached_tokens = 0
|
|
75
75
|
self.last_turn_cost = 0.0
|
|
76
|
+
self.last_turn_duration: float | None = None
|
|
76
77
|
self._turn_tokens = 0
|
|
77
78
|
self._turn_cost = 0.0
|
|
78
79
|
self._turn_input_tokens = 0
|
|
@@ -83,6 +84,9 @@ class TuiState:
|
|
|
83
84
|
self.context_window = None
|
|
84
85
|
self.context_percent = None
|
|
85
86
|
self.reasoning_effort: str | None = None
|
|
87
|
+
# Run budgets (for the sidebar progress lines); None = no cap.
|
|
88
|
+
self.max_cost: float | None = None
|
|
89
|
+
self.max_total_tokens: int | None = None
|
|
86
90
|
self.tools: list[dict] = []
|
|
87
91
|
self.feed: list[tuple[str, str]] = []
|
|
88
92
|
self.streaming = ""
|
|
@@ -183,10 +187,24 @@ class TuiState:
|
|
|
183
187
|
self.say("tool", f"◆ {tool_call_label(name, args)}")
|
|
184
188
|
self.status = f"工具 {name}"
|
|
185
189
|
elif kind == "tool_result":
|
|
186
|
-
self._settle_tool(ev.get("id"), bool(ev.get("ok")),
|
|
190
|
+
self._settle_tool(ev.get("id"), bool(ev.get("ok")),
|
|
191
|
+
ev.get("summary"), ev.get("error"))
|
|
187
192
|
elif kind == "todo_change":
|
|
188
193
|
self.todos = list(ev.get("new") or [])
|
|
189
|
-
|
|
194
|
+
done = sum(1 for t in self.todos if t.get("status") == "completed")
|
|
195
|
+
# The list belongs in the conversation feed, not only the
|
|
196
|
+
# sidebar: the sidebar can be hidden (F2) and caps at the last
|
|
197
|
+
# few items, which is exactly how "todos were created but I
|
|
198
|
+
# can't see them" happens.
|
|
199
|
+
self.say("dim", f"▤ 任务清单已更新({done}/{len(self.todos)} 完成)")
|
|
200
|
+
marks = {"pending": "[ ]", "in_progress": "[~]",
|
|
201
|
+
"completed": "[x]", "cancelled": "[-]"}
|
|
202
|
+
row_cls = {"in_progress": "warn", "completed": "ok"}
|
|
203
|
+
for n, item in enumerate(self.todos, 1):
|
|
204
|
+
status = str(item.get("status") or "pending")
|
|
205
|
+
self.say(row_cls.get(status, "dim"),
|
|
206
|
+
f" {n}. {marks.get(status, '[ ]')} "
|
|
207
|
+
f"{item.get('content', '')}")
|
|
190
208
|
elif kind == "usage":
|
|
191
209
|
self._turn_input_tokens += int(ev.get("prompt_tokens") or 0)
|
|
192
210
|
self._turn_output_tokens += int(ev.get("completion_tokens") or 0)
|
|
@@ -208,6 +226,11 @@ class TuiState:
|
|
|
208
226
|
self.say("err", str(ev.get("message") or "运行出错"))
|
|
209
227
|
elif kind == "cancelled":
|
|
210
228
|
self.say("warn", "(已取消)")
|
|
229
|
+
elif kind == "user_injected":
|
|
230
|
+
# Steering: a queued user text the kernel injected mid-run at a
|
|
231
|
+
# step boundary; render it as a user line so the transcript
|
|
232
|
+
# shows why the model's course changed.
|
|
233
|
+
self.say("user", str(ev.get("text") or ""))
|
|
211
234
|
elif kind == "done":
|
|
212
235
|
status = str(ev.get("status") or _STATUS_DONE)
|
|
213
236
|
self.last_status = status
|
|
@@ -236,21 +259,38 @@ class TuiState:
|
|
|
236
259
|
self.context_window = int(ev["context_window"])
|
|
237
260
|
if ev.get("context_percent") is not None:
|
|
238
261
|
self.context_percent = ev["context_percent"]
|
|
239
|
-
|
|
240
|
-
|
|
262
|
+
# Turn length: prefer the kernel's duration_s (covers the whole
|
|
263
|
+
# run incl. prompt assembly); fall back to the local run_start
|
|
264
|
+
# timer for envelopes that predate the field.
|
|
265
|
+
if ev.get("duration_s") is not None:
|
|
266
|
+
self.last_turn_duration = float(ev["duration_s"])
|
|
267
|
+
elif self.started is not None:
|
|
268
|
+
self.last_turn_duration = time.monotonic() - self.started
|
|
269
|
+
if self.last_turn_duration is not None:
|
|
270
|
+
self.status += f" · {fmt_duration(self.last_turn_duration)}"
|
|
241
271
|
self.invalidate()
|
|
242
272
|
|
|
243
|
-
def _settle_tool(self, tool_id, ok: bool, summary) -> None:
|
|
273
|
+
def _settle_tool(self, tool_id, ok: bool, summary, error=None) -> None:
|
|
244
274
|
tool = next(
|
|
245
275
|
(t for t in reversed(self.tools) if t["id"] == tool_id and t["status"] == "running"),
|
|
246
276
|
None,
|
|
247
277
|
)
|
|
248
|
-
if tool is
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
278
|
+
if tool is None:
|
|
279
|
+
return
|
|
280
|
+
tool["elapsed"] = time.monotonic() - tool["t0"]
|
|
281
|
+
tool["status"] = "done" if ok else "failed"
|
|
282
|
+
label = str(summary or tool["name"]).replace("\n", " ")
|
|
283
|
+
if not ok and error:
|
|
284
|
+
# Same rule as the plain CLI: a failed call's summary ("参数错误")
|
|
285
|
+
# without the diagnostic is not readable output; when one text
|
|
286
|
+
# contains the other, keep only the longer one.
|
|
287
|
+
detail = str(error).replace("\n", " ")
|
|
288
|
+
if detail and label and (detail in label or label in detail):
|
|
289
|
+
label = detail if len(detail) > len(label) else label
|
|
290
|
+
elif detail:
|
|
291
|
+
label = f"{label} · {detail}" if label else detail
|
|
292
|
+
mark = "✓" if ok else "✗"
|
|
293
|
+
self.say("ok" if ok else "err", f"{mark} {label} {tool['elapsed']:.1f}s")
|
|
254
294
|
|
|
255
295
|
|
|
256
296
|
_CHAT_KEYS = """按键:PgUp/PgDn 或鼠标滚轮 滚动对话,Home/End 跳到顶/底。
|
|
@@ -126,6 +126,23 @@ def tool_call_label(name: str, args: dict) -> str:
|
|
|
126
126
|
return name
|
|
127
127
|
|
|
128
128
|
|
|
129
|
+
def fmt_duration(seconds: float | None) -> str:
|
|
130
|
+
"""Human wall-clock length: ``12.3s`` / ``2m05s`` / ``1h04m``.
|
|
131
|
+
|
|
132
|
+
Empty string for ``None`` so callers can drop the field silently.
|
|
133
|
+
"""
|
|
134
|
+
if seconds is None:
|
|
135
|
+
return ""
|
|
136
|
+
seconds = max(0.0, float(seconds))
|
|
137
|
+
if seconds < 60:
|
|
138
|
+
return f"{seconds:.1f}s"
|
|
139
|
+
minutes = int(seconds // 60)
|
|
140
|
+
sec = int(round(seconds % 60))
|
|
141
|
+
if minutes < 60:
|
|
142
|
+
return f"{minutes}m{sec:02d}s"
|
|
143
|
+
return f"{minutes // 60}h{minutes % 60:02d}m"
|
|
144
|
+
|
|
145
|
+
|
|
129
146
|
class UI:
|
|
130
147
|
"""All terminal output goes through here; ``color`` gates every code."""
|
|
131
148
|
|
|
@@ -227,6 +244,28 @@ class UI:
|
|
|
227
244
|
label = truncate(summary, max(8, self.width - 8 - display_width(tail)))
|
|
228
245
|
print(f" {mark} {self.s(label, GREEN if ok else RED)}{tail}")
|
|
229
246
|
|
|
247
|
+
_TODO_MARKS = {"pending": "[ ]", "in_progress": "[~]",
|
|
248
|
+
"completed": "[x]", "cancelled": "[-]"}
|
|
249
|
+
_TODO_COLORS = {"in_progress": YELLOW, "completed": GREEN}
|
|
250
|
+
|
|
251
|
+
def todo_change(self, items: list) -> None:
|
|
252
|
+
"""Print the full task list after an ``update_todos`` replace.
|
|
253
|
+
|
|
254
|
+
The tool's one-line summary only carries the count; without this
|
|
255
|
+
block the user never sees what the agent actually planned.
|
|
256
|
+
"""
|
|
257
|
+
done = sum(1 for it in items if it.get("status") == "completed")
|
|
258
|
+
head = f"任务清单({done}/{len(items)} 完成)"
|
|
259
|
+
print(f" {self.s('▤', MAGENTA)} {self.s(head, MAGENTA, BOLD)}")
|
|
260
|
+
for n, it in enumerate(items, 1):
|
|
261
|
+
status = str(it.get("status") or "pending")
|
|
262
|
+
mark = self._TODO_MARKS.get(status, "[ ]")
|
|
263
|
+
color = self._TODO_COLORS.get(status)
|
|
264
|
+
mark = self.s(mark, color) if color else mark
|
|
265
|
+
content = truncate(str(it.get("content") or ""),
|
|
266
|
+
max(8, self.width - 12))
|
|
267
|
+
print(f" {n}. {mark} {content}")
|
|
268
|
+
|
|
230
269
|
def error(self, msg: str) -> None:
|
|
231
270
|
print(f" {self.s('!', RED)} {self.s(msg, RED)}")
|
|
232
271
|
|
|
@@ -244,7 +283,7 @@ class UI:
|
|
|
244
283
|
return self.s(f" ~ {digest}", DIM)
|
|
245
284
|
|
|
246
285
|
def footer(self, ev: dict) -> None:
|
|
247
|
-
"""The one-line wrap-up after a run: status · steps · tokens · cost."""
|
|
286
|
+
"""The one-line wrap-up after a run: status · steps · tokens · cost · time."""
|
|
248
287
|
parts = [self.status(str(ev.get("status", "?")))]
|
|
249
288
|
if ev.get("steps") is not None:
|
|
250
289
|
parts.append(f"steps {ev['steps']}")
|
|
@@ -256,6 +295,9 @@ class UI:
|
|
|
256
295
|
cost = ev.get("cost")
|
|
257
296
|
if cost:
|
|
258
297
|
parts.append(f"cost {cost:.4f}")
|
|
298
|
+
duration = fmt_duration(ev.get("duration_s"))
|
|
299
|
+
if duration:
|
|
300
|
+
parts.append(duration)
|
|
259
301
|
print(f"{self.s('──', DIM)} {' · '.join(parts)}")
|
|
260
302
|
|
|
261
303
|
# -- chat ---------------------------------------------------------------
|