crabcode 0.1.6__py3-none-any.whl → 0.1.7__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: crabcode
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: CrabCode - AI coding assistant in the terminal
5
5
  Requires-Python: >=3.10
6
6
  Requires-Dist: anthropic>=0.40.0
@@ -2,16 +2,16 @@ crabcode_cli/__init__.py,sha256=vBL_d7W0Vt2kIaYI3iZ2yS7kZleJEQXTTlIBICm5GRY,136
2
2
  crabcode_cli/__main__.py,sha256=ekwH_ayJ5YpefhbXSDj-IM9mS9YrCwWpoDIH92V6tjg,75
3
3
  crabcode_cli/app.py,sha256=o7P9cQBTo7mY6OFDhaJVx39qdfj_Zqc2Qfku-z3eGSU,31579
4
4
  crabcode_cli/banner.py,sha256=WlQPxVLLnzIE6xlP6gFbpCDYmDewzIwLtHKFLf9GC-I,1339
5
- crabcode_cli/computer_use.py,sha256=n4N--P5i9-GBzcfsAbhM5J5ebPFt0P2_shbaHq1ZpyU,13570
5
+ crabcode_cli/computer_use.py,sha256=F2ROhv4c7-j70N_-qPKRv69PkTIwkt2sWFC_qPEfpiQ,13973
6
6
  crabcode_cli/model_manager.py,sha256=vEoD3JVyWGAnIoUAe4jspPA8dt5d3pvbRNQ_A0Ank6o,21459
7
7
  crabcode_cli/model_picker.py,sha256=ghxsVySXy9WZVJLVb3ElTf9D2sWeT6lidcPWB0gX-_Y,8352
8
8
  crabcode_cli/pipe.py,sha256=hIOqrkUNbm3jXXz7NRX-HlbbWb3uPlWZwO6UUpIhtvg,5431
9
- crabcode_cli/repl.py,sha256=Bs_gBAa4cIyMjX0no_QEm9Ow68vghpIQE43_z-sVMq4,191906
9
+ crabcode_cli/repl.py,sha256=Kl_z99bdBWxe1Ghfer2ebO4kQ2ApEA_Ewwy49HA-tJY,193026
10
10
  crabcode_cli/session_picker.py,sha256=Pett41MV4xcg6vDR4Rbq8C0bh40u-GVF_cjQldNQIoQ,10307
11
11
  crabcode_cli/render/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  crabcode_cli/render/messages.py,sha256=n9OsbLIAU3FyO9gwGMMJld7zq-71N0caz9ecmE2kIjo,568
13
13
  crabcode_core/__init__.py,sha256=ArpgEg5xC3iR4DRT0HBg7DwU3K-r1MnmDOHpIb1b0E4,142
14
- crabcode_core/_version.py,sha256=Dt9sZjC9UYWEhBzyy8qd6c9WoL9oj_Ct2KhDhWrK14E,82
14
+ crabcode_core/_version.py,sha256=NTuzp5GKvC1kBra8mTYyHzhWrod9nFOh9Rj9CZMMAZQ,82
15
15
  crabcode_core/_windows_process.py,sha256=PjRQqZfLSHdvexANQYHZDQNxyu2s1Yaxt1YNlawwNIU,2949
16
16
  crabcode_core/agent_manager.py,sha256=Wu7kHfA5_zSTHYLemqOD85deblcwDdtvnZVE4rmq-Vc,71475
17
17
  crabcode_core/command_line.py,sha256=MWbAF4QUDVdwGM8cKoHYnIgr8yOgqk3Y_0ndt9f-t6Y,544
@@ -38,7 +38,8 @@ crabcode_core/api/base.py,sha256=2fAiYazrzbk5kb4oKARClnePT4IVn9cF2tgxxoeKbP4,857
38
38
  crabcode_core/api/codex_adapter.py,sha256=pgX8rzfdotUMQNDHWPiSW9QbmFrv0-MqPJ130ayCfNc,54775
39
39
  crabcode_core/api/error_logging.py,sha256=2GMD8naR-Tk9Eki_i2GJQShAWGVvt6XZATs8SLXRR8Q,5326
40
40
  crabcode_core/api/gemini_adapter.py,sha256=RVk3zlLPqDtzG8w5psu4aSoFyFLua5qQx3subqz-5DQ,1130
41
- crabcode_core/api/model_info.py,sha256=xovzBB52FxkS7mFweltYYRtxiIHWVh13F9iel6xEt2c,8367
41
+ crabcode_core/api/model_discovery.py,sha256=f4s0dHSzpLXHpOxlBO-C14pSqwucSHmaCYDdBROYMTw,7194
42
+ crabcode_core/api/model_info.py,sha256=hAP8bOiELV80E_sbZxXfOXriiBjpZ8nmTcYAMrp0x_0,8661
42
43
  crabcode_core/api/network.py,sha256=108VR8Ix67bklhZoV2FIPNtQ_jrI7JXUjS9A98p81-I,2438
43
44
  crabcode_core/api/ollama_adapter.py,sha256=ZpTg11zOUGFE0J88qBXL7AvxDQU5PjWg2wWvm4uxUvY,1158
44
45
  crabcode_core/api/openai_adapter.py,sha256=HRrsmoc01qEo49hXU2VBbEZiMgUPvwXxgBtx3s_0NHo,12303
@@ -157,7 +158,7 @@ crabcode_gateway/event_bus.py,sha256=lWLCeoKkJ9fhDT_Kwc_esokDsbeRkPi5hsK87kPxRRY
157
158
  crabcode_gateway/middleware.py,sha256=bn0pUJHWINc_28ZgZ6e7i-AarkqhfQZMaxbknAVU5UA,11293
158
159
  crabcode_gateway/protocol.py,sha256=psXRNQjkfwliXZdETlo1qsGM0IcE_OIUarCLnSNuq6o,466
159
160
  crabcode_gateway/safe_file.py,sha256=uOdkxWdZNQ5RJ2jJ9urnIRiF_2uAP8Dkj8wR08vbDaU,2108
160
- crabcode_gateway/schemas.py,sha256=dpW66eWgeYEw_wUls-JavmvPnHKiCyFHNYEBWMulPcM,55935
161
+ crabcode_gateway/schemas.py,sha256=v4D5J6_tcsn9whiwpAYwg5a-kkQlF1j9YIwQiSZ0EvQ,56362
161
162
  crabcode_gateway/server.py,sha256=ShCrO1Zw-Ed37HfUYihyOToJasGJjL7Kzy1BFA4CJ64,20408
162
163
  crabcode_gateway/session_registry.py,sha256=HhvLvlGDx0EgmGwjk2zHCCtWURmNDZHHmpBjroX35fk,1214
163
164
  crabcode_gateway/task_registry.py,sha256=Ij8USxQ13ockqhoZ286hn8jXckFeLglNSgwgcnQ5tX4,26461
@@ -176,7 +177,7 @@ crabcode_gateway/routes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG
176
177
  crabcode_gateway/routes/agent.py,sha256=ZI97BVRMPgwpv45IqWFoESO_Khr0uFfy6J-tDojNWOU,13955
177
178
  crabcode_gateway/routes/auth.py,sha256=kIynPq7LUBlKwS--1Qp1hJHpLqebB5Unt1qAI8V_dUI,4945
178
179
  crabcode_gateway/routes/computer_use.py,sha256=_NtMi3zciudhDRcha53fXL3jECp6Oj5cWWvWKD_JLAY,4622
179
- crabcode_gateway/routes/config.py,sha256=P4f_RwQoBV3fDpoHSeuuH9EtDtgWe8mgZbK72sULHoY,68334
180
+ crabcode_gateway/routes/config.py,sha256=VCA97t7dU8c5EctjHFsXotiFAE0vZ8N5K0ie97cQxZ4,70636
180
181
  crabcode_gateway/routes/document.py,sha256=j01jt88A29GF6fHYcX2AparZAOPsUrwllec9YGtFswg,78665
181
182
  crabcode_gateway/routes/event.py,sha256=WOr1WHJ-5nCcpCWIkpIos2aAl2ASJUyYKSaLZ5bCRS0,155226
182
183
  crabcode_gateway/routes/git_review.py,sha256=-fbMOWo8JKnHCMsKew3i02lTE7Ohj9w6ocgFKCsYeio,10460
@@ -197,7 +198,7 @@ crabcode_search/embedder.py,sha256=NlNuOHS7t4JvaWXkNU-T_xxnkjRxFrr3l57dlB5IRkc,1
197
198
  crabcode_search/indexer.py,sha256=bBL3OE6HMqdIRBCnI--XjaHl7_G3H4VO2d-RMKtjlkI,7745
198
199
  crabcode_search/store.py,sha256=s1hsyRRGcAO_hdJli6M0C8rhkMW4tXj5ZVMPuCP3uhQ,8074
199
200
  crabcode_search/tool.py,sha256=xJjAN3esvJIH3z7ILNQ1gQs5Ty5fu6u7CYX6P2WB_BY,10238
200
- crabcode-0.1.6.dist-info/METADATA,sha256=KtN7VCKR2jNBJ7cevwN176mEmxExIYbcmlX8PQZsZC4,2799
201
- crabcode-0.1.6.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
202
- crabcode-0.1.6.dist-info/entry_points.txt,sha256=tpYKME-yDLFb2eqwryWJG-d-HW4dkvDbzwogRl2jays,52
203
- crabcode-0.1.6.dist-info/RECORD,,
201
+ crabcode-0.1.7.dist-info/METADATA,sha256=Q6Sqy5M53yQ7A7I6vBjUJE-vVeXQTju-vninazwV9xs,2799
202
+ crabcode-0.1.7.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
203
+ crabcode-0.1.7.dist-info/entry_points.txt,sha256=tpYKME-yDLFb2eqwryWJG-d-HW4dkvDbzwogRl2jays,52
204
+ crabcode-0.1.7.dist-info/RECORD,,
@@ -250,12 +250,20 @@ async def connect_session(session: Any) -> LocalComputerUse | None:
250
250
  backend = LocalComputerUse()
251
251
  if not backend.client.installed and backend.client.bundle is None:
252
252
  return None
253
+ session._computer_use_connecting = True
253
254
  try:
254
255
  await backend.connect()
255
256
  except ComputerUseError as exc:
256
257
  logger.warning("Computer Use unavailable: %s", exc)
257
258
  await backend.close()
258
259
  return None
260
+ except BaseException:
261
+ # REPL shutdown may cancel an in-flight bootstrap. Do not leave a
262
+ # heartbeat or partially connected backend behind.
263
+ await backend.close()
264
+ raise
265
+ finally:
266
+ session._computer_use_connecting = False
259
267
  session.computer_use_backend = backend
260
268
  session.computer_use_host_id = backend.host_id
261
269
  session.computer_use_enabled = True
@@ -267,6 +275,8 @@ def session_status(session: Any) -> str:
267
275
  backend = getattr(session, "computer_use_backend", None)
268
276
  host_id = getattr(session, "computer_use_host_id", None)
269
277
  if backend is None:
278
+ if getattr(session, "_computer_use_connecting", False):
279
+ return "starting"
270
280
  client = NativeClient()
271
281
  return "unavailable (run crabcode computer-use status)" if client.installed or client.bundle else "not installed"
272
282
  if not getattr(session, "computer_use_enabled", False):
crabcode_cli/repl.py CHANGED
@@ -594,6 +594,14 @@ def _configure_composer_layout(
594
594
  if not isinstance(root, HSplit) or not root.children:
595
595
  return
596
596
  main = root.children[0]
597
+ # Newer prompt_toolkit versions wrap the input in a conditional Frame.
598
+ # Follow its active branch before configuring our own frame and status.
599
+ while isinstance(main, ConditionalContainer):
600
+ main = (
601
+ main.content
602
+ if main.filter()
603
+ else getattr(main, "alternative_content", None)
604
+ )
597
605
  if not isinstance(main, FloatContainer) or not isinstance(main.content, HSplit):
598
606
  return
599
607
 
@@ -2228,10 +2236,21 @@ async def run_repl(
2228
2236
  session.on_tool_event = _on_tool_event
2229
2237
 
2230
2238
  computer_use = None
2239
+ computer_use_task: asyncio.Task[None] | None = None
2231
2240
  try:
2232
2241
  from crabcode_cli.computer_use import connect_session
2233
2242
 
2234
- computer_use = await connect_session(session)
2243
+ async def connect_computer_use() -> None:
2244
+ nonlocal computer_use
2245
+ try:
2246
+ computer_use = await connect_session(session)
2247
+ except Exception:
2248
+ logger.exception("Failed to connect optional Computer Use component")
2249
+
2250
+ # The optional native host can take tens of seconds to install, start,
2251
+ # or time out. Keep input and normal chat available while it connects;
2252
+ # ComputerUseTool reads the session's backend dynamically.
2253
+ computer_use_task = asyncio.create_task(connect_computer_use())
2235
2254
  if resume_session_id:
2236
2255
  await session.initialize()
2237
2256
  ok = await session.resume(resume_session_id)
@@ -2748,6 +2767,10 @@ async def run_repl(
2748
2767
  console.print()
2749
2768
  finally:
2750
2769
  with _shutdown_deadline():
2770
+ if computer_use_task is not None:
2771
+ computer_use_task.cancel()
2772
+ with contextlib.suppress(asyncio.CancelledError):
2773
+ await computer_use_task
2751
2774
  if background_consumer is not None:
2752
2775
  background_consumer.cancel()
2753
2776
  with contextlib.suppress(asyncio.CancelledError):
crabcode_core/_version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Single source of truth for the CrabCode release version."""
2
2
 
3
- VERSION = "0.1.6"
3
+ VERSION = "0.1.7"
@@ -0,0 +1,136 @@
1
+ """Read a provider's model catalog using a saved group's connection policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ from collections.abc import Mapping
9
+ from urllib.parse import urlsplit, urlunsplit
10
+
11
+ import httpx
12
+
13
+ from crabcode_core.api.network import certificate_failure, http_options
14
+ from crabcode_core.types.config import ApiConfig
15
+
16
+
17
+ class ModelDiscoveryError(ValueError):
18
+ """A safe, user-facing discovery error (never a raw provider response)."""
19
+
20
+
21
+ def _connection(config: ApiConfig, env: Mapping[str, str]) -> tuple[str, httpx.Headers, bool]:
22
+ provider = config.provider or "anthropic"
23
+ protocol = (config.format or "openai") if provider == "router" else provider
24
+ if protocol not in {"openai", "codex", "anthropic"}:
25
+ raise ModelDiscoveryError("此配置组暂不支持获取模型列表,请手动添加模型")
26
+ anthropic = protocol == "anthropic"
27
+ key = env.get(config.api_key_env or "") or env.get(
28
+ "ANTHROPIC_API_KEY" if anthropic else "OPENAI_API_KEY"
29
+ )
30
+ base = config.base_url or env.get(
31
+ "ANTHROPIC_BASE_URL" if anthropic else "OPENAI_BASE_URL"
32
+ )
33
+ if protocol == "codex" and not config.base_url and not key:
34
+ raise ModelDiscoveryError("Codex 登录认证暂不支持获取模型列表,请使用配置了 API 地址的组或手动添加")
35
+ base = base or ("https://api.anthropic.com" if anthropic else "https://api.openai.com/v1")
36
+ try:
37
+ url = urlsplit(base.strip())
38
+ if url.scheme not in {"http", "https"} or not url.hostname or url.username or url.password or url.query or url.fragment:
39
+ raise ValueError
40
+ _ = url.port
41
+ except ValueError:
42
+ raise ModelDiscoveryError("请为配置组填写有效的 HTTP(S) Base URL(不含账号密码、查询参数或片段)") from None
43
+ path = url.path.rstrip("/")
44
+ if anthropic and not path.endswith("/v1"):
45
+ path += "/v1"
46
+ elif not path:
47
+ path = "/v1"
48
+ endpoint = urlunsplit((url.scheme, url.netloc, path + "/models", "", ""))
49
+ headers = httpx.Headers({"accept": "application/json"})
50
+ if anthropic:
51
+ headers["anthropic-version"] = "2023-06-01"
52
+ if key:
53
+ headers["x-api-key"] = key
54
+ elif env.get("ANTHROPIC_AUTH_TOKEN"):
55
+ headers["authorization"] = f"Bearer {env['ANTHROPIC_AUTH_TOKEN']}"
56
+ elif key:
57
+ headers["authorization"] = f"Bearer {key}"
58
+ if not anthropic:
59
+ for variable, header in (("OPENAI_ORG_ID", "OpenAI-Organization"), ("OPENAI_PROJECT_ID", "OpenAI-Project")):
60
+ if env.get(variable):
61
+ headers[header] = env[variable]
62
+ headers.update(config.http_headers)
63
+ return endpoint, headers, anthropic
64
+
65
+
66
+ async def _fetch(config: ApiConfig, env: Mapping[str, str]) -> list[dict[str, str]]:
67
+ endpoint, headers, anthropic = _connection(config, env)
68
+ models: dict[str, dict[str, str]] = {}
69
+ cursors: set[str] = set()
70
+ params: dict[str, str | int] = {"limit": 1000} if anthropic else {}
71
+ remaining_bytes = 4 * 1024 * 1024
72
+ async with httpx.AsyncClient(
73
+ **http_options(config), timeout=15, follow_redirects=False,
74
+ ) as client:
75
+ for _ in range(50):
76
+ async with client.stream("GET", endpoint, headers=headers, params=params) as response:
77
+ response.raise_for_status()
78
+ chunks = []
79
+ async for chunk in response.aiter_bytes():
80
+ remaining_bytes -= len(chunk)
81
+ if remaining_bytes < 0:
82
+ raise ModelDiscoveryError("模型列表过大,请缩小服务端返回范围后重试")
83
+ chunks.append(chunk)
84
+ try:
85
+ payload = json.loads(b"".join(chunks))
86
+ except (ValueError, UnicodeError):
87
+ raise ModelDiscoveryError("接口没有返回有效的模型列表,请检查 Base URL 是否指向 API") from None
88
+ entries = payload.get("data") if isinstance(payload, dict) else None
89
+ if not isinstance(entries, list):
90
+ raise ModelDiscoveryError("接口没有返回有效的模型列表,请检查 Base URL 是否指向 API")
91
+ for entry in entries:
92
+ model_id = entry.get("id") if isinstance(entry, dict) else None
93
+ if not isinstance(model_id, str) or not model_id.strip() or len(model_id) > 512 or any(ord(char) < 32 for char in model_id):
94
+ raise ModelDiscoveryError("模型列表包含无效的模型 ID,请检查服务端响应")
95
+ model_id = model_id.strip()
96
+ model = {"id": model_id}
97
+ display_name = entry.get("display_name")
98
+ if isinstance(display_name, str) and display_name.strip():
99
+ model["name"] = display_name.strip()[:512]
100
+ models.setdefault(model_id, model)
101
+ if len(models) > 5000:
102
+ raise ModelDiscoveryError("模型列表过大,请缩小服务端返回范围后重试")
103
+ if not payload.get("has_more"):
104
+ return sorted(models.values(), key=lambda model: model["id"].casefold())
105
+ cursor = payload.get("last_id")
106
+ if not isinstance(cursor, str) or not cursor or cursor in cursors:
107
+ raise ModelDiscoveryError("模型列表分页无效,请检查服务端响应")
108
+ cursors.add(cursor)
109
+ params["after_id" if anthropic else "after"] = cursor
110
+ raise ModelDiscoveryError("模型列表分页过多,请缩小服务端返回范围后重试")
111
+
112
+
113
+ async def discover_models(config: ApiConfig, settings_env: Mapping[str, str] | None = None) -> list[dict[str, str]]:
114
+ try:
115
+ # Match session initialization's setdefault precedence without mutating
116
+ # the Gateway environment or requiring an initialized chat session.
117
+ env = {**(settings_env or {}), **os.environ}
118
+ return await asyncio.wait_for(_fetch(config, env), timeout=15)
119
+ except ModelDiscoveryError:
120
+ raise
121
+ except httpx.HTTPStatusError as exc:
122
+ status = exc.response.status_code
123
+ reason = {
124
+ 401: "认证失败,请检查配置组的 API Key 或认证请求头",
125
+ 403: "没有获取模型列表的权限,请检查密钥权限",
126
+ 404: "服务未提供模型列表接口,请检查 Base URL 或手动添加模型",
127
+ 405: "服务未提供模型列表接口,请手动添加模型",
128
+ 429: "请求过于频繁,请稍后重试",
129
+ }.get(status, "获取模型列表失败,请检查服务状态与 API 地址")
130
+ raise ModelDiscoveryError(f"HTTP {status}:{reason}") from None
131
+ except (TimeoutError, httpx.TimeoutException):
132
+ raise ModelDiscoveryError("获取模型列表超时(最多 15 秒),请检查网络和代理") from None
133
+ except Exception as exc:
134
+ if certificate_failure(exc):
135
+ raise ModelDiscoveryError("证书校验失败,请检查证书或网络拦截") from None
136
+ raise ModelDiscoveryError("获取模型列表失败,请检查配置组的 API 地址、认证信息和网络策略") from None
@@ -100,14 +100,17 @@ KNOWN_CONTEXT_WINDOWS: dict[str, int] = {
100
100
  "grok-build-0.1": 256_000,
101
101
  "grok-code-fast": 256_000,
102
102
  # DeepSeek
103
- "deepseek-flash": 1_000_000,
104
- "deepseek-v4-pro": 1_000_000,
105
- "deepseek-v4-flash": 1_000_000,
106
- "deepseek-v4.1": 1_000_000,
103
+ # Official /models metadata: https://api-docs.deepseek.com/api/list-models/
104
+ # deepseek-flash currently serves DeepSeek-V4.1-Flash-1017.
105
+ "deepseek-flash": 1_048_576,
106
+ "deepseek-v4.1-flash-1017": 1_048_576,
107
+ "deepseek-v4.1-flash": 1_048_576,
108
+ "deepseek-v4.1": 1_048_576,
109
+ "deepseek-v4-pro": 1_048_576,
110
+ "deepseek-v4-flash": 1_048_576,
107
111
  "deep-research-preview-04-2026": 1_048_576,
108
112
  "deep-research-max-preview-04-2026": 1_048_576,
109
113
  "antigravity-preview-09-2026": 1_048_576,
110
- "deepseek-v4.1-flash": 1_000_000,
111
114
  "deepseek-chat": 128_000,
112
115
  "deepseek-reasoner": 128_000,
113
116
  # GLM (Zhipu)
@@ -127,6 +130,8 @@ KNOWN_CONTEXT_WINDOWS: dict[str, int] = {
127
130
  "qwen3.6-flash": 1_000_000,
128
131
  "qwen3.5-plus": 1_000_000,
129
132
  "qwen3.5-flash": 1_000_000,
133
+ "kimi-k3.1-pro-highspeed": 1_000_000,
134
+ "kimi-k3.1-pro": 1_000_000,
130
135
  "kimi-k3": 1_000_000,
131
136
  "kimi-k2.7-code": 262_144,
132
137
  "kimi-k2.6": 262_144,
@@ -213,6 +218,7 @@ KNOWN_CONTEXT_WINDOWS: dict[str, int] = {
213
218
  "mistral": 32_000,
214
219
  "mixtral": 32_000,
215
220
  # Gemini
221
+ "gemini-4-argon": 1_048_576,
216
222
  "gemini-3.8-live-extended-thinking": 131_072,
217
223
  "gemini-3.8-live": 131_072,
218
224
  "gemini-3.8-flash": 1_048_576,
@@ -61,6 +61,27 @@ class ModelTestRequest(BaseModel):
61
61
  cwd: str | None = None
62
62
 
63
63
 
64
+ class GroupModelsRequest(BaseModel):
65
+ group: str
66
+ cwd: str | None = None
67
+
68
+
69
+ @router.post("/config/discover-models")
70
+ async def discover_group_models(req: GroupModelsRequest, request: Request) -> dict[str, Any]:
71
+ from crabcode_core.api.model_discovery import ModelDiscoveryError, discover_models
72
+
73
+ cwd = _resolve_model_settings_cwd(request, req.cwd)
74
+ settings = ConfigManager(cwd=cwd).load()
75
+ config = settings.groups.get(req.group)
76
+ if config is None:
77
+ raise HTTPException(status_code=404, detail="配置组不存在,请刷新模型目录")
78
+ try:
79
+ models = await discover_models(config, settings.env)
80
+ except ModelDiscoveryError as exc:
81
+ raise HTTPException(status_code=400, detail=str(exc)) from None
82
+ return {"group": req.group, "models": models}
83
+
84
+
64
85
  def _model_test_error(exc: Exception) -> str:
65
86
  # Do not return raw provider messages: they may contain keys, headers or URLs.
66
87
  from crabcode_core.api.network import certificate_failure
@@ -603,7 +624,39 @@ def _mutate_model_settings(request: Request, req: ModelSettingsMutationRequest)
603
624
  current = _read_settings_object(path)
604
625
  action = req.action
605
626
 
606
- if action in {"upsert_model", "delete_model"}:
627
+ if action == "import_group_models":
628
+ import re
629
+
630
+ name = _validate_model_settings_name(req.name)
631
+ preview = _model_settings_from_files(cwd)
632
+ if name not in preview.groups:
633
+ raise HTTPException(status_code=404, detail="配置组不存在,请刷新模型目录")
634
+ models = current.setdefault("models", {})
635
+ if not isinstance(models, dict):
636
+ raise HTTPException(status_code=422, detail="models must be a JSON object")
637
+ existing_ids = {
638
+ model.effective.get("model") for model in preview.models if model.group == name
639
+ }
640
+ used_names = {model.name for model in preview.models} | set(models)
641
+ for model_id in dict.fromkeys(value.strip() for value in req.model_ids):
642
+ if model_id in existing_ids:
643
+ continue
644
+ # Profile names cannot contain slashes; the API ID remains exact.
645
+ stem = re.sub(r"[/\\\x00-\x1f]", "-", model_id)[:120].strip()
646
+ if stem in {".", ".."}:
647
+ stem = "model"
648
+ candidate = stem
649
+ if candidate in used_names:
650
+ stem = f"{name} - {stem}"[:120]
651
+ candidate = stem
652
+ suffix = 2
653
+ while candidate in used_names:
654
+ tail = f" ({suffix})"
655
+ candidate = stem[:120 - len(tail)] + tail
656
+ suffix += 1
657
+ models[candidate] = {"group": name, "model": model_id}
658
+ used_names.add(candidate)
659
+ elif action in {"upsert_model", "delete_model"}:
607
660
  name = _validate_model_settings_name(req.name)
608
661
  models = current.get("models")
609
662
  if models is None:
@@ -287,6 +287,7 @@ class ModelSettingsMutationRequest(BaseModel):
287
287
  "delete_group",
288
288
  "set_default_model",
289
289
  "clear_default_model",
290
+ "import_group_models",
290
291
  ]
291
292
  source: Literal["userSettings", "projectSettings", "localSettings"] = "projectSettings"
292
293
  cwd: str | None = None
@@ -294,6 +295,7 @@ class ModelSettingsMutationRequest(BaseModel):
294
295
  previous_name: str | None = None
295
296
  config: dict[str, Any] | None = None
296
297
  remove_fields: list[str] = Field(default_factory=list)
298
+ model_ids: list[str] = Field(default_factory=list, max_length=1000)
297
299
 
298
300
  @model_validator(mode="after")
299
301
  def validate_mutation(self) -> "ModelSettingsMutationRequest":
@@ -302,6 +304,12 @@ class ModelSettingsMutationRequest(BaseModel):
302
304
  raise ValueError("name is required for this model settings action")
303
305
  if self.action in {"upsert_model", "upsert_group"} and self.config is None:
304
306
  raise ValueError("config is required when creating or updating settings")
307
+ if self.action == "import_group_models":
308
+ if not self.model_ids or any(
309
+ not value.strip() or len(value) > 512 or any(ord(char) < 32 for char in value)
310
+ for value in self.model_ids
311
+ ):
312
+ raise ValueError("Select valid model IDs to add to the group")
305
313
  if self.name is not None:
306
314
  self.name = self.name.strip()
307
315
  return self