fix: restore clean server.py from upstream + HEAD support for /health
Browse files
server.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
"""
|
| 2 |
-
WorkBuddy
|
| 3 |
|
| 4 |
Accepts standard OpenAI API requests and forwards them to WorkBuddy's
|
| 5 |
/v2/chat/completions endpoint with the required authentication headers.
|
| 6 |
|
| 7 |
All user-specific values (user_id, enterprise_id, domain) are automatically
|
| 8 |
-
extracted from the JWT token
|
| 9 |
|
| 10 |
Usage:
|
| 11 |
python server.py # auto-extract via CDP
|
|
@@ -13,7 +13,6 @@ Usage:
|
|
| 13 |
"""
|
| 14 |
|
| 15 |
import asyncio
|
| 16 |
-
import hmac
|
| 17 |
import json
|
| 18 |
import logging
|
| 19 |
import os
|
|
@@ -44,17 +43,18 @@ log = logging.getLogger("wb-proxy")
|
|
| 44 |
|
| 45 |
BASE_DIR = Path(__file__).parent
|
| 46 |
|
| 47 |
-
# README / .env.example:本地与 Docker 均通过 .env 配置;已有环境变量优先(
|
|
|
|
| 48 |
from dotenv import load_dotenv
|
| 49 |
|
| 50 |
load_dotenv(BASE_DIR / ".env", override=False)
|
| 51 |
except ImportError:
|
| 52 |
pass
|
| 53 |
|
| 54 |
-
TOKEN_FILE =
|
| 55 |
|
| 56 |
PROXY_PORT = int(os.getenv("PROXY_PORT", "19090"))
|
| 57 |
-
PROXY_API_KEY = os.getenv("PROXY_API_KEY", "")
|
| 58 |
WB_API_BASE = os.getenv("WB_API_BASE", "https://copilot.tencent.com")
|
| 59 |
CDP_URL = os.getenv("CDP_URL", "http://127.0.0.1:9222")
|
| 60 |
|
|
@@ -64,7 +64,7 @@ def _detect_wb_version() -> str:
|
|
| 64 |
candidates = [
|
| 65 |
# macOS
|
| 66 |
Path("/Applications/WorkBuddy.app/Contents/Resources/app/product.json"),
|
| 67 |
-
# Windows
|
| 68 |
Path(os.path.expandvars(r"%LOCALAPPDATA%\Programs\WorkBuddy\resources\app\product.json")),
|
| 69 |
Path(os.path.expandvars(r"%ProgramFiles%\WorkBuddy\resources\app\product.json")),
|
| 70 |
Path(os.path.expandvars(r"%ProgramFiles(x86)%\WorkBuddy\resources\app\product.json")),
|
|
@@ -98,15 +98,8 @@ HEADERS_TEMPLATE = {
|
|
| 98 |
"User-Agent": f"CodeBuddyIDE/{WB_VERSION} coding-copilot/{WB_VERSION}",
|
| 99 |
}
|
| 100 |
|
| 101 |
-
REASONING_MODELS = {"deepseek-r1", "deepseek-r1-0528-lkeap", "hunyuan-2.0-thinking-ioa"
|
| 102 |
DEFAULT_TIMEOUT = int(os.getenv("WB_TIMEOUT", "120"))
|
| 103 |
-
|
| 104 |
-
# WorkBuddy prepends "Thought: Xms\n" to each reasoning chunk �?strip it
|
| 105 |
-
_THOUGHT_RE = re.compile(r"^Thought:\s*\d+ms\s*\n", re.MULTILINE)
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def _clean_reasoning(text: str) -> str:
|
| 109 |
-
return _THOUGHT_RE.sub("", text)
|
| 110 |
REASONING_TIMEOUT = int(os.getenv("WB_REASONING_TIMEOUT", "300"))
|
| 111 |
|
| 112 |
|
|
@@ -198,9 +191,8 @@ class TokenManager:
|
|
| 198 |
try:
|
| 199 |
payload = jwt.decode(self.access_token, options={"verify_signature": False})
|
| 200 |
return time.time() > (payload.get("exp", 0) - 300)
|
| 201 |
-
except Exception
|
| 202 |
-
|
| 203 |
-
return True
|
| 204 |
|
| 205 |
def _log_token_info(self):
|
| 206 |
try:
|
|
@@ -236,7 +228,7 @@ class TokenManager:
|
|
| 236 |
}
|
| 237 |
if self.department_info:
|
| 238 |
headers["X-Department-Info"] = self.department_info
|
| 239 |
-
async with httpx.AsyncClient() as client:
|
| 240 |
resp = await client.post(
|
| 241 |
f"{WB_API_BASE}/v2/plugin/auth/token/refresh",
|
| 242 |
headers=headers,
|
|
@@ -257,7 +249,6 @@ class TokenManager:
|
|
| 257 |
await self._extract_from_cdp()
|
| 258 |
|
| 259 |
async def _extract_from_cdp(self):
|
| 260 |
-
"""Extract token via CDP (deprecated: WorkBuddy 5.1.4+ no longer exposes ipcRenderer)."""
|
| 261 |
log.info(f"Extracting token from WorkBuddy via CDP ({CDP_URL})...")
|
| 262 |
try:
|
| 263 |
async with httpx.AsyncClient() as client:
|
|
@@ -322,7 +313,7 @@ class TokenManager:
|
|
| 322 |
log.error(f"CDP extraction error: {session['error']}")
|
| 323 |
|
| 324 |
except ImportError:
|
| 325 |
-
log.warning("websockets not installed
|
| 326 |
except Exception as e:
|
| 327 |
log.error(f"CDP extraction failed: {e}")
|
| 328 |
|
|
@@ -333,7 +324,7 @@ token_mgr = TokenManager()
|
|
| 333 |
# ---------------------------------------------------------------------------
|
| 334 |
# Cursor model name mapping
|
| 335 |
# Cursor validates model names server-side; only its built-in names pass.
|
| 336 |
-
# This map translates Cursor names
|
| 337 |
# ---------------------------------------------------------------------------
|
| 338 |
CURSOR_TO_WB_MAP: dict[str, str] = {
|
| 339 |
# Claude
|
|
@@ -359,7 +350,7 @@ CURSOR_TO_WB_MAP: dict[str, str] = {
|
|
| 359 |
"kimi-k2.5": "kimi-k2.5-ioa",
|
| 360 |
}
|
| 361 |
|
| 362 |
-
# Reverse map: WB model ID
|
| 363 |
WB_TO_CURSOR_MAP: dict[str, str] = {
|
| 364 |
"claude-opus-4.6": "claude-4.6-opus-high",
|
| 365 |
"claude-opus-4.6-1m": "claude-4.6-opus-max",
|
|
@@ -385,39 +376,40 @@ def resolve_model(model: str) -> str:
|
|
| 385 |
MODELS = [
|
| 386 |
# DeepSeek
|
| 387 |
{"id": "deepseek-r1", "name": "DeepSeek-R1"},
|
| 388 |
-
{"id": "deepseek-r1-0528-lkeap", "name": "DeepSeek-R1-LKEAP"},
|
| 389 |
{"id": "deepseek-v3", "name": "DeepSeek-V3"},
|
| 390 |
{"id": "deepseek-v3.2", "name": "DeepSeek-V3.2"},
|
| 391 |
{"id": "deepseek-v3-1", "name": "DeepSeek-V3.1"},
|
| 392 |
{"id": "deepseek-v3-0324", "name": "DeepSeek-V3-0324"},
|
|
|
|
| 393 |
{"id": "deepseek-v3-0324-lkeap", "name": "DeepSeek-V3-0324-LKEAP"},
|
| 394 |
-
{"id": "deepseek-
|
| 395 |
-
{"id": "deepseek-
|
| 396 |
-
|
| 397 |
-
# Claude
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
{"id": "claude-haiku-4.5", "name": "Claude-Haiku-4.5"},
|
| 399 |
-
|
| 400 |
-
{"id": "
|
|
|
|
| 401 |
# GLM
|
| 402 |
{"id": "glm-4.6", "name": "GLM-4.6"},
|
| 403 |
{"id": "glm-4.7", "name": "GLM-4.7"},
|
| 404 |
-
{"id": "glm-
|
| 405 |
-
{"id": "glm-5.
|
| 406 |
-
{"id": "glm-5.
|
| 407 |
{"id": "glm-5v-turbo", "name": "GLM-5v-Turbo"},
|
| 408 |
{"id": "glm-5v-turbo-ioa", "name": "GLM-5v-Turbo-IOA"},
|
| 409 |
# Hunyuan
|
| 410 |
-
{"id": "hunyuan-2.0-instruct", "name": "Hunyuan-2.0"},
|
| 411 |
-
{"id": "hunyuan-2.0-
|
| 412 |
-
{"id": "hunyuan-2.0-thinking-ioa", "name": "Hunyuan-2.0-Thinking
|
| 413 |
-
{"id": "hy3-preview", "name": "Hunyuan-3-Preview"},
|
| 414 |
# Kimi
|
| 415 |
-
{"id": "kimi-k2.
|
| 416 |
-
{"id": "kimi-k2.6-ioa", "name": "Kimi-K2.6-IOA"},
|
| 417 |
-
{"id": "kimi-k2.7", "name": "Kimi-K2.7"},
|
| 418 |
-
# MiniMax
|
| 419 |
-
{"id": "minimax-m3", "name": "MiniMax-M3"},
|
| 420 |
-
{"id": "minimax-m3-ioa", "name": "MiniMax-M3-IOA"},
|
| 421 |
# Default
|
| 422 |
{"id": "codewise-default-model-v2", "name": "Default (Codewise)"},
|
| 423 |
]
|
|
@@ -433,6 +425,7 @@ http_pool: httpx.AsyncClient | None = None
|
|
| 433 |
async def lifespan(_app: FastAPI):
|
| 434 |
global http_pool
|
| 435 |
http_pool = httpx.AsyncClient(
|
|
|
|
| 436 |
timeout=httpx.Timeout(DEFAULT_TIMEOUT, connect=10),
|
| 437 |
limits=httpx.Limits(max_connections=50, max_keepalive_connections=10),
|
| 438 |
)
|
|
@@ -444,12 +437,11 @@ async def lifespan(_app: FastAPI):
|
|
| 444 |
|
| 445 |
app = FastAPI(title="WorkBuddy Proxy", lifespan=lifespan)
|
| 446 |
|
| 447 |
-
#
|
| 448 |
-
# Auth is enforced via API key, not origin.
|
| 449 |
app.add_middleware(
|
| 450 |
CORSMiddleware,
|
| 451 |
allow_origins=["*"],
|
| 452 |
-
allow_credentials=False, #
|
| 453 |
allow_methods=["*"],
|
| 454 |
allow_headers=["*"],
|
| 455 |
)
|
|
@@ -460,7 +452,7 @@ def _verify_api_key(request: Request):
|
|
| 460 |
key = auth.replace("Bearer ", "").strip()
|
| 461 |
if not key:
|
| 462 |
key = (request.headers.get("X-API-Key") or "").strip()
|
| 463 |
-
if
|
| 464 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 465 |
|
| 466 |
|
|
@@ -525,12 +517,12 @@ def _timeout_for(model: str) -> float:
|
|
| 525 |
|
| 526 |
|
| 527 |
async def _upstream_stream(url: str, headers: dict, body: dict, timeout: float):
|
| 528 |
-
"""Open a streaming connection to upstream;
|
| 529 |
try:
|
| 530 |
-
req = http_pool.build_request("POST", url, headers=headers, json=body
|
| 531 |
resp = await http_pool.send(req, stream=True)
|
| 532 |
return resp
|
| 533 |
-
except
|
| 534 |
return None
|
| 535 |
|
| 536 |
|
|
@@ -540,20 +532,16 @@ async def chat_completions(request: Request):
|
|
| 540 |
|
| 541 |
body = await request.json()
|
| 542 |
raw_model = body.get("model", "deepseek-v3")
|
| 543 |
-
model = resolve_model(raw_model) # Cursor name
|
| 544 |
stream = body.get("stream", False)
|
| 545 |
|
| 546 |
if raw_model != model:
|
| 547 |
-
log.info(f"[Model] Mapped: {raw_model}
|
| 548 |
|
| 549 |
wb_body = {k: v for k, v in body.items() if k != "stream"}
|
| 550 |
wb_body["stream"] = True
|
| 551 |
wb_body["model"] = model
|
| 552 |
|
| 553 |
-
# Auto-inject reasoning for thinking models
|
| 554 |
-
if model in REASONING_MODELS:
|
| 555 |
-
wb_body.setdefault("reasoning", {"effort": "medium"})
|
| 556 |
-
|
| 557 |
access_token = await token_mgr.get_token()
|
| 558 |
if not access_token:
|
| 559 |
raise HTTPException(status_code=503, detail="No valid WorkBuddy token")
|
|
@@ -595,6 +583,7 @@ async def _stream_response(
|
|
| 595 |
|
| 596 |
try:
|
| 597 |
if resp.status_code == 401:
|
|
|
|
| 598 |
log.warning(f"[{model}] Got 401, refreshing token...")
|
| 599 |
await token_mgr.refresh()
|
| 600 |
if attempt < max_attempts:
|
|
@@ -605,59 +594,27 @@ async def _stream_response(
|
|
| 605 |
|
| 606 |
if resp.status_code != 200:
|
| 607 |
error_body = await resp.aread()
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
yield f"data: {json.dumps({'error': error_text})}\n\n"
|
| 611 |
yield "data: [DONE]\n\n"
|
| 612 |
return
|
| 613 |
|
| 614 |
done_sent = False
|
| 615 |
-
reasoning_buf = ""
|
| 616 |
async for line in resp.aiter_lines():
|
| 617 |
-
if
|
| 618 |
-
if line
|
|
|
|
|
|
|
| 619 |
has_content = True
|
| 620 |
yield line + "\n\n"
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
if reasoning_buf:
|
| 625 |
-
buf_chunk = {"choices": [{"index": 0, "delta": {"reasoning_content": reasoning_buf}}]}
|
| 626 |
-
yield f"data: {json.dumps(buf_chunk)}\n\n"
|
| 627 |
-
yield line + "\n\n"
|
| 628 |
-
continue
|
| 629 |
-
|
| 630 |
-
has_content = True
|
| 631 |
-
try:
|
| 632 |
-
chunk = json.loads(line.removeprefix("data: "))
|
| 633 |
-
choice = chunk.get("choices", [{}])[0]
|
| 634 |
-
delta = choice.get("delta", {})
|
| 635 |
-
rc = delta.get("reasoning_content")
|
| 636 |
-
has_content_field = bool(delta.get("content") or delta.get("tool_calls"))
|
| 637 |
-
|
| 638 |
-
if rc is not None:
|
| 639 |
-
cleaned = _clean_reasoning(rc)
|
| 640 |
-
if has_content_field and reasoning_buf:
|
| 641 |
-
buf_chunk = {"choices": [{"index": 0, "delta": {"reasoning_content": reasoning_buf}}]}
|
| 642 |
-
yield f"data: {json.dumps(buf_chunk)}\n\n"
|
| 643 |
-
reasoning_buf = ""
|
| 644 |
-
reasoning_buf += cleaned
|
| 645 |
-
if not has_content_field:
|
| 646 |
-
continue
|
| 647 |
-
delta.pop("reasoning_content", None)
|
| 648 |
-
|
| 649 |
-
if reasoning_buf:
|
| 650 |
-
buf_chunk = {"choices": [{"index": 0, "delta": {"reasoning_content": reasoning_buf}}]}
|
| 651 |
-
yield f"data: {json.dumps(buf_chunk)}\n\n"
|
| 652 |
-
reasoning_buf = ""
|
| 653 |
-
|
| 654 |
-
yield f"data: {json.dumps(chunk)}\n\n"
|
| 655 |
-
except (json.JSONDecodeError, KeyError):
|
| 656 |
-
yield line + "\n\n"
|
| 657 |
|
| 658 |
elapsed = time.monotonic() - t_start
|
| 659 |
|
| 660 |
-
if not has_content and
|
|
|
|
| 661 |
log.warning(f"[{model}] Empty response, retrying... ({elapsed:.1f}s)")
|
| 662 |
await asyncio.sleep(1)
|
| 663 |
continue
|
|
@@ -671,6 +628,7 @@ async def _stream_response(
|
|
| 671 |
except httpx.ReadTimeout:
|
| 672 |
log.error(f"[{model}] Read timeout during stream (attempt {attempt})")
|
| 673 |
if attempt < max_attempts:
|
|
|
|
| 674 |
continue
|
| 675 |
yield 'data: {"error":"upstream timeout"}\n\n'
|
| 676 |
yield "data: [DONE]\n\n"
|
|
@@ -692,7 +650,6 @@ async def _non_stream_response(
|
|
| 692 |
headers = _build_headers(access_token)
|
| 693 |
|
| 694 |
collected_content = ""
|
| 695 |
-
collected_reasoning = ""
|
| 696 |
tool_calls_map: dict[int, dict] = {}
|
| 697 |
finish_reason = "stop"
|
| 698 |
resp_model = model
|
|
@@ -707,6 +664,7 @@ async def _non_stream_response(
|
|
| 707 |
|
| 708 |
try:
|
| 709 |
if resp.status_code == 401:
|
|
|
|
| 710 |
log.warning(f"[{model}] Got 401, refreshing token...")
|
| 711 |
await token_mgr.refresh()
|
| 712 |
if attempt < max_attempts:
|
|
@@ -716,7 +674,7 @@ async def _non_stream_response(
|
|
| 716 |
if resp.status_code != 200:
|
| 717 |
error_body = await resp.aread()
|
| 718 |
raise HTTPException(status_code=resp.status_code,
|
| 719 |
-
detail=error_body.decode(
|
| 720 |
|
| 721 |
async for line in resp.aiter_lines():
|
| 722 |
text = line.removeprefix("data: ").strip()
|
|
@@ -728,9 +686,6 @@ async def _non_stream_response(
|
|
| 728 |
delta = choice.get("delta", {})
|
| 729 |
|
| 730 |
collected_content += delta.get("content") or ""
|
| 731 |
-
rc = delta.get("reasoning_content")
|
| 732 |
-
if rc:
|
| 733 |
-
collected_reasoning += _clean_reasoning(rc)
|
| 734 |
|
| 735 |
for tc in delta.get("tool_calls") or []:
|
| 736 |
idx = tc.get("index", 0)
|
|
@@ -759,15 +714,10 @@ async def _non_stream_response(
|
|
| 759 |
except (json.JSONDecodeError, IndexError, KeyError):
|
| 760 |
pass
|
| 761 |
|
| 762 |
-
except httpx.ReadTimeout:
|
| 763 |
-
log.error(f"[{model}] Read timeout during non-stream (attempt {attempt})")
|
| 764 |
-
if attempt < max_attempts:
|
| 765 |
-
continue
|
| 766 |
-
raise HTTPException(status_code=504, detail="Upstream read timeout")
|
| 767 |
finally:
|
| 768 |
await resp.aclose()
|
| 769 |
|
| 770 |
-
if not collected_content and not
|
| 771 |
log.warning(f"[{model}] Empty response, retrying...")
|
| 772 |
await asyncio.sleep(1)
|
| 773 |
continue
|
|
@@ -778,8 +728,6 @@ async def _non_stream_response(
|
|
| 778 |
log.info(f"[{model}] non-stream {elapsed:.1f}s prompt={prompt_t} completion={compl_t}")
|
| 779 |
|
| 780 |
message: dict = {"role": "assistant", "content": collected_content or None}
|
| 781 |
-
if collected_reasoning:
|
| 782 |
-
message["reasoning_content"] = collected_reasoning
|
| 783 |
if tool_calls_map:
|
| 784 |
message["tool_calls"] = [tool_calls_map[i] for i in sorted(tool_calls_map)]
|
| 785 |
|
|
@@ -808,14 +756,8 @@ async def health():
|
|
| 808 |
|
| 809 |
|
| 810 |
if __name__ == "__main__":
|
| 811 |
-
if not PROXY_API_KEY:
|
| 812 |
-
log.error("PROXY_API_KEY is not set. Set it via env var or .env file.")
|
| 813 |
-
log.error("Example: PROXY_API_KEY=$(openssl rand -hex 32) python server.py")
|
| 814 |
-
sys.exit(1)
|
| 815 |
-
if len(PROXY_API_KEY) < 16:
|
| 816 |
-
log.warning("PROXY_API_KEY is shorter than 16 chars �?consider using a stronger key")
|
| 817 |
log.info(f"Starting WorkBuddy proxy on port {PROXY_PORT}")
|
| 818 |
log.info(f"WB version: {WB_VERSION}")
|
| 819 |
-
log.info(f"API key: {PROXY_API_KEY
|
| 820 |
log.info(f"Upstream: {WB_API_BASE}")
|
| 821 |
uvicorn.run(app, host="0.0.0.0", port=PROXY_PORT, log_level="info")
|
|
|
|
| 1 |
"""
|
| 2 |
+
WorkBuddy → OpenAI-compatible reverse proxy.
|
| 3 |
|
| 4 |
Accepts standard OpenAI API requests and forwards them to WorkBuddy's
|
| 5 |
/v2/chat/completions endpoint with the required authentication headers.
|
| 6 |
|
| 7 |
All user-specific values (user_id, enterprise_id, domain) are automatically
|
| 8 |
+
extracted from the JWT token — no manual configuration required.
|
| 9 |
|
| 10 |
Usage:
|
| 11 |
python server.py # auto-extract via CDP
|
|
|
|
| 13 |
"""
|
| 14 |
|
| 15 |
import asyncio
|
|
|
|
| 16 |
import json
|
| 17 |
import logging
|
| 18 |
import os
|
|
|
|
| 43 |
|
| 44 |
BASE_DIR = Path(__file__).parent
|
| 45 |
|
| 46 |
+
# README / .env.example:本地与 Docker 均通过 .env 配置;已有环境变量优先(不 override)
|
| 47 |
+
try:
|
| 48 |
from dotenv import load_dotenv
|
| 49 |
|
| 50 |
load_dotenv(BASE_DIR / ".env", override=False)
|
| 51 |
except ImportError:
|
| 52 |
pass
|
| 53 |
|
| 54 |
+
TOKEN_FILE = BASE_DIR / "data" / "token.json"
|
| 55 |
|
| 56 |
PROXY_PORT = int(os.getenv("PROXY_PORT", "19090"))
|
| 57 |
+
PROXY_API_KEY = os.getenv("PROXY_API_KEY", "wb-proxy-key")
|
| 58 |
WB_API_BASE = os.getenv("WB_API_BASE", "https://copilot.tencent.com")
|
| 59 |
CDP_URL = os.getenv("CDP_URL", "http://127.0.0.1:9222")
|
| 60 |
|
|
|
|
| 64 |
candidates = [
|
| 65 |
# macOS
|
| 66 |
Path("/Applications/WorkBuddy.app/Contents/Resources/app/product.json"),
|
| 67 |
+
# Windows — common locations
|
| 68 |
Path(os.path.expandvars(r"%LOCALAPPDATA%\Programs\WorkBuddy\resources\app\product.json")),
|
| 69 |
Path(os.path.expandvars(r"%ProgramFiles%\WorkBuddy\resources\app\product.json")),
|
| 70 |
Path(os.path.expandvars(r"%ProgramFiles(x86)%\WorkBuddy\resources\app\product.json")),
|
|
|
|
| 98 |
"User-Agent": f"CodeBuddyIDE/{WB_VERSION} coding-copilot/{WB_VERSION}",
|
| 99 |
}
|
| 100 |
|
| 101 |
+
REASONING_MODELS = {"deepseek-r1", "deepseek-r1-0528-lkeap", "hunyuan-2.0-thinking-ioa"}
|
| 102 |
DEFAULT_TIMEOUT = int(os.getenv("WB_TIMEOUT", "120"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
REASONING_TIMEOUT = int(os.getenv("WB_REASONING_TIMEOUT", "300"))
|
| 104 |
|
| 105 |
|
|
|
|
| 191 |
try:
|
| 192 |
payload = jwt.decode(self.access_token, options={"verify_signature": False})
|
| 193 |
return time.time() > (payload.get("exp", 0) - 300)
|
| 194 |
+
except Exception:
|
| 195 |
+
return False
|
|
|
|
| 196 |
|
| 197 |
def _log_token_info(self):
|
| 198 |
try:
|
|
|
|
| 228 |
}
|
| 229 |
if self.department_info:
|
| 230 |
headers["X-Department-Info"] = self.department_info
|
| 231 |
+
async with httpx.AsyncClient(verify=False) as client:
|
| 232 |
resp = await client.post(
|
| 233 |
f"{WB_API_BASE}/v2/plugin/auth/token/refresh",
|
| 234 |
headers=headers,
|
|
|
|
| 249 |
await self._extract_from_cdp()
|
| 250 |
|
| 251 |
async def _extract_from_cdp(self):
|
|
|
|
| 252 |
log.info(f"Extracting token from WorkBuddy via CDP ({CDP_URL})...")
|
| 253 |
try:
|
| 254 |
async with httpx.AsyncClient() as client:
|
|
|
|
| 313 |
log.error(f"CDP extraction error: {session['error']}")
|
| 314 |
|
| 315 |
except ImportError:
|
| 316 |
+
log.warning("websockets not installed — run: pip install websockets")
|
| 317 |
except Exception as e:
|
| 318 |
log.error(f"CDP extraction failed: {e}")
|
| 319 |
|
|
|
|
| 324 |
# ---------------------------------------------------------------------------
|
| 325 |
# Cursor model name mapping
|
| 326 |
# Cursor validates model names server-side; only its built-in names pass.
|
| 327 |
+
# This map translates Cursor names → WorkBuddy model IDs.
|
| 328 |
# ---------------------------------------------------------------------------
|
| 329 |
CURSOR_TO_WB_MAP: dict[str, str] = {
|
| 330 |
# Claude
|
|
|
|
| 350 |
"kimi-k2.5": "kimi-k2.5-ioa",
|
| 351 |
}
|
| 352 |
|
| 353 |
+
# Reverse map: WB model ID → preferred Cursor alias (for /v1/models)
|
| 354 |
WB_TO_CURSOR_MAP: dict[str, str] = {
|
| 355 |
"claude-opus-4.6": "claude-4.6-opus-high",
|
| 356 |
"claude-opus-4.6-1m": "claude-4.6-opus-max",
|
|
|
|
| 376 |
MODELS = [
|
| 377 |
# DeepSeek
|
| 378 |
{"id": "deepseek-r1", "name": "DeepSeek-R1"},
|
|
|
|
| 379 |
{"id": "deepseek-v3", "name": "DeepSeek-V3"},
|
| 380 |
{"id": "deepseek-v3.2", "name": "DeepSeek-V3.2"},
|
| 381 |
{"id": "deepseek-v3-1", "name": "DeepSeek-V3.1"},
|
| 382 |
{"id": "deepseek-v3-0324", "name": "DeepSeek-V3-0324"},
|
| 383 |
+
{"id": "deepseek-v3-1-volc", "name": "DeepSeek-V3-1-Terminus"},
|
| 384 |
{"id": "deepseek-v3-0324-lkeap", "name": "DeepSeek-V3-0324-LKEAP"},
|
| 385 |
+
{"id": "deepseek-r1-0528-lkeap", "name": "DeepSeek-R1-0528-LKEAP"},
|
| 386 |
+
{"id": "deepseek-v3-2-volc-ioa", "name": "DeepSeek-V3-2-Volc"},
|
| 387 |
+
# GPT (5.1–5.4 removed: HTTP 400 on WorkBuddy backend)
|
| 388 |
+
# Claude
|
| 389 |
+
{"id": "claude-4.5", "name": "Claude-Sonnet-4.5"},
|
| 390 |
+
{"id": "claude-opus-4.5", "name": "Claude-Opus-4.5"},
|
| 391 |
+
{"id": "claude-opus-4.6", "name": "Claude-Opus-4.6"},
|
| 392 |
+
{"id": "claude-opus-4.6-1m", "name": "Claude-Opus-4.6 (1M context)"},
|
| 393 |
+
{"id": "claude-sonnet-4.6", "name": "Claude-Sonnet-4.6"},
|
| 394 |
+
{"id": "claude-sonnet-4.6-1m", "name": "Claude-Sonnet-4.6 (1M context)"},
|
| 395 |
{"id": "claude-haiku-4.5", "name": "Claude-Haiku-4.5"},
|
| 396 |
+
# Gemini (3.0-flash removed: returns empty responses)
|
| 397 |
+
{"id": "gemini-3.0-pro", "name": "Gemini-3.0-Pro"},
|
| 398 |
+
{"id": "gemini-3.1-flash-lite", "name": "Gemini-3.1-Flash-Lite"},
|
| 399 |
# GLM
|
| 400 |
{"id": "glm-4.6", "name": "GLM-4.6"},
|
| 401 |
{"id": "glm-4.7", "name": "GLM-4.7"},
|
| 402 |
+
{"id": "glm-4.7-ioa", "name": "GLM-4.7-IOA"},
|
| 403 |
+
{"id": "glm-5.0-ioa", "name": "GLM-5.0"},
|
| 404 |
+
{"id": "glm-5.0-turbo-ioa", "name": "GLM-5.0-Turbo"},
|
| 405 |
{"id": "glm-5v-turbo", "name": "GLM-5v-Turbo"},
|
| 406 |
{"id": "glm-5v-turbo-ioa", "name": "GLM-5v-Turbo-IOA"},
|
| 407 |
# Hunyuan
|
| 408 |
+
{"id": "hunyuan-2.0-instruct", "name": "Hunyuan-2.0-Instruct"},
|
| 409 |
+
{"id": "hunyuan-2.0-instruct-ioa", "name": "Hunyuan-2.0-Instruct-IOA"},
|
| 410 |
+
{"id": "hunyuan-2.0-thinking-ioa", "name": "Hunyuan-2.0-Thinking"},
|
|
|
|
| 411 |
# Kimi
|
| 412 |
+
{"id": "kimi-k2.5-ioa", "name": "Kimi-K2.5"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
# Default
|
| 414 |
{"id": "codewise-default-model-v2", "name": "Default (Codewise)"},
|
| 415 |
]
|
|
|
|
| 425 |
async def lifespan(_app: FastAPI):
|
| 426 |
global http_pool
|
| 427 |
http_pool = httpx.AsyncClient(
|
| 428 |
+
verify=False,
|
| 429 |
timeout=httpx.Timeout(DEFAULT_TIMEOUT, connect=10),
|
| 430 |
limits=httpx.Limits(max_connections=50, max_keepalive_connections=10),
|
| 431 |
)
|
|
|
|
| 437 |
|
| 438 |
app = FastAPI(title="WorkBuddy Proxy", lifespan=lifespan)
|
| 439 |
|
| 440 |
+
# Cherry Studio 等 Electron 应用可能从渲染进程请求本机 API,需放行 CORS
|
|
|
|
| 441 |
app.add_middleware(
|
| 442 |
CORSMiddleware,
|
| 443 |
allow_origins=["*"],
|
| 444 |
+
allow_credentials=False, # 与 allow_origins=["*"] 不能同时为 True
|
| 445 |
allow_methods=["*"],
|
| 446 |
allow_headers=["*"],
|
| 447 |
)
|
|
|
|
| 452 |
key = auth.replace("Bearer ", "").strip()
|
| 453 |
if not key:
|
| 454 |
key = (request.headers.get("X-API-Key") or "").strip()
|
| 455 |
+
if key != PROXY_API_KEY:
|
| 456 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 457 |
|
| 458 |
|
|
|
|
| 517 |
|
| 518 |
|
| 519 |
async def _upstream_stream(url: str, headers: dict, body: dict, timeout: float):
|
| 520 |
+
"""Open a streaming connection to upstream; yields (resp, None) or (None, error_str)."""
|
| 521 |
try:
|
| 522 |
+
req = http_pool.build_request("POST", url, headers=headers, json=body)
|
| 523 |
resp = await http_pool.send(req, stream=True)
|
| 524 |
return resp
|
| 525 |
+
except httpx.TimeoutException:
|
| 526 |
return None
|
| 527 |
|
| 528 |
|
|
|
|
| 532 |
|
| 533 |
body = await request.json()
|
| 534 |
raw_model = body.get("model", "deepseek-v3")
|
| 535 |
+
model = resolve_model(raw_model) # Cursor name → WB model ID
|
| 536 |
stream = body.get("stream", False)
|
| 537 |
|
| 538 |
if raw_model != model:
|
| 539 |
+
log.info(f"[Model] Mapped: {raw_model} → {model}")
|
| 540 |
|
| 541 |
wb_body = {k: v for k, v in body.items() if k != "stream"}
|
| 542 |
wb_body["stream"] = True
|
| 543 |
wb_body["model"] = model
|
| 544 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
access_token = await token_mgr.get_token()
|
| 546 |
if not access_token:
|
| 547 |
raise HTTPException(status_code=503, detail="No valid WorkBuddy token")
|
|
|
|
| 583 |
|
| 584 |
try:
|
| 585 |
if resp.status_code == 401:
|
| 586 |
+
await resp.aclose()
|
| 587 |
log.warning(f"[{model}] Got 401, refreshing token...")
|
| 588 |
await token_mgr.refresh()
|
| 589 |
if attempt < max_attempts:
|
|
|
|
| 594 |
|
| 595 |
if resp.status_code != 200:
|
| 596 |
error_body = await resp.aread()
|
| 597 |
+
log.error(f"[{model}] Upstream {resp.status_code}: {error_body.decode()[:200]}")
|
| 598 |
+
yield f"data: {json.dumps({'error': error_body.decode()})}\n\n"
|
|
|
|
| 599 |
yield "data: [DONE]\n\n"
|
| 600 |
return
|
| 601 |
|
| 602 |
done_sent = False
|
|
|
|
| 603 |
async for line in resp.aiter_lines():
|
| 604 |
+
if line.startswith("data: "):
|
| 605 |
+
if line == "data: [DONE]":
|
| 606 |
+
done_sent = True
|
| 607 |
+
else:
|
| 608 |
has_content = True
|
| 609 |
yield line + "\n\n"
|
| 610 |
+
elif line.strip():
|
| 611 |
+
has_content = True
|
| 612 |
+
yield f"data: {line}\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 613 |
|
| 614 |
elapsed = time.monotonic() - t_start
|
| 615 |
|
| 616 |
+
if not has_content and attempt < max_attempts:
|
| 617 |
+
await resp.aclose()
|
| 618 |
log.warning(f"[{model}] Empty response, retrying... ({elapsed:.1f}s)")
|
| 619 |
await asyncio.sleep(1)
|
| 620 |
continue
|
|
|
|
| 628 |
except httpx.ReadTimeout:
|
| 629 |
log.error(f"[{model}] Read timeout during stream (attempt {attempt})")
|
| 630 |
if attempt < max_attempts:
|
| 631 |
+
await resp.aclose()
|
| 632 |
continue
|
| 633 |
yield 'data: {"error":"upstream timeout"}\n\n'
|
| 634 |
yield "data: [DONE]\n\n"
|
|
|
|
| 650 |
headers = _build_headers(access_token)
|
| 651 |
|
| 652 |
collected_content = ""
|
|
|
|
| 653 |
tool_calls_map: dict[int, dict] = {}
|
| 654 |
finish_reason = "stop"
|
| 655 |
resp_model = model
|
|
|
|
| 664 |
|
| 665 |
try:
|
| 666 |
if resp.status_code == 401:
|
| 667 |
+
await resp.aclose()
|
| 668 |
log.warning(f"[{model}] Got 401, refreshing token...")
|
| 669 |
await token_mgr.refresh()
|
| 670 |
if attempt < max_attempts:
|
|
|
|
| 674 |
if resp.status_code != 200:
|
| 675 |
error_body = await resp.aread()
|
| 676 |
raise HTTPException(status_code=resp.status_code,
|
| 677 |
+
detail=error_body.decode())
|
| 678 |
|
| 679 |
async for line in resp.aiter_lines():
|
| 680 |
text = line.removeprefix("data: ").strip()
|
|
|
|
| 686 |
delta = choice.get("delta", {})
|
| 687 |
|
| 688 |
collected_content += delta.get("content") or ""
|
|
|
|
|
|
|
|
|
|
| 689 |
|
| 690 |
for tc in delta.get("tool_calls") or []:
|
| 691 |
idx = tc.get("index", 0)
|
|
|
|
| 714 |
except (json.JSONDecodeError, IndexError, KeyError):
|
| 715 |
pass
|
| 716 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 717 |
finally:
|
| 718 |
await resp.aclose()
|
| 719 |
|
| 720 |
+
if not collected_content and not tool_calls_map and attempt < max_attempts:
|
| 721 |
log.warning(f"[{model}] Empty response, retrying...")
|
| 722 |
await asyncio.sleep(1)
|
| 723 |
continue
|
|
|
|
| 728 |
log.info(f"[{model}] non-stream {elapsed:.1f}s prompt={prompt_t} completion={compl_t}")
|
| 729 |
|
| 730 |
message: dict = {"role": "assistant", "content": collected_content or None}
|
|
|
|
|
|
|
| 731 |
if tool_calls_map:
|
| 732 |
message["tool_calls"] = [tool_calls_map[i] for i in sorted(tool_calls_map)]
|
| 733 |
|
|
|
|
| 756 |
|
| 757 |
|
| 758 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 759 |
log.info(f"Starting WorkBuddy proxy on port {PROXY_PORT}")
|
| 760 |
log.info(f"WB version: {WB_VERSION}")
|
| 761 |
+
log.info(f"API key: {PROXY_API_KEY}")
|
| 762 |
log.info(f"Upstream: {WB_API_BASE}")
|
| 763 |
uvicorn.run(app, host="0.0.0.0", port=PROXY_PORT, log_level="info")
|