lithe-cli 0.8.9__tar.gz → 0.9.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 (34) hide show
  1. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/PKG-INFO +19 -8
  2. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/README.md +17 -6
  3. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/agent.py +16 -2
  5. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/config.py +31 -0
  6. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/main.py +48 -0
  7. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/profiles.py +19 -0
  8. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/ttui.py +23 -6
  9. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/tui.py +8 -0
  10. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/workbench.py +66 -9
  11. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/PKG-INFO +19 -8
  12. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/SOURCES.txt +1 -0
  13. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/requires.txt +1 -1
  14. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/pyproject.toml +1 -1
  15. lithe_cli-0.9.0/tests/test_cli_budget_steer.py +272 -0
  16. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_ttui.py +10 -6
  17. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/LICENSE +0 -0
  18. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/__main__.py +0 -0
  19. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/commands.py +0 -0
  20. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/prompts.py +0 -0
  21. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/py.typed +0 -0
  22. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/sessions.py +0 -0
  23. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/setup.py +0 -0
  24. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli/ui.py +0 -0
  25. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/dependency_links.txt +0 -0
  26. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/entry_points.txt +0 -0
  27. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/lithe_cli.egg-info/top_level.txt +0 -0
  28. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/setup.cfg +0 -0
  29. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_cli.py +0 -0
  30. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_cli_sessions.py +0 -0
  31. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_cli_subagents.py +0 -0
  32. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_profiles.py +0 -0
  33. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/tests/test_tui_v2.py +0 -0
  34. {lithe_cli-0.8.9 → lithe_cli-0.9.0}/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.9
3
+ Version: 0.9.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.19
42
+ Requires-Dist: lithe>=0.9.21
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.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
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. 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.
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.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
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. 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.
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
 
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.8.9"
3
+ __version__ = "0.9.0"
@@ -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
 
@@ -334,6 +344,7 @@ async def execute(
334
344
  on_event=None,
335
345
  stop=None,
336
346
  conversation_id: int | None = None,
347
+ inbox=None,
337
348
  ) -> tuple[str, dict, Any]:
338
349
  """Run one task end-to-end; returns (run_id, done_event, host).
339
350
 
@@ -342,7 +353,9 @@ async def execute(
342
353
  footer — the caller renders from the events instead. ``stop`` is the
343
354
  kernel's cancellation handle, surfaced so Ctrl+C can cancel a turn
344
355
  without killing the process. ``conversation_id`` attaches the run to a
345
- stored session (kernel host already consumes ctx.extra).
356
+ stored session (kernel host already consumes ctx.extra). ``inbox`` is
357
+ the steering channel: a queue of user texts the kernel drains at step
358
+ boundaries and injects as user messages (see AgentRuntime.run).
346
359
  """
347
360
  reg = build_registry(cfg)
348
361
  host = build_host(cfg, reg)
@@ -369,7 +382,8 @@ async def execute(
369
382
  ev: dict = {}
370
383
  pending: dict[str, float] = {}
371
384
  try:
372
- async for ev in host.run(ctx, task, history=history, stop=stop):
385
+ async for ev in host.run(ctx, task, history=history, stop=stop,
386
+ inbox=inbox):
373
387
  if on_event is not None:
374
388
  on_event(ev)
375
389
  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",
@@ -514,6 +544,24 @@ def _cmd_config(args: Any) -> int:
514
544
  print(ui.kv("provider", saved["provider"]))
515
545
  if saved.get("document_format"):
516
546
  print(ui.kv("document_format", saved["document_format"]))
547
+ ep = store.endpoint() # full dict: sampling/vendor/pricing fields
548
+ if ep.get("context_window"):
549
+ print(ui.kv("context_window", f"{ep['context_window']:,}"))
550
+ if ep.get("temperature") is not None:
551
+ print(ui.kv("temperature", ep["temperature"]))
552
+ if ep.get("max_tokens"):
553
+ print(ui.kv("max_tokens", f"{ep['max_tokens']:,}"))
554
+ if ep.get("extra_body"):
555
+ import json as _json
556
+
557
+ print(ui.kv("extra_body",
558
+ _json.dumps(ep["extra_body"], ensure_ascii=False)))
559
+ if ep.get("default_headers"):
560
+ print(ui.kv("default_headers",
561
+ ",".join(ep["default_headers"])))
562
+ if ep.get("pricing"):
563
+ print(ui.kv("pricing", "、".join(
564
+ f"{k}=${v}/1M" for k, v in ep["pricing"].items())))
517
565
  print(ui.kv("base_url", saved["base_url"]))
518
566
  print(ui.kv("api_key", masked))
519
567
  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()]
@@ -124,6 +124,10 @@ def sidebar_markup(state: TuiState) -> str:
124
124
  out.append(f"合计 {tokens:,}")
125
125
  out.append(f"本轮费用 ${turn_cost:.4f}")
126
126
  out.append(f"累计费用 ${cost:.4f}")
127
+ if state.max_cost is not None:
128
+ out.append(f"[dim]成本预算 ${cost:.4f} / ${state.max_cost:.2f}[/]")
129
+ if state.max_total_tokens is not None:
130
+ out.append(f"[dim]token 预算 {tokens:,} / {state.max_total_tokens:,}[/]")
127
131
  out.append(f"上下文 {context}")
128
132
  return "\n".join(out)
129
133
 
@@ -447,7 +451,7 @@ class LitheApp(App):
447
451
  title = ""
448
452
  if cid is not None:
449
453
  title = (self.wb.sessions.get(cid) or {}).get("title", "")
450
- return TuiState(
454
+ st = TuiState(
451
455
  self.cfg.model or "(scripted)",
452
456
  str(self.cfg.workspace_dir.resolve()),
453
457
  self.cfg.max_steps,
@@ -456,12 +460,18 @@ class LitheApp(App):
456
460
  session_id=cid,
457
461
  session_title=title,
458
462
  )
463
+ st.max_cost = self.cfg.max_cost
464
+ st.max_total_tokens = self.cfg.max_total_tokens
465
+ return st
459
466
 
460
467
  def _refresh_meta(self) -> None:
461
468
  st = self.state
462
469
  st.model = self.cfg.model or "(scripted)"
463
470
  st.profile = self.cfg.profile or ""
464
471
  st.reasoning_effort = self.cfg.reasoning_effort
472
+ st.max_steps = self.cfg.max_steps
473
+ st.max_cost = self.cfg.max_cost
474
+ st.max_total_tokens = self.cfg.max_total_tokens
465
475
  if self.wb.current is not None:
466
476
  st.session_id = self.wb.current["id"]
467
477
  st.session_title = self.wb.current.get("title") or ""
@@ -604,11 +614,18 @@ class LitheApp(App):
604
614
  if not line:
605
615
  return
606
616
  if self.state.running and not line.startswith("/"):
607
- # Plain text mid-turn is not silently discarded: it goes back
608
- # into the input box for resubmitting when the turn ends.
609
- # Slash commands still dispatch below — the workbench supports
610
- # them while a turn runs (/model, /resume, ...), matching the
611
- # plain REPL.
617
+ # Plain text mid-turn steers the running turn: queued into the
618
+ # kernel's inbox and injected as a user message at the next
619
+ # step boundary (user_injected event renders the line). When
620
+ # no turn is actually draining (one-shot mode), fall back to
621
+ # putting the text back in the input box. Slash commands still
622
+ # dispatch below — the workbench supports them mid-turn.
623
+ if self.wb.steer(line, self._current_cid()):
624
+ from .ui import truncate
625
+ self.state.say(
626
+ "dim", f"(已排队,将在当前步骤后注入:{truncate(line, 48)})")
627
+ self._sync_feed()
628
+ return
612
629
  self.query_one("#prompt", HistoryInput).value = line
613
630
  self.state.say("warn", "本轮还在进行中,未发送;文本已放回输入框,命令仍可用")
614
631
  self._sync_feed()
@@ -83,6 +83,9 @@ class TuiState:
83
83
  self.context_window = None
84
84
  self.context_percent = None
85
85
  self.reasoning_effort: str | None = None
86
+ # Run budgets (for the sidebar progress lines); None = no cap.
87
+ self.max_cost: float | None = None
88
+ self.max_total_tokens: int | None = None
86
89
  self.tools: list[dict] = []
87
90
  self.feed: list[tuple[str, str]] = []
88
91
  self.streaming = ""
@@ -208,6 +211,11 @@ class TuiState:
208
211
  self.say("err", str(ev.get("message") or "运行出错"))
209
212
  elif kind == "cancelled":
210
213
  self.say("warn", "(已取消)")
214
+ elif kind == "user_injected":
215
+ # Steering: a queued user text the kernel injected mid-run at a
216
+ # step boundary; render it as a user line so the transcript
217
+ # shows why the model's course changed.
218
+ self.say("user", str(ev.get("text") or ""))
211
219
  elif kind == "done":
212
220
  status = str(ev.get("status") or _STATUS_DONE)
213
221
  self.last_status = status
@@ -48,6 +48,10 @@ _SETTING_DEFS: list[tuple[str, str, str, str]] = [
48
48
  ("max-steps", "max_steps", "工具循环步数上限", "int"),
49
49
  ("timeout", "timeout", "单次模型调用超时(秒)", "float"),
50
50
  ("attempts", "attempts", "模型调用重试次数", "int"),
51
+ ("temperature", "temperature", "采样温度(off = 端点默认)", "float"),
52
+ ("max-output-tokens", "max_tokens", "单次调用输出上限(off = 端点默认)", "int"),
53
+ ("max-cost", "max_cost", "单轮成本预算 $(off = 不限)", "float"),
54
+ ("max-tokens", "max_total_tokens", "单轮 token 预算(off = 不限)", "int"),
51
55
  ("reasoning-effort", "reasoning_effort",
52
56
  "推理强度(off/minimal/low/medium/high,原样透传)", "enum"),
53
57
  ]
@@ -55,6 +59,9 @@ _SETTING_DEFS: list[tuple[str, str, str, str]] = [
55
59
  # or rendering knobs): flipping them invalidates the /tools cache.
56
60
  _TOOL_AFFECTING = {"shell", "code", "vision", "document", "download",
57
61
  "subagents"}
62
+ # Numeric knobs that accept "off"/"none" to clear back to None (unset),
63
+ # and (for temperature) a zero value.
64
+ _NULLABLE = {"temperature", "max-output-tokens", "max-cost", "max-tokens"}
58
65
  _TRUTHY = {"on", "true", "1", "开"}
59
66
  _FALSY = {"off", "false", "0", "关"}
60
67
  # Reasoning levels offered by /reasoning; any other typed token passes
@@ -352,7 +359,13 @@ class Workbench:
352
359
  async def _run_turn(self, conv: dict, task: str) -> None:
353
360
  cid = conv["id"]
354
361
  stop = asyncio.Event()
355
- handle = {"task": asyncio.current_task(), "stop": stop}
362
+ # Steering inbox: texts submitted while this turn runs (see steer);
363
+ # the kernel drains it at step boundaries and injects them as user
364
+ # messages. The wrap-up step skips the drain — leftovers are
365
+ # reported below instead of vanishing.
366
+ inbox: asyncio.Queue = asyncio.Queue()
367
+ handle = {"task": asyncio.current_task(), "stop": stop,
368
+ "inbox": inbox}
356
369
  existing = self.turns.get(cid)
357
370
  if existing is not None and existing.get("task") not in (None, handle["task"]):
358
371
  self._emit(cid, {"type": "error",
@@ -377,6 +390,7 @@ class Workbench:
377
390
  conversation_id=cid,
378
391
  on_event=lambda ev: self._emit(cid, ev),
379
392
  stop=stop,
393
+ inbox=inbox,
380
394
  )
381
395
  status = done.get("status")
382
396
  if self.current and self.current["id"] == cid:
@@ -390,6 +404,18 @@ class Workbench:
390
404
  status = "failed"
391
405
  finally:
392
406
  self.turns.pop(cid, None)
407
+ leftover = 0
408
+ while not inbox.empty():
409
+ try:
410
+ inbox.get_nowait()
411
+ leftover += 1
412
+ except asyncio.QueueEmpty:
413
+ break
414
+ if leftover:
415
+ self._emit(cid, {
416
+ "type": "command_output", "style": "warn",
417
+ "text": f"({leftover} 条运行中输入未能在本轮结束前注入,已丢弃)",
418
+ })
393
419
  self._emit(cid, {"type": "session_idle", "conv_id": cid,
394
420
  "run_id": rid, "status": status})
395
421
 
@@ -435,6 +461,27 @@ class Workbench:
435
461
  return True
436
462
  return False
437
463
 
464
+ def steer(self, text: str, conv_id: int | None = None) -> bool:
465
+ """Queue a user text into the running turn's steering inbox.
466
+
467
+ The kernel drains the inbox at step boundaries and injects each
468
+ text as a user message (announced via ``user_injected`` events),
469
+ so the model incorporates it on its next call. False when no turn
470
+ is running for the session (the caller falls back to normal
471
+ submit behavior).
472
+ """
473
+ if not text.strip():
474
+ return False
475
+ cid = self._cid(conv_id)
476
+ if cid is None:
477
+ return False
478
+ handle = self.turns.get(cid)
479
+ inbox = handle.get("inbox") if handle else None
480
+ if inbox is None:
481
+ return False
482
+ inbox.put_nowait(text)
483
+ return True
484
+
438
485
  # -- undo -------------------------------------------------------------------
439
486
 
440
487
  async def _undo(self, run_id: str | None) -> None:
@@ -517,17 +564,27 @@ class Workbench:
517
564
  # endpoint's call (400 diagnostics catch mistakes).
518
565
  new = None if token.lower() == "off" else token
519
566
  else:
567
+ token = value.strip().lower()
520
568
  if not value.strip():
521
569
  result.say("err", f"用法:/set {ukey} 值(当前 {current})")
522
570
  return result
523
- try:
524
- new = int(value.strip()) if kind == "int" else float(value.strip())
525
- except ValueError:
526
- result.say("err", f"{ukey} 需要一个{'整数' if kind == 'int' else '数值'}")
527
- return result
528
- if kind == "int" and new < 1 or kind == "float" and new <= 0:
529
- result.say("err", f"{ukey} 必须为正数")
530
- return result
571
+ if token in ("off", "none") and ukey in _NULLABLE:
572
+ new = None # clear back to "unset / endpoint default"
573
+ else:
574
+ try:
575
+ new = int(value.strip()) if kind == "int" \
576
+ else float(value.strip())
577
+ except ValueError:
578
+ result.say(
579
+ "err",
580
+ f"{ukey} 需要一个{'整数' if kind == 'int' else '数值'}"
581
+ "(off 清除)")
582
+ return result
583
+ # positivity, except temperature where 0 is a valid setting
584
+ if ukey != "temperature" and (
585
+ kind == "int" and new < 1 or kind == "float" and new <= 0):
586
+ result.say("err", f"{ukey} 必须为正数")
587
+ return result
531
588
  if new == current:
532
589
  result.say("dim", f"{label}:已是 {new if new is not None else 'off'}")
533
590
  return result
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.8.9
3
+ Version: 0.9.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.19
42
+ Requires-Dist: lithe>=0.9.21
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.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
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. 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.
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
 
@@ -23,6 +23,7 @@ lithe_cli.egg-info/entry_points.txt
23
23
  lithe_cli.egg-info/requires.txt
24
24
  lithe_cli.egg-info/top_level.txt
25
25
  tests/test_cli.py
26
+ tests/test_cli_budget_steer.py
26
27
  tests/test_cli_sessions.py
27
28
  tests/test_cli_subagents.py
28
29
  tests/test_profiles.py
@@ -1,4 +1,4 @@
1
- lithe>=0.9.19
1
+ lithe>=0.9.21
2
2
  prompt-toolkit>=3.0.38
3
3
  textual>=1.0
4
4
 
@@ -9,7 +9,7 @@ description = "Command-line interface for the lithe agent kernel: chat, one-shot
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
11
11
  requires-python = ">=3.10"
12
- dependencies = ["lithe>=0.9.19", "prompt-toolkit>=3.0.38", "textual>=1.0"]
12
+ dependencies = ["lithe>=0.9.21", "prompt-toolkit>=3.0.38", "textual>=1.0"]
13
13
  keywords = ["agent", "llm", "react", "cli", "tool-calling"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
@@ -0,0 +1,272 @@
1
+ """Run budgets (--max-cost/--max-tokens + profile pricing) and steering.
2
+
3
+ The kernel's AgentHost budgets end a run with status="budget_exceeded";
4
+ the CLI wires them as flags + /set knobs, with profile-level pricing making
5
+ max_cost real on endpoints that report no usage cost. Steering queues
6
+ mid-turn user texts into the kernel inbox, injected at step boundaries.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+
13
+ import pytest
14
+
15
+ from lithe_cli.agent import build_host, build_llm, build_registry, execute
16
+ from lithe_cli.config import load_config
17
+ from lithe_cli.ttui import sidebar_markup
18
+ from lithe_cli.tui import TuiState
19
+ from lithe_cli.workbench import Workbench
20
+
21
+ from conftest import make_config
22
+
23
+
24
+ def _tc_call(name, args, cid="c1"):
25
+ return {"id": cid, "type": "function",
26
+ "function": {"name": name, "arguments": json.dumps(args)}}
27
+
28
+
29
+ WRITE_THEN_ANSWER = [
30
+ {"tool_calls": [_tc_call("write_file", {"path": "a.txt", "content": "hi"})]},
31
+ {"content": "已写入。"},
32
+ ]
33
+
34
+
35
+ def test_run_token_budget_ends_with_budget_exceeded(tmp_path):
36
+ cfg = make_config(tmp_path, WRITE_THEN_ANSWER)
37
+ cfg.max_total_tokens = 100 # scripted usage reports 120 per call
38
+ rid, done, host = asyncio.run(execute(cfg, "写 a.txt"))
39
+ assert rid
40
+ assert done["status"] == "budget_exceeded"
41
+ assert host.max_total_tokens == 100
42
+
43
+
44
+ def test_run_cost_budget_uses_profile_pricing(tmp_path):
45
+ # scripted usage carries no cost field: without a price table the
46
+ # budget can never trigger (cost stays 0)
47
+ cfg = make_config(tmp_path, WRITE_THEN_ANSWER)
48
+ cfg.pricing = {"prompt": 3000.0, "completion": 15000.0} # $/1M
49
+ cfg.max_cost = 0.5
50
+ rid, done, _ = asyncio.run(execute(cfg, "写 a.txt"))
51
+ assert rid
52
+ assert done["status"] == "budget_exceeded"
53
+ # 100 prompt × $3k/1M + 20 completion × $15k/1M = 0.30 + 0.30
54
+ assert done["cost"] == pytest.approx(0.6, abs=1e-6)
55
+
56
+
57
+ def test_budgets_and_pricing_round_trip_from_profile(tmp_path, monkeypatch):
58
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path))
59
+ (tmp_path / "config.json").write_text(
60
+ '{"version": 2, "active": "p", "profiles": {"p": {'
61
+ '"api_key": "sk", "base_url": "https://x/api", "model": "m", '
62
+ '"pricing": {"prompt": 3, "completion": 15}, '
63
+ '"temperature": 0.4, "max_tokens": 2048, '
64
+ '"extra_body": {"enable_thinking": true}, '
65
+ '"default_headers": {"X-Title": "lithe"}}}}',
66
+ encoding="utf-8")
67
+
68
+ class Args:
69
+ api_key = base_url = model = profile = store = workspace = user = None
70
+ skills = mcp = None
71
+ download = code = shell = vision = color = no_color = verbose = False
72
+ subagents = document = False
73
+ temperature = max_tokens = max_cost = max_total_tokens = None
74
+
75
+ cfg = load_config(Args())
76
+ assert cfg.pricing == {"prompt": 3, "completion": 15}
77
+ assert cfg.temperature == 0.4 and cfg.max_tokens == 2048
78
+ assert cfg.extra_body == {"enable_thinking": True}
79
+ assert cfg.default_headers == {"X-Title": "lithe"}
80
+ llm = build_llm(cfg)
81
+ assert llm.pricing == {"prompt": 3, "completion": 15}
82
+ assert llm.temperature == 0.4 and llm.max_tokens == 2048
83
+ assert llm.extra_body == {"enable_thinking": True}
84
+ assert llm.default_headers == {"X-Title": "lithe"}
85
+ # flag beats profile for the sampling knobs (0.0 is a real value)
86
+ Args.temperature = 0.0
87
+ Args.max_tokens = 512
88
+ cfg2 = load_config(Args())
89
+ assert cfg2.temperature == 0.0 and cfg2.max_tokens == 512
90
+
91
+
92
+ def test_preset_extra_body_merges_under_profile_fields(tmp_path):
93
+ cfg = make_config(tmp_path, [])
94
+ cfg.provider = "openrouter"
95
+ cfg.extra_body = {"route": "fallback"}
96
+ llm = build_llm(cfg)
97
+ # explicit key wins; preset siblings survive
98
+ assert llm.extra_body.get("route") == "fallback"
99
+
100
+
101
+ def test_set_budget_and_sampling_knobs(tmp_path):
102
+ cfg = make_config(tmp_path, [])
103
+ wb = Workbench(cfg)
104
+ r = wb.dispatch("/set max-cost 1.5")
105
+ assert cfg.max_cost == 1.5
106
+ assert any("1.5" in t for _, t in r.messages)
107
+ assert wb.dispatch("/set max-cost off").messages
108
+ assert cfg.max_cost is None
109
+ wb.dispatch("/set max-tokens 5000")
110
+ assert cfg.max_total_tokens == 5000
111
+ wb.dispatch("/set max-tokens off")
112
+ assert cfg.max_total_tokens is None
113
+ # temperature 0 is a valid setting, not rejected as non-positive
114
+ wb.dispatch("/set temperature 0")
115
+ assert cfg.temperature == 0.0
116
+ wb.dispatch("/set temperature off")
117
+ assert cfg.temperature is None
118
+ wb.dispatch("/set max-output-tokens 1024")
119
+ assert cfg.max_tokens == 1024
120
+ # budgets reach the host on the next build
121
+ cfg.max_cost, cfg.max_total_tokens = 2.0, 9000
122
+ host = build_host(cfg, build_registry(cfg))
123
+ assert host.max_cost == 2.0 and host.max_total_tokens == 9000
124
+
125
+
126
+ def test_sidebar_shows_budget_progress_lines():
127
+ state = TuiState("m", "/ws", 35)
128
+ state.on_event({"type": "run_start"})
129
+ state.on_event({
130
+ "type": "usage", "prompt_tokens": 100, "completion_tokens": 20,
131
+ "cached_tokens": 0, "total_tokens": 120, "cost": 0.01,
132
+ })
133
+ side = sidebar_markup(state)
134
+ assert "预算" not in side # no caps set → no lines
135
+ state.max_cost = 1.0
136
+ state.max_total_tokens = 10_000
137
+ side = sidebar_markup(state)
138
+ assert "成本预算 $0.0100 / $1.00" in side
139
+ assert "token 预算 120 / 10,000" in side
140
+
141
+
142
+ def test_budget_status_maps_to_chinese_label():
143
+ state = TuiState("m", "/ws", 35)
144
+ state.on_event({"type": "done", "status": "budget_exceeded", "steps": 1})
145
+ assert state.status == "预算超限"
146
+
147
+
148
+ # --------------------------------------------------------------------------- #
149
+ # steering
150
+ # --------------------------------------------------------------------------- #
151
+
152
+ class _GateTransport:
153
+ """Holds the first model call open until the gate is set, so the test
154
+ can steer mid-run deterministically; captures every call's kwargs."""
155
+
156
+ def __init__(self):
157
+ self.gate = asyncio.Event()
158
+ self.stage = 0
159
+ self.calls: list[dict] = []
160
+
161
+ async def complete(self, client, **kw):
162
+ self.calls.append(kw)
163
+ if self.stage == 0:
164
+ self.stage = 1
165
+ await self.gate.wait()
166
+ return {"content": "",
167
+ "tool_calls": [_tc_call("read_file", {"path": "a.txt"})],
168
+ "usage": {}}
169
+ return {"content": "完成", "tool_calls": [], "usage": {}}
170
+
171
+
172
+ def test_steering_injects_at_step_boundary(tmp_path):
173
+ cfg = make_config(tmp_path, [])
174
+ tr = _GateTransport()
175
+ cfg.transport = tr
176
+ cfg.workspace_dir.mkdir(parents=True, exist_ok=True)
177
+ (cfg.workspace_dir / "a.txt").write_text("hi", encoding="utf-8")
178
+
179
+ async def scenario():
180
+ inbox: asyncio.Queue = asyncio.Queue()
181
+ events: list[dict] = []
182
+ task = asyncio.get_running_loop().create_task(execute(
183
+ cfg, "读一下 a.txt", on_event=events.append, inbox=inbox))
184
+ for _ in range(200):
185
+ await asyncio.sleep(0.01)
186
+ if tr.calls:
187
+ break
188
+ assert tr.calls, "first model call never started"
189
+ inbox.put_nowait("顺便也看看 b.txt 存不存在")
190
+ tr.gate.set()
191
+ rid, done, _ = await task
192
+ assert done["status"] == "done"
193
+ # injected text reaches the second model call's messages
194
+ second = tr.calls[1]["messages"]
195
+ assert any(m.get("role") == "user"
196
+ and "b.txt" in (m.get("content") or "")
197
+ for m in second), second
198
+ # the injection was announced as an event and persisted as a row
199
+ assert any(ev.get("type") == "user_injected"
200
+ and "b.txt" in ev.get("text", "") for ev in events)
201
+ rows = _messages_of(rid, cfg)
202
+ assert any(r.get("role") == "user" and "b.txt" in (r.get("content") or "")
203
+ for r in rows)
204
+
205
+ asyncio.run(scenario())
206
+
207
+
208
+ def _messages_of(rid, cfg):
209
+ from lithe.bundles import JsonlRunStore
210
+
211
+ return JsonlRunStore(cfg.store_dir).messages_for_run(rid, cfg.user_id)
212
+
213
+
214
+ def test_workbench_steer_routes_and_reports_leftovers(tmp_path):
215
+ cfg = make_config(tmp_path, [])
216
+ tr = _GateTransport()
217
+ cfg.transport = tr
218
+ cfg.workspace_dir.mkdir(parents=True, exist_ok=True)
219
+ (cfg.workspace_dir / "a.txt").write_text("hi", encoding="utf-8")
220
+ wb = Workbench(cfg)
221
+ wb.open()
222
+
223
+ async def scenario():
224
+ got: list[dict] = []
225
+ wb.subscribe(lambda cid, ev: got.append(ev))
226
+ task = asyncio.get_running_loop().create_task(wb.run_turn("读 a.txt"))
227
+ for _ in range(200):
228
+ await asyncio.sleep(0.01)
229
+ if tr.calls:
230
+ break
231
+ assert wb.steer("改看 c.txt") is True
232
+ assert wb.steer(" ") is False # blank never queues
233
+ tr.gate.set()
234
+ await task
235
+ # injected (announced) + the model saw it on the next call
236
+ assert any(ev.get("type") == "user_injected" for ev in got)
237
+ assert any("c.txt" in (m.get("content") or "")
238
+ for m in tr.calls[1]["messages"])
239
+ # turn over: steer has nothing to route to
240
+ assert wb.steer("x") is False
241
+
242
+ asyncio.run(scenario())
243
+
244
+
245
+ def test_workbench_reports_uninjectable_leftovers(tmp_path):
246
+ cfg = make_config(tmp_path, [])
247
+ release = asyncio.Event()
248
+
249
+ class _Hang:
250
+ async def complete(self, client, **kw):
251
+ await release.wait()
252
+ return {"content": "ok", "tool_calls": [], "usage": {}}
253
+
254
+ cfg.transport = _Hang()
255
+ wb = Workbench(cfg)
256
+ wb.open()
257
+
258
+ async def scenario():
259
+ got: list[dict] = []
260
+ wb.subscribe(lambda cid, ev: got.append(ev))
261
+ task = asyncio.get_running_loop().create_task(wb.run_turn("任务"))
262
+ for _ in range(200):
263
+ await asyncio.sleep(0.01)
264
+ if wb.busy_ids():
265
+ break
266
+ assert wb.steer("补充") is True
267
+ release.set() # the hung call returns; run ends with no step 2
268
+ await task
269
+ assert any("未能在本轮结束前注入" in (ev.get("text") or "")
270
+ for ev in got)
271
+
272
+ asyncio.run(scenario())
@@ -248,9 +248,10 @@ def test_run_mode_ctrl_c_cancels_one_shot_turn(tmp_path):
248
248
  asyncio.run(scenario())
249
249
 
250
250
 
251
- def test_mid_turn_text_restored_and_commands_still_work(tmp_path):
252
- """Plain text typed mid-turn is not silently dropped (it returns to the
253
- input box); slash commands dispatch while a turn runs, as in the REPL."""
251
+ def test_mid_turn_text_steers_and_commands_still_work(tmp_path):
252
+ """Plain text typed mid-turn steers the running turn (queued into the
253
+ kernel inbox); slash commands dispatch while a turn runs. When the
254
+ model call never yields a step boundary, leftovers are reported."""
254
255
  async def scenario():
255
256
  release = asyncio.Event()
256
257
 
@@ -269,24 +270,27 @@ def test_mid_turn_text_restored_and_commands_still_work(tmp_path):
269
270
  await pilot.press("enter")
270
271
  await pilot.pause(0.2)
271
272
  assert app.state.running
272
- # plain text mid-turn: warned and restored, not sent
273
+ # plain text mid-turn: queued for injection, not restored
273
274
  inp.value = "补充说明"
274
275
  await pilot.press("enter")
275
276
  await pilot.pause(0.1)
276
- assert "未发送" in _conv_text(app)
277
- assert app.query_one("#prompt").value == "补充说明"
277
+ assert "已排队" in _conv_text(app)
278
+ assert app.query_one("#prompt").value == ""
278
279
  # slash command mid-turn: dispatches normally
279
280
  inp.value = "/help"
280
281
  await pilot.press("enter")
281
282
  await pilot.pause(0.1)
282
283
  text = _conv_text(app)
283
284
  assert "命令" in text or "/model" in text
285
+ # the hung call never reaches a step boundary: the queued text
286
+ # cannot be injected and is honestly reported as dropped
284
287
  release.set()
285
288
  for _ in range(100):
286
289
  await pilot.pause(0.05)
287
290
  if not app.state.running:
288
291
  break
289
292
  assert not app.state.running
293
+ assert "未能在本轮结束前注入" in _conv_text(app)
290
294
 
291
295
  asyncio.run(scenario())
292
296
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes