DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(provider): add codebuddy as a LLM provider (#780)
Ching Wing Kwok8297fc7b7e12
diff --git a/README.md b/README.mdindex 627b5479c..6e88112f6 100644--- a/README.md+++ b/README.md@@ -741,7 +741,7 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a ~150-line handover doc that t| `deeptutor book list/health/refresh-fingerprints` | Inspect books and refresh source fingerprints || `deeptutor plugin list/info` | Inspect registered tools and capabilities || `deeptutor config show` | Print configuration summary |-| `deeptutor provider login <provider>` | Provider auth (`openai-codex` OAuth login; `github-copilot` validates an existing Copilot auth session) |+| `deeptutor provider login <provider>` | Provider auth (`openai-codex` OAuth login; `github-copilot` validates an existing Copilot auth session; `codebuddy` validates CodeBuddy SDK auth and starts login when needed) |</details>diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex e61a08784..7809fc50d 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -42,6 +42,7 @@ from deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBusfrom deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_idfrom deeptutor.services.llm import clean_thinking_tags+from deeptutor.services.llm.capabilities import threads_session_idfrom deeptutor.services.llm.multimodal import should_degrade_to_text, strip_image_parts_inplacefrom deeptutor.services.llm.request_compat import (is_image_input_unsupported,@@ -607,6 +608,8 @@ class AgentLoop:"stream": True,**self.pipeline._completion_kwargs(max_tokens=max_tokens),}+ if threads_session_id(self.pipeline.binding):+ kwargs["deeptutor_session_id"] = self.context.session_idif self.pipeline.usage is not None:kwargs["stream_options"] = {"include_usage": True}if tool_schemas:diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 827139cdf..4d5bb74b6 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -21,6 +21,7 @@ logger = logging.getLogger(__name__)from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.model_access import allowed_llm_options+from deeptutor.services.codebuddy_auth import get_codebuddy_auth_servicefrom deeptutor.services.codex_auth import (CodexAuthError,get_codex_oauth_service,@@ -182,7 +183,7 @@ class CodexReasoningEffortUpdate(BaseModel):class FetchModelsPayload(BaseModel):binding: str = ""- base_url: str+ base_url: str = ""api_key: Optional[str] = None@@ -614,6 +615,30 @@ async def refresh_openai_codex_models() -> dict[str, Any]:raise _codex_http_exception(exc) from None[email protected]("/providers/codebuddy/auth/status")+async def get_codebuddy_auth_status() -> dict[str, Any]:+ _require_settings_admin()+ return await get_codebuddy_auth_service().status()++[email protected]("/providers/codebuddy/auth/start")+async def start_codebuddy_auth() -> dict[str, Any]:+ _require_settings_admin()+ return await get_codebuddy_auth_service().start_login()++[email protected]("/providers/codebuddy/auth/cancel")+async def cancel_codebuddy_auth() -> dict[str, Any]:+ _require_settings_admin()+ return await get_codebuddy_auth_service().cancel_login()++[email protected]("/providers/codebuddy/auth/logout")+async def logout_codebuddy_auth() -> dict[str, Any]:+ _require_settings_admin()+ return await get_codebuddy_auth_service().logout()++@router.post("/providers/openai-codex/models/reasoning-effort")async def update_openai_codex_reasoning_effort(payload: CodexReasoningEffortUpdate,@@ -1112,10 +1137,10 @@ async def fetch_models_from_provider(payload: FetchModelsPayload):base_url = (payload.base_url or "").strip()binding = (payload.binding or "").strip().lower() or "openai"- if not base_url:+ if not base_url and binding != "codebuddy":raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,- detail="base_url is required.",+ detail="base_url is required for this provider.",)try:diff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.pyindex af23cd747..1e430d82b 100644--- a/deeptutor/capabilities/explore_context/explorer.py+++ b/deeptutor/capabilities/explore_context/explorer.py@@ -43,6 +43,7 @@ from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, newfrom deeptutor.runtime.registry.tool_registry import get_tool_registryfrom deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargsfrom deeptutor.services.llm import stream as llm_stream+from deeptutor.services.llm.capabilities import threads_session_idlogger = logging.getLogger(__name__)@@ -208,7 +209,12 @@ class ContextExplorer:messages.append({"role": "user", "content": self._forced_finish_instruction()})total_in += sum(_content_chars(m) for m in messages)result = await self._call_llm(- client, messages, tool_schemas if not is_last else None, chunk_meta, stream+ client,+ messages,+ tool_schemas if not is_last else None,+ chunk_meta,+ stream,+ context.session_id,)total_out += result.output_charsif not result.tool_calls:@@ -247,6 +253,7 @@ class ContextExplorer:tool_schemas: list[dict[str, Any]] | None,chunk_meta: dict[str, Any],stream: StreamBus,+ session_id: str,) -> _CallResult:"""One streamed LLM call. All output streams to the *thinking* channel(never CONTENT — that is the answer loop's channel); the returned text@@ -263,6 +270,8 @@ class ContextExplorer:reasoning_effort=self.reasoning_effort,),}+ if threads_session_id(self.binding):+ kwargs["deeptutor_session_id"] = f"{session_id}:explore"if tool_schemas:kwargs["tools"] = tool_schemaskwargs["tool_choice"] = "auto"diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.pyindex 4d352843e..0fca886bd 100644--- a/deeptutor/core/agentic/client.py+++ b/deeptutor/core/agentic/client.py@@ -42,7 +42,7 @@ _NATIVE_TOOL_BLOCKED_BINDINGS: frozenset[str] = frozenset(# backend needs an adapter branch, or tool schemas would be attached to a plain# AsyncOpenAI client pointed at a non-OpenAI wire format. github_copilot is# adapter-routed but deliberately excluded from this set.-_NATIVE_TOOL_BACKENDS: frozenset[str] = frozenset({"anthropic", "openai_codex"})+_NATIVE_TOOL_BACKENDS: frozenset[str] = frozenset({"anthropic", "openai_codex", "codebuddy"})_AGENTIC_CLIENT_POOL_MAXSIZE = 2_agentic_client_pool: "OrderedDict[tuple[Any, ...], Any]" = OrderedDict()_agentic_client_pool_lock = threading.RLock()@@ -214,10 +214,23 @@ def _build_copilot_adapter(config: LLMClientConfig, spec: Any) -> Any:return _ProviderOpenAIAdapter(copilot_provider)+def _build_codebuddy_adapter(config: LLMClientConfig, spec: Any) -> Any:+ from deeptutor.services.llm.provider_core.codebuddy_http_provider import (+ build_codebuddy_provider,+ )++ codebuddy_provider = build_codebuddy_provider(+ api_key=config.api_key,+ default_model=config.model or "codebuddy/hy3",+ )+ return _ProviderOpenAIAdapter(codebuddy_provider)++_NATIVE_ADAPTER_BUILDERS: dict[str, Callable[[LLMClientConfig, Any], Any]] = {"anthropic": _build_anthropic_adapter,"openai_codex": _build_codex_adapter,"github_copilot": _build_copilot_adapter,+ "codebuddy": _build_codebuddy_adapter,}diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.pyindex e86ebebaa..3cfd5290f 100644--- a/deeptutor/multi_user/model_access.py+++ b/deeptutor/multi_user/model_access.py@@ -46,6 +46,15 @@ def _model_by_id(profile: dict[str, Any], model_id: str) -> dict[str, Any] | Nonreturn None+#: Bindings whose credential is one person's own subscription login rather than+#: a billable team key. Codex stamps ``owner_bound`` onto the managed profile it+#: publishes, but a profile can also be created by hand in the settings editor —+#: a CodeBuddy profile is, and it reads the operator's own IDE-plugin session —+#: and there is nowhere for such a profile to acquire the flag. Binding is the+#: durable fact, so it decides too.+OWNER_BOUND_BINDINGS = frozenset({"openai_codex", "codebuddy"})++def is_owner_bound(profile: dict[str, Any]) -> bool:"""Whether a profile is tied to the identity of the operator who set it up.@@ -53,6 +62,9 @@ def is_owner_bound(profile: dict[str, Any]) -> bool:a billable team key, so those profiles are never lent to other accountsthrough grants — each user signs in for themselves or goes without."""+ binding = str(profile.get("binding") or "").strip().lower()+ if binding in OWNER_BOUND_BINDINGS:+ return Truereturn bool(profile.get("owner_bound"))diff --git a/deeptutor/services/codebuddy_auth.py b/deeptutor/services/codebuddy_auth.pynew file mode 100644index 000000000..82195ef26--- /dev/null+++ b/deeptutor/services/codebuddy_auth.py@@ -0,0 +1,239 @@+"""Process-local coordinator for CodeBuddy SDK authentication."""++from __future__ import annotations++import asyncio+from typing import Any+++class CodeBuddyAuthService:+ """Probe existing SDK auth and keep one browser login flow alive."""++ def __init__(self) -> None:+ self._lock = asyncio.Lock()+ self._flow: Any | None = None+ self._task: asyncio.Task[None] | None = None+ self._connection = "disconnected"+ self._operation_state: str | None = None+ self._authorize_url: str | None = None+ self._user_label: str | None = None+ self._error_code: str | None = None++ def public_status(self) -> dict[str, Any]:+ return {+ "connection": self._connection,+ "operation_state": self._operation_state,+ "authorize_url": self._authorize_url,+ "user_label": self._user_label,+ "error_code": self._error_code,+ }++ async def status(self) -> dict[str, Any]:+ """Return current status, probing the SDK when no login is active."""+ async with self._lock:+ if self._task and not self._task.done():+ return self.public_status()+ await self._probe_locked()+ return self.public_status()++ async def start_login(self) -> dict[str, Any]:+ """Reuse local auth or start a browser-based SDK login flow."""+ async with self._lock:+ if self._task and not self._task.done():+ return self.public_status()+ if await self._probe_local_login():+ return self.public_status()+ try:+ flow = await _start_sdk_authenticate()+ if not getattr(flow, "auth_url", ""):+ result = await flow+ self._mark_connected(result)+ return self.public_status()++ self._flow = flow+ self._connection = "authorizing"+ self._operation_state = "waiting"+ self._authorize_url = str(flow.auth_url)+ self._user_label = None+ self._error_code = None+ self._task = asyncio.create_task(self._wait_for_login(flow))+ except Exception as exc: # noqa: BLE001 - converted to stable public state+ self._mark_error(exc)+ return self.public_status()++ async def cancel_login(self) -> dict[str, Any]:+ async with self._lock:+ flow = self._flow+ task = self._task+ self._flow = None+ self._task = None+ self._connection = "disconnected"+ self._operation_state = "cancelled"+ self._authorize_url = None+ self._error_code = None+ if task and not task.done():+ task.cancel()+ if flow is not None:+ try:+ await flow.cancel()+ except Exception:+ pass+ return self.public_status()++ async def logout(self) -> dict[str, Any]:+ """Disconnect DeepTutor from the CodeBuddy session on this host.++ Not a sign-out: the session belongs to the IDE plugin / CLI that+ created it, and only they can end it.+ """+ async with self._lock:+ flow = self._flow+ task = self._task+ self._flow = None+ self._task = None+ if task and not task.done():+ task.cancel()+ if flow is not None:+ try:+ await flow.cancel()+ except Exception:+ pass++ # DeepTutor does not own this credential: it is the session the IDE+ # plugin and the `codebuddy` CLI share on this host. Ending it from a+ # web endpoint would sign the operator out of their editor too — and on+ # a shared host, out of whoever else is on that login. Drop our cached+ # clients and report where the session actually lives.+ from deeptutor.core.agentic.client import reset_agentic_client_pool+ from deeptutor.services.codebuddy_credentials import load_credentials++ reset_agentic_client_pool()+ async with self._lock:+ if load_credentials() is not None:+ self._connection = "connected"+ self._operation_state = "failed"+ self._authorize_url = None+ self._error_code = "logout_external"+ return self.public_status()+ self._connection = "disconnected"+ self._operation_state = None+ self._authorize_url = None+ self._user_label = None+ self._error_code = None+ return self.public_status()++ async def _probe_locked(self) -> None:+ if await self._probe_local_login():+ return+ try:+ flow = await _start_sdk_authenticate()+ if getattr(flow, "auth_url", ""):+ await flow.cancel()+ self._connection = "disconnected"+ self._operation_state = None+ self._authorize_url = None+ self._user_label = None+ self._error_code = None+ return+ result = await flow+ self._mark_connected(result)+ except Exception as exc: # noqa: BLE001 - converted to stable public state+ self._mark_error(exc)++ async def _probe_local_login(self) -> bool:+ """Accept the session the IDE plugin / CLI already stored on disk.++ This path needs no Agent SDK, so it is tried before the SDK probe.+ """+ from deeptutor.services.codebuddy_credentials import load_credentials, probe_account++ credentials = load_credentials()+ if credentials is None:+ return False+ try:+ label = await probe_account(credentials)+ except Exception: # noqa: BLE001 - fall through to the SDK probe+ return False+ if label is None:+ return False++ self._connection = "connected"+ self._operation_state = "completed"+ self._authorize_url = None+ self._user_label = label+ self._error_code = None+ return True++ async def _wait_for_login(self, flow: Any) -> None:+ try:+ result = await flow+ except asyncio.CancelledError:+ return+ except Exception as exc: # noqa: BLE001 - converted to stable public state+ async with self._lock:+ if self._flow is flow:+ self._flow = None+ self._task = None+ self._mark_error(exc)+ return++ async with self._lock:+ if self._flow is flow:+ self._flow = None+ self._task = None+ self._mark_connected(result)++ def _mark_connected(self, result: Any) -> None:+ userinfo = getattr(result, "userinfo", None)+ self._connection = "connected"+ self._operation_state = "completed"+ self._authorize_url = None+ self._user_label = _userinfo_label(userinfo)+ self._error_code = None++ def _mark_error(self, exc: Exception) -> None:+ message = str(exc).lower()+ if isinstance(exc, ImportError):+ code = "sdk_missing"+ elif "not found" in message or "no such file" in message:+ code = "cli_missing"+ elif "timed out" in message or "timeout" in message:+ code = "login_timeout"+ else:+ code = "auth_failed"+ self._connection = "error"+ self._operation_state = "failed"+ self._authorize_url = None+ self._user_label = None+ self._error_code = code+++async def _start_sdk_authenticate() -> Any:+ try:+ from codebuddy_agent_sdk import authenticate+ except ImportError as exc:+ raise ImportError("codebuddy-agent-sdk is not installed") from exc+ return await authenticate(timeout=300.0)+++def _userinfo_label(userinfo: Any) -> str | None:+ if userinfo is None:+ return None+ for field in ("user_nickname", "user_name", "user_id"):+ value = getattr(userinfo, field, None)+ if value:+ return str(value)+ return None+++_service: CodeBuddyAuthService | None = None+++def get_codebuddy_auth_service() -> CodeBuddyAuthService:+ global _service+ if _service is None:+ _service = CodeBuddyAuthService()+ return _service+++__all__ = ["CodeBuddyAuthService", "get_codebuddy_auth_service"]diff --git a/deeptutor/services/codebuddy_credentials.py b/deeptutor/services/codebuddy_credentials.pynew file mode 100644index 000000000..9a1a5d3a6--- /dev/null+++ b/deeptutor/services/codebuddy_credentials.py@@ -0,0 +1,363 @@+"""Read the CodeBuddy desktop/CLI login state without the Agent SDK.++CodeBuddy's IDE plugin and CLI share a single OAuth session file whose name+matches ``authentication.id`` in the CLI's ``product.json``+(``Tencent-Cloud.coding-copilot``). Reading it lets DeepTutor call the+CodeBuddy cloud over plain HTTP the same way the Codex and Copilot providers+do, which keeps the ~130 MB Agent SDK (a bundled headless CLI binary) optional.++The cloud speaks OpenAI ``/chat/completions`` under ``<endpoint>/v2`` and only+needs ``Authorization: Bearer <accessToken>``.+"""++from __future__ import annotations++import base64+from dataclasses import dataclass, replace+import gzip+import json+import os+from pathlib import Path+import sys+import time+from typing import Any+from urllib.parse import urlsplit++_AUTH_FILE_NAME = "Tencent-Cloud.coding-copilot.info"+_AUTH_SUBPATH = ("CodeBuddyExtension", "Data", "Public", "auth")++OVERSEAS_ENDPOINT = "https://www.codebuddy.ai"+INTERNAL_ENDPOINT = "https://copilot.tencent.com"+API_PATH_PREFIX = "/v2"++# Accounts on the China deployment authenticate against copilot.tencent.com;+# the overseas deployment uses www.codebuddy.ai. The model catalogs differ.+_INTERNAL_DOMAIN_HINTS = ("codebuddy.cn", "workbuddy.cn", "copilot.tencent.com")++_EXPIRY_SKEW_SECONDS = 300.0+_REFRESH_PATH = "/v2/auth/token/refresh"+_ACCOUNTS_PATH = "/v2/accounts"++# Used when no cached product config is available. Overseas ids are different,+# but ``default`` resolves on both deployments.+FALLBACK_MODEL_CATALOG = ("default",)+++class CodeBuddyAuthUnavailable(RuntimeError):+ """No usable CodeBuddy login state could be found or refreshed."""+++@dataclass(frozen=True)+class CodeBuddyCredentials:+ """A CodeBuddy OAuth session read from the shared auth file."""++ access_token: str+ refresh_token: str = ""+ expires_at: float = 0.0+ refresh_expires_at: float = 0.0+ user_id: str = ""+ user_label: str = ""+ domain: str = ""+ source: Path | None = None++ @property+ def api_base(self) -> str:+ return resolve_api_base(self.domain)++ def is_expired(self, skew: float = _EXPIRY_SKEW_SECONDS) -> bool:+ if not self.expires_at:+ return False+ return time.time() >= self.expires_at - skew++ def can_refresh(self) -> bool:+ if not self.refresh_token:+ return False+ if not self.refresh_expires_at:+ return True+ return time.time() < self.refresh_expires_at+++def _auth_search_dirs() -> list[Path]:+ """Candidate directories holding the shared auth file, per platform.++ These are the same three locations the CodeBuddy CLI lists as its own+ credential paths.+ """+ home = Path.home()+ roots: list[Path] = []+ if sys.platform == "win32":+ local = os.environ.get("LOCALAPPDATA")+ if local:+ roots.append(Path(local))+ roots.append(home / "AppData" / "Local")+ elif sys.platform == "darwin":+ roots.append(home / "Library" / "Application Support")+ else:+ data_home = os.environ.get("XDG_DATA_HOME")+ if data_home:+ roots.append(Path(data_home))+ roots.append(home / ".local" / "share")+ return [root.joinpath(*_AUTH_SUBPATH) for root in roots]+++def find_auth_file() -> Path | None:+ override = os.environ.get("DEEPTUTOR_CODEBUDDY_AUTH_FILE")+ if override:+ path = Path(override)+ return path if path.is_file() else None+ for directory in _auth_search_dirs():+ candidate = directory / _AUTH_FILE_NAME+ if candidate.is_file():+ return candidate+ return None+++def _as_float(value: Any) -> float:+ try:+ number = float(value)+ except (TypeError, ValueError):+ return 0.0+ # The auth file stores epoch milliseconds.+ return number / 1000.0 if number > 1e11 else number+++def load_credentials() -> CodeBuddyCredentials | None:+ """Return the current login state, or ``None`` when not signed in."""+ path = find_auth_file()+ if path is None:+ return None+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None++ auth = payload.get("auth")+ account = payload.get("account")+ if not isinstance(auth, dict):+ return None+ token = auth.get("accessToken")+ if not isinstance(token, str) or not token:+ return None+ account = account if isinstance(account, dict) else {}++ label = ""+ for field in ("nickname", "uin", "uid"):+ value = account.get(field)+ if value:+ label = str(value)+ break++ return CodeBuddyCredentials(+ access_token=token,+ refresh_token=str(auth.get("refreshToken") or ""),+ expires_at=_as_float(auth.get("expiresAt")),+ refresh_expires_at=_as_float(auth.get("refreshExpiresAt")),+ user_id=str(account.get("uid") or ""),+ user_label=label,+ domain=str(auth.get("domain") or ""),+ source=path,+ )+++def resolve_api_base(domain: str = "") -> str:+ """Return the ``/v2`` API base for the account's deployment."""+ override = os.environ.get("CODEBUDDY_BASE_URL")+ if override:+ base = override.rstrip("/")+ return base if base.endswith(API_PATH_PREFIX) else base + API_PATH_PREFIX++ environment = (os.environ.get("CODEBUDDY_INTERNET_ENVIRONMENT") or "").strip().lower()+ if environment in {"internal", "ioa"}:+ return INTERNAL_ENDPOINT + API_PATH_PREFIX++ cached = cached_product_endpoint()+ if cached:+ return cached.rstrip("/") + API_PATH_PREFIX++ hint = domain.lower()+ if any(marker in hint for marker in _INTERNAL_DOMAIN_HINTS):+ return INTERNAL_ENDPOINT + API_PATH_PREFIX+ return OVERSEAS_ENDPOINT + API_PATH_PREFIX+++# ----------------------------------------------------------------------+# Cached product config (endpoint + model catalog)+# ----------------------------------------------------------------------+++def _local_storage_dir() -> Path:+ return Path.home() / ".codebuddy" / "local_storage"+++def _iter_cached_product_configs() -> list[dict[str, Any]]:+ """Decode the CLI's cached product configs.++ Entries are JSON strings; large ones wrap gzip+base64 payloads.+ """+ directory = _local_storage_dir()+ if not directory.is_dir():+ return []+ configs: list[dict[str, Any]] = []+ for path in sorted(directory.glob("entry_*.info")):+ try:+ raw = json.loads(path.read_text(encoding="utf-8", errors="ignore"))+ except (OSError, ValueError):+ continue+ if not isinstance(raw, str):+ continue+ try:+ decoded = json.loads(gzip.decompress(base64.b64decode(raw)).decode("utf-8"))+ except Exception: # noqa: BLE001 - opaque cache blob, skip on any failure+ continue+ if isinstance(decoded, dict) and decoded.get("models"):+ configs.append(decoded)+ return configs+++#: Hosts the cached product config may name. That file belongs to another+#: application, so anything able to write under this account's home can choose+#: where the bearer token is sent — and ``startswith("http")`` accepts plain+#: HTTP to an arbitrary host. An operator who needs a different deployment sets+#: ``CODEBUDDY_BASE_URL``, which ``resolve_api_base`` honours before consulting+#: the cache at all.+_TRUSTED_ENDPOINT_HOSTS = frozenset(+ host+ for host in (+ urlsplit(OVERSEAS_ENDPOINT).hostname,+ urlsplit(INTERNAL_ENDPOINT).hostname,+ )+ if host+)+++def _is_trusted_endpoint(endpoint: str) -> bool:+ try:+ parts = urlsplit(endpoint)+ except ValueError:+ return False+ return parts.scheme == "https" and (parts.hostname or "") in _TRUSTED_ENDPOINT_HOSTS+++def cached_product_endpoint() -> str | None:+ for config in _iter_cached_product_configs():+ endpoint = config.get("endpoint")+ if isinstance(endpoint, str) and _is_trusted_endpoint(endpoint):+ return endpoint+ return None+++def cached_model_catalog() -> list[str]:+ """Return the model ids the CLI last cached for this deployment."""+ models: list[str] = []+ for config in _iter_cached_product_configs():+ for entry in config.get("models") or []:+ if not isinstance(entry, dict):+ continue+ model_id = entry.get("id")+ if isinstance(model_id, str) and model_id and model_id not in models:+ models.append(model_id)+ if models:+ break+ return models+++# ----------------------------------------------------------------------+# Token refresh / account probe+# ----------------------------------------------------------------------+++async def refresh_credentials(credentials: CodeBuddyCredentials) -> CodeBuddyCredentials:+ """Exchange the refresh token for a new access token."""+ if not credentials.can_refresh():+ raise CodeBuddyAuthUnavailable(+ "CodeBuddy session expired and cannot be refreshed. Sign in again in the "+ "CodeBuddy IDE plugin or run `codebuddy` and enter `/login`."+ )++ import httpx++ base = credentials.api_base.removesuffix(API_PATH_PREFIX)+ async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, connect=20.0)) as client:+ response = await client.post(+ base + _REFRESH_PATH,+ json={"refreshToken": credentials.refresh_token},+ headers={"Authorization": f"Bearer {credentials.access_token}"},+ )+ if response.status_code >= 400:+ raise CodeBuddyAuthUnavailable(+ "CodeBuddy token refresh failed "+ f"({response.status_code}). Sign in again in the CodeBuddy IDE plugin "+ "or run `codebuddy` and enter `/login`."+ )++ payload = response.json()+ auth = payload.get("data") if isinstance(payload, dict) else None+ if isinstance(auth, dict) and isinstance(auth.get("auth"), dict):+ auth = auth["auth"]+ if not isinstance(auth, dict):+ auth = payload if isinstance(payload, dict) else {}++ token = auth.get("accessToken")+ if not isinstance(token, str) or not token:+ raise CodeBuddyAuthUnavailable("CodeBuddy token refresh returned no access token.")++ return replace(+ credentials,+ access_token=token,+ refresh_token=str(auth.get("refreshToken") or credentials.refresh_token),+ expires_at=_as_float(auth.get("expiresAt")) or credentials.expires_at,+ refresh_expires_at=(+ _as_float(auth.get("refreshExpiresAt")) or credentials.refresh_expires_at+ ),+ )+++async def probe_account(credentials: CodeBuddyCredentials) -> str | None:+ """Validate the session and return a display label, or ``None`` if invalid.++ ``/v2/accounts`` is a free call, unlike a completion request.+ """+ import httpx++ base = credentials.api_base.removesuffix(API_PATH_PREFIX)+ headers = {"Authorization": f"Bearer {credentials.access_token}"}+ if credentials.user_id:+ headers["X-User-Id"] = credentials.user_id+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(20.0, connect=15.0)) as client:+ response = await client.get(base + _ACCOUNTS_PATH, headers=headers)+ except Exception: # noqa: BLE001 - network failure is not an auth failure+ return credentials.user_label or None+ if response.status_code >= 400:+ return None++ try:+ accounts = (response.json().get("data") or {}).get("accounts") or []+ except (ValueError, AttributeError):+ return credentials.user_label or None+ for account in accounts:+ if not isinstance(account, dict):+ continue+ if credentials.user_id and account.get("uid") != credentials.user_id:+ continue+ for field in ("nickname", "uin", "uid"):+ value = account.get(field)+ if value:+ return str(value)+ return credentials.user_label or None+++__all__ = [+ "CodeBuddyAuthUnavailable",+ "CodeBuddyCredentials",+ "FALLBACK_MODEL_CATALOG",+ "cached_model_catalog",+ "cached_product_endpoint",+ "find_auth_file",+ "load_credentials",+ "probe_account",+ "refresh_credentials",+ "resolve_api_base",+]diff --git a/deeptutor/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.pyindex 98e438608..74adf0ae9 100644--- a/deeptutor/services/llm/capabilities.py+++ b/deeptutor/services/llm/capabilities.py@@ -90,6 +90,14 @@ PROVIDER_CAPABILITIES: dict[str, dict[str, object]] = {"system_in_messages": False,"has_thinking_tags": False,},+ "codebuddy": {+ "supports_response_format": False,+ "supports_streaming": True,+ "supports_tools": True,+ "supports_vision": False,+ "system_in_messages": True,+ "has_thinking_tags": False,+ },# DeepSeek"deepseek": {"supports_response_format": False, # DeepSeek doesn't support strict JSON schema yet@@ -567,8 +575,22 @@ def get_effective_temperature(return requested_temp+#: Bindings whose upstream tracks a multi-turn conversation by an id the caller+#: supplies, so each request carries the turn's own session id. Stated here+#: rather than tested inline: the chat loop and the explore capability both+#: need it, and neither should have to name a provider to run a turn.+SESSION_SCOPED_BINDINGS: frozenset[str] = frozenset({"codebuddy"})+++def threads_session_id(binding: str | None) -> bool:+ """Whether *binding* expects ``deeptutor_session_id`` on each request."""+ return (binding or "").strip().lower() in SESSION_SCOPED_BINDINGS++__all__ = ["PROVIDER_CAPABILITIES",+ "SESSION_SCOPED_BINDINGS",+ "threads_session_id","MODEL_OVERRIDES","DEFAULT_CAPABILITIES","get_capability",diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 7292b3da1..f0b9734f6 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -588,9 +588,14 @@ async def stream(async def fetch_models(binding: str,- base_url: str,+ base_url: str = "",api_key: str | None = None,) -> list[str]:+ if canonical_provider_name(binding) == "codebuddy":+ from .provider_core.codebuddy_models import fetch_codebuddy_models++ return await fetch_codebuddy_models(api_key)+if is_local_llm_server(base_url):from . import local_providerdiff --git a/deeptutor/services/llm/provider_core/__init__.py b/deeptutor/services/llm/provider_core/__init__.pyindex 767c376c1..16ff39087 100644--- a/deeptutor/services/llm/provider_core/__init__.py+++ b/deeptutor/services/llm/provider_core/__init__.py@@ -10,6 +10,8 @@ from .base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequestif TYPE_CHECKING:from .anthropic_provider import AnthropicProviderfrom .azure_openai_provider import AzureOpenAIProvider+ from .codebuddy_http_provider import CodeBuddyHTTPProvider+ from .codebuddy_provider import CodeBuddyProviderfrom .github_copilot_provider import GitHubCopilotProviderfrom .openai_codex_provider import OpenAICodexProviderfrom .openai_compat_provider import OpenAICompatProvider@@ -17,6 +19,8 @@ if TYPE_CHECKING:__all__ = ["AnthropicProvider","AzureOpenAIProvider",+ "CodeBuddyHTTPProvider",+ "CodeBuddyProvider","GenerationSettings","GitHubCopilotProvider","LLMProvider",@@ -30,6 +34,8 @@ __all__ = [_LAZY_TYPES = {"AnthropicProvider": ("anthropic_provider", "AnthropicProvider"),"AzureOpenAIProvider": ("azure_openai_provider", "AzureOpenAIProvider"),+ "CodeBuddyHTTPProvider": ("codebuddy_http_provider", "CodeBuddyHTTPProvider"),+ "CodeBuddyProvider": ("codebuddy_provider", "CodeBuddyProvider"),"GitHubCopilotProvider": ("github_copilot_provider", "GitHubCopilotProvider"),"OpenAICodexProvider": ("openai_codex_provider", "OpenAICodexProvider"),"OpenAICompatProvider": ("openai_compat_provider", "OpenAICompatProvider"),diff --git a/deeptutor/services/llm/provider_core/codebuddy_http_provider.py b/deeptutor/services/llm/provider_core/codebuddy_http_provider.pynew file mode 100644index 000000000..41c61d18b--- /dev/null+++ b/deeptutor/services/llm/provider_core/codebuddy_http_provider.py@@ -0,0 +1,243 @@+"""CodeBuddy provider that talks to the cloud over plain HTTP.++The CodeBuddy cloud exposes an OpenAI-compatible ``/chat/completions`` under+``<endpoint>/v2`` and accepts the OAuth session that the IDE plugin and CLI+already store on disk. That makes the Agent SDK (a bundled headless CLI+binary) unnecessary for chat, so this provider is preferred whenever a login+state or API key is available.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable+import importlib.util+import os+from typing import Any++from openai import AuthenticationError++from deeptutor.services.codebuddy_credentials import (+ CodeBuddyAuthUnavailable,+ CodeBuddyCredentials,+ load_credentials,+ refresh_credentials,+ resolve_api_base,+)+from deeptutor.services.llm.provider_core.base import LLMResponse+from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider+from deeptutor.services.provider_registry import find_by_name++DEFAULT_CODEBUDDY_MODEL = "codebuddy/hy3"+_NO_KEY_PLACEHOLDER = "sk-no-key-required"+_SIGN_IN_HINT = (+ "CodeBuddy is not signed in. Sign in with the CodeBuddy IDE plugin, run "+ "`codebuddy` and enter `/login`, or set CODEBUDDY_API_KEY."+)+++def normalize_api_key(api_key: str | None) -> str | None:+ if not api_key:+ return None+ key = api_key.strip()+ if not key or key == _NO_KEY_PLACEHOLDER:+ return None+ return key+++class CodeBuddyHTTPProvider(OpenAICompatProvider):+ """CodeBuddy over HTTP, authenticating with the local login state."""++ def __init__(+ self,+ api_key: str | None = None,+ default_model: str = DEFAULT_CODEBUDDY_MODEL,+ ):+ self._explicit_api_key = normalize_api_key(api_key)+ self._credentials: CodeBuddyCredentials | None = (+ None if self._explicit_api_key else load_credentials()+ )++ extra_headers: dict[str, str] = {}+ if self._explicit_api_key:+ extra_headers["X-API-Key"] = self._explicit_api_key+ elif self._credentials and self._credentials.user_id:+ extra_headers["X-User-Id"] = self._credentials.user_id++ super().__init__(+ api_key=None,+ api_base=resolve_api_base(self._credentials.domain if self._credentials else ""),+ default_model=default_model or DEFAULT_CODEBUDDY_MODEL,+ extra_headers=extra_headers,+ spec=find_by_name("codebuddy"),+ provider_name="codebuddy",+ )+ if self._explicit_api_key:+ self._apply_token(self._explicit_api_key)++ def get_default_model(self) -> str:+ return self.default_model or DEFAULT_CODEBUDDY_MODEL++ def _apply_token(self, token: str) -> None:+ self.api_key = token+ self._client.api_key = token++ async def _ensure_auth(self, *, reload_from_disk: bool = False) -> None:+ if self._explicit_api_key:+ return++ credentials = self._credentials+ if reload_from_disk or credentials is None:+ credentials = load_credentials() or credentials+ if credentials is None:+ raise CodeBuddyAuthUnavailable(_SIGN_IN_HINT)++ if credentials.is_expired():+ credentials = await refresh_credentials(credentials)++ base = credentials.api_base+ if base != str(self._client.base_url).rstrip("/"):+ self._client.base_url = base+ self.api_base = base+ self._credentials = credentials+ self._apply_token(credentials.access_token)++ async def _chat_impl(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str | None,+ max_tokens: int,+ temperature: float,+ reasoning_effort: str | None,+ tool_choice: str | dict[str, Any] | None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ on_reasoning_delta: Callable[[str], Awaitable[None]] | None = None,+ **kwargs: Any,+ ) -> LLMResponse:+ # Session affinity is SDK-only; strip it so OpenAI client kwargs stay clean.+ kwargs.pop("deeptutor_session_id", None)+ await self._ensure_auth()+ try:+ return await super().chat_stream(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ reasoning_effort=reasoning_effort,+ tool_choice=tool_choice,+ on_content_delta=on_content_delta,+ on_reasoning_delta=on_reasoning_delta,+ **kwargs,+ )+ except AuthenticationError:+ await self._ensure_auth(reload_from_disk=True)+ return await super().chat_stream(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ reasoning_effort=reasoning_effort,+ tool_choice=tool_choice,+ on_content_delta=on_content_delta,+ on_reasoning_delta=on_reasoning_delta,+ **kwargs,+ )++ async def chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ **kwargs: Any,+ ) -> LLMResponse:+ return await self._chat_impl(+ messages,+ tools,+ model,+ max_tokens,+ temperature,+ reasoning_effort,+ tool_choice,+ **kwargs,+ )++ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ on_reasoning_delta: Callable[[str], Awaitable[None]] | None = None,+ **kwargs: Any,+ ) -> LLMResponse:+ return await self._chat_impl(+ messages,+ tools,+ model,+ max_tokens,+ temperature,+ reasoning_effort,+ tool_choice,+ on_content_delta,+ on_reasoning_delta,+ **kwargs,+ )+++def codebuddy_http_available(api_key: str | None = None) -> bool:+ """Whether HTTP access can authenticate without the Agent SDK."""+ if normalize_api_key(api_key) or normalize_api_key(os.environ.get("CODEBUDDY_API_KEY")):+ return True+ return load_credentials() is not None+++def sdk_installed() -> bool:+ return importlib.util.find_spec("codebuddy_agent_sdk") is not None+++def build_codebuddy_provider(+ api_key: str | None = None,+ default_model: str = DEFAULT_CODEBUDDY_MODEL,+) -> Any:+ """Return the HTTP transport when it can authenticate, else the Agent SDK.++ ``DEEPTUTOR_CODEBUDDY_BACKEND`` (``http`` / ``sdk``) forces one transport;+ the SDK is still needed for CLI-driven agent features such as sandboxed+ shell tools.+ """+ preference = (os.environ.get("DEEPTUTOR_CODEBUDDY_BACKEND") or "").strip().lower()+ has_sdk = sdk_installed()++ if preference == "sdk" and has_sdk:+ use_http = False+ elif preference == "http":+ use_http = True+ else:+ use_http = codebuddy_http_available(api_key) or not has_sdk++ if use_http:+ return CodeBuddyHTTPProvider(api_key=api_key, default_model=default_model)++ from deeptutor.services.llm.provider_core.codebuddy_provider import CodeBuddyProvider++ return CodeBuddyProvider(api_key=api_key, default_model=default_model)+++__all__ = [+ "CodeBuddyHTTPProvider",+ "DEFAULT_CODEBUDDY_MODEL",+ "build_codebuddy_provider",+ "codebuddy_http_available",+ "normalize_api_key",+ "sdk_installed",+]diff --git a/deeptutor/services/llm/provider_core/codebuddy_models.py b/deeptutor/services/llm/provider_core/codebuddy_models.pynew file mode 100644index 000000000..78fd1cebb--- /dev/null+++ b/deeptutor/services/llm/provider_core/codebuddy_models.py@@ -0,0 +1,36 @@+"""Model catalog lookup for CodeBuddy.++The cloud has no public model-list route, so the catalog comes from the config+the CodeBuddy CLI caches on disk. The CLI subprocess probe is only used as a+fallback, and ``default`` resolves on every deployment.+"""++from __future__ import annotations++import importlib.util++from deeptutor.services.codebuddy_credentials import FALLBACK_MODEL_CATALOG, cached_model_catalog+++async def fetch_codebuddy_models(api_key: str | None = None) -> list[str]:+ """Return the model ids available to the signed-in CodeBuddy account."""+ cached = cached_model_catalog()+ if cached:+ return cached++ if importlib.util.find_spec("codebuddy_agent_sdk") is not None:+ from deeptutor.services.llm.provider_core.codebuddy_provider import (+ fetch_codebuddy_models as fetch_via_cli,+ )++ try:+ models = await fetch_via_cli(api_key)+ except Exception: # noqa: BLE001 - CLI probe is best effort+ models = []+ if models:+ return models++ return list(FALLBACK_MODEL_CATALOG)+++__all__ = ["fetch_codebuddy_models"]diff --git a/deeptutor/services/llm/provider_core/codebuddy_provider.py b/deeptutor/services/llm/provider_core/codebuddy_provider.pynew file mode 100644index 000000000..9c19cdc89--- /dev/null+++ b/deeptutor/services/llm/provider_core/codebuddy_provider.py@@ -0,0 +1,836 @@+"""CodeBuddy Agent SDK provider."""++from __future__ import annotations++import asyncio+from collections import OrderedDict+from collections.abc import Awaitable, Callable+from contextlib import asynccontextmanager+from copy import deepcopy+from dataclasses import dataclass, field+import json+import os+import re+import shutil+import subprocess+from types import ModuleType+from typing import Any++from deeptutor.services.llm.provider_core.base import (+ LLMProvider,+ LLMResponse,+ ToolCallRequest,+)++DEFAULT_CODEBUDDY_MODEL = "codebuddy/hy3"+_CODEBUDDY_API_KEY_ENV = "CODEBUDDY_API_KEY"+_API_KEY_ENV_LOCK = asyncio.Lock()+_SESSION_POOL_MAXSIZE = 4+_MCP_SERVER_NAME = "deeptutor"+_MCP_TOOL_PREFIX = f"mcp__{_MCP_SERVER_NAME}__"+++@dataclass+class _SessionTurn:+ prompt: str+ on_content_delta: Callable[[str], Awaitable[None]] | None+ future: asyncio.Future[LLMResponse]+++@dataclass+class _CodeBuddySession:+ """Stateful CodeBuddy CLI session with task-bound SDK ownership.++ The CodeBuddy Agent SDK enters anyio cancel scopes / TaskGroups during+ ``connect()`` and must exit them from the same task. DeepTutor chat turns+ run in fresh ``_ProviderOpenAIStream`` tasks, so this session keeps a+ dedicated owner task for connect / query / receive / disconnect.+ """++ signature: str+ messages: list[dict[str, Any]] = field(default_factory=list)+ last_response: str = ""+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ client: Any = None+ _ops: asyncio.Queue[_SessionTurn | None] = field(default_factory=asyncio.Queue)+ _owner: asyncio.Task[None] | None = None++ @classmethod+ async def start(+ cls,+ *,+ sdk: ModuleType,+ signature: str,+ options: Any,+ env_api_key: str | None,+ ) -> "_CodeBuddySession":+ session = cls(signature=signature)+ loop = asyncio.get_running_loop()+ ready: asyncio.Future[None] = loop.create_future()+ session._owner = asyncio.create_task(+ session._owner_loop(sdk, options, env_api_key, ready),+ name="codebuddy-session-owner",+ )+ await ready+ return session++ async def _owner_loop(+ self,+ sdk: ModuleType,+ options: Any,+ env_api_key: str | None,+ ready: asyncio.Future[None],+ ) -> None:+ client = sdk.CodeBuddySDKClient(options=options)+ try:+ async with _temporary_codebuddy_api_key(env_api_key):+ await client.connect()+ self.client = client+ if not ready.done():+ ready.set_result(None)+ while True:+ turn = await self._ops.get()+ if turn is None:+ break+ try:+ await client.query(turn.prompt)+ response = await _consume_messages(+ client.receive_response(),+ on_content_delta=turn.on_content_delta,+ interrupt=client.interrupt,+ )+ if not turn.future.done():+ turn.future.set_result(response)+ except BaseException as exc:+ if not turn.future.done():+ turn.future.set_exception(exc)+ except BaseException as exc:+ if not ready.done():+ ready.set_exception(exc)+ raise+ finally:+ self.client = client+ try:+ await client.disconnect()+ except BaseException:+ pass++ async def run_turn(+ self,+ prompt: str,+ on_content_delta: Callable[[str], Awaitable[None]] | None,+ ) -> LLMResponse:+ if self._owner is None or self._owner.done():+ raise RuntimeError("CodeBuddy session owner is not running")+ loop = asyncio.get_running_loop()+ future: asyncio.Future[LLMResponse] = loop.create_future()+ await self._ops.put(+ _SessionTurn(prompt=prompt, on_content_delta=on_content_delta, future=future)+ )+ return await future++ async def close(self) -> None:+ owner = self._owner+ if owner is None:+ return+ self._owner = None+ if not owner.done():+ try:+ await self._ops.put(None)+ except Exception:+ owner.cancel()+ try:+ await owner+ except Exception:+ pass+++class CodeBuddyProvider(LLMProvider):+ """Provider backed by the CodeBuddy Agent SDK.++ CodeBuddy is exposed as an agent SDK instead of an OpenAI-compatible chat+ endpoint. This adapter keeps one stateful CLI process per DeepTutor session+ and exposes DeepTutor's tool schemas through an in-process SDK MCP server.+ Tool execution remains owned by DeepTutor's existing dispatcher.+ """++ def __init__(+ self,+ api_key: str | None = None,+ default_model: str | None = DEFAULT_CODEBUDDY_MODEL,+ ):+ normalized_api_key = None if api_key in {None, "", "sk-no-key-required"} else api_key+ super().__init__(api_key=normalized_api_key, api_base=None)+ self.default_model = default_model or DEFAULT_CODEBUDDY_MODEL+ self._sessions: OrderedDict[str, _CodeBuddySession] = OrderedDict()+ self._sessions_lock = asyncio.Lock()++ async def chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ **kwargs: Any,+ ) -> LLMResponse:+ session_id = str(kwargs.pop("deeptutor_session_id", "") or "").strip()+ del temperature, tool_choice, kwargs+ return await self._run_codebuddy(+ messages,+ tools,+ model,+ max_tokens,+ reasoning_effort=reasoning_effort,+ session_id=session_id,+ )++ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ on_reasoning_delta: Callable[[str], Awaitable[None]] | None = None,+ **kwargs: Any,+ ) -> LLMResponse:+ session_id = str(kwargs.pop("deeptutor_session_id", "") or "").strip()+ del temperature, tool_choice, on_reasoning_delta, kwargs+ return await self._run_codebuddy(+ messages,+ tools,+ model,+ max_tokens,+ reasoning_effort=reasoning_effort,+ on_content_delta=on_content_delta,+ session_id=session_id,+ )++ async def _run_codebuddy(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str | None,+ max_tokens: int,+ reasoning_effort: str | None = None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ session_id: str = "",+ ) -> LLMResponse:+ try:+ sdk = _load_sdk()+ if session_id and hasattr(sdk, "CodeBuddySDKClient"):+ return await self._run_session(+ sdk,+ session_id,+ messages,+ tools,+ model or self.default_model,+ max_tokens,+ reasoning_effort,+ on_content_delta,+ )+ return await self._run_one_shot(+ sdk,+ messages,+ tools,+ model or self.default_model,+ max_tokens,+ reasoning_effort,+ on_content_delta,+ )+ except Exception as exc:+ return LLMResponse(content=_friendly_error(exc), finish_reason="error")++ async def _run_one_shot(+ self,+ sdk: ModuleType,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str,+ max_tokens: int,+ reasoning_effort: str | None,+ on_content_delta: Callable[[str], Awaitable[None]] | None,+ ) -> LLMResponse:+ options = _build_options(sdk, model, max_tokens, self.api_key, reasoning_effort, tools)+ env_api_key = None if _options_has_api_key_env(options) else self.api_key+ stream: Any | None = None+ async with _temporary_codebuddy_api_key(env_api_key):+ kwargs: dict[str, Any] = {"prompt": _messages_to_prompt(messages)}+ if options is not None:+ kwargs["options"] = options+ stream = sdk.query(**kwargs)+ try:+ return await _consume_messages(stream, on_content_delta=on_content_delta)+ finally:+ close = getattr(stream, "aclose", None)+ if callable(close):+ await close()++ async def _run_session(+ self,+ sdk: ModuleType,+ session_id: str,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str,+ max_tokens: int,+ reasoning_effort: str | None,+ on_content_delta: Callable[[str], Awaitable[None]] | None,+ ) -> LLMResponse:+ signature = _session_signature(model, reasoning_effort, tools)+ session = await self._get_session(+ sdk, session_id, signature, model, max_tokens, reasoning_effort, tools+ )+ try:+ async with session.lock:+ prompt = _incremental_prompt(session, messages)+ session.messages = deepcopy(messages)+ response = await session.run_turn(prompt, on_content_delta)+ session.last_response = response.content or ""+ return response+ except BaseException:+ await self._drop_session(session_id, session)+ raise++ async def _get_session(+ self,+ sdk: ModuleType,+ session_id: str,+ signature: str,+ model: str,+ max_tokens: int,+ reasoning_effort: str | None,+ tools: list[dict[str, Any]] | None,+ ) -> _CodeBuddySession:+ to_close: list[_CodeBuddySession] = []+ try:+ async with self._sessions_lock:+ existing = self._sessions.get(session_id)+ if (+ existing+ and existing.signature == signature+ and existing._owner is not None+ and not existing._owner.done()+ ):+ self._sessions.move_to_end(session_id)+ return existing+ if existing:+ self._sessions.pop(session_id, None)+ to_close.append(existing)++ options = _build_options(+ sdk, model, max_tokens, self.api_key, reasoning_effort, tools+ )+ env_api_key = None if _options_has_api_key_env(options) else self.api_key+ session = await _CodeBuddySession.start(+ sdk=sdk,+ signature=signature,+ options=options,+ env_api_key=env_api_key,+ )+ self._sessions[session_id] = session+ while len(self._sessions) > _SESSION_POOL_MAXSIZE:+ _, evicted = self._sessions.popitem(last=False)+ to_close.append(evicted)+ return session+ finally:+ for stale in to_close:+ await stale.close()++ async def _drop_session(self, session_id: str, session: _CodeBuddySession) -> None:+ async with self._sessions_lock:+ if self._sessions.get(session_id) is session:+ self._sessions.pop(session_id, None)+ await session.close()++ async def aclose(self) -> None:+ async with self._sessions_lock:+ sessions = list(self._sessions.values())+ self._sessions.clear()+ for session in sessions:+ try:+ await session.close()+ except asyncio.CancelledError:+ task = asyncio.current_task()+ if task is not None:+ task.uncancel()+ except Exception:+ pass++ def get_default_model(self) -> str:+ return self.default_model+++def _load_sdk() -> ModuleType:+ try:+ import codebuddy_agent_sdk+ except ImportError as exc: # pragma: no cover - optional dependency+ raise RuntimeError(+ "codebuddy-agent-sdk is not installed. Install it with "+ "`python -m pip install codebuddy-agent-sdk` or `pip install -e .[codebuddy]`."+ ) from exc+ if not hasattr(codebuddy_agent_sdk, "query"):+ raise RuntimeError("Installed codebuddy-agent-sdk does not expose query().")+ return codebuddy_agent_sdk+++def _strip_model_prefix(model: str | None) -> str | None:+ if not model:+ return None+ if "/" not in model:+ return model+ prefix, value = model.split("/", 1)+ if prefix.lower().replace("-", "_") in {"codebuddy", "codebuddy_code", "workbuddy"}:+ return value+ return model+++def _build_options(+ sdk: ModuleType,+ model: str | None,+ max_tokens: int,+ api_key: str | None = None,+ reasoning_effort: str | None = None,+ tools: list[dict[str, Any]] | None = None,+) -> Any | None:+ options_cls = getattr(sdk, "CodeBuddyAgentOptions", None)+ if options_cls is None:+ return None++ stripped_model = _strip_model_prefix(model)+ model_kwargs = (+ {} if not stripped_model or stripped_model == "default" else {"model": stripped_model}+ )+ env_kwargs = {"env": {_CODEBUDDY_API_KEY_ENV: api_key}} if api_key else {}+ reasoning_kwargs = _reasoning_options(reasoning_effort)+ tool_kwargs = _build_tool_options(sdk, tools)+ # The turn limit and the permission mode ARE the sandbox — they keep the+ # agent from acting on its own beyond the single turn we asked for. The SDK+ # spells them snake_case or camelCase depending on version, so both are+ # tried; but a build that accepts neither is a build whose restrictions we+ # cannot express, and running unrestricted is not the safe fallback. Every+ # candidate therefore carries them, and exhausting the list raises.+ candidates: list[dict[str, Any]] = []+ for guard in (+ {"max_turns": 1, "permission_mode": "plan"},+ {"maxTurns": 1, "permissionMode": "plan"},+ ):+ restricted = {+ **model_kwargs,+ **env_kwargs,+ **reasoning_kwargs,+ **tool_kwargs,+ **guard,+ }+ if max_tokens > 0:+ candidates.append({**restricted, "max_tokens": max_tokens})+ candidates.append(restricted)++ for kwargs in candidates:+ try:+ return options_cls(**kwargs)+ except TypeError:+ continue+ raise RuntimeError(+ "The installed codebuddy-agent-sdk does not accept the turn limit and "+ "permission mode this provider requires. Install a supported version "+ '(pip install "deeptutor[codebuddy]").'+ )+++def _build_tool_options(sdk: ModuleType, tools: list[dict[str, Any]] | None) -> dict[str, Any]:+ if not tools:+ return {"tools": []}+ decorate = getattr(sdk, "tool", None)+ create_server = getattr(sdk, "create_sdk_mcp_server", None)+ if not callable(decorate) or not callable(create_server):+ return {"tools": []}++ sdk_tools: list[Callable[..., Any]] = []+ allowed: list[str] = []+ for schema in tools:+ function = schema.get("function") if isinstance(schema, dict) else None+ if not isinstance(function, dict):+ continue+ name = str(function.get("name") or "").strip()+ if not name:+ continue+ description = str(function.get("description") or name)+ parameters = function.get("parameters")+ if not isinstance(parameters, dict):+ parameters = {"type": "object", "properties": {}}++ async def pending_result(_args: dict[str, Any]) -> dict[str, Any]:+ return {+ "content": [+ {+ "type": "text",+ "text": (+ "DeepTutor accepted this tool call and will provide its result next."+ ),+ }+ ]+ }++ pending_result.__name__ = f"deeptutor_{name}"+ sdk_tools.append(decorate(name, description, parameters)(pending_result))+ allowed.append(f"{_MCP_TOOL_PREFIX}{name}")++ if not sdk_tools:+ return {"tools": []}+ server = create_server(_MCP_SERVER_NAME, tools=sdk_tools)+ return {+ "tools": allowed,+ "allowed_tools": allowed,+ "mcp_servers": {_MCP_SERVER_NAME: server},+ }+++def _session_signature(+ model: str,+ reasoning_effort: str | None,+ tools: list[dict[str, Any]] | None,+) -> str:+ payload = {+ "model": _strip_model_prefix(model),+ "reasoning_effort": reasoning_effort or "",+ "tools": tools or [],+ }+ return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)+++def _incremental_prompt(+ session: _CodeBuddySession,+ messages: list[dict[str, Any]],+) -> str:+ previous = session.messages+ if previous and len(messages) >= len(previous) and messages[: len(previous)] == previous:+ delta = list(messages[len(previous) :])+ if delta and session.last_response and delta[0].get("role") == "assistant":+ if _content_text(delta[0].get("content")) == session.last_response:+ delta.pop(0)+ prompt = _messages_to_prompt(delta)+ if prompt:+ return prompt+ return _messages_to_prompt(messages)+++async def _consume_messages(+ messages: Any,+ *,+ on_content_delta: Callable[[str], Awaitable[None]] | None,+ interrupt: Callable[[], Awaitable[None]] | None = None,+) -> LLMResponse:+ chunks: list[str] = []+ pending_result_text = ""+ async for message in messages:+ if _is_error_result(message):+ return LLMResponse(+ content=f"Error calling CodeBuddy: {_result_text(message)}",+ finish_reason="error",+ )+ if _is_result_message(message):+ pending_result_text = _result_text(message)+ continue++ tool_calls = _assistant_tool_calls(message)+ text = _assistant_text(message)+ if text:+ chunks.append(text)+ if on_content_delta:+ await on_content_delta(text)+ if tool_calls:+ if interrupt is not None:+ try:+ await interrupt()+ await _drain_interrupted_response(messages)+ except Exception:+ pass+ return LLMResponse(+ content="".join(chunks),+ tool_calls=tool_calls,+ finish_reason="tool_calls",+ )++ if not chunks and pending_result_text:+ chunks.append(pending_result_text)+ if on_content_delta:+ await on_content_delta(pending_result_text)+ return LLMResponse(content="".join(chunks), finish_reason="stop")+++async def _drain_interrupted_response(messages: Any) -> None:+ """Consume the SDK's interrupt result so it cannot leak into the next turn."""+ try:+ async for message in messages:+ if _is_result_message(message) or type(message).__name__ == "ErrorMessage":+ return+ except Exception:+ return+++def _assistant_tool_calls(message: Any) -> list[ToolCallRequest]:+ content = getattr(message, "content", None)+ if content is None and isinstance(message, dict):+ content = message.get("content")+ if not isinstance(content, list):+ return []++ calls: list[ToolCallRequest] = []+ for block in content:+ if isinstance(block, dict):+ block_type = str(block.get("type") or "").lower()+ name = str(block.get("name") or "")+ call_id = str(block.get("id") or "")+ arguments = block.get("input")+ else:+ block_type = type(block).__name__.lower()+ name = str(getattr(block, "name", "") or "")+ call_id = str(getattr(block, "id", "") or "")+ arguments = getattr(block, "input", None)+ if block_type not in {"tool_use", "tooluse"} and not block_type.endswith("tooluseblock"):+ continue+ if not name.startswith(_MCP_TOOL_PREFIX):+ continue+ tool_name = name[len(_MCP_TOOL_PREFIX) :]+ if not tool_name:+ continue+ calls.append(+ ToolCallRequest(+ id=call_id or f"codebuddy_tool_{len(calls)}",+ name=tool_name,+ arguments=arguments if isinstance(arguments, dict) else {},+ )+ )+ return calls+++def _reasoning_options(reasoning_effort: str | None) -> dict[str, Any]:+ """Map DeepTutor reasoning levels to CodeBuddy SDK thinking controls.++ The SDK enables adaptive thinking when the field is omitted, unlike the+ local CodeBuddy CLI configuration. Defaulting to disabled keeps ordinary+ chat latency aligned with the CLI; an explicit effort turns it back on.+ """+ effort = (reasoning_effort or "").strip().lower()+ if effort in {"low", "medium", "high", "xhigh"}:+ return {"thinking": {"type": "adaptive"}, "effort": effort}+ if effort == "adaptive":+ return {"thinking": {"type": "adaptive"}}+ return {"thinking": {"type": "disabled"}}+++def _options_has_api_key_env(options: Any | None) -> bool:+ if options is None:+ return False+ env = getattr(options, "env", None)+ if isinstance(env, dict) and env.get(_CODEBUDDY_API_KEY_ENV):+ return True+ kwargs = getattr(options, "kwargs", None)+ if isinstance(kwargs, dict):+ option_env = kwargs.get("env")+ return isinstance(option_env, dict) and bool(option_env.get(_CODEBUDDY_API_KEY_ENV))+ return False+++def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:+ sections: list[str] = []+ for message in messages:+ role = str(message.get("role") or "user").strip() or "user"+ content = _content_text(message.get("content"))+ if not content:+ continue+ if role == "system":+ heading = "System instructions"+ elif role == "assistant":+ heading = "Assistant"+ elif role == "tool":+ name = message.get("name") or message.get("tool_call_id") or "tool"+ heading = f"Tool result ({name})"+ else:+ heading = "User"+ sections.append(f"{heading}:\n{content}")++ return "\n\n".join(sections) if sections else ""+++def _content_text(content: Any) -> str:+ if content is None:+ return ""+ if isinstance(content, str):+ return content+ if isinstance(content, dict):+ return _content_part_text(content)+ if isinstance(content, list):+ parts = [_content_part_text(part) for part in content]+ return "\n".join(part for part in parts if part)+ return str(content)+++def _content_part_text(part: Any) -> str:+ if isinstance(part, str):+ return part+ if not isinstance(part, dict):+ return str(part)+ part_type = part.get("type")+ if part_type in {"text", "input_text", "output_text"}:+ return str(part.get("text") or "")+ if "text" in part and isinstance(part.get("text"), str):+ return str(part["text"])+ if part_type in {"image_url", "input_image"}:+ return "[image input omitted]"+ return ""+++def _assistant_text(message: Any) -> str:+ content = getattr(message, "content", None)+ if content is None and isinstance(message, dict):+ content = message.get("content")+ if content is None:+ return ""+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ content = [content]++ chunks: list[str] = []+ for block in content:+ text = _block_text(block)+ if text:+ chunks.append(text)+ return "".join(chunks)+++def _block_text(block: Any) -> str:+ if isinstance(block, str):+ return block+ if isinstance(block, dict):+ block_type = block.get("type")+ if block_type in {"text", "assistant_text"} or "text" in block:+ return str(block.get("text") or "")+ return ""+ block_type = type(block).__name__+ if block_type == "TextBlock" or hasattr(block, "text"):+ return str(getattr(block, "text") or "")+ return ""+++def _is_result_message(message: Any) -> bool:+ message_type = type(message).__name__+ if message_type == "ResultMessage" or message_type.endswith("ResultMessage"):+ return True+ if hasattr(message, "result") and hasattr(message, "is_error"):+ return True+ return isinstance(message, dict) and str(message.get("type") or "").lower() == "result"+++def _is_error_result(message: Any) -> bool:+ if not _is_result_message(message):+ return False+ if isinstance(message, dict):+ return bool(message.get("is_error") or message.get("error"))+ return bool(getattr(message, "is_error", False) or getattr(message, "error", None))+++def _result_text(message: Any) -> str:+ if isinstance(message, dict):+ value = message.get("result") or message.get("error") or message.get("content")+ else:+ value = getattr(message, "result", None) or getattr(message, "error", None)+ return "" if value is None else str(value)+++def _friendly_error(exc: Exception) -> str:+ message = str(exc)+ if "Authentication required" in message:+ return (+ "Error calling CodeBuddy: authentication required. Run "+ "`deeptutor provider login codebuddy`, run `codebuddy` and enter `/login`, "+ "or set CODEBUDDY_API_KEY."+ )+ if "cancel scope" in message.lower():+ return (+ "Error calling CodeBuddy: the SDK session was closed from a different "+ "async task than it was opened on. Retry the message; if it persists, "+ "restart the backend."+ )+ return f"Error calling CodeBuddy: {message}"+++@asynccontextmanager+async def _temporary_codebuddy_api_key(api_key: str | None):+ if not api_key:+ yield+ return+ async with _API_KEY_ENV_LOCK:+ previous = os.environ.get(_CODEBUDDY_API_KEY_ENV)+ os.environ[_CODEBUDDY_API_KEY_ENV] = api_key+ try:+ yield+ finally:+ if previous is None:+ os.environ.pop(_CODEBUDDY_API_KEY_ENV, None)+ else:+ os.environ[_CODEBUDDY_API_KEY_ENV] = previous+++async def fetch_codebuddy_models(api_key: str | None = None) -> list[str]:+ """Return the model catalog currently available to the logged-in account."""+ _load_sdk()+ cli_path = shutil.which("codebuddy") or shutil.which("cbc")+ if not cli_path:+ raise RuntimeError("CodeBuddy CLI is required to sync account models.")++ cli_args = [+ cli_path,+ "--print",+ ".",+ "--model",+ "__deeptutor_list_models__",+ "--output-format",+ "json",+ "--max-turns",+ "1",+ ]+ process_kwargs: dict[str, Any] = {}+ if os.name == "nt":+ command = ["cmd.exe", "/d", "/s", "/c", subprocess.list2cmdline(cli_args)]+ process_kwargs["creationflags"] = (+ subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP+ )+ else:+ command = cli_args+ process_kwargs["start_new_session"] = True++ env = os.environ.copy()+ if api_key:+ env[_CODEBUDDY_API_KEY_ENV] = api_key+ process = await asyncio.create_subprocess_exec(+ *command,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ env=env,+ **process_kwargs,+ )+ stdout, stderr = await process.communicate()+ output = (stdout + b"\n" + stderr).decode("utf-8", errors="replace")+ marker = "supported models for your account:"+ catalog = output.lower().split(marker, 1)[-1] if marker in output.lower() else ""+ models = re.findall(r"(?m)^\s*-\s+([A-Za-z0-9][A-Za-z0-9._-]*)\s*$", catalog)+ if not models:+ raise RuntimeError(output.strip() or "CodeBuddy did not return an account model catalog.")+ return list(dict.fromkeys(models))+++__all__ = [+ "CodeBuddyProvider",+ "DEFAULT_CODEBUDDY_MODEL",+ "fetch_codebuddy_models",+]diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.pyindex 783cc2a2d..99c8647e2 100644--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py@@ -593,6 +593,17 @@ class OpenAICompatProvider(LLMProvider):if not chunk.choices:usage = cls._extract_usage(chunk) or usagecontinue+ # Some providers (CodeBuddy) attach usage to the chunk carrying the+ # last delta rather than to a final choice-less one. Only a report+ # with real numbers replaces what we already have: a gateway that+ # echoes a zero-filled usage object on every delta would otherwise+ # wipe the counts on its way past.+ delta_usage = cls._extract_usage(chunk)+ if delta_usage and any(+ delta_usage.get(key)+ for key in ("prompt_tokens", "completion_tokens", "total_tokens")+ ):+ usage = delta_usagechoice = chunk.choices[0]if choice.finish_reason:finish_reason = choice.finish_reasondiff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.pyindex 485693c9d..c0f4c0a15 100644--- a/deeptutor/services/llm/provider_factory.py+++ b/deeptutor/services/llm/provider_factory.py@@ -60,6 +60,15 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:)provider = GitHubCopilotProvider(default_model=llm_config.model)+ elif backend == "codebuddy":+ from deeptutor.services.llm.provider_core.codebuddy_http_provider import (+ build_codebuddy_provider,+ )++ provider = build_codebuddy_provider(+ api_key=llm_config.api_key or None,+ default_model=llm_config.model,+ )elif backend == "azure_openai":from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProviderdiff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.pyindex d4867fd67..b11c724a8 100644--- a/deeptutor/services/provider_registry.py+++ b/deeptutor/services/provider_registry.py@@ -30,7 +30,7 @@ class ProviderSpec:display_name: str = ""# Which provider implementation to use:- # "openai_compat" | "anthropic" | "azure_openai" | "openai_codex" | "github_copilot"+ # "openai_compat" | "anthropic" | "azure_openai" | "openai_codex" | "github_copilot" | "codebuddy"backend: str = "openai_compat"env_extras: tuple[tuple[str, str], ...] = ()@@ -91,6 +91,9 @@ PROVIDER_ALIASES = {"byteplusCodingPlan": "byteplus_coding_plan","github-copilot": "github_copilot","openai-codex": "openai_codex",+ "codebuddy-code": "codebuddy",+ "codebuddy_code": "codebuddy",+ "workbuddy": "codebuddy","lm-studio": "lm_studio","atlas": "atlascloud","atlas_cloud": "atlascloud",@@ -303,6 +306,16 @@ PROVIDERS: tuple[ProviderSpec, ...] = (strip_model_prefix=True,supports_max_completion_tokens=True,),+ ProviderSpec(+ name="codebuddy",+ keywords=("codebuddy", "workbuddy"),+ env_key="CODEBUDDY_API_KEY",+ display_name="CodeBuddy/WorkBuddy",+ backend="codebuddy",+ is_oauth=True,+ strip_model_prefix=True,+ supports_stream_options=False,+ ),ProviderSpec(name="deepseek",keywords=("deepseek",),diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.mdindex c692e04da..207b0d8ed 100644--- a/deeptutor_cli/README.md+++ b/deeptutor_cli/README.md@@ -226,6 +226,7 @@ deeptutor config show```bashdeeptutor provider login openai-codex # 执行 OpenAI Codex OAuth 登录deeptutor provider login github-copilot # 校验现有 GitHub Copilot 认证是否可用+deeptutor provider login codebuddy # 校验 CodeBuddy SDK 登录;未登录时打开登录入口````openai-codex` 使用 DeepTutor 自己的独立 OAuth 流程登录。它不需要 `OPENAI_API_KEY`,也不会读取或同步本机 `~/.codex`;凭据保存在 `data/system/user-secrets/<owner>/private/openai-codex/`(沙箱访问不到的目录),与 Web 设置页共用。diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.pyindex 468ebc785..117142e73 100644--- a/deeptutor_cli/provider_cmd.py+++ b/deeptutor_cli/provider_cmd.py@@ -17,7 +17,10 @@ def register(app: typer.Typer) -> None:def provider_login(provider: str = typer.Argument(...,- help="Provider: openai-codex (OAuth login) | github-copilot (validate existing Copilot auth)",+ help=(+ "Provider: openai-codex (OAuth login) | github-copilot "+ "(validate existing Copilot auth) | codebuddy (validate CodeBuddy SDK auth)"+ ),),) -> None:"""Authenticate or validate provider access."""@@ -28,8 +31,11 @@ def register(app: typer.Typer) -> None:if key == "github_copilot":maybe_run(_login_github_copilot())return+ if key in {"codebuddy", "codebuddy_code", "workbuddy"}:+ maybe_run(_login_codebuddy())+ returnraise typer.BadParameter(- f"Unknown provider `{provider}`. Supported: openai-codex, github-copilot"+ f"Unknown provider `{provider}`. Supported: openai-codex, github-copilot, codebuddy")@@ -101,3 +107,60 @@ async def _login_github_copilot() -> None:typer.echo(f"GitHub Copilot auth validation failed: {exc}")raise typer.Exit(code=1) from exctyper.echo("GitHub Copilot auth validation succeeded.")+++async def _login_codebuddy() -> None:+ """Validate CodeBuddy auth, starting an SDK login when needed."""+ from deeptutor.services.codebuddy_credentials import load_credentials, probe_account++ credentials = load_credentials()+ if credentials is not None:+ label = await probe_account(credentials)+ if label:+ typer.echo(f"CodeBuddy auth validation succeeded for {label}.")+ return++ try:+ from codebuddy_agent_sdk import authenticate, query+ except ImportError:+ typer.echo(+ "CodeBuddy is not signed in. Sign in with the CodeBuddy IDE plugin, run "+ "`codebuddy` and enter `/login`, or set CODEBUDDY_API_KEY. For in-app login "+ "install the SDK: `python -m pip install codebuddy-agent-sdk`."+ )+ raise typer.Exit(code=1)++ try:+ saw_message = False+ async for _message in query(prompt="Reply with only OK."):+ saw_message = True+ if not saw_message:+ raise RuntimeError("CodeBuddy SDK returned no messages.")+ except Exception as exc:+ if "Authentication required" not in str(exc):+ typer.echo(f"CodeBuddy auth validation failed: {exc}")+ raise typer.Exit(code=1) from exc+ typer.echo("CodeBuddy is not logged in. Starting CodeBuddy login flow ...")+ try:+ auth = await authenticate(timeout=300.0)+ if getattr(auth, "auth_url", ""):+ typer.echo(f"Open this URL to sign in: {auth.auth_url}")+ try:+ webbrowser.open(auth.auth_url)+ except Exception:+ pass+ result = await auth+ except Exception as login_exc:+ typer.echo(f"CodeBuddy login failed: {login_exc}")+ typer.echo("You can also run `codebuddy`, enter `/login`, or set CODEBUDDY_API_KEY.")+ raise typer.Exit(code=1) from login_exc+ userinfo = getattr(result, "userinfo", None)+ label = (+ getattr(userinfo, "user_nickname", None)+ or getattr(userinfo, "user_name", None)+ or getattr(userinfo, "user_id", None)+ or "current account"+ )+ typer.echo(f"CodeBuddy auth validation succeeded for {label}.")+ return+ typer.echo("CodeBuddy auth validation succeeded.")diff --git a/pyproject.toml b/pyproject.tomlindex f689fea7e..4ed206651 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -108,6 +108,15 @@ cli = ["defusedxml>=0.7.1",]+# CodeBuddy chat works over HTTP with the login state the IDE plugin / CLI+# already stores. This extra adds the Agent SDK (a ~130 MB bundled headless+# CLI) for in-app browser login and CLI-driven agent tools.+# Upper-bounded on purpose: the provider probes the SDK for its turn-limit+# and permission-mode kwargs, and a minor bump that renames them would make+# every options build fail. Not in `all` — it vendors a ~130 MB headless CLI+# and chat works over plain HTTP without it.+codebuddy = ["codebuddy-agent-sdk>=0.1.24,<0.2"]+# Compatibility extra for source installs and older docs. These packages are# already included in the public `deeptutor` wheel.server = [diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex dde4aa324..e891f2230 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -995,6 +995,57 @@ async def test_fetch_models_requires_base_url() -> None:assert exc_info.value.status_code == 400+async def test_fetch_models_allows_codebuddy_without_base_url(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import deeptutor.services.llm.factory as factory_module++ async def _fake_fetch(binding: str, base_url: str, api_key: str | None = None):+ assert (binding, base_url, api_key) == ("codebuddy", "", None)+ return ["hy3", "glm-5.2"]++ monkeypatch.setattr(factory_module, "fetch_models", _fake_fetch)++ response = await settings_router.fetch_models_from_provider(+ settings_router.FetchModelsPayload(binding="codebuddy")+ )++ assert response == {+ "models": [+ {"id": "hy3", "name": "hy3"},+ {"id": "glm-5.2", "name": "glm-5.2"},+ ]+ }+++async def test_codebuddy_auth_routes_use_admin_scoped_service(monkeypatch) -> None:+ class FakeService:+ async def status(self):+ return {"connection": "connected"}++ async def start_login(self):+ return {"connection": "authorizing"}++ async def cancel_login(self):+ return {"connection": "disconnected"}++ async def logout(self):+ return {"connection": "disconnected", "user_label": None}++ monkeypatch.setattr(settings_router, "_require_settings_admin", lambda: None)+ monkeypatch.setattr(settings_router, "get_codebuddy_auth_service", lambda: FakeService())++ assert await settings_router.get_codebuddy_auth_status() == {"connection": "connected"}+ assert await settings_router.start_codebuddy_auth() == {"connection": "authorizing"}+ assert await settings_router.cancel_codebuddy_auth() == {"connection": "disconnected"}+ assert await settings_router.logout_codebuddy_auth() == {+ "connection": "disconnected",+ "user_label": None,+ }++@pytest.mark.asyncioasync def test_fetch_models_maps_provider_error_to_502(monkeypatch: pytest.MonkeyPatch) -> None:from fastapi import HTTPExceptiondiff --git a/tests/cli/test_codebuddy_login.py b/tests/cli/test_codebuddy_login.pynew file mode 100644index 000000000..5d5e8bfde--- /dev/null+++ b/tests/cli/test_codebuddy_login.py@@ -0,0 +1,53 @@+from __future__ import annotations++import sys+from types import SimpleNamespace++import pytest++from deeptutor_cli.provider_cmd import _login_codebuddy+++class FakeAuthFlow:+ auth_url = "https://codebuddy.example/login"++ def __await__(self):+ async def _wait():+ return SimpleNamespace(+ userinfo=SimpleNamespace(+ user_id="u1",+ user_name="karsa",+ user_nickname="Karsa",+ )+ )++ return _wait().__await__()+++async def test_codebuddy_login_starts_auth_flow_when_not_logged_in(monkeypatch, capsys) -> None:+ opened: list[str] = []++ async def fake_query(**_kwargs):+ if False:+ yield None+ raise RuntimeError("Authentication required. Please use /login command")++ async def fake_authenticate(**kwargs):+ assert kwargs["timeout"] == 300.0+ return FakeAuthFlow()++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(query=fake_query, authenticate=fake_authenticate),+ )+ monkeypatch.setattr("deeptutor_cli.provider_cmd.webbrowser.open", opened.append)++ await _login_codebuddy()++ output = capsys.readouterr().out+ assert "Starting CodeBuddy login flow" in output+ assert "https://codebuddy.example/login" in output+ assert "CodeBuddy auth validation succeeded for Karsa." in output+ assert opened == ["https://codebuddy.example/login"]diff --git a/tests/cli/test_provider_cli.py b/tests/cli/test_provider_cli.pyindex 3dd7eca6b..17cad208a 100644--- a/tests/cli/test_provider_cli.py+++ b/tests/cli/test_provider_cli.py@@ -15,24 +15,32 @@ ROOT_README = (ROOT / "README.md").read_text(encoding="utf-8")class ProviderCliDocsContractTest(unittest.TestCase):def test_provider_contract_describes_copilot_as_validation_not_oauth_login(self) -> None:self.assertIn(- 'help="Provider: openai-codex (OAuth login) | github-copilot (validate existing Copilot auth)"',+ '"Provider: openai-codex (OAuth login) | github-copilot "',PROVIDER_CMD,)+ self.assertIn("| codebuddy (validate CodeBuddy SDK auth)", PROVIDER_CMD)self.assertIn('"""Authenticate or validate provider access."""', PROVIDER_CMD)self.assertIn("GitHub Copilot auth validation succeeded.", PROVIDER_CMD)self.assertIn("GitHub Copilot auth validation failed:", PROVIDER_CMD)+ self.assertIn("CodeBuddy auth validation succeeded.", PROVIDER_CMD)+ self.assertIn("CodeBuddy auth validation failed:", PROVIDER_CMD)+ self.assertIn("Starting CodeBuddy login flow", PROVIDER_CMD)self.assertNotIn("OAuth provider: openai-codex | github-copilot", PROVIDER_CMD)self.assertNotIn("GitHub Copilot OAuth authentication succeeded.", PROVIDER_CMD)def test_readmes_match_the_cli_contract(self) -> None:self.assertIn(- "Provider auth (`openai-codex` OAuth login; `github-copilot` validates an existing Copilot auth session)",+ "Provider auth (`openai-codex` OAuth login; `github-copilot` validates an existing Copilot auth session; `codebuddy` validates CodeBuddy SDK auth and starts login when needed)",ROOT_README,)self.assertIn("deeptutor provider login github-copilot # 校验现有 GitHub Copilot 认证是否可用",CLI_README,)+ self.assertIn(+ "deeptutor provider login codebuddy # 校验 CodeBuddy SDK 登录;未登录时打开登录入口",+ CLI_README,+ )self.assertNotIn("OAuth login (`openai-codex`, `github-copilot`)", ROOT_README)diff --git a/tests/conftest.py b/tests/conftest.pyindex d20cffa79..8d233738b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -89,6 +89,32 @@ def _guard_legacy_multi_user_migration(monkeypatch):yield[email protected](autouse=True)+def _isolate_codebuddy_login(monkeypatch):+ """Hide the developer's real CodeBuddy session from every test.++ The CodeBuddy provider reads the OAuth session the IDE plugin / CLI stores+ outside the repo, so without this a developer who is signed in gets+ different results than CI. Tests that exercise the signed-in path point the+ override at a fixture file.+ """+ from deeptutor.services import codebuddy_credentials++ monkeypatch.setenv(+ "DEEPTUTOR_CODEBUDDY_AUTH_FILE", str(Path("/nonexistent/codebuddy-auth.info"))+ )+ monkeypatch.setattr(+ codebuddy_credentials,+ "_local_storage_dir",+ lambda: Path("/nonexistent/codebuddy-local-storage"),+ )+ monkeypatch.delenv("CODEBUDDY_API_KEY", raising=False)+ monkeypatch.delenv("CODEBUDDY_BASE_URL", raising=False)+ monkeypatch.delenv("CODEBUDDY_INTERNET_ENVIRONMENT", raising=False)+ monkeypatch.delenv("DEEPTUTOR_CODEBUDDY_BACKEND", raising=False)+ yield++# ---------------------------------------------------------------------------# StreamBus# ---------------------------------------------------------------------------diff --git a/tests/core/test_agentic_client_provider_kwargs.py b/tests/core/test_agentic_client_provider_kwargs.pyindex cd7d86475..36656245f 100644--- a/tests/core/test_agentic_client_provider_kwargs.py+++ b/tests/core/test_agentic_client_provider_kwargs.py@@ -174,6 +174,32 @@ def test_build_openai_client_routes_github_copilot_backend_through_adapter(monkeassert captured["default_model"] == "github-copilot/gpt-4.1"+def test_build_openai_client_routes_codebuddy_backend_through_adapter(monkeypatch) -> None:+ captured = {}++ class FakeProvider:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr(+ "deeptutor.services.llm.provider_core.codebuddy_http_provider.CodeBuddyHTTPProvider",+ FakeProvider,+ )++ client = build_openai_client(+ LLMClientConfig(+ binding="codebuddy",+ model="codebuddy/hy3",+ api_key="sk-codebuddy",+ base_url=None,+ )+ )++ assert isinstance(client, _ProviderOpenAIAdapter)+ assert captured["api_key"] == "sk-codebuddy"+ assert captured["default_model"] == "codebuddy/hy3"++def test_anthropic_backend_can_use_native_tool_calling() -> None:assert can_use_native_tool_calling(binding="custom_anthropic", model="claude-test") is Trueassert can_use_native_tool_calling(binding="minimax_anthropic", model="MiniMax-M3") is True@@ -227,6 +253,10 @@ def test_openai_codex_backend_can_use_native_tool_calling() -> None:)+def test_codebuddy_backend_can_use_native_tool_calling() -> None:+ assert can_use_native_tool_calling(binding="codebuddy", model="codebuddy/hy3") is True++def test_local_and_github_copilot_backends_stay_opted_out_of_native_tools() -> None:# Local OpenAI-compatible servers have model-dependent, unreliable tool support.# GitHub Copilot remains opted out until its native tool path is validated.diff --git a/tests/multi_user/test_model_access.py b/tests/multi_user/test_model_access.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/multi_user/test_owner_bound_models.py b/tests/multi_user/test_owner_bound_models.pyindex 0c2b1ca37..d738c9edf 100644--- a/tests/multi_user/test_owner_bound_models.py+++ b/tests/multi_user/test_owner_bound_models.py@@ -89,3 +89,19 @@ def test_ordinary_shared_profiles_stay_grantable(tmp_path, monkeypatch):) == {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}finally:reset_current_user(token)+++def test_a_codebuddy_profile_is_owner_bound_by_its_binding() -> None:+ """CodeBuddy reads the operator's own IDE-plugin login on this host.++ Codex stamps ``owner_bound`` onto the managed profile it publishes, but a+ CodeBuddy profile is created by hand in the settings editor and has nowhere+ to acquire the flag — so without this the administrator's own subscription+ would be grantable to every account on the deployment.+ """+ assert model_access.is_owner_bound({"binding": "codebuddy"}) is True+ assert model_access.is_owner_bound({"binding": "CodeBuddy"}) is True+ # An ordinary team key stays grantable.+ assert model_access.is_owner_bound({"binding": "openai"}) is False+ # The explicit flag still wins for anything else that sets it.+ assert model_access.is_owner_bound({"binding": "openai", "owner_bound": True}) is Truediff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.pyindex 54dcd0ac4..fb8d3fb18 100644--- a/tests/services/config/test_provider_runtime.py+++ b/tests/services/config/test_provider_runtime.py@@ -422,6 +422,27 @@ def test_llm_lm_studio_alias_resolves_to_local_provider() -> None:assert resolved.api_key == "sk-no-key-required"+def test_llm_codebuddy_resolves_without_endpoint() -> None:+ catalog = _build_catalog(+ llm_profile={+ "id": "llm-p",+ "name": "CodeBuddy",+ "binding": "codebuddy",+ "base_url": "",+ "api_key": "",+ "api_version": "",+ "extra_headers": {},+ "models": [{"id": "llm-m", "name": "CodeBuddy Default", "model": "codebuddy/default"}],+ }+ )++ resolved = resolve_llm_runtime_config(catalog=catalog)++ assert resolved.provider_name == "codebuddy"+ assert resolved.provider_mode == "oauth"+ assert resolved.effective_url is None++def test_llm_context_window_passes_through_from_catalog() -> None:catalog = _build_catalog(llm_profile={diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.pyindex 59facfbbb..35ba69559 100644--- a/tests/services/llm/test_capabilities.py+++ b/tests/services/llm/test_capabilities.py@@ -90,6 +90,12 @@ def test_custom_and_dashscope_openai_compat_support_native_tools_for_qwen() -> Nassert has_thinking_tags("custom", "qwen3.6-plus") is True+def test_codebuddy_capabilities_use_agent_sdk_mcp_tools() -> None:+ assert supports_tools("codebuddy", "codebuddy/default") is True+ assert supports_response_format("codebuddy", "codebuddy/default") is False+ assert supports_vision("codebuddy", "codebuddy/default") is False++def test_qwen_model_override_enables_vision() -> None:assert supports_vision("dashscope", "qwen-vl-plus") is Trueassert supports_vision("openai", "qwen2.5-vl-72b-instruct") is Truediff --git a/tests/services/llm/test_codebuddy_http_provider.py b/tests/services/llm/test_codebuddy_http_provider.pynew file mode 100644index 000000000..35190a4cd--- /dev/null+++ b/tests/services/llm/test_codebuddy_http_provider.py@@ -0,0 +1,161 @@+"""Tests for the SDK-free CodeBuddy HTTP provider."""++from __future__ import annotations++import json+from pathlib import Path+import time+from typing import Any++import pytest++from deeptutor.services.codebuddy_credentials import (+ INTERNAL_ENDPOINT,+ CodeBuddyAuthUnavailable,+)+from deeptutor.services.llm.provider_core import codebuddy_http_provider as http_module+from deeptutor.services.llm.provider_core.base import LLMResponse+from deeptutor.services.llm.provider_core.codebuddy_http_provider import (+ CodeBuddyHTTPProvider,+ build_codebuddy_provider,+ codebuddy_http_available,+)+++def _sign_in(tmp_path: Path, monkeypatch, *, expires_in: float = 86400.0) -> Path:+ path = tmp_path / "Tencent-Cloud.coding-copilot.info"+ path.write_text(+ json.dumps(+ {+ "account": {"uid": "uid-1", "nickname": "tester"},+ "auth": {+ "accessToken": "access-token",+ "refreshToken": "refresh-token",+ "expiresAt": int((time.time() + expires_in) * 1000),+ "refreshExpiresAt": int((time.time() + 7776000) * 1000),+ "domain": "www.codebuddy.cn",+ },+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_AUTH_FILE", str(path))+ return path+++def _capture_stream(monkeypatch) -> dict[str, Any]:+ captured: dict[str, Any] = {}++ async def fake_chat_stream(self, **kwargs):+ captured.update(kwargs)+ captured["api_key"] = self._client.api_key+ captured["base_url"] = str(self._client.base_url).rstrip("/")+ return LLMResponse(content="OK")++ monkeypatch.setattr(+ "deeptutor.services.llm.provider_core.openai_compat_provider."+ "OpenAICompatProvider.chat_stream",+ fake_chat_stream,+ )+ return captured+++async def test_provider_uses_local_session_and_regional_endpoint(tmp_path, monkeypatch) -> None:+ _sign_in(tmp_path, monkeypatch)+ captured = _capture_stream(monkeypatch)++ provider = CodeBuddyHTTPProvider()+ response = await provider.chat_stream(messages=[{"role": "user", "content": "hi"}])++ assert response.content == "OK"+ assert captured["api_key"] == "access-token"+ assert captured["base_url"] == INTERNAL_ENDPOINT + "/v2"+ assert provider.extra_headers["X-User-Id"] == "uid-1"+++async def test_blocking_chat_streams_because_cloud_rejects_non_stream(+ tmp_path, monkeypatch+) -> None:+ _sign_in(tmp_path, monkeypatch)+ captured = _capture_stream(monkeypatch)++ async def fail_chat(self, **kwargs):+ raise AssertionError("CodeBuddy rejects stream: false")++ monkeypatch.setattr(+ "deeptutor.services.llm.provider_core.openai_compat_provider.OpenAICompatProvider.chat",+ fail_chat,+ )++ response = await CodeBuddyHTTPProvider().chat(messages=[{"role": "user", "content": "hi"}])++ assert response.content == "OK"+ assert captured["messages"] == [{"role": "user", "content": "hi"}]+++async def test_expired_session_is_refreshed_before_the_request(tmp_path, monkeypatch) -> None:+ _sign_in(tmp_path, monkeypatch, expires_in=-60.0)+ captured = _capture_stream(monkeypatch)++ async def fake_refresh(credentials):+ from dataclasses import replace++ return replace(credentials, access_token="fresh-token", expires_at=time.time() + 3600)++ monkeypatch.setattr(http_module, "refresh_credentials", fake_refresh)++ await CodeBuddyHTTPProvider().chat_stream(messages=[{"role": "user", "content": "hi"}])++ assert captured["api_key"] == "fresh-token"+++async def test_signed_out_provider_reports_how_to_sign_in() -> None:+ provider = CodeBuddyHTTPProvider()++ with pytest.raises(CodeBuddyAuthUnavailable, match="not signed in"):+ await provider.chat_stream(messages=[{"role": "user", "content": "hi"}])+++async def test_api_key_mode_sends_the_key_header(monkeypatch) -> None:+ captured = _capture_stream(monkeypatch)++ provider = CodeBuddyHTTPProvider(api_key="cb-key")+ await provider.chat_stream(messages=[{"role": "user", "content": "hi"}])++ assert provider.extra_headers["X-API-Key"] == "cb-key"+ assert captured["api_key"] == "cb-key"+++async def test_provider_strips_deeptutor_session_id(tmp_path, monkeypatch) -> None:+ _sign_in(tmp_path, monkeypatch)+ captured = _capture_stream(monkeypatch)++ await CodeBuddyHTTPProvider().chat_stream(+ messages=[{"role": "user", "content": "hi"}],+ deeptutor_session_id="session-1",+ )++ assert "deeptutor_session_id" not in captured+++def test_placeholder_api_key_is_not_treated_as_auth() -> None:+ assert codebuddy_http_available("sk-no-key-required") is False+++def test_dispatch_prefers_http_when_signed_in(tmp_path, monkeypatch) -> None:+ _sign_in(tmp_path, monkeypatch)+ monkeypatch.setattr(http_module, "sdk_installed", lambda: True)++ assert isinstance(build_codebuddy_provider(), CodeBuddyHTTPProvider)+++def test_dispatch_falls_back_to_http_when_sdk_is_absent(monkeypatch) -> None:+ monkeypatch.setattr(http_module, "sdk_installed", lambda: False)++ assert isinstance(build_codebuddy_provider(), CodeBuddyHTTPProvider)diff --git a/tests/services/llm/test_codebuddy_provider.py b/tests/services/llm/test_codebuddy_provider.pynew file mode 100644index 000000000..aafb02fda--- /dev/null+++ b/tests/services/llm/test_codebuddy_provider.py@@ -0,0 +1,466 @@+from __future__ import annotations++import asyncio+import os+import shutil+import sys+from types import SimpleNamespace++import pytest++from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.provider_core import CodeBuddyProvider+from deeptutor.services.llm.provider_core.codebuddy_provider import fetch_codebuddy_models+from deeptutor.services.llm.provider_factory import get_runtime_provider+from deeptutor.services.provider_registry import find_by_name+++class FakeOptions:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++class FakeTextBlock:+ def __init__(self, text: str):+ self.text = text+++class FakeAssistantMessage:+ def __init__(self, content):+ self.content = content+++class FakeResultMessage:+ def __init__(self, result: str = "", is_error: bool = False):+ self.result = result+ self.is_error = is_error+++class FakeToolUseBlock:+ def __init__(self, call_id: str, name: str, arguments: dict[str, object]):+ self.id = call_id+ self.name = name+ self.input = arguments+++def fake_tool(name, description, parameters):+ def decorate(func):+ func.tool_definition = (name, description, parameters)+ return func++ return decorate+++def fake_mcp_server(name, tools):+ return {"name": name, "tools": tools}+++async def test_codebuddy_provider_streams_sdk_text_blocks(monkeypatch) -> None:+ captured: dict[str, object] = {}++ async def fake_query(**kwargs):+ captured.update(kwargs)+ yield FakeAssistantMessage([FakeTextBlock("hel"), FakeTextBlock("lo")])+ yield FakeResultMessage("ignored because assistant text already streamed")++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(query=fake_query, CodeBuddyAgentOptions=FakeOptions),+ )+ monkeypatch.delenv("CODEBUDDY_API_KEY", raising=False)++ provider = CodeBuddyProvider(api_key="secret", default_model="codebuddy/claude-sonnet-4")+ deltas: list[str] = []+ response = await provider.chat_stream(+ messages=[+ {"role": "system", "content": "Be concise."},+ {"role": "user", "content": [{"type": "text", "text": "Say hello"}]},+ ],+ model=None,+ max_tokens=32,+ on_content_delta=lambda text: _append_async(deltas, text),+ )++ assert response.content == "hello"+ assert deltas == ["hello"]+ assert "System instructions:\nBe concise." in captured["prompt"]+ assert "User:\nSay hello" in captured["prompt"]+ assert captured["options"].kwargs["model"] == "claude-sonnet-4"+ assert captured["options"].kwargs["permission_mode"] == "plan"+ assert captured["options"].kwargs["env"]["CODEBUDDY_API_KEY"] == "secret"+ assert captured["options"].kwargs["tools"] == []+ assert captured["options"].kwargs["thinking"] == {"type": "disabled"}+ assert "CODEBUDDY_API_KEY" not in os.environ+++async def test_codebuddy_explicit_reasoning_effort_enables_sdk_thinking(monkeypatch) -> None:+ captured: dict[str, object] = {}++ async def fake_query(**kwargs):+ captured.update(kwargs)+ yield FakeResultMessage("done")++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(query=fake_query, CodeBuddyAgentOptions=FakeOptions),+ )++ response = await CodeBuddyProvider().chat(+ [{"role": "user", "content": "think"}],+ reasoning_effort="high",+ )++ assert response.content == "done"+ assert captured["options"].kwargs["thinking"] == {"type": "adaptive"}+ assert captured["options"].kwargs["effort"] == "high"+++async def test_codebuddy_provider_uses_result_when_no_assistant_text(monkeypatch) -> None:+ async def fake_query(**_kwargs):+ yield FakeResultMessage("final")++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(query=fake_query, CodeBuddyAgentOptions=FakeOptions),+ )++ response = await CodeBuddyProvider().chat([{"role": "user", "content": "ping"}])++ assert response.content == "final"+ assert response.finish_reason == "stop"+++async def test_codebuddy_provider_maps_sdk_mcp_tool_calls(monkeypatch) -> None:+ captured: dict[str, object] = {}++ async def fake_query(**kwargs):+ captured.update(kwargs)+ yield FakeAssistantMessage(+ [+ FakeToolUseBlock(+ "tool-1",+ "mcp__deeptutor__web_search",+ {"query": "latest news"},+ )+ ]+ )++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(+ query=fake_query,+ CodeBuddyAgentOptions=FakeOptions,+ tool=fake_tool,+ create_sdk_mcp_server=fake_mcp_server,+ ),+ )++ response = await CodeBuddyProvider().chat(+ [{"role": "user", "content": "Search the web"}],+ tools=[+ {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+ }+ ],+ )++ assert response.finish_reason == "tool_calls"+ assert len(response.tool_calls) == 1+ assert response.tool_calls[0].id == "tool-1"+ assert response.tool_calls[0].name == "web_search"+ assert response.tool_calls[0].arguments == {"query": "latest news"}+ option_kwargs = captured["options"].kwargs+ assert option_kwargs["tools"] == ["mcp__deeptutor__web_search"]+ assert "deeptutor" in option_kwargs["mcp_servers"]+++async def test_codebuddy_session_survives_cross_task_turns(monkeypatch) -> None:+ """Chat streams run each turn in a fresh task; SDK cancel scopes must not."""+ clients = []++ class FakeClient:+ def __init__(self, options):+ self.options = options+ self.prompts = []+ self.connect_task = None+ self.disconnect_task = None+ self.response_index = 0+ clients.append(self)++ async def connect(self):+ self.connect_task = asyncio.current_task()++ async def query(self, prompt):+ self.prompts.append(prompt)++ async def receive_response(self):+ self.response_index += 1+ yield FakeResultMessage("first" if self.response_index == 1 else "second")++ async def interrupt(self):+ pass++ async def disconnect(self):+ self.disconnect_task = asyncio.current_task()++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(+ query=lambda **_kwargs: None,+ CodeBuddyAgentOptions=FakeOptions,+ CodeBuddySDKClient=FakeClient,+ ),+ )+ provider = CodeBuddyProvider()++ async def turn(content: str) -> str:+ response = await provider.chat(+ [{"role": "user", "content": content}],+ deeptutor_session_id="cross-task",+ )+ return response.content++ first = await asyncio.create_task(turn("one"))+ second = await asyncio.create_task(turn("two"))+ await provider.aclose()++ assert first == "first"+ assert second == "second"+ assert len(clients) == 1+ assert clients[0].connect_task is not None+ assert clients[0].disconnect_task is clients[0].connect_task+ assert clients[0].prompts == ["User:\none", "User:\ntwo"]+++async def test_codebuddy_provider_reuses_session_and_sends_message_delta(monkeypatch) -> None:+ clients = []++ class FakeClient:+ def __init__(self, options):+ self.options = options+ self.prompts = []+ self.connected = 0+ self.disconnected = 0+ self.response_index = 0+ clients.append(self)++ async def connect(self):+ self.connected += 1++ async def query(self, prompt):+ self.prompts.append(prompt)++ async def receive_response(self):+ self.response_index += 1+ yield FakeResultMessage("first" if self.response_index == 1 else "second")++ async def interrupt(self):+ pass++ async def disconnect(self):+ self.disconnected += 1++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(+ query=lambda **_kwargs: None,+ CodeBuddyAgentOptions=FakeOptions,+ CodeBuddySDKClient=FakeClient,+ ),+ )+ provider = CodeBuddyProvider()+ initial = [{"role": "user", "content": "first question"}]+ first = await provider.chat(initial, deeptutor_session_id="chat-1")+ second = await provider.chat(+ [+ *initial,+ {"role": "assistant", "content": "first"},+ {"role": "user", "content": "second question"},+ ],+ deeptutor_session_id="chat-1",+ )++ assert first.content == "first"+ assert second.content == "second"+ assert len(clients) == 1+ assert clients[0].connected == 1+ assert clients[0].prompts == ["User:\nfirst question", "User:\nsecond question"]+ await provider.aclose()+ assert clients[0].disconnected == 1+++async def test_codebuddy_session_drains_interrupt_before_tool_result_round(monkeypatch) -> None:+ class FakeClient:+ def __init__(self, options):+ self.options = options+ self.response_index = 0+ self.interrupted = 0++ async def connect(self):+ pass++ async def query(self, _prompt):+ self.response_index += 1++ async def receive_response(self):+ if self.response_index == 1:+ yield FakeAssistantMessage(+ [+ FakeToolUseBlock(+ "tool-1",+ "mcp__deeptutor__web_search",+ {"query": "latest news"},+ )+ ]+ )+ yield FakeResultMessage("Interrupted by user")+ else:+ yield FakeResultMessage("final answer")++ async def interrupt(self):+ self.interrupted += 1++ async def disconnect(self):+ pass++ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(+ query=lambda **_kwargs: None,+ CodeBuddyAgentOptions=FakeOptions,+ CodeBuddySDKClient=FakeClient,+ tool=fake_tool,+ create_sdk_mcp_server=fake_mcp_server,+ ),+ )+ provider = CodeBuddyProvider()+ tools = [+ {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]+ initial = [{"role": "user", "content": "Search"}]++ tool_response = await provider.chat(+ initial,+ tools=tools,+ deeptutor_session_id="chat-tools",+ )+ final_response = await provider.chat(+ [+ *initial,+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [tool_response.tool_calls[0].to_openai_tool_call()],+ },+ {+ "role": "tool",+ "tool_call_id": "tool-1",+ "content": "real search result",+ },+ ],+ tools=tools,+ deeptutor_session_id="chat-tools",+ )++ assert tool_response.finish_reason == "tool_calls"+ assert final_response.content == "final answer"+ session = provider._sessions["chat-tools"]+ assert session.client.interrupted == 1+ await provider.aclose()+++async def test_fetch_codebuddy_models_uses_account_catalog(monkeypatch) -> None:+ captured: dict[str, object] = {}++ class FakeProcess:+ async def communicate(self):+ return (+ b"Currently supported models for your account:\n - hy3\n - glm-5.2\n - hy3\n",+ b"",+ )++ async def fake_subprocess(*args, **kwargs):+ captured["args"] = args+ captured["env"] = kwargs["env"]+ return FakeProcess()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_subprocess)+ monkeypatch.setattr(+ shutil,+ "which",+ lambda name: "codebuddy.cmd" if name == "codebuddy" else None,+ )+ monkeypatch.setitem(+ sys.modules,+ "codebuddy_agent_sdk",+ SimpleNamespace(query=lambda: None),+ )++ assert await fetch_codebuddy_models("secret") == ["hy3", "glm-5.2"]+ assert isinstance(captured["env"], dict)+ assert captured["env"]["CODEBUDDY_API_KEY"] == "secret"+++def test_codebuddy_registry_aliases_and_factory(monkeypatch) -> None:+ spec = find_by_name("workbuddy")++ assert spec is not None+ assert spec.name == "codebuddy"+ assert spec.backend == "codebuddy"++ monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_BACKEND", "sdk")+ monkeypatch.setattr(+ "deeptutor.services.llm.provider_core.codebuddy_http_provider.sdk_installed",+ lambda: True,+ )+ provider = get_runtime_provider(+ LLMConfig(+ model="codebuddy/hy3",+ api_key="",+ binding="codebuddy",+ provider_name="codebuddy",+ )+ )++ assert isinstance(provider, CodeBuddyProvider)+++def test_codebuddy_ignores_deeptutor_no_key_placeholder() -> None:+ provider = CodeBuddyProvider(api_key="sk-no-key-required")++ assert provider.api_key is None+++async def _append_async(items: list[str], text: str) -> None:+ items.append(text)diff --git a/tests/services/test_codebuddy_auth.py b/tests/services/test_codebuddy_auth.pynew file mode 100644index 000000000..eaf920ac9--- /dev/null+++ b/tests/services/test_codebuddy_auth.py@@ -0,0 +1,175 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest++from deeptutor.services import codebuddy_auth+from deeptutor.services.codebuddy_auth import CodeBuddyAuthService+++class FakeFlow:+ def __init__(self, auth_url: str, result=None) -> None:+ self.auth_url = auth_url+ self.result = result+ self.cancelled = False+ self.ready = asyncio.Event()+ if result is not None:+ self.ready.set()++ def __await__(self):+ return self.wait().__await__()++ async def wait(self):+ await self.ready.wait()+ return self.result++ async def cancel(self) -> None:+ self.cancelled = True+++def auth_result(label: str = "Karsa"):+ return SimpleNamespace(+ userinfo=SimpleNamespace(user_nickname=label, user_name="", user_id="user-1")+ )+++async def test_status_reports_existing_local_login(monkeypatch) -> None:+ flow = FakeFlow("", auth_result())+ monkeypatch.setattr(codebuddy_auth, "_start_sdk_authenticate", lambda: _value(flow))++ status = await CodeBuddyAuthService().status()++ assert status == {+ "connection": "connected",+ "operation_state": "completed",+ "authorize_url": None,+ "user_label": "Karsa",+ "error_code": None,+ }+++async def test_status_cancels_probe_when_login_is_required(monkeypatch) -> None:+ flow = FakeFlow("https://codebuddy.example/login")+ monkeypatch.setattr(codebuddy_auth, "_start_sdk_authenticate", lambda: _value(flow))++ status = await CodeBuddyAuthService().status()++ assert status["connection"] == "disconnected"+ assert status["authorize_url"] is None+ assert flow.cancelled is True+++async def test_start_login_exposes_url_then_records_completion(monkeypatch) -> None:+ flow = FakeFlow("https://codebuddy.example/login")+ monkeypatch.setattr(codebuddy_auth, "_start_sdk_authenticate", lambda: _value(flow))+ service = CodeBuddyAuthService()++ started = await service.start_login()++ assert started["connection"] == "authorizing"+ assert started["operation_state"] == "waiting"+ assert started["authorize_url"] == "https://codebuddy.example/login"++ flow.result = auth_result("CodeBuddy User")+ flow.ready.set()+ await asyncio.sleep(0)+ await asyncio.sleep(0)++ completed = service.public_status()+ assert completed["connection"] == "connected"+ assert completed["user_label"] == "CodeBuddy User"+ assert completed["authorize_url"] is None+++async def test_start_login_reports_missing_sdk(monkeypatch) -> None:+ async def missing():+ raise ImportError("codebuddy-agent-sdk is not installed")++ monkeypatch.setattr(codebuddy_auth, "_start_sdk_authenticate", missing)++ status = await CodeBuddyAuthService().start_login()++ assert status["connection"] == "error"+ assert status["error_code"] == "sdk_missing"+++async def test_logout_disconnects_when_no_session_remains(monkeypatch) -> None:+ """With no login on the host there is nothing to report but disconnection."""+ service = CodeBuddyAuthService()+ service._connection = "connected"+ service._operation_state = "completed"+ service._user_label = "Old Account"++ status = await service.logout()++ assert status == {+ "connection": "disconnected",+ "operation_state": None,+ "authorize_url": None,+ "user_label": None,+ "error_code": None,+ }+++async def test_status_accepts_ide_session_without_the_sdk(tmp_path, monkeypatch) -> None:+ _write_ide_session(tmp_path, monkeypatch)++ async def unused_sdk():+ raise AssertionError("the SDK must not be probed when a session file exists")++ monkeypatch.setattr(codebuddy_auth, "_start_sdk_authenticate", unused_sdk)+ monkeypatch.setattr("deeptutor.services.codebuddy_credentials.probe_account", _account_label)++ status = await CodeBuddyAuthService().status()++ assert status["connection"] == "connected"+ assert status["user_label"] == "tester"+ assert status["error_code"] is None+++async def test_logout_explains_that_an_ide_session_ends_in_the_ide(tmp_path, monkeypatch) -> None:+ """DeepTutor never ends a session it does not own.++ The auth file is shared with the IDE plugin and the CLI on this host —+ signing it out from a web endpoint would sign the operator out of their+ editor, and on a shared host out of whoever else is on that login.+ """+ _write_ide_session(tmp_path, monkeypatch)++ status = await CodeBuddyAuthService().logout()++ assert status["connection"] == "connected"+ assert status["error_code"] == "logout_external"+++def _write_ide_session(tmp_path, monkeypatch) -> None:+ import json++ path = tmp_path / "Tencent-Cloud.coding-copilot.info"+ path.write_text(+ json.dumps(+ {+ "account": {"uid": "uid-1", "nickname": "tester"},+ "auth": {"accessToken": "access-token", "domain": "www.codebuddy.cn"},+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_AUTH_FILE", str(path))+++async def _account_label(credentials):+ return credentials.user_label+++async def _value(value):+ return valuediff --git a/tests/services/test_codebuddy_credentials.py b/tests/services/test_codebuddy_credentials.pynew file mode 100644index 000000000..4cb647210--- /dev/null+++ b/tests/services/test_codebuddy_credentials.py@@ -0,0 +1,161 @@+"""Tests for reading the shared CodeBuddy login state."""++from __future__ import annotations++import base64+import gzip+import json+from pathlib import Path+import time++import pytest++from deeptutor.services import codebuddy_credentials+from deeptutor.services.codebuddy_credentials import (+ INTERNAL_ENDPOINT,+ OVERSEAS_ENDPOINT,+ CodeBuddyAuthUnavailable,+ CodeBuddyCredentials,+ cached_model_catalog,+ load_credentials,+ refresh_credentials,+ resolve_api_base,+)+++def _write_auth_file(tmp_path: Path, monkeypatch, **auth_overrides) -> Path:+ auth = {+ "accessToken": "access-token",+ "refreshToken": "refresh-token",+ "tokenType": "Bearer",+ "expiresAt": 1791055241000,+ "refreshExpiresAt": 1793647241000,+ "domain": "www.codebuddy.cn",+ }+ auth.update(auth_overrides)+ path = tmp_path / "Tencent-Cloud.coding-copilot.info"+ path.write_text(+ json.dumps({"account": {"uid": "uid-1", "nickname": "tester"}, "auth": auth}),+ encoding="utf-8",+ )+ monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_AUTH_FILE", str(path))+ return path+++def test_load_credentials_parses_session(tmp_path, monkeypatch) -> None:+ _write_auth_file(tmp_path, monkeypatch)++ credentials = load_credentials()++ assert credentials is not None+ assert credentials.access_token == "access-token"+ assert credentials.refresh_token == "refresh-token"+ assert credentials.user_id == "uid-1"+ assert credentials.user_label == "tester"+ # Epoch milliseconds in the file, seconds in the dataclass.+ assert credentials.expires_at == pytest.approx(1791055241.0)+ assert credentials.is_expired() is False+++def test_load_credentials_returns_none_when_signed_out() -> None:+ assert load_credentials() is None+++def test_load_credentials_rejects_file_without_token(tmp_path, monkeypatch) -> None:+ path = tmp_path / "Tencent-Cloud.coding-copilot.info"+ path.write_text(json.dumps({"auth": {"refreshToken": "only-refresh"}}), encoding="utf-8")+ monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_AUTH_FILE", str(path))++ assert load_credentials() is None+++def test_resolve_api_base_follows_account_domain() -> None:+ assert resolve_api_base("www.codebuddy.cn") == INTERNAL_ENDPOINT + "/v2"+ assert resolve_api_base("www.codebuddy.ai") == OVERSEAS_ENDPOINT + "/v2"+++def test_resolve_api_base_honours_env_overrides(monkeypatch) -> None:+ monkeypatch.setenv("CODEBUDDY_BASE_URL", "https://proxy.example.com")+ assert resolve_api_base("www.codebuddy.ai") == "https://proxy.example.com/v2"++ monkeypatch.delenv("CODEBUDDY_BASE_URL")+ monkeypatch.setenv("CODEBUDDY_INTERNET_ENVIRONMENT", "internal")+ assert resolve_api_base("www.codebuddy.ai") == INTERNAL_ENDPOINT + "/v2"+++def test_cached_model_catalog_reads_cli_cache(tmp_path, monkeypatch) -> None:+ config = {"endpoint": INTERNAL_ENDPOINT, "models": [{"id": "default"}, {"id": "glm-5.2"}]}+ blob = base64.b64encode(gzip.compress(json.dumps(config).encode())).decode()+ (tmp_path / "entry_abc.info").write_text(json.dumps(blob), encoding="utf-8")+ monkeypatch.setattr(codebuddy_credentials, "_local_storage_dir", lambda: tmp_path)++ assert cached_model_catalog() == ["default", "glm-5.2"]+ assert resolve_api_base("www.codebuddy.ai") == INTERNAL_ENDPOINT + "/v2"+++def test_expired_session_without_refresh_token_is_reported(tmp_path, monkeypatch) -> None:+ _write_auth_file(+ tmp_path,+ monkeypatch,+ refreshToken="",+ expiresAt=int((time.time() - 60) * 1000),+ )++ credentials = load_credentials()++ assert credentials is not None+ assert credentials.is_expired() is True+ assert credentials.can_refresh() is False+++async def test_refresh_credentials_requires_a_refresh_token() -> None:+ credentials = CodeBuddyCredentials(access_token="stale", refresh_token="")++ with pytest.raises(CodeBuddyAuthUnavailable):+ await refresh_credentials(credentials)+++def test_a_cached_endpoint_cannot_redirect_the_bearer_token(tmp_path, monkeypatch) -> None:+ """The product cache belongs to another application on this host.++ Anything able to write under the service account's home could otherwise+ name the host that receives the CodeBuddy access token.+ """+ import base64+ import gzip+ import json++ from deeptutor.services import codebuddy_credentials as creds++ storage = tmp_path / ".codebuddy" / "local_storage"+ storage.mkdir(parents=True)+ blob = {"models": [{"id": "default"}], "endpoint": "http://attacker.example"}+ packed = base64.b64encode(gzip.compress(json.dumps(blob).encode())).decode()+ (storage / "entry_1.info").write_text(json.dumps(packed), encoding="utf-8")+ monkeypatch.setattr(creds, "_local_storage_dir", lambda: storage)+ monkeypatch.delenv("CODEBUDDY_BASE_URL", raising=False)+ monkeypatch.delenv("CODEBUDDY_INTERNET_ENVIRONMENT", raising=False)++ assert creds.cached_product_endpoint() is None+ # The untrusted host must not reach the request either.+ assert "attacker.example" not in creds.resolve_api_base("")+++def test_a_trusted_cached_endpoint_is_still_honoured(tmp_path, monkeypatch) -> None:+ import base64+ import gzip+ import json++ from deeptutor.services import codebuddy_credentials as creds++ storage = tmp_path / ".codebuddy" / "local_storage"+ storage.mkdir(parents=True)+ blob = {"models": [{"id": "default"}], "endpoint": creds.INTERNAL_ENDPOINT}+ packed = base64.b64encode(gzip.compress(json.dumps(blob).encode())).decode()+ (storage / "entry_1.info").write_text(json.dumps(packed), encoding="utf-8")+ monkeypatch.setattr(creds, "_local_storage_dir", lambda: storage)+ monkeypatch.delenv("CODEBUDDY_BASE_URL", raising=False)+ monkeypatch.delenv("CODEBUDDY_INTERNET_ENVIRONMENT", raising=False)++ assert creds.cached_product_endpoint() == creds.INTERNAL_ENDPOINTdiff --git a/web/components/settings/CodeBuddyAuthCard.tsx b/web/components/settings/CodeBuddyAuthCard.tsxnew file mode 100644index 000000000..254de8be9--- /dev/null+++ b/web/components/settings/CodeBuddyAuthCard.tsx@@ -0,0 +1,208 @@+"use client";++import {+ CheckCircle2,+ ExternalLink,+ Loader2,+ LogIn,+ LogOut,+ RefreshCw,+ X,+} from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";++import {+ cancelCodeBuddyLogin,+ getCodeBuddyAuthStatus,+ logoutCodeBuddy,+ shouldPollCodeBuddyAuth,+ startCodeBuddyLogin,+ type CodeBuddyAuthStatus,+} from "@/lib/codebuddy-auth";++export function CodeBuddyAuthCard() {+ const { t } = useTranslation();+ const [status, setStatus] = useState<CodeBuddyAuthStatus | null>(null);+ const [loading, setLoading] = useState(true);+ const [working, setWorking] = useState(false);+ const [requestError, setRequestError] = useState("");++ const refresh = useCallback(async () => {+ try {+ setRequestError("");+ setStatus(await getCodeBuddyAuthStatus());+ } catch (error) {+ setRequestError(error instanceof Error ? error.message : String(error));+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ useEffect(() => {+ if (!status || !shouldPollCodeBuddyAuth(status)) return;+ const timer = window.setInterval(() => void refresh(), 1000);+ return () => window.clearInterval(timer);+ }, [refresh, status]);++ const startLogin = async () => {+ setWorking(true);+ setRequestError("");+ const popup = window.open("about:blank", "_blank");+ try {+ const next = await startCodeBuddyLogin();+ setStatus(next);+ if (next.authorize_url) {+ if (popup) popup.location.href = next.authorize_url;+ } else {+ popup?.close();+ }+ } catch (error) {+ popup?.close();+ setRequestError(error instanceof Error ? error.message : String(error));+ } finally {+ setWorking(false);+ }+ };++ const cancelLogin = async () => {+ setWorking(true);+ try {+ setStatus(await cancelCodeBuddyLogin());+ } catch (error) {+ setRequestError(error instanceof Error ? error.message : String(error));+ } finally {+ setWorking(false);+ }+ };++ const logout = async () => {+ setWorking(true);+ setRequestError("");+ try {+ setStatus(await logoutCodeBuddy());+ } catch (error) {+ setRequestError(error instanceof Error ? error.message : String(error));+ } finally {+ setWorking(false);+ }+ };++ const errorKey =+ status?.error_code === "sdk_missing"+ ? "codebuddy.auth.sdkMissing"+ : status?.error_code === "cli_missing"+ ? "codebuddy.auth.cliMissing"+ : status?.error_code === "login_timeout"+ ? "codebuddy.auth.timeout"+ : status?.error_code === "logout_external"+ ? "codebuddy.auth.logoutExternal"+ : "codebuddy.auth.failed";++ return (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/20 p-4">+ <div className="flex items-start justify-between gap-3">+ <div>+ <p className="text-[13px] font-medium text-[var(--foreground)]">+ {t("codebuddy.auth.title")}+ </p>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t("codebuddy.auth.description")}+ </p>+ </div>+ <button+ type="button"+ onClick={() => void refresh()}+ disabled={loading || working}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"+ title={t("codebuddy.auth.checkAgain")}+ aria-label={t("codebuddy.auth.checkAgain")}+ >+ <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />+ </button>+ </div>++ <div className="mt-3 flex flex-wrap items-center gap-2">+ {loading ? (+ <span className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("codebuddy.auth.checking")}+ </span>+ ) : status?.connection === "connected" ? (+ <>+ <span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-600 dark:text-emerald-400">+ <CheckCircle2 className="h-3.5 w-3.5" />+ {status.user_label+ ? t("codebuddy.auth.loggedInAs", { user: status.user_label })+ : t("codebuddy.auth.loggedIn")}+ </span>+ <button+ type="button"+ onClick={() => void logout()}+ disabled={working}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2.5 py-1.5 text-[12px] hover:bg-[var(--muted)] disabled:opacity-50"+ >+ {working ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <LogOut className="h-3.5 w-3.5" />+ )}+ {t("codebuddy.auth.logout")}+ </button>+ </>+ ) : status && shouldPollCodeBuddyAuth(status) ? (+ <>+ <span className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("codebuddy.auth.waiting")}+ </span>+ {status.authorize_url && (+ <a+ href={status.authorize_url}+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2.5 py-1.5 text-[12px] hover:bg-[var(--muted)]"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ {t("codebuddy.auth.openAuthorization")}+ </a>+ )}+ <button+ type="button"+ onClick={() => void cancelLogin()}+ disabled={working}+ className="inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:bg-[var(--muted)]"+ >+ <X className="h-3.5 w-3.5" />+ {t("codebuddy.auth.cancel")}+ </button>+ </>+ ) : (+ <button+ type="button"+ onClick={() => void startLogin()}+ disabled={working}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--foreground)] px-3 py-1.5 text-[12px] text-[var(--background)] disabled:opacity-50"+ >+ {working ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <LogIn className="h-3.5 w-3.5" />+ )}+ {t("codebuddy.auth.signIn")}+ </button>+ )}+ </div>++ {(requestError || status?.connection === "error") && (+ <p className="mt-2 text-[11px] text-red-500">+ {requestError || t(errorKey)}+ </p>+ )}+ </div>+ );+}diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex 2e0f9840b..45d9f6c57 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -10,17 +10,20 @@ import {Loader2,Pencil,Plus,+ RefreshCw,Terminal,Trash2,} from "lucide-react";import { useTranslation } from "react-i18next";import ProviderIcon from "@/components/common/ProviderIcon";+import { apiFetch, apiUrl } from "@/lib/api";import {reasoningEffortOptions,reasoningEffortOptionsFromSupportedLevels,} from "@/lib/reasoning-effort";import { CodexOAuthCard } from "./CodexOAuthCard";+import { CodeBuddyAuthCard } from "./CodeBuddyAuthCard";import {isBoundManagedCodexProfile,isCodexOAuthProfile,@@ -30,6 +33,7 @@ import {type CatalogModel,type CatalogProfile,type LlmContextWindowDetection,+ type ProviderOption,type ServiceName,getActiveModel,getActiveProfile,@@ -84,6 +88,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {llmContextDetection,applyDetectedContextWindow,runDetailedTest,+ setToast,} = useSettings();const activeProfile = getActiveProfile(draft, service);@@ -110,6 +115,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {const [editingModelName, setEditingModelName] = useState("");const [editingProfileId, setEditingProfileId] = useState<string | null>(null);const [editingProfileName, setEditingProfileName] = useState("");+ const [modelsSyncing, setModelsSyncing] = useState(false);// Reset API-key visibility whenever we land on a different profile or// switch services — same effect the old code had, but using React's@@ -158,6 +164,70 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {): [];+ const syncProviderModels = async (+ connection?: Pick<CatalogProfile, "binding" | "base_url" | "api_key">,+ ) => {+ if (service !== "llm" || !activeProfile || modelsSyncing) return;+ const binding = connection?.binding ?? activeProfile.binding ?? "";+ const baseUrl = connection?.base_url ?? activeProfile.base_url ?? "";+ const apiKey = connection?.api_key ?? activeProfile.api_key ?? "";+ if (!binding || (binding !== "codebuddy" && !baseUrl.trim())) return;++ const profileId = activeProfile.id;+ setModelsSyncing(true);+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings/fetch-models"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ binding,+ base_url: baseUrl,+ api_key: apiKey || null,+ }),+ });+ if (!response.ok) {+ const payload = (await response.json().catch(() => ({}))) as {+ detail?: string;+ };+ throw new Error(payload.detail || `HTTP ${response.status}`);+ }+ const payload = (await response.json()) as {+ models?: Array<{ id: string; name?: string }>;+ };+ const fetched = payload.models || [];+ if (fetched.length === 0) throw new Error(t("No models returned"));++ mutateCatalog((next) => {+ const target = next.services.llm;+ const profile = target.profiles.find((item) => item.id === profileId);+ if (!profile || profile.binding !== binding) return;+ const existing = new Map(+ profile.models.map((model) => [model.model, model]),+ );+ profile.models = fetched.map((item, index) => {+ const previous = existing.get(item.id);+ return previous+ ? { ...previous, name: item.name || previous.name, model: item.id }+ : {+ id: `llm-model-${Date.now()}-${index}`,+ name: item.name || item.id,+ model: item.id,+ };+ });+ if (+ !profile.models.some((model) => model.id === target.active_model_id)+ ) {+ target.active_model_id = profile.models[0]?.id ?? null;+ }+ });+ setToast(t("Synced {{count}} models", { count: fetched.length }));+ } catch (error) {+ setToast(error instanceof Error ? error.message : String(error));+ } finally {+ setModelsSyncing(false);+ }+ };+const startModelRename = (model: CatalogModel) => {setEditingModelId(model.id);setEditingModelName(model.name || model.model || "");@@ -403,6 +473,44 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {isSupportedSearchProvider={isSupportedSearchProvider}isDeprecatedSearchProvider={isDeprecatedSearchProvider}isPerplexityMissingKey={isPerplexityMissingKey}+ onProviderChanged={(provider, previousProvider) => {+ if (service !== "llm" || !activeProfile) return;+ const crossesCodeBuddyBoundary =+ provider.value === "codebuddy" ||+ previousProvider === "codebuddy";+ if (crossesCodeBuddyBoundary) {+ const profileId = activeProfile.id;+ mutateCatalog((next) => {+ const target = next.services.llm;+ const profile = target.profiles.find(+ (item) => item.id === profileId,+ );+ if (!profile || profile.binding !== provider.value)+ return;+ if (provider.value === "codebuddy") {+ profile.models = [];+ target.active_model_id = null;+ return;+ }+ const modelId = `llm-model-${Date.now()}`;+ profile.models = [+ {+ id: modelId,+ name: defaultModelLabel(language, 1),+ model: "",+ },+ ];+ target.active_model_id = modelId;+ });+ }+ if (provider.value === "codebuddy") {+ void syncProviderModels({+ binding: provider.value,+ base_url: provider.base_url || "",+ api_key: "",+ });+ }+ }}/></div>@@ -414,6 +522,20 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {</div>{!isCodexOAuth && (<div className="flex items-center gap-2">+ {service === "llm" &&+ activeProfile.binding === "codebuddy" && (+ <button+ type="button"+ onClick={() => void syncProviderModels()}+ disabled={modelsSyncing}+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ <RefreshCw+ className={`h-3 w-3 ${modelsSyncing ? "animate-spin" : ""}`}+ />+ {t("Sync models")}+ </button>+ )}<buttontype="button"onClick={() => addModel(service)}@@ -1033,6 +1155,7 @@ function ProfileFields({isSupportedSearchProvider,isDeprecatedSearchProvider,isPerplexityMissingKey,+ onProviderChanged,}: {service: ServiceName;profile: CatalogProfile;@@ -1042,6 +1165,10 @@ function ProfileFields({isSupportedSearchProvider: boolean;isDeprecatedSearchProvider: boolean;isPerplexityMissingKey: boolean;+ onProviderChanged: (+ provider: ProviderOption,+ previousProvider: string,+ ) => void;}) {const { t } = useTranslation();const { providers, updateProfileField, updateModelField } = useSettings();@@ -1059,12 +1186,14 @@ function ProfileFields({providerOption,profile,);+ const isCodeBuddyAuth = service === "llm" && providerValue === "codebuddy";- const fields = isCodexOAuth- ? { apiKey: false, baseUrl: false, baseUrlRequired: false }- : service === "search"- ? searchProviderFields(profile.provider)- : { apiKey: true, baseUrl: true, baseUrlRequired: false };+ const fields =+ isCodexOAuth || isCodeBuddyAuth+ ? { apiKey: false, baseUrl: false, baseUrlRequired: false }+ : service === "search"+ ? searchProviderFields(profile.provider)+ : { apiKey: true, baseUrl: true, baseUrlRequired: false };const searxngMissingBaseUrl =fields.baseUrlRequired && !String(profile.base_url || "").trim();@@ -1103,9 +1232,15 @@ function ProfileFields({if (renamed !== profile.name) {updateProfileField(service, "name", renamed);}- if (match?.base_url) {+ if (val === "codebuddy") {+ updateProfileField(service, "base_url", "");+ updateProfileField(service, "api_key", "");+ } else if (match?.base_url) {updateProfileField(service, "base_url", match.base_url);}+ if (match) {+ onProviderChanged(match, providerValue);+ }if (service === "embedding" && match?.default_dim) {updateModelField(service, "dimension", match.default_dim);}@@ -1169,6 +1304,11 @@ function ProfileFields({<CodexOAuthCard /></div>)}+ {isCodeBuddyAuth && (+ <div className="sm:col-span-2">+ <CodeBuddyAuthCard />+ </div>+ )}{fields.baseUrl && (<div className="sm:col-span-2"><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">@@ -1235,7 +1375,7 @@ function ProfileFields({</div></div>)}- {!isCodexOAuth && (+ {!isCodexOAuth && !isCodeBuddyAuth && (<div className="sm:col-span-2 rounded-xl border border-[var(--border)]/60 bg-[var(--muted)]/20"><buttontype="button"diff --git a/web/lib/codebuddy-auth.ts b/web/lib/codebuddy-auth.tsnew file mode 100644index 000000000..f418efd8a--- /dev/null+++ b/web/lib/codebuddy-auth.ts@@ -0,0 +1,45 @@+import { apiFetch, apiUrl } from "@/lib/api";++export type CodeBuddyAuthStatus = {+ connection: "disconnected" | "authorizing" | "connected" | "error";+ operation_state: "waiting" | "completed" | "cancelled" | "failed" | null;+ authorize_url: string | null;+ user_label: string | null;+ error_code: string | null;+};++const BASE = "/api/v1/settings/providers/codebuddy/auth";++async function request(+ path: string,+ method: "GET" | "POST",+): Promise<CodeBuddyAuthStatus> {+ const response = await apiFetch(apiUrl(`${BASE}${path}`), {+ method,+ skipAuthRedirect: true,+ });+ if (!response.ok) {+ throw new Error(`CodeBuddy auth request failed: HTTP ${response.status}`);+ }+ return (await response.json()) as CodeBuddyAuthStatus;+}++export function getCodeBuddyAuthStatus(): Promise<CodeBuddyAuthStatus> {+ return request("/status", "GET");+}++export function startCodeBuddyLogin(): Promise<CodeBuddyAuthStatus> {+ return request("/start", "POST");+}++export function cancelCodeBuddyLogin(): Promise<CodeBuddyAuthStatus> {+ return request("/cancel", "POST");+}++export function logoutCodeBuddy(): Promise<CodeBuddyAuthStatus> {+ return request("/logout", "POST");+}++export function shouldPollCodeBuddyAuth(status: CodeBuddyAuthStatus): boolean {+ return status.operation_state === "waiting";+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 087c16b2b..d2a115ae2 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -750,6 +750,9 @@"Proxy": "Proxy","Extra Headers (JSON)": "Extra Headers (JSON)","Models": "Models",+ "Sync models": "Sync models",+ "No models returned": "No models returned",+ "Synced {{count}} models": "Synced {{count}} models","Label": "Label","Model ID": "Model ID","Context Window": "Context Window",@@ -2744,6 +2747,22 @@"Core {{version}}": "Core {{version}}","API key accepted": "API key accepted","Open access": "Open access",+ "codebuddy.auth.title": "CodeBuddy account",+ "codebuddy.auth.description": "Uses the CodeBuddy login stored on this machine. No API key is sent to DeepTutor.",+ "codebuddy.auth.checkAgain": "Check login status",+ "codebuddy.auth.checking": "Checking local CodeBuddy login…",+ "codebuddy.auth.loggedIn": "Logged in",+ "codebuddy.auth.loggedInAs": "Logged in as {{user}}",+ "codebuddy.auth.waiting": "Waiting for browser authorization…",+ "codebuddy.auth.openAuthorization": "Open authorization",+ "codebuddy.auth.cancel": "Cancel",+ "codebuddy.auth.signIn": "Sign in with CodeBuddy",+ "codebuddy.auth.logout": "Sign out",+ "codebuddy.auth.logoutExternal": "This session belongs to the CodeBuddy IDE plugin or CLI. Sign out there to disconnect it.",+ "codebuddy.auth.sdkMissing": "Sign in with the CodeBuddy IDE plugin or run `codebuddy` and enter /login — DeepTutor reuses that session. For in-app login instead: python -m pip install codebuddy-agent-sdk",+ "codebuddy.auth.cliMissing": "Install the CodeBuddy CLI before signing in.",+ "codebuddy.auth.timeout": "CodeBuddy login timed out. Try again.",+ "codebuddy.auth.failed": "Could not check or start CodeBuddy login.","codex.oauth.title": "OpenAI Codex OAuth","codex.oauth.signIn": "Sign in with Codex","codex.oauth.waiting": "Waiting for browser authorization…",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 7694f739a..596d1b06c 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -757,6 +757,9 @@"API version and proxy": "API 版本和代理","Extra Headers (JSON)": "额外请求头 (JSON)","Models": "模型列表",+ "Sync models": "同步模型",+ "No models returned": "未返回任何模型",+ "Synced {{count}} models": "已同步 {{count}} 个模型","Label": "标签","Model ID": "模型 ID","Rename model": "重命名模型",@@ -2744,6 +2747,22 @@"Core {{version}}": "内核 {{version}}","API key accepted": "API 密钥已通过","Open access": "开放访问",+ "codebuddy.auth.title": "CodeBuddy 账号",+ "codebuddy.auth.description": "使用本机保存的 CodeBuddy 登录状态,不会向 DeepTutor 提交 API Key。",+ "codebuddy.auth.checkAgain": "重新检查登录状态",+ "codebuddy.auth.checking": "正在检查本地 CodeBuddy 登录…",+ "codebuddy.auth.loggedIn": "已登录",+ "codebuddy.auth.loggedInAs": "已登录:{{user}}",+ "codebuddy.auth.waiting": "正在等待浏览器授权…",+ "codebuddy.auth.openAuthorization": "打开授权页面",+ "codebuddy.auth.cancel": "取消",+ "codebuddy.auth.signIn": "登录 CodeBuddy",+ "codebuddy.auth.logout": "退出登录",+ "codebuddy.auth.logoutExternal": "当前登录态来自 CodeBuddy IDE 插件或 CLI,请在那里退出登录。",+ "codebuddy.auth.sdkMissing": "请在 CodeBuddy IDE 插件中登录,或运行 `codebuddy` 后输入 /login,DeepTutor 会直接复用该登录态。若想在应用内登录:python -m pip install codebuddy-agent-sdk",+ "codebuddy.auth.cliMissing": "请先安装 CodeBuddy CLI。",+ "codebuddy.auth.timeout": "CodeBuddy 登录已超时,请重试。",+ "codebuddy.auth.failed": "无法检查或启动 CodeBuddy 登录。","codex.oauth.title": "OpenAI Codex OAuth","codex.oauth.signIn": "使用 Codex 登录","codex.oauth.waiting": "等待浏览器授权…",diff --git a/web/tests/codebuddy-auth-settings-contract.test.ts b/web/tests/codebuddy-auth-settings-contract.test.tsnew file mode 100644index 000000000..f47f02f65--- /dev/null+++ b/web/tests/codebuddy-auth-settings-contract.test.ts@@ -0,0 +1,72 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import test from "node:test";++import { shouldPollCodeBuddyAuth } from "../lib/codebuddy-auth";++const EDITOR = path.resolve(+ process.cwd(),+ "components/settings/ServiceConfigEditor.tsx",+);+const CARD = path.resolve(+ process.cwd(),+ "components/settings/CodeBuddyAuthCard.tsx",+);+const EN = path.resolve(process.cwd(), "locales/en/app.json");+const ZH = path.resolve(process.cwd(), "locales/zh/app.json");++test("CodeBuddy renders a login card without changing other OAuth cards", () => {+ const editor = readFileSync(EDITOR, "utf8");++ assert.match(editor, /providerValue === "codebuddy"/);+ assert.match(editor, /<CodeBuddyAuthCard/);+ assert.match(editor, /<CodexOAuthCard/);+ assert.match(editor, /isCodexOAuth \|\| isCodeBuddyAuth/);+ assert.match(editor, /!isCodexOAuth && !isCodeBuddyAuth/);+ assert.match(readFileSync(CARD, "utf8"), /startCodeBuddyLogin/);+ assert.match(readFileSync(CARD, "utf8"), /logoutCodeBuddy/);+});++test("CodeBuddy model sync cannot write into a profile after provider switch", () => {+ const editor = readFileSync(EDITOR, "utf8");++ assert.match(editor, /!profile \|\| profile\.binding !== binding/);+ assert.match(editor, /previousProvider === "codebuddy"/);+ assert.match(editor, /profile\.models = \[\]/);+});++test("CodeBuddy auth polling only runs while browser authorization is waiting", () => {+ const base = {+ connection: "authorizing" as const,+ operation_state: "waiting" as const,+ authorize_url: "https://codebuddy.example/login",+ user_label: null,+ error_code: null,+ };++ assert.equal(shouldPollCodeBuddyAuth(base), true);+ assert.equal(+ shouldPollCodeBuddyAuth({+ ...base,+ connection: "connected",+ operation_state: "completed",+ }),+ false,+ );+});++test("CodeBuddy auth copy stays in sync across locales", () => {+ const en = JSON.parse(readFileSync(EN, "utf8")) as Record<string, unknown>;+ const zh = JSON.parse(readFileSync(ZH, "utf8")) as Record<string, unknown>;+ const keys = (locale: Record<string, unknown>) =>+ Object.keys(locale)+ .filter((key) => key.startsWith("codebuddy.auth."))+ .sort();++ assert.deepEqual(keys(en), keys(zh));+ for (const key of keys(en)) {+ assert.equal(typeof en[key], "string");+ assert.equal(typeof zh[key], "string");+ }+});