JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix (harness): improve search tool, disable free search engines by default
m05683870008e99353dda7
diff --git a/docs/en/Configuration.md b/docs/en/Configuration.mdindex 842507334b..925145b579 100644--- a/docs/en/Configuration.md+++ b/docs/en/Configuration.md@@ -30,7 +30,7 @@ These can be changed in the web app; values are written back to `.env` or config| `serper_api_key` | `SERPER_API_KEY` | Serper search API key || `perplexity_api_key` | `PERPLEXITY_API_KEY` | Perplexity API key || `github_token` | `GITHUB_TOKEN` | GitHub PAT; SkillNet search/install uses the GitHub API |-| `free_search_proxy_url` | `FREE_SEARCH_PROXY_URL` | Optional HTTP/HTTPS proxy for free search and webpage fetch, for example `http://username:[email protected]:8080` |+| `free_search_proxy_url` | `FREE_SEARCH_PROXY_URL` | Optional HTTP/HTTPS proxy for free search, webpage fetch, and SkillNet network requests. The UI asks for username/password and stores `http://username:[email protected]:8080`. || `evolution_auto_scan` | `EVOLUTION_AUTO_SCAN` | Auto-scan evolvable skills after each turn (`true`/`false`) |**Note**: After saving, the backend restarts to load new settings. Model fields (`api_base`, `api_key`, `model`, `model_provider`) are required.diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex db1a36fc49..89d655d36a 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -65,6 +65,25 @@ from openjiuwen.harness.tools import (create_audio_tools,create_vision_tools,)+try:+ from openjiuwen.harness.tools import is_paid_search_enabled+except ImportError: # Compatibility with older agent-core versions.+ try:+ from openjiuwen.harness.tools.web_tools import is_paid_search_enabled+ except ImportError:++ def is_paid_search_enabled() -> bool:+ api_key_envs = (+ "BOCHA_API_KEY",+ "PERPLEXITY_API_KEY",+ "SERPER_API_KEY",+ "JINA_API_KEY",+ )+ for key in api_key_envs:+ if str(os.environ.get(key, "") or "").strip():+ return True+ return False+from openjiuwen.harness.schema.task import TodoStatusfrom openjiuwen.harness.tools.todo import TodoModifyToolfrom openjiuwen.harness.workspace.workspace import Workspace, WorkspaceNode@@ -143,9 +162,11 @@ from jiuwenclaw.utils import (get_agent_workspace_dir,get_checkpoint_dir,get_env_file,+ reset_free_search_runtime_flags,)load_dotenv(dotenv_path=get_env_file())+reset_free_search_runtime_flags()_react_config = get_config().get("react", {})_sandbox_config = get_config().get("sandbox", {})@@ -776,6 +797,29 @@ class JiuWenClawDeepAdapter:if card.name not in existing_names:self._tool_cards.append(card)+ def _prioritize_paid_search_tool_card(self) -> None:+ """Keep paid_search before free_search when both cards are present."""+ if not self._tool_cards:+ return+ paid_cards = [+ item for item in self._tool_cards+ if (item.card.name if hasattr(item, "card") else item.name) == "paid_search"+ ]+ if not paid_cards:+ return+ remaining_cards = [+ item for item in self._tool_cards+ if (item.card.name if hasattr(item, "card") else item.name) != "paid_search"+ ]+ free_index = next(+ (+ idx for idx, item in enumerate(remaining_cards)+ if (item.card.name if hasattr(item, "card") else item.name) == "free_search"+ ),+ 0,+ )+ self._tool_cards = remaining_cards[:free_index] + paid_cards + remaining_cards[free_index:]+def _prune_tool_cards(self, tool_names: set[str]) -> None:"""Remove tracked tool cards by tool name."""if not self._tool_cards:@@ -833,14 +877,13 @@ class JiuWenClawDeepAdapter:tools, self._paid_search_registered = self._sync_tool_group(current_tools=[self._paid_search_tool] if self._paid_search_tool else [],registered=self._paid_search_registered,- enabled=any(- os.environ.get(key)- for key in ("BOCHA_API_KEY", "PERPLEXITY_API_KEY", "SERPER_API_KEY", "JINA_API_KEY")- ),+ enabled=is_paid_search_enabled(),create_fn=lambda: [WebPaidSearchTool(language=self._resolve_runtime_language(), agent_id=agent_id)],warn_label="paid search tool",)self._paid_search_tool = tools[0] if tools else None+ if self._paid_search_tool is not None:+ self._prioritize_paid_search_tool_card()@staticmethodasync def set_checkpoint():@@ -1373,21 +1416,18 @@ class JiuWenClawDeepAdapter:"""Get tool cards."""tool_cards = []- for tool_cls in [WebFreeSearchTool, WebFetchWebpageTool]:- tool_instance = tool_cls(agent_id=agent_id)- Runner.resource_mgr.add_tool(tool_instance)- tool_cards.append(tool_instance.card)-# 付费搜索工具:有任意一个付费 key 就注册- if any(- os.environ.get(key)- for key in ("BOCHA_API_KEY", "PERPLEXITY_API_KEY", "SERPER_API_KEY", "JINA_API_KEY")- ):+ if is_paid_search_enabled():self._paid_search_tool = WebPaidSearchTool(language=self._resolve_runtime_language(), agent_id=agent_id)Runner.resource_mgr.add_tool(self._paid_search_tool)tool_cards.append(self._paid_search_tool.card)self._paid_search_registered = True+ for tool_cls in [WebFreeSearchTool, WebFetchWebpageTool]:+ tool_instance = tool_cls(agent_id=agent_id)+ Runner.resource_mgr.add_tool(tool_instance)+ tool_cards.append(tool_instance.card)+self._vision_tools = []self._vision_tools_registered = Falseif self._vision_model_config is not None:diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.pyindex 0b2923ac05..a117e1aabb 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py@@ -49,6 +49,7 @@ class RuntimePromptRail(DeepAgentRail):if self.system_prompt_builder is not None:self.system_prompt_builder.remove_section("time")self.system_prompt_builder.remove_section("runtime")+ self.system_prompt_builder.remove_section("browser_tool_policy")self.system_prompt_builder = Nonedef set_language(self, language: str) -> None:@@ -145,3 +146,22 @@ class RuntimePromptRail(DeepAgentRail):content={"cn": runtime_content, "en": runtime_content},priority=95,))++ self.system_prompt_builder.remove_section("browser_tool_policy")+ if self._channel == "web":+ browser_tool_policy = (+ "# Browser Tool Policy\n\n"+ "- For browser tasks such as opening pages, navigation, clicking, typing, login, screenshots, "+ "page inspection, or extracting data from a live website, use `task_tool` with "+ '`subagent_type` set to `"browser_agent"` and put the full browser objective in '+ "`task_description`.\n"+ "- Do not use bash, execute_code, subprocess, shell commands, or direct Chrome/Edge launches "+ "for browser automation.\n"+ "- If `task_tool` or `browser_agent` is unavailable, say that the browser subagent is unavailable "+ "before trying to start a browser through commands."+ )+ self.system_prompt_builder.add_section(PromptSection(+ name="browser_tool_policy",+ content={"cn": browser_tool_policy, "en": browser_tool_policy},+ priority=98,+ ))diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 955769b2a4..b6497ecb73 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -34,9 +34,15 @@ from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChfrom jiuwenclaw.schema.hook_event import AgentServerHookEventsfrom jiuwenclaw.schema.hooks_context import MemoryHookContextfrom jiuwenclaw.schema.message import EventType, ReqMethod-from jiuwenclaw.utils import get_agent_home_dir, get_agent_workspace_dir, get_env_file+from jiuwenclaw.utils import (+ get_agent_home_dir,+ get_agent_workspace_dir,+ get_env_file,+ reset_free_search_runtime_flags,+)load_dotenv(dotenv_path=get_env_file())+reset_free_search_runtime_flags()logger = logging.getLogger(__name__)diff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.pyindex e6978f1353..9b3e71cd54 100644--- a/jiuwenclaw/agentserver/skill_manager.py+++ b/jiuwenclaw/agentserver/skill_manager.py@@ -12,11 +12,13 @@ import reimport shutilimport tempfileimport uuid+from contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Awaitable, Callablefrom urllib.parse import urlparseimport yaml+import urllib3from jiuwenclaw.utils import (get_agent_root_dir,get_agent_skills_dir,@@ -29,6 +31,20 @@ logger = logging.getLogger(__name__)_SKILLNET_DOWNLOAD_TIMEOUT: int = int(os.environ.get("SKILLNET_DOWNLOAD_TIMEOUT", "60"))_SKILLNET_MAX_RETRIES: int = int(os.environ.get("SKILLNET_MAX_RETRIES", "3"))+_FREE_SEARCH_PROXY_URL_ENV = "FREE_SEARCH_PROXY_URL"+_FREE_SEARCH_SSL_VERIFY_ENV = "FREE_SEARCH_SSL_VERIFY"+_SKILLNET_PROXY_ENV_KEYS = (+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "http_proxy",+ "https_proxy",+ "all_proxy",+)+_SKILLNET_NO_PROXY_ENV_KEYS = ("NO_PROXY", "no_proxy")+_FREE_SEARCH_DEFAULT_NO_PROXY = (+ "127.0.0.1,.huawei.com,localhost,local,.local,10.155.97.247,.myhuaweicloud.com"+)# ---------------------------------------------------------------------------@@ -74,6 +90,66 @@ def _is_valid_http_mirror_url(url: str) -> bool:return True+def _env_bool(name: str, default: bool = True) -> bool:+ raw = str(os.environ.get(name, "") or "").strip().lower()+ if not raw:+ return default+ return raw in {"1", "true", "yes", "on", "enabled"}+++def _get_free_search_proxy_url() -> str:+ return str(os.environ.get(_FREE_SEARCH_PROXY_URL_ENV, "") or "").strip()+++def _free_search_ssl_verify() -> bool:+ return _env_bool(_FREE_SEARCH_SSL_VERIFY_ENV, default=False)+++def _disable_insecure_request_warning() -> None:+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)+++def _skillnet_proxy_mapping() -> dict[str, str]:+ proxy_url = _get_free_search_proxy_url()+ if not proxy_url:+ return {}+ return {"http": proxy_url, "https": proxy_url}+++def _configure_skillnet_requests_session(session: Any) -> None:+ proxies = _skillnet_proxy_mapping()+ if proxies:+ session.proxies.update(proxies)+ verify = _free_search_ssl_verify()+ session.verify = verify+ if verify is False:+ _disable_insecure_request_warning()+++@contextmanager+def _skillnet_network_context():+ """Expose the configured proxy to third-party SkillNet clients during one call."""+ proxy_url = _get_free_search_proxy_url()+ env_keys = (*_SKILLNET_PROXY_ENV_KEYS, *_SKILLNET_NO_PROXY_ENV_KEYS)+ previous = {key: os.environ.get(key) for key in env_keys}+ try:+ if proxy_url:+ for key in _SKILLNET_PROXY_ENV_KEYS:+ os.environ[key] = proxy_url+ if not os.environ.get("NO_PROXY") and not os.environ.get("no_proxy"):+ for key in _SKILLNET_NO_PROXY_ENV_KEYS:+ os.environ[key] = _FREE_SEARCH_DEFAULT_NO_PROXY+ if _free_search_ssl_verify() is False:+ _disable_insecure_request_warning()+ yield+ finally:+ for key, value in previous.items():+ if value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value++def _safe_rmtree(path: Path) -> bool:"""安全地删除目录树,处理 Windows 上的 git 文件锁定问题."""@@ -1856,8 +1932,9 @@ class SkillManager:"github_token": SkillManager._get_github_token() or None,}try:- client = SkillNetClient(**kwargs)- result = client.evaluate(target=skill_url, model=str(llm["model"]))+ with _skillnet_network_context():+ client = SkillNetClient(**kwargs)+ result = client.evaluate(target=skill_url, model=str(llm["model"]))except SkillNetError as exc:return {"ok": False, "detail": str(exc).strip() or "评估失败。"}except Exception as exc:@@ -1872,14 +1949,16 @@ class SkillManager:def _skillnet_search_sync(search_kwargs: dict[str, Any]) -> list[Any]:"""同步调用 skillnet-ai search,供 asyncio.to_thread 使用."""try:- from skillnet_ai import SkillNetClient+ from skillnet_ai.searcher import SkillNetSearcherexcept Exception as exc:raise RuntimeError("未安装 skillnet-ai,请先安装依赖: pip install skillnet-ai") from exc- client = SkillNetClient(github_token=SkillManager._get_github_token())- results = client.search(**search_kwargs)+ with _skillnet_network_context():+ searcher = SkillNetSearcher()+ _configure_skillnet_requests_session(searcher.session)+ results = searcher.search(**search_kwargs)if results is None:return []if isinstance(results, list):@@ -1895,6 +1974,7 @@ class SkillManager:return ""dl = SkillDownloader(api_token=SkillManager._get_github_token())+ _configure_skillnet_requests_session(dl.session)parsed = dl._parse_github_url(skill_url)if not parsed:return ""@@ -1902,7 +1982,8 @@ class SkillManager:owner, repo, ref, dir_path, _ = parsedapi = f"https://api.github.com/repos/{owner}/{repo}/contents/{dir_path}?ref={ref}"try:- r = dl.session.get(api, timeout=_SKILLNET_DOWNLOAD_TIMEOUT)+ with _skillnet_network_context():+ r = dl.session.get(api, timeout=_SKILLNET_DOWNLOAD_TIMEOUT)except Exception as exc:logger.debug("SkillNet 安装错误上下文: GitHub Contents 请求失败: %s", exc@@ -1932,7 +2013,8 @@ class SkillManager:"rate limit" in p.lower() for p in parts):try:- rl = dl.session.get("https://api.github.com/rate_limit", timeout=12)+ with _skillnet_network_context():+ rl = dl.session.get("https://api.github.com/rate_limit", timeout=12)if rl.status_code == 200:core = rl.json().get("resources", {}).get("core") or {}rem, lim = core.get("remaining"), core.get("limit")@@ -1969,17 +2051,18 @@ class SkillManager:}if mirror_url:dl_kwargs["mirror_url"] = mirror_url- downloader = SkillDownloader(**dl_kwargs)-- try:- local_path = downloader.download(folder_url=skill_url, target_dir=target_dir)- except GitHubAPIError:- raise- except Exception as exc:- ctx = SkillManager._github_skillnet_install_error_context(skill_url)- if ctx:- raise RuntimeError(f"{exc} | {ctx}") from exc- raise+ with _skillnet_network_context():+ downloader = SkillDownloader(**dl_kwargs)+ _configure_skillnet_requests_session(downloader.session)+ try:+ local_path = downloader.download(folder_url=skill_url, target_dir=target_dir)+ except GitHubAPIError:+ raise+ except Exception as exc:+ ctx = SkillManager._github_skillnet_install_error_context(skill_url)+ if ctx:+ raise RuntimeError(f"{exc} | {ctx}") from exc+ raiseif not local_path:# skillnet-ai 在多种情况下会无异常地返回 None:URL 无效、目录下列表为空、# 或 Contents API 成功但拉 raw 文件全部失败(超时/网络)等,库未区分原因。diff --git a/jiuwenclaw/agentserver/tools/mcp_toolkits.py b/jiuwenclaw/agentserver/tools/mcp_toolkits.pyindex f634ccb2a4..1f486377ba 100644--- a/jiuwenclaw/agentserver/tools/mcp_toolkits.py+++ b/jiuwenclaw/agentserver/tools/mcp_toolkits.py@@ -22,11 +22,27 @@ def _has_paid_search_api_key() -> bool:])+def _env_flag(name: str, default: bool = False) -> bool:+ raw = str(os.environ.get(name, "") or "").strip().lower()+ if not raw:+ return default+ return raw in {"1", "true", "yes", "on", "enabled"}+++def _is_free_search_enabled() -> bool:+ return (+ _env_flag("FREE_SEARCH_DDG_ENABLED", default=False)+ or _env_flag("FREE_SEARCH_BING_ENABLED", default=False)+ )++def get_mcp_tools() -> list[Tool]:"""Return all MCP toolkit tools for registration in Runner."""- tools: list[Tool] = [mcp_free_search]+ tools = []if _has_paid_search_api_key():tools.append(mcp_paid_search)+ if _is_free_search_enabled():+ tools.append(mcp_free_search)tools.extend([mcp_fetch_webpage, mcp_exec_command])return toolsdiff --git a/jiuwenclaw/agentserver/tools/search_tools.py b/jiuwenclaw/agentserver/tools/search_tools.pyindex 27371312df..4f30952373 100644--- a/jiuwenclaw/agentserver/tools/search_tools.py+++ b/jiuwenclaw/agentserver/tools/search_tools.py@@ -13,6 +13,7 @@ from typing import Anyfrom urllib.parse import parse_qs, quote_plus, unquote, urlparseimport requests+import urllib3from openjiuwen.core.foundation.tool import tool_USER_AGENT = (@@ -21,9 +22,13 @@ _USER_AGENT = ("Chrome/124.0.0.0 Safari/537.36")_REQUEST_HEADERS = {"User-Agent": _USER_AGENT}+_FREE_SEARCH_DDG_ENABLED_ENV = "FREE_SEARCH_DDG_ENABLED"+_FREE_SEARCH_BING_ENABLED_ENV = "FREE_SEARCH_BING_ENABLED"_FREE_SEARCH_PROXY_URL_ENV = "FREE_SEARCH_PROXY_URL"+_FREE_SEARCH_SSL_VERIFY_ENV = "FREE_SEARCH_SSL_VERIFY"+_FREE_SEARCH_DDG_URL_ENV = "FREE_SEARCH_DDG_URL"_FREE_SEARCH_DEFAULT_NO_PROXY = (- "127.0.0.1,.huawei.com,localhost,local,.local,10.155.97.247,.myhuaweicloud.coms"+ "127.0.0.1,.huawei.com,localhost,local,.local,10.155.97.247,.myhuaweicloud.com")@@ -31,6 +36,34 @@ def _get_free_search_proxy_url() -> str:return str(os.environ.get(_FREE_SEARCH_PROXY_URL_ENV, "") or "").strip()+def _env_bool(name: str, default: bool = True) -> bool:+ raw = str(os.environ.get(name, "") or "").strip().lower()+ if not raw:+ return default+ return raw in {"1", "true", "yes", "on", "enabled"}+++def _env_flag(name: str, default: bool = False) -> bool:+ return _env_bool(name, default=default)+++def _free_search_ssl_verify() -> bool:+ return _env_bool(_FREE_SEARCH_SSL_VERIFY_ENV, default=False)+++def _disable_insecure_request_warning() -> None:+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)+++def _duckduckgo_search_url(query: str) -> str:+ base_url = (+ os.environ.get(_FREE_SEARCH_DDG_URL_ENV, "https://html.duckduckgo.com/html/")+ or "https://html.duckduckgo.com/html/"+ ).strip()+ separator = "&" if "?" in base_url else "?"+ return f"{base_url.rstrip('?&')}{separator}q={quote_plus(query)}"++def _no_proxy_entries() -> list[str]:configured = os.environ.get("NO_PROXY") or os.environ.get("no_proxy") or _FREE_SEARCH_DEFAULT_NO_PROXYreturn [entry.strip().lower() for entry in configured.split(",") if entry.strip()]@@ -65,6 +98,10 @@ def _http_request(method: str, url: str, **kwargs) -> requests.Response:"""Try normal request first; retry without env proxies on ProxyError."""method_up = method.upper()explicit_proxy = _apply_free_search_proxy(url, kwargs)+ if "verify" not in kwargs:+ kwargs["verify"] = _free_search_ssl_verify()+ if kwargs["verify"] is False:+ _disable_insecure_request_warning()try:if method_up == "GET":return requests.get(url, **kwargs)@@ -138,7 +175,7 @@ def _is_ddg_challenge_page(status_code: int, html: str) -> bool:def _search_duckduckgo_sync(query: str, max_results: int, timeout_seconds: int) -> list[dict[str, str]]:- url = f"https://duckduckgo.com/html/?q={quote_plus(query)}"+ url = _duckduckgo_search_url(query)response = _http_request("GET", url, headers=_REQUEST_HEADERS, timeout=timeout_seconds)if _is_ddg_challenge_page(response.status_code, response.text):raise RuntimeError("DuckDuckGo anti-bot challenge page returned")@@ -247,11 +284,16 @@ def _search_free_sync(query: str, max_results: int, timeout_seconds: int) -> tuple[str, list[dict[str, str]]]:errors: list[str] = []- engines = [- ("duckduckgo", _search_duckduckgo_sync),- ("duckduckgo-jina", _search_duckduckgo_via_jina_sync),- ("bing", _search_bing_sync),- ]+ engines = []+ if _env_flag(_FREE_SEARCH_DDG_ENABLED_ENV, default=False):+ engines.extend([+ ("duckduckgo", _search_duckduckgo_sync),+ ("duckduckgo-jina", _search_duckduckgo_via_jina_sync),+ ])+ if _env_flag(_FREE_SEARCH_BING_ENABLED_ENV, default=False):+ engines.append(("bing", _search_bing_sync))+ if not engines:+ raise RuntimeError("all free search engines are disabled")for engine_name, runner in engines:try:rows = runner(query, max_results, timeout_seconds)diff --git a/jiuwenclaw/agentserver/tools/web_fetch_tools.py b/jiuwenclaw/agentserver/tools/web_fetch_tools.pyindex 7a52521b1b..ecccabae54 100644--- a/jiuwenclaw/agentserver/tools/web_fetch_tools.py+++ b/jiuwenclaw/agentserver/tools/web_fetch_tools.py@@ -11,6 +11,7 @@ from html import unescapefrom urllib.parse import parse_qs, unquote, urlparseimport requests+import urllib3from openjiuwen.core.foundation.tool import tool_USER_AGENT = (@@ -20,8 +21,9 @@ _USER_AGENT = ()_REQUEST_HEADERS = {"User-Agent": _USER_AGENT}_FREE_SEARCH_PROXY_URL_ENV = "FREE_SEARCH_PROXY_URL"+_FREE_SEARCH_SSL_VERIFY_ENV = "FREE_SEARCH_SSL_VERIFY"_FREE_SEARCH_DEFAULT_NO_PROXY = (- "127.0.0.1,.huawei.com,localhost,local,.local,10.155.97.247,.myhuaweicloud.coms"+ "127.0.0.1,.huawei.com,localhost,local,.local,10.155.97.247,.myhuaweicloud.com")_CHARSET_HEADER_RE = re.compile(r"charset=([^\s;]+)", flags=re.IGNORECASE)_CHARSET_META_RE = re.compile(@@ -50,6 +52,21 @@ def _get_free_search_proxy_url() -> str:return str(os.environ.get(_FREE_SEARCH_PROXY_URL_ENV, "") or "").strip()+def _env_bool(name: str, default: bool = True) -> bool:+ raw = str(os.environ.get(name, "") or "").strip().lower()+ if not raw:+ return default+ return raw in {"1", "true", "yes", "on", "enabled"}+++def _free_search_ssl_verify() -> bool:+ return _env_bool(_FREE_SEARCH_SSL_VERIFY_ENV, default=False)+++def _disable_insecure_request_warning() -> None:+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)++def _no_proxy_entries() -> list[str]:configured = os.environ.get("NO_PROXY") or os.environ.get("no_proxy") or _FREE_SEARCH_DEFAULT_NO_PROXYreturn [entry.strip().lower() for entry in configured.split(",") if entry.strip()]@@ -125,6 +142,10 @@ def _decode_response_text(response: requests.Response) -> str:def _http_get(url: str, **kwargs) -> requests.Response:"""Try normal requests first; retry without env proxies on ProxyError."""explicit_proxy = _apply_free_search_proxy(url, kwargs)+ verify = _free_search_ssl_verify()+ kwargs.setdefault("verify", verify)+ if verify is False:+ _disable_insecure_request_warning()try:return requests.get(url, **kwargs)except requests.exceptions.ProxyError:diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex a2296f285b..eb45cf26ad 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -13,7 +13,13 @@ import timefrom dotenv import load_dotenv-from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace, cleanup_team_files+from jiuwenclaw.utils import (+ cleanup_team_files,+ get_env_file,+ get_user_workspace_dir,+ prepare_workspace,+ reset_free_search_runtime_flags,+)_workspace_dir = get_user_workspace_dir()@@ -29,6 +35,7 @@ if not _config_file.exists() or (_old_workspace.exists() and not _new_workspace.prepare_workspace(overwrite=False)load_dotenv(dotenv_path=get_env_file())+reset_free_search_runtime_flags()def main() -> None:diff --git a/jiuwenclaw/app_agentserver.py b/jiuwenclaw/app_agentserver.pyindex 8f86cc2c3a..79fda0dda2 100644--- a/jiuwenclaw/app_agentserver.py+++ b/jiuwenclaw/app_agentserver.py@@ -19,7 +19,13 @@ import osfrom dotenv import load_dotenvfrom openjiuwen.core.common.logging import LogManager-from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace, logger+from jiuwenclaw.utils import (+ get_env_file,+ get_user_workspace_dir,+ logger,+ prepare_workspace,+ reset_free_search_runtime_flags,+)# Ensure workspace initialized_workspace_dir = get_user_workspace_dir()@@ -36,6 +42,7 @@ for _lg in LogManager.get_all_loggers().values():# Load env from user workspace config/.envload_dotenv(dotenv_path=get_env_file())+reset_free_search_runtime_flags()async def _run(host: str, port: int) -> None:diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 57c505020c..13c165f3c0 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -30,7 +30,14 @@ from openjiuwen.core.common.logging import LogManagerimport jiuwenclaw.channel.acp_channel as acp_channel_modulefrom jiuwenclaw.channel.acp_channel import AcpGatewayBridgefrom jiuwenclaw.gateway.route_binding import GatewayRouteBinding-from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace, get_cron_jobs_path+from jiuwenclaw.utils import (+ get_env_file,+ get_user_workspace_dir,+ prepare_workspace,+ reset_free_search_runtime_flags,+ get_cron_jobs_path+)+# Ensure workspace initialized_workspace_dir = get_user_workspace_dir()@@ -47,6 +54,7 @@ for _lg in LogManager.get_all_loggers().values():_lg.set_level(logging.CRITICAL)load_dotenv(dotenv_path=get_env_file())+reset_free_search_runtime_flags()logger = logging.getLogger(__name__)diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.pyindex 8aa311d655..480a1057f2 100644--- a/jiuwenclaw/app_web_handlers.py+++ b/jiuwenclaw/app_web_handlers.py@@ -349,17 +349,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:preferred_lang = raw.get("preferred_language", "zh")payload["memory_forbidden_description"] = memory_desc.get(preferred_lang, memory_desc.get("zh", ""))if not payload.get("free_search_ddg_enabled"):- payload["free_search_ddg_enabled"] = "true"+ payload["free_search_ddg_enabled"] = "false"if not payload.get("free_search_bing_enabled"):- payload["free_search_bing_enabled"] = "true"+ payload["free_search_bing_enabled"] = "false"except Exception: # noqa: BLE001payload.setdefault("context_engine_enabled", "false")payload.setdefault("kv_cache_affinity_enabled", "false")payload.setdefault("permissions_enabled", "false")payload.setdefault("memory_forbidden_enabled", "false")payload.setdefault("memory_forbidden_description", "")- payload.setdefault("free_search_ddg_enabled", "true")- payload.setdefault("free_search_bing_enabled", "true")+ payload.setdefault("free_search_ddg_enabled", "false")+ payload.setdefault("free_search_bing_enabled", "false")await channel.send_response(ws, req_id, ok=True, payload=payload)def _persist_env_updates(updates: dict[str, str]) -> None:diff --git a/jiuwenclaw/resources/.env.template b/jiuwenclaw/resources/.env.templateindex e84d90009a..57a3056b27 100644--- a/jiuwenclaw/resources/.env.template+++ b/jiuwenclaw/resources/.env.template@@ -32,6 +32,12 @@ SERPER_API_KEY=PERPLEXITY_API_KEY=GITHUB_TOKEN=FREE_SEARCH_PROXY_URL=+# Set to false behind corporate TLS interception proxies if free search fails+# with SSLCertVerificationError/self-signed certificate errors.+FREE_SEARCH_SSL_VERIFY=false+# DuckDuckGo HTML endpoint. html.duckduckgo.com is usually less likely to return+# anti-bot pages than duckduckgo.com/html behind corporate proxies.+FREE_SEARCH_DDG_URL=https://html.duckduckgo.com/html/# Browser MCP runtime (optional)# 0: disabled, 1: enableddiff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.pyindex 19b41cafb2..9f1ba58040 100644--- a/jiuwenclaw/utils.py+++ b/jiuwenclaw/utils.py@@ -1086,6 +1086,12 @@ def get_env_file() -> Path:return get_config_dir() / ".env"+def reset_free_search_runtime_flags() -> None:+ """Start each process with free-search engines disabled unless reopened via config UI."""+ os.environ["FREE_SEARCH_DDG_ENABLED"] = "false"+ os.environ["FREE_SEARCH_BING_ENABLED"] = "false"++def get_config_file() -> Path:"""Get the config.yaml file path."""return get_config_dir() / "config.yaml"diff --git a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx b/jiuwenclaw/web/src/components/ConfigPanel/index.tsxindex 87f7495e28..9df3780345 100644--- a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ConfigPanel/index.tsx@@ -51,6 +51,56 @@ const EVOLUTION_KEYS = new Set(["evolution_auto_scan"]);const FREE_SEARCH_BOOLEAN_KEYS = new Set(["free_search_ddg_enabled", "free_search_bing_enabled"]);const FREE_SEARCH_KEYS = new Set([...FREE_SEARCH_BOOLEAN_KEYS, "free_search_proxy_url"]);const MEMORY_KEYS = new Set(["memory_forbidden_enabled", "memory_forbidden_description"]);+const DEFAULT_PROXY_SCHEME = "http";+const DEFAULT_PROXY_HOST = "proxyhk.huawei.com";+const DEFAULT_PROXY_PORT = "8080";++type ProxyParts = {+ username: string;+ password: string;+};++function decodeUrlPart(value: string): string {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}++function parseProxyUrl(value: string): ProxyParts {+ const trimmed = (value || "").trim();+ if (!trimmed) {+ return { username: "", password: "" };+ }+ try {+ const url = new URL(trimmed);+ return {+ username: decodeUrlPart(url.username),+ password: decodeUrlPart(url.password),+ };+ } catch {+ const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");+ const [authAndHost] = withoutScheme.split(/[/?#]/, 1);+ const at = authAndHost.lastIndexOf("@");+ const auth = at >= 0 ? authAndHost.slice(0, at) : "";+ const colon = auth.indexOf(":");+ return {+ username: colon >= 0 ? decodeUrlPart(auth.slice(0, colon)) : decodeUrlPart(auth),+ password: colon >= 0 ? decodeUrlPart(auth.slice(colon + 1)) : "",+ };+ }+}++function buildProxyUrl(parts: ProxyParts): string {+ const username = parts.username.trim();+ const password = parts.password;+ if (!username && !password) return "";+ const auth = username || password+ ? `${encodeURIComponent(username)}${password ? `:${encodeURIComponent(password)}` : ""}@`+ : "";+ return `${DEFAULT_PROXY_SCHEME}://${auth}${DEFAULT_PROXY_HOST}:${DEFAULT_PROXY_PORT}`;+}function classifyKey(key: string): string {if (MODEL_DEFAULT_KEYS.has(key)) return "model_default";@@ -243,6 +293,45 @@ function isProviderKey(key: string): boolean {return key.endsWith("_provider");}+function ProxyUrlInput({+ value,+ onChange,+ t,+}: {+ value: string;+ onChange: (value: string) => void;+ t: (key: string) => string;+}) {+ const parts = parseProxyUrl(value);+ const update = (patch: Partial<ProxyParts>) => {+ onChange(buildProxyUrl({ ...parts, ...patch }));+ };+ const inputClass = "w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent";+ return (+ <div className="space-y-1.5">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">+ <input+ type="text"+ value={parts.username}+ onChange={(e) => update({ username: e.target.value })}+ placeholder={t("config.keys.proxyUsernamePlaceholder")}+ className={inputClass}+ autoComplete="username"+ />+ <input+ type="password"+ value={parts.password}+ onChange={(e) => update({ password: e.target.value })}+ placeholder={t("config.keys.proxyPasswordPlaceholder")}+ className={inputClass}+ autoComplete="current-password"+ />+ </div>+ <p className="text-xs text-text-muted">{t("config.keys.freeSearchProxyUrlPlaceholder")}</p>+ </div>+ );+}+/** 表格列显示用:video_api_base -> api_base,避免与分组标题重复 *//** i18n 键名映射:字段名 -> 翻译 key(显示名 / placeholder) */const KEY_DISPLAY_I18N: Record<string, string> = {@@ -401,6 +490,22 @@ function GroupSection({</select></div></div>+ ) : key === "free_search_proxy_url" ? (+ <div className="flex items-center gap-2">+ <span+ className="inline-flex w-3 justify-center shrink-0 font-semibold leading-none select-none text-transparent"+ aria-hidden="true"+ >+ *+ </span>+ <div className="flex-1">+ <ProxyUrlInput+ value={draftValues[key] ?? value}+ onChange={(nextValue) => onChange(key, nextValue)}+ t={t}+ />+ </div>+ </div>) : (<div className="flex items-center gap-2"><span