"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(providers): add claude-cli provider backed by local `claude -p` (#1804)
alexwan949d49f2318c
diff --git a/README.md b/README.mdindex 518bef9ee..f16c0f1e7 100644--- a/README.md+++ b/README.md@@ -1023,8 +1023,9 @@ vibe-trading-mcp # start MCP server (stdio)- **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 an active Copilot subscription instead of a separately billed LLM API key. See [GitHub Copilot SDK provider](#github-copilot-sdk-provider).+- A local Claude Code login can drive the agent without an API key. See [Claude Code CLI provider](#claude-code-cli-provider).-> **Supported LLM providers:** OpenRouter, OpenAI, Anthropic (native Messages API), DeepSeek, OpenCode (Go / Zen), Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, Novita AI, 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.+> **Supported LLM providers:** OpenRouter, OpenAI, Anthropic (native Messages API), DeepSeek, OpenCode (Go / Zen), Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, Novita AI, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, GitHub Copilot, Claude Code CLI, 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/UK), OKX (crypto), and AKShare (A-shares, US, HK, futures, forex) are all free. LSE `.L` quotes must declare GBP or GBp so pence can be normalized before GBP accounting. Tushare token is optional; tencent, baostock and AKShare are the no-token A-share fallbacks.@@ -1054,6 +1055,35 @@ vibe-tradingAuthentication priority is `COPILOT_GITHUB_TOKEN`, `GH_TOKEN`, `GITHUB_TOKEN`, stored Copilot CLI credentials, then `gh` credentials. Vibe-Trading does not copy or persist SDK credentials. Host keychain credentials are not automatically available inside Docker, so containers should receive `COPILOT_GITHUB_TOKEN`.+### Claude Code CLI provider++The `claude-cli` provider uses the [Claude Code](https://claude.com/claude-code) CLI you already have installed and logged in. Each agent step runs one headless `claude -p` process that only chooses the next step — call these tools, or give the final answer. Vibe-Trading runs the tools itself, so the evidence ledger, grounding checks and swarm deliverable checks behave exactly as with an API provider. It does not read `ANTHROPIC_API_KEY`.++Log in once with Claude Code, then check that Vibe-Trading can see the login:++```bash+claude auth login+vibe-trading provider login claude-cli # reports the login; it does not start a new one+```++Then configure `agent/.env`:++```dotenv+LANGCHAIN_PROVIDER=claude-cli+LANGCHAIN_MODEL_NAME=claude-opus-5-5+# LANGCHAIN_REASONING_EFFORT=high # low|medium|high|xhigh|max; passed as --effort+# CLAUDE_CLI_PATH=/opt/homebrew/bin/claude # when `claude` is not on PATH or in ~/.local/bin+# CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # default; set empty to offer every tool+# CLAUDE_CLI_BASH_POLICY=python-only # or `off`+```++- `CLAUDE_CLI_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from the model. The default hides every `trading_*` and `etoro_*` tool, read-only ones included, so the agent cannot quote or list positions through a broker connector under this provider until you change it.+- `CLAUDE_CLI_BASH_POLICY=python-only` lets the `bash` tool run only `python <relative script>.py`, `python -c ...`, and read-only `ls`/`cat`/`head`/`tail`/`wc`/`pwd` on non-hidden relative paths (so not `.env`); refused calls are returned to the model so it can choose again. Any other value stops the provider from starting.++> **Warning:** Both settings are convenience filters, not a security boundary. `python -c` can still run arbitrary code, and external MCP tools (`mcp_<server>_<tool>`) are not covered by the default prefixes. Live orders stay bound by the mandate gate and kill switch whatever these settings allow.++> **Note:** When Settings shows this provider, it loads the models your Claude Code login can run (cached for 5 minutes; **Load models** refreshes), and the reasoning effort menu offers only the levels the selected model accepts. The chosen level is passed to each `claude -p` call as `--effort`; it does not read or change `~/.claude/settings.json`, and "Provider default" means the model's own default. Base URL, temperature and `MAX_RETRIES` have no effect with this provider, and `TIMEOUT_SECONDS` is raised to at least 600 seconds per decision. Image input is not supported. The CLI returns each decision in one piece, so a decision longer than `VIBE_TRADING_SSE_TIMEOUT` (default 90 seconds) makes the Web UI report a timeout while the run continues; raise that value if you use high effort levels.+### Path A: Docker (zero setup)```bash@@ -1151,12 +1181,15 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w|----------|:--------:|-------------|| `LANGCHAIN_PROVIDER` | Yes | Provider name (`openrouter`, `deepseek`, `groq`, `ollama`, etc.) || `<PROVIDER>_API_KEY` | Yes* | API key (`OPENROUTER_API_KEY`, `DEEPSEEK_API_KEY`, etc.) |-| `<PROVIDER>_BASE_URL` | Yes | API endpoint URL |+| `<PROVIDER>_BASE_URL` | Yes* | API endpoint URL || `LANGCHAIN_MODEL_NAME` | Yes | Model name (e.g. `deepseek-v4-pro`) |-| `LANGCHAIN_REASONING_EFFORT` | No | Reasoning effort (`none`, `low`, `medium`, `high`, or `max`) |+| `LANGCHAIN_REASONING_EFFORT` | No | Reasoning effort (`none`, `low`, `medium`, `high`, or `max`; `claude-cli` takes `low` through `max` plus `xhigh`, and no `none`) || `LANGCHAIN_USE_RESPONSES_API` | No | Responses transport override: literal `true` uses `/v1/responses` when the endpoint supports it; native adapters retain their own transport; all other values use Chat Completions || `TUSHARE_TOKEN` | No | Tushare Pro token for A-share data (falls back to AKShare) || `TIMEOUT_SECONDS` | No | LLM call timeout, default 120s |+| `CLAUDE_CLI_PATH` | No | `claude` executable for the `claude-cli` provider when it is not on PATH or in `~/.local/bin` |+| `CLAUDE_CLI_DENY_TOOL_PREFIXES` | No | Tool-name prefixes hidden from the `claude-cli` model (default `trading_,etoro_`; empty offers every tool) |+| `CLAUDE_CLI_BASH_POLICY` | No | `python-only` (default) or `off` for the `claude-cli` provider's `bash` tool || `API_AUTH_KEY` | Recommended for network deployments | Bearer token required when the API is reachable from non-local clients || `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | Explicit opt-in for shell-capable tools in remote API/MCP-SSE style deployments || `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | Extra comma-separated roots for document and broker-journal imports |@@ -1166,7 +1199,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`. GitHub Copilot authentication is handled by the official SDK.</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. Claude Code CLI uses the local `claude` login and needs no API key or base URL.</sub>**Free data (no key needed):** A-shares via AKShare, HK/US/Canada/UK 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 1446fcfcd..7cf80535b 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -41,6 +41,17 @@ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1# LANGCHAIN_MODEL_NAME=claude-sonnet-5# COPILOT_GITHUB_TOKEN=gho_xxx+# --- Claude Code CLI (local `claude -p`; no API key) ---+# Log in with `claude auth login`; check with `vibe-trading provider login claude-cli`.+# The deny list and bash policy are convenience filters, not a security boundary;+# live orders are still bound by the mandate gate.+# LANGCHAIN_PROVIDER=claude-cli+# LANGCHAIN_MODEL_NAME=claude-opus-5-5+# LANGCHAIN_REASONING_EFFORT=high # low|medium|high|xhigh|max; passed as --effort+# CLAUDE_CLI_PATH= # executable when `claude` is not on PATH+# CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # empty offers every tool to the model+# CLAUDE_CLI_BASH_POLICY=python-only # or off+# --- DeepSeek ---# LANGCHAIN_PROVIDER=deepseek# LANGCHAIN_MODEL_NAME=deepseek-v4-prodiff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex dbf04227c..59c75b72f 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -3008,9 +3008,11 @@ def cmd_provider_login(provider: str) -> int:normalized = provider.strip().lower().replace("_", "-")if normalized in {"copilot", "github-copilot"}:return _login_copilot()+ if normalized == "claude-cli":+ return _login_claude_cli()if normalized != "openai-codex":console.print(- "[red]Unknown OAuth provider.[/red] Supported: openai-codex, copilot"+ "[red]Unknown OAuth provider.[/red] Supported: openai-codex, copilot, claude-cli")return EXIT_USAGE_ERRORtry:@@ -3063,6 +3065,23 @@ def _login_copilot() -> int:return EXIT_RUN_FAILED+def _login_claude_cli() -> int:+ """Report the local Claude Code CLI login used by the claude-cli provider."""+ from src.providers.claude_cli import get_claude_cli_auth_status++ logged_in, method = get_claude_cli_auth_status()+ if logged_in:+ console.print(f"[green]Claude Code CLI is logged in[/green] [dim]{method}[/dim]")+ return EXIT_SUCCESS++ console.print(+ f"[yellow]Claude Code CLI is not logged in[/yellow] ({method}).\n"+ "Run [bold]claude auth login[/bold], or set [bold]CLAUDE_CLI_PATH[/bold] "+ "to the claude executable."+ )+ return EXIT_RUN_FAILED++# ---------------------------------------------------------------------------# Live connector runtime internals.#diff --git a/agent/src/api/settings_routes.py b/agent/src/api/settings_routes.pyindex e9cee6671..206aa963f 100644--- a/agent/src/api/settings_routes.py+++ b/agent/src/api/settings_routes.py@@ -5,7 +5,9 @@ Mounted by ``agent/api_server.py`` via ``register_settings_routes(app, ...)``.from __future__ import annotations+import asyncioimport importlib.util+import loggingimport jsonimport osimport sys as _sys@@ -19,6 +21,8 @@ from pydantic import BaseModel, Fieldfrom src.config.accessor import get_env_value, reset_env_config+logger = logging.getLogger(__name__)+# Agent root (agent/) — resolved from this file's location (agent/src/api/)._AGENT_DIR = Path(__file__).resolve().parent.parent.parent@@ -28,6 +32,11 @@ _AGENT_DIR = Path(__file__).resolve().parent.parent.parent# ---------------------------------------------------------------------------+# "none" is an explicit value direct OpenAI needs to allow function tools on+# gpt-5.6-* models; a provider with its own levels lists them in llm_providers.json.+DEFAULT_REASONING_EFFORTS = ("none", "low", "medium", "high", "max")++class LLMProviderOption(BaseModel):"""Supported LLM provider metadata for the settings UI."""@@ -41,6 +50,9 @@ class LLMProviderOption(BaseModel):api_key_required: bool = Trueauth_type: str = "api_key"login_command: Optional[str] = None+ # Levels the settings form offers and the update route accepts; "" (unset)+ # is always allowed on top of these.+ reasoning_efforts: List[str] = Field(default_factory=lambda: list(DEFAULT_REASONING_EFFORTS))class LLMSettingsResponse(BaseModel):@@ -82,6 +94,7 @@ class ListLLMModelsRequest(BaseModel):provider: str = Field(..., min_length=1)base_url: Optional[str] = Noneapi_key: Optional[str] = None+ refresh: bool = FalseModelDiscoveryWarningCode = Literal[@@ -98,6 +111,9 @@ class LLMModelsResponse(BaseModel):models: List[str]source: strwarning_code: Optional[ModelDiscoveryWarningCode] = None+ # Model id -> reasoning effort levels it accepts; an empty list means the+ # model takes no effort setting. Only providers that report it fill this.+ effort_levels: Optional[Dict[str, List[str]]] = Noneclass SourceOrderEntry(BaseModel):@@ -169,9 +185,6 @@ def _load_llm_providers() -> List[LLMProviderOption]:LLM_PROVIDERS = _load_llm_providers()LLM_PROVIDER_BY_NAME = {provider.name: provider for provider in LLM_PROVIDERS}-# "" leaves the setting unset (Off); "none" is an explicit value direct OpenAI-# needs to allow function tools on gpt-5.6-* models.-LLM_REASONING_EFFORTS = {"", "none", "low", "medium", "high", "max"}LLM_API_KEY_PLACEHOLDERS = {"", "sk-or-v1-your-key-here", "sk-xxx", "xxx", "gsk_xxx"}TUSHARE_TOKEN_PLACEHOLDERS = {"", "your-tushare-token"}GILDATA_TOKEN_PLACEHOLDERS = {"", "your-gildata-token"}@@ -314,7 +327,7 @@ async def _list_provider_models(provider=provider.name,models=fallback,source="default",- warning_code=f"{provider.auth_type}_discovery_unsupported",+ warning_code="oauth_discovery_unsupported",)if provider.api_key_required and not api_key:return LLMModelsResponse(@@ -353,6 +366,33 @@ async def _list_provider_models()+async def _list_claude_cli_models(+ provider: LLMProviderOption, *, refresh: bool+) -> LLMModelsResponse:+ """List the models the local Claude Code login can run, with their effort levels."""+ from src.providers.claude_cli_models import list_claude_cli_models++ try:+ discovered = await asyncio.to_thread(list_claude_cli_models, refresh=refresh)+ except RuntimeError as exc:+ logger.warning("claude-cli model list unavailable: %s", exc)+ return LLMModelsResponse(+ provider=provider.name,+ models=[provider.default_model],+ source="default",+ warning_code="model_list_unavailable",+ )+ models = [model.model_id for model in discovered]+ if provider.default_model not in models:+ models.insert(0, provider.default_model)+ return LLMModelsResponse(+ provider=provider.name,+ models=models,+ source="provider",+ effort_levels={model.model_id: list(model.effort_levels) for model in discovered},+ )++# ---------------------------------------------------------------------------# Response builders# ---------------------------------------------------------------------------@@ -387,6 +427,15 @@ def _build_llm_settings_response(authenticated, auth_status = False, ""api_key_configured = authenticatedapi_key_hint = auth_status if authenticated else None+ elif provider.auth_type == "claude_cli":+ try:+ from src.providers.claude_cli import get_claude_cli_auth_status++ authenticated, auth_status = get_claude_cli_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),@@ -512,8 +561,8 @@ def _sync_runtime_env(provider: LLMProviderOption, updates: Dict[str, str]) -> Nelse:os.environ.pop(key, None)- if provider.auth_type == "gh_cli":- # The Copilot SDK owns credential discovery and transport.+ if provider.auth_type in {"gh_cli", "claude_cli"}:+ # The Copilot SDK / Claude Code CLI own 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)@@ -611,7 +660,9 @@ def register_settings_routes()async def get_llm_settings():"""Return project-local LLM settings for the Web UI."""- return _build_llm_settings_response()+ # gh_cli / claude_cli providers shell out for their login status; keep+ # that off the event loop so open SSE streams are not stalled.+ return await asyncio.to_thread(_build_llm_settings_response)@app.put("/settings/llm",@@ -641,11 +692,11 @@ def register_settings_routes()reasoning_effort = (payload.reasoning_effort or "").strip().lower()- if reasoning_effort not in LLM_REASONING_EFFORTS:+ if reasoning_effort and reasoning_effort not in provider.reasoning_efforts:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail=(- "Reasoning effort must be none, low, medium, high, or max, "+ f"Reasoning effort must be one of {', '.join(provider.reasoning_efforts)}, ""or empty to leave it unset"),)@@ -694,7 +745,7 @@ def register_settings_routes(saved_values = _persist_settings_updates(updates)_sync_runtime_env(provider, updates)- return _build_llm_settings_response(saved_values)+ return await asyncio.to_thread(_build_llm_settings_response, saved_values)@app.post("/settings/llm/models",@@ -709,6 +760,9 @@ def register_settings_routes(raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Unsupported LLM provider")+ if provider.auth_type == "claude_cli":+ # No HTTP endpoint: the base URL checks below would reject it outright.+ return await _list_claude_cli_models(provider, refresh=payload.refresh)current_values = _read_settings_env_values()requested_base_url = (payload.base_url or "").strip()diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex 6a366d2aa..6e2e3e019 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -156,7 +156,8 @@ class LLMConfig(_EnvBase):"""LLM provider and generation parameters.Sources: ``src/providers/llm.py``, ``src/providers/chat.py``,- ``src/providers/openai_codex.py``, ``src/preflight.py``.+ ``src/providers/openai_codex.py``, ``src/providers/claude_cli.py``,+ ``src/preflight.py``."""langchain_provider: str = Field(alias="LANGCHAIN_PROVIDER", default="openai")@@ -180,6 +181,15 @@ class LLMConfig(_EnvBase):alias="OPENAI_CODEX_BASE_URL",default="https://chatgpt.com/backend-api/codex/responses",)+ claude_cli_path: str = Field(alias="CLAUDE_CLI_PATH", default="")+ # A convenience filter, not a security boundary: live orders are still bound+ # by the mandate gate whatever this list hides.+ claude_cli_deny_tool_prefixes: str = Field(+ alias="CLAUDE_CLI_DENY_TOOL_PREFIXES", default="trading_,etoro_"+ )+ claude_cli_bash_policy: str = Field(+ alias="CLAUDE_CLI_BASH_POLICY", default="python-only"+ )openai_model: str = Field(alias="OPENAI_MODEL", default="")vibe_trading_disable_http_proxy: EnvBool = Field(alias="VIBE_TRADING_DISABLE_HTTP_PROXY", default=False,diff --git a/agent/src/preflight.py b/agent/src/preflight.pyindex 81631341e..4f0c44a2f 100644--- a/agent/src/preflight.py+++ b/agent/src/preflight.py@@ -119,6 +119,25 @@ def _check_llm_provider() -> CheckResult:impact="",)+ if provider.lower() == "claude-cli":+ from src.providers.claude_cli import get_claude_cli_auth_status++ logged_in, auth_method = get_claude_cli_auth_status()+ if not logged_in:+ return CheckResult(+ name=f"LLM ({provider})",+ status="not_configured",+ message=f"Claude Code CLI: {auth_method}",+ impact="install Claude Code and run `claude auth login`, or set CLAUDE_CLI_PATH",+ critical=True,+ )+ return CheckResult(+ name=f"LLM ({provider})",+ status="ready",+ message=f"{model} via local claude -p ({auth_method}) | {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 c17ca1aea..1109190ec 100644--- a/agent/src/providers/capabilities.py+++ b/agent/src/providers/capabilities.py@@ -176,6 +176,14 @@ _COPILOT_CAPABILITIES = ProviderCapabilities()+# The local Claude Code CLI is driven as a subprocess in ``build_llm``; it has+# no HTTP endpoint or key of its own. The base-URL variable is never read — the+# settings UI requires one per provider.+_CLAUDE_CLI_CAPABILITIES = ProviderCapabilities(+ "claude-cli", None, "CLAUDE_CLI_BASE_URL"+)++_PROVIDERS: dict[str, ProviderCapabilities] = {# ``gpt-5.6-*`` reject function tools on /v1/chat/completions unless the# request carries an explicit ``reasoning_effort`` — including the literal@@ -257,6 +265,7 @@ _PROVIDERS: dict[str, ProviderCapabilities] = {"ollama": ProviderCapabilities("ollama", None, "OLLAMA_BASE_URL"),"copilot": _COPILOT_CAPABILITIES,"github-copilot": _COPILOT_CAPABILITIES,+ "claude-cli": _CLAUDE_CLI_CAPABILITIES,"openai-codex": _OPENAI_CODEX_CAPABILITIES,"openai_codex": _OPENAI_CODEX_CAPABILITIES,"opencode": _OPENCODE_CAPABILITIES,diff --git a/agent/src/providers/claude_cli.py b/agent/src/providers/claude_cli.pynew file mode 100644index 000000000..b4a71e4b4--- /dev/null+++ b/agent/src/providers/claude_cli.py@@ -0,0 +1,627 @@+"""Claude Code CLI provider: the local ``claude -p`` as a decision-only chat model.++Each call starts one headless ``claude -p`` process with every built-in tool and+MCP server disabled, and constrains its output with ``--json-schema`` to either+"call these tools" or "final answer". Vibe-Trading executes the tools itself, so+the ReAct loop, the grounding ledger and the swarm deliverable checks see every+tool result exactly as they would with an API provider.++Authentication is whatever the local Claude Code login provides; no API key is+read or required.+"""++from __future__ import annotations++import asyncio+import json+import os+import queue+import shutil+import subprocess+import tempfile+import threading+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Iterable, Optional++from langchain_core.messages import AIMessage, AIMessageChunk++from src.config.accessor import get_env_config+from src.providers.claude_cli_policy import (+ bash_policy,+ offered_tools,+ screen_calls,+ tool_name,+)++DEFAULT_MODEL = "claude-opus-5-5"+_TIMEOUT_FLOOR_S = 600+_AUTH_STATUS_TIMEOUT_S = 15+_MAX_RETRIES = 3+_POLL_INTERVAL_S = 0.5+_HEARTBEAT_S = 1.0++# The union of the levels any model accepts as ``--effort``. Anything outside it+# (``""``, a ``none`` saved for another provider) is never passed. The CLI does+# not reject a level the chosen model lacks, so narrowing to the selected+# model's own levels happens in the settings form.+CLAUDE_CLI_EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max")++# The flags that keep a child away from user settings, hooks, MCP servers and+# built-in tools. Model discovery uses them too, so the list matches what a turn+# can actually run.+ISOLATION_ARGS = (+ "--restricted",+ "--strict-mcp-config",+ "--tools",+ "",+ "--no-session-persistence",+)++# The child process must authenticate with the local login, never with a key+# meant for the in-process Anthropic provider.+_STRIPPED_ENV = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL")+++def child_env() -> dict[str, str]:+ return {k: v for k, v in os.environ.items() if k not in _STRIPPED_ENV}+++_PROTOCOL = (+ "\n\n## Tool-calling protocol\n"+ "You cannot execute tools yourself; the host executes them and returns the "+ "results in the next turn. Respond with action=tool_calls and the calls you "+ "want (name + arguments that match the tool's JSON schema), or action=final "+ "with your complete answer in content once you have what you need.\n"+ "Available tools (OpenAI function format):\n"+)+_FINAL_ONLY = (+ "\n\n## Output protocol\n"+ "No tools are available in this turn. Respond with action=final and your "+ "complete answer in content."+)++# Where the native Claude Code installer puts the executable; checked last.+_FALLBACK_CLI_PATH = Path.home() / ".local" / "bin" / "claude"+++def resolve_claude_cli() -> str:+ """Return the ``claude`` executable: ``CLAUDE_CLI_PATH``, PATH, then ``~/.local/bin``.++ Returns:+ Path or command name of the executable to run.++ Raises:+ RuntimeError: No executable was found.+ """+ explicit = get_env_config().llm.claude_cli_path.strip()+ if explicit:+ return explicit+ found = shutil.which("claude")+ if found:+ return found+ if _FALLBACK_CLI_PATH.is_file():+ return str(_FALLBACK_CLI_PATH)+ raise RuntimeError(+ "claude-cli provider requires the Claude Code CLI. Install it and run "+ "`claude auth login`, or set CLAUDE_CLI_PATH to the executable."+ )+++def get_claude_cli_auth_status() -> tuple[bool, str]:+ """Report the local Claude Code login, as a turn would see it; never raises.++ Runs with the same environment as a turn: an ``ANTHROPIC_API_KEY`` meant for+ the in-process Anthropic provider would otherwise report ``api_key`` as+ logged in while every turn, which strips it, fails.++ Returns:+ ``(logged_in, auth_method)``; on failure ``(False, "unavailable: ...")``.+ """+ try:+ result = subprocess.run(+ [resolve_claude_cli(), "auth", "status"],+ capture_output=True,+ text=True,+ timeout=_AUTH_STATUS_TIMEOUT_S,+ env=child_env(),+ )+ payload = json.loads(result.stdout or "{}")+ except (RuntimeError, OSError, subprocess.SubprocessError, ValueError) as exc:+ return False, f"unavailable: {type(exc).__name__}"+ logged_in = bool(payload.get("loggedIn"))+ return logged_in, str(+ payload.get("authMethod") or ("logged in" if logged_in else "not logged in")+ )+++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):+ texts: list[str] = []+ for part in content:+ if isinstance(part, dict):+ if part.get("type", "text") != "text":+ # Dropping an image silently would let the model answer a+ # question about a picture it never saw.+ raise RuntimeError(+ f"claude-cli supports text input only, not {part.get('type')!r}"+ )+ texts.append(str(part.get("text", "")))+ else:+ texts.append(str(part))+ return "".join(texts)+ return "" if content is None else str(content)+++def _role(message: Any) -> str:+ return str(+ _message_value(message, "role", "") or _message_value(message, "type", "")+ )+++def _render(messages: list[Any]) -> tuple[str, str]:+ """Split messages into the system prompt and the stdin transcript.++ A lone user message is passed through verbatim so a swarm worker's prompt+ reaches the model byte-for-byte; longer histories keep role boundaries and+ tool results in a fixed text layout.+ """+ system: list[str] = []+ rest: list[Any] = []+ for message in messages:+ role = _role(message)+ if role == "system":+ system.append(_content_text(_message_value(message, "content", "")))+ else:+ rest.append(message)+ if len(rest) == 1 and _role(rest[0]) in {"user", "human"}:+ return "\n\n".join(system), _content_text(+ _message_value(rest[0], "content", "")+ )+ parts: list[str] = []+ for message in rest:+ role = _role(message)+ content = _content_text(_message_value(message, "content", ""))+ tool_calls = _message_value(message, "tool_calls")+ if role in {"assistant", "ai"} and tool_calls:+ calls = [+ {+ "id": _message_value(tc, "id"),+ "name": (_message_value(tc, "function") or {}).get("name")+ or _message_value(tc, "name"),+ "arguments": (_message_value(tc, "function") or {}).get("arguments")+ or _message_value(tc, "args"),+ }+ for tc in tool_calls+ ]+ parts.append(+ f"[assistant]\n{content}\n[assistant tool_calls]\n{json.dumps(calls, ensure_ascii=False, default=str)}"+ )+ elif role == "tool":+ parts.append(+ f"[tool result: {_message_value(message, 'name')} id={_message_value(message, 'tool_call_id')}]\n{content}"+ )+ else:+ parts.append(f"[{role}]\n{content}")+ return "\n\n".join(system), "\n\n".join(parts)+++def _schema(allow_tools: bool) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": ["tool_calls", "final"] if allow_tools else ["final"],+ },+ "content": {"type": "string"},+ "tool_calls": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "arguments": {"type": "object"},+ },+ "required": ["name", "arguments"],+ },+ },+ },+ "required": ["action"],+ }+++@dataclass+class _Decision:+ content: str = ""+ tool_calls: list[dict[str, Any]] = field(default_factory=list)+ usage: dict[str, int] = field(+ default_factory=lambda: {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ }+ )+++def _run_cli(+ *,+ system: str,+ user_input: str,+ allow_tools: bool,+ model: str,+ effort: str = "",+ timeout: float,+ cancel_event: threading.Event,+) -> dict[str, Any]:+ """Run one ``claude -p`` turn and return its parsed JSON result."""+ fd, system_path = tempfile.mkstemp(prefix="vibe-claude-cli-", suffix=".md")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(system)+ # An empty or foreign level (``none`` saved for another provider) leaves+ # the model's own default in place.+ effort_args = ["--effort", effort] if effort in CLAUDE_CLI_EFFORT_LEVELS else []+ cmd = [+ resolve_claude_cli(),+ "-p",+ *ISOLATION_ARGS,+ "--output-format",+ "json",+ "--model",+ model,+ *effort_args,+ "--system-prompt-file",+ system_path,+ "--json-schema",+ json.dumps(_schema(allow_tools)),+ ]+ env = child_env()+ proc = subprocess.Popen(+ cmd,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ encoding="utf-8",+ env=env,+ )+ result: dict[str, Any] = {}++ def communicate() -> None:+ result["out"], result["err"] = proc.communicate(user_input)++ worker = threading.Thread(target=communicate, daemon=True)+ worker.start()+ waited = 0.0+ while worker.is_alive():+ worker.join(_POLL_INTERVAL_S)+ waited += _POLL_INTERVAL_S+ if cancel_event.is_set() or waited > timeout:+ proc.kill()+ worker.join(5)+ if cancel_event.is_set():+ return {"cancelled": True}+ raise RuntimeError(f"claude -p exceeded {timeout:.0f}s")+ finally:+ try:+ os.unlink(system_path)+ except OSError:+ pass+ try:+ payload = json.loads(result.get("out") or "")+ except ValueError:+ raise RuntimeError(+ f"claude -p produced no JSON (exit {proc.returncode}): {(result.get('err') or '')[:300]}"+ ) from None+ if payload.get("is_error"):+ raise RuntimeError(+ f"claude -p failed: {payload.get('subtype')} {str(payload.get('result'))[:300]}"+ )+ if not isinstance(payload.get("structured_output"), dict):+ raise RuntimeError("claude -p returned no structured_output")+ return payload+++def _usage(payload: dict[str, Any]) -> dict[str, int]:+ usage = payload.get("usage") or {}+ tokens_in = sum(+ int(usage.get(k) or 0)+ for k in (+ "input_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ )+ )+ tokens_out = int(usage.get("output_tokens") or 0)+ return {+ "input_tokens": tokens_in,+ "output_tokens": tokens_out,+ "total_tokens": tokens_in + tokens_out,+ }+++def _decide(+ *,+ model: str,+ effort: str = "",+ messages: list[Any],+ tools: list[dict[str, Any]],+ timeout: float,+ cancel_event: threading.Event,+) -> Optional[_Decision]:+ """Ask the CLI for the next step; refused calls are fed back for a new choice.++ Every attempt shares one deadline, so feedback retries cannot stretch a+ decision past ``timeout``.+ """+ deadline = time.monotonic() + timeout+ offered = offered_tools(tools)+ offered_names = {tool_name(t) for t in offered}+ system, user_input = _render(messages)+ allow_tools = bool(offered)+ system += (+ (_PROTOCOL + json.dumps(offered, ensure_ascii=False))+ if allow_tools+ else _FINAL_ONLY+ )+ decision = _Decision()+ for _ in range(_MAX_RETRIES + 1):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise RuntimeError(f"claude-cli: decision exceeded {timeout:.0f}s")+ payload = _run_cli(+ system=system,+ user_input=user_input,+ allow_tools=allow_tools,+ model=model,+ effort=effort,+ timeout=remaining,+ cancel_event=cancel_event,+ )+ if payload.get("cancelled"):+ return None+ # The loop reads input_tokens as the current context size; summing the+ # re-sent prompt over feedback retries would double it and compact early.+ attempt = _usage(payload)+ decision.usage["input_tokens"] = attempt["input_tokens"]+ decision.usage["output_tokens"] += attempt["output_tokens"]+ decision.usage["total_tokens"] = (+ decision.usage["input_tokens"] + decision.usage["output_tokens"]+ )+ output = payload["structured_output"]+ calls = (+ (output.get("tool_calls") or [])+ if allow_tools and output.get("action") == "tool_calls"+ else []+ )+ if not calls:+ # Under --json-schema, payload["result"] is the structured output as text, so+ # an empty content must not fall back to it: the user would see raw JSON.+ content = str(output.get("content") or "")+ if content.strip():+ decision.content = content+ return decision+ user_input += (+ "\n\n[host] Your reply had no tool calls and no content, so the user saw nothing. "+ "Reply again with action=final and the complete answer in content."+ )+ failure = "final answers kept arriving without content"+ continue+ accepted, notes = screen_calls(calls, offered_names)+ if not notes:+ decision.content = str(output.get("content") or "")+ decision.tool_calls = [+ {+ "id": f"ccli_{uuid.uuid4().hex[:8]}_{i}",+ "name": c["name"],+ "args": c["arguments"],+ }+ for i, c in enumerate(accepted)+ ]+ return decision+ user_input += (+ "\n\n[host] These tool calls were rejected and NOT executed:\n"+ + "\n".join(notes)+ + "\nChoose different calls or answer with what you have."+ )+ failure = "tool calls kept violating the host policy: " + "; ".join(notes)+ raise RuntimeError(f"claude-cli: {failure}")+++class ClaudeCliLLM:+ """LangChain-compatible wrapper around the local ``claude -p`` CLI."""++ _llm_type = "claude-cli"++ def __init__(+ self,+ *,+ model: str = DEFAULT_MODEL,+ timeout: int = 120,+ reasoning_effort: str = "",+ tools: list[dict[str, Any]] | None = None,+ ) -> None:+ """Configure one CLI-backed model.++ Args:+ model: Full model name or CLI alias, passed to ``--model``.+ timeout: Per-decision budget in seconds; never below+ ``_TIMEOUT_FLOOR_S``.+ reasoning_effort: Level passed as ``--effort``; values outside+ ``CLAUDE_CLI_EFFORT_LEVELS`` leave the model's default.+ tools: Tool definitions in OpenAI function format.++ Raises:+ RuntimeError: ``CLAUDE_CLI_BASH_POLICY`` is not a known policy, so+ the error surfaces before a paid turn rather than after one.+ """+ bash_policy()+ self.model = model+ self.timeout = timeout+ self.reasoning_effort = reasoning_effort+ self.tools = tools or []++ def bind_tools(self, tools: list[dict[str, Any]]) -> "ClaudeCliLLM":+ """Return a copy that offers *tools* to the model.++ Args:+ tools: Tool definitions in OpenAI function format.++ Returns:+ A new instance with the same model, timeout and reasoning effort.+ """+ return ClaudeCliLLM(+ model=self.model,+ timeout=self.timeout,+ reasoning_effort=self.reasoning_effort,+ tools=tools,+ )++ def _budget(self, config: Optional[dict[str, Any]]) -> float:+ # Vibe sizes timeouts for one HTTP request; one CLI turn also pays for+ # process start-up and prompt-cache creation, so keep a higher floor.+ return float(+ max((config or {}).get("timeout") or self.timeout or 0, _TIMEOUT_FLOOR_S)+ )++ def _message(self, decision: _Decision) -> AIMessage:+ return AIMessage(+ content=decision.content,+ tool_calls=decision.tool_calls,+ usage_metadata=decision.usage,+ response_metadata={+ "finish_reason": "tool_calls" if decision.tool_calls else "stop",+ "model_name": self.model,+ },+ )++ def invoke(+ self, messages: list[Any], config: Optional[dict[str, Any]] = None, **_: Any+ ) -> AIMessage:+ """Run one decision and return it as a single message.++ Args:+ messages: Conversation so far, as LangChain messages or dicts.+ config: Optional run config; its ``timeout`` raises the budget above+ the floor.++ Returns:+ The final answer, or the tool calls to execute next.+ """+ decision = _decide(+ model=self.model,+ effort=self.reasoning_effort,+ messages=messages,+ tools=self.tools,+ timeout=self._budget(config),+ cancel_event=threading.Event(),+ )+ return self._message(decision or _Decision())++ def stream(+ self, messages: list[Any], config: Optional[dict[str, Any]] = None, **_: Any+ ) -> Iterable[AIMessageChunk]:+ """Run one decision, yielding an empty chunk every second until it lands.++ Args:+ messages: Conversation so far, as LangChain messages or dicts.+ config: Optional run config; its ``timeout`` raises the budget above+ the floor.++ Yields:+ Empty keep-alive chunks while the CLI runs, then one chunk carrying+ the answer or tool calls. Closing the iterator kills the child.+ """+ chunks: queue.Queue[Any] = queue.Queue()+ sentinel = object()+ cancel_event = threading.Event()+ budget = self._budget(config)++ def run() -> None:+ try:+ decision = _decide(+ model=self.model,+ effort=self.reasoning_effort,+ messages=messages,+ tools=self.tools,+ timeout=budget,+ cancel_event=cancel_event,+ )+ if decision is not None:+ chunks.put(+ AIMessageChunk(+ content=decision.content,+ tool_call_chunks=[+ {+ "id": call["id"],+ "name": call["name"],+ "args": json.dumps(+ call["args"], ensure_ascii=False+ ),+ "index": index,+ "type": "tool_call_chunk",+ }+ for index, call in enumerate(decision.tool_calls)+ ],+ usage_metadata=decision.usage,+ response_metadata={+ "finish_reason": (+ "tool_calls" if decision.tool_calls else "stop"+ ),+ "model_name": self.model,+ },+ )+ )+ except Exception as exc:+ chunks.put(exc)+ finally:+ chunks.put(sentinel)++ threading.Thread(target=run, daemon=True).start()+ try:+ while True:+ try:+ chunk = chunks.get(timeout=_HEARTBEAT_S)+ except queue.Empty:+ # One decision is a single chunk that can take minutes. Without+ # empty chunks meanwhile, vibe's idle timeout discards an answer+ # that is still on its way and the stop button is never polled.+ yield AIMessageChunk(content="")+ continue+ if chunk is sentinel:+ return+ if isinstance(chunk, Exception):+ raise chunk+ yield chunk+ finally:+ # Closing the iterator (vibe's cooperative cancel) kills the child.+ cancel_event.set()++ async def ainvoke(+ self,+ messages: list[Any],+ config: Optional[dict[str, Any]] = None,+ **kwargs: Any,+ ) -> AIMessage:+ """Run :meth:`invoke` in a worker thread.++ Args:+ messages: Conversation so far, as LangChain messages or dicts.+ config: Optional run config, passed through to :meth:`invoke`.+ **kwargs: Passed through to :meth:`invoke`.++ Returns:+ The message :meth:`invoke` returns.+ """+ return await asyncio.to_thread(self.invoke, messages, config, **kwargs)diff --git a/agent/src/providers/claude_cli_models.py b/agent/src/providers/claude_cli_models.pynew file mode 100644index 000000000..5e892bb53--- /dev/null+++ b/agent/src/providers/claude_cli_models.py@@ -0,0 +1,142 @@+"""Models the local Claude Code login can run, as the settings page lists them.++The list comes from the CLI's ``initialize`` control request, which starts no+model turn and costs nothing.+"""++from __future__ import annotations++import json+import subprocess+import threading+import time+import uuid+from dataclasses import dataclass+from typing import Any++from src.providers.claude_cli import (+ CLAUDE_CLI_EFFORT_LEVELS,+ ISOLATION_ARGS,+ child_env,+ resolve_claude_cli,+)++_MODEL_LIST_TIMEOUT_S = 30+_MODEL_LIST_TTL_S = 300+++@dataclass(frozen=True)+class ClaudeCliModel:+ """One model the local login can run, with the effort levels it accepts.++ Attributes:+ model_id: Full model name, as passed to ``--model``.+ effort_levels: Levels the model accepts; empty when it takes none.+ """++ model_id: str+ effort_levels: tuple[str, ...]+++_model_cache: dict[str, tuple[float, tuple[ClaudeCliModel, ...]]] = {}+# One CLI launch at a time: a settings page opened twice, or an auto-load racing+# a manual refresh, should wait for the first answer instead of spawning another.+_model_cache_lock = threading.Lock()+++def list_claude_cli_models(*, refresh: bool = False) -> tuple[ClaudeCliModel, ...]:+ """Return the models the local Claude Code login can run.++ Asks the CLI with an ``initialize`` control request, which starts no model+ turn. Aliases such as ``opus`` and ``default`` resolve to the same full name,+ so entries are de-duplicated on that name: a saved full name stays pinned+ instead of following whatever an alias points to after a CLI update.++ Args:+ refresh: Skip the cached list and ask the CLI again.++ Returns:+ One entry per distinct full model name, in the CLI's order.++ Raises:+ RuntimeError: The CLI is missing, failed, or returned no models.+ """+ executable = resolve_claude_cli()+ with _model_cache_lock:+ cached = _model_cache.get(executable)+ if cached and not refresh and time.monotonic() - cached[0] < _MODEL_LIST_TTL_S:+ return cached[1]+ models = _query_claude_cli_models(executable)+ _model_cache[executable] = (time.monotonic(), models)+ return models+++def _query_claude_cli_models(executable: str) -> tuple[ClaudeCliModel, ...]:+ request = {+ "type": "control_request",+ "request_id": f"models_{uuid.uuid4().hex[:8]}",+ "request": {"subtype": "initialize"},+ }+ try:+ result = subprocess.run(+ [+ executable,+ "-p",+ *ISOLATION_ARGS,+ "--input-format",+ "stream-json",+ "--output-format",+ "stream-json",+ "--verbose",+ ],+ input=json.dumps(request) + "\n",+ capture_output=True,+ text=True,+ encoding="utf-8",+ timeout=_MODEL_LIST_TIMEOUT_S,+ env=child_env(),+ )+ except (OSError, subprocess.SubprocessError) as exc:+ raise RuntimeError(+ f"claude model list unavailable: {type(exc).__name__}"+ ) from exc+ raw_models: list[Any] = []+ for line in (result.stdout or "").splitlines():+ try:+ message = json.loads(line)+ except ValueError:+ continue+ if isinstance(message, dict) and message.get("type") == "control_response":+ outer = message.get("response")+ inner = outer.get("response") if isinstance(outer, dict) else None+ models_field = inner.get("models") if isinstance(inner, dict) else None+ raw_models = models_field if isinstance(models_field, list) else []+ break+ models: list[ClaudeCliModel] = []+ seen: set[str] = set()+ for entry in raw_models:+ if not isinstance(entry, dict):+ continue+ model_id = str(entry.get("resolvedModel") or "").strip()+ if not model_id or model_id in seen:+ continue+ seen.add(model_id)+ levels = (+ (entry.get("supportedEffortLevels") or [])+ if entry.get("supportsEffort")+ else []+ )+ models.append(+ ClaudeCliModel(+ model_id=model_id,+ effort_levels=tuple(+ level for level in levels if level in CLAUDE_CLI_EFFORT_LEVELS+ ),+ )+ )+ if not models:+ raise RuntimeError(+ f"claude model list unavailable (exit {result.returncode}): "+ f"{(result.stderr or '')[:300]}"+ )+ return tuple(models)diff --git a/agent/src/providers/claude_cli_policy.py b/agent/src/providers/claude_cli_policy.pynew file mode 100644index 000000000..d99243c7b--- /dev/null+++ b/agent/src/providers/claude_cli_policy.py@@ -0,0 +1,129 @@+"""Tool screening for the claude-cli provider: the deny list and the bash policy.++Both are convenience filters, not a security boundary: ``python -c`` can still+run anything, and live orders stay bound by the mandate gate and kill switch.+"""++from __future__ import annotations++import shlex+import sys+from pathlib import Path+from typing import Any, Optional++from src.config.accessor import get_env_config++_PYTHON_COMMANDS = frozenset({"python", "python3"})+_READONLY_COMMANDS = frozenset({"ls", "cat", "head", "tail", "wc", "pwd"})+_SHELL_PROCESS_TOOLS = frozenset({"background_run", "cancel_background"})+_SHELL_OPERATOR_CHARS = set("();<>|&")+++def _deny_prefixes() -> tuple[str, ...]:+ """Tool-name prefixes never offered to the model; ``""`` disables the list."""+ raw = get_env_config().llm.claude_cli_deny_tool_prefixes+ return tuple(p.strip() for p in raw.split(",") if p.strip())+++def bash_policy() -> str:+ """``python-only`` (default) or ``off``; anything else is a configuration error."""+ value = get_env_config().llm.claude_cli_bash_policy.strip().lower()+ if value not in {"python-only", "off"}:+ raise RuntimeError(+ f"CLAUDE_CLI_BASH_POLICY must be python-only or off, got {value!r}"+ )+ return value+++def tool_name(definition: dict[str, Any]) -> str:+ return str((definition.get("function") or definition).get("name") or "")+++def offered_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:+ prefixes = _deny_prefixes()+ return (+ [t for t in tools if not tool_name(t).startswith(prefixes)]+ if prefixes+ else list(tools)+ )+++def _relative_path(token: str) -> bool:+ return not token.startswith(("/", "~")) and ".." not in Path(token).parts+++def _hidden_path(token: str) -> bool:+ # ``.env`` and ``.git`` hold credentials; a read would put them in the trace.+ return any(part.startswith(".") and part != "." for part in Path(token).parts)+++def check_bash_command(command: str) -> tuple[Optional[str], Optional[str]]:+ """Apply the ``python-only`` policy to one shell command.++ Args:+ command: The command the model asked ``bash`` to run.++ Returns:+ ``(rewritten_command, None)`` when allowed, else ``(None, reason)``.+ An allowed ``python``/``python3`` call is rewritten to this process's+ interpreter so scripts can import Vibe-Trading's own packages.+ """+ if "\n" in command or "`" in command or "$(" in command:+ return None, "newlines, backticks and $( ) are not allowed"+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)+ lexer.whitespace_split = True+ try:+ tokens = list(lexer)+ except ValueError as exc:+ return None, f"unparseable command: {exc}"+ if not tokens:+ return None, "empty command"+ if any(tok and set(tok) <= _SHELL_OPERATOR_CHARS for tok in tokens):+ return None, "shell operators (; && || | redirection) are not allowed"+ program, args = tokens[0], tokens[1:]+ if program in _PYTHON_COMMANDS:+ if args[:1] == ["-c"] and len(args) >= 2:+ return shlex.join([sys.executable, *args]), None+ if args and args[0].endswith(".py") and _relative_path(args[0]):+ return shlex.join([sys.executable, *args]), None+ return (+ None,+ "python may only run `python <relative script>.py` or `python -c <code>`",+ )+ if program in _READONLY_COMMANDS:+ paths = [a for a in args if not a.startswith("-")]+ if all(_relative_path(p) and not _hidden_path(p) for p in paths):+ return shlex.join(tokens), None+ return (+ None,+ f"{program} may only read non-hidden relative paths inside the working directory",+ )+ return None, f"program {program!r} is not allowed (python-only policy)"+++def screen_calls(+ calls: list[dict[str, Any]], offered: set[str]+) -> tuple[list[dict[str, Any]], list[str]]:+ """Return calls the host may execute, plus one rejection note per refused call."""+ policy = bash_policy()+ accepted: list[dict[str, Any]] = []+ notes: list[str] = []+ for call in calls:+ name = str(call.get("name") or "")+ args = dict(call.get("arguments") or {})+ if name not in offered:+ notes.append(f"- {name}: not an available tool")+ continue+ if policy == "python-only" and name in _SHELL_PROCESS_TOOLS:+ notes.append(+ f"- {name}: background processes are not allowed (python-only policy)"+ )+ continue+ if policy == "python-only" and name == "bash":+ rewritten, reason = check_bash_command(str(args.get("command") or ""))+ if reason:+ notes.append(f"- bash `{args.get('command')}`: {reason}")+ continue+ args["command"] = rewritten+ accepted.append({"name": name, "arguments": args})+ return accepted, notesdiff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 032482140..6ca17b8c7 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -1412,7 +1412,7 @@ def _sync_provider_env() -> None:os.environ.pop("OPENAI_API_KEY", None)return- if provider in {"copilot", "github-copilot"}:+ if provider in {"copilot", "github-copilot", "claude-cli"}:os.environ.pop("OPENAI_API_BASE", None)os.environ.pop("OPENAI_BASE_URL", None)os.environ.pop("OPENAI_API_KEY", None)@@ -1668,6 +1668,16 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Anytimeout=get_env_config().llm.timeout_seconds,)+ if provider == "claude-cli":+ from src.providers.claude_cli import ClaudeCliLLM++ llm_cfg = get_env_config().llm+ return ClaudeCliLLM(+ model=name,+ timeout=llm_cfg.timeout_seconds,+ reasoning_effort=llm_cfg.langchain_reasoning_effort.strip().lower(),+ )+if provider == "anthropic":return _build_anthropic(model=name,diff --git a/agent/src/providers/llm_providers.json b/agent/src/providers/llm_providers.jsonindex f73a5d7a7..a97d6732b 100644--- a/agent/src/providers/llm_providers.json+++ b/agent/src/providers/llm_providers.json@@ -235,5 +235,17 @@"api_key_required": false,"auth_type": "gh_cli","login_command": "gh auth login"+ },+ {+ "name": "claude-cli",+ "label": "Claude Code CLI (local login)",+ "api_key_env": null,+ "base_url_env": "CLAUDE_CLI_BASE_URL",+ "default_model": "claude-opus-5-5",+ "default_base_url": "",+ "api_key_required": false,+ "auth_type": "claude_cli",+ "login_command": "claude auth login",+ "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]}]diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.pyindex bb3d2446f..e0a67cffb 100644--- a/agent/src/swarm/models.py+++ b/agent/src/swarm/models.py@@ -16,10 +16,11 @@ from src.tools.redaction import redact_text_PUBLIC_METADATA_MAX_LENGTH = 128_REDACTED_METADATA = "[redacted]"-_REASONING_EFFORTS = frozenset({"none", "low", "medium", "high", "max"})+_REASONING_EFFORTS = frozenset({"none", "low", "medium", "high", "xhigh", "max"})_PUBLIC_PROVIDERS = frozenset({"anthropic",+ "claude-cli","dashscope","deepseek","gemini",diff --git a/agent/tests/claude_cli_helpers.py b/agent/tests/claude_cli_helpers.pynew file mode 100644index 000000000..08f3e2576--- /dev/null+++ b/agent/tests/claude_cli_helpers.py@@ -0,0 +1,201 @@+"""Fake ``claude`` executables and payload builders for the claude-cli provider tests.++Both fakes are real scripts on ``CLAUDE_CLI_PATH``, so the provider's actual+subprocess handling runs; every call is logged to disk for the test to inspect.+"""++from __future__ import annotations++import json+import sys+import textwrap+from pathlib import Path+from typing import Any, Callable++import pytest++from src.providers import claude_cli_models++# Answers one ``claude -p`` turn from a reply list, one reply per call.+_FAKE_CLI = textwrap.dedent("""\+ #!{python}+ import json, os, sys, time+ from pathlib import Path++ log = Path(os.environ["FAKE_CLAUDE_LOG"])+ replies = json.loads(Path(os.environ["FAKE_CLAUDE_REPLIES"]).read_text())+ calls = sorted(log.glob("call-*.json"))+ n = len(calls)+ args = sys.argv[1:]+ system = Path(args[args.index("--system-prompt-file") + 1]).read_text()+ record = {{"args": args, "stdin": sys.stdin.read(), "system": system}}+ (log / f"call-{{n:03d}}.json").write_text(json.dumps(record))+ reply = replies[min(n, len(replies) - 1)]+ if reply.get("sleep"):+ time.sleep(reply["sleep"])+ if reply.get("raw") is not None:+ sys.stdout.write(reply["raw"])+ else:+ sys.stdout.write(json.dumps(reply["payload"]))+ """)++# Answers the ``initialize`` control request, surrounded by the noise a real+# CLI prints: a non-JSON line and a system event before the response.+_FAKE_INIT_CLI = textwrap.dedent("""\+ #!{python}+ import json, os, sys+ from pathlib import Path++ log = Path(os.environ["FAKE_CLAUDE_LOG"])+ n = len(list(log.glob("init-*.json")))+ record = {{"args": sys.argv[1:], "stdin": sys.stdin.read()}}+ (log / f"init-{{n:03d}}.json").write_text(json.dumps(record))+ reply = json.loads(Path(os.environ["FAKE_CLAUDE_REPLIES"]).read_text())+ if reply.get("exit"):+ sys.stderr.write("boom")+ sys.exit(reply["exit"])+ sys.stdout.write("not json at all\\n")+ sys.stdout.write(json.dumps({{"type": "system", "subtype": "hook_started"}}) + "\\n")+ response = {{"models": reply["models"]}}+ sys.stdout.write(json.dumps({{+ "type": "control_response",+ "response": {{"subtype": "success", "request_id": "x", "response": response}},+ }}) + "\\n")+ """)++SetReplies = Callable[..., None]+Calls = Callable[[], list[dict[str, Any]]]+++def _install(+ script_text: str, log_glob: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> tuple[Path, Calls]:+ script = tmp_path / "claude"+ script.write_text(script_text.format(python=sys.executable))+ script.chmod(0o755)+ log = tmp_path / "log"+ log.mkdir()+ reply_path = tmp_path / "replies.json"+ monkeypatch.setenv("CLAUDE_CLI_PATH", str(script))+ monkeypatch.setenv("FAKE_CLAUDE_LOG", str(log))+ monkeypatch.setenv("FAKE_CLAUDE_REPLIES", str(reply_path))++ def calls() -> list[dict[str, Any]]:+ return [json.loads(p.read_text()) for p in sorted(log.glob(log_glob))]++ return reply_path, calls+++def install_fake_cli(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> tuple[SetReplies, Calls]:+ """Put a fake turn-answering ``claude`` on ``CLAUDE_CLI_PATH``.++ Args:+ tmp_path: Directory for the script, its replies and its call log.+ monkeypatch: Fixture used to point the provider at the script.++ Returns:+ ``(set_replies, calls)``: ``set_replies(*replies)`` queues one reply per+ call (the last repeats); ``calls()`` returns each logged invocation.+ """+ reply_path, calls = _install(_FAKE_CLI, "call-*.json", tmp_path, monkeypatch)+ monkeypatch.delenv("CLAUDE_CLI_DENY_TOOL_PREFIXES", raising=False)+ monkeypatch.delenv("CLAUDE_CLI_BASH_POLICY", raising=False)++ def set_replies(*replies: dict[str, Any]) -> None:+ reply_path.write_text(json.dumps(list(replies)))++ return set_replies, calls+++def install_fake_init_cli(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> tuple[SetReplies, Calls]:+ """Put a fake ``claude`` answering the ``initialize`` request on the path.++ Also empties the provider's model-list cache so each test starts cold.++ Args:+ tmp_path: Directory for the script, its reply and its call log.+ monkeypatch: Fixture used to point the provider at the script.++ Returns:+ ``(set_reply, calls)``: ``set_reply({"models": [...]})`` or+ ``set_reply({"exit": code})`` sets the answer; ``calls()`` returns each+ logged invocation.+ """+ reply_path, calls = _install(_FAKE_INIT_CLI, "init-*.json", tmp_path, monkeypatch)+ monkeypatch.setattr(claude_cli_models, "_model_cache", {})++ def set_reply(reply: dict[str, Any]) -> None:+ reply_path.write_text(json.dumps(reply))++ return set_reply, calls+++def payload(+ structured: dict[str, Any] | None,+ *,+ is_error: bool = False,+ cost_in: int = 10,+ cost_out: int = 5,+) -> dict[str, Any]:+ """Build a ``claude -p --output-format json`` result.++ Args:+ structured: The ``structured_output`` object, or ``None`` to omit it.+ is_error: Mark the result as a failed run.+ cost_in: Input tokens reported in ``usage``.+ cost_out: Output tokens reported in ``usage``.++ Returns:+ The JSON payload the CLI would print.+ """+ body: dict[str, Any] = {+ "type": "result",+ "subtype": "error_during_execution" if is_error else "success",+ "is_error": is_error,+ "result": json.dumps(structured) if structured else "",+ "usage": {+ "input_tokens": cost_in,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": cost_out,+ },+ }+ if structured is not None:+ body["structured_output"] = structured+ return body+++def tool(name: str) -> dict[str, Any]:+ """Build an OpenAI-format function tool with no parameters.++ Args:+ name: Tool name, also used as its description.++ Returns:+ The tool definition.+ """+ return {+ "type": "function",+ "function": {+ "name": name,+ "description": name,+ "parameters": {"type": "object", "properties": {}},+ },+ }+++def use_provider(monkeypatch: pytest.MonkeyPatch) -> None:+ """Select claude-cli as the configured provider without reading any ``.env``.++ Args:+ monkeypatch: Fixture used to set the provider environment.+ """+ import src.providers.llm as llm++ monkeypatch.setenv("LANGCHAIN_PROVIDER", "claude-cli")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "claude-opus-5-5")+ monkeypatch.setattr(llm, "_ensure_dotenv", lambda: None)diff --git a/agent/tests/test_claude_cli_models.py b/agent/tests/test_claude_cli_models.pynew file mode 100644index 000000000..2046e24d4--- /dev/null+++ b/agent/tests/test_claude_cli_models.py@@ -0,0 +1,176 @@+"""Model discovery and reasoning effort for the claude-cli provider."""++from __future__ import annotations++import json+import subprocess+from types import SimpleNamespace++import pytest++from src.providers import claude_cli, claude_cli_models+from tests.claude_cli_helpers import (+ install_fake_cli,+ install_fake_init_cli,+ payload,+ tool,+ use_provider,+)++_CLI_MODELS = [+ {+ "value": "default",+ "resolvedModel": "claude-opus-5-5",+ "supportsEffort": True,+ "supportedEffortLevels": ["low", "medium", "high", "xhigh", "max"],+ },+ {+ "value": "opus",+ "resolvedModel": "claude-opus-5-5",+ "supportsEffort": True,+ "supportedEffortLevels": ["low"],+ },+ {"value": "haiku", "resolvedModel": "claude-haiku-4-5-20251001"},+ {+ "value": "claude-sonnet-4-6",+ "resolvedModel": "claude-sonnet-4-6",+ "supportsEffort": True,+ "supportedEffortLevels": ["low", "medium", "high", "max"],+ },+ {"value": "broken"},+]+++def fake_cli(tmp_path, monkeypatch):+ return install_fake_cli(tmp_path, monkeypatch)+++def fake_init_cli(tmp_path, monkeypatch):+ return install_fake_init_cli(tmp_path, monkeypatch)+++# --- model discovery ----------------------------------------------------------+++def test_model_list_dedupes_on_resolved_name_and_keeps_levels(fake_init_cli) -> None:+ set_reply, calls = fake_init_cli+ set_reply({"models": _CLI_MODELS})++ models = claude_cli_models.list_claude_cli_models()++ assert [m.model_id for m in models] == [+ "claude-opus-5-5",+ "claude-haiku-4-5-20251001",+ "claude-sonnet-4-6",+ ]+ assert models[0].effort_levels == ("low", "medium", "high", "xhigh", "max")+ assert models[1].effort_levels == ()+ assert models[2].effort_levels == ("low", "medium", "high", "max")+ (call,) = calls()+ assert {"--restricted", "--strict-mcp-config", "--no-session-persistence"} <= set(+ call["args"]+ )+ assert json.loads(call["stdin"])["request"] == {"subtype": "initialize"}+++def test_model_list_skips_lines_that_are_not_json(fake_init_cli) -> None:+ set_reply, _ = fake_init_cli+ set_reply({"models": [_CLI_MODELS[3]]})++ models = claude_cli_models.list_claude_cli_models()++ assert [m.model_id for m in models] == ["claude-sonnet-4-6"]+++def test_model_list_is_cached_until_refresh(fake_init_cli) -> None:+ set_reply, calls = fake_init_cli+ set_reply({"models": _CLI_MODELS})++ claude_cli_models.list_claude_cli_models()+ claude_cli_models.list_claude_cli_models()+ assert len(calls()) == 1++ claude_cli_models.list_claude_cli_models(refresh=True)+ assert len(calls()) == 2++[email protected]("reply", [{"exit": 1}, {"models": []}])+def test_model_list_failure_raises(fake_init_cli, reply) -> None:+ set_reply, _ = fake_init_cli+ set_reply(reply)++ with pytest.raises(RuntimeError, match="model list unavailable"):+ claude_cli_models.list_claude_cli_models()+++# --- reasoning effort ---------------------------------------------------------+++ ("effort", "expected"),+ [+ ("high", ["--effort", "high"]),+ ("xhigh", ["--effort", "xhigh"]),+ ("", None),+ ("none", None),+ ("turbo", None),+ ],+)+def test_effort_reaches_the_cli_only_when_it_is_a_cli_level(+ fake_cli, effort, expected+) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})++ claude_cli.ClaudeCliLLM(reasoning_effort=effort).invoke(+ [{"role": "user", "content": "hi"}]+ )++ args = calls()[0]["args"]+ if expected is None:+ assert "--effort" not in args+ else:+ index = args.index("--effort")+ assert args[index : index + 2] == expected+++def test_malformed_control_response_is_reported_not_crashed(monkeypatch) -> None:+ def fake_run(cmd, **kwargs):+ line = json.dumps({"type": "control_response", "response": "oops"})+ return subprocess.CompletedProcess(cmd, 0, stdout=line + "\n", stderr="")++ monkeypatch.setenv("CLAUDE_CLI_PATH", "/bin/true")+ monkeypatch.setattr(claude_cli_models, "_model_cache", {})+ # Replace the module's reference, not the shared ``subprocess`` module (#1123).+ monkeypatch.setattr(+ claude_cli_models,+ "subprocess",+ SimpleNamespace(run=fake_run, SubprocessError=subprocess.SubprocessError),+ )++ with pytest.raises(RuntimeError, match="model list unavailable"):+ claude_cli_models.list_claude_cli_models()++[email protected]("raw", ["High", " high "])+def test_build_llm_normalises_reasoning_effort(monkeypatch, raw) -> None:+ import src.providers.llm as llm++ use_provider(monkeypatch)+ monkeypatch.setenv("LANGCHAIN_REASONING_EFFORT", raw)++ assert llm.build_llm().reasoning_effort == "high"+++def test_build_llm_passes_reasoning_effort_through_bind_tools(monkeypatch) -> None:+ import src.providers.llm as llm++ use_provider(monkeypatch)+ monkeypatch.setenv("LANGCHAIN_REASONING_EFFORT", "xhigh")++ model = llm.build_llm()++ assert model.reasoning_effort == "xhigh"+ assert model.bind_tools([tool("get_market_data")]).reasoning_effort == "xhigh"diff --git a/agent/tests/test_claude_cli_provider.py b/agent/tests/test_claude_cli_provider.pynew file mode 100644index 000000000..1f367d5c9--- /dev/null+++ b/agent/tests/test_claude_cli_provider.py@@ -0,0 +1,409 @@+"""Coverage for the local Claude Code CLI provider (``claude -p`` as a decision-only model)."""++from __future__ import annotations++import json+import subprocess+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++import api_server # noqa: F401+from src.api import settings_routes+from src.providers import claude_cli+from src.providers.capabilities import get_provider_capabilities+from src.providers.chat import ChatLLM+from src.swarm.models import public_provider_metadata+from tests.claude_cli_helpers import install_fake_cli, payload, tool, use_provider++_PROVIDERS_JSON = (+ Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json"+)+++def fake_cli(tmp_path, monkeypatch):+ return install_fake_cli(tmp_path, monkeypatch)+++# --- registration -----------------------------------------------------------+++def test_claude_cli_is_registered_in_catalog_and_capabilities() -> None:+ entries = {+ item["name"]: item+ for item in json.loads(_PROVIDERS_JSON.read_text(encoding="utf-8"))+ }+ entry = entries["claude-cli"]+ assert entry["api_key_required"] is False+ assert entry["auth_type"] == "claude_cli"+ assert (+ get_provider_capabilities("claude-cli", "claude-opus-5-5").name == "claude-cli"+ )+++def test_claude_cli_label_survives_public_run_metadata() -> None:+ assert public_provider_metadata("claude-cli") == "claude-cli"+++def test_sync_provider_env_clears_openai_transport(monkeypatch) -> None:+ import src.providers.llm as llm++ use_provider(monkeypatch)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-should-be-removed")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://example.invalid/v1")+ llm._sync_provider_env()+ import os++ assert "OPENAI_API_KEY" not in os.environ+ assert "OPENAI_BASE_URL" not in os.environ+++def test_build_llm_returns_cli_wrapper(monkeypatch) -> None:+ import src.providers.llm as llm++ use_provider(monkeypatch)+ model = llm.build_llm()+ assert isinstance(model, claude_cli.ClaudeCliLLM)+ assert model.model == "claude-opus-5-5"+++# --- decision mapping ---------------------------------------------------------+++def test_tool_calls_map_to_vibe_tool_call_requests(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {+ "name": "get_market_data",+ "arguments": {"codes": ["03988.HK"]},+ }+ ],+ }+ )+ }+ )+ use_provider(monkeypatch)++ response = ChatLLM().stream_chat(+ [{"role": "system", "content": "SYS"}, {"role": "user", "content": "price?"}],+ tools=[tool("get_market_data")],+ )++ assert response.has_tool_calls+ call = response.tool_calls[0]+ assert call.name == "get_market_data"+ assert call.arguments == {"codes": ["03988.HK"]}+ assert call.id.startswith("ccli_")+ assert response.usage_metadata["input_tokens"] == 10+++def test_final_answer_maps_to_content(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "close 6.125"})})+ use_provider(monkeypatch)++ response = ChatLLM().chat([{"role": "user", "content": "hi"}])++ assert response.content == "close 6.125"+ assert not response.has_tool_calls+++def test_final_without_content_is_fed_back_and_retried(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies(+ {"payload": payload({"action": "final"})},+ {"payload": payload({"action": "final", "content": "order 42 cancelled"})},+ )++ message = claude_cli.ClaudeCliLLM(tools=[tool("get_market_data")]).invoke(+ [{"role": "user", "content": "cancel"}]+ )++ assert message.content == "order 42 cancelled"+ assert "no tool calls and no content" in calls()[1]["stdin"]+ # input_tokens is the last prompt's size (what the context meter reads);+ # output_tokens is what both attempts generated.+ assert message.usage_metadata["input_tokens"] == 10+ assert message.usage_metadata["output_tokens"] == 10+++def test_final_never_echoes_the_structured_output_as_content(fake_cli) -> None:+ set_replies, _ = fake_cli+ set_replies({"payload": payload({"action": "final", "content": " "})})++ with pytest.raises(RuntimeError, match="without content"):+ claude_cli.ClaudeCliLLM().invoke([{"role": "user", "content": "x"}])+++def test_vibe_system_prompt_is_a_verbatim_prefix_and_lone_user_is_verbatim(+ fake_cli,+) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})+ system = "## Role\n\nexact text {with braces}\n"+ user = "Report the latest close of 03988.HK."++ claude_cli.ClaudeCliLLM(tools=[tool("get_market_data")]).invoke(+ [{"role": "system", "content": system}, {"role": "user", "content": user}]+ )++ record = calls()[0]+ assert record["system"].startswith(system)+ assert "Tool-calling protocol" in record["system"]+ assert record["stdin"] == user+++def test_turn_without_tools_only_allows_final(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})++ claude_cli.ClaudeCliLLM().invoke([{"role": "user", "content": "x"}])++ args = calls()[0]["args"]+ schema = json.loads(args[args.index("--json-schema") + 1])+ assert schema["properties"]["action"]["enum"] == ["final"]+ assert args[args.index("--tools") + 1] == ""+ assert "--strict-mcp-config" in args and "--restricted" in args+++def test_history_renders_tool_calls_and_results(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "done"})})+ messages = [+ {"role": "system", "content": "SYS"},+ {"role": "user", "content": "price?"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "get_market_data", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "c1",+ "name": "get_market_data",+ "content": "close=6.125",+ },+ ]++ claude_cli.ClaudeCliLLM(tools=[tool("get_market_data")]).invoke(messages)++ stdin = calls()[0]["stdin"]+ assert "[assistant tool_calls]" in stdin+ assert "[tool result: get_market_data id=c1]\nclose=6.125" in stdin+++# --- error paths --------------------------------------------------------------+++ "reply, message",+ [+ ({"raw": "not json"}, "no JSON"),+ ({"payload": payload({"action": "final"}, is_error=True)}, "failed"),+ ({"payload": payload(None)}, "structured_output"),+ ],+)+def test_bad_cli_output_raises(fake_cli, reply, message) -> None:+ set_replies, _ = fake_cli+ set_replies(reply)+ with pytest.raises(RuntimeError, match=message):+ claude_cli.ClaudeCliLLM().invoke([{"role": "user", "content": "x"}])+++def test_timeout_kills_the_child(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {"sleep": 30, "payload": payload({"action": "final", "content": "late"})}+ )+ monkeypatch.setattr(claude_cli, "_TIMEOUT_FLOOR_S", 1)+ started = time.monotonic()+ with pytest.raises(RuntimeError, match="exceeded"):+ claude_cli.ClaudeCliLLM(timeout=1).invoke([{"role": "user", "content": "x"}])+ assert time.monotonic() - started < 10+++def test_cancel_event_stops_the_child(fake_cli) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {"sleep": 30, "payload": payload({"action": "final", "content": "late"})}+ )+ cancel = threading.Event()+ threading.Timer(1.0, cancel.set).start()+ started = time.monotonic()+ result = claude_cli._run_cli(+ system="S",+ user_input="x",+ allow_tools=False,+ model="m",+ timeout=60,+ cancel_event=cancel,+ )+ assert result == {"cancelled": True}+ assert time.monotonic() - started < 10+++def test_slow_decision_outlives_the_stream_idle_timeout(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {"sleep": 3, "payload": payload({"action": "final", "content": "slow answer"})}+ )+ monkeypatch.setattr(claude_cli, "_HEARTBEAT_S", 0.2)+ use_provider(monkeypatch)++ response = ChatLLM().stream_chat(+ [{"role": "user", "content": "x"}], idle_timeout_s=1+ )++ assert response.content == "slow answer"+++def test_stop_button_ends_a_running_decision(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {"sleep": 30, "payload": payload({"action": "final", "content": "late"})}+ )+ monkeypatch.setattr(claude_cli, "_HEARTBEAT_S", 0.2)+ use_provider(monkeypatch)+ stop_at = time.monotonic() + 1.0++ started = time.monotonic()+ response = ChatLLM().stream_chat(+ [{"role": "user", "content": "x"}],+ should_cancel=lambda: time.monotonic() > stop_at,+ )++ assert time.monotonic() - started < 10+ assert response.content == ""+++def test_retries_share_one_deadline(fake_cli, monkeypatch) -> None:+ set_replies, calls = fake_cli+ set_replies({"sleep": 0.7, "payload": payload({"action": "final"})})+ monkeypatch.setattr(claude_cli, "_TIMEOUT_FLOOR_S", 1)++ with pytest.raises(RuntimeError, match="exceeded"):+ claude_cli.ClaudeCliLLM(timeout=1).invoke([{"role": "user", "content": "x"}])++ # Four attempts fit in 4 x 1s budgets but not in one shared 1s deadline.+ assert len(calls()) < 4+++def test_image_input_is_refused_instead_of_dropped(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "a cat"})})+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}++ with pytest.raises(RuntimeError, match="text input only"):+ claude_cli.ClaudeCliLLM().invoke(+ [{"role": "user", "content": [{"type": "text", "text": "what?"}, image]}]+ )++ assert calls() == []+++def test_lone_langchain_human_message_is_passed_verbatim(fake_cli) -> None:+ from langchain_core.messages import HumanMessage, SystemMessage++ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})++ claude_cli.ClaudeCliLLM().invoke(+ [SystemMessage(content="SYS"), HumanMessage(content="exact prompt")]+ )++ assert calls()[0]["stdin"] == "exact prompt"+++def test_unknown_bash_policy_fails_before_any_turn(fake_cli, monkeypatch) -> None:+ _, calls = fake_cli+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "strict")++ with pytest.raises(RuntimeError, match="CLAUDE_CLI_BASH_POLICY"):+ claude_cli.ClaudeCliLLM()++ assert calls() == []+++def test_auth_status_runs_without_the_anthropic_key(monkeypatch) -> None:+ seen: dict = {}++ def fake_run(cmd, **kwargs):+ seen.update(kwargs)+ return subprocess.CompletedProcess(+ cmd, 0, stdout='{"loggedIn": true, "authMethod": "claude.ai"}', stderr=""+ )++ monkeypatch.setenv("CLAUDE_CLI_PATH", "/bin/true")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-not-used")+ # Replace the module's reference, not the shared ``subprocess`` module (#1123).+ monkeypatch.setattr(+ claude_cli,+ "subprocess",+ SimpleNamespace(run=fake_run, SubprocessError=subprocess.SubprocessError),+ )++ assert claude_cli.get_claude_cli_auth_status() == (True, "claude.ai")+ assert "ANTHROPIC_API_KEY" not in seen["env"]+++def test_missing_cli_raises_with_setup_hint(monkeypatch) -> None:+ monkeypatch.delenv("CLAUDE_CLI_PATH", raising=False)+ monkeypatch.setattr(claude_cli.shutil, "which", lambda _: None)+ monkeypatch.setattr(claude_cli.Path, "home", lambda: Path("/nonexistent-home"))+ with pytest.raises(RuntimeError, match="claude auth login"):+ claude_cli.resolve_claude_cli()+++# --- settings / preflight -----------------------------------------------------+++def test_settings_report_cli_login(monkeypatch) -> None:+ monkeypatch.setattr(+ claude_cli, "get_claude_cli_auth_status", lambda: (True, "claude.ai")+ )++ response = settings_routes._build_llm_settings_response(+ {"LANGCHAIN_PROVIDER": "claude-cli"}+ )++ assert response.api_key_required is False+ assert response.api_key_configured is True+ assert response.api_key_hint == "claude.ai"+++def test_preflight_uses_cli_login(monkeypatch) -> None:+ import src.providers.llm as llm+ from src import preflight++ monkeypatch.setenv("LANGCHAIN_PROVIDER", "claude-cli")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "claude-opus-5-5")+ monkeypatch.setattr(llm, "_ensure_dotenv", lambda: None)+ monkeypatch.setattr(llm, "_sync_provider_env", lambda: None)+ monkeypatch.setattr(+ llm,+ "provider_diagnostics",+ lambda: {"base_url": "", "timeout_seconds": 120, "max_retries": 2, "proxy": {}},+ )+ monkeypatch.setattr(+ claude_cli, "get_claude_cli_auth_status", lambda: (False, "not logged in")+ )++ result = preflight._check_llm_provider()++ assert result.status == "not_configured"+ assert "claude auth login" in result.impactdiff --git a/agent/tests/test_claude_cli_tool_policy.py b/agent/tests/test_claude_cli_tool_policy.pynew file mode 100644index 000000000..2c9be8440--- /dev/null+++ b/agent/tests/test_claude_cli_tool_policy.py@@ -0,0 +1,238 @@+"""Tool screening for the claude-cli provider: the deny list and the bash policy."""++from __future__ import annotations++import shlex+import sys++import pytest++from src.providers import claude_cli, claude_cli_policy+from tests.claude_cli_helpers import install_fake_cli, payload, tool+++def fake_cli(tmp_path, monkeypatch):+ return install_fake_cli(tmp_path, monkeypatch)+++# --- tool deny list -----------------------------------------------------------+++def test_trading_tools_are_not_offered_by_default(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})++ claude_cli.ClaudeCliLLM(+ tools=[+ tool("get_market_data"),+ tool("trading_place_order"),+ tool("etoro_close_position"),+ ]+ ).invoke([{"role": "user", "content": "x"}])++ system = calls()[0]["system"]+ assert "get_market_data" in system+ assert "trading_place_order" not in system+ assert "etoro_close_position" not in system+++def test_request_for_unoffered_tool_is_fed_back_and_retried(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [{"name": "trading_place_order", "arguments": {}}],+ }+ )+ },+ {"payload": payload({"action": "final", "content": "cannot trade"})},+ )++ message = claude_cli.ClaudeCliLLM(+ tools=[tool("get_market_data"), tool("trading_place_order")]+ ).invoke([{"role": "user", "content": "buy"}])++ assert message.content == "cannot trade"+ assert not message.tool_calls+ assert "trading_place_order: not an available tool" in calls()[1]["stdin"]+ # input_tokens is the last prompt's size (what the context meter reads);+ # output_tokens is what both attempts generated.+ assert message.usage_metadata["input_tokens"] == 10+ assert message.usage_metadata["output_tokens"] == 10+++def test_empty_deny_list_offers_every_tool(fake_cli, monkeypatch) -> None:+ set_replies, calls = fake_cli+ set_replies({"payload": payload({"action": "final", "content": "ok"})})+ monkeypatch.setenv("CLAUDE_CLI_DENY_TOOL_PREFIXES", "")++ claude_cli.ClaudeCliLLM(tools=[tool("trading_place_order")]).invoke(+ [{"role": "user", "content": "x"}]+ )++ assert "trading_place_order" in calls()[0]["system"]+++# --- bash policy --------------------------------------------------------------+++ "command",+ [+ "python script.py",+ "python3 analysis.py --window 30",+ 'python -c "print(1 | 2)"',+ "ls",+ "cat report.md",+ "head -n 5 data/bars.csv",+ "pwd",+ ],+)+def test_python_only_policy_allows(command) -> None:+ rewritten, reason = claude_cli_policy.check_bash_command(command)+ assert reason is None+ if command.startswith("python"):+ assert shlex.split(rewritten)[0] == sys.executable+++ "command",+ [+ "python script.py; rm -rf ~",+ "python script.py && curl x",+ "cat a | sh",+ "python script.py > /etc/x",+ "curl https://example.com",+ "pip install x",+ "python -m pip install x",+ "python /tmp/evil.py",+ "python ../escape.py",+ "cat ~/.claude.json",+ "cat /etc/passwd",+ 'python -c "$(whoami)"',+ "echo `id`",+ "python a.py\nrm x",+ "rm -rf .",+ "cat .env",+ "head agent/.env",+ "ls .git",+ ],+)+def test_python_only_policy_blocks(command) -> None:+ rewritten, reason = claude_cli_policy.check_bash_command(command)+ assert rewritten is None+ assert reason+++def test_blocked_bash_is_fed_back_and_allowed_bash_is_rewritten(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {+ "name": "bash",+ "arguments": {"command": "curl https://example.com"},+ }+ ],+ }+ )+ },+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {"name": "bash", "arguments": {"command": "python var.py"}}+ ],+ }+ )+ },+ )++ message = claude_cli.ClaudeCliLLM(tools=[tool("bash")]).invoke(+ [{"role": "user", "content": "risk"}]+ )++ assert "program 'curl' is not allowed" in calls()[1]["stdin"]+ assert shlex.split(message.tool_calls[0]["args"]["command"]) == [+ sys.executable,+ "var.py",+ ]+++def test_background_tools_are_blocked_under_python_only(fake_cli) -> None:+ set_replies, calls = fake_cli+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {+ "name": "background_run",+ "arguments": {"command": "python a.py"},+ }+ ],+ }+ )+ },+ {"payload": payload({"action": "final", "content": "ok"})},+ )++ claude_cli.ClaudeCliLLM(tools=[tool("background_run")]).invoke(+ [{"role": "user", "content": "x"}]+ )++ assert "background processes are not allowed" in calls()[1]["stdin"]+++def test_policy_off_passes_bash_through_unchanged(fake_cli, monkeypatch) -> None:+ set_replies, _ = fake_cli+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "off")+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {+ "name": "bash",+ "arguments": {"command": "curl https://example.com"},+ }+ ],+ }+ )+ }+ )++ message = claude_cli.ClaudeCliLLM(tools=[tool("bash")]).invoke(+ [{"role": "user", "content": "x"}]+ )++ assert message.tool_calls[0]["args"]["command"] == "curl https://example.com"+++def test_repeated_policy_violations_raise(fake_cli) -> None:+ set_replies, _ = fake_cli+ set_replies(+ {+ "payload": payload(+ {+ "action": "tool_calls",+ "tool_calls": [+ {"name": "bash", "arguments": {"command": "curl x"}}+ ],+ }+ )+ }+ )+ with pytest.raises(RuntimeError, match="host policy"):+ claude_cli.ClaudeCliLLM(tools=[tool("bash")]).invoke(+ [{"role": "user", "content": "x"}]+ )diff --git a/agent/tests/test_llm_provider_defaults.py b/agent/tests/test_llm_provider_defaults.pyindex 86c3b8392..56f7f64fe 100644--- a/agent/tests/test_llm_provider_defaults.py+++ b/agent/tests/test_llm_provider_defaults.py@@ -171,9 +171,12 @@ def test_credential_fallback_map_matches_provider_catalog() -> None:providers_path = (Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json")+ # claude-cli drives a local executable and has no HTTP endpoint, so it is+ # the one provider deliberately left out of the fallback map.catalog = {item["name"]: item["default_base_url"]for item in json.loads(providers_path.read_text(encoding="utf-8"))+ if item.get("auth_type") != "claude_cli"}assert _provider_default_base_urls() == catalogdiff --git a/agent/tests/test_llm_reasoning_effort.py b/agent/tests/test_llm_reasoning_effort.pyindex 877c2f9a3..226278b0a 100644--- a/agent/tests/test_llm_reasoning_effort.py+++ b/agent/tests/test_llm_reasoning_effort.py@@ -728,10 +728,11 @@ class TestSettingsAllowlist:"""The settings API admits the explicit 'none' value and says so."""def test_none_is_a_valid_reasoning_effort(self) -> None:- from src.api.settings_routes import LLM_REASONING_EFFORTS+ from src.api.settings_routes import LLM_PROVIDER_BY_NAME- assert "none" in LLM_REASONING_EFFORTS- assert "" in LLM_REASONING_EFFORTS, "empty still means 'leave unset'"+ # Levels are per provider now; every provider without its own list+ # inherits the default one, which keeps the explicit "none".+ assert "none" in LLM_PROVIDER_BY_NAME["openai"].reasoning_effortsdef test_none_persists_through_the_settings_endpoint(self, settings_client: TestClient, settings_env_path: Pathdiff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.pyindex 00a59fc0b..1c1e1aaa8 100644--- a/agent/tests/test_settings_api.py+++ b/agent/tests/test_settings_api.py@@ -83,6 +83,9 @@ def test_extract_model_ids_normalizes_openai_compatible_payloads() -> None:},"oauth_discovery_unsupported",),+ # gh_cli used to build "gh_cli_discovery_unsupported", which the response+ # model rejects; it shares the OAuth code instead.+ ({"provider": "copilot"}, "oauth_discovery_unsupported"),],)def test_model_discovery_returns_stable_warning_codes_not_english_prose(@@ -811,3 +814,102 @@ def test_update_source_orders_rejects_unknown_market(assert response.status_code == 400assert "Unknown market" in response.json()["detail"]assert not (tmp_path / ".env").exists()+++def test_claude_cli_model_list_skips_base_url_checks_and_reports_effort_levels(+ client: TestClient, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from src.providers import claude_cli_models++ observed: dict[str, bool] = {}++ def fake_list(*, refresh: bool = False):+ observed["refresh"] = refresh+ return [+ claude_cli_models.ClaudeCliModel("claude-sonnet-4-6", ("low", "medium", "high", "max")),+ claude_cli_models.ClaudeCliModel("claude-haiku-4-5-20251001", ()),+ ]++ monkeypatch.setattr(claude_cli_models, "list_claude_cli_models", fake_list)+ response = client.post(+ "/settings/llm/models", json={"provider": "claude-cli", "refresh": True}+ )++ assert response.status_code == 200+ body = response.json()+ assert body["models"] == [+ "claude-opus-5-5",+ "claude-sonnet-4-6",+ "claude-haiku-4-5-20251001",+ ]+ assert body["source"] == "provider"+ assert body["effort_levels"] == {+ "claude-sonnet-4-6": ["low", "medium", "high", "max"],+ "claude-haiku-4-5-20251001": [],+ }+ assert observed == {"refresh": True}+++def test_claude_cli_model_list_falls_back_when_cli_is_unavailable(+ client: TestClient, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from src.providers import claude_cli_models++ def failing_list(*, refresh: bool = False):+ raise RuntimeError("claude model list unavailable")++ monkeypatch.setattr(claude_cli_models, "list_claude_cli_models", failing_list)+ response = client.post("/settings/llm/models", json={"provider": "claude-cli"})++ assert response.status_code == 200+ body = response.json()+ assert body["models"] == ["claude-opus-5-5"]+ assert body["warning_code"] == "model_list_unavailable"+ assert body["effort_levels"] is None+++def _llm_update(provider: str, model: str, effort: str) -> dict:+ return {+ "provider": provider,+ "model_name": model,+ "base_url": "",+ "temperature": 0.0,+ "timeout_seconds": 120,+ "max_retries": 2,+ "reasoning_effort": effort,+ }+++ ("effort", "status_code"), [("xhigh", 200), ("", 200), ("none", 400)]+)+def test_claude_cli_effort_is_validated_against_cli_levels(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ effort: str,+ status_code: int,+) -> None:+ from src.providers import claude_cli++ monkeypatch.setattr(claude_cli, "get_claude_cli_auth_status", lambda: (True, "claude.ai"))+ response = client.put(+ "/settings/llm", json=_llm_update("claude-cli", "claude-opus-5-5", effort)+ )++ assert response.status_code == status_code+ if status_code == 200:+ # "" leaves the level unset, so the model's own default applies.+ assert response.json()["reasoning_effort"] == effort+ if effort:+ env_text = (tmp_path / ".env").read_text(encoding="utf-8")+ assert f"LANGCHAIN_REASONING_EFFORT={effort}" in env_text+++def test_other_providers_still_reject_xhigh(client: TestClient) -> None:+ payload = _llm_update("openrouter", "deepseek/deepseek-v4-pro", "xhigh")+ payload["base_url"] = "https://openrouter.ai/api/v1"++ response = client.put("/settings/llm", json=payload)++ assert response.status_code == 400diff --git a/agent/tests/test_swarm_run_metadata.py b/agent/tests/test_swarm_run_metadata.pyindex 7e23bde21..603a5c8a3 100644--- a/agent/tests/test_swarm_run_metadata.py+++ b/agent/tests/test_swarm_run_metadata.py@@ -340,3 +340,11 @@ def test_accepts_other_providers(provider: str, model: str) -> None:run = SwarmRun(**_base_kwargs(), provider=provider, model=model)assert run.provider == providerassert run.model == model+++def test_claude_cli_xhigh_effort_is_public_metadata() -> None:+ """``xhigh`` is a real claude-cli level, so run records must show it."""+ from src.swarm.models import public_reasoning_effort++ assert public_reasoning_effort("xhigh") == "xhigh"+ assert public_reasoning_effort("XHIGH") == "xhigh"diff --git a/frontend/src/components/chat/ModelRuntimeBar.tsx b/frontend/src/components/chat/ModelRuntimeBar.tsxindex e7d1f52d0..22b02f571 100644--- a/frontend/src/components/chat/ModelRuntimeBar.tsx+++ b/frontend/src/components/chat/ModelRuntimeBar.tsx@@ -1,6 +1,7 @@import { Cpu } from "lucide-react";import { useTranslation } from "react-i18next";import type { LLMSettings } from "@/lib/api";+import { effortLabelKey } from "@/lib/reasoningEffort";interface Props {settings: LLMSettings | null;@@ -22,17 +23,11 @@ export function ModelRuntimeBar({const provider = settings.providers.find((item) => item.name === providerId);const providerLabel = provider?.label || providerId || t("agent.unknownProvider");const model = runtimeModel || settings.model_name || t("agent.unknownModel");- const effortLabels: Record<string, string> = {- none: t("settings.reasoningEffortNone"),- low: t("settings.reasoningEffortLow"),- medium: t("settings.reasoningEffortMedium"),- high: t("settings.reasoningEffortHigh"),- max: t("settings.reasoningEffortMax"),- };const reasoningEffort = runtimeReasoningEffort !== undefined? runtimeReasoningEffort: settings.reasoning_effort;- const effortLabel = effortLabels[reasoningEffort] || t("settings.providerDefault");+ const effortKey = effortLabelKey(reasoningEffort);+ const effortLabel = effortKey ? t(effortKey) : t("settings.providerDefault");return (<div className="shrink-0 border-b border-border/70 bg-background/95 px-6 py-2 backdrop-blur-sm">diff --git a/frontend/src/components/chat/__tests__/ModelRuntimeBar.test.tsx b/frontend/src/components/chat/__tests__/ModelRuntimeBar.test.tsxindex 58f09c74d..6dc84fab2 100644--- a/frontend/src/components/chat/__tests__/ModelRuntimeBar.test.tsx+++ b/frontend/src/components/chat/__tests__/ModelRuntimeBar.test.tsx@@ -49,6 +49,19 @@ describe("ModelRuntimeBar", () => {expect(screen.getByText(/Reasoning Effort: None \(explicit\)/)).toBeInTheDocument();});+ it("labels the claude-cli xhigh level instead of falling back to the default", () => {+ render(+ <ModelRuntimeBar+ settings={settings}+ runtimeProvider="claude-cli"+ runtimeModel="claude-opus-5-5"+ runtimeReasoningEffort="xhigh"+ />,+ );++ expect(screen.getByText(/Reasoning Effort: Extra high/)).toBeInTheDocument();+ });+it("shows the persisted historical reasoning effort instead of current settings", () => {render(<ModelRuntimeBardiff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 32141ef88..9b7459059 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -454,8 +454,10 @@"reasoningEffortLow": "منخفض","reasoningEffortMedium": "متوسط","reasoningEffortHigh": "مرتفع",+ "reasoningEffortXhigh": "مرتفع جدًا","reasoningEffortMax": "أقصى","reasoningEffortDesc": "يتحكم في عمق الاستدلال للنماذج المدعومة. قد تحسن القيم الأعلى التحليل المعقد لكنها تستغرق وقتًا أطول، وقد يتجاهلها المزوّد غير المدعوم. يرسل «بدون (صريح)» الحقل مع تعطيل الاستدلال، وبعض طرازات OpenAI تحتاج ذلك لاستخدام الأدوات.",+ "reasoningEffortReset": "النموذج المحدد لا يدعم {{level}}؛ تمت إعادته إلى الإعداد الافتراضي للمزوّد.","localApiAccess": "الوصول إلى API المحلي","localApiAccessDesc": "لعمليات نشر واجهة الويب عن بُعد أو الخاصة، أدخل مفتاح API الخادم مرة واحدة في هذا المتصفح. يمكن ترك الاستخدام المحلي فارغًا.","serverApiKey": "مفتاح API الخادم",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex ccad464a3..ac3dfbfb4 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -443,8 +443,10 @@"reasoningEffortLow": "Niedrig","reasoningEffortMedium": "Mittel","reasoningEffortHigh": "Hoch",+ "reasoningEffortXhigh": "Sehr hoch","reasoningEffortMax": "Maximal","reasoningEffortDesc": "Steuert die Reasoning-Tiefe bei unterstützten Modellen. Höhere Stufen können die komplexe Analyse verbessern, dauern aber länger; nicht unterstützte Anbieter ignorieren diese Einstellung möglicherweise. Keine (explizit) sendet das Feld mit deaktiviertem Reasoning — einige OpenAI-Modelle benötigen dies, um Tools zu verwenden.",+ "reasoningEffortReset": "Das gewählte Modell unterstützt {{level}} nicht; auf den Anbieter-Standard zurückgesetzt.","useDefaultModel": "Standardmodell verwenden","useDefaultUrl": "Standard-URL verwenden","dataSourcesDesc": "Konfigurieren Sie externe Datenquellen für die Backtesting-Engine.",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 3e98865da..2f1bbc6d6 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -443,8 +443,10 @@"reasoningEffortLow": "Low","reasoningEffortMedium": "Medium","reasoningEffortHigh": "High",+ "reasoningEffortXhigh": "Extra high","reasoningEffortMax": "Max","reasoningEffortDesc": "Controls reasoning depth on supported models. Higher levels may improve complex analysis but can take longer; unsupported providers may ignore this setting. None (explicit) sends the field with reasoning disabled — some OpenAI models need that to use tools.",+ "reasoningEffortReset": "The selected model does not support {{level}}; reset to provider default.","useDefaultModel": "Use default model","useDefaultUrl": "Use default URL","dataSourcesDesc": "Configure external data sources for the backtesting engine.",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex db4ea1b0a..1e8568b2f 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -443,8 +443,10 @@"reasoningEffortLow": "Bajo","reasoningEffortMedium": "Medio","reasoningEffortHigh": "Alto",+ "reasoningEffortXhigh": "Muy alto","reasoningEffortMax": "Máximo","reasoningEffortDesc": "Controla la profundidad de razonamiento en modelos compatibles. Niveles más altos pueden mejorar el análisis complejo pero tardar más; proveedores no compatibles pueden ignorar esta opción. \"Ninguno (explícito)\" envía el campo con el razonamiento desactivado — algunos modelos de OpenAI lo necesitan para usar herramientas.",+ "reasoningEffortReset": "El modelo seleccionado no admite {{level}}; se restableció el valor predeterminado del proveedor.","useDefaultModel": "Usar modelo predeterminado","useDefaultUrl": "Usar URL predeterminada","dataSourcesDesc": "Configura fuentes de datos externas para el motor de backtesting.",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex f39f876d6..d7b114893 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -443,8 +443,10 @@"reasoningEffortLow": "Rendah","reasoningEffortMedium": "Sedang","reasoningEffortHigh": "Tinggi",+ "reasoningEffortXhigh": "Sangat tinggi","reasoningEffortMax": "Maksimum","reasoningEffortDesc": "Mengatur kedalaman reasoning pada model yang mendukung. Tingkat yang lebih tinggi dapat meningkatkan analisis kompleks tetapi bisa membutuhkan waktu lebih lama; provider yang tidak mendukung dapat mengabaikan pengaturan ini. Tidak ada (eksplisit) mengirim field dengan reasoning dinonaktifkan — beberapa model OpenAI memerlukannya agar dapat menggunakan tool.",+ "reasoningEffortReset": "Model yang dipilih tidak mendukung {{level}}; dikembalikan ke Provider bawaan.","useDefaultModel": "Gunakan model default","useDefaultUrl": "Gunakan URL default","dataSourcesDesc": "Konfigurasikan sumber data eksternal untuk engine backtest.",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 4d5772441..0d1de6817 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -454,8 +454,10 @@"reasoningEffortLow": "低","reasoningEffortMedium": "中","reasoningEffortHigh": "高",+ "reasoningEffortXhigh": "超高","reasoningEffortMax": "最大","reasoningEffortDesc": "対応モデルの推論の深さを調整します。高いほど複雑な分析に有効な場合がありますが、時間がかかります。未対応のプロバイダーでは無視されることがあります。「なし(明示)」は推論を無効にしたままフィールドを明示送信し、一部の OpenAI モデルはツール利用時にこれが必要です。",+ "reasoningEffortReset": "選択したモデルは {{level}} に対応していないため、プロバイダーのデフォルトに戻しました。","localApiAccess": "ローカル API アクセス","localApiAccessDesc": "リモートまたはプライベート Web UI デプロイメントの場合、ブラウザにサーバー API キーを一度入力してください。ローカルホストは空欄のままで構いません。","serverApiKey": "サーバー API キー",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 6c556b993..a995bdfee 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -454,8 +454,10 @@"reasoningEffortLow": "낮음","reasoningEffortMedium": "중간","reasoningEffortHigh": "높음",+ "reasoningEffortXhigh": "매우 높음","reasoningEffortMax": "최대","reasoningEffortDesc": "지원되는 모델의 추론 깊이를 조절합니다. 높을수록 복잡한 분석에 도움이 될 수 있지만 더 오래 걸리며, 지원하지 않는 제공자는 이 설정을 무시할 수 있습니다. '없음(명시)'은 추론을 끈 상태로 필드를 명시적으로 전송하며, 일부 OpenAI 모델은 도구를 사용할 때 이 값이 필요합니다.",+ "reasoningEffortReset": "선택한 모델은 {{level}}을(를) 지원하지 않아 제공자 기본값으로 되돌렸습니다.","localApiAccess": "로컬 API 액세스","localApiAccessDesc": "원격 또는 비공개 Web UI 배포의 경우, 브라우저에 서버 API 키를 한 번 입력하세요. 로컬호스트는 비워둬도 됩니다.","serverApiKey": "서버 API 키",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex c75d52495..23c79aa62 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -443,8 +443,10 @@"reasoningEffortLow": "Baixo","reasoningEffortMedium": "Médio","reasoningEffortHigh": "Alto",+ "reasoningEffortXhigh": "Muito alto","reasoningEffortMax": "Máx.","reasoningEffortDesc": "Controla a profundidade do raciocínio nos modelos suportados. Níveis mais elevados podem melhorar análises complexas, mas podem demorar mais; provedores não suportados podem ignorar esta configuração. Nenhum (explícito) envia o campo com o raciocínio desabilitado — alguns modelos OpenAI precisam disso para usar ferramentas.",+ "reasoningEffortReset": "O modelo selecionado não suporta {{level}}; redefinido para o padrão do provedor.","useDefaultModel": "Usar modelo padrão","useDefaultUrl": "Usar URL padrão","dataSourcesDesc": "Configure fontes de dados externas para o mecanismo de backtesting.",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex e18abd8b0..639fa2744 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -454,8 +454,10 @@"reasoningEffortLow": "低","reasoningEffortMedium": "中","reasoningEffortHigh": "高",+ "reasoningEffortXhigh": "超高","reasoningEffortMax": "最大","reasoningEffortDesc": "控制支持该功能的模型所使用的推理深度。强度越高,复杂分析可能更充分,但耗时也可能更长;不支持的提供商可能会忽略此设置。选择「无(显式)」会显式发送该字段并关闭推理——部分 OpenAI 模型需要这样才能调用工具。",+ "reasoningEffortReset": "所选模型不支持 {{level}},已改回提供商默认。","localApiAccess": "本地 API 访问","localApiAccessDesc": "对远程或专用 Web UI 部署,请在浏览器中输入一次服务器 API 密钥。本地主机(localhost)使用可保持为空。","serverApiKey": "服务器 API 密钥",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 50b1878dc..78cbae398 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -846,6 +846,8 @@ export interface LLMProviderOption {api_key_required: boolean;auth_type?: string;login_command?: string | null;+ /** Reasoning effort levels the provider accepts, besides "" (provider default). */+ reasoning_efforts?: string[];}export interface LLMSettings {@@ -881,6 +883,7 @@ export interface ListLLMModelsRequest {provider: string;base_url?: string;api_key?: string;+ refresh?: boolean;}export interface LLMModelsResponse {@@ -892,6 +895,8 @@ export interface LLMModelsResponse {| "api_key_required"| "model_list_unavailable"| null;+ /** Model id -> reasoning effort levels it accepts; empty means none. */+ effort_levels?: Record<string, string[]> | null;}export interface SourceOrderEntry {diff --git a/frontend/src/lib/reasoningEffort.ts b/frontend/src/lib/reasoningEffort.tsnew file mode 100644index 000000000..5d18ed342--- /dev/null+++ b/frontend/src/lib/reasoningEffort.ts@@ -0,0 +1,13 @@+// i18n key for each reasoning effort level; a level missing here has no label.+export const EFFORT_LABEL_KEYS = {+ none: "settings.reasoningEffortNone",+ low: "settings.reasoningEffortLow",+ medium: "settings.reasoningEffortMedium",+ high: "settings.reasoningEffortHigh",+ xhigh: "settings.reasoningEffortXhigh",+ max: "settings.reasoningEffortMax",+} as const;++export function effortLabelKey(level: string) {+ return EFFORT_LABEL_KEYS[level as keyof typeof EFFORT_LABEL_KEYS];+}diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex a4fa09d60..309d585f1 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState, type FormEvent } from "react";+import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";import { Database, KeyRound, Loader2, RefreshCw, RotateCcw, Save, Server, SlidersHorizontal } from "lucide-react";import { useTranslation } from "react-i18next";import { toast } from "sonner";@@ -8,6 +8,7 @@ import { QVerisSettings } from "@/components/settings/QVerisSettings"; // QVERISimport { SourcePrioritySettings } from "@/components/settings/SourcePrioritySettings";import { api, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";+import { effortLabelKey } from "@/lib/reasoningEffort";interface LLMFormState {provider: string;@@ -46,6 +47,7 @@ export function Settings() {const [modelOptions, setModelOptions] = useState<string[]>([]);const [modelsLoading, setModelsLoading] = useState(false);const [modelListHint, setModelListHint] = useState<string | null>(null);+ const [effortLevelsByModel, setEffortLevelsByModel] = useState<Record<string, string[]> | null>(null);const [localApiKey, setLocalApiKeyState] = useState(() => getApiAuthKey());const [clearApiKey, setClearApiKey] = useState(false);const [tushareToken, setTushareToken] = useState("");@@ -139,10 +141,17 @@ export function Settings() {setClearApiKey(false);setModelOptions([provider.default_model]);setModelListHint(null);+ setEffortLevelsByModel(null);};- const refreshModels = async () => {+ // The provider the form shows now; a model list answering for an earlier one+ // (the CLI can take seconds) must not overwrite the current options.+ const currentProviderRef = useRef(form?.provider);+ currentProviderRef.current = form?.provider;++ const refreshModels = async ({ refresh }: { refresh: boolean }) => {if (!form || !selectedProvider) return;+ const requestedProvider = form.provider;setModelsLoading(true);setModelListHint(null);try {@@ -150,12 +159,15 @@ export function Settings() {provider: form.provider,base_url: form.base_url,api_key: apiKey.trim() || undefined,+ refresh,});+ if (currentProviderRef.current !== requestedProvider) return;setModelOptions(Array.from(new Set([form.model_name,selectedProvider.default_model,...result.models,].filter(Boolean))));+ setEffortLevelsByModel(result.effort_levels ?? null);const warningMessages = {oauth_discovery_unsupported: t("settings.modelDiscoveryOauthUnsupported"),api_key_required: t("settings.modelDiscoveryApiKeyRequired"),@@ -167,12 +179,33 @@ export function Settings() {: t("settings.modelsLoaded", { count: result.models.length }),);} catch (error) {+ if (currentProviderRef.current !== requestedProvider) return;setModelListHint(error instanceof Error ? error.message : t("settings.modelsLoadFailed"));} finally {setModelsLoading(false);}};+ // The CLI reports which models the login can run and the levels each accepts,+ // so fetch that as soon as the provider is shown rather than on a button press.+ const isClaudeCli = selectedProvider?.auth_type === "claude_cli";+ useEffect(() => {+ if (isClaudeCli) void refreshModels({ refresh: false });+ // refreshModels reads the form at call time; re-run only when the provider changes.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isClaudeCli]);++ // A model's own levels when the provider reports them, else the provider's.+ const visibleEffortLevels =+ (form && effortLevelsByModel?.[form.model_name]) ?? selectedProvider?.reasoning_efforts ?? [];+ // A level the selected model does not accept would be saved but never take+ // effect, so it is shown and saved as the provider default, with the reason.+ const unsupportedEffort =+ form?.reasoning_effort && !visibleEffortLevels.includes(form.reasoning_effort)+ ? form.reasoning_effort+ : null;+ const unsupportedEffortKey = unsupportedEffort ? effortLabelKey(unsupportedEffort) : undefined;+const submitLocalApiKey = (event: FormEvent) => {event.preventDefault();setApiAuthKey(localApiKey);@@ -188,6 +221,7 @@ export function Settings() {const desktop = window.vibeDesktop;const updated = await api.updateLLMSettings({...form,+ reasoning_effort: unsupportedEffort ? "" : form.reasoning_effort,api_key: isDesktop ? undefined : apiKey.trim() || undefined,clear_api_key: isDesktop ? false : clearApiKey,});@@ -398,7 +432,7 @@ export function Settings() {/><buttontype="button"- onClick={() => void refreshModels()}+ onClick={() => void refreshModels({ refresh: true })}disabled={modelsLoading}className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"title={t("settings.loadModels")}@@ -529,18 +563,28 @@ export function Settings() {<label className="grid gap-2"><span className={labelClass}>{t("settings.reasoningEffort")}</span><select- value={form.reasoning_effort}+ value={unsupportedEffort ? "" : form.reasoning_effort}onChange={(event) => setForm({ ...form, reasoning_effort: event.target.value })}className={fieldClass}><option value="">{t("settings.providerDefault")}</option>- <option value="none">{t("settings.reasoningEffortNone")}</option>- <option value="low">{t("settings.reasoningEffortLow")}</option>- <option value="medium">{t("settings.reasoningEffortMedium")}</option>- <option value="high">{t("settings.reasoningEffortHigh")}</option>- <option value="max">{t("settings.reasoningEffortMax")}</option>+ {visibleEffortLevels.map((level) => {+ const labelKey = effortLabelKey(level);+ return (+ <option key={level} value={level}>+ {labelKey ? t(labelKey) : level}+ </option>+ );+ })}</select><span className={hintClass}>{t("settings.reasoningEffortDesc")}</span>+ {unsupportedEffort && (+ <span className={hintClass}>+ {t("settings.reasoningEffortReset", {+ level: unsupportedEffortKey ? t(unsupportedEffortKey) : unsupportedEffort,+ })}+ </span>+ )}</label><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">diff --git a/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsx b/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsxnew file mode 100644index 000000000..b9c81267d--- /dev/null+++ b/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsx@@ -0,0 +1,185 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { Settings } from "../Settings";++const apiMock = vi.hoisted(() => ({+ getLLMSettings: vi.fn(),+ getDataSourceSettings: vi.fn(),+ listLLMModels: vi.fn(),+ updateLLMSettings: vi.fn(),+ updateDataSourceSettings: vi.fn(),+}));++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return {+ ...actual,+ api: apiMock,+ isAuthRequiredError: vi.fn(() => false),+ };+});++vi.mock("@/lib/apiAuth", () => ({+ getApiAuthKey: vi.fn(() => ""),+ setApiAuthKey: vi.fn(),+}));++vi.mock("@/components/settings/ChannelSettings", () => ({ ChannelSettings: () => null }));+vi.mock("@/components/settings/QVerisSettings", () => ({ QVerisSettings: () => null }));+vi.mock("@/components/settings/SourcePrioritySettings", () => ({+ SourcePrioritySettings: () => null,+}));++const providers = [+ {+ name: "claude-cli",+ label: "Claude Code CLI (local login)",+ api_key_env: null,+ base_url_env: "CLAUDE_CLI_BASE_URL",+ default_model: "claude-opus-5-5",+ default_base_url: "",+ api_key_required: false,+ auth_type: "claude_cli",+ reasoning_efforts: ["low", "medium", "high", "xhigh", "max"],+ },+ {+ name: "openrouter",+ label: "OpenRouter",+ api_key_env: "OPENROUTER_API_KEY",+ base_url_env: "OPENROUTER_BASE_URL",+ default_model: "deepseek/deepseek-v3.2",+ default_base_url: "https://openrouter.ai/api/v1",+ api_key_required: true,+ auth_type: "api_key",+ reasoning_efforts: ["none", "low", "medium", "high", "max"],+ },+];++function llmSettings(overrides = {}) {+ return {+ provider: "claude-cli",+ model_name: "claude-opus-5-5",+ base_url: "",+ api_key_env: null,+ api_key_configured: true,+ api_key_required: false,+ temperature: 0,+ timeout_seconds: 120,+ max_retries: 2,+ reasoning_effort: "",+ sse_timeout_seconds: 300,+ env_path: "agent/.env",+ providers,+ ...overrides,+ };+}++const modelList = {+ provider: "claude-cli",+ models: ["claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"],+ source: "provider",+ warning_code: null,+ effort_levels: {+ "claude-opus-5-5": ["low", "medium", "high", "xhigh", "max"],+ "claude-sonnet-4-6": ["low", "medium", "high", "max"],+ "claude-haiku-4-5-20251001": [],+ },+};++function effortSelect(): HTMLSelectElement {+ return screen.getByText("Reasoning Effort").closest("label")!.querySelector("select")!;+}++function effortOptions(): string[] {+ return Array.from(effortSelect().options).map((option) => option.value);+}++describe("Settings with the claude-cli provider", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ apiMock.getDataSourceSettings.mockResolvedValue({+ tushare_token_configured: false,+ baostock_supported: true,+ baostock_installed: true,+ baostock_message: "BaoStock available",+ env_path: "agent/.env",+ });+ apiMock.listLLMModels.mockResolvedValue(modelList);+ });++ it("loads the CLI model list on open and offers the selected model's levels", async () => {+ apiMock.getLLMSettings.mockResolvedValue(llmSettings());+ render(<Settings />);++ await waitFor(() =>+ expect(apiMock.listLLMModels).toHaveBeenCalledWith(+ expect.objectContaining({ provider: "claude-cli", refresh: false }),+ ),+ );+ await waitFor(() => expect(effortOptions()).toContain("xhigh"));+ expect(effortOptions()).toEqual(["", "low", "medium", "high", "xhigh", "max"]);+ });++ it("narrows the levels when a model without them is picked", async () => {+ apiMock.getLLMSettings.mockResolvedValue(llmSettings());+ render(<Settings />);+ await waitFor(() => expect(effortOptions()).toContain("xhigh"));++ fireEvent.change(screen.getByRole("combobox", { name: "Model" }), {+ target: { value: "claude-haiku-4-5-20251001" },+ });++ expect(effortOptions()).toEqual([""]);+ });++ it("resets a level the selected model does not accept and says why", async () => {+ apiMock.getLLMSettings.mockResolvedValue(+ llmSettings({ model_name: "claude-sonnet-4-6", reasoning_effort: "xhigh" }),+ );+ render(<Settings />);++ // The hint appears once the model list says sonnet-4-6 has no xhigh.+ // The hint names the level by its label, as the menu does, not by its id.+ expect(await screen.findByText(/does not support Extra high/)).toBeInTheDocument();+ expect(effortSelect().value).toBe("");+ expect(effortOptions()).not.toContain("xhigh");++ apiMock.updateLLMSettings.mockResolvedValue(llmSettings({ model_name: "claude-sonnet-4-6" }));+ fireEvent.click(effortSelect().closest("form")!.querySelector('button[type="submit"]')!);+ await waitFor(() =>+ expect(apiMock.updateLLMSettings).toHaveBeenCalledWith(+ expect.objectContaining({ reasoning_effort: "" }),+ ),+ );+ });++ it("drops a model list that arrives after the provider was switched", async () => {+ let answer: (value: typeof modelList) => void = () => {};+ apiMock.listLLMModels.mockReturnValue(new Promise((resolve) => { answer = resolve; }));+ apiMock.getLLMSettings.mockResolvedValue(llmSettings());+ render(<Settings />);+ await waitFor(() => expect(apiMock.listLLMModels).toHaveBeenCalled());++ fireEvent.change(screen.getByDisplayValue("Claude Code CLI (local login)"), {+ target: { value: "openrouter" },+ });+ answer(modelList);+ await new Promise((resolve) => setTimeout(resolve, 0));++ fireEvent.click(screen.getByRole("combobox", { name: "Model" }));+ expect(screen.queryByText("claude-sonnet-4-6")).not.toBeInTheDocument();+ });++ it("keeps the existing levels and makes no request for other providers", async () => {+ apiMock.getLLMSettings.mockResolvedValue(+ llmSettings({+ provider: "openrouter",+ model_name: "deepseek/deepseek-v3.2",+ base_url: "https://openrouter.ai/api/v1",+ }),+ );+ render(<Settings />);++ await waitFor(() => expect(effortOptions()).toEqual(["", "none", "low", "medium", "high", "max"]));+ expect(apiMock.listLLMModels).not.toHaveBeenCalled();+ });+});