lithe-cli 0.8.8__tar.gz → 0.8.9__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 (33) hide show
  1. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/PKG-INFO +4 -2
  2. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/README.md +3 -1
  3. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/agent.py +90 -1
  5. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/config.py +5 -0
  6. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/main.py +11 -0
  7. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/workbench.py +7 -3
  8. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/PKG-INFO +4 -2
  9. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/SOURCES.txt +1 -0
  10. lithe_cli-0.8.9/tests/test_cli_subagents.py +118 -0
  11. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/LICENSE +0 -0
  12. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/__main__.py +0 -0
  13. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/commands.py +0 -0
  14. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/profiles.py +0 -0
  15. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/prompts.py +0 -0
  16. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/py.typed +0 -0
  17. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/sessions.py +0 -0
  18. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/setup.py +0 -0
  19. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/ttui.py +0 -0
  20. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/tui.py +0 -0
  21. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli/ui.py +0 -0
  22. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/dependency_links.txt +0 -0
  23. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/entry_points.txt +0 -0
  24. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/requires.txt +0 -0
  25. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/lithe_cli.egg-info/top_level.txt +0 -0
  26. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/pyproject.toml +0 -0
  27. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/setup.cfg +0 -0
  28. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/tests/test_cli.py +0 -0
  29. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/tests/test_cli_sessions.py +0 -0
  30. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/tests/test_profiles.py +0 -0
  31. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/tests/test_ttui.py +0 -0
  32. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/tests/test_tui_v2.py +0 -0
  33. {lithe_cli-0.8.8 → lithe_cli-0.8.9}/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.8
3
+ Version: 0.8.9
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
 
@@ -160,7 +160,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
160
160
  工具/待办、用量:
161
161
 
162
162
  ```text
163
- lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
163
+ lithe 0.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
164
164
  ╭──────────────────────────────────────╮╭──────────────────────────╮
165
165
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
166
166
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -249,11 +249,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
249
249
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
250
250
  | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
251
251
  | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
252
+ | `--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 |
252
253
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
253
254
 
254
255
  ```bash
255
256
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
256
257
  $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
258
+ $ lithe run --subagents "先让 researcher 摸清 src 结构,再让 coder 分头改"
257
259
  $ lithe run --shell "检查当前目录的项目状态"
258
260
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
259
261
  ```
@@ -111,7 +111,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
111
111
  工具/待办、用量:
112
112
 
113
113
  ```text
114
- lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
114
+ lithe 0.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
115
115
  ╭──────────────────────────────────────╮╭──────────────────────────╮
116
116
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
117
117
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -200,11 +200,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
200
200
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
201
201
  | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
202
202
  | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
203
+ | `--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 |
203
204
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
204
205
 
205
206
  ```bash
206
207
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
207
208
  $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
209
+ $ lithe run --subagents "先让 researcher 摸清 src 结构,再让 coder 分头改"
208
210
  $ lithe run --shell "检查当前目录的项目状态"
209
211
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
210
212
  ```
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.8.8"
3
+ __version__ = "0.8.9"
@@ -12,7 +12,8 @@ Everything here maps lithe's host contract onto CLI defaults:
12
12
  library), ``--vision`` (image probe/analysis), ``--document``
13
13
  (PDF/OOXML probe/analysis — dialect from ``--document-format`` > profile
14
14
  ``document_format`` > provider preset), ``--download`` (SSRF-guarded
15
- network fetch) and ``--mcp`` (external MCP servers);
15
+ network fetch), ``--mcp`` (external MCP servers) and ``--subagents``
16
+ (kernel delegation on the CLI's default roster);
16
17
  - undo — the bundled tools register reverters, so ``lithe undo`` works with
17
18
  zero configuration.
18
19
  """
@@ -87,6 +88,10 @@ def build_system_prompt(cfg: Config) -> str:
87
88
  if cfg.document:
88
89
  extras.append("可以用 analyze_document 直接阅读 PDF/DOCX/XLSX/PPTX 文档并回答关于它的具体问题;"
89
90
  "确定元信息(格式/页数)先用 document_info。")
91
+ if cfg.subagents:
92
+ extras.append("可以用 delegate 把独立子任务委派给子代理(可用名单见工具说明:检索/编码/操作),"
93
+ "互不依赖的子任务用 delegate_parallel 并行委派;"
94
+ "子代理与本对话共享预算,汇报时合并它们的结果。")
90
95
  if not extras:
91
96
  return SYSTEM_PROMPT_BASE
92
97
  return SYSTEM_PROMPT_BASE + "".join(extras)
@@ -187,6 +192,88 @@ def build_host(cfg: Config, reg: ToolRegistry) -> AgentHost:
187
192
  )
188
193
 
189
194
 
195
+ # -- subagent delegation (--subagents) ----------------------------------------
196
+ #
197
+ # The kernel's delegation bundle (lithe.bundles.subagents) is host data: a
198
+ # roster of SubagentSpecs + an engine over the host. The CLI's default roster
199
+ # filters each spec's tool list against what is actually registered, so a
200
+ # capability flag (--vision, --code, …) automatically shapes the workers.
201
+
202
+ _RESEARCHER_PROMPT = (
203
+ "你是只读检索子代理。用文件/文档/图像工具查找、阅读并汇总信息,绝不修改、新建或删除任何文件。"
204
+ "输出简明的发现清单,标注出处路径;找不到就如实说找不到。"
205
+ )
206
+ _CODER_PROMPT = (
207
+ "你是编码子代理。先用只读工具了解现状,再做最小必要的修改"
208
+ "(优先 edit_file / apply_patch 局部修改,仅新建文件或确需重写时用 write_file),"
209
+ "可用 run_code 验证;完成后简述改了什么、为什么。"
210
+ )
211
+ _OPERATOR_PROMPT = (
212
+ "你是操作子代理。用 run_command 执行命令、download_file 下载文件来完成指定操作。"
213
+ "命令以当前用户权限运行且副作用不可撤销,执行前先确认必要性;输出关键结果与退出码。"
214
+ )
215
+
216
+
217
+ def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry):
218
+ """Register delegate/delegate_parallel over the CLI's default roster.
219
+
220
+ Must run after ``build_host`` (the engine shares the host's registry,
221
+ store and LLM config — children inherit the endpoint, retry policy and
222
+ budgets; parallel siblings share one live cost ceiling, kernel ≥0.9.20).
223
+ Returns the engine (roster inspection for hosts and tests).
224
+ """
225
+ from lithe.bundles.subagents import (
226
+ SubagentEngine,
227
+ SubagentRoster,
228
+ SubagentSpec,
229
+ register_delegate_tools,
230
+ )
231
+
232
+ available = set(reg.names())
233
+
234
+ def pick(names: list[str]) -> list[str]:
235
+ return [n for n in names if n in available]
236
+
237
+ specs = [
238
+ SubagentSpec(
239
+ "researcher", "检索员",
240
+ "只读检索:在工作区查找、阅读、汇总信息与文档(不修改文件)",
241
+ pick(["read_file", "list_files", "search_files", "glob_files",
242
+ "image_info", "analyze_image",
243
+ "document_info", "analyze_document"]),
244
+ _RESEARCHER_PROMPT, read_only=True),
245
+ SubagentSpec(
246
+ "coder", "编码员",
247
+ "读写代码:定位、修改、验证工作区内的代码",
248
+ pick(["read_file", "write_file", "edit_file", "apply_patch",
249
+ "list_files", "search_files", "glob_files",
250
+ "run_code", "run_file"]),
251
+ _CODER_PROMPT),
252
+ ]
253
+ op_core = pick(["run_command", "download_file"])
254
+ if op_core:
255
+ specs.append(SubagentSpec(
256
+ "operator", "操作员",
257
+ "执行主机命令与网络下载等操作",
258
+ op_core + pick(["read_file", "list_files"]),
259
+ _OPERATOR_PROMPT))
260
+ # A spec whose tool list filtered to nothing can do nothing meaningful;
261
+ # researcher/coder always keep the ever-present file tools.
262
+ specs = [s for s in specs if s.tools]
263
+ engine = SubagentEngine(host, SubagentRoster(specs))
264
+ register_delegate_tools(reg, engine, parallel=True)
265
+ return engine
266
+
267
+
268
+ def tool_names(cfg: Config) -> list[str]:
269
+ """Sorted tool names for /tools: the registry plus the delegation pair
270
+ when enabled (registered later against the host, same names)."""
271
+ names = sorted(build_registry(cfg).names())
272
+ if cfg.subagents:
273
+ names = sorted(names + ["delegate", "delegate_parallel"])
274
+ return names
275
+
276
+
190
277
  def render_event(
191
278
  ev: dict,
192
279
  verbose: bool = False,
@@ -259,6 +346,8 @@ async def execute(
259
346
  """
260
347
  reg = build_registry(cfg)
261
348
  host = build_host(cfg, reg)
349
+ if cfg.subagents:
350
+ register_subagents(cfg, host, reg)
262
351
  rid = run_id or uuid.uuid4().hex[:12]
263
352
  extra = {"conversation_id": conversation_id} if conversation_id is not None else {}
264
353
  ctx = AgentContext(run_id=rid, user_id=cfg.user_id, extra=extra)
@@ -67,6 +67,10 @@ class Config:
67
67
  # in-session profile switches re-resolve it). None = not explicit.
68
68
  document_format: str | None = None
69
69
  document: bool = False
70
+ # Subagent delegation (kernel bundles.subagents): grants delegate /
71
+ # delegate_parallel on the CLI's default roster. Off by default — each
72
+ # delegation is a full agent run, so token spend multiplies.
73
+ subagents: bool = False
70
74
  store_dir: Path = field(default_factory=lambda: default_store_dir())
71
75
  workspace_dir: Path = field(default_factory=lambda: Path.cwd())
72
76
  user_id: str = DEFAULT_USER
@@ -295,6 +299,7 @@ def load_config(args: Any) -> Config:
295
299
  if isinstance(document_format, str)
296
300
  and document_format.strip() else None),
297
301
  document=g("document", False),
302
+ subagents=g("subagents", False),
298
303
  reasoning_effort=(effort.strip() if isinstance(effort, str) and effort.strip()
299
304
  else None),
300
305
  store_dir=store_dir,
@@ -104,6 +104,13 @@ def build_parser() -> argparse.ArgumentParser:
104
104
  help="grant document_info/analyze_document "
105
105
  "(PDF/OOXML reading on the main endpoint)",
106
106
  )
107
+ sp.add_argument(
108
+ "--subagents",
109
+ action="store_true",
110
+ help="grant delegate/delegate_parallel (subagent delegation on "
111
+ "the default roster: researcher/coder/operator; multiplies "
112
+ "token spend)",
113
+ )
107
114
  sp.add_argument(
108
115
  "--document-format",
109
116
  metavar="DIALECT",
@@ -366,6 +373,7 @@ def _cmd_doctor() -> int:
366
373
  api_key = base_url = model = profile = store = workspace = user = None
367
374
  skills = mcp = None
368
375
  download = code = shell = vision = color = no_color = verbose = False
376
+ subagents = document = False
369
377
 
370
378
  cfg = load_config(_Args())
371
379
  print(ui.s(f"lithe-cli {__version__}(lithe {lithe_version})", CYAN, BOLD))
@@ -442,6 +450,9 @@ def _cmd_doctor() -> int:
442
450
  print(ui.kv("mcp", f"{len(cfg.mcp_servers)} 个服务器:{names}"))
443
451
  else:
444
452
  print(ui.kv("mcp", "未配置(--mcp 或环境变量 LITHE_MCP)"))
453
+ delegation = "已启用(delegate 可委派子代理,token 花费会放大)" \
454
+ if cfg.subagents else "未启用(--subagents 显式授权)"
455
+ print(ui.kv("subagents", delegation))
445
456
  print(ui.kv("color", "on" if ui.color else "off"))
446
457
  return 0
447
458
 
@@ -25,7 +25,7 @@ from collections.abc import Callable
25
25
  from lithe import replay_messages
26
26
  from lithe.bundles import JsonlRunStore
27
27
 
28
- from .agent import build_registry, execute, undo
28
+ from .agent import execute, tool_names, undo
29
29
  from .commands import ActionResult, help_text
30
30
  from .config import Config
31
31
  from .profiles import ProfileStore, fetch_models
@@ -42,6 +42,7 @@ _SETTING_DEFS: list[tuple[str, str, str, str]] = [
42
42
  ("vision", "vision", "image_info / analyze_image(图像理解)", "bool"),
43
43
  ("document", "document", "document_info / analyze_document(文档理解)", "bool"),
44
44
  ("download", "download", "download_file(网络下载)", "bool"),
45
+ ("subagents", "subagents", "delegate / delegate_parallel(子代理委派)", "bool"),
45
46
  ("stream", "stream", "流式输出 token", "bool"),
46
47
  ("verbose", "verbose", "显示 usage / reasoning 事件", "bool"),
47
48
  ("max-steps", "max_steps", "工具循环步数上限", "int"),
@@ -52,7 +53,8 @@ _SETTING_DEFS: list[tuple[str, str, str, str]] = [
52
53
  ]
53
54
  # Settings whose change alters the next turn's tool registry (vs. sampling
54
55
  # or rendering knobs): flipping them invalidates the /tools cache.
55
- _TOOL_AFFECTING = {"shell", "code", "vision", "document", "download"}
56
+ _TOOL_AFFECTING = {"shell", "code", "vision", "document", "download",
57
+ "subagents"}
56
58
  _TRUTHY = {"on", "true", "1", "开"}
57
59
  _FALSY = {"off", "false", "0", "关"}
58
60
  # Reasoning levels offered by /reasoning; any other typed token passes
@@ -542,6 +544,8 @@ class Workbench:
542
544
  result.say("warn", "run_command 以当前用户权限执行、非沙箱、结果不可撤销")
543
545
  elif ukey == "code" and new is True:
544
546
  result.say("dim", "(无 bubblewrap 的环境回退为非沙箱直通执行)")
547
+ elif ukey == "subagents" and new is True:
548
+ result.say("warn", "委派子代理会成倍放大 token 花费;并行子任务共享同一预算上限")
545
549
  return result
546
550
 
547
551
  # -- dispatch -----------------------------------------------------------------
@@ -572,7 +576,7 @@ class Workbench:
572
576
  return result
573
577
  if cmd == "tools":
574
578
  if self._tool_names is None:
575
- self._tool_names = sorted(build_registry(self.cfg).names())
579
+ self._tool_names = tool_names(self.cfg)
576
580
  result.say("dim", "已注册工具:" + "、".join(self._tool_names))
577
581
  return result
578
582
  if cmd == "new":
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.8.8
3
+ Version: 0.8.9
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
 
@@ -160,7 +160,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
160
160
  工具/待办、用量:
161
161
 
162
162
  ```text
163
- lithe 0.8.8 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
163
+ lithe 0.8.9 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
164
164
  ╭──────────────────────────────────────╮╭──────────────────────────╮
165
165
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
166
166
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -249,11 +249,13 @@ The kernel ships these as bundles; the CLI grants them per flag:
249
249
  | `--vision` | `image_info` / `analyze_image` | image probe is stdlib-only; analysis routes one vision call to the main endpoint |
250
250
  | `--document` | `document_info` / `analyze_document` | PDF/DOCX/XLSX/PPTX reading on the main endpoint; `/set document` toggles in-session |
251
251
  | `--document-format` | (dialect for `analyze_document`) | `inline-file` (OpenRouter family) / `files-api` (strict OpenAI upload) / `none` (probe only); default: profile field `document_format`, else provider preset |
252
+ | `--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 |
252
253
  | `--mcp SPEC` | whatever the servers expose | JSON array/object or `@file` (env `LITHE_MCP`); stdio and streamable-http; failed servers degrade gracefully |
253
254
 
254
255
  ```bash
255
256
  $ lithe run --code "用 run_code 验证 results.csv 的行数"
256
257
  $ lithe run --document "总结 report.pdf 的结论,存到 NOTES.md"
258
+ $ lithe run --subagents "先让 researcher 摸清 src 结构,再让 coder 分头改"
257
259
  $ lithe run --shell "检查当前目录的项目状态"
258
260
  $ lithe chat --skills ~/my-skills --mcp @~/mcp.json
259
261
  ```
@@ -24,6 +24,7 @@ lithe_cli.egg-info/requires.txt
24
24
  lithe_cli.egg-info/top_level.txt
25
25
  tests/test_cli.py
26
26
  tests/test_cli_sessions.py
27
+ tests/test_cli_subagents.py
27
28
  tests/test_profiles.py
28
29
  tests/test_ttui.py
29
30
  tests/test_tui_v2.py
@@ -0,0 +1,118 @@
1
+ """CLI wiring for the kernel's subagent delegation (--subagents).
2
+
3
+ The kernel bundle (lithe.bundles.subagents) is host data; the CLI grants it
4
+ via --subagents / /set subagents with a default roster (researcher / coder /
5
+ operator) whose tool lists filter against the actually-registered tools, so
6
+ capability flags shape the workers automatically.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+
13
+ from lithe_cli.agent import (
14
+ build_host,
15
+ build_registry,
16
+ build_system_prompt,
17
+ register_subagents,
18
+ tool_names,
19
+ )
20
+ from lithe_cli.config import Config
21
+ from lithe_cli.workbench import Workbench
22
+
23
+ from conftest import make_config
24
+
25
+
26
+ def _tc_call(name, args, cid="c1"):
27
+ return {"id": cid, "type": "function",
28
+ "function": {"name": name, "arguments": json.dumps(args)}}
29
+
30
+
31
+ DELEGATE_SCRIPT = [
32
+ # parent step 1: delegate a read-only lookup to the researcher
33
+ {"tool_calls": [_tc_call(
34
+ "delegate_parallel",
35
+ {"tasks": [{"agent": "researcher", "task": "找一下 a.md 里写了什么"}]})]},
36
+ # the child's own model call (shares the scripted transport)
37
+ {"content": "a.md 的内容是待办清单。"},
38
+ # parent step 2: final answer incorporating the child's report
39
+ {"content": "子代理已确认:a.md 是待办清单。"},
40
+ ]
41
+
42
+
43
+ def test_delegation_disabled_by_default(tmp_path):
44
+ cfg = make_config(tmp_path, DELEGATE_SCRIPT)
45
+ reg = build_registry(cfg)
46
+ assert reg.spec("delegate") is None and reg.spec("delegate_parallel") is None
47
+ assert "delegate" not in tool_names(cfg)
48
+ assert "delegate" not in build_system_prompt(Config())
49
+
50
+
51
+ def test_delegation_runs_and_records_child_messages(tmp_path, capsys):
52
+ cfg = make_config(tmp_path, DELEGATE_SCRIPT)
53
+ cfg.subagents = True
54
+ (cfg.workspace_dir).mkdir(parents=True, exist_ok=True)
55
+ (cfg.workspace_dir / "a.md").write_text("- 待办", encoding="utf-8")
56
+
57
+ from lithe_cli.agent import execute
58
+
59
+ rid, done, host = asyncio.run(execute(cfg, "看看 a.md 是什么"))
60
+ assert done["status"] == "done"
61
+ out = capsys.readouterr().out
62
+ assert "子代理已确认" in out
63
+ # the child's messages are recorded under the run, tagged by subagent id
64
+ rows = host.store.messages_for_run(rid, cfg.user_id)
65
+ tagged = [r for r in rows if r.get("subagent") == "researcher"]
66
+ assert tagged, "researcher's turns must be recorded with its tag"
67
+ assert any("a.md" in (r.get("content") or "") for r in tagged)
68
+
69
+
70
+ def test_roster_adapts_to_capability_flags(tmp_path):
71
+ cfg = make_config(tmp_path, [])
72
+ cfg.subagents = True
73
+ reg = build_registry(cfg)
74
+ host = build_host(cfg, reg)
75
+ engine = register_subagents(cfg, host, reg)
76
+ assert engine.roster.ids() == ["researcher", "coder"]
77
+ assert "delegate" in tool_names(cfg)
78
+ # researcher is read-only and never gets the write tools
79
+ assert "write_file" not in engine.trimmed_tools(
80
+ engine.roster.get("researcher"), None) and \
81
+ all(t["function"]["name"] != "write_file"
82
+ for t in engine.trimmed_tools(engine.roster.get("researcher"), None))
83
+
84
+ # shell capability adds the operator with run_command
85
+ cfg2 = make_config(tmp_path, [])
86
+ cfg2.shell = True
87
+ cfg2.subagents = True
88
+ reg2 = build_registry(cfg2)
89
+ host2 = build_host(cfg2, reg2)
90
+ engine2 = register_subagents(cfg2, host2, reg2)
91
+ assert "operator" in engine2.roster.ids()
92
+ op_names = [t["function"]["name"]
93
+ for t in engine2.trimmed_tools(engine2.roster.get("operator"),
94
+ None)]
95
+ assert "run_command" in op_names
96
+
97
+
98
+ def test_set_subagents_toggles_and_warns(tmp_path):
99
+ cfg = make_config(tmp_path, [])
100
+ wb = Workbench(cfg)
101
+ keys = [row["key"] for row in wb.settings_rows()]
102
+ assert "subagents" in keys
103
+ r = wb.dispatch("/set subagents on")
104
+ assert cfg.subagents is True
105
+ assert any("token 花费" in text for cls, text in r.messages
106
+ if cls == "warn")
107
+ # /tools reflects the delegation pair without rebuilding a host
108
+ r = wb.dispatch("/tools")
109
+ listing = "".join(text for cls, text in r.messages)
110
+ assert "delegate" in listing and "delegate_parallel" in listing
111
+ r = wb.dispatch("/set subagents off")
112
+ assert cfg.subagents is False
113
+ r = wb.dispatch("/tools")
114
+ assert "delegate" not in "".join(text for cls, text in r.messages)
115
+
116
+
117
+ def test_system_prompt_mentions_delegation():
118
+ assert "delegate" in build_system_prompt(Config(subagents=True))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes