"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(providers): add GitHub Copilot SDK support
SYKuang2dcefe8a527b
diff --git a/README.md b/README.mdindex 3aa58dfde..1d69190de 100644--- a/README.md+++ b/README.md@@ -728,8 +728,9 @@ vibe-trading-mcp # start MCP server (stdio)- **Python 3.11+** for Path B- **Docker** for Path A- OpenAI Codex can also be used with ChatGPT OAuth: set `LANGCHAIN_PROVIDER=openai-codex`, then run `vibe-trading provider login openai-codex`. This does not use `OPENAI_API_KEY`.+- GitHub Copilot can be used with a Copilot subscription instead of an API key: set `LANGCHAIN_PROVIDER=copilot`. The official Copilot SDK resolves `COPILOT_GITHUB_TOKEN`, stored Copilot CLI credentials, or GitHub CLI credentials. Run `copilot` or `gh auth login` if needed.-> **Supported LLM providers:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.+> **Supported LLM providers:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, GitHub Copilot, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.> **Tip:** All markets work without any API keys thanks to automatic fallback. yfinance/Yahoo (HK/US/Canada), OKX (crypto), mootdx (A-shares, TCP-direct, no IP throttle), and AKShare (A-shares, US, HK, futures, forex) are all free. Tushare token is optional — mootdx is the preferred no-token A-share fallback, with AKShare as a broader backup.@@ -842,7 +843,7 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w| `VIBE_TRADING_EXTRA_CORS_ORIGINS` | No | Comma-separated origins **added** to the loopback CORS defaults (`CORS_ORIGINS` replaces them instead) || `CONTENT_FILTER_WARNING_THRESHOLD` | No | Content-filter warning ratio threshold (default 0.05 = 5%). When the ratio of LLM responses blocked by content moderation exceeds this, the run card warns you to switch providers. |-<sub>* Ollama does not require an API key. OpenAI Codex uses ChatGPT OAuth and stores tokens via `oauth-cli-kit`, not in `agent/.env`.</sub>+<sub>* Ollama does not require an API key. OpenAI Codex uses ChatGPT OAuth and stores tokens via `oauth-cli-kit`, not in `agent/.env`. GitHub Copilot authentication is handled by the official SDK.</sub>**Free data (no key needed):** A-shares via AKShare, HK/US/Canada equities via Yahoo/yfinance, crypto via OKX, 100+ crypto exchanges via CCXT. The system automatically selects the best available source for each market.diff --git a/agent/.env.example b/agent/.env.exampleindex e844e6e3c..61975336d 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -37,6 +37,14 @@ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1# LANGCHAIN_MODEL_NAME=openai-codex/gpt-5.4# OPENAI_CODEX_BASE_URL=https://chatgpt.com/backend-api/codex/responses+# --- GitHub Copilot SDK (no API key required) ---+# Requires an active Copilot subscription. The official SDK resolves+# COPILOT_GITHUB_TOKEN, stored Copilot CLI credentials, or `gh` credentials.+# Run `copilot` or `gh auth login` if needed.+# LANGCHAIN_PROVIDER=copilot+# LANGCHAIN_MODEL_NAME=claude-sonnet-5+# COPILOT_GITHUB_TOKEN=gho_xxx+# --- DeepSeek ---# LANGCHAIN_PROVIDER=deepseek# LANGCHAIN_MODEL_NAME=deepseek-v4-prodiff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex fee9a4c3a..f37e9e5c1 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -2903,8 +2903,12 @@ def cmd_upload(file_path: str) -> None:def cmd_provider_login(provider: str) -> int:"""Authenticate OAuth-backed LLM providers."""normalized = provider.strip().lower().replace("_", "-")+ if normalized in {"copilot", "github-copilot"}:+ return _login_copilot()if normalized != "openai-codex":- console.print("[red]Unknown OAuth provider.[/red] Supported: openai-codex")+ console.print(+ "[red]Unknown OAuth provider.[/red] Supported: openai-codex, copilot"+ )return EXIT_USAGE_ERRORtry:from src.providers.openai_codex import login_openai_codex@@ -2937,6 +2941,25 @@ def cmd_provider_login(provider: str) -> int:return EXIT_RUN_FAILED+def _login_copilot() -> int:+ """Report supported GitHub Copilot SDK authentication options."""+ from src.providers.copilot_auth import get_copilot_auth_status++ authenticated, status = get_copilot_auth_status()+ if authenticated:+ console.print(+ f"[green]Already authenticated with GitHub Copilot[/green] [dim]{status}[/dim]"+ )+ return EXIT_SUCCESS++ console.print(+ "[yellow]No GitHub credential found.[/yellow]\n"+ "Run [bold]copilot[/bold] and sign in, run [bold]gh auth login[/bold], "+ "or set [bold]COPILOT_GITHUB_TOKEN[/bold]."+ )+ return EXIT_RUN_FAILED++# ---------------------------------------------------------------------------# Live connector runtime internals.#diff --git a/agent/requirements.txt b/agent/requirements.txtindex 4a3c61b20..2426395ef 100644--- a/agent/requirements.txt+++ b/agent/requirements.txt@@ -13,6 +13,7 @@ python-dotenv>=1.0.0httpx>=0.28.0h2>=4.4.1oauth-cli-kit>=0.1.3+github-copilot-sdk>=1.0.8,<2# Data & Computationpandas>=2.0.0,<3.0.0diff --git a/agent/src/api/settings_routes.py b/agent/src/api/settings_routes.pyindex 7cae5d2c5..2a4be646b 100644--- a/agent/src/api/settings_routes.py+++ b/agent/src/api/settings_routes.py@@ -284,12 +284,12 @@ async def _list_provider_models() -> LLMModelsResponse:"""Best-effort live model discovery with a safe editable fallback."""fallback = [provider.default_model]- if provider.auth_type == "oauth":+ if provider.auth_type in {"oauth", "gh_cli"}:return LLMModelsResponse(provider=provider.name,models=fallback,source="default",- warning_code="oauth_discovery_unsupported",+ warning_code=f"{provider.auth_type}_discovery_unsupported",)if provider.api_key_required and not api_key:return LLMModelsResponse(@@ -353,6 +353,15 @@ def _build_llm_settings_response(token = Noneapi_key_configured = bool(token)api_key_hint = None+ elif provider.auth_type == "gh_cli":+ try:+ from src.providers.copilot_auth import get_copilot_auth_status++ authenticated, auth_status = get_copilot_auth_status()+ except Exception:+ authenticated, auth_status = False, ""+ api_key_configured = authenticated+ api_key_hint = auth_status if authenticated else Nonereturn LLMSettingsResponse(provider=provider.name,model_name=env_values.get("LANGCHAIN_MODEL_NAME", provider.default_model),@@ -409,7 +418,14 @@ def _sync_runtime_env(provider: LLMProviderOption, updates: Dict[str, str]) -> Nelse:os.environ.pop(key, None)- if provider.api_key_env:+ if provider.auth_type == "gh_cli":+ # The Copilot SDK owns credential discovery and transport.+ os.environ.pop("OPENAI_API_KEY", None)+ os.environ.pop("OPENAI_API_BASE", None)+ os.environ.pop("OPENAI_BASE_URL", None)+ reset_env_config()+ return+ elif provider.api_key_env:key_value = os.environ.get(provider.api_key_env, "") # noqa: env-gate — dynamic provider api_key_envif host._is_configured_secret(key_value, LLM_API_KEY_PLACEHOLDERS):os.environ["OPENAI_API_KEY"] = key_valuediff --git a/agent/src/preflight.py b/agent/src/preflight.pyindex f6d17fcac..81631341e 100644--- a/agent/src/preflight.py+++ b/agent/src/preflight.py@@ -100,6 +100,25 @@ def _check_llm_provider() -> CheckResult:impact="",)+ if provider.lower() in {"copilot", "github-copilot"}:+ from src.providers.copilot_auth import get_copilot_auth_status++ authenticated, status_message = get_copilot_auth_status()+ if not authenticated:+ return CheckResult(+ name=f"LLM ({provider})",+ status="not_configured",+ message=f"Copilot SDK: {status_message}",+ impact="run `gh auth login`, `copilot`, or set COPILOT_GITHUB_TOKEN",+ critical=True,+ )+ return CheckResult(+ name=f"LLM ({provider})",+ status="ready",+ message=f"{model} via Copilot SDK ({status_message}) | {diag_hint}",+ impact="",+ )+if not base_url:return CheckResult(name=f"LLM ({provider})",diff --git a/agent/src/providers/capabilities.py b/agent/src/providers/capabilities.pyindex 9ff64ef2f..adb61fa87 100644--- a/agent/src/providers/capabilities.py+++ b/agent/src/providers/capabilities.py@@ -64,6 +64,14 @@ def _package_version() -> str:_VIBE_USER_AGENT = f"Vibe-Trading/{_package_version()}"+@lru_cache(maxsize=1)+def _gh_cli_token() -> str:+ """Return an explicit Copilot token; the SDK handles stored credentials."""+ from src.providers.copilot_auth import resolve_copilot_token++ return resolve_copilot_token()[0]++_MOONSHOT_CAPABILITIES = ProviderCapabilities("moonshot","MOONSHOT_API_KEY",@@ -117,6 +125,13 @@ _OPENAI_CODEX_CAPABILITIES = ProviderCapabilities("openai-codex", None, "OPENAI_CODEX_BASE_URL")+# GitHub Copilot is routed through the official SDK in ``build_llm``.+_COPILOT_CAPABILITIES = ProviderCapabilities(+ "copilot",+ "COPILOT_GITHUB_TOKEN",+ "COPILOT_BASE_URL",+)+_PROVIDERS: dict[str, ProviderCapabilities] = {"openai": ProviderCapabilities("openai", "OPENAI_API_KEY", "OPENAI_BASE_URL"),@@ -189,6 +204,8 @@ _PROVIDERS: dict[str, ProviderCapabilities] = {"MODELSCOPE_BASE_URL",),"ollama": ProviderCapabilities("ollama", None, "OLLAMA_BASE_URL"),+ "copilot": _COPILOT_CAPABILITIES,+ "github-copilot": _COPILOT_CAPABILITIES,"openai-codex": _OPENAI_CODEX_CAPABILITIES,"openai_codex": _OPENAI_CODEX_CAPABILITIES,"opencode-zen": ProviderCapabilities(@@ -332,6 +349,9 @@ def get_llm_credentials(or "ollama")+ if caps.name == "copilot" and not api_key:+ api_key = _gh_cli_token()+base_url = ((os.getenv(base_env, "") # noqa: env-gate — dynamic provider URL chaindiff --git a/agent/src/providers/copilot_auth.py b/agent/src/providers/copilot_auth.pynew file mode 100644index 000000000..414ab364f--- /dev/null+++ b/agent/src/providers/copilot_auth.py@@ -0,0 +1,454 @@+"""GitHub Copilot SDK adapter.++Authentication and transport are delegated to GitHub's supported SDK. The SDK+resolves ``COPILOT_GITHUB_TOKEN``, stored Copilot CLI credentials, and ``gh``+credentials without Vibe-Trading borrowing an OAuth client or editor identity.+"""++from __future__ import annotations++import asyncio+import json+import os+import queue+import shutil+import subprocess+import threading+from collections.abc import Callable, Iterable+from dataclasses import dataclass+from typing import Any, Optional++from langchain_core.messages import AIMessage, AIMessageChunk++COPILOT_TOKEN_ENV = "COPILOT_GITHUB_TOKEN"+_SUPPORTED_TOKEN_PREFIXES = ("gho_", "ghu_", "github_pat_")+++def is_supported_token(token: str) -> bool:+ """Return whether ``token`` is accepted by the Copilot SDK."""+ return bool(token) and token.startswith(_SUPPORTED_TOKEN_PREFIXES)+++def gh_cli_token() -> str:+ """Return a supported token from ``gh auth token``, if available."""+ executable = shutil.which("gh")+ if not executable:+ return ""+ try:+ result = subprocess.run(+ [executable, "auth", "token"],+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return ""+ token = result.stdout.strip()+ return token if result.returncode == 0 and is_supported_token(token) else ""+++def resolve_copilot_token() -> tuple[str, str]:+ """Resolve explicit credentials; the SDK handles stored CLI credentials."""+ for name in (COPILOT_TOKEN_ENV, "GH_TOKEN", "GITHUB_TOKEN"):+ token = os.getenv(name, "").strip() # noqa: env-gate - provider credential+ if is_supported_token(token):+ return token, name+ token = gh_cli_token()+ return (token, "gh auth token") if token else ("", "")+++def get_copilot_login_status() -> Optional[str]:+ """Return an explicit token, or None when the SDK must resolve login."""+ token, _source = resolve_copilot_token()+ return token or None+++def _client_options() -> dict[str, str]:+ """Return explicit SDK options without disabling stored CLI credentials."""+ token, _source = resolve_copilot_token()+ return {"github_token": token} if token else {}+++def get_copilot_auth_status() -> tuple[bool, str]:+ """Return the official SDK's authentication status."""+ result: queue.Queue[Any] = queue.Queue(maxsize=1)++ async def check() -> tuple[bool, str]:+ try:+ from copilot import CopilotClient+ except ImportError:+ return False, "github-copilot-sdk is not installed"++ async with CopilotClient(**_client_options()) as client:+ status = await client.get_auth_status()+ return bool(status.isAuthenticated), str(+ status.statusMessage or status.login or "not authenticated"+ )++ def run() -> None:+ try:+ result.put(asyncio.run(check()))+ except Exception as exc:+ result.put((False, f"{type(exc).__name__}: {exc}"))++ thread = threading.Thread(target=run, daemon=True)+ thread.start()+ thread.join()+ return result.get()+++@dataclass+class _CopilotResult:+ content: str = ""+ model: str | None = None+ tool_calls: list[dict[str, Any]] | None = None+++def _message_value(message: Any, key: str, default: Any = None) -> Any:+ if isinstance(message, dict):+ return message.get(key, default)+ return getattr(message, key, default)+++def _content_text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(+ str(item.get("text", ""))+ for item in content+ if isinstance(item, dict) and item.get("type") == "text"+ )+ return str(content or "")+++def _convert_messages(messages: list[Any]) -> tuple[str, str]:+ """Convert chat history into one SDK turn while preserving role boundaries."""+ system: list[str] = []+ transcript: list[dict[str, Any]] = []+ for message in messages:+ role = str(_message_value(message, "role", "") or "")+ if not role:+ message_type = str(_message_value(message, "type", "") or "")+ role = {+ "human": "user",+ "ai": "assistant",+ "system": "system",+ "tool": "tool",+ }.get(message_type, message_type or "user")+ content = _content_text(_message_value(message, "content", ""))+ if role == "system":+ if content:+ system.append(content)+ continue+ item: dict[str, Any] = {"role": role, "content": content}+ tool_call_id = _message_value(message, "tool_call_id")+ if tool_call_id:+ item["tool_call_id"] = str(tool_call_id)+ tool_calls = _message_value(message, "tool_calls")+ if tool_calls:+ item["tool_calls"] = tool_calls+ transcript.append(item)++ prompt = (+ "Continue the following conversation and produce only the next assistant "+ "response. Preserve tool-call behavior.\n\n"+ + json.dumps(transcript, ensure_ascii=False, default=str)+ )+ return "\n\n".join(system), prompt+++def _convert_tools(tools: list[dict[str, Any]]) -> list[Any]:+ try:+ from copilot.tools import Tool+ except ImportError as exc:+ raise RuntimeError(+ "GitHub Copilot requires github-copilot-sdk. Install project dependencies."+ ) from exc++ converted = []+ for entry in tools:+ function = entry.get("function", entry)+ name = str(function.get("name", "")).strip()+ if not name:+ continue+ parameters = function.get("parameters")+ converted.append(+ Tool(+ name=name,+ description=str(function.get("description", "") or ""),+ parameters=parameters if isinstance(parameters, dict) else {},+ overrides_built_in_tool=True,+ defer="never",+ )+ )+ return converted+++async def _run_copilot(+ *,+ model: str,+ messages: list[Any],+ tools: list[dict[str, Any]],+ timeout: float,+ emit: Callable[[str, str], None] | None = None,+ cancel_event: threading.Event | None = None,+) -> _CopilotResult:+ try:+ from copilot import CopilotClient, ToolSet+ from copilot.session_events import (+ AssistantMessageData,+ AssistantMessageDeltaData,+ AssistantReasoningDeltaData,+ ExternalToolRequestedData,+ SessionErrorData,+ SessionIdleData,+ )+ except ImportError as exc:+ raise RuntimeError(+ "GitHub Copilot requires github-copilot-sdk. Install project dependencies."+ ) from exc++ system_message, prompt = _convert_messages(messages)+ result = _CopilotResult(tool_calls=[])+ finished = asyncio.Event()+ tool_requested = asyncio.Event()+ error: list[Exception] = []++ def add_tool_call(tool_call_id: str, name: str, arguments: Any) -> None:+ assert result.tool_calls is not None+ if any(item["id"] == tool_call_id for item in result.tool_calls):+ return+ if isinstance(arguments, str):+ try:+ arguments = json.loads(arguments)+ except json.JSONDecodeError:+ arguments = {}+ result.tool_calls.append(+ {+ "id": tool_call_id,+ "name": name,+ "args": arguments if isinstance(arguments, dict) else {},+ "type": "tool_call",+ }+ )++ def on_event(event: Any) -> None:+ data = event.data+ if isinstance(data, AssistantMessageDeltaData):+ if emit and data.delta_content:+ emit("text", data.delta_content)+ elif isinstance(data, AssistantReasoningDeltaData):+ if emit and data.delta_content:+ emit("reasoning", data.delta_content)+ elif isinstance(data, AssistantMessageData):+ result.content = data.content or result.content+ result.model = data.model or result.model+ for request in data.tool_requests or []:+ add_tool_call(request.tool_call_id, request.name, request.arguments)+ if data.tool_requests:+ tool_requested.set()+ elif isinstance(data, ExternalToolRequestedData):+ add_tool_call(data.tool_call_id, data.tool_name, data.arguments)+ tool_requested.set()+ elif isinstance(data, SessionErrorData):+ error.append(RuntimeError(f"GitHub Copilot SDK error: {data.message}"))+ finished.set()+ elif isinstance(data, SessionIdleData):+ finished.set()++ # ponytail: one runtime per call keeps lifecycle simple; pool it if startup+ # latency becomes material in profiling.+ async with CopilotClient(**_client_options()) as client:+ sdk_tools = _convert_tools(tools)+ available_tools = ToolSet()+ for tool in sdk_tools:+ available_tools.add_custom(tool.name)+ session_options: dict[str, Any] = {+ "model": model,+ "tools": sdk_tools,+ "available_tools": available_tools,+ "streaming": emit is not None,+ "enable_config_discovery": False,+ "enable_session_store": False,+ "enable_skills": False,+ "skip_custom_instructions": True,+ "on_event": on_event,+ }+ if system_message:+ session_options["system_message"] = {+ "mode": "append",+ "content": system_message,+ }+ async with await client.create_session(**session_options) as session:+ await session.send(prompt)+ finish_task = asyncio.create_task(finished.wait())+ tool_task = asyncio.create_task(tool_requested.wait())++ async def watch_cancel() -> None:+ if cancel_event is None:+ return+ while not cancel_event.is_set():+ await asyncio.sleep(0.05)+ await session.abort()+ finished.set()++ cancel_task = asyncio.create_task(watch_cancel())+ try:+ done, _pending = await asyncio.wait_for(+ asyncio.wait(+ {finish_task, tool_task},+ return_when=asyncio.FIRST_COMPLETED,+ ),+ timeout=timeout,+ )+ if tool_task in done:+ # ponytail: 100 ms debounce collects parallel tool events;+ # replace it if the SDK exposes an explicit batch-complete event.+ await asyncio.sleep(0.1)+ finally:+ for task in (finish_task, tool_task, cancel_task):+ task.cancel()+ await asyncio.gather(+ finish_task,+ tool_task,+ cancel_task,+ return_exceptions=True,+ )+ if result.tool_calls and not (cancel_event and cancel_event.is_set()):+ await session.abort()++ if error:+ raise error[0]+ return result+++class CopilotSDKLLM:+ """Minimal LangChain-compatible wrapper around the official Copilot SDK."""++ def __init__(+ self,+ *,+ model: str,+ timeout: int = 120,+ tools: list[dict[str, Any]] | None = None,+ ) -> None:+ self.model = model+ self.timeout = timeout+ self.tools = tools or []++ def bind_tools(self, tools: list[dict[str, Any]]) -> "CopilotSDKLLM":+ return CopilotSDKLLM(model=self.model, timeout=self.timeout, tools=tools)++ def invoke(+ self,+ messages: list[Any],+ config: Optional[dict[str, Any]] = None,+ ) -> AIMessage:+ timeout = float((config or {}).get("timeout") or self.timeout)+ result = asyncio.run(+ _run_copilot(+ model=self.model,+ messages=messages,+ tools=self.tools,+ timeout=timeout,+ )+ )+ return AIMessage(+ content=result.content,+ tool_calls=result.tool_calls or [],+ response_metadata={+ "finish_reason": "tool_calls" if result.tool_calls else "stop",+ "model_name": result.model or self.model,+ },+ )++ def stream(+ self,+ messages: list[Any],+ config: Optional[dict[str, Any]] = None,+ ) -> Iterable[AIMessageChunk]:+ timeout = float((config or {}).get("timeout") or self.timeout)+ chunks: queue.Queue[Any] = queue.Queue()+ sentinel = object()+ cancel_event = threading.Event()++ def run() -> None:+ emitted_text = False++ def emit(kind: str, value: str) -> None:+ nonlocal emitted_text+ emitted_text = emitted_text or kind == "text"+ chunks.put(+ AIMessageChunk(+ content=value if kind == "text" else "",+ additional_kwargs=(+ {"reasoning_content": value} if kind == "reasoning" else {}+ ),+ )+ )++ try:+ result = asyncio.run(+ _run_copilot(+ model=self.model,+ messages=messages,+ tools=self.tools,+ timeout=timeout,+ emit=emit,+ cancel_event=cancel_event,+ )+ )+ if result.content and not emitted_text:+ chunks.put(AIMessageChunk(content=result.content))+ if result.tool_calls:+ chunks.put(+ AIMessageChunk(+ content="",+ tool_call_chunks=[+ {+ "id": call["id"],+ "name": call["name"],+ "args": json.dumps(call["args"]),+ "index": index,+ "type": "tool_call_chunk",+ }+ for index, call in enumerate(result.tool_calls)+ ],+ response_metadata={"finish_reason": "tool_calls"},+ )+ )+ else:+ chunks.put(+ AIMessageChunk(+ content="",+ response_metadata={+ "finish_reason": "stop",+ "model_name": result.model or self.model,+ },+ )+ )+ except Exception as exc:+ chunks.put(exc)+ finally:+ chunks.put(sentinel)++ threading.Thread(target=run, daemon=True).start()+ try:+ while True:+ chunk = chunks.get()+ if chunk is sentinel:+ return+ if isinstance(chunk, Exception):+ raise chunk+ yield chunk+ finally:+ cancel_event.set()++ async def ainvoke(+ self,+ messages: list[Any],+ config: Optional[dict[str, Any]] = None,+ ) -> AIMessage:+ return await asyncio.to_thread(self.invoke, messages, config)diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 425cb4bb3..9f03f7525 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -1016,6 +1016,12 @@ def _sync_provider_env() -> None:os.environ.pop("OPENAI_API_KEY", None)return+ if provider in {"copilot", "github-copilot"}:+ os.environ.pop("OPENAI_API_BASE", None)+ os.environ.pop("OPENAI_BASE_URL", None)+ os.environ.pop("OPENAI_API_KEY", None)+ return+creds = get_llm_credentials(provider, get_env_config().llm.langchain_model_name)api_key = creds["api_key"]base_url = creds["base_url"]@@ -1216,6 +1222,14 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Anyreasoning_effort=effort or None,)+ if provider in {"copilot", "github-copilot"}:+ from src.providers.copilot_auth import CopilotSDKLLM++ return CopilotSDKLLM(+ model=name,+ timeout=get_env_config().llm.timeout_seconds,+ )+if provider == "anthropic":return _build_anthropic(model=name,diff --git a/agent/src/providers/llm_providers.json b/agent/src/providers/llm_providers.jsonindex 5ee629ef7..eba8a35c6 100644--- a/agent/src/providers/llm_providers.json+++ b/agent/src/providers/llm_providers.json@@ -211,5 +211,16 @@"default_model": "qwen2.5:32b","default_base_url": "http://localhost:11434","api_key_required": false+ },+ {+ "name": "copilot",+ "label": "GitHub Copilot SDK",+ "api_key_env": "COPILOT_GITHUB_TOKEN",+ "base_url_env": "COPILOT_BASE_URL",+ "default_model": "claude-sonnet-5",+ "default_base_url": "https://api.githubcopilot.com",+ "api_key_required": false,+ "auth_type": "gh_cli",+ "login_command": "gh auth login"}]diff --git a/agent/tests/test_copilot_provider.py b/agent/tests/test_copilot_provider.pynew file mode 100644index 000000000..a02afd2a7--- /dev/null+++ b/agent/tests/test_copilot_provider.py@@ -0,0 +1,250 @@+"""Coverage for the official GitHub Copilot SDK provider."""++from __future__ import annotations++import json+import threading+from pathlib import Path++import pytest++import api_server # noqa: F401+from src.api import settings_routes+from src.providers import capabilities as caps_mod+from src.providers import copilot_auth+from src.providers.capabilities import (+ get_llm_credentials,+ get_provider_capabilities,+)++[email protected](autouse=True)+def _clear_token_cache():+ caps_mod._gh_cli_token.cache_clear()+ yield+ caps_mod._gh_cli_token.cache_clear()+++def no_ambient_credentials(monkeypatch):+ for name in (+ copilot_auth.COPILOT_TOKEN_ENV,+ "GH_TOKEN",+ "GITHUB_TOKEN",+ "OPENAI_API_KEY",+ "COPILOT_BASE_URL",+ "OPENAI_BASE_URL",+ "OPENAI_API_BASE",+ ):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(copilot_auth, "gh_cli_token", lambda: "")+++def _copilot_entry() -> dict:+ providers_path = (+ Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json"+ )+ entries = {+ item["name"]: item+ for item in json.loads(providers_path.read_text(encoding="utf-8"))+ }+ return entries["copilot"]+++def test_copilot_is_registered_as_sdk_provider() -> None:+ entry = _copilot_entry()++ assert entry["label"] == "GitHub Copilot SDK"+ assert entry["default_base_url"] == "https://api.githubcopilot.com"+ assert entry["api_key_required"] is False+++def test_copilot_has_no_editor_impersonation_headers() -> None:+ caps = get_provider_capabilities("copilot", "claude-sonnet-5")++ assert caps.name == "copilot"+ assert caps.default_headers == {}+++def test_copilot_alias_resolves_to_same_capabilities() -> None:+ assert (+ get_provider_capabilities("github-copilot", "claude-sonnet-5").name+ == get_provider_capabilities("copilot", "claude-sonnet-5").name+ == "copilot"+ )+++def test_token_type_validation_rejects_classic_pat() -> None:+ assert copilot_auth.is_supported_token("gho_abc")+ assert copilot_auth.is_supported_token("ghu_abc")+ assert copilot_auth.is_supported_token("github_pat_abc")+ assert not copilot_auth.is_supported_token("ghp_classic")+ assert not copilot_auth.is_supported_token("")+++def test_resolution_prefers_copilot_then_gh_environment(monkeypatch) -> None:+ monkeypatch.setenv("GITHUB_TOKEN", "ghu_actions")+ monkeypatch.setenv("GH_TOKEN", "gho_gh")+ monkeypatch.setenv(copilot_auth.COPILOT_TOKEN_ENV, "gho_copilot")++ assert copilot_auth.resolve_copilot_token() == (+ "gho_copilot",+ copilot_auth.COPILOT_TOKEN_ENV,+ )++ monkeypatch.delenv(copilot_auth.COPILOT_TOKEN_ENV)+ assert copilot_auth.resolve_copilot_token() == ("gho_gh", "GH_TOKEN")+++def test_resolution_falls_back_to_gh_cli(no_ambient_credentials, monkeypatch) -> None:+ monkeypatch.setattr(copilot_auth, "gh_cli_token", lambda: "gho_cli")++ assert copilot_auth.resolve_copilot_token() == ("gho_cli", "gh auth token")+++def test_no_credential_is_left_for_sdk_resolution(no_ambient_credentials) -> None:+ assert copilot_auth.resolve_copilot_token() == ("", "")+++def test_sdk_client_options_keep_stored_cli_credentials_enabled(+ no_ambient_credentials, monkeypatch+) -> None:+ assert copilot_auth._client_options() == {}++ monkeypatch.setenv(copilot_auth.COPILOT_TOKEN_ENV, "gho_explicit")+ assert copilot_auth._client_options() == {"github_token": "gho_explicit"}+++def test_credentials_do_not_require_openai_base_url(+ no_ambient_credentials, monkeypatch+) -> None:+ monkeypatch.setenv(copilot_auth.COPILOT_TOKEN_ENV, "gho_explicit")++ creds = get_llm_credentials("copilot", "claude-sonnet-5")++ assert creds["api_key"] == "gho_explicit"+ assert creds["base_url"] == "https://api.githubcopilot.com"+++def test_sdk_adapter_maps_tool_calls(monkeypatch) -> None:+ async def fake_run(**_kwargs):+ return copilot_auth._CopilotResult(+ model="claude-sonnet-5",+ tool_calls=[+ {+ "id": "call_1",+ "name": "quote",+ "args": {"symbol": "AAPL"},+ "type": "tool_call",+ }+ ],+ )++ monkeypatch.setattr(copilot_auth, "_run_copilot", fake_run)++ message = copilot_auth.CopilotSDKLLM(model="claude-sonnet-5").bind_tools(+ [+ {+ "type": "function",+ "function": {+ "name": "quote",+ "description": "Get a quote",+ "parameters": {"type": "object"},+ },+ }+ ]+ ).invoke([{"role": "user", "content": "Price?"}])++ assert message.tool_calls == [+ {+ "name": "quote",+ "args": {"symbol": "AAPL"},+ "id": "call_1",+ "type": "tool_call",+ }+ ]+ assert message.response_metadata["finish_reason"] == "tool_calls"+++def test_sdk_adapter_streams_text(monkeypatch) -> None:+ async def fake_run(*, emit, **_kwargs):+ emit("text", "hello ")+ emit("text", "world")+ return copilot_auth._CopilotResult(content="hello world")++ monkeypatch.setattr(copilot_auth, "_run_copilot", fake_run)++ chunks = list(+ copilot_auth.CopilotSDKLLM(model="claude-sonnet-5").stream(+ [{"role": "user", "content": "Hello"}]+ )+ )++ assert "".join(chunk.content for chunk in chunks) == "hello world"+ assert chunks[-1].response_metadata["finish_reason"] == "stop"+++def test_sdk_stream_close_cancels_background_session(monkeypatch) -> None:+ cancelled = threading.Event()++ async def fake_run(*, emit, cancel_event, **_kwargs):+ emit("text", "hello")+ while not cancel_event.is_set():+ await copilot_auth.asyncio.sleep(0.01)+ cancelled.set()+ return copilot_auth._CopilotResult(content="hello")++ monkeypatch.setattr(copilot_auth, "_run_copilot", fake_run)+ stream = copilot_auth.CopilotSDKLLM(model="claude-sonnet-5").stream(+ [{"role": "user", "content": "Hello"}]+ )++ assert next(stream).content == "hello"+ stream.close()++ assert cancelled.wait(1)+++def test_message_conversion_keeps_system_and_tool_history() -> None:+ system, prompt = copilot_auth._convert_messages(+ [+ {"role": "system", "content": "Be concise."},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "call_1"}]},+ {"role": "tool", "tool_call_id": "call_1", "content": "123"},+ ]+ )++ assert system == "Be concise."+ assert '"tool_call_id": "call_1"' in prompt+ assert '"role": "tool"' in prompt+++def test_settings_report_explicit_copilot_credential(monkeypatch) -> None:+ monkeypatch.setattr(+ copilot_auth,+ "get_copilot_auth_status",+ lambda: (True, "authenticated via GH_TOKEN"),+ )++ response = settings_routes._build_llm_settings_response(+ {"LANGCHAIN_PROVIDER": "copilot"}+ )++ assert response.api_key_configured is True+ assert response.api_key_hint == "authenticated via GH_TOKEN"+++def test_settings_allow_sdk_managed_credentials(monkeypatch) -> None:+ monkeypatch.setattr(+ copilot_auth,+ "get_copilot_auth_status",+ lambda: (True, "authenticated via Copilot CLI"),+ )++ response = settings_routes._build_llm_settings_response(+ {"LANGCHAIN_PROVIDER": "copilot"}+ )++ assert response.api_key_required is False+ assert response.api_key_configured is True+ assert response.api_key_hint == "authenticated via Copilot CLI"diff --git a/agent/tests/test_preflight.py b/agent/tests/test_preflight.pyindex 54e237929..734f2320c 100644--- a/agent/tests/test_preflight.py+++ b/agent/tests/test_preflight.py@@ -75,6 +75,43 @@ def test_llm_preflight_probe_reports_request_errors(monkeypatch) -> None:assert "Timeout: timed out" in result.message+def test_copilot_preflight_uses_sdk_auth_instead_of_openai_base_url(+ monkeypatch,+) -> None:+ """Copilot has no OpenAI base URL because the official SDK owns transport."""+ import src.providers.copilot_auth as copilot_auth+ import src.providers.llm as llm++ monkeypatch.setenv("LANGCHAIN_PROVIDER", "copilot")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "claude-sonnet-5")+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)+ monkeypatch.setattr(llm, "_ensure_dotenv", lambda: None)+ monkeypatch.setattr(llm, "_sync_provider_env", lambda: None)+ monkeypatch.setattr(+ llm,+ "provider_diagnostics",+ lambda: {+ "base_url": "https://api.githubcopilot.com",+ "timeout_seconds": 120,+ "max_retries": 2,+ "proxy": {},+ },+ )+ monkeypatch.setattr(+ copilot_auth,+ "get_copilot_auth_status",+ lambda: (True, "sykuang (via gh)"),+ raising=False,+ )++ result = preflight._check_llm_provider()++ assert result.status == "ready"+ assert result.critical is False+ assert "sykuang (via gh)" in result.message++def test_akshare_check_uses_spec_without_import(monkeypatch) -> None:"""AKShare's package import is heavy; preflight should only check discovery."""monkeypatch.delitem(sys.modules, "akshare", raising=False)diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex fc848e30e..bf4bd5a23 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -399,6 +399,7 @@"configured": "تم التكوين","keepCurrentKey": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي","providerUsesOauth": "يستخدم هذا المزوّد OAuth. شغّل: {{command}}",+ "providerUsesManagedAuth": "يدير هذا المزوّد المصادقة. شغّل: {{command}}","noApiKeyRequired": "لا يتطلب هذا المزوّد مفتاح API.","keepCurrentToken": "اتركه فارغًا للاحتفاظ بالرمز الحالي","iwencaiApiKey": "مفتاح API لـ iWenCai",@@ -415,6 +416,7 @@"unknownError": "خطأ غير معروف","providerChangeHint": "يؤدي تغيير المزوّد إلى تحديث النموذج ونقطة النهاية الموصى بهما.","oauth": "OAuth",+ "authentication": "المصادقة","apiKey": "مفتاح API","tushareTokenDesc": "يُستخدم لبيانات الأسهم الصينية (فئة A) والعقود الآجلة والصناديق والاقتصاد الكلي. إذا لم يُضبط، يتراجع المشروع إلى AKShare حيثما توفر."},diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 50cd27427..f41d1ab46 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -404,6 +404,7 @@"configured": "Configured","keepCurrentKey": "Leave blank to keep the current key","providerUsesOauth": "This provider uses OAuth. Run: {{command}}",+ "providerUsesManagedAuth": "This provider manages authentication. Run: {{command}}","noApiKeyRequired": "This provider does not require an API key.","keepCurrentToken": "Leave blank to keep the current token","iwencaiApiKey": "iWenCai API Key",@@ -420,6 +421,7 @@"unknownError": "Unknown error","providerChangeHint": "Changing providers updates the recommended model and endpoint.","oauth": "OAuth",+ "authentication": "Authentication","apiKey": "API key","tushareTokenDesc": "Used for China A-share, futures, fund, and macro data. If unset, the project falls back to AKShare where available."},diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 410a3415a..c681ac6ce 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -399,6 +399,7 @@"configured": "設定済み","keepCurrentKey": "空欄で現在のキーを保持","providerUsesOauth": "このプロバイダーは OAuth を使用します。実行: {{command}}",+ "providerUsesManagedAuth": "このプロバイダーが認証を管理します。実行: {{command}}","noApiKeyRequired": "このプロバイダーは API キーを必要としません。","keepCurrentToken": "空欄で現在のトークンを保持","iwencaiApiKey": "iWenCai API キー",@@ -415,6 +416,7 @@"unknownError": "不明なエラー","providerChangeHint": "プロバイダーを変更すると、推奨モデルとエンドポイントが更新されます。","oauth": "OAuth",+ "authentication": "認証","apiKey": "APIキー","tushareTokenDesc": "中国A株・先物・ファンド・マクロデータに使用します。未設定の場合、利用可能なところではAKShareにフォールバックします。"},diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex a5c7ae860..dd3b6d288 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -399,6 +399,7 @@"configured": "구성됨","keepCurrentKey": "비우면 현재 키 유지","providerUsesOauth": "이 프로바이더는 OAuth를 사용합니다. 실행: {{command}}",+ "providerUsesManagedAuth": "이 프로바이더가 인증을 관리합니다. 실행: {{command}}","noApiKeyRequired": "이 프로바이더는 API 키가 필요하지 않습니다.","keepCurrentToken": "비우면 현재 토큰 유지","iwencaiApiKey": "iWenCai API 키",@@ -415,6 +416,7 @@"unknownError": "알 수 없는 오류","providerChangeHint": "제공자를 변경하면 권장 모델과 엔드포인트가 업데이트됩니다.","oauth": "OAuth",+ "authentication": "인증","apiKey": "API 키","tushareTokenDesc": "중국 A주·선물·펀드·거시 데이터에 사용됩니다. 설정하지 않으면 가능한 경우 AKShare로 대체됩니다."},diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex a0cb3d13e..454800948 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -399,6 +399,7 @@"configured": "已配置","keepCurrentKey": "留空以保留当前密钥","providerUsesOauth": "该提供商使用 OAuth。请运行: {{command}}",+ "providerUsesManagedAuth": "该提供商自行管理身份验证。请运行: {{command}}","noApiKeyRequired": "此提供商不需要 API 密钥。","keepCurrentToken": "留空以保留当前 Token","iwencaiApiKey": "iWenCai API 密钥",@@ -415,6 +416,7 @@"unknownError": "未知错误","providerChangeHint": "切换服务商后,推荐的模型和接口地址会自动更新。","oauth": "OAuth",+ "authentication": "身份验证","apiKey": "API 密钥","tushareTokenDesc": "用于中国 A 股、期货、基金和宏观数据。没填的话会自动改用 AKShare 的免费数据。"},diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex 7775e2bc0..6fcbce8e0 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -345,12 +345,15 @@ export function Settings() {);}+ const usesManagedAuth = Boolean(+ selectedProvider?.auth_type && selectedProvider.auth_type !== "api_key",+ );const keyStatus = settings.api_key_configured? t("settings.configured"): settings.api_key_required? t("settings.keepCurrentKey")- : selectedProvider?.auth_type === "oauth" && selectedProvider.login_command- ? t("settings.providerUsesOauth", { command: selectedProvider.login_command })+ : usesManagedAuth && selectedProvider?.login_command+ ? t("settings.providerUsesManagedAuth", { command: selectedProvider.login_command }): t("settings.noApiKeyRequired");const apiKeyDisabled = !selectedProvider?.api_key_required || clearApiKey;const tushareStatus = dataSettings.tushare_token_configured@@ -561,7 +564,7 @@ export function Settings() {className={fieldClass}placeholder={selectedProvider?.default_base_url}list={selectedProvider?.base_url_options?.length ? "llm-base-url-options" : undefined}- disabled={selectedProvider?.auth_type === "oauth"}+ disabled={usesManagedAuth}/>{selectedProvider?.base_url_options?.length ? (<datalist id="llm-base-url-options">@@ -574,8 +577,8 @@ export function Settings() {<label className="grid gap-2"><span className={labelClass}>- {selectedProvider?.auth_type === "oauth"- ? t("settings.oauth", { defaultValue: "OAuth" })+ {usesManagedAuth+ ? t("settings.authentication", { defaultValue: "Authentication" }): t("settings.apiKey", { defaultValue: "API key" })}</span><div className="relative">diff --git a/frontend/src/pages/__tests__/SettingsChannels.test.tsx b/frontend/src/pages/__tests__/SettingsChannels.test.tsxindex ba63b1672..eb9bfa7eb 100644--- a/frontend/src/pages/__tests__/SettingsChannels.test.tsx+++ b/frontend/src/pages/__tests__/SettingsChannels.test.tsx@@ -150,6 +150,40 @@ describe("Settings IM channels panel", () => {expect(screen.getByRole("button", { name: "Start channels" })).toBeDisabled();});+ it("renders SDK-managed provider authentication without editable transport fields", async () => {+ apiMock.getLLMSettings.mockResolvedValue({+ ...llmSettings(),+ provider: "copilot",+ model_name: "claude-sonnet-5",+ base_url: "https://api.githubcopilot.com",+ api_key_env: "COPILOT_GITHUB_TOKEN",+ api_key_required: false,+ providers: [+ {+ name: "copilot",+ label: "GitHub Copilot SDK",+ api_key_env: "COPILOT_GITHUB_TOKEN",+ base_url_env: "COPILOT_BASE_URL",+ default_model: "claude-sonnet-5",+ default_base_url: "https://api.githubcopilot.com",+ api_key_required: false,+ auth_type: "gh_cli",+ login_command: "gh auth login",+ },+ ],+ });++ render(<Settings />);++ expect(+ await screen.findByDisplayValue("https://api.githubcopilot.com"),+ ).toBeDisabled();+ const authStatus = screen.getByText(+ "This provider manages authentication. Run: gh auth login",+ );+ expect(authStatus.closest("label")?.querySelector("input")).toBeDisabled();+ });+it("translates stable model-discovery warning codes in the frontend", async () => {render(<Settings />);await screen.findByText("LLM Settings");diff --git a/pyproject.toml b/pyproject.tomlindex 09ca0a643..844a1feb0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,6 +34,7 @@ dependencies = ["h2>=4.4.1","defusedxml>=0.7.1","oauth-cli-kit>=0.1.3",+ "github-copilot-sdk>=1.0.8,<2","pandas>=2.0.0,<3.0.0","openpyxl>=3.1.0","python-docx>=1.1.0",diff --git a/requirements-lock.txt b/requirements-lock.txtindex ab9340631..77f5019eb 100644--- a/requirements-lock.txt+++ b/requirements-lock.txt@@ -1144,6 +1144,9 @@ frozenlist==1.8.0 \# aiohttp# aiosignal# ccxt+github-copilot-sdk==1.0.8 \+ --hash=sha256:7c3d868b73daa3a154ae6c1c5a2bd9301c47349c6b080f1ed77ba9027da3e0fa+ # via -r agent/requirements.txtgriffelib==2.1.0 \--hash=sha256:762a186d2c6fd6794d4ea20d428d597ffb857cb56b66421651cbba15bdd5e813 \--hash=sha256:cc7b3d2d2865ad0b909fcc38086e3f554b5ea7acbaa7bbb7ecaa3f5dfb7d9f00@@ -1231,6 +1234,7 @@ httpx[brotli,http2,socks]==0.28.1 \# -r agent/requirements.txt# ddgs# fastmcp-slim+ # github-copilot-sdk# langgraph-sdk# langsmith# mcp@@ -2720,6 +2724,7 @@ pydantic[email]==2.13.4 \# -r agent/requirements.txt# fastapi# fastmcp-slim+ # github-copilot-sdk# langchain# langchain-core# langgraph@@ -2910,6 +2915,7 @@ python-dateutil==2.9.0.post0 \--hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \--hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427# via+ # github-copilot-sdk# matplotlib# pandaspython-docx==1.2.0 \