txcode-sdk 0.4.1__py3-none-any.whl → 0.5.0__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.
- txcode_sdk/client.py +5 -0
- txcode_sdk/server/config_store.py +39 -0
- txcode_sdk/server/handler.py +42 -13
- txcode_sdk/server/http.py +469 -4
- txcode_sdk/server/hub_client.py +139 -0
- txcode_sdk/server/plan_code.py +234 -0
- txcode_sdk/server/server.py +19 -0
- txcode_sdk/server/skill_manager.py +148 -0
- txcode_sdk/server/spec_manager.py +121 -0
- txcode_sdk/server/zip_utils.py +42 -0
- txcode_sdk/session/manager.py +50 -1
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/METADATA +1 -1
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/RECORD +17 -11
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/WHEEL +0 -0
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/entry_points.txt +0 -0
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/licenses/LICENSE +0 -0
- {txcode_sdk-0.4.1.dist-info → txcode_sdk-0.5.0.dist-info}/top_level.txt +0 -0
txcode_sdk/client.py
CHANGED
|
@@ -68,6 +68,11 @@ class TxCodeClient:
|
|
|
68
68
|
def work_dir(self) -> str:
|
|
69
69
|
return self._work_dir
|
|
70
70
|
|
|
71
|
+
@property
|
|
72
|
+
def session_manager(self) -> SessionManager:
|
|
73
|
+
"""当前 SessionManager(set_work_dir 重建后仍指向最新实例)。"""
|
|
74
|
+
return self._session_manager
|
|
75
|
+
|
|
71
76
|
def get_model(self) -> str:
|
|
72
77
|
return self._model
|
|
73
78
|
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""ConfigStore:通用 KV 配置存储(`~/.txcode/config.json`,用户级,跨项目共享)。
|
|
2
|
+
|
|
3
|
+
与 TS 版 configService 对齐:字符串值原样存取,非字符串 JSON 序列化。
|
|
4
|
+
复用 JsonStore(asyncio.Lock + 原子写),Python 3.6 兼容,零第三方依赖。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from .json_store import JsonStore
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConfigStore:
|
|
14
|
+
"""通用 KV 配置:~/.txcode/config.json(用户级,跨项目共享)。"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, path: str = "~/.txcode/config.json"):
|
|
17
|
+
self._store = JsonStore(os.path.expanduser(path))
|
|
18
|
+
|
|
19
|
+
def get(self, key: str):
|
|
20
|
+
"""不存在返回 None;值为字符串原样返回,否则返回 JSON 对象。"""
|
|
21
|
+
data = self._store.load({})
|
|
22
|
+
value = data.get(key)
|
|
23
|
+
if value is None:
|
|
24
|
+
return None
|
|
25
|
+
if isinstance(value, str):
|
|
26
|
+
return value
|
|
27
|
+
try:
|
|
28
|
+
return json.loads(value)
|
|
29
|
+
except (TypeError, ValueError):
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
async def set(self, key: str, value):
|
|
33
|
+
"""value 为字符串原样存,否则 json.dumps;原子写。"""
|
|
34
|
+
data = self._store.load({})
|
|
35
|
+
if isinstance(value, str):
|
|
36
|
+
data[key] = value
|
|
37
|
+
else:
|
|
38
|
+
data[key] = json.dumps(value, ensure_ascii=False)
|
|
39
|
+
await self._store.save(data)
|
txcode_sdk/server/handler.py
CHANGED
|
@@ -12,6 +12,7 @@ import os
|
|
|
12
12
|
from typing import Any, Dict, Optional, Set
|
|
13
13
|
|
|
14
14
|
from ..types import MediaFile, StepInfo
|
|
15
|
+
from .config_store import ConfigStore
|
|
15
16
|
from .provider_config import ProviderConfigManager
|
|
16
17
|
from .project_manager import ProjectManager
|
|
17
18
|
from .websocket import OPCODE_TEXT, build_close_frame, build_frame, read_message
|
|
@@ -66,10 +67,11 @@ def _usage_to_desktop(usage) -> Optional[dict]:
|
|
|
66
67
|
|
|
67
68
|
|
|
68
69
|
class CodeWebSocketHandler:
|
|
69
|
-
def __init__(self, client, provider_config=None, project_manager=None):
|
|
70
|
+
def __init__(self, client, provider_config=None, project_manager=None, config_store=None):
|
|
70
71
|
self._client = client
|
|
71
72
|
self._provider_config = provider_config or ProviderConfigManager()
|
|
72
73
|
self._project_manager = project_manager or ProjectManager()
|
|
74
|
+
self._config_store = config_store or ConfigStore()
|
|
73
75
|
self._writers: Set = set()
|
|
74
76
|
self._abort_signals: Dict[str, AbortSignal] = {}
|
|
75
77
|
self._running: Set[str] = set()
|
|
@@ -194,25 +196,29 @@ class CodeWebSocketHandler:
|
|
|
194
196
|
self.broadcast({"type": "error", "error": "sessionId is required"})
|
|
195
197
|
return
|
|
196
198
|
|
|
199
|
+
# ① 携带 modelName → 优先解析激活(_apply_model_name 内部 resolve + switch + client.set_provider)
|
|
200
|
+
model_name = data.get("modelName")
|
|
201
|
+
if model_name:
|
|
202
|
+
ok = await self._apply_model_name(model_name, session_id)
|
|
203
|
+
if not ok:
|
|
204
|
+
return
|
|
205
|
+
|
|
206
|
+
# ② 无 modelName → 从 KV defaultModel 兜底激活
|
|
197
207
|
active_provider, _ = self._provider_config.get_active()
|
|
198
208
|
if not active_provider:
|
|
199
|
-
self.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
209
|
+
ok = await self._ensure_default_provider()
|
|
210
|
+
if not ok:
|
|
211
|
+
self.broadcast({
|
|
212
|
+
"type": "error",
|
|
213
|
+
"sessionId": session_id,
|
|
214
|
+
"error": "No active provider configured, please add provider first",
|
|
215
|
+
})
|
|
216
|
+
return
|
|
205
217
|
|
|
206
218
|
message = data.get("message", "")
|
|
207
219
|
agent_type = data.get("agent") or "code"
|
|
208
220
|
media_files = data.get("mediaFiles") or []
|
|
209
221
|
|
|
210
|
-
model_name = data.get("modelName")
|
|
211
|
-
if model_name:
|
|
212
|
-
ok = await self._apply_model_name(model_name, session_id)
|
|
213
|
-
if not ok:
|
|
214
|
-
return
|
|
215
|
-
|
|
216
222
|
existing = self._abort_signals.get(session_id)
|
|
217
223
|
if existing:
|
|
218
224
|
existing.abort()
|
|
@@ -302,6 +308,29 @@ class CodeWebSocketHandler:
|
|
|
302
308
|
|
|
303
309
|
# ---------- 供应商 / 模型 ----------
|
|
304
310
|
|
|
311
|
+
async def _ensure_default_provider(self) -> bool:
|
|
312
|
+
"""KV defaultModel → resolve_model → switch 激活 + 同步 client。成功返回 True。"""
|
|
313
|
+
model_name = self._config_store.get("defaultModel")
|
|
314
|
+
if not model_name:
|
|
315
|
+
return False
|
|
316
|
+
resolved = self._provider_config.resolve_model(model_name)
|
|
317
|
+
if resolved is None:
|
|
318
|
+
return False
|
|
319
|
+
provider_id, resolved_model = resolved
|
|
320
|
+
provider = self._provider_config.get_provider(provider_id)
|
|
321
|
+
if not provider:
|
|
322
|
+
return False
|
|
323
|
+
await self._provider_config.switch(provider_id, resolved_model)
|
|
324
|
+
self._client.set_provider(
|
|
325
|
+
provider.get("api_key", ""), provider.get("base_url", ""), resolved_model
|
|
326
|
+
)
|
|
327
|
+
self.broadcast({"type": "model_changed", "data": {
|
|
328
|
+
"providerName": provider.get("name", ""),
|
|
329
|
+
"modelName": model_name,
|
|
330
|
+
"model": resolved_model,
|
|
331
|
+
}})
|
|
332
|
+
return True
|
|
333
|
+
|
|
305
334
|
async def _apply_model_name(self, model_name: str, session_id: str) -> bool:
|
|
306
335
|
"""chat.modelName 解析:命中 → 切换供应商/模型 + 广播 model_changed;未命中 → error。"""
|
|
307
336
|
resolved = self._provider_config.resolve_model(model_name)
|
txcode_sdk/server/http.py
CHANGED
|
@@ -15,6 +15,8 @@ import os
|
|
|
15
15
|
from typing import Dict, List, Optional, Tuple
|
|
16
16
|
from urllib.parse import unquote
|
|
17
17
|
|
|
18
|
+
from ..session.manager import SessionManager
|
|
19
|
+
from .config_store import ConfigStore
|
|
18
20
|
from .project_manager import ProjectManager
|
|
19
21
|
from .provider_config import ProviderConfigManager, is_masked_api_key, mask_api_key
|
|
20
22
|
|
|
@@ -164,11 +166,27 @@ class HttpApiHandler:
|
|
|
164
166
|
保证 HTTP 与 WS 客户端状态一致(多端联动)。
|
|
165
167
|
"""
|
|
166
168
|
|
|
167
|
-
def __init__(
|
|
169
|
+
def __init__(
|
|
170
|
+
self,
|
|
171
|
+
client=None,
|
|
172
|
+
provider_config=None,
|
|
173
|
+
project_manager=None,
|
|
174
|
+
ws_handler=None,
|
|
175
|
+
plan_code_manager=None,
|
|
176
|
+
skill_manager=None,
|
|
177
|
+
spec_manager=None,
|
|
178
|
+
hub_client=None,
|
|
179
|
+
config_store=None,
|
|
180
|
+
):
|
|
168
181
|
self._client = client
|
|
169
182
|
self._provider_config = provider_config or ProviderConfigManager()
|
|
170
183
|
self._project_manager = project_manager or ProjectManager()
|
|
171
184
|
self._ws_handler = ws_handler
|
|
185
|
+
self._plan_code = plan_code_manager
|
|
186
|
+
self._skill_mgr = skill_manager
|
|
187
|
+
self._spec_mgr = spec_manager
|
|
188
|
+
self._hub = hub_client
|
|
189
|
+
self._config_store = config_store or ConfigStore()
|
|
172
190
|
|
|
173
191
|
# ---------- 入口 ----------
|
|
174
192
|
|
|
@@ -177,6 +195,8 @@ class HttpApiHandler:
|
|
|
177
195
|
status, payload = await self._route(request)
|
|
178
196
|
except ValueError as exc:
|
|
179
197
|
status, payload = 400, {"success": False, "error": str(exc)}
|
|
198
|
+
except Exception as exc:
|
|
199
|
+
status, payload = 500, {"success": False, "error": str(exc)}
|
|
180
200
|
try:
|
|
181
201
|
writer.write(build_json_response(status, payload))
|
|
182
202
|
await writer.drain()
|
|
@@ -189,6 +209,31 @@ class HttpApiHandler:
|
|
|
189
209
|
method = request.method
|
|
190
210
|
path = request.path
|
|
191
211
|
|
|
212
|
+
if path.startswith("/api/plan-code/"):
|
|
213
|
+
result = self._route_plan_code(request)
|
|
214
|
+
if result is not None:
|
|
215
|
+
return result
|
|
216
|
+
elif path.startswith("/api/session/"):
|
|
217
|
+
result = self._route_session(request)
|
|
218
|
+
if result is not None:
|
|
219
|
+
return result
|
|
220
|
+
elif path.startswith("/api/skill/"):
|
|
221
|
+
result = self._route_skill(request)
|
|
222
|
+
if result is not None:
|
|
223
|
+
return result
|
|
224
|
+
elif path.startswith("/api/spec/"):
|
|
225
|
+
result = self._route_spec(request)
|
|
226
|
+
if result is not None:
|
|
227
|
+
return result
|
|
228
|
+
elif path.startswith("/api/file/"):
|
|
229
|
+
result = self._route_file(request)
|
|
230
|
+
if result is not None:
|
|
231
|
+
return result
|
|
232
|
+
elif path.startswith("/api/chat/"):
|
|
233
|
+
result = self._route_chat(request)
|
|
234
|
+
if result is not None:
|
|
235
|
+
return result
|
|
236
|
+
|
|
192
237
|
if method == "GET":
|
|
193
238
|
if path == "/api/sys_config/get_config":
|
|
194
239
|
return self._get_config(request)
|
|
@@ -207,6 +252,8 @@ class HttpApiHandler:
|
|
|
207
252
|
if path == "/api/project/current_project":
|
|
208
253
|
return self._current_project()
|
|
209
254
|
elif method == "POST":
|
|
255
|
+
if path == "/api/sys_config/set_config":
|
|
256
|
+
return await self._set_config(request)
|
|
210
257
|
if path == "/api/sys_config/create_provider_config":
|
|
211
258
|
return await self._create_provider(request)
|
|
212
259
|
if path == "/api/sys_config/update_provider_config":
|
|
@@ -234,18 +281,436 @@ class HttpApiHandler:
|
|
|
234
281
|
|
|
235
282
|
return 404, {"success": False, "error": "Not Found"}
|
|
236
283
|
|
|
237
|
-
# ----------
|
|
284
|
+
# ---------- plan-code(编码会话) ----------
|
|
285
|
+
|
|
286
|
+
def _require_plan_code(self):
|
|
287
|
+
if self._plan_code is None:
|
|
288
|
+
raise ValueError("plan-code manager not configured")
|
|
289
|
+
return self._plan_code
|
|
290
|
+
|
|
291
|
+
def _route_plan_code(self, request: HttpRequest):
|
|
292
|
+
path = request.path
|
|
293
|
+
if request.method == "GET":
|
|
294
|
+
if path == "/api/plan-code/list":
|
|
295
|
+
return 200, {"success": True, "data": self._require_plan_code().list()}
|
|
296
|
+
if path == "/api/plan-code/detail":
|
|
297
|
+
folder = request.query.get("folderName", "")
|
|
298
|
+
if not folder:
|
|
299
|
+
raise ValueError("folderName 必填")
|
|
300
|
+
session = self._require_plan_code().detail(folder)
|
|
301
|
+
if session is None:
|
|
302
|
+
return 404, {"success": False, "error": "会话不存在"}
|
|
303
|
+
return 200, {"success": True, "data": session}
|
|
304
|
+
if path == "/api/plan-code/read-plan":
|
|
305
|
+
folder = request.query.get("folderName", "")
|
|
306
|
+
if not folder:
|
|
307
|
+
raise ValueError("folderName 必填")
|
|
308
|
+
content = self._require_plan_code().read_plan(folder)
|
|
309
|
+
return 200, {"success": True, "data": {"content": content}}
|
|
310
|
+
elif request.method == "POST":
|
|
311
|
+
body = parse_json_body(request)
|
|
312
|
+
if path == "/api/plan-code/create":
|
|
313
|
+
session_name = body.get("sessionName")
|
|
314
|
+
if not session_name:
|
|
315
|
+
raise ValueError("sessionName 必填")
|
|
316
|
+
parent = body.get("parentPlanPath")
|
|
317
|
+
session = self._require_plan_code().create(session_name, parent or None)
|
|
318
|
+
return 201, {"success": True, "data": session}
|
|
319
|
+
if path == "/api/plan-code/update":
|
|
320
|
+
folder = body.get("folderName")
|
|
321
|
+
session_name = body.get("sessionName")
|
|
322
|
+
if not folder or not session_name:
|
|
323
|
+
raise ValueError("folderName 和 sessionName 必填")
|
|
324
|
+
session = self._require_plan_code().rename_session(folder, session_name)
|
|
325
|
+
return 200, {"success": True, "data": session}
|
|
326
|
+
if path == "/api/plan-code/delete":
|
|
327
|
+
folder = body.get("folderName")
|
|
328
|
+
if not folder:
|
|
329
|
+
raise ValueError("folderName 必填")
|
|
330
|
+
self._require_plan_code().delete(folder)
|
|
331
|
+
return 200, {"success": True, "message": "删除成功"}
|
|
332
|
+
if path == "/api/plan-code/save-meta":
|
|
333
|
+
folder = body.get("folderName")
|
|
334
|
+
meta = body.get("meta")
|
|
335
|
+
if not folder or not isinstance(meta, dict):
|
|
336
|
+
raise ValueError("folderName 和 meta 必填")
|
|
337
|
+
self._require_plan_code().save_meta(folder, meta)
|
|
338
|
+
return 200, {"success": True, "message": "保存成功"}
|
|
339
|
+
if path == "/api/plan-code/save-plan":
|
|
340
|
+
folder = body.get("folderName")
|
|
341
|
+
if not folder:
|
|
342
|
+
raise ValueError("folderName 必填")
|
|
343
|
+
self._require_plan_code().save_plan(folder, body.get("content") or "")
|
|
344
|
+
return 200, {"success": True, "message": "保存成功"}
|
|
345
|
+
return None
|
|
346
|
+
|
|
347
|
+
# ---------- session ----------
|
|
348
|
+
|
|
349
|
+
def _session_manager(self) -> SessionManager:
|
|
350
|
+
if self._client is not None:
|
|
351
|
+
sm = getattr(self._client, "session_manager", None)
|
|
352
|
+
if sm is not None:
|
|
353
|
+
return sm
|
|
354
|
+
return SessionManager(self._current_project_path())
|
|
355
|
+
|
|
356
|
+
def _route_session(self, request: HttpRequest):
|
|
357
|
+
path = request.path
|
|
358
|
+
sm = self._session_manager()
|
|
359
|
+
if request.method == "GET":
|
|
360
|
+
if path == "/api/session/list_session":
|
|
361
|
+
try:
|
|
362
|
+
limit = int(request.query.get("limit", "20") or "20")
|
|
363
|
+
except ValueError:
|
|
364
|
+
limit = 20
|
|
365
|
+
limit = max(0, min(limit, 100))
|
|
366
|
+
try:
|
|
367
|
+
offset = int(request.query.get("offset", "0") or "0")
|
|
368
|
+
except ValueError:
|
|
369
|
+
offset = 0
|
|
370
|
+
offset = max(0, offset)
|
|
371
|
+
sessions = sm.list_by_project(self._current_project_path(), limit, offset)
|
|
372
|
+
data = [SessionManager.session_dto(s) for s in sessions]
|
|
373
|
+
return 200, {"success": True, "data": data}
|
|
374
|
+
if path == "/api/session/detail_session":
|
|
375
|
+
sid = request.query.get("id", "")
|
|
376
|
+
if not sid:
|
|
377
|
+
raise ValueError("id 必填")
|
|
378
|
+
session = sm.get(sid)
|
|
379
|
+
if session is None:
|
|
380
|
+
return 404, {"success": False, "error": "Session not found"}
|
|
381
|
+
return 200, {"success": True, "data": SessionManager.session_dto(session)}
|
|
382
|
+
elif request.method == "POST":
|
|
383
|
+
body = parse_json_body(request)
|
|
384
|
+
if path == "/api/session/create_session":
|
|
385
|
+
title = body.get("title") or ""
|
|
386
|
+
project_path = body.get("projectPath") or self._current_project_path()
|
|
387
|
+
session = sm.create(title=title, project_path=project_path)
|
|
388
|
+
return 201, {"success": True, "data": SessionManager.session_dto(session)}
|
|
389
|
+
if path == "/api/session/update_session":
|
|
390
|
+
sid = body.get("id")
|
|
391
|
+
if not sid:
|
|
392
|
+
raise ValueError("id 必填")
|
|
393
|
+
fields = {}
|
|
394
|
+
if "title" in body:
|
|
395
|
+
fields["title"] = body["title"]
|
|
396
|
+
if "projectPath" in body and body["projectPath"] is not None:
|
|
397
|
+
fields["project_path"] = body["projectPath"]
|
|
398
|
+
session = sm.update(sid, **fields)
|
|
399
|
+
if session is None:
|
|
400
|
+
return 404, {"success": False, "error": "Session not found"}
|
|
401
|
+
return 200, {"success": True, "data": SessionManager.session_dto(session)}
|
|
402
|
+
if path == "/api/session/delete_session":
|
|
403
|
+
sid = body.get("id")
|
|
404
|
+
if not sid:
|
|
405
|
+
raise ValueError("id 必填")
|
|
406
|
+
sm.delete(sid)
|
|
407
|
+
return 200, {"success": True}
|
|
408
|
+
return None
|
|
409
|
+
|
|
410
|
+
# ---------- skill ----------
|
|
411
|
+
|
|
412
|
+
def _current_project_path(self) -> str:
|
|
413
|
+
current = self._project_manager.get_current()
|
|
414
|
+
if current and current.get("path"):
|
|
415
|
+
return current["path"]
|
|
416
|
+
if self._client is not None and getattr(self._client, "work_dir", ""):
|
|
417
|
+
return self._client.work_dir
|
|
418
|
+
return os.getcwd()
|
|
419
|
+
|
|
420
|
+
def _hub_json(self, fn):
|
|
421
|
+
try:
|
|
422
|
+
data = fn()
|
|
423
|
+
except Exception as exc:
|
|
424
|
+
return 500, {"success": False, "error": str(exc) or "hub 请求失败"}
|
|
425
|
+
return 200, {"success": True, "data": data}
|
|
426
|
+
|
|
427
|
+
@staticmethod
|
|
428
|
+
def _published_params(request: HttpRequest, keys: Tuple[str, ...]) -> dict:
|
|
429
|
+
params = {}
|
|
430
|
+
for key in keys:
|
|
431
|
+
value = request.query.get(key)
|
|
432
|
+
if value is not None and value != "":
|
|
433
|
+
params[key] = value
|
|
434
|
+
return params
|
|
435
|
+
|
|
436
|
+
def _local_skills(self, request: HttpRequest = None) -> list:
|
|
437
|
+
if self._skill_mgr is None:
|
|
438
|
+
raise ValueError("skill manager not configured")
|
|
439
|
+
project_path = None
|
|
440
|
+
if request is not None:
|
|
441
|
+
project_path = request.query.get("projectPath") or None
|
|
442
|
+
self._skill_mgr.set_project_path(project_path or self._current_project_path())
|
|
443
|
+
return [
|
|
444
|
+
{"name": s["name"], "description": s["description"], "filePath": s["filePath"]}
|
|
445
|
+
for s in self._skill_mgr.get_local_skills()
|
|
446
|
+
]
|
|
447
|
+
|
|
448
|
+
def _route_skill(self, request: HttpRequest):
|
|
449
|
+
path = request.path
|
|
450
|
+
if request.method == "GET":
|
|
451
|
+
if path == "/api/skill/list_skill":
|
|
452
|
+
return 200, {"success": True, "data": self._local_skills()}
|
|
453
|
+
if path == "/api/skill/local_skill":
|
|
454
|
+
return 200, {"success": True, "data": self._local_skills(request)}
|
|
455
|
+
if path == "/api/skill/categories":
|
|
456
|
+
if self._hub is None:
|
|
457
|
+
raise ValueError("hub client not configured")
|
|
458
|
+
return self._hub_json(lambda: self._hub.fetch_categories())
|
|
459
|
+
if path == "/api/skill/published":
|
|
460
|
+
if self._hub is None:
|
|
461
|
+
raise ValueError("hub client not configured")
|
|
462
|
+
params = self._published_params(request, ("page", "page_size", "keyword", "category_id"))
|
|
463
|
+
return self._hub_json(lambda: self._hub.fetch_published_skills(params))
|
|
464
|
+
if path == "/api/skill/detail_skill":
|
|
465
|
+
name = request.query.get("name", "")
|
|
466
|
+
if not name:
|
|
467
|
+
raise ValueError("name 必填")
|
|
468
|
+
if self._skill_mgr is None:
|
|
469
|
+
raise ValueError("skill manager not configured")
|
|
470
|
+
self._skill_mgr.set_project_path(self._current_project_path())
|
|
471
|
+
content = self._skill_mgr.get_skill_content(name)
|
|
472
|
+
if content is None:
|
|
473
|
+
return 404, {"success": False, "error": "Skill not found"}
|
|
474
|
+
return 200, {"success": True, "data": content}
|
|
475
|
+
elif request.method == "POST":
|
|
476
|
+
body = parse_json_body(request)
|
|
477
|
+
if path == "/api/skill/install":
|
|
478
|
+
skill_id = body.get("skillId")
|
|
479
|
+
skill_name = body.get("skillName")
|
|
480
|
+
if not skill_id or not skill_name:
|
|
481
|
+
raise ValueError("skillId 和 skillName 必填")
|
|
482
|
+
if self._skill_mgr is None:
|
|
483
|
+
raise ValueError("skill manager not configured")
|
|
484
|
+
self._skill_mgr.set_project_path(self._current_project_path())
|
|
485
|
+
try:
|
|
486
|
+
self._skill_mgr.install(skill_id, skill_name)
|
|
487
|
+
except Exception as exc:
|
|
488
|
+
return 500, {"success": False, "error": str(exc) or "安装失败"}
|
|
489
|
+
return 200, {"success": True, "message": "安装成功"}
|
|
490
|
+
if path == "/api/skill/uninstall":
|
|
491
|
+
skill_name = body.get("skillName")
|
|
492
|
+
if not skill_name:
|
|
493
|
+
raise ValueError("skillName 必填")
|
|
494
|
+
if self._skill_mgr is None:
|
|
495
|
+
raise ValueError("skill manager not configured")
|
|
496
|
+
self._skill_mgr.set_project_path(self._current_project_path())
|
|
497
|
+
ok = self._skill_mgr.delete_local_skill(skill_name)
|
|
498
|
+
if not ok:
|
|
499
|
+
return 404, {"success": False, "error": "Skill 不存在或删除失败"}
|
|
500
|
+
return 200, {"success": True, "message": "卸载成功"}
|
|
501
|
+
return None
|
|
502
|
+
|
|
503
|
+
# ---------- spec ----------
|
|
504
|
+
|
|
505
|
+
def _route_spec(self, request: HttpRequest):
|
|
506
|
+
path = request.path
|
|
507
|
+
if request.method == "GET":
|
|
508
|
+
if path == "/api/spec/categories":
|
|
509
|
+
if self._hub is None:
|
|
510
|
+
raise ValueError("hub client not configured")
|
|
511
|
+
return self._hub_json(lambda: self._hub.fetch_spec_categories())
|
|
512
|
+
if path == "/api/spec/published":
|
|
513
|
+
if self._hub is None:
|
|
514
|
+
raise ValueError("hub client not configured")
|
|
515
|
+
params = self._published_params(
|
|
516
|
+
request, ("page", "page_size", "keyword", "category_id", "platform_category")
|
|
517
|
+
)
|
|
518
|
+
return self._hub_json(lambda: self._hub.fetch_published_specs(params))
|
|
519
|
+
if path == "/api/spec/local_spec":
|
|
520
|
+
if self._spec_mgr is None:
|
|
521
|
+
raise ValueError("spec manager not configured")
|
|
522
|
+
project_path = request.query.get("projectPath") or self._current_project_path()
|
|
523
|
+
self._spec_mgr.set_project_path(project_path)
|
|
524
|
+
specs = [
|
|
525
|
+
{
|
|
526
|
+
"name": s["name"],
|
|
527
|
+
"description": s["description"],
|
|
528
|
+
"read_mode": s["read_mode"],
|
|
529
|
+
"filePath": s["filePath"],
|
|
530
|
+
}
|
|
531
|
+
for s in self._spec_mgr.get_local_specs()
|
|
532
|
+
]
|
|
533
|
+
return 200, {"success": True, "data": {"specs": specs, "projectPath": project_path}}
|
|
534
|
+
if path == "/api/spec/detail_spec":
|
|
535
|
+
name = request.query.get("name", "")
|
|
536
|
+
if not name:
|
|
537
|
+
raise ValueError("name 必填")
|
|
538
|
+
if self._spec_mgr is None:
|
|
539
|
+
raise ValueError("spec manager not configured")
|
|
540
|
+
self._spec_mgr.set_project_path(self._current_project_path())
|
|
541
|
+
content = self._spec_mgr.get_spec_content(name)
|
|
542
|
+
if content is None:
|
|
543
|
+
return 404, {"success": False, "error": "Spec not found"}
|
|
544
|
+
return 200, {"success": True, "data": content}
|
|
545
|
+
elif request.method == "POST":
|
|
546
|
+
body = parse_json_body(request)
|
|
547
|
+
if path == "/api/spec/install":
|
|
548
|
+
spec_id = body.get("specId")
|
|
549
|
+
spec_name = body.get("specName")
|
|
550
|
+
if not spec_id or not spec_name:
|
|
551
|
+
raise ValueError("specId 和 specName 必填")
|
|
552
|
+
if self._spec_mgr is None:
|
|
553
|
+
raise ValueError("spec manager not configured")
|
|
554
|
+
self._spec_mgr.set_project_path(self._current_project_path())
|
|
555
|
+
try:
|
|
556
|
+
self._spec_mgr.install(spec_id, spec_name)
|
|
557
|
+
except Exception as exc:
|
|
558
|
+
return 500, {"success": False, "error": str(exc) or "安装失败"}
|
|
559
|
+
return 200, {"success": True, "message": "安装成功"}
|
|
560
|
+
if path == "/api/spec/uninstall":
|
|
561
|
+
spec_name = body.get("specName")
|
|
562
|
+
if not spec_name:
|
|
563
|
+
raise ValueError("specName 必填")
|
|
564
|
+
if self._spec_mgr is None:
|
|
565
|
+
raise ValueError("spec manager not configured")
|
|
566
|
+
self._spec_mgr.set_project_path(self._current_project_path())
|
|
567
|
+
ok = self._spec_mgr.delete_spec(spec_name)
|
|
568
|
+
if not ok:
|
|
569
|
+
return 404, {"success": False, "error": "规范不存在或删除失败"}
|
|
570
|
+
return 200, {"success": True, "message": "卸载成功"}
|
|
571
|
+
if path == "/api/spec/delete_spec":
|
|
572
|
+
name = body.get("name")
|
|
573
|
+
if not name:
|
|
574
|
+
raise ValueError("name 必填")
|
|
575
|
+
if self._spec_mgr is None:
|
|
576
|
+
raise ValueError("spec manager not configured")
|
|
577
|
+
self._spec_mgr.set_project_path(self._current_project_path())
|
|
578
|
+
ok = self._spec_mgr.delete_spec(name)
|
|
579
|
+
if not ok:
|
|
580
|
+
return 404, {"success": False, "error": "Spec not found or delete failed"}
|
|
581
|
+
return 200, {"success": True}
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
# ---------- file ----------
|
|
585
|
+
|
|
586
|
+
def _route_file(self, request: HttpRequest):
|
|
587
|
+
path = request.path
|
|
588
|
+
if request.method == "GET":
|
|
589
|
+
if path == "/api/file/content_file":
|
|
590
|
+
return self._content_file(request)
|
|
591
|
+
return None
|
|
592
|
+
|
|
593
|
+
def _resolve_file_path(self, input_path: str) -> str:
|
|
594
|
+
"""路径解析:win32 绝对路径(盘符 C:\\ 或以 /、\\ 开头)原样;相对 → join(当前项目路径)。
|
|
595
|
+
|
|
596
|
+
与 TS 版 content_file.ts 的 `path.isAbsolute` + `path.resolve(当前项目路径)` 对齐,
|
|
597
|
+
`os.path.normpath` 归一化。
|
|
598
|
+
"""
|
|
599
|
+
if not input_path:
|
|
600
|
+
return ""
|
|
601
|
+
normalized = input_path.replace("\\", "/")
|
|
602
|
+
is_abs = (
|
|
603
|
+
len(input_path) >= 2
|
|
604
|
+
and input_path[0].isalpha()
|
|
605
|
+
and input_path[1] == ":"
|
|
606
|
+
) or normalized.startswith("/")
|
|
607
|
+
if is_abs:
|
|
608
|
+
return os.path.normpath(input_path)
|
|
609
|
+
return os.path.normpath(os.path.join(self._current_project_path(), input_path))
|
|
610
|
+
|
|
611
|
+
def _content_file(self, request: HttpRequest):
|
|
612
|
+
raw = request.query.get("path", "")
|
|
613
|
+
if not raw:
|
|
614
|
+
raise ValueError("path 必填")
|
|
615
|
+
file_path = self._resolve_file_path(raw)
|
|
616
|
+
if not os.path.isfile(file_path):
|
|
617
|
+
return 404, {"success": False, "error": "File not found"}
|
|
618
|
+
try:
|
|
619
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
620
|
+
content = f.read()
|
|
621
|
+
except Exception as exc:
|
|
622
|
+
return 500, {"success": False, "error": str(exc) or "读取文件失败"}
|
|
623
|
+
return 200, {"success": True, "data": {
|
|
624
|
+
"content": content,
|
|
625
|
+
"path": file_path.replace("\\", "/"),
|
|
626
|
+
}}
|
|
627
|
+
|
|
628
|
+
# ---------- chat ----------
|
|
629
|
+
|
|
630
|
+
def _route_chat(self, request: HttpRequest):
|
|
631
|
+
path = request.path
|
|
632
|
+
if request.method == "GET":
|
|
633
|
+
if path == "/api/chat/history_chat":
|
|
634
|
+
return self._history_chat(request)
|
|
635
|
+
return None
|
|
636
|
+
|
|
637
|
+
def _history_chat(self, request: HttpRequest):
|
|
638
|
+
session_id = request.query.get("sessionId", "")
|
|
639
|
+
if not session_id:
|
|
640
|
+
raise ValueError("sessionId 必填")
|
|
641
|
+
session = self._session_manager().get(session_id)
|
|
642
|
+
if session is None:
|
|
643
|
+
return 200, {"success": True, "data": []}
|
|
644
|
+
result = []
|
|
645
|
+
for msg in session.get("messages", []):
|
|
646
|
+
role = msg.get("role", "")
|
|
647
|
+
content = msg.get("content", "")
|
|
648
|
+
if role == "user" and msg.get("is_original"):
|
|
649
|
+
media_files = []
|
|
650
|
+
for mf in msg.get("media_files") or []:
|
|
651
|
+
media_files.append({
|
|
652
|
+
"filePath": mf.get("file_path", ""),
|
|
653
|
+
"type": mf.get("type", ""),
|
|
654
|
+
})
|
|
655
|
+
result.append({
|
|
656
|
+
"type": "chat",
|
|
657
|
+
"role": "user",
|
|
658
|
+
"content": content,
|
|
659
|
+
"mediaFiles": media_files,
|
|
660
|
+
})
|
|
661
|
+
elif role == "assistant":
|
|
662
|
+
thought = content
|
|
663
|
+
tool_calls = []
|
|
664
|
+
success = True
|
|
665
|
+
try:
|
|
666
|
+
parsed = json.loads(content)
|
|
667
|
+
except (TypeError, ValueError):
|
|
668
|
+
parsed = None
|
|
669
|
+
if isinstance(parsed, dict) and parsed.get("type") == "assistant_with_tools":
|
|
670
|
+
thought = parsed.get("thought") or ""
|
|
671
|
+
tool_calls = parsed.get("toolCalls") or []
|
|
672
|
+
success = parsed.get("success") is not False
|
|
673
|
+
result.append({
|
|
674
|
+
"type": "step",
|
|
675
|
+
"role": "assistant",
|
|
676
|
+
"thought": thought,
|
|
677
|
+
"toolCalls": tool_calls,
|
|
678
|
+
"success": success,
|
|
679
|
+
})
|
|
680
|
+
return 200, {"success": True, "data": result}
|
|
681
|
+
|
|
682
|
+
# ---------- sys_config:get_config / set_config ----------
|
|
238
683
|
|
|
239
684
|
def _get_config(self, request: HttpRequest):
|
|
240
685
|
key = request.query.get("key", "")
|
|
241
686
|
if not key:
|
|
242
687
|
raise ValueError("key 必填")
|
|
243
|
-
value =
|
|
244
|
-
if key == "defaultModel":
|
|
688
|
+
value = self._config_store.get(key)
|
|
689
|
+
if value is None and key == "defaultModel":
|
|
690
|
+
# 兼容旧逻辑:无 KV 时回退 active_model
|
|
245
691
|
_, active_model = self._provider_config.get_active()
|
|
246
692
|
value = active_model or None
|
|
247
693
|
return 200, {"success": True, "data": {"key": key, "value": value}}
|
|
248
694
|
|
|
695
|
+
async def _set_config(self, request: HttpRequest):
|
|
696
|
+
body = parse_json_body(request)
|
|
697
|
+
key = body.get("key")
|
|
698
|
+
value = body.get("value")
|
|
699
|
+
if not key:
|
|
700
|
+
raise ValueError("key 必填")
|
|
701
|
+
await self._config_store.set(key, value)
|
|
702
|
+
if key == "defaultModel" and value:
|
|
703
|
+
# 联动激活:模型命中 → switch + 同步 client + 广播 model_changed
|
|
704
|
+
resolved = self._provider_config.resolve_model(value)
|
|
705
|
+
if resolved is not None:
|
|
706
|
+
provider_id, resolved_model = resolved
|
|
707
|
+
provider = self._provider_config.get_provider(provider_id)
|
|
708
|
+
if provider:
|
|
709
|
+
await self._provider_config.switch(provider_id, resolved_model)
|
|
710
|
+
self._apply_client_provider(provider, resolved_model)
|
|
711
|
+
self._broadcast_model_changed(provider, resolved_model)
|
|
712
|
+
return 200, {"success": True, "message": "Config updated"}
|
|
713
|
+
|
|
249
714
|
# ---------- 供应商 ----------
|
|
250
715
|
|
|
251
716
|
def _list_providers(self):
|