DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(cli): add GitHub Copilot device login to init (#1277)
Yongliangb19a83745764
diff --git a/README.md b/README.mdindex aebc69fbc..74a34485b 100644--- a/README.md+++ b/README.md@@ -998,7 +998,22 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a ~200-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; `codebuddy` validates CodeBuddy SDK auth and starts login when needed) |+| `deeptutor provider login <provider>` | Provider auth (`openai-codex` OAuth login; `github-copilot` GitHub device login; `codebuddy` validates CodeBuddy SDK auth and starts login when needed) |++GitHub Copilot credentials belong to the signed-in DeepTutor owner and live only at+`<runtime-home>/data/system/user-secrets/<owner-id>/private/github-copilot/credentials.v1.json`,+outside sandbox workspaces. CLI/admin partners use the administrator's credentials;+other users sign in separately, and Copilot profiles cannot be shared through model grants.+External nanobot/Copilot token files are never imported: after upgrading, run+`deeptutor provider login github-copilot` again.++Login validates inference with a currently discovered model; `init` validates the selected+model and aborts on failure without saving the draft configuration. Successful GitHub+authentication alone does not establish Copilot model access (the saved login is retained+if validation fails). Runtime requests follow the API endpoint returned by token exchange,+including refreshes, and respect each model's Responses/Chat Completions endpoint metadata.++Copilot-specific Responses compatibility is applied at dispatch without rewriting stored history.</details>diff --git a/SKILL.md b/SKILL.mdindex 8ef9e846a..b41115017 100644--- a/SKILL.md+++ b/SKILL.md@@ -146,7 +146,7 @@ deeptutor notebook remove-record <notebook_id> <record_id>```bashdeeptutor provider login openai-codex # OAuth login for OpenAI Codex-deeptutor provider login github-copilot # Validate an existing Copilot auth session+deeptutor provider login github-copilot # Sign in through GitHub device flow```### Systemdiff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 13e8f4edf..827c4d4fd 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -1972,18 +1972,20 @@ async def test_provider_connection(payload: ProviderProbePayload):@router.post("/fetch-models")async def fetch_models_from_provider(payload: FetchModelsPayload):- """List the model IDs an OpenAI-compatible provider exposes.+ """List selectable model IDs using the provider's own authentication.Thin HTTP surface over ``factory.fetch_models`` so the settings UI can- populate a model picker from ``base_url`` + ``api_key`` instead of making- the user type model IDs by hand.+ populate a model picker. Copilot uses the caller's owner-private CLI login,+ not the profile's API key or base URL."""_require_settings_admin()from deeptutor.services.llm.factory import fetch_models as fetch_llm_models+ from deeptutor.services.provider_registry import canonical_provider_namebase_url = (payload.base_url or "").strip()binding = (payload.binding or "").strip().lower() or "openai"- if not base_url and binding != "codebuddy":+ is_copilot = canonical_provider_name(binding) == "github_copilot"+ if not base_url and binding != "codebuddy" and not is_copilot:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail="base_url is required for this provider.",@@ -1991,7 +1993,9 @@ async def fetch_models_from_provider(payload: FetchModelsPayload):api_key = payload.api_keyapi_format = (payload.api_format or "").strip().lower()- if payload.profile_id and (api_key == CATALOG_SECRET_MASK or not api_format):+ if is_copilot:+ base_url, api_key, api_format = "", None, "auto"+ elif payload.profile_id and (api_key == CATALOG_SECRET_MASK or not api_format):service = get_model_catalog_service().load().get("services", {}).get(payload.service, {})profile = next((item for item in service.get("profiles", []) if item.get("id") == payload.profile_id),@@ -2005,6 +2009,18 @@ async def fetch_models_from_provider(payload: FetchModelsPayload):try:model_ids = await fetch_llm_models(binding, base_url, api_key, api_format or "auto")except Exception as exc: # noqa: BLE001 — surface any provider error as 502+ if is_copilot:+ # OAuth exceptions can contain credential-bearing URLs or responses.+ # Never echo or log their raw text at this public HTTP boundary.+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=(+ "Could not list GitHub Copilot models. "+ "Run: deeptutor provider login github-copilot "+ "for this account in the server's DeepTutor home, "+ "then retry. If already logged in, check Copilot access and connectivity."+ ),+ ) from Nonelogger.exception("Failed to fetch models from %s", base_url)raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY,diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.pyindex bbdc58eb4..76ae465fb 100644--- a/deeptutor/multi_user/model_access.py+++ b/deeptutor/multi_user/model_access.py@@ -53,7 +53,7 @@ def _model_by_id(profile: dict[str, Any], model_id: str) -> dict[str, Any] | Non#: 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"})+OWNER_BOUND_BINDINGS = frozenset({"openai_codex", "codebuddy", "github_copilot"})def is_owner_bound(profile: dict[str, Any]) -> bool:@@ -63,7 +63,7 @@ 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()+ binding = str(profile.get("binding") or "").strip().lower().replace("-", "_")if binding in OWNER_BOUND_BINDINGS:return Truereturn bool(profile.get("owner_bound"))diff --git a/deeptutor/multi_user/paths.py b/deeptutor/multi_user/paths.pyindex 816dc2a60..036d56616 100644--- a/deeptutor/multi_user/paths.py+++ b/deeptutor/multi_user/paths.py@@ -214,7 +214,7 @@ def get_owner_path_service() -> PathService:return _resolve_owner()[1]-def owner_secrets_dir(owner_id: str) -> Path:+def owner_secrets_dir(owner_id: str, *, system_root: Path | None = None) -> Path:"""Secrets directory of a *named* owner, independent of the request scope.Needed because not every reader runs inside a request: an MCP connection@@ -223,7 +223,7 @@ def owner_secrets_dir(owner_id: str) -> Path:whoever happens to be current."""# SYSTEM_ROOT is read per call so a monkey-patched root (tests) is honored.- secrets_root = SYSTEM_ROOT / USER_SECRETS_DIRNAME+ secrets_root = (system_root if system_root is not None else SYSTEM_ROOT) / USER_SECRETS_DIRNAMEowner_dir = secrets_root / (owner_id or LOCAL_ADMIN_ID)owner_dir.mkdir(parents=True, exist_ok=True)# Re-asserted rather than assumed from ``ensure_system_dirs``: this is the@@ -235,7 +235,7 @@ def owner_secrets_dir(owner_id: str) -> Path:return owner_dir.resolve()-def get_owner_secrets_dir() -> Path:+def get_owner_secrets_dir(*, runtime_home: Path | None = None) -> Path:"""Owner-private directory for secrets the sandbox must never see.``data/system`` is the one branch of the tree the sandbox runner does not@@ -247,8 +247,13 @@ def get_owner_secrets_dir() -> Path:Laid out like a user root (``private/<asset>/``) so a store written againstone can be pointed here without changing what it knows about its own files.+ An explicit ``runtime_home`` supports callers such as ``init --home`` that+ switch homes after this module's deployment paths have been initialized."""- return owner_secrets_dir(current_owner_id())+ return owner_secrets_dir(+ current_owner_id(),+ system_root=runtime_home / "data" / "system" if runtime_home is not None else None,+ )def current_owner_id() -> str:diff --git a/deeptutor/runtime/banner.py b/deeptutor/runtime/banner.pyindex d392e4f97..97a095be6 100644--- a/deeptutor/runtime/banner.py+++ b/deeptutor/runtime/banner.py@@ -78,6 +78,10 @@ LABELS: dict[str, dict[str, str]] = {"init.probe_ok": "{what} OK · {ms}ms","init.probe_fail": "{what} failed: {error}","init.probe_retry": "Re-enter API key and retry?",+ "init.copilot_reuse_login": "Reuse the GitHub Copilot login for {account}?",+ "init.copilot_login_start": "Starting GitHub device login ...",+ "init.copilot_login_ok": "GitHub Copilot login succeeded for {account}.",+ "init.copilot_login_fail": "GitHub Copilot login failed: {error}","init.review_title": "Review","init.review_llm": "LLM","init.review_embedding": "Embedding",@@ -198,6 +202,10 @@ LABELS: dict[str, dict[str, str]] = {"init.probe_ok": "{what} 连接成功 · {ms}ms","init.probe_fail": "{what} 连接失败: {error}","init.probe_retry": "重新输入 API Key 并重试?",+ "init.copilot_reuse_login": "复用 {account} 的 GitHub Copilot 登录?",+ "init.copilot_login_start": "正在启动 GitHub 设备登录 ...",+ "init.copilot_login_ok": "GitHub Copilot 登录成功: {account}。",+ "init.copilot_login_fail": "GitHub Copilot 登录失败: {error}","init.review_title": "配置确认","init.review_llm": "大模型","init.review_embedding": "向量",diff --git a/deeptutor/services/github_copilot_auth.py b/deeptutor/services/github_copilot_auth.pynew file mode 100644index 000000000..7106d53c2--- /dev/null+++ b/deeptutor/services/github_copilot_auth.py@@ -0,0 +1,268 @@+"""GitHub device login and Copilot token exchange."""++from __future__ import annotations++import asyncio+from collections.abc import Callable+from contextlib import suppress+from dataclasses import dataclass+import os+import time+import webbrowser++import httpx++from deeptutor.services.github_copilot_storage import GitHubToken, get_github_copilot_storage++DEFAULT_GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code"+DEFAULT_GITHUB_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"+DEFAULT_GITHUB_USER_URL = "https://api.github.com/user"+DEFAULT_COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token"+DEFAULT_COPILOT_BASE_URL = "https://api.githubcopilot.com"+GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98"+GITHUB_COPILOT_SCOPE = "read:user"+USER_AGENT = "DeepTutor/1"+EDITOR_VERSION = "vscode/1.99.0"+EDITOR_PLUGIN_VERSION = "copilot-chat/0.26.0"+_LONG_LIVED_TOKEN_SECONDS = 315_360_000+++@dataclass(frozen=True)+class CopilotAccess:+ token: str+ expires_at: float+ api_base: str+++def _resolve(env_var: str, default: str) -> str:+ value = os.environ.get(env_var)+ return value.strip() if value and value.strip() else default+++def load_github_token() -> GitHubToken | None:+ token = get_github_copilot_storage().load()+ if not token or not getattr(token, "access", None):+ return None+ return token+++def _github_headers(token: str) -> dict[str, str]:+ return {+ "Authorization": f"token {token}",+ "Accept": "application/json",+ "User-Agent": USER_AGENT,+ "Editor-Version": EDITOR_VERSION,+ "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,+ }+++async def login_github_copilot(+ print_fn: Callable[[str], None] | None = None,+) -> GitHubToken:+ """Run GitHub's device flow and persist the resulting OAuth token."""+ storage = get_github_copilot_storage()+ printer = print_fn or print+ timeout = httpx.Timeout(20.0, connect=20.0)+ client_id = _resolve("DEEPTUTOR_GITHUB_COPILOT_CLIENT_ID", GITHUB_COPILOT_CLIENT_ID)+ device_code_url = _resolve("DEEPTUTOR_GITHUB_DEVICE_CODE_URL", DEFAULT_GITHUB_DEVICE_CODE_URL)+ access_token_url = _resolve(+ "DEEPTUTOR_GITHUB_ACCESS_TOKEN_URL", DEFAULT_GITHUB_ACCESS_TOKEN_URL+ )+ user_url = _resolve("DEEPTUTOR_GITHUB_USER_URL", DEFAULT_GITHUB_USER_URL)++ async with httpx.AsyncClient(+ timeout=timeout,+ follow_redirects=True,+ trust_env=True,+ ) as client:+ response = await client.post(+ device_code_url,+ headers={"Accept": "application/json", "User-Agent": USER_AGENT},+ data={"client_id": client_id, "scope": GITHUB_COPILOT_SCOPE},+ )+ response.raise_for_status()+ payload = response.json()++ device_code = str(payload["device_code"])+ user_code = str(payload["user_code"])+ verification_url = str(+ payload.get("verification_uri") or payload.get("verification_uri_complete") or ""+ )+ verification_complete = str(payload.get("verification_uri_complete") or verification_url)+ interval = max(1, int(payload.get("interval") or 5))+ expires_in = int(payload.get("expires_in") or 900)++ printer(f"Open: {verification_url}")+ printer(f"Code: {user_code}")+ if verification_complete:+ with suppress(webbrowser.Error, OSError):+ webbrowser.open(verification_complete)++ deadline = time.monotonic() + expires_in+ current_interval = interval+ access_token = ""+ token_expires_in = _LONG_LIVED_TOKEN_SECONDS+ while time.monotonic() < deadline:+ await asyncio.sleep(current_interval)+ poll = await client.post(+ access_token_url,+ headers={"Accept": "application/json", "User-Agent": USER_AGENT},+ data={+ "client_id": client_id,+ "device_code": device_code,+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",+ },+ )+ poll.raise_for_status()+ poll_payload = poll.json()+ access_token = str(poll_payload.get("access_token") or "")+ if access_token:+ token_expires_in = int(poll_payload.get("expires_in") or _LONG_LIVED_TOKEN_SECONDS)+ break++ error = poll_payload.get("error")+ if error == "authorization_pending":+ continue+ if error == "slow_down":+ current_interval += 5+ continue+ if error == "expired_token":+ raise RuntimeError("GitHub device code expired. Please run login again.")+ if error == "access_denied":+ raise RuntimeError("GitHub device login was denied.")+ if error:+ raise RuntimeError(str(poll_payload.get("error_description") or error))+ else:+ raise RuntimeError("GitHub device login timed out.")++ user = await client.get(+ user_url,+ headers={+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/vnd.github+json",+ "User-Agent": USER_AGENT,+ },+ )+ user.raise_for_status()+ user_payload = user.json()+ account_id = user_payload.get("login") or user_payload.get("id")++ token = GitHubToken(+ access=access_token,+ expires=int((time.time() + token_expires_in) * 1000),+ account_id=str(account_id) if account_id else None,+ )+ storage.save(token)+ return token+++async def exchange_copilot_token(github_token: str | None = None) -> CopilotAccess:+ """Exchange a GitHub OAuth token for a short-lived Copilot API token."""+ if not github_token:+ stored = load_github_token()+ github_token = str(getattr(stored, "access", "") or "")+ if not github_token:+ raise RuntimeError(+ "GitHub Copilot is not logged in. Run: deeptutor provider login github-copilot"+ )++ async with httpx.AsyncClient(+ timeout=httpx.Timeout(20.0, connect=20.0),+ follow_redirects=True,+ trust_env=True,+ ) as client:+ response = await client.get(+ _resolve("DEEPTUTOR_COPILOT_TOKEN_URL", DEFAULT_COPILOT_TOKEN_URL),+ headers=_github_headers(github_token),+ )+ response.raise_for_status()+ payload = response.json()++ token = str(payload.get("token") or "")+ if not token:+ raise RuntimeError("GitHub Copilot token exchange returned no token.")+ expires_at = payload.get("expires_at")+ if not isinstance(expires_at, (int, float)):+ expires_at = time.time() + int(payload.get("refresh_in") or 1500)+ endpoints = payload.get("endpoints")+ api_base = (+ str(endpoints.get("api"))+ if isinstance(endpoints, dict) and endpoints.get("api")+ else _resolve("DEEPTUTOR_COPILOT_BASE_URL", DEFAULT_COPILOT_BASE_URL)+ )+ return CopilotAccess(token=token, expires_at=float(expires_at), api_base=api_base)+++@dataclass(frozen=True)+class CopilotModel:+ id: str+ supported_endpoints: tuple[str, ...] | None = None+++async def fetch_github_copilot_models(access: CopilotAccess) -> list[CopilotModel]:+ """Keep protocol metadata alongside IDs; omit explicitly unsupported models."""+ async with httpx.AsyncClient(+ timeout=httpx.Timeout(20.0, connect=20.0),+ follow_redirects=True,+ trust_env=True,+ ) as client:+ response = await client.get(+ f"{access.api_base.rstrip('/')}/models",+ headers={+ "Authorization": f"Bearer {access.token}",+ "Accept": "application/json",+ "User-Agent": USER_AGENT,+ "Editor-Version": EDITOR_VERSION,+ "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,+ },+ )+ response.raise_for_status()+ payload = response.json()++ rows = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(rows, list):+ return []+ models: dict[str, CopilotModel] = {}+ for row in rows:+ if not isinstance(row, dict):+ continue+ model_id = row.get("id")+ policy = row.get("policy")+ if (+ not isinstance(model_id, str)+ or not model_id+ or row.get("model_picker_enabled") is False+ or (isinstance(policy, dict) and policy.get("state") == "disabled")+ ):+ continue+ raw_endpoints = row.get("supported_endpoints")+ endpoints = None+ if raw_endpoints is not None:+ if not isinstance(raw_endpoints, list):+ continue+ endpoints = tuple(+ endpoint+ for endpoint in raw_endpoints+ if endpoint in ("/responses", "/chat/completions")+ )+ if not endpoints:+ continue+ models[model_id] = CopilotModel(model_id, endpoints)+ return list(models.values())+++async def list_github_copilot_models() -> list[str]:+ access = await exchange_copilot_token()+ return [f"github-copilot/{model.id}" for model in await fetch_github_copilot_models(access)]+++__all__ = [+ "CopilotAccess",+ "CopilotModel",+ "exchange_copilot_token",+ "fetch_github_copilot_models",+ "get_github_copilot_storage",+ "list_github_copilot_models",+ "load_github_token",+ "login_github_copilot",+]diff --git a/deeptutor/services/github_copilot_storage.py b/deeptutor/services/github_copilot_storage.pynew file mode 100644index 000000000..0ae5c9088--- /dev/null+++ b/deeptutor/services/github_copilot_storage.py@@ -0,0 +1,85 @@+"""Owner-private GitHub credentials; never import another application's login."""++from __future__ import annotations++from contextlib import contextmanager+from dataclasses import asdict, dataclass, field+import json+import os+from pathlib import Path+import stat+import threading+from typing import Iterator++from deeptutor.services.codex_auth.contracts import CodexAuthError+from deeptutor.services.codex_auth.storage import (+ _assert_safe_directory,+ _assert_safe_regular_path,+ _atomic_write_json,+ _locked_file,+)+++@dataclass(frozen=True)+class GitHubToken:+ access: str = field(repr=False)+ expires: int+ account_id: str | None = None+++class GitHubCopilotStorage:+ def __init__(self, owner_root: Path) -> None:+ self.root = owner_root / "private" / "github-copilot"+ self.credentials_path = self.root / "credentials.v1.json"+ self._thread_lock = threading.Lock()++ @contextmanager+ def _locked(self) -> Iterator[None]:+ try:+ with self._thread_lock:+ for directory in (self.root.parent, self.root):+ _assert_safe_directory(directory)+ directory.mkdir(parents=True, exist_ok=True)+ os.chmod(directory, stat.S_IRWXU)+ with _locked_file(self.root / "auth.lock"):+ _assert_safe_regular_path(self.credentials_path)+ yield+ except CodexAuthError as exc:+ raise RuntimeError("GitHub Copilot credential storage uses an unsafe path.") from exc++ def load(self) -> GitHubToken | None:+ with self._locked():+ if not self.credentials_path.exists():+ return None+ try:+ payload = json.loads(self.credentials_path.read_text(encoding="utf-8"))+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ raise ValueError("Invalid schema")+ access = payload.get("access")+ expires = payload.get("expires")+ account = payload.get("account_id")+ if (+ not isinstance(access, str)+ or not access+ or type(expires) is not int+ or (account is not None and not isinstance(account, str))+ ):+ raise ValueError("Invalid credential fields")+ return GitHubToken(access=access, expires=expires, account_id=account)+ except (OSError, ValueError) as exc:+ raise RuntimeError(+ "Stored GitHub Copilot credentials are invalid. "+ "Run: deeptutor provider login github-copilot"+ ) from exc++ def save(self, token: GitHubToken) -> None:+ with self._locked():+ _atomic_write_json(self.credentials_path, {"schema_version": 1, **asdict(token)})+++def get_github_copilot_storage() -> GitHubCopilotStorage:+ from deeptutor.multi_user.paths import get_owner_secrets_dir+ from deeptutor.runtime.home import get_runtime_home++ # Resolve the home per call: `init --home` can change it after paths was imported.+ return GitHubCopilotStorage(get_owner_secrets_dir(runtime_home=get_runtime_home()))diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 3a9947a74..0019bc4bb 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -729,6 +729,11 @@ async def fetch_models(api_key: str | None = None,api_format: str = "auto",) -> list[str]:+ if canonical_provider_name(binding) == "github_copilot":+ from deeptutor.services.github_copilot_auth import list_github_copilot_models++ return await list_github_copilot_models()+if canonical_provider_name(binding) == "codebuddy":from .provider_core.codebuddy_models import fetch_codebuddy_modelsdiff --git a/deeptutor/services/llm/provider_core/github_copilot_provider.py b/deeptutor/services/llm/provider_core/github_copilot_provider.pyindex 38b1583c5..66f619638 100644--- a/deeptutor/services/llm/provider_core/github_copilot_provider.py+++ b/deeptutor/services/llm/provider_core/github_copilot_provider.py@@ -1,20 +1,23 @@-"""GitHub Copilot provider with graceful fallback to existing local auth."""+"""GitHub Copilot provider backed by a persisted GitHub device login."""from __future__ import annotations+import asynciofrom collections.abc import Awaitable, Callableimport timefrom typing import Any-import httpx-from openai import AuthenticationError-+from deeptutor.services.github_copilot_auth import (+ CopilotModel,+ exchange_copilot_token,+ fetch_github_copilot_models,+ get_github_copilot_storage,+)from deeptutor.services.llm.provider_core.base import LLMResponsefrom deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProviderfrom deeptutor.services.provider_registry import find_by_nameDEFAULT_COPILOT_BASE_URL = "https://api.githubcopilot.com"-DEFAULT_COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token"USER_AGENT = "DeepTutor/1"EDITOR_VERSION = "vscode/1.99.0"EDITOR_PLUGIN_VERSION = "copilot-chat/0.26.0"@@ -22,7 +25,7 @@ _EXPIRY_SKEW_SECONDS = 60class GitHubCopilotProvider(OpenAICompatProvider):- """Provider that first tries existing Copilot auth, then oauth-cli-kit tokens."""+ """Provider that exchanges a stored GitHub token for Copilot access."""def __init__(self,@@ -32,8 +35,14 @@ class GitHubCopilotProvider(OpenAICompatProvider):):self._copilot_access_token: str | None = Noneself._copilot_expires_at: float = 0.0+ self._storage = get_github_copilot_storage()+ self._models: dict[str, CopilotModel] = {}+ self._refresh_lock = asyncio.Lock()super().__init__(- api_key="copilot",+ # The real short-lived token is installed by _ensure_api_key().+ # Passing a placeholder here would create a KeyPool that later+ # overwrites the client's Authorization header with that placeholder.+ api_key=None,api_base=DEFAULT_COPILOT_BASE_URL,default_model=default_model,extra_headers={@@ -46,69 +55,97 @@ class GitHubCopilotProvider(OpenAICompatProvider):configure_env=configure_env,)- async def _try_existing_local_auth(self) -> None:- self.api_key = "copilot"- self._client.api_key = "copilot"-- async def _load_stored_github_token(self) -> str | None:- try:- from oauth_cli_kit.storage import FileTokenStorage- except ImportError:- return None- storage = FileTokenStorage( # nosec B106 - token_filename is a file name, not a password.- token_filename="github-copilot.json",- app_name="nanobot",- import_codex_cli=False,- )- token = storage.load()- if not token or not getattr(token, "access", None):- return None- return str(token.access)-async def _exchange_token(self) -> str:- github_token = await self._load_stored_github_token()- if not github_token:+ stored = self._storage.load()+ if stored is None:raise RuntimeError(- "GitHub Copilot auth is unavailable. Validate local Copilot auth or log in first."- )-- timeout = httpx.Timeout(20.0, connect=20.0)- async with httpx.AsyncClient(- timeout=timeout, follow_redirects=True, trust_env=True- ) as client:- response = await client.get(- DEFAULT_COPILOT_TOKEN_URL,- headers={- "Authorization": f"token {github_token}",- "Accept": "application/json",- "User-Agent": USER_AGENT,- "Editor-Version": EDITOR_VERSION,- "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,- },+ "GitHub Copilot is not logged in for this owner. "+ "Run: deeptutor provider login github-copilot")- response.raise_for_status()- payload = response.json()-- token = payload.get("token")- if not token:- raise RuntimeError("GitHub Copilot token exchange returned no token.")- expires_at = payload.get("expires_at")- if isinstance(expires_at, (int, float)):- self._copilot_expires_at = float(expires_at)- else:- refresh_in = payload.get("refresh_in") or 1500- self._copilot_expires_at = time.time() + int(refresh_in)- self._copilot_access_token = str(token)+ access = await exchange_copilot_token(stored.access)+ models = await fetch_github_copilot_models(access)+ self.api_base = access.api_base.rstrip("/")+ self._effective_base = self.api_base+ self._client.base_url = self.api_base + "/"+ self._models = {model.id: model for model in models}+ self._copilot_expires_at = access.expires_at+ self._copilot_access_token = access.tokenreturn self._copilot_access_tokenasync def _ensure_api_key(self) -> None:+ async with self._refresh_lock:+ await self._refresh_api_key()++ async def _refresh_api_key(self) -> None:now = time.time()if self._copilot_access_token and now < self._copilot_expires_at - _EXPIRY_SKEW_SECONDS:self.api_key = self._copilot_access_tokenself._client.api_key = self._copilot_access_tokenreturn- await self._try_existing_local_auth()+ token = await self._exchange_token()+ self.api_key = token+ self._client.api_key = token++ @staticmethod+ def _supports_temperature(+ model_name: str,+ reasoning_effort: str | None = None,+ ) -> bool:+ if model_name.lower().split("/")[-1] == "gpt-6-astra":+ return False+ return OpenAICompatProvider._supports_temperature(model_name, reasoning_effort)++ def _should_use_responses_api(+ self,+ model: str | None,+ reasoning_effort: str | None,+ tools: list[dict[str, Any]] | None = None,+ ) -> bool:+ model_id = (model or self.default_model).split("/")[-1]+ discovered = self._models.get(model_id)+ if discovered is None:+ raise ValueError(f"GitHub Copilot model is not currently available: {model_id}")+ endpoints = discovered.supported_endpoints+ if endpoints is not None:+ if "/chat/completions" not in endpoints:+ return True+ if "/responses" not in endpoints:+ return False+ return super()._should_use_responses_api(model, reasoning_effort, tools)++ @staticmethod+ def _normalize_responses_input(value: Any) -> Any:+ if not isinstance(value, list):+ return value+ normalized = []+ for item in value:+ if not isinstance(item, dict):+ normalized.append(item)+ continue+ # Copilot rejects message/reasoning status, including the null+ # added by SDK model_dump for reasoning. Function-call status is+ # accepted; keep tool lifecycle fields and reasoning IDs intact.+ excluded = set()+ if item.get("type") == "reasoning":+ excluded.add("status")+ elif item.get("type") == "message" or ("type" not in item and "role" in item):+ excluded.update(("status", "id"))+ normalized.append({key: val for key, val in item.items() if key not in excluded})+ return normalized++ async def _create_with_key_rotation(self, create, kwargs: dict[str, Any]) -> Any:+ if create == self._client.responses.create:+ # Run after extra kwargs are merged in both streaming and ordinary+ # requests. extra_body can override input again inside the SDK.+ kwargs = {**kwargs, "input": self._normalize_responses_input(kwargs.get("input"))}+ extra_body = kwargs.get("extra_body")+ if isinstance(extra_body, dict) and "input" in extra_body:+ kwargs["extra_body"] = {+ **extra_body,+ "input": self._normalize_responses_input(extra_body["input"]),+ }+ return await super()._create_with_key_rotation(create, kwargs)async def _chat_impl(self,@@ -125,48 +162,8 @@ class GitHubCopilotProvider(OpenAICompatProvider):**kwargs: Any,) -> LLMResponse:await self._ensure_api_key()- try:- if stream:- 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,- )- return await super().chat(- messages=messages,- tools=tools,- model=model,- max_tokens=max_tokens,- temperature=temperature,- reasoning_effort=reasoning_effort,- tool_choice=tool_choice,- **kwargs,- )- except AuthenticationError:- token = await self._exchange_token()- self.api_key = token- self._client.api_key = token- if stream:- 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,- )- return await super().chat(+ if stream:+ return await super().chat_stream(messages=messages,tools=tools,model=model,@@ -174,8 +171,20 @@ class GitHubCopilotProvider(OpenAICompatProvider):temperature=temperature,reasoning_effort=reasoning_effort,tool_choice=tool_choice,+ on_content_delta=on_content_delta,+ on_reasoning_delta=on_reasoning_delta,**kwargs,)+ return await super().chat(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ reasoning_effort=reasoning_effort,+ tool_choice=tool_choice,+ **kwargs,+ )async def chat(self,@@ -232,3 +241,20 @@ class GitHubCopilotProvider(OpenAICompatProvider):on_reasoning_delta,**kwargs,)+++async def validate_github_copilot_model(model: str) -> None:+ """Probe inference through the same authenticated, protocol-aware runtime."""+ provider = GitHubCopilotProvider(default_model=model)+ try:+ response = await provider.chat(+ messages=[{"role": "user", "content": "Reply with OK."}],+ max_tokens=16,+ )+ if response.finish_reason == "error":+ raise RuntimeError(+ f"Copilot model validation failed for {model}: "+ f"{response.content or 'provider returned an error'}"+ )+ finally:+ await provider.aclose()diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.pyindex b2be33e49..77d0fdf25 100644--- a/deeptutor/services/llm/provider_factory.py+++ b/deeptutor/services/llm/provider_factory.py@@ -28,6 +28,12 @@ def _secret_fingerprint(value: str | list[str] | None) -> str:def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> tuple[Any, ...]:headers = json.dumps(config.extra_headers or {}, sort_keys=True, separators=(",", ":"))+ owner_identity = ""+ spec = find_by_name(config.provider_name or config.binding)+ if spec and spec.backend == "github_copilot":+ from deeptutor.services.github_copilot_storage import get_github_copilot_storage++ owner_identity = str(get_github_copilot_storage().credentials_path)return (loop,config.provider_name or config.binding,@@ -42,6 +48,7 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> tconfig.temperature,config.max_tokens,config.reasoning_effort,+ owner_identity,)diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.mdindex 98a90add0..bef0f2384 100644--- a/deeptutor_cli/README.md+++ b/deeptutor_cli/README.md@@ -225,12 +225,18 @@ deeptutor config show```bashdeeptutor provider login openai-codex # 执行 OpenAI Codex OAuth 登录-deeptutor provider login github-copilot # 校验现有 GitHub Copilot 认证是否可用+deeptutor provider login github-copilot # 通过 GitHub 设备授权登录 Copilotdeeptutor provider login codebuddy # 校验 CodeBuddy SDK 登录;未登录时打开登录入口````openai-codex` 使用 DeepTutor 自己的独立 OAuth 流程登录。它不需要 `OPENAI_API_KEY`,也不会读取或同步本机 `~/.codex`;凭据保存在 `data/system/user-secrets/<owner>/private/openai-codex/`(沙箱访问不到的目录),与 Web 设置页共用。+`github-copilot` 使用 GitHub Device Flow。命令会显示一次性验证码并打开 GitHub 授权页;登录成功后会保存 GitHub token,运行时再自动换取短期 Copilot API token。`deeptutor init` 也会在选择 GitHub Copilot 后直接进入同一登录流程。++凭据仅保存在当前 DeepTutor home 的 `data/system/user-secrets/<owner-id>/private/github-copilot/credentials.v1.json`,不写入模型配置、不共享给其他用户,也不会自动读取 nanobot 等外部应用的登录文件。升级后请重新运行 `deeptutor provider login github-copilot`。CLI/本地管理员和其 Partner 使用管理员所属凭据;普通用户必须独立登录,Copilot 模型不能通过管理员授权借用。++登录命令使用实时发现的可用模型验证推理访问;`init` 验证用户选中的模型,失败时中止而非显示验证成功或保存配置。GitHub 登录成功不等于 Copilot 模型可用,失败后登录凭据仍保留。运行时遵循 token 交换返回的 API 地址(包括刷新后的变化),并根据模型的 `supported_endpoints` 选择 Responses 或 Chat Completions;只支持其他协议的模型不在列表中。+远程部署时,浏览器的 `localhost` 和服务器的 `localhost` 不是同一台机器,仅有普通反向代理无法把浏览器的 localhost callback 送到服务器,必须用 SSH 隧道建立 callback 桥。隧道通向已发布的 Web 端口;Next.js 只把精确的 callback 路径改写到 public callback broker,broker 校验 `state` 后才路由到原 OAuth operation。callback listener 仍位于后端 loopback,不发布 `1455`/`1457`,并支持默认 Docker bridge 网络。```bashdiff --git a/deeptutor_cli/init_cmd.py b/deeptutor_cli/init_cmd.pyindex dad1a4007..a5ad4f2dd 100644--- a/deeptutor_cli/init_cmd.py+++ b/deeptutor_cli/init_cmd.py@@ -10,9 +10,12 @@ intentionally thin so the order of steps is easy to read top-to-bottom.from __future__ import annotations+import asynciofrom pathlib import Path+import timefrom typing import Any+import httpxfrom rich.console import Consoleimport typer@@ -94,6 +97,15 @@ def _llm_step(display_provider = "Custom"env_key = ""+ if binding == "github_copilot":+ return _github_copilot_step(+ console,+ strings,+ base_url=default_base,+ current_model=str(current_model.get("model") or ""),+ display_provider=display_provider,+ )+edit_base = typer.confirm(strings["init.edit_base_url"], default=not bool(default_base))if edit_base:base_url = typer.prompt(strings["init.new_base_url"], default=default_base or "")@@ -139,6 +151,78 @@ def _llm_step(return choice+def _github_copilot_step(+ console: Console,+ strings: dict,+ *,+ base_url: str,+ current_model: str,+ display_provider: str,+) -> wiz.LLMChoice:+ from deeptutor.services.github_copilot_auth import (+ list_github_copilot_models,+ load_github_token,+ login_github_copilot,+ )+ from deeptutor.services.llm.provider_core.github_copilot_provider import (+ validate_github_copilot_model,+ )++ try:+ token = load_github_token()+ reuse = bool(token) and typer.confirm(+ strings["init.copilot_reuse_login"].format(+ account=getattr(token, "account_id", None) or "GitHub"+ ),+ default=True,+ )+ if not reuse:+ wiz.info(console, strings["init.copilot_login_start"])+ token = asyncio.run(login_github_copilot(print_fn=console.print))+ wiz.ok(+ console,+ strings["init.copilot_login_ok"].format(+ account=getattr(token, "account_id", None) or "GitHub"+ ),+ )+ models = asyncio.run(list_github_copilot_models())+ if not models:+ raise RuntimeError("No usable GitHub Copilot models are available for this account.")+ wiz.ok(console, strings["init.fetch_models_ok"].format(count=len(models)))+ except (httpx.HTTPError, OSError, RuntimeError, ValueError, KeyError) as exc:+ wiz.fail(console, strings["init.copilot_login_fail"].format(error=str(exc)[:200]))+ raise typer.Exit(code=1) from exc++ model = wiz.select_model(+ console,+ strings,+ models=models,+ current=current_model,+ )+ choice = wiz.LLMChoice(+ binding="github_copilot",+ base_url=base_url,+ api_key="",+ model=model,+ display_provider=display_provider,+ )+ wiz.info(console, strings["init.probe_running"].format(what=display_provider))+ started = time.monotonic()+ try:+ asyncio.run(validate_github_copilot_model(model))+ except (httpx.HTTPError, OSError, RuntimeError, ValueError) as exc:+ wiz.fail(+ console,+ strings["init.probe_fail"].format(what=display_provider, error=str(exc)[:200]),+ )+ raise typer.Exit(code=1) from exc+ choice.probed = True+ choice.probe_ok = True+ choice.probe_ms = int((time.monotonic() - started) * 1000)+ wiz.ok(console, strings["init.probe_ok"].format(what=display_provider, ms=choice.probe_ms))+ return choice++def _probe_llm_with_retry(console: Console, strings: dict, choice: wiz.LLMChoice) -> None:"""Run the probe; on failure, offer a single retry with a fresh API key."""while True:diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.pyindex 740062f69..09ad6efb9 100644--- a/deeptutor_cli/init_wizard.py+++ b/deeptutor_cli/init_wizard.py@@ -47,6 +47,7 @@ FEATURED_LLM_PROVIDERS: tuple[str, ...] = ("gemini","siliconflow","openrouter",+ "github_copilot","ollama",)@@ -54,6 +55,11 @@ FEATURED_LLM_PROVIDERS: tuple[str, ...] = (# provider is "custom". Live fetch is preferred — keep these short, just enough# to unblock common cases.LLM_FALLBACK_MODELS: dict[str, tuple[str, ...]] = {+ "github_copilot": (+ "github-copilot/gpt-4.1",+ "github-copilot/gpt-4o",+ "github-copilot/claude-sonnet-4",+ ),"openai": ("gpt-4o-mini", "gpt-4o", "o4-mini", "gpt-4.1", "gpt-4.1-mini"),"anthropic": ("claude-sonnet-4-6",diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.pyindex 117142e73..7aca2da42 100644--- a/deeptutor_cli/provider_cmd.py+++ b/deeptutor_cli/provider_cmd.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport webbrowser+import httpximport typerfrom deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service@@ -19,7 +20,7 @@ def register(app: typer.Typer) -> None:...,help=("Provider: openai-codex (OAuth login) | github-copilot "- "(validate existing Copilot auth) | codebuddy (validate CodeBuddy SDK auth)"+ "(GitHub device login) | codebuddy (validate CodeBuddy SDK auth)"),),) -> None:@@ -83,30 +84,36 @@ async def _login_openai_codex() -> None:async def _login_github_copilot() -> None:- """Validate an existing GitHub Copilot auth session via a lightweight request."""+ """Authenticate with GitHub device flow and validate Copilot access."""try:- from openai import AsyncOpenAI+ from deeptutor.services.github_copilot_auth import (+ list_github_copilot_models,+ login_github_copilot,+ )+ from deeptutor.services.llm.provider_core.github_copilot_provider import (+ validate_github_copilot_model,+ )except ImportError:typer.echo(- "openai is not installed. Install CLI deps from a local checkout: "+ "GitHub Copilot login dependencies are not installed. Install CLI deps: ""python -m pip install -e ./packaging/deeptutor-cli")raise typer.Exit(code=1)try:- client = AsyncOpenAI(- api_key="copilot",- base_url="https://api.githubcopilot.com",- max_retries=0,- )- await client.chat.completions.create(- model="gpt-4o",- messages=[{"role": "user", "content": "ping"}],- max_tokens=1,+ token = await login_github_copilot(print_fn=typer.echo)+ typer.echo(+ "GitHub sign-in saved in DeepTutor's owner-private storage. Validating Copilot...")- except Exception as exc:- typer.echo(f"GitHub Copilot auth validation failed: {exc}")+ models = await list_github_copilot_models()+ if not models:+ raise RuntimeError("No usable GitHub Copilot models are available for this account.")+ await validate_github_copilot_model(models[0])+ except (httpx.HTTPError, OSError, RuntimeError, ValueError, KeyError) as exc:+ typer.echo(f"GitHub Copilot login failed: {exc}")raise typer.Exit(code=1) from exc- typer.echo("GitHub Copilot auth validation succeeded.")+ account = getattr(token, "account_id", None) or "current account"+ typer.echo(f"GitHub Copilot login succeeded for {account}.")+ typer.echo(f"Validated model access: {models[0]}")async def _login_codebuddy() -> None:diff --git a/tests/api/test_github_copilot_models.py b/tests/api/test_github_copilot_models.pynew file mode 100644index 000000000..207a2b7be--- /dev/null+++ b/tests/api/test_github_copilot_models.py@@ -0,0 +1,258 @@+"""The settings picker must use the same owner-private discovery as the CLI."""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock++from fastapi import FastAPI+from fastapi.testclient import TestClient+import httpx+import pytest++from deeptutor.api.routers import settings+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.multi_user.paths import user_context+from deeptutor.services import github_copilot_auth as auth+from deeptutor.services.github_copilot_storage import GitHubToken+from deeptutor.services.llm import cloud_provider, local_provider+from deeptutor.services.partners.scope import PARTNER_USER_PREFIX++ENDPOINT = "/api/settings/fetch-models"+LOGIN_COMMAND = "deeptutor provider login github-copilot"+++def client(tmp_path, monkeypatch):+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home"))+ app = FastAPI()+ app.include_router(settings.router, prefix="/api/settings")+ with TestClient(app) as test_client:+ yield test_client+++def copilot_http(monkeypatch):+ """Only the HTTP transport is faked; storage, exchange and filtering are real."""+ state = SimpleNamespace(+ calls=[],+ rows=[+ {"id": "claude-live", "supported_endpoints": ["/responses"]},+ {"id": "gpt-live", "supported_endpoints": ["/chat/completions"]},+ {"id": "legacy-live"},+ {"id": "hidden", "model_picker_enabled": False},+ {"id": "disabled", "policy": {"state": "disabled"}},+ {"id": "unsupported", "supported_endpoints": ["/embeddings"]},+ ],+ failure=None,+ )++ def handle(request):+ state.calls.append(request)+ if state.failure:+ raise state.failure+ if request.url == auth.DEFAULT_COPILOT_TOKEN_URL:+ assert request.headers["Authorization"].startswith("token fixture-")+ return httpx.Response(+ 200,+ json={+ "token": "fixture-short-lived",+ "expires_at": 2_000_000_000,+ "endpoints": {"api": "https://tenant.example/copilot"},+ },+ )+ assert str(request.url) == "https://tenant.example/copilot/models"+ assert request.headers["Authorization"] == "Bearer fixture-short-lived"+ return httpx.Response(200, json={"data": state.rows})++ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ auth.httpx,+ "AsyncClient",+ lambda **kwargs: real_client(transport=httpx.MockTransport(handle), **kwargs),+ )+ monkeypatch.delenv("DEEPTUTOR_COPILOT_TOKEN_URL", raising=False)+ monkeypatch.setattr(+ cloud_provider, "fetch_models", AsyncMock(side_effect=AssertionError("generic cloud path"))+ )+ monkeypatch.setattr(+ local_provider, "fetch_models", AsyncMock(side_effect=AssertionError("generic local path"))+ )+ return state+++def _login():+ auth.get_github_copilot_storage().save(+ GitHubToken("fixture-github", 2_000_000_000_000, "fixture-account")+ )++[email protected]("binding", ["github_copilot", "github-copilot", " GitHub_Copilot "])[email protected]("api_key", [None, "", "***"])+def test_picker_returns_live_selectable_models(client, copilot_http, monkeypatch, binding, api_key):+ _login()+ monkeypatch.setattr(+ settings,+ "get_model_catalog_service",+ lambda: pytest.fail("Copilot must not load API keys from the shared catalog"),+ )+ response = client.post(+ ENDPOINT,+ json={+ "binding": binding,+ "base_url": "",+ "api_key": api_key,+ "profile_id": "copilot-profile",+ "service": "llm",+ },+ )+ assert response.status_code == 200+ ids = ["github-copilot/claude-live", "github-copilot/gpt-live", "github-copilot/legacy-live"]+ assert response.json() == {"models": [{"id": model, "name": model} for model in ids]}+ assert len(copilot_http.calls) == 2+ assert "fixture-" not in response.text+++def test_task_picker_ignores_draft_endpoint_and_key(client, copilot_http):+ _login()+ response = client.post(+ ENDPOINT,+ json={+ "binding": "github_copilot",+ "base_url": "http://localhost:1234/v1",+ "api_key": "untrusted-draft-key",+ "api_format": "anthropic",+ "service": "task",+ },+ )+ assert response.status_code == 200+ assert len(copilot_http.calls) == 2+ assert response.json()["models"][0]["id"] == "github-copilot/claude-live"+++def test_missing_login_is_actionable_not_empty_success(client, copilot_http):+ response = client.post(ENDPOINT, json={"binding": "github_copilot"})+ assert response.status_code == 502+ assert LOGIN_COMMAND in response.json()["detail"]+ assert "models" not in response.json()+ assert copilot_http.calls == []++[email protected]("failure_kind", ["unauthorized", "forbidden", "timeout", "invalid"])+def test_provider_errors_are_safe_and_actionable(client, copilot_http, caplog, failure_kind):+ _login()+ secret = "fixture-sensitive-error"+ request = httpx.Request("GET", f"https://tenant.example/?token={secret}")+ if failure_kind in {"unauthorized", "forbidden"}:+ upstream = httpx.Response(+ 401 if failure_kind == "unauthorized" else 403,+ request=request,+ json={"error": secret},+ )+ failure = httpx.HTTPStatusError(secret, request=request, response=upstream)+ elif failure_kind == "timeout":+ failure = httpx.ReadTimeout(secret, request=request)+ else:+ failure = ValueError(secret)+ copilot_http.failure = failure++ response = client.post(ENDPOINT, json={"binding": "github_copilot"})++ assert response.status_code == 502+ assert LOGIN_COMMAND in response.json()["detail"]+ assert secret not in response.text+ assert secret not in caplog.text+++def test_catalog_failure_is_not_silently_swallowed(client, copilot_http, monkeypatch):+ _login()+ monkeypatch.setattr(+ auth, "fetch_github_copilot_models", AsyncMock(side_effect=RuntimeError("fixture-error"))+ )+ response = client.post(ENDPOINT, json={"binding": "github_copilot"})+ assert response.status_code == 502+ assert LOGIN_COMMAND in response.json()["detail"]+ assert "fixture-error" not in response.text+++def test_owner_and_home_scope_are_preserved(client, copilot_http, tmp_path, monkeypatch):+ _login()+ other = CurrentUser(+ id="u_other",+ username="other",+ role="admin",+ scope=UserScope(kind="user", user_id="u_other", root=tmp_path / "other"),+ )+ with user_context(other):+ response = client.post(ENDPOINT, json={"binding": "github_copilot"})+ assert response.status_code == 502+ assert copilot_http.calls == []+ auth.get_github_copilot_storage().save(+ GitHubToken("fixture-other", 2_000_000_000_000, "other")+ )+ response = client.post(ENDPOINT, json={"binding": "github_copilot"})+ assert response.status_code == 200+ assert copilot_http.calls[0].headers["Authorization"] == "token fixture-other"++ copilot_http.calls.clear()+ assert client.post(ENDPOINT, json={"binding": "github_copilot"}).status_code == 200+ assert copilot_http.calls[0].headers["Authorization"] == "token fixture-github"++ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "different-home"))+ copilot_http.calls.clear()+ assert client.post(ENDPOINT, json={"binding": "github_copilot"}).status_code == 502+ assert copilot_http.calls == []++[email protected]("user_id", ["u_reader", f"{PARTNER_USER_PREFIX}ada"])+def test_settings_permission_gate_still_applies(client, copilot_http, tmp_path, user_id):+ user = CurrentUser(+ id=user_id,+ username=user_id,+ role="user",+ scope=UserScope(kind="user", user_id=user_id, root=tmp_path / "reader"),+ )+ with user_context(user):+ response = client.post(ENDPOINT, json={"binding": "github_copilot"})+ assert response.status_code == 403+ assert copilot_http.calls == []+++def test_standard_provider_keeps_key_endpoint_format_and_contract(client, monkeypatch):+ fetch = AsyncMock(return_value=["gpt-standard"])+ monkeypatch.setattr(cloud_provider, "fetch_models", fetch)+ response = client.post(+ ENDPOINT,+ json={+ "binding": "OpenAI",+ "base_url": "https://standard.example/v1",+ "api_key": "fixture-standard",+ "api_format": "responses",+ },+ )+ assert response.status_code == 200+ assert response.json() == {"models": [{"id": "gpt-standard", "name": "gpt-standard"}]}+ fetch.assert_awaited_once_with(+ "https://standard.example/v1", "fixture-standard", "openai", api_format="responses"+ )+ assert client.post(ENDPOINT, json={"binding": "openai"}).status_code == 400+++def test_copilot_registry_and_probe_accept_empty_api_key():+ from deeptutor.services.llm.config import LLMConfig+ from deeptutor.services.provider_registry import find_by_name++ spec = find_by_name("github_copilot")+ assert spec.is_oauth+ assert spec.auth_mode == "oauth"+ choices = settings._provider_choices()["llm"]+ assert next(row for row in choices if row["value"] == spec.name)["auth_mode"] == "oauth"+ config = LLMConfig(+ model="github-copilot/gpt-live",+ binding=spec.name,+ provider_name=spec.name,+ provider_mode=spec.mode,+ api_key="",+ base_url="",+ )+ assert config.get_api_key() == ""diff --git a/tests/cli/test_init_wizard_probe.py b/tests/cli/test_init_wizard_probe.pyindex f445e1c74..1456304d4 100644--- a/tests/cli/test_init_wizard_probe.py+++ b/tests/cli/test_init_wizard_probe.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom io import StringIOfrom types import SimpleNamespace+import pytestfrom rich.console import Console@@ -17,6 +18,93 @@ def test_gemini_embedding_fallback_prefers_stable_embedding2() -> None:)+def test_github_copilot_is_featured_with_prefixed_fallback_models() -> None:+ from deeptutor_cli.init_wizard import FEATURED_LLM_PROVIDERS, LLM_FALLBACK_MODELS++ assert "github_copilot" in FEATURED_LLM_PROVIDERS+ assert LLM_FALLBACK_MODELS["github_copilot"][0] == "github-copilot/gpt-4.1"++[email protected]("outcome", ["success", "error", "exception", "no-models"])+def test_github_copilot_init_logs_in_and_uses_live_models(+ monkeypatch: pytest.MonkeyPatch,+ outcome: str,+) -> None:+ import typer++ from deeptutor.runtime.banner import labels_for+ from deeptutor.services import github_copilot_auth+ from deeptutor.services.llm.provider_core import github_copilot_provider+ from deeptutor_cli import init_cmd++ probes = []++ class FakeProvider:+ def __init__(self, *, default_model):+ probes.append(default_model)++ async def chat(self, **kwargs):+ probes.append("chat")+ if outcome == "exception":+ raise RuntimeError("unavailable model")+ return SimpleNamespace(+ finish_reason="error" if outcome == "error" else "stop",+ content="unavailable model" if outcome == "error" else "OK",+ )++ async def aclose(self):+ probes.append("close")++ monkeypatch.setattr(github_copilot_provider, "GitHubCopilotProvider", FakeProvider)++ async def login(*, print_fn):+ print_fn("Code: ABCD-1234")+ return SimpleNamespace(account_id="octocat")++ async def models():+ return [] if outcome == "no-models" else ["github-copilot/gpt-4.1", "github-copilot/gpt-5"]++ monkeypatch.setattr(github_copilot_auth, "load_github_token", lambda: None)+ monkeypatch.setattr(github_copilot_auth, "login_github_copilot", login)+ monkeypatch.setattr(github_copilot_auth, "list_github_copilot_models", models)+ monkeypatch.setattr(+ init_cmd.wiz,+ "select_model",+ lambda _console, _strings, *, models, current: models[-1],+ )++ output = StringIO()+ if outcome != "success":+ with pytest.raises(typer.Exit) as exc:+ init_cmd._github_copilot_step(+ Console(file=output),+ labels_for("en"),+ base_url="https://api.githubcopilot.com",+ current_model="",+ display_provider="GitHub Copilot",+ )+ assert exc.value.exit_code == 1+ assert probes == (+ [] if outcome == "no-models" else ["github-copilot/gpt-5", "chat", "close"]+ )+ return+ choice = init_cmd._github_copilot_step(+ Console(file=output, force_terminal=False),+ labels_for("en"),+ base_url="https://api.githubcopilot.com",+ current_model="",+ display_provider="GitHub Copilot",+ )++ assert choice.binding == "github_copilot"+ assert choice.api_key == ""+ assert choice.model == "github-copilot/gpt-5"+ assert choice.probed is True+ assert choice.probe_ok is True+ assert "Code: ABCD-1234" in output.getvalue()+ assert probes == ["github-copilot/gpt-5", "chat", "close"]++def test_embedding_setup_preserves_saved_endpoint_for_same_provider() -> None:from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERSfrom deeptutor_cli.init_cmd import _embedding_default_endpointdiff --git a/tests/cli/test_provider_cli.py b/tests/cli/test_provider_cli.pyindex 17cad208a..72e2c4d44 100644--- a/tests/cli/test_provider_cli.py+++ b/tests/cli/test_provider_cli.py@@ -1,6 +1,8 @@from pathlib import Path+from types import SimpleNamespaceimport unittest+import pytestfrom typer.testing import CliRunnerfrom deeptutor_cli import provider_cmd@@ -13,28 +15,28 @@ 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:+ def test_provider_contract_describes_copilot_device_login(self) -> None:self.assertIn('"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("(GitHub device login)", PROVIDER_CMD)+ self.assertIn("GitHub Copilot login succeeded for", PROVIDER_CMD)+ self.assertIn("GitHub Copilot login 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; `codebuddy` validates CodeBuddy SDK auth and starts login when needed)",+ "Provider auth (`openai-codex` OAuth login; `github-copilot` GitHub device login; `codebuddy` validates CodeBuddy SDK auth and starts login when needed)",ROOT_README,)self.assertIn(- "deeptutor provider login github-copilot # 校验现有 GitHub Copilot 认证是否可用",+ "deeptutor provider login github-copilot # 通过 GitHub 设备授权登录 Copilot",CLI_README,)self.assertIn(@@ -126,5 +128,57 @@ def test_cli_opens_authorize_url_and_waits_for_completion(monkeypatch) -> None:assert "gpt-5.6-sol" in result.stdout[email protected]("outcome", ["success", "error", "exception", "no-models"])+def test_github_copilot_cli_runs_device_login_and_validates_access(monkeypatch, outcome) -> None:+ from deeptutor.services import github_copilot_auth+ from deeptutor.services.llm.provider_core import github_copilot_provider++ events: list[str] = []++ async def login(*, print_fn):+ print_fn("Code: ABCD-1234")+ events.append("login")+ return SimpleNamespace(account_id="octocat")++ async def models():+ return [] if outcome == "no-models" else ["github-copilot/claude-sonnet"]++ class FakeProvider:+ def __init__(self, *, default_model: str) -> None:+ events.append(default_model)++ async def chat(self, **_kwargs):+ events.append("chat")+ if outcome == "exception":+ raise RuntimeError("model disabled")+ return SimpleNamespace(+ content="model disabled" if outcome == "error" else "OK",+ finish_reason="error" if outcome == "error" else "stop",+ )++ async def aclose(self) -> None:+ events.append("close")++ monkeypatch.setattr(github_copilot_auth, "login_github_copilot", login)+ monkeypatch.setattr(github_copilot_auth, "list_github_copilot_models", models)+ monkeypatch.setattr(github_copilot_provider, "GitHubCopilotProvider", FakeProvider)++ result = CliRunner().invoke(app, ["provider", "login", "github-copilot"])++ assert result.exit_code == (0 if outcome == "success" else 1)+ assert "Code: ABCD-1234" in result.stdout+ if outcome == "success":+ assert "GitHub Copilot login succeeded for octocat." in result.stdout+ assert "Validated model access: github-copilot/claude-sonnet" in result.stdout+ else:+ assert "login succeeded" not in result.stdout+ assert "GitHub Copilot login failed:" in result.stdout+ assert events == (+ ["login"]+ if outcome == "no-models"+ else ["login", "github-copilot/claude-sonnet", "chat", "close"]+ )++if __name__ == "__main__":unittest.main()diff --git a/tests/multi_user/test_owner_bound_models.py b/tests/multi_user/test_owner_bound_models.pyindex 2860d1f6c..4753de71e 100644--- a/tests/multi_user/test_owner_bound_models.py+++ b/tests/multi_user/test_owner_bound_models.py@@ -151,3 +151,34 @@ def test_individual_provider_references_keep_subscription_models_private(tmp_patassert rows[0]["model_id"] == "m-sol"finally:reset_current_user(token)+++def test_copilot_binding_blocks_existing_grants_and_assignment(tmp_path, monkeypatch):+ from deeptutor.api.routers import multi_user as router++ catalog = _catalog(owner_bound=False)+ catalog["services"]["llm"]["profiles"][0]["binding"] = "github_copilot"+ assert model_access.is_owner_bound({"binding": "GitHub_Copilot"})+ assert model_access.is_owner_bound({"binding": "github-copilot"})+ monkeypatch.setattr(model_access, "admin_catalog", lambda: catalog)+ monkeypatch.setattr(model_access, "load_grant", _grant)+ monkeypatch.setattr(+ router, "ModelCatalogService", lambda path=None: SimpleNamespace(load=lambda: catalog)+ )+ monkeypatch.setattr(+ router,+ "get_admin_path_service",+ lambda: SimpleNamespace(get_settings_file=lambda _: tmp_path / "catalog.json"),+ )+ token = set_current_user(make_user(tmp_path))+ try:+ assert model_access.redacted_model_access()["llm"] == []+ assert model_access.allowed_llm_options()["options"] == []+ assert not model_access.has_capability_access("llm")+ with pytest.raises(PermissionError):+ model_access.apply_allowed_llm_selection(+ {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}+ )+ assert router._admin_catalog_summary() == {"llm": []}+ finally:+ reset_current_user(token)diff --git a/tests/multi_user/test_owner_path_service.py b/tests/multi_user/test_owner_path_service.pyindex 5035f6a0c..ba9f1b910 100644--- a/tests/multi_user/test_owner_path_service.py+++ b/tests/multi_user/test_owner_path_service.py@@ -49,3 +49,17 @@ def test_partner_scope_resolves_to_its_owner(mu_isolated_root) -> None:def test_no_active_scope_falls_back_to_the_current_path_service(mu_isolated_root) -> None:assert get_owner_path_service().get_user_root() == (get_current_path_service().get_user_root())+++def test_copilot_partner_uses_owner_secret_not_workspace(mu_isolated_root, monkeypatch):+ from deeptutor.services.github_copilot_storage import get_github_copilot_storage++ monkeypatch.setenv("DEEPTUTOR_HOME", str(mu_isolated_root))+ owner_path = get_github_copilot_storage().credentials_path+ token = set_current_user(partner_user("ada"))+ try:+ assert get_github_copilot_storage().credentials_path == owner_path+ assert owner_path.is_relative_to(mu_isolated_root / "data" / "system")+ assert not owner_path.is_relative_to(get_current_path_service().get_user_root())+ finally:+ reset_current_user(token)diff --git a/tests/services/llm/test_github_copilot_provider.py b/tests/services/llm/test_github_copilot_provider.pynew file mode 100644index 000000000..16ceb2bf2--- /dev/null+++ b/tests/services/llm/test_github_copilot_provider.py@@ -0,0 +1,624 @@+from __future__ import annotations++from copy import deepcopy+import json+from types import SimpleNamespace++import httpx+from openai import AsyncOpenAI+import pytest++from deeptutor.services.llm.provider_core import github_copilot_provider as module+from deeptutor.services.session.context_builder import ContextBuilder+from deeptutor.services.session.provider_response_state import normalize_provider_response_state+from deeptutor.services.session.sqlite_store import SQLiteSessionStore++[email protected]("model", ["gpt-6-astra", "github-copilot/gpt-6-astra", "GPT-6-ASTRA"])[email protected]("effort", [None, "none", "high"])+def test_astra_never_supports_temperature(model, effort):+ assert module.GitHubCopilotProvider._supports_temperature(model, effort) is False+++async def test_provider_exchanges_stored_token_before_every_uncached_request(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ exchanges = 0+ seen_keys: list[str] = []++ async def exchange(github_token):+ assert github_token == "owner-token"+ nonlocal exchanges+ exchanges += 1+ return SimpleNamespace(+ token="copilot-access",+ expires_at=2_000_000_000,+ api_base="https://tenant.example",+ )++ async def models(_access):+ return [module.CopilotModel("gpt-4.1")]++ async def chat(self, **_kwargs):+ seen_keys.append(self.api_key)+ return SimpleNamespace(content="ok")++ monkeypatch.setattr(module, "exchange_copilot_token", exchange)+ monkeypatch.setattr(module, "fetch_github_copilot_models", models)+ monkeypatch.setattr(+ module,+ "get_github_copilot_storage",+ lambda: SimpleNamespace(load=lambda: SimpleNamespace(access="owner-token")),+ )+ monkeypatch.setattr(module.OpenAICompatProvider, "chat", chat)++ provider = module.GitHubCopilotProvider()+ assert provider._key_pool is None+ await provider.chat(messages=[{"role": "user", "content": "hello"}])+ await provider.chat(messages=[{"role": "user", "content": "again"}])++ assert exchanges == 1+ assert seen_keys == ["copilot-access", "copilot-access"]+ assert provider.api_base == "https://tenant.example"+ assert provider._effective_base == "https://tenant.example"+ assert str(provider._client.base_url) == "https://tenant.example/"+ await provider.aclose()+++async def _provider_with_transport(monkeypatch, handler, catalog):+ async def exchange(_token):+ return SimpleNamespace(+ token="copilot-access",+ expires_at=2_000_000_000,+ api_base="https://tenant.example",+ )++ async def models(_access):+ return catalog++ monkeypatch.setattr(module, "exchange_copilot_token", exchange)+ monkeypatch.setattr(module, "fetch_github_copilot_models", models)+ monkeypatch.setattr(+ module,+ "get_github_copilot_storage",+ lambda: SimpleNamespace(load=lambda: SimpleNamespace(access="owner-token")),+ )+ provider = module.GitHubCopilotProvider()+ await provider.aclose()+ provider._client = AsyncOpenAI(+ api_key="no-key",+ max_retries=0,+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ )+ return provider++[email protected]("stream", [False, True])+ "model,endpoints,path",+ [+ ("gpt-6-astra", ("/responses",), "/responses"),+ ("gpt-6-astra", ("/chat/completions",), "/chat/completions"),+ ("claude-sonnet", ("/responses",), "/responses"),+ ("gpt-5-chat-only", ("/chat/completions",), "/chat/completions"),+ ("gpt-5", ("/responses", "/chat/completions"), "/responses"),+ ("claude-both", ("/responses", "/chat/completions"), "/chat/completions"),+ ],+)+async def test_model_protocol_metadata_routes_actual_sdk_requests(+ monkeypatch, stream, model, endpoints, path+):+ calls = []++ def handler(request):+ calls.append(request)+ assert request.url.host == "tenant.example"+ assert request.url.path == path+ assert request.headers["authorization"] == "Bearer copilot-access"+ body = json.loads(request.content)+ assert body["model"] == model+ if model == "gpt-6-astra":+ assert "temperature" not in body+ elif model.startswith("claude"):+ assert body["temperature"] == 0.7+ if stream:+ if path == "/responses":+ events = [+ {"type": "response.output_text.delta", "delta": "OK"},+ {+ "type": "response.completed",+ "response": {+ "id": "resp_1",+ "status": "completed",+ "output": [],+ },+ },+ ]+ else:+ events = [+ {+ "id": "chat_1",+ "choices": [+ {"index": 0, "delta": {"content": "OK"}, "finish_reason": "stop"}+ ],+ }+ ]+ content = "".join(f"data: {json.dumps(event)}\n\n" for event in events)+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text=content + "data: [DONE]\n\n",+ )+ if path == "/responses":+ return httpx.Response(+ 200,+ json={+ "id": "resp_1",+ "status": "completed",+ "output": [+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "OK"}],+ }+ ],+ },+ )+ return httpx.Response(+ 200,+ json={+ "id": "chat_1",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "OK"},+ "finish_reason": "stop",+ }+ ],+ },+ )++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel(model, endpoints)]+ )+ # A Responses-only model must not be redirected by the heuristic circuit breaker.+ provider._responses_circuit_allows = lambda *args: False if len(endpoints) == 1 else True+ try:+ method = provider.chat_stream if stream else provider.chat+ response = await method(+ messages=[{"role": "user", "content": "hi"}], model=f"github-copilot/{model}"+ )+ assert response.finish_reason != "error", response.content+ assert response.content == "OK"+ assert len(calls) == 1+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])+async def test_responses_only_error_never_falls_back_to_chat(monkeypatch, stream):+ calls = []++ def handler(request):+ calls.append(request.url.path)+ return httpx.Response(400, json={"error": {"message": "responses unavailable"}})++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("claude", ("/responses",))]+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ response = await method(messages=[], model="claude")+ assert response.finish_reason == "error"+ assert calls == ["/responses"]+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])[email protected]("replay", [False, True])+async def test_multiturn_responses_omits_output_message_metadata(monkeypatch, stream, replay):+ messages = [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi"},+ {"role": "user", "content": "Continue"},+ ]+ if replay:+ messages[1]["_provider_response_state"] = {+ "responses_output_items": [+ {+ "type": "message",+ "role": "assistant",+ "id": "msg_previous",+ "status": "completed",+ "content": [{"type": "output_text", "text": "Hi"}],+ },+ {+ "type": "function_call",+ "id": "fc_previous",+ "call_id": "call_previous",+ "name": "lookup",+ "arguments": "{}",+ },+ ]+ }+ messages.insert(2, {"role": "tool", "tool_call_id": "call_previous", "content": "result"})+ original = deepcopy(messages)+ calls = []++ def handler(request):+ body = json.loads(request.content)+ calls.append(body)+ assert request.url.path == "/responses"+ assistant = body["input"][1]+ assert assistant["role"] == "assistant"+ assert assistant["content"][0]["text"] == "Hi"+ assert "status" not in assistant+ assert "id" not in assistant+ if replay:+ assert body["input"][2]["id"] == "fc_previous"+ assert body["input"][2]["call_id"] == body["input"][3]["call_id"]+ if stream:+ events = [+ {"type": "response.output_text.delta", "delta": "OK"},+ {+ "type": "response.completed",+ "response": {"id": "resp_2", "status": "completed", "output": []},+ },+ ]+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text="".join(f"data: {json.dumps(event)}\n\n" for event in events),+ )+ return httpx.Response(+ 200,+ json={+ "id": "resp_2",+ "status": "completed",+ "output": [+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "OK"}],+ }+ ],+ },+ )++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("gpt-5", ("/responses",))]+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ response = await method(messages=messages, model="gpt-5")+ assert response.finish_reason != "error", response.content+ assert response.content == "OK"+ assert len(calls) == 1+ assert messages == original+ finally:+ await provider.aclose()+++def _reasoning_output(index):+ # Shape observed on Copilot's wire: no status. SDK model_dump adds status=None.+ return {+ "type": "reasoning",+ "id": f"rs_{index}",+ "summary": [],+ "content": [],+ "encrypted_content": f"opaque-test-reasoning-{index}",+ }+++def _message_output(index):+ return {+ "type": "message",+ "id": f"msg_{index}",+ "role": "assistant",+ "status": "completed",+ "phase": "final_answer",+ "content": [{"type": "output_text", "text": "OK", "annotations": []}],+ }+++def _responses_reply(output, stream):+ response = {"id": "resp_test", "status": "completed", "output": output}+ if not stream:+ return httpx.Response(200, json=response)+ events = []+ for index, item in enumerate(output):+ events.append({"type": "response.output_item.added", "output_index": index, "item": item})+ if item["type"] == "message":+ events.append({"type": "response.output_text.delta", "delta": "OK"})+ events.append({"type": "response.output_item.done", "output_index": index, "item": item})+ events.append({"type": "response.completed", "response": response})+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text="".join(f"data: {json.dumps(event)}\n\n" for event in events),+ )++[email protected]("stream", [False, True])+async def test_four_turn_sqlite_history_replays_sdk_reasoning_without_status(+ monkeypatch, tmp_path, stream+):+ bodies = []++ def handler(request):+ body = json.loads(request.content)+ bodies.append(body)+ for index, item in enumerate(body["input"]):+ if "status" in item:+ return httpx.Response(+ 400,+ json={"error": {"message": f"Unknown parameter: 'input[{index}].status'."}},+ )+ turn = len(bodies)+ output = ([] if turn == 1 else [_reasoning_output(turn)]) + [_message_output(turn)]+ return _responses_reply(output, stream)++ store = SQLiteSessionStore(db_path=tmp_path / "copilot-replay.db")+ session = await store.create_session()+ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("gpt-5.6-sol-fast", ("/responses",))]+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ for turn in range(1, 5):+ await store.add_message(session["id"], "user", f"Synthetic turn {turn}")+ stored = await store.get_messages(session["id"])+ history = ContextBuilder(store)._build_history("", stored)+ original = deepcopy(history)+ result = await method(messages=history, model="gpt-5.6-sol-fast")+ assert result.finish_reason == "stop", result.content+ assert history == original+ items = result.provider_specific_fields.get("native_output_items", [])+ if turn >= 2:+ assert items[0]["type"] == "reasoning"+ assert "status" in items[0] and items[0]["status"] is None+ assert items[0]["encrypted_content"] == f"opaque-test-reasoning-{turn}"+ state = normalize_provider_response_state({"responses_output_items": items})+ await store.add_message(+ session["id"],+ "assistant",+ result.content,+ metadata={"provider_response_state": state},+ )+ if turn >= 3:+ reasoning = bodies[-1]["input"][3]+ assert reasoning["type"] == "reasoning"+ assert reasoning["id"] == "rs_2"+ assert reasoning["encrypted_content"] == "opaque-test-reasoning-2"+ assert reasoning["summary"] == []+ assert "status" not in reasoning+ assistant = bodies[-1]["input"][4]+ assert assistant["phase"] == "final_answer"+ assert "id" not in assistant+ persisted = await store.get_messages(session["id"])+ assert persisted[:-1] == stored+ assert persisted[-1]["metadata"]["provider_response_state"] == state+ assert len(bodies) == 4+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])+async def test_replayed_reasoning_and_tool_rounds_preserve_call_pairing(monkeypatch, stream):+ bodies = []++ def handler(request):+ body = json.loads(request.content)+ bodies.append(body)+ assert all(+ "status" not in item+ for item in body["input"]+ if item.get("type") in {"message", "reasoning"}+ )+ for item in body["input"]:+ if item.get("type") == "function_call":+ assert item["status"] == "completed"+ assert item["id"] == f"fc_{item['call_id'].split('_')[-1]}"+ assert item["arguments"] == '{"status":"keep nested argument"}'+ assert any(+ output.get("type") == "function_call_output"+ and output["call_id"] == item["call_id"]+ for output in body["input"]+ )+ turn = len(bodies)+ output = [+ _reasoning_output(turn),+ {+ "type": "function_call",+ "id": f"fc_{turn}",+ "call_id": f"call_{turn}",+ "name": "lookup",+ "arguments": '{"status":"keep nested argument"}',+ "status": "completed",+ },+ ]+ return _responses_reply(output, stream)++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("gpt-5", ("/responses",))]+ )+ try:+ history = [{"role": "user", "content": "Use lookup"}]+ method = provider.chat_stream if stream else provider.chat+ for turn in range(1, 5):+ original = deepcopy(history)+ result = await method(messages=history, model="gpt-5")+ assert result.finish_reason != "error", result.content+ assert history == original+ items = result.provider_specific_fields["native_output_items"]+ assert items[1]["status"] == "completed"+ call = result.tool_calls[0]+ assert call.id == f"call_{turn}|fc_{turn}"+ history.extend(+ [+ {+ "role": "assistant",+ "content": "",+ "_provider_response_state": {"responses_output_items": items},+ },+ {"role": "tool", "tool_call_id": call.id, "content": "Synthetic result"},+ ]+ )+ history = json.loads(json.dumps(history))+ assert len(bodies) == 4+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])[email protected]("override", ["input", "extra_body"])[email protected]("reasoning_status", [None, "completed"])+async def test_responses_input_overrides_are_normalized_after_kwargs_merge(+ monkeypatch, stream, override, reasoning_status+):+ items = [+ {"role": "assistant", "id": "msg_raw", "status": "completed", "content": "OK"},+ {**_reasoning_output(1), "status": reasoning_status},+ {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": "lookup",+ "arguments": "{}",+ "status": "completed",+ },+ {"type": "function_call_output", "call_id": "call_1", "output": "OK", "status": None},+ {"type": "web_search_call", "id": "ws_1", "status": "completed"},+ ]+ kwargs = {"input": items} if override == "input" else {"extra_body": {"input": items}}+ original = deepcopy(kwargs)++ def handler(request):+ body = json.loads(request.content)+ expected = deepcopy(items)+ for item in expected[:2]:+ item.pop("status")+ expected[0].pop("id")+ assert body["input"] == expected+ return _responses_reply([_message_output(1)], stream)++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("gpt-5", ("/responses",))]+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ result = await method(+ messages=[{"role": "user", "content": "Ignored"}], model="gpt-5", **kwargs+ )+ assert result.finish_reason == "stop", result.content+ assert kwargs == original+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])+async def test_copilot_normalization_does_not_change_openai_requests(stream):+ items = [{**_reasoning_output(1), "status": None}, _message_output(1)]+ history = [+ {+ "role": "assistant",+ "content": "OK",+ "_provider_response_state": {"responses_output_items": items},+ },+ {"role": "user", "content": "Continue"},+ ]+ original = deepcopy(history)+ bodies = []++ def handler(request):+ body = json.loads(request.content)+ bodies.append(body)+ assert body["input"][:2] == items+ return _responses_reply([_message_output(2)], stream)++ provider = module.OpenAICompatProvider(+ api_key="test-key", wire_api="responses", configure_env=False+ )+ await provider.aclose()+ provider._client = AsyncOpenAI(+ api_key="test-key",+ max_retries=0,+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ result = await method(messages=history, model="gpt-5")+ assert result.finish_reason == "stop", result.content+ assert len(bodies) == 1+ assert history == original+ finally:+ await provider.aclose()++[email protected]("stream", [False, True])+async def test_unavailable_model_does_not_send_inference(monkeypatch, stream):+ provider = await _provider_with_transport(+ monkeypatch, lambda request: pytest.fail("unavailable model was requested"), []+ )+ try:+ method = provider.chat_stream if stream else provider.chat+ response = await method(messages=[], model="removed-model")+ assert response.finish_reason == "error"+ assert "not currently available" in response.content+ finally:+ await provider.aclose()+++async def test_refresh_changes_endpoint_and_keeps_original_owner(monkeypatch):+ seen = []++ def handler(request):+ seen.append((request.url.host, request.headers["authorization"]))+ assert request.url.path == "/api/chat/completions"+ return httpx.Response(+ 200, json={"choices": [{"message": {"content": "OK"}, "finish_reason": "stop"}]}+ )++ provider = await _provider_with_transport(+ monkeypatch, handler, [module.CopilotModel("gpt-4.1", ("/chat/completions",))]+ )+ count = 0++ async def exchange(token):+ nonlocal count+ assert token == "owner-token"+ count += 1+ return SimpleNamespace(+ token=f"token-{count}",+ expires_at=2_000_000_000,+ api_base=f"https://tenant-{count}.example/api",+ )++ monkeypatch.setattr(module, "exchange_copilot_token", exchange)+ try:+ await provider.chat(messages=[])+ # A later request context must not change the owner attached to the provider.+ monkeypatch.setattr(+ module, "get_github_copilot_storage", lambda: pytest.fail("wrong owner")+ )+ provider._copilot_expires_at = 0+ await provider.chat(messages=[])+ assert seen == [+ ("tenant-1.example", "Bearer token-1"),+ ("tenant-2.example", "Bearer token-2"),+ ]+ assert provider.api_base == provider._effective_base == "https://tenant-2.example/api"+ assert str(provider._client.base_url) == "https://tenant-2.example/api/"+ finally:+ await provider.aclose()diff --git a/tests/services/llm/test_provider_pool.py b/tests/services/llm/test_provider_pool.pyindex be282f9ba..ce92e2587 100644--- a/tests/services/llm/test_provider_pool.py+++ b/tests/services/llm/test_provider_pool.py@@ -117,3 +117,29 @@ async def test_reset_closes_all_cached_providers(monkeypatch) -> None:await asyncio.sleep(0)assert provider_factory.runtime_provider_pool_size() == 0assert built[0].closed == 1++[email protected]("name", ["github_copilot", "github-copilot"])+async def test_copilot_pool_separates_owners_and_runtime_homes(tmp_path, monkeypatch, name) -> None:+ from deeptutor.multi_user.models import CurrentUser, UserScope+ from deeptutor.multi_user.paths import user_context++ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home-one"))+ monkeypatch.setattr(provider_factory, "_build_runtime_provider", lambda _: _FakeProvider())+ config = _config(binding=name, provider_name=name, api_key="")+ admin = provider_factory.get_runtime_provider(config)+ assert admin is provider_factory.get_runtime_provider(config)+ user = CurrentUser(+ id="u_alice",+ username="alice",+ role="user",+ scope=UserScope(kind="user", user_id="u_alice", root=tmp_path / "alice"),+ )+ with user_context(user):+ alice = provider_factory.get_runtime_provider(config)+ assert alice is provider_factory.get_runtime_provider(config)+ assert alice is not admin+ assert admin is provider_factory.get_runtime_provider(config)+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home-two"))+ assert provider_factory.get_runtime_provider(config) is not admindiff --git a/tests/services/test_github_copilot_auth.py b/tests/services/test_github_copilot_auth.pynew file mode 100644index 000000000..0b5f0910c--- /dev/null+++ b/tests/services/test_github_copilot_auth.py@@ -0,0 +1,209 @@+from __future__ import annotations++import os+import stat+import sys+from types import ModuleType, SimpleNamespace++import pytest++from deeptutor.services import github_copilot_auth as auth+++class _Response:+ def __init__(self, payload: dict) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict:+ return self._payload+++class _Client:+ calls: list[tuple[str, str, dict]] = []+ poll_count = 0++ def __init__(self, **_kwargs) -> None:+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ async def post(self, url: str, **kwargs):+ self.calls.append(("post", url, kwargs))+ if url.endswith("/device/code"):+ return _Response(+ {+ "device_code": "device-code",+ "user_code": "ABCD-1234",+ "verification_uri": "https://github.com/login/device",+ "interval": 1,+ "expires_in": 30,+ }+ )+ type(self).poll_count += 1+ if type(self).poll_count == 1:+ return _Response({"error": "authorization_pending"})+ return _Response({"access_token": "github-token"})++ async def get(self, url: str, **kwargs):+ self.calls.append(("get", url, kwargs))+ return _Response({"login": "octocat"})+++async def test_device_login_persists_github_token(monkeypatch: pytest.MonkeyPatch) -> None:+ saved: list[object] = []+ storage = SimpleNamespace(load=lambda: None, save=saved.append)++ _Client.calls = []+ _Client.poll_count = 0+ monkeypatch.setattr(auth.httpx, "AsyncClient", _Client)+ monkeypatch.setattr(auth, "get_github_copilot_storage", lambda: storage)+ monkeypatch.setattr(auth.asyncio, "sleep", lambda _seconds: _immediate())+ opened: list[str] = []+ monkeypatch.setattr(auth.webbrowser, "open", opened.append)++ output: list[str] = []+ token = await auth.login_github_copilot(print_fn=output.append)++ assert token.access == "github-token"+ assert token.account_id == "octocat"+ assert saved == [token]+ assert opened == ["https://github.com/login/device"]+ assert output == ["Open: https://github.com/login/device", "Code: ABCD-1234"]+ assert _Client.poll_count == 2+++async def _immediate() -> None:+ return None+++def test_storage_is_private_and_isolated_by_owner_and_home(tmp_path, monkeypatch):+ from deeptutor.multi_user.models import CurrentUser, UserScope+ from deeptutor.multi_user.paths import user_context+ from deeptutor.services.github_copilot_storage import GitHubToken++ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home-one"))+ admin_store = auth.get_github_copilot_storage()+ admin_token = GitHubToken("admin-token", 2_000_000_000_000, "admin")+ admin_store.save(admin_token)+ assert admin_store.load() == admin_token+ assert "data\\system\\user-secrets" in str(admin_store.root).replace("/", "\\")+ user = CurrentUser(+ id="u_alice",+ username="alice",+ role="user",+ scope=UserScope(kind="user", user_id="u_alice", root=tmp_path / "alice"),+ )+ with user_context(user):+ alice_store = auth.get_github_copilot_storage()+ assert alice_store.load() is None+ alice_store.save(GitHubToken("alice-token", 2_000_000_000_000, "alice"))+ assert alice_store.load().access == "alice-token"+ assert admin_store.load() == admin_token+ assert admin_store.credentials_path != alice_store.credentials_path+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home-two"))+ other_home = auth.get_github_copilot_storage()+ assert other_home.credentials_path != admin_store.credentials_path+ assert other_home.load() is None+ if os.name != "nt":+ assert stat.S_IMODE(admin_store.root.stat().st_mode) == 0o700+ assert stat.S_IMODE(admin_store.credentials_path.stat().st_mode) == 0o600+++def test_storage_never_reads_external_tokens_or_sets_environment(tmp_path, monkeypatch):+ from deeptutor.services.github_copilot_storage import GitHubCopilotStorage++ external = ModuleType("oauth_cli_kit.storage")++ def forbidden(**kwargs):+ pytest.fail("External OS-user token storage must not be instantiated")++ external.FileTokenStorage = forbidden+ monkeypatch.setitem(sys.modules, "oauth_cli_kit.storage", external)+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ before = dict(os.environ)+ storage = auth.get_github_copilot_storage()+ assert isinstance(storage, GitHubCopilotStorage)+ assert storage.load() is None+ assert dict(os.environ) == before+++def test_storage_rejects_invalid_credentials_and_unsafe_paths(tmp_path, monkeypatch):+ from deeptutor.services.codex_auth import storage as storage_helpers+ from deeptutor.services.github_copilot_storage import GitHubCopilotStorage++ store = GitHubCopilotStorage(tmp_path)+ store.root.mkdir(parents=True)+ store.credentials_path.write_text('{"access": "invalid"}', encoding="utf-8")+ with pytest.raises(RuntimeError, match="credentials are invalid"):+ store.load()+ monkeypatch.setattr(+ storage_helpers, "_is_reparse_point", lambda path: path == store.root.parent+ )+ with pytest.raises(RuntimeError, match="unsafe path"):+ store.load()+++async def test_model_discovery_preserves_endpoints_and_filters_unusable_rows(monkeypatch):+ rows = [+ {"id": "claude", "supported_endpoints": ["/responses"]},+ {"id": "gpt-5-chat", "supported_endpoints": ["/chat/completions"]},+ {"id": "both", "supported_endpoints": ["/responses", "/chat/completions"]},+ {"id": "legacy"},+ {"id": "empty", "supported_endpoints": []},+ {"id": "other", "supported_endpoints": ["/messages"]},+ {"id": "hidden", "model_picker_enabled": False},+ {"id": "disabled", "policy": {"state": "disabled"}},+ {"id": "bad", "supported_endpoints": "responses"},+ ]++ class ModelsClient(_Client):+ async def get(self, url, **kwargs):+ assert url == "https://tenant.example/models"+ return _Response({"data": rows})++ access = auth.CopilotAccess("short-token", 2_000_000_000, "https://tenant.example")+ monkeypatch.setattr(auth.httpx, "AsyncClient", ModelsClient)+ discovered = await auth.fetch_github_copilot_models(access)+ assert discovered == [+ auth.CopilotModel("claude", ("/responses",)),+ auth.CopilotModel("gpt-5-chat", ("/chat/completions",)),+ auth.CopilotModel("both", ("/responses", "/chat/completions")),+ auth.CopilotModel("legacy", None),+ ]++ async def exchange():+ return access++ monkeypatch.setattr(auth, "exchange_copilot_token", exchange)+ assert await auth.list_github_copilot_models() == [+ f"github-copilot/{row.id}" for row in discovered+ ]+++async def test_exchange_preserves_account_endpoint_and_uses_supplied_owner_token(monkeypatch):+ class ExchangeClient(_Client):+ async def get(self, url, **kwargs):+ assert kwargs["headers"]["Authorization"] == "token owner-github-token"+ return _Response(+ {+ "token": "short-lived-token",+ "expires_at": 2_000_000_000,+ "endpoints": {"api": "https://enterprise.example/copilot"},+ }+ )++ monkeypatch.setattr(auth.httpx, "AsyncClient", ExchangeClient)+ monkeypatch.setattr(auth, "load_github_token", lambda: pytest.fail("must use captured owner"))+ assert await auth.exchange_copilot_token("owner-github-token") == auth.CopilotAccess(+ "short-lived-token", 2_000_000_000, "https://enterprise.example/copilot"+ )