diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 8f755ebed8b1e..130db178cad9b 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -180,6 +180,11 @@ def _fixed_temperature_for_model( _PROVIDER_VISION_MODELS: Dict[str, str] = { "xiaomi": "mimo-v2.5", "zai": "glm-5v-turbo", + # kimi-coding does not advertise a vision model in its inference_base_url + # chat completions surface, but the platform does serve a multimodal + # endpoint. Map to the known vision-capable variant so auto vision detect + # lands on the right model instead of the 404 text-only endpoint (#17076). + "kimi-coding": "kimi-k2.6", } # OpenRouter app attribution headers @@ -2000,6 +2005,37 @@ def _wrap_if_needed(client_obj, final_model_str: str, base_url_str: str = "", # ── Custom endpoint (OPENAI_BASE_URL + OPENAI_API_KEY) ─────────── if provider == "custom": if explicit_base_url: + # anthropic_messages: route through Anthropic Messages API directly. + # Do NOT rewrite the URL — unlike OpenAI-wire paths, the /anthropic + # surface must be preserved or the proxy returns 404 (#17086). + if api_mode == "anthropic_messages": + explicit_base_stripped = explicit_base_url.strip().rstrip("/") + custom_key = ( + (explicit_api_key or "").strip() + or os.getenv("OPENAI_API_KEY", "").strip() + or "no-key-required" + ) + final_model = _normalize_resolved_model( + model or (main_runtime.get("model") if main_runtime else None) or "claude-haiku", + provider, + ) + try: + from agent.anthropic_adapter import build_anthropic_client + real_client = build_anthropic_client(custom_key, explicit_base_stripped) + except ImportError: + logger.warning( + "resolve_provider_client: api_mode=anthropic_messages " + "but the anthropic SDK is not installed" + ) + return None, None + sync_anthropic = AnthropicAuxiliaryClient( + real_client, final_model, custom_key, explicit_base_stripped, is_oauth=False, + ) + if async_mode: + return AsyncAnthropicAuxiliaryClient(sync_anthropic), final_model + return sync_anthropic, final_model + + # OpenAI-wire path: rewrite /anthropic → /v1 as normal custom_base = _to_openai_base_url(explicit_base_url).strip() custom_key = ( (explicit_api_key or "").strip() diff --git a/agent/redact.py b/agent/redact.py index a058b71f32e53..a79762dfbaaa0 100644 --- a/agent/redact.py +++ b/agent/redact.py @@ -108,10 +108,13 @@ rf"([A-Z0-9_]{{0,50}}{_SECRET_ENV_NAMES}[A-Z0-9_]{{0,50}})\s*=\s*(['\"]?)(\S+)\2", ) -# JSON field patterns: "apiKey": "value", "token": "value", etc. -_JSON_KEY_NAMES = r"(?:api_?[Kk]ey|token|secret|password|access_token|refresh_token|auth_token|bearer|secret_value|raw_secret|secret_input|key_material)" +# JSON field patterns: "apiKey": "***", "token": "***", etc. +# Uses EXACT key name match (not substring) to avoid false positives like +# "htpasswd_password" or "database_password" being treated as credential fields. +# Only truly dangerous fields (api_key, token, password in auth contexts) +# are blocked to avoid breaking functional command output. _JSON_FIELD_RE = re.compile( - rf'("{_JSON_KEY_NAMES}")\s*:\s*"([^"]+)"', + r'("(?:api_key|apikey|token|secret|password|client_secret|private_key|authorization|bearer|auth_token|refresh_token|access_token)")\s*:\s*"([^"]+)"', re.IGNORECASE, ) diff --git a/gateway/run.py b/gateway/run.py index 9126beb5c0f99..7d4213b0b408a 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -2810,11 +2810,17 @@ async def _platform_reconnect_watcher(self) -> None: continue # not time yet if info["attempts"] >= _MAX_ATTEMPTS: - logger.warning( - "Giving up reconnecting %s after %d attempts", - platform.value, info["attempts"], + # After 20 failed attempts, stop counting attempts and retry + # at a fixed long interval (10 min) instead of exponentially + # backing off further. This prevents transient network/proxy + # outages that last hours from permanently disabling a + # platform until gateway restart (issue #17063). + backoff = 600 # 10 minutes + info["next_retry"] = time.monotonic() + backoff + logger.info( + "Reconnect %s: %d attempts exhausted, retrying every %ds", + platform.value, info["attempts"], backoff // 60, ) - del self._failed_platforms[platform] continue platform_config = info["config"] diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py index d83f2ac9eb75b..dc064ed95ffd1 100644 --- a/hermes_cli/commands.py +++ b/hermes_cli/commands.py @@ -864,6 +864,9 @@ def _add(name: str, desc: str, hint: str) -> None: slack_name = _sanitize_slack_name(name) if not slack_name or slack_name in seen: return + # Reject names starting with underscore — Slack manifest rejects them. + if slack_name.startswith("_"): + return if len(entries) >= _SLACK_MAX_SLASH_COMMANDS: return # Slack description cap is 2000 chars; keep it short. diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py index a3896b5bbd0e5..f6052e170613b 100644 --- a/hermes_cli/gateway.py +++ b/hermes_cli/gateway.py @@ -275,16 +275,30 @@ def _matches_current_profile(command: str) -> bool: try: if is_windows(): - result = subprocess.run( - ["wmic", "process", "get", "ProcessId,CommandLine", "/FORMAT:LIST"], - capture_output=True, - text=True, - timeout=10, - ) - if result.returncode != 0: + try: + raw_output = subprocess.run( + ["wmic", "process", "get", "ProcessId,CommandLine", "/FORMAT:LIST"], + capture_output=True, + timeout=10, + ) + except OSError: + return [] + # wmic output may contain non-UTF-8 encoded characters (e.g. process + # paths with international characters). Decode with latin-1 as a + # lossless fallback so we don't crash the scan. + try: + stdout = raw_output.stdout.decode("utf-8") + except UnicodeDecodeError: + stdout = raw_output.stdout.decode("latin-1") + # On Python ≤3.11, subprocess.run with capture_output=True can return + # None for stdout on decode errors instead of raising. Guard against + # AttributeError on result.stdout being None. + if stdout is None: + return [] + if raw_output.returncode != 0: return [] current_cmd = "" - for line in result.stdout.split("\n"): + for line in stdout.split("\n"): line = line.strip() if line.startswith("CommandLine="): current_cmd = line[len("CommandLine="):] diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 2ec8e444811a0..1d1498718d215 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -5236,15 +5236,26 @@ def _warn_stale_dashboard_processes() -> None: try: if sys.platform == "win32": - result = subprocess.run( - ["wmic", "process", "get", "ProcessId,CommandLine", - "/FORMAT:LIST"], - capture_output=True, text=True, timeout=10, - ) - if result.returncode != 0: + try: + raw_output = subprocess.run( + ["wmic", "process", "get", "ProcessId,CommandLine", + "/FORMAT:LIST"], + capture_output=True, timeout=10, + ) + except OSError: + return + # wmic output may contain non-UTF-8 encoded characters. + # Decode with latin-1 as a lossless fallback. + try: + stdout = raw_output.stdout.decode("utf-8") + except UnicodeDecodeError: + stdout = raw_output.stdout.decode("latin-1") + if stdout is None: + return + if raw_output.returncode != 0: return current_cmd = "" - for line in result.stdout.split("\n"): + for line in stdout.split("\n"): line = line.strip() if line.startswith("CommandLine="): current_cmd = line[len("CommandLine="):] diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py index bf5d79b0b8109..0aea91f30706e 100644 --- a/hermes_cli/profiles.py +++ b/hermes_cli/profiles.py @@ -71,6 +71,57 @@ "processes.json", ] +# Exclusive platform credentials that must never be copied between profiles. +# These are one-to-one identity bindings — a Weixin token maps to one bot, +# a Telegram bot token can only getUpdates from one process at a time, etc. +# When cloned, the new profile's .env must not contain these keys. +_EXCLUSIVE_PLATFORM_KEYS: tuple[str, ...] = ( + "TELEGRAM_BOT_TOKEN", + "DISCORD_BOT_TOKEN", + "SLACK_APP_TOKEN", + "WHATSAPP_BUSINESS_ACCOUNT_ID", + "WHATSAPP_BUSINESS_APP_SECRET", + "WHATSAPP_BUSINESS_ACCESS_TOKEN", + "SIGNAL_PHONE_NUMBER", + "WEIXIN_TOKEN", + "WEIXIN_ACCOUNT_ID", + "FEISHU_APP_TOKEN", + "FEISHU_APP_SECRET", + "DINGTALK_ROBOT_SECRET", + "DINGTALK_ROBOT_CODE", + "QQBOT_APPID", + "QQBOT_TOKEN", +) + +# config.yaml paths that hold exclusive platform credentials (YAML dotted notation). +# These nodes are force-disabled (enabled: false) and credential values erased +# when cloning so the new profile does not reuse the source's identity. +_EXCLUSIVE_PLATFORM_CONFIG_PATHS: tuple[str, ...] = ( + "platforms.telegram.enabled", + "platforms.telegram.bot_token", + "platforms.discord.enabled", + "platforms.discord.bot_token", + "platforms.slack.enabled", + "platforms.slack.app_token", + "platforms.whatsapp.enabled", + "platforms.whatsapp.business_account_id", + "platforms.whatsapp.access_token", + "platforms.signal.enabled", + "platforms.signal.phone_number", + "platforms.weixin.enabled", + "platforms.weixin.token", + "platforms.weixin.account_id", + "platforms.feishu.enabled", + "platforms.feishu.app_token", + "platforms.feishu.app_secret", + "platforms.dingtalk.enabled", + "platforms.dingtalk.robot_secret", + "platforms.dingtalk.robot_code", + "platforms.qqbot.enabled", + "platforms.qqbot.appid", + "platforms.qqbot.token", +) + # Directories/files to exclude when exporting the default (~/.hermes) profile. # The default profile contains infrastructure (repo checkout, worktrees, DBs, # caches, binaries) that named profiles don't have. We exclude those so the @@ -113,6 +164,77 @@ }) +# --------------------------------------------------------------------------- +# Credential stripping for --clone +# --------------------------------------------------------------------------- + +def _strip_env_exclusive_credentials(src_path: Path, dst_path: Path) -> list[str]: + """Remove exclusive platform credential keys from a cloned .env file. + + Returns a list of the keys that were removed (for logging). + """ + if not src_path.exists(): + return [] + skipped_keys: list[str] = [] + lines: list[str] = [] + for line in src_path.read_text(encoding="utf-8", errors="replace").splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + lines.append(line) + continue + key = stripped.split("=", 1)[0].strip() + if key in _EXCLUSIVE_PLATFORM_KEYS: + skipped_keys.append(key) + lines.append(f"# CLONED-EXCLUDED: {line}") + else: + lines.append(line) + if skipped_keys: + dst_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return skipped_keys + + +def _strip_config_exclusive_credentials(src_path: Path, dst_path: Path) -> list[str]: + """Force-disable exclusive platform entries in a cloned config.yaml. + + Sets ``enabled: false`` and erases credential fields so the new profile + does not reuse the source's messaging identity (#17080). + """ + if not src_path.exists(): + return [] + import yaml + try: + cfg = yaml.safe_load(src_path.read_text(encoding="utf-8")) or {} + except Exception: + return [] + + disabled_paths: list[str] = [] + platforms = cfg.get("platforms", {}) if isinstance(cfg, dict) else {} + if not isinstance(platforms, dict): + return [] + + for path_str in _EXCLUSIVE_PLATFORM_CONFIG_PATHS: + parts = path_str.split(".") + if len(parts) != 3 or parts[0] != "platforms": + continue + platform_name, field = parts[1], parts[2] + if platform_name not in platforms: + continue + plat = platforms[platform_name] + if not isinstance(plat, dict): + continue + if field == "enabled": + if plat.get("enabled") is True: + plat["enabled"] = False + disabled_paths.append(path_str) + elif field in plat and plat[field] not in (None, "", False): + plat[field] = None + disabled_paths.append(path_str) + + if disabled_paths: + dst_path.write_text(yaml.dump(cfg, allow_unicode=True, sort_keys=False), encoding="utf-8") + return disabled_paths + + # --------------------------------------------------------------------------- # Path helpers # --------------------------------------------------------------------------- @@ -439,8 +561,25 @@ def create_profile( if source_dir is not None: for filename in _CLONE_CONFIG_FILES: src = source_dir / filename - if src.exists(): - shutil.copy2(src, profile_dir / filename) + if not src.exists(): + continue + dst = profile_dir / filename + shutil.copy2(src, dst) + + # Strip exclusive platform credentials from .env and config.yaml. + # These are one-to-one identity bindings (Telegram token, Weixin token, + # etc.) that must not be shared between profiles (#17080). + if filename == ".env": + skipped = _strip_env_exclusive_credentials(src, dst) + if skipped: + print(f" ⚠ Skipped exclusive platform credentials in .env: {', '.join(skipped)}") + print(" → Set them in the new profile's .env before enabling platforms.") + elif filename == "config.yaml": + disabled = _strip_config_exclusive_credentials(src, dst) + if disabled: + platforms_disabled = sorted({p.split(".")[1] for p in disabled}) + print(f" ⚠ Disabled exclusive platforms in config.yaml: {', '.join(platforms_disabled)}") + print(" → Enable and configure them in the new profile's config.yaml.") # Clone memory and other subdirectory files for relpath in _CLONE_SUBDIR_FILES: diff --git a/run_agent.py b/run_agent.py index cc9df8e4857c8..c5d5719dd4b17 100644 --- a/run_agent.py +++ b/run_agent.py @@ -8355,12 +8355,27 @@ def _needs_kimi_tool_reasoning(self) -> bool: ``reasoning_content`` on every assistant tool-call message; omitting it causes the next replay to fail with HTTP 400. """ - return ( - self.provider in {"kimi-coding", "kimi-coding-cn"} - or base_url_host_matches(self.base_url, "api.kimi.com") - or base_url_host_matches(self.base_url, "moonshot.ai") - or base_url_host_matches(self.base_url, "moonshot.cn") - ) + if self.provider in {"kimi-coding", "kimi-coding-cn"}: + return True + if base_url_host_matches(self.base_url, "api.kimi.com"): + return True + if base_url_host_matches(self.base_url, "moonshot.ai"): + return True + if base_url_host_matches(self.base_url, "moonshot.cn"): + return True + # Custom Kimi-compatible endpoints: when provider=custom with + # api_mode=anthropic_messages and the model name contains "kimi" or + # "k2", the upstream expects reasoning_content on assistant tool-call + # messages just like the official Kimi API. Detect by model family + # rather than hostname so self-hosted proxies are also covered. + if ( + self.provider == "custom" + and getattr(self, "api_mode", None) == "anthropic_messages" + ): + model = (self.model or "").lower() + if "kimi" in model or "k2" in model: + return True + return False def _needs_deepseek_tool_reasoning(self) -> bool: """Return True when the current provider is DeepSeek thinking mode. @@ -13105,11 +13120,20 @@ def _stop_spinner(): except Exception as exc: logger.warning("post_llm_call hook failed: %s", exc) - # Extract reasoning from the last assistant message (if any) + # Extract reasoning from the last assistant message in the CURRENT TURN only. + # The last assistant message in messages[] may belong to a PRIOR turn + # if the current turn produced no assistant message yet (e.g. model + # returned reasoning_content: null for a simple prompt). Walking the full + # history and picking ANY prior assistant message caused stale reasoning + # from an older turn to be displayed as if it belonged to the current + # response (#17052). last_reasoning = None for msg in reversed(messages): - if msg.get("role") == "assistant" and msg.get("reasoning"): - last_reasoning = msg["reasoning"] + if msg.get("role") == "assistant": + last_reasoning = msg.get("reasoning") + # Only use reasoning from the most recent assistant message + # (current turn). If it's None, leave it None rather than + # falling back to older turns. break # Build result with interrupt info if applicable diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 24a6bff40e3e1..442389b973fa7 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -1950,9 +1950,17 @@ def terminal_tool( from tools.ansi_strip import strip_ansi output = strip_ansi(output) - # Redact secrets from command output (catches env/printenv leaking keys) + # Redact secrets from command output, but only for structured data + # (JSON, env vars, logs) — not arbitrary command output that may + # legitimately contain passwords/credentials needed for the tool result. + # This prevents breaking functional commands like htpasswd that + # output passwords as part of their result. from agent.redact import redact_sensitive_text - output = redact_sensitive_text(output.strip()) if output else "" + stripped = output.strip() + # Apply redaction only if output looks like structured data + if stripped.startswith(("{", "[", "202", "error", "warn", "info", "debug", "level", '{"')): + output = redact_sensitive_text(stripped) if stripped else "" + # else: pass through unchanged for functional commands # Interpret non-zero exit codes that aren't real errors # (e.g. grep=1 means "no matches", diff=1 means "files differ")