lithe-cli 0.1.9__tar.gz → 0.1.12__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.
Files changed (42) hide show
  1. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/PKG-INFO +26 -10
  2. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/README.md +24 -8
  3. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/agent.py +59 -5
  5. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/cli_parser.py +10 -0
  6. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/commands.py +4 -3
  7. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/config.py +28 -11
  8. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/main.py +16 -0
  9. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/profiles.py +164 -22
  10. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/prompts.py +30 -0
  11. lithe_cli-0.1.12/lithe_cli/setup.py +190 -0
  12. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/ttui.py +91 -34
  13. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/ttui_render.py +2 -1
  14. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/ttui_widgets.py +51 -12
  15. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/workbench.py +277 -53
  16. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/PKG-INFO +26 -10
  17. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/SOURCES.txt +1 -0
  18. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/requires.txt +1 -1
  19. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/pyproject.toml +1 -1
  20. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli.py +30 -4
  21. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli_subagents.py +23 -0
  22. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_profiles.py +180 -0
  23. lithe_cli-0.1.12/tests/test_setup.py +173 -0
  24. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_ttui.py +24 -1
  25. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_workbench.py +142 -0
  26. lithe_cli-0.1.9/lithe_cli/setup.py +0 -109
  27. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/LICENSE +0 -0
  28. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/__main__.py +0 -0
  29. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/clipboard.py +0 -0
  30. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/py.typed +0 -0
  31. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/sessions.py +0 -0
  32. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/tui.py +0 -0
  33. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli/ui.py +0 -0
  34. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/dependency_links.txt +0 -0
  35. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/entry_points.txt +0 -0
  36. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/lithe_cli.egg-info/top_level.txt +0 -0
  37. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/setup.cfg +0 -0
  38. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli_budget_steer.py +0 -0
  39. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli_clipboard.py +0 -0
  40. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli_guard.py +0 -0
  41. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_cli_sessions.py +0 -0
  42. {lithe_cli-0.1.9 → lithe_cli-0.1.12}/tests/test_tui_v2.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.9
3
+ Version: 0.1.12
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.1.5
42
+ Requires-Dist: lithe>=0.1.9
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -69,9 +69,14 @@ pip install lithe-cli
69
69
  There is no default endpoint — the CLI refuses to run rather than silently
70
70
  hitting some third-party URL. The easiest way in is the wizard: on the
71
71
  first `lithe chat` / `lithe run` (or any time, via `lithe config`) an
72
- interactive terminal prompts for the three essentials and saves them to
73
- `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
74
- connectivity probe catches typos before your first turn.
72
+ interactive terminal walks a **provider-first interview** — profile name,
73
+ provider type (Tab-completed: openai / anthropic / zai / deepseek /
74
+ openrouter / qwen / moonshot, or `none` for a hand-written endpoint),
75
+ base_url (defaults to the preset's official URL — override it to point a
76
+ provider's format at your own router), API key, model — and saves them
77
+ to `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
78
+ connectivity probe catches typos before your first turn, using the
79
+ provider's own auth (`x-api-key` for messages endpoints).
75
80
 
76
81
  The config file holds **named profiles** — several endpoints, one active:
77
82
 
@@ -91,19 +96,30 @@ A profile may set `"provider"` instead of (or alongside) `base_url`: the
91
96
  vendor preset from `lithe.bundles.providers` fills `base_url` when unset
92
97
  and contributes `LLMConfig` defaults (transport, `extra_body`,
93
98
  `default_headers`) **under** your explicit values — you write the key and
94
- model, the preset knows the endpoint shape. `LITHE_PROVIDER` overrides the
95
- profile field; `config --list` / `--show` display it; an unknown name fails
96
- loudly with the available presets (openai / zai / deepseek / openrouter /
97
- qwen / moonshot).
99
+ model, the preset knows the endpoint shape. `--provider` /
100
+ `LITHE_PROVIDER` override the profile field; `config --list` / `--show`
101
+ display it; an unknown name fails loudly with the available presets
102
+ (openai / anthropic / zai / deepseek / openrouter / qwen / moonshot).
98
103
 
99
104
  ```bash
100
- lithe config # wizard (edits the active profile)
105
+ lithe config # provider-first wizard (edits a named profile)
101
106
  lithe config --list # profiles, key masked
102
107
  lithe config --use openrouter # switch active profile (script-friendly)
103
108
  lithe config --model glm-4.5 # set the active profile's default model
109
+ lithe config --provider anthropic # set the active profile's preset
110
+ # (none/off clears)
104
111
  lithe models # GET {base_url}/models, cached into the profile
105
112
  ```
106
113
 
114
+ A one-shot provider for a single invocation pairs the flag with an
115
+ explicit `--base-url` — the custom-router form without touching the
116
+ config file:
117
+
118
+ ```bash
119
+ lithe run --provider openrouter --base-url https://my-router/api/v1 \
120
+ --api-key sk-... --model vendor/claude-sonnet-4 "task"
121
+ ```
122
+
107
123
  To configure by hand instead, point the CLI at any OpenAI-compatible
108
124
  endpoint:
109
125
 
@@ -20,9 +20,14 @@ pip install lithe-cli
20
20
  There is no default endpoint — the CLI refuses to run rather than silently
21
21
  hitting some third-party URL. The easiest way in is the wizard: on the
22
22
  first `lithe chat` / `lithe run` (or any time, via `lithe config`) an
23
- interactive terminal prompts for the three essentials and saves them to
24
- `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
25
- connectivity probe catches typos before your first turn.
23
+ interactive terminal walks a **provider-first interview** — profile name,
24
+ provider type (Tab-completed: openai / anthropic / zai / deepseek /
25
+ openrouter / qwen / moonshot, or `none` for a hand-written endpoint),
26
+ base_url (defaults to the preset's official URL — override it to point a
27
+ provider's format at your own router), API key, model — and saves them
28
+ to `$LITHE_HOME/config.json` (mode 0600 — it holds the key). An optional
29
+ connectivity probe catches typos before your first turn, using the
30
+ provider's own auth (`x-api-key` for messages endpoints).
26
31
 
27
32
  The config file holds **named profiles** — several endpoints, one active:
28
33
 
@@ -42,19 +47,30 @@ A profile may set `"provider"` instead of (or alongside) `base_url`: the
42
47
  vendor preset from `lithe.bundles.providers` fills `base_url` when unset
43
48
  and contributes `LLMConfig` defaults (transport, `extra_body`,
44
49
  `default_headers`) **under** your explicit values — you write the key and
45
- model, the preset knows the endpoint shape. `LITHE_PROVIDER` overrides the
46
- profile field; `config --list` / `--show` display it; an unknown name fails
47
- loudly with the available presets (openai / zai / deepseek / openrouter /
48
- qwen / moonshot).
50
+ model, the preset knows the endpoint shape. `--provider` /
51
+ `LITHE_PROVIDER` override the profile field; `config --list` / `--show`
52
+ display it; an unknown name fails loudly with the available presets
53
+ (openai / anthropic / zai / deepseek / openrouter / qwen / moonshot).
49
54
 
50
55
  ```bash
51
- lithe config # wizard (edits the active profile)
56
+ lithe config # provider-first wizard (edits a named profile)
52
57
  lithe config --list # profiles, key masked
53
58
  lithe config --use openrouter # switch active profile (script-friendly)
54
59
  lithe config --model glm-4.5 # set the active profile's default model
60
+ lithe config --provider anthropic # set the active profile's preset
61
+ # (none/off clears)
55
62
  lithe models # GET {base_url}/models, cached into the profile
56
63
  ```
57
64
 
65
+ A one-shot provider for a single invocation pairs the flag with an
66
+ explicit `--base-url` — the custom-router form without touching the
67
+ config file:
68
+
69
+ ```bash
70
+ lithe run --provider openrouter --base-url https://my-router/api/v1 \
71
+ --api-key sk-... --model vendor/claude-sonnet-4 "task"
72
+ ```
73
+
58
74
  To configure by hand instead, point the CLI at any OpenAI-compatible
59
75
  endpoint:
60
76
 
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.9"
3
+ __version__ = "0.1.12"
@@ -96,8 +96,55 @@ def sandbox_backend() -> str:
96
96
  return "bwrap" if shutil.which("bwrap") else "passthrough"
97
97
 
98
98
 
99
+ def environment_facts(cfg: Config) -> str:
100
+ """Env-fact lines for the system prompt (host, shell, workspace layout).
101
+
102
+ The layout line exists because the dominant first-hour failures in a
103
+ real delegation session were assumption mismatches, not tool bugs:
104
+ git run at a workspace root that is not a repo while the real repos
105
+ live in nested sub-directories, CI snippets with project-relative
106
+ paths, a husk ``.venv`` guessed usable. A few dozen tokens of facts
107
+ replace each of those wrong guesses (one failed round-trip apiece).
108
+ The ``run_command`` hint rides along only when the shell capability
109
+ is on, keeping the no-shell prompt free of the tool's name.
110
+ """
111
+ if sys.platform == "win32":
112
+ if shutil.which("pwsh"):
113
+ shell = "PowerShell 7+(pwsh)"
114
+ elif shutil.which("powershell"):
115
+ shell = "Windows PowerShell 5.1(无 &&,用 cmd1; if ($?) { cmd2 })"
116
+ else:
117
+ shell = "cmd"
118
+ facts = f"宿主环境:Windows,shell 为 {shell}。"
119
+ else:
120
+ facts = "宿主环境:Linux/macOS(POSIX shell)。"
121
+ root = cfg.workspace_dir.expanduser().resolve()
122
+ try:
123
+ entries = sorted(
124
+ (p for p in root.iterdir()
125
+ if p.is_dir() and not p.name.startswith(".")),
126
+ key=lambda p: p.name.lower())
127
+ except OSError:
128
+ return facts
129
+ names = [p.name for p in entries[:10]]
130
+ layout = "、".join(names) if names else "(空)"
131
+ if len(entries) > 10:
132
+ layout += f" 等 {len(entries)} 项"
133
+ line = (f"工作区 {root}("
134
+ f"{'是' if (root / '.git').exists() else '不是'} git 仓库)"
135
+ f"顶层目录:{layout}")
136
+ repos = [p.name for p in entries if (p / ".git").exists()]
137
+ if repos:
138
+ line += f";其中的独立 git 仓库:{'、'.join(repos)}"
139
+ if cfg.shell:
140
+ line += ("。对子项目执行命令用 run_command 的 cwd 参数指定目录"
141
+ "(区内自由、区外需用户审批),不要假设工作区根是仓库,"
142
+ "也不要在命令里拼接 cd")
143
+ return facts + "\n" + line
144
+
145
+
99
146
  def build_system_prompt(cfg: Config) -> str:
100
- """Base prompt plus one line per enabled capability."""
147
+ """Base prompt plus one line per enabled capability, then env facts."""
101
148
  extras = []
102
149
  if cfg.code:
103
150
  extras.append("可以用 run_code 执行 Python 来验证想法、计算或测试。")
@@ -114,8 +161,7 @@ def build_system_prompt(cfg: Config) -> str:
114
161
  extras.append("可以用 delegate 把独立子任务委派给子代理(可用名单见工具说明:检索/编码/操作),"
115
162
  "互不依赖的子任务用 delegate_parallel 并行委派;"
116
163
  "子代理与本对话共享预算,汇报时合并它们的结果。")
117
- if not extras:
118
- return SYSTEM_PROMPT_BASE
164
+ extras.append(environment_facts(cfg))
119
165
  return SYSTEM_PROMPT_BASE + "\n" + "\n".join(extras)
120
166
 
121
167
 
@@ -196,7 +242,8 @@ def build_registry(
196
242
  from lithe.bundles.command import CommandRunner
197
243
 
198
244
  register_command_tools(
199
- reg, lambda ctx: cfg.workspace_dir.resolve(), CommandRunner()
245
+ reg, lambda ctx: cfg.workspace_dir.resolve(), CommandRunner(),
246
+ approver=approver,
200
247
  )
201
248
  # Dangerous-command guard: catastrophic commands never run; the
202
249
  # destructive-but-scoped tier (rm -r <path>, git push --force,
@@ -328,7 +375,14 @@ def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry,
328
375
  else:
329
376
  render_event(enriched)
330
377
 
331
- engine = SubagentEngine(host, roster, on_subagent_event=forward_progress)
378
+ engine = SubagentEngine(
379
+ host, roster, on_subagent_event=forward_progress,
380
+ # Subagents do not inherit the orchestrator's system prompt — the
381
+ # roster's spec prompts are all they see. Prepending the same env
382
+ # facts (platform, shell, nested-repo layout) keeps the operator
383
+ # from re-learning the workspace layout by failed guesses.
384
+ prompt_builder=lambda spec, ctx: f"{environment_facts(cfg)}\n\n{spec.prompt}",
385
+ )
332
386
  register_delegate_tools(reg, engine, parallel=True)
333
387
  return engine
334
388
 
@@ -25,6 +25,13 @@ def build_parser() -> argparse.ArgumentParser:
25
25
  sp.add_argument("--api-key", help="endpoint API key (env LITHE_API_KEY)")
26
26
  sp.add_argument("--base-url", help="endpoint base URL (env LITHE_BASE_URL)")
27
27
  sp.add_argument("--model", help="model name (env LITHE_MODEL)")
28
+ sp.add_argument(
29
+ "--provider",
30
+ help="vendor preset (openai/anthropic/zai/deepseek/openrouter/"
31
+ "qwen/moonshot; env LITHE_PROVIDER): fills base_url when "
32
+ "unset, sets transport/dialect defaults under explicit "
33
+ "values — pair with --base-url for a custom router",
34
+ )
28
35
  sp.add_argument(
29
36
  "--profile",
30
37
  help="endpoint profile name (env LITHE_PROFILE; default: active "
@@ -182,5 +189,8 @@ def build_parser() -> argparse.ArgumentParser:
182
189
  config_p.add_argument("--use", metavar="NAME", help="switch the active profile")
183
190
  config_p.add_argument("--model", metavar="NAME",
184
191
  help="set the active profile's default model")
192
+ config_p.add_argument("--provider", metavar="NAME",
193
+ help="set the active profile's provider preset "
194
+ "(none/off clears)")
185
195
 
186
196
  return p
@@ -24,10 +24,11 @@ COMMANDS: dict[str, tuple[str, str]] = {
24
24
  "sessions": ("", "列出会话(F3 同效)"),
25
25
  "resume": ("[编号|标题]", "切换会话;不带参数等同 /sessions"),
26
26
  "rename": ("标题", "重命名当前会话"),
27
- "model": ("[名称|--save]", "查看/切换模型(F4 同效);--save 同时存为档案默认"),
28
- "models": ("", "从端点拉取模型列表并缓存"),
27
+ "model": ("[名称|档案:模型|--save]", "查看/切换模型(F4 同效);常用区置顶,档案:模型 跨档案切换;--save 存为档案默认"),
28
+ "models": ("[all]", "从端点拉取模型列表并缓存;all 并行拉取全部档案(限定名显示)"),
29
29
  "reasoning": ("[级别|--save]", "查看/设置推理强度(F6 同效);off/minimal/low/medium/high,下一轮生效"),
30
- "profile": ("[名称]", "查看/切换 provider 档案"),
30
+ "profile": ("[名称]", "查看/切换 provider 档案(列表含 provider · 协议标注)"),
31
+ "fav": ("[档案:模型]", "查看/收藏常用模型;/model 列表与 F4 选择器顶部直达"),
31
32
  "set": ("[名称] [值]", "查看/调整运行设置(F5 同效);面板内空格连切不关闭、Enter 切换并关闭,下一轮生效"),
32
33
  "tools": ("", "列出已注册的工具"),
33
34
  "copy": (f"[{COPY_SCOPE_HELP}]", "复制对话文本到系统剪贴板(右键同效);默认最后一条回答"),
@@ -239,14 +239,22 @@ def _restrict_to_owner(path: Path, directory: bool = False) -> None:
239
239
  raise OSError(f"failed to restrict access to {path}")
240
240
 
241
241
 
242
- def save_endpoint(api_key: str, base_url: str, model: str) -> Path:
243
- """Write the endpoint into the active profile (creating ``default`` when
244
- no profile exists), preserving every other saved profile."""
242
+ def save_endpoint(
243
+ api_key: str,
244
+ base_url: str,
245
+ model: str,
246
+ provider: str | None = None,
247
+ name: str | None = None,
248
+ ) -> Path:
249
+ """Write the endpoint into a profile (creating ``default`` when no
250
+ profile exists), preserving every other saved profile. *name* picks
251
+ the profile (default: the active one); *provider* records the vendor
252
+ preset the profile belongs to."""
245
253
  from .profiles import DEFAULT_PROFILE, ProfileStore
246
254
 
247
255
  store = ProfileStore()
248
- name = store.active_name() or DEFAULT_PROFILE
249
- return store.upsert(name, base_url, api_key, model)
256
+ profile = name or store.active_name() or DEFAULT_PROFILE
257
+ return store.upsert(profile, base_url, api_key, model, provider=provider)
250
258
 
251
259
 
252
260
  def load_config(args: Any) -> Config:
@@ -285,15 +293,20 @@ def load_config(args: Any) -> Config:
285
293
  ("api_key", g("api_key", None), ENV_API_KEY),
286
294
  ("base_url", g("base_url", None), ENV_BASE_URL),
287
295
  ("model", g("model", None), ENV_MODEL),
296
+ # LITHE_PROVIDER / --provider pin the vendor preset for this
297
+ # invocation: in-session profile switching must not swap it out
298
+ # from under a CI-pinned dialect.
299
+ ("provider", g("provider", None), ENV_PROVIDER),
288
300
  )
289
301
  if flag or os.environ.get(env)
290
302
  )
291
- # Vendor preset (profile "provider" field > LITHE_PROVIDER): fills
292
- # base_url when nothing explicit set it — the preset's whole point —
293
- # while every explicit value stays untouched. An unknown name is a
294
- # config typo: die loudly like an unknown --profile, listing options.
295
- provider = (os.environ.get(ENV_PROVIDER) or saved.get("provider")
296
- or g("provider", None))
303
+ # Vendor preset (--provider flag > LITHE_PROVIDER > profile field,
304
+ # matching the other endpoint pins): fills base_url when nothing
305
+ # explicit set it — the preset's whole point — while every explicit
306
+ # value stays untouched. An unknown name is a config typo: die
307
+ # loudly like an unknown --profile, listing options.
308
+ provider = (g("provider", None) or os.environ.get(ENV_PROVIDER)
309
+ or saved.get("provider"))
297
310
  base_url = (
298
311
  g("base_url", None) or os.environ.get(ENV_BASE_URL)
299
312
  or saved.get("base_url")
@@ -387,6 +400,10 @@ def require_endpoint(cfg: Config, interactive: bool = False) -> None:
387
400
  cfg.api_key = cfg.api_key or saved.get("api_key")
388
401
  cfg.base_url = cfg.base_url or saved.get("base_url")
389
402
  cfg.model = cfg.model or saved.get("model")
403
+ # a wizard-configured provider takes effect this process: the
404
+ # right transport/auth, not a chat-completions default until
405
+ # the next invocation reads the profile back.
406
+ cfg.provider = cfg.provider or saved.get("provider")
390
407
  if cfg.has_endpoint:
391
408
  return
392
409
  raise SystemExit(
@@ -338,6 +338,22 @@ def _cmd_config(args: Any) -> int:
338
338
  store.set_model(active, args.model)
339
339
  print(ui.s(f"✓ 档案 {active} 默认模型 → {args.model}", GREEN))
340
340
  return 0
341
+ if args.provider:
342
+ active = store.active_name()
343
+ if not active:
344
+ print(ui.s("没有已保存档案,先运行 lithe-cli config。", RED))
345
+ return 1
346
+ try:
347
+ store.set_provider(active, args.provider)
348
+ except ValueError as exc:
349
+ print(ui.s(str(exc), RED))
350
+ return 1
351
+ raw = args.provider.strip().lower()
352
+ if raw in ("", "none", "off"):
353
+ print(ui.s(f"✓ 档案 {active} 已清除 provider", GREEN))
354
+ else:
355
+ print(ui.s(f"✓ 档案 {active} provider → {args.provider}", GREEN))
356
+ return 0
341
357
 
342
358
  saved = load_saved_endpoint()
343
359
  if args.show:
@@ -6,9 +6,10 @@ holds keys) grows from the original flat triple to a profile map::
6
6
  {
7
7
  "version": 2,
8
8
  "active": "zhipu",
9
+ "favorites": ["zhipu:glm-4.6", "anthropic:claude-sonnet-4"],
9
10
  "profiles": {
10
11
  "zhipu": {"base_url": "...", "api_key": "...", "model": "glm-4.6",
11
- "context_window": 128000, "cached_models": ["glm-4.6"]},
12
+ "context_window": 128000, "cached_models": ["glm-4.6"]},
12
13
  "openrouter": {"base_url": "...", "api_key": "...", "model": "...",
13
14
  "provider": "openrouter"},
14
15
  "selfhost": {"base_url": "https://my-router/api/v1", "api_key": "...",
@@ -23,6 +24,10 @@ speaking the OpenRouter format keeps its own URL. ``document_format``
23
24
  overrides the preset's document-block dialect for ``analyze_document``
24
25
  (see lithe.bundles.documents).
25
26
 
27
+ ``favorites`` are qualified model refs (``profile:model``) shown as the
28
+ "常用" section by the model pickers — the quick-switch lane across
29
+ providers. Entries whose profile has been deleted are pruned on load.
30
+
26
31
  A legacy flat ``{api_key, base_url, model}`` file is translated in memory to
27
32
  the single profile ``default`` and is never rewritten until an explicit save
28
33
  (a mutation through this module) — old installs keep working untouched.
@@ -108,6 +113,20 @@ def _clean_endpoint(data: dict) -> dict:
108
113
  return out
109
114
 
110
115
 
116
+ def _clean_favorites(raw: Any, profiles: dict) -> list[str]:
117
+ """Validated ``profile:model`` refs pointing at live profiles only."""
118
+ if not isinstance(raw, list):
119
+ return []
120
+ out: list[str] = []
121
+ for item in raw:
122
+ if not isinstance(item, str) or ":" not in item:
123
+ continue
124
+ profile, _, model = item.partition(":")
125
+ if profile in profiles and model.strip() and item not in out:
126
+ out.append(item)
127
+ return out
128
+
129
+
111
130
  class ProfileStore:
112
131
  """Read/modify the profile file; every mutation rewrites it via an
113
132
  atomic temp-file replace (the previous version survives as ``.bak``)
@@ -126,24 +145,27 @@ class ProfileStore:
126
145
  return None
127
146
 
128
147
  def load(self) -> dict:
129
- """Normalized ``{"active": str | None, "profiles": {name: endpoint}}``.
148
+ """Normalized ``{"active", "profiles", "favorites"}``.
130
149
 
131
150
  A corrupt main file falls back to the ``.bak`` left by the last
132
151
  atomic save before degrading to empty — a bad edit or a torn write
133
- costs the edit, not every saved profile.
152
+ costs the edit, not every saved profile. Favorites whose profile no
153
+ longer exists are pruned here, so every read (and the save round
154
+ trips built on it) never sees ghost entries.
134
155
  """
135
156
  data = self._read_json(self.path)
136
157
  if data is None:
137
158
  data = self._read_json(
138
159
  self.path.parent / (self.path.name + ".bak"))
139
160
  if data is None or not isinstance(data, dict):
140
- return {"active": None, "profiles": {}}
161
+ return {"active": None, "profiles": {}, "favorites": []}
141
162
  if "profiles" not in data: # legacy flat triple → profile "default"
142
163
  endpoint = _clean_endpoint(data)
143
164
  if not endpoint:
144
- return {"active": None, "profiles": {}}
165
+ return {"active": None, "profiles": {}, "favorites": []}
145
166
  return {"active": DEFAULT_PROFILE,
146
- "profiles": {DEFAULT_PROFILE: endpoint}}
167
+ "profiles": {DEFAULT_PROFILE: endpoint},
168
+ "favorites": []}
147
169
  profiles_raw = data.get("profiles")
148
170
  profiles = {}
149
171
  if isinstance(profiles_raw, dict):
@@ -156,14 +178,18 @@ class ProfileStore:
156
178
  active = data.get("active")
157
179
  if active not in profiles:
158
180
  active = next(iter(profiles), None)
159
- return {"active": active, "profiles": profiles}
181
+ favorites = _clean_favorites(data.get("favorites"), profiles)
182
+ return {"active": active, "profiles": profiles,
183
+ "favorites": favorites}
160
184
 
161
- def _save(self, active: str | None, profiles: dict) -> Path:
185
+ def _save(self, data: dict) -> Path:
162
186
  fresh_dir = not self.path.parent.exists()
163
187
  self.path.parent.mkdir(parents=True, exist_ok=True)
164
188
  if fresh_dir:
165
189
  _restrict_to_owner(self.path.parent, directory=True)
166
- payload = {"version": 2, "active": active, "profiles": profiles}
190
+ payload = {"version": 2, "active": data.get("active"),
191
+ "favorites": data.get("favorites") or [],
192
+ "profiles": data["profiles"]}
167
193
  text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
168
194
  # Atomic replace: a crash mid-write must never destroy every saved
169
195
  # profile (API keys included). The old file survives as .bak for the
@@ -256,13 +282,14 @@ class ProfileStore:
256
282
  data["profiles"][name] = {k: v for k, v in endpoint.items() if v}
257
283
  if data["active"] is None:
258
284
  data["active"] = name
259
- return self._save(data["active"], data["profiles"])
285
+ return self._save(data)
260
286
 
261
287
  def set_active(self, name: str) -> bool:
262
288
  data = self.load()
263
289
  if name not in data["profiles"]:
264
290
  return False
265
- self._save(name, data["profiles"])
291
+ data["active"] = name
292
+ self._save(data)
266
293
  return True
267
294
 
268
295
  def set_model(self, name: str, model: str) -> bool:
@@ -270,7 +297,33 @@ class ProfileStore:
270
297
  if name not in data["profiles"]:
271
298
  return False
272
299
  data["profiles"][name]["model"] = model
273
- self._save(data["active"], data["profiles"])
300
+ self._save(data)
301
+ return True
302
+
303
+ def set_provider(self, name: str, provider: str | None) -> bool:
304
+ """Set (or clear, with None/""/``none``/``off``) a profile's provider.
305
+
306
+ An unknown name raises the preset module's :class:`ValueError`
307
+ (its message lists the available presets) — a typo'd provider
308
+ must not silently strip the profile's protocol. Returns False
309
+ only for an unknown *profile* name.
310
+ """
311
+ data = self.load()
312
+ if name not in data["profiles"]:
313
+ return False
314
+ endpoint = data["profiles"][name]
315
+ raw = (provider or "").strip()
316
+ if not raw or raw.lower() in ("none", "off"):
317
+ endpoint.pop("provider", None)
318
+ else:
319
+ try:
320
+ from lithe.bundles.providers import get_preset
321
+ except ImportError: # kernel not importable in this environment
322
+ get_preset = None
323
+ if get_preset is not None:
324
+ get_preset(raw) # ValueError on unknown, listing options
325
+ endpoint["provider"] = raw.lower()
326
+ self._save(data)
274
327
  return True
275
328
 
276
329
  def set_reasoning_effort(self, name: str, effort: str | None) -> bool:
@@ -283,7 +336,7 @@ class ProfileStore:
283
336
  endpoint.pop("reasoning_effort", None)
284
337
  else:
285
338
  endpoint["reasoning_effort"] = effort.strip()
286
- self._save(data["active"], data["profiles"])
339
+ self._save(data)
287
340
  return True
288
341
 
289
342
  def cache_models(self, name: str, models: list[str]) -> bool:
@@ -291,7 +344,7 @@ class ProfileStore:
291
344
  if name not in data["profiles"]:
292
345
  return False
293
346
  data["profiles"][name]["cached_models"] = list(models)
294
- self._save(data["active"], data["profiles"])
347
+ self._save(data)
295
348
  return True
296
349
 
297
350
  def delete(self, name: str) -> bool:
@@ -301,18 +354,47 @@ class ProfileStore:
301
354
  del data["profiles"][name]
302
355
  if data["active"] == name:
303
356
  data["active"] = next(iter(data["profiles"]), None)
304
- self._save(data["active"], data["profiles"])
357
+ # favorites pointing at the deleted profile die with it
358
+ data["favorites"] = _clean_favorites(
359
+ data.get("favorites"), data["profiles"])
360
+ self._save(data)
305
361
  return True
306
362
 
363
+ # -- favorites -------------------------------------------------------------
307
364
 
308
- def fetch_models(base_url: str, api_key: str, timeout: float = 10.0) -> list[str] | None:
309
- """GET ``{base_url}/models`` and return the model ids, or None on failure.
365
+ def favorites(self) -> list[str]:
366
+ """Qualified ``profile:model`` refs (pruned to live profiles)."""
367
+ return self.load()["favorites"]
310
368
 
311
- Never raises: a listing is a convenience, and endpoints legitimately lack
312
- ``/models`` or gate it behind different auth.
313
- """
314
- url = base_url.rstrip("/") + "/models"
315
- req = Request(url, headers={"Authorization": f"Bearer {api_key}"})
369
+ def set_favorites(self, items: list[str]) -> bool:
370
+ data = self.load()
371
+ data["favorites"] = _clean_favorites(items, data["profiles"])
372
+ self._save(data)
373
+ return True
374
+
375
+ def toggle_favorite(self, qualified: str) -> bool | None:
376
+ """Add/remove a qualified ref. Returns the new state (True = now a
377
+ favorite), or None when the ref is malformed / its profile is
378
+ unknown — a typo'd favorite must fail loudly, not save garbage."""
379
+ profile, _, model = (qualified or "").partition(":")
380
+ data = self.load()
381
+ if not model.strip() or profile not in data["profiles"]:
382
+ return None
383
+ ref = f"{profile}:{model.strip()}"
384
+ favs = data["favorites"]
385
+ if ref in favs:
386
+ favs.remove(ref)
387
+ added = False
388
+ else:
389
+ favs.append(ref)
390
+ added = True
391
+ self._save(data)
392
+ return added
393
+
394
+
395
+ def _fetch_models_url(url: str, headers: dict, timeout: float) -> list[str] | None:
396
+ """GET *url* and parse ``data[].id`` items; None on any failure."""
397
+ req = Request(url, headers=headers)
316
398
  try:
317
399
  with urlopen(req, timeout=timeout) as resp:
318
400
  data = json.loads(resp.read().decode("utf-8", "replace"))
@@ -328,3 +410,63 @@ def fetch_models(base_url: str, api_key: str, timeout: float = 10.0) -> list[str
328
410
  elif isinstance(item, str):
329
411
  ids.append(item)
330
412
  return ids or None
413
+
414
+
415
+ def fetch_models(base_url: str, api_key: str, timeout: float = 10.0) -> list[str] | None:
416
+ """GET ``{base_url}/models`` (Bearer auth) and return the model ids, or
417
+ None on failure.
418
+
419
+ Never raises: a listing is a convenience, and endpoints legitimately lack
420
+ ``/models`` or gate it behind different auth.
421
+ """
422
+ url = base_url.rstrip("/") + "/models"
423
+ return _fetch_models_url(
424
+ url, {"Authorization": f"Bearer {api_key}"}, timeout)
425
+
426
+
427
+ def models_request(endpoint: dict) -> tuple[str, dict[str, str]] | None:
428
+ """Protocol-aware ``(url, headers)`` for a GET ``{base_url}/models``.
429
+
430
+ The endpoint's provider preset names its transport: a ``messages``
431
+ endpoint authenticates with ``x-api-key`` + ``anthropic-version``
432
+ (and takes a ``limit`` so the default 20-model page doesn't silently
433
+ truncate the list); everything else keeps the OpenAI-style Bearer
434
+ header. A missing/unknown provider degrades to Bearer; None when the
435
+ endpoint lacks ``base_url`` / ``api_key``.
436
+ """
437
+ base_url = (endpoint.get("base_url") or "").rstrip("/")
438
+ api_key = endpoint.get("api_key") or ""
439
+ if not (base_url and api_key):
440
+ return None
441
+ url = f"{base_url}/models"
442
+ headers = {"Authorization": f"Bearer {api_key}"}
443
+ provider = endpoint.get("provider")
444
+ if provider:
445
+ try:
446
+ from lithe.bundles.providers import get_preset
447
+ except ImportError: # kernel not importable in this environment
448
+ get_preset = None
449
+ if get_preset is not None:
450
+ try:
451
+ preset = get_preset(provider)
452
+ except ValueError:
453
+ preset = None
454
+ if preset and preset.get("transport") == "messages":
455
+ url = f"{base_url}/models?limit=1000"
456
+ headers = {"x-api-key": api_key,
457
+ "anthropic-version": "2023-06-01"}
458
+ return url, headers
459
+
460
+
461
+ def fetch_models_for(endpoint: dict, timeout: float = 10.0) -> list[str] | None:
462
+ """List models for a stored profile with its protocol's own auth
463
+ (:func:`models_request`). Both flavors answer with the same
464
+ ``{"data": [{"id": ...}]}`` shape. Never raises: a listing is a
465
+ convenience, and endpoints legitimately lack ``/models`` or gate it
466
+ behind different auth — None on failure.
467
+ """
468
+ request = models_request(endpoint)
469
+ if request is None:
470
+ return None
471
+ url, headers = request
472
+ return _fetch_models_url(url, headers, timeout)