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: 日志整改&send_file调整&model patch 问题修复&xiaoyi支持push
ray_le85aac84c8fd2
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 53a50e433b..fa933f9fca 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -4,6 +4,7 @@from __future__ import annotations+import loggingimport asyncioimport jsonimport math@@ -11,10 +12,13 @@ from dataclasses import asdictfrom pathlib import Pathfrom typing import Any, ClassVar-from jiuwenclaw.utils import get_agent_sessions_dir, get_config_file, logger+from jiuwenclaw.utils import get_agent_sessions_dir, get_config_filefrom jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+logger = logging.getLogger(__name__)++def _payload_to_request(data: dict[str, Any]) -> AgentRequest:"""将 Gateway 发送的 JSON 载荷解析为 AgentRequest."""from jiuwenclaw.schema.message import ReqMethoddiff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 3b209663d5..80a4b070ad 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport json+import loggingimport osimport timefrom typing import Any, AsyncIterator@@ -26,13 +27,13 @@ from jiuwenclaw.agentserver.tools.multi_session_toolkits import MultiSessionToolfrom jiuwenclaw.agentserver.tools import SendFileToolkitfrom jiuwenclaw.agentserver.prompt_builder import build_system_prompt, build_user_promptfrom jiuwenclaw.gateway.cron import CronController, CronTargetChannel+from jiuwenclaw.utils import (get_agent_root_dir,get_agent_home_dir,get_checkpoint_dir,get_env_file,get_workspace_dir,- logger,)from jiuwenclaw.config import get_configfrom jiuwenclaw.agentserver.react_agent import JiuClawReActAgent@@ -91,6 +92,8 @@ from jiuwenclaw.schema.message import ReqMethodload_dotenv(dotenv_path=get_env_file())+logger = logging.getLogger(__name__)+SYSTEM_PROMPT = """# 角色你是一个能够帮助用户执行任务的小助手。@@ -552,6 +555,16 @@ class JiuWenClaw:channels_cfg = config_base.get("channels", {})xiaoyi_cfg = channels_cfg.get("xiaoyi", {})xiaoyi_phone_tools_enabled = xiaoyi_cfg.get("phone_tools_enabled", False)+ if xiaoyi_phone_tools_enabled:+ # Register send file toolkit+ send_file_toolkit = SendFileToolkit(+ request_id=request_id,+ session_id=effective_session_id,+ channel_id=channel_id,+ )+ for tool in send_file_toolkit.get_tools():+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)if xiaoyi_phone_tools_enabled and not self._xiaoyi_phone_tools_registered:try:@@ -574,7 +587,7 @@ class JiuWenClaw:Runner.resource_mgr.add_tool(tool)self._instance.ability_manager.add(tool.card)except Exception as tool_exc:- logger.debug(f"[JiuWenClaw] Tool {tool.card.name} may already exist: {tool_exc}")+ logger.error(f"[JiuWenClaw] Tool {tool.card.name} may already exist: {tool_exc}")except Exception as exc:logger.warning(f"[JiuWenClaw] xiaoyi phone tools runtime registration skipped: {exc}")@@ -599,21 +612,6 @@ class JiuWenClaw:Runner.resource_mgr.add_tool(tool)self._instance.ability_manager.add(tool.card)- # Register send file toolkit- send_file_toolkit = SendFileToolkit(- request_id=request_id,- session_id=effective_session_id,- channel_id=channel_id,- )- for tool in send_file_toolkit.get_tools():- Runner.resource_mgr.add_tool(tool)- self._instance.ability_manager.add(tool.card)- # tool_list = self._instance.ability_manager.list()- # for tool in tool_list:- # if isinstance(tool, ToolCard):- # if tool.name.startswith("todo_"):- # self._instance.ability_manager.remove(tool.name)-if not self._memory_tools_registered:await init_memory_manager_async(workspace_dir=self._workspace_dir,diff --git a/jiuwenclaw/agentserver/memory/compaction.py b/jiuwenclaw/agentserver/memory/compaction.pyindex c7fa547323..ad3dcbed08 100644--- a/jiuwenclaw/agentserver/memory/compaction.py+++ b/jiuwenclaw/agentserver/memory/compaction.py@@ -7,15 +7,17 @@ Provides automatic triggering of message compression when token threshold is excimport asyncioimport json+import loggingimport osfrom enum import Enumfrom typing import List, Dict, Any, Optionalfrom dataclasses import dataclass, fieldfrom datetime import datetime-from jiuwenclaw.utils import loggerfrom .internal import estimate_tokens+logger = logging.getLogger(__name__)+CONTEXT_COMPACT_THRESHOLD = 8000CONTEXT_COMPACT_KEEP_RECENT = 10COMPRESSED_SUMMARY_FILE = "compressed_summary.json"diff --git a/jiuwenclaw/agentserver/memory/config.py b/jiuwenclaw/agentserver/memory/config.pyindex 7cb9db5479..376342aae5 100644--- a/jiuwenclaw/agentserver/memory/config.py+++ b/jiuwenclaw/agentserver/memory/config.py@@ -6,6 +6,7 @@ Configuration is loaded from config/config.yaml.Embedding API settings are in the 'embed' section."""+import loggingimport osimport refrom typing import Any, Optional, Dict, List@@ -14,8 +15,9 @@ from pathlib import Pathimport yaml-from jiuwenclaw.utils import get_config_file, get_agent_root_dir, logger+from jiuwenclaw.utils import get_config_file, get_agent_root_dir+logger = logging.getLogger(__name__)DEFAULT_CONFIG_PATH = str(get_config_file())DEFAULT_WORKSPACE_DIR = str(get_agent_root_dir())diff --git a/jiuwenclaw/agentserver/memory/embeddings.py b/jiuwenclaw/agentserver/memory/embeddings.pyindex 1d1e00b1ff..4706e9c250 100644--- a/jiuwenclaw/agentserver/memory/embeddings.py+++ b/jiuwenclaw/agentserver/memory/embeddings.py@@ -2,11 +2,13 @@"""Embedding providers for memory system."""+import loggingimport osfrom abc import ABC, abstractmethodfrom typing import List, Optional-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)class EmbeddingProvider(ABC):"""Base class for embedding providers."""diff --git a/jiuwenclaw/agentserver/memory/manager.py b/jiuwenclaw/agentserver/memory/manager.pyindex da82f61139..6faffbd499 100644--- a/jiuwenclaw/agentserver/memory/manager.py+++ b/jiuwenclaw/agentserver/memory/manager.py@@ -2,6 +2,7 @@"""Memory Index Manager - Core memory management for JiuWenClaw."""+import loggingimport osimport jsonimport sqlite3@@ -21,7 +22,8 @@ from .internal import ()from .embeddings import EmbeddingProvider, create_embedding_providerfrom .config import MemorySettings-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)META_KEY = "memory_index_meta_v1"SNIPPET_MAX_CHARS = 700diff --git a/jiuwenclaw/agentserver/memory/summarizer.py b/jiuwenclaw/agentserver/memory/summarizer.pyindex 93094e0290..f2e8d5a649 100644--- a/jiuwenclaw/agentserver/memory/summarizer.py+++ b/jiuwenclaw/agentserver/memory/summarizer.py@@ -1,9 +1,8 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""LLM-based memory compression and summarization for JiuWenClaw.--"""+"""LLM-based memory compression and summarization for JiuWenClaw."""+import loggingimport osimport datetimefrom typing import List, Dict, Any, Optional@@ -12,9 +11,10 @@ from pathlib import Pathfrom openjiuwen.core.foundation.llm import Modelfrom openjiuwen.core.foundation.llm.schema.config import ModelRequestConfig, ModelClientConfig-from jiuwenclaw.utils import loggerfrom jiuwenclaw.config import get_config+logger = logging.getLogger(__name__)+def format_messages_for_summary(messages: List[Dict[str, Any]],diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.pyindex 4a9c47e2d4..84efb9d02f 100644--- a/jiuwenclaw/agentserver/prompt_builder.py+++ b/jiuwenclaw/agentserver/prompt_builder.py@@ -1,11 +1,14 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+import loggingimport jsonimport osfrom datetime import datetime, timezone, timedeltafrom typing import Optional-from jiuwenclaw.utils import USER_WORKSPACE_DIR, logger+from jiuwenclaw.utils import USER_WORKSPACE_DIR++logger = logging.getLogger(__name__)CONFIG_DIR = USER_WORKSPACE_DIR / "config"HOME_DIR = USER_WORKSPACE_DIR / "agent" / "home"MEMORY_DIR = USER_WORKSPACE_DIR / "agent" / "memory"diff --git a/jiuwenclaw/agentserver/react_agent.py b/jiuwenclaw/agentserver/react_agent.pyindex 110bdb48ab..46084624c4 100644--- a/jiuwenclaw/agentserver/react_agent.py+++ b/jiuwenclaw/agentserver/react_agent.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport importlib.util+import loggingimport reimport sysimport uuid@@ -39,9 +40,11 @@ from jiuwenclaw.agentserver.permissions import (from jiuwenclaw.agentserver.permissions.models import PermissionLevelfrom jiuwenclaw.agentserver.tools.todo_toolkits import TodoToolkitfrom jiuwenclaw.evolution.service import EvolutionService-from jiuwenclaw.utils import get_agent_memory_dir, get_workspace_dir, logger+from jiuwenclaw.utils import get_agent_memory_dir, get_workspace_dirfrom jiuwenclaw.config import get_config+logger = logging.getLogger(__name__)+# 加载流式输出配置_react_config = get_config().get("react", {})diff --git a/jiuwenclaw/agentserver/session_history.py b/jiuwenclaw/agentserver/session_history.pyindex ad52b891f5..385a94b1db 100644--- a/jiuwenclaw/agentserver/session_history.py+++ b/jiuwenclaw/agentserver/session_history.py@@ -1,13 +1,16 @@from __future__ import annotations+import loggingimport jsonimport queueimport threadingfrom pathlib import Pathfrom typing import Any-from jiuwenclaw.utils import get_agent_sessions_dir, logger+from jiuwenclaw.utils import get_agent_sessions_dir++logger = logging.getLogger(__name__)_FILE_LOCK = threading.Lock()_WRITE_QUEUE: queue.Queue[tuple[str, dict[str, Any]]] = queue.Queue(maxsize=20000)_WORKER_STARTED = Falsediff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.pyindex 9efd7da7c0..0d24906691 100644--- a/jiuwenclaw/agentserver/skill_manager.py+++ b/jiuwenclaw/agentserver/skill_manager.py@@ -4,6 +4,7 @@from __future__ import annotations+import loggingimport asyncioimport jsonimport os@@ -16,7 +17,9 @@ from pathlib import Pathfrom typing import Any, Awaitable, Callablefrom urllib.parse import urlparse-from jiuwenclaw.utils import get_agent_root_dir, get_agent_skills_dir, logger+from jiuwenclaw.utils import get_agent_root_dir, get_agent_skills_dir++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"))diff --git a/jiuwenclaw/agentserver/tools/audio_tools.py b/jiuwenclaw/agentserver/tools/audio_tools.pyindex f9e8b67fe7..4d9f2b955a 100644--- a/jiuwenclaw/agentserver/tools/audio_tools.py+++ b/jiuwenclaw/agentserver/tools/audio_tools.py@@ -21,9 +21,10 @@ from openjiuwen.core.foundation.tool import McpServerConfig, toolfrom openjiuwen.core.runner import Runnerimport requests-from jiuwenclaw.utils import loggerfrom jiuwenclaw.agentserver.tools.multimodal_config import apply_audio_model_config_from_yaml++logger = logging.getLogger(__name__)ACR_ACCESS_KEY = os.environ.get("ACR_ACCESS_KEY", "")ACR_ACCESS_SECRET = os.environ.get("ACR_ACCESS_SECRET", "")ACR_BASE_URL = os.environ.get(@@ -38,8 +39,6 @@ DEFAULT_USER_AGENT = (mcp = FastMCP("audio-mcp-server")-_log = logging.getLogger(__name__)-_AUDIO_EXT_MAP = {".mp3": "mp3", ".wav": "wav", ".m4a": "m4a",".aac": "aac", ".ogg": "ogg", ".flac": "flac", ".wma": "wma",@@ -74,7 +73,7 @@ def _compute_audio_length_seconds(file_path: str) -> float:if secs > 0:return secsexcept (wave.Error, OSError):- _log.debug("wave module failed to read %s, trying mutagen", file_path)+ logger.debug("wave module failed to read %s, trying mutagen", file_path)try:audio_obj = MutagenFile(file_path)if audio_obj is not None and hasattr(audio_obj, "info"):@@ -83,7 +82,7 @@ def _compute_audio_length_seconds(file_path: str) -> float:if secs > 0:return secsexcept Exception:- _log.debug("mutagen failed to read %s", file_path, exc_info=True)+ logger.debug("mutagen failed to read %s", file_path, exc_info=True)raise ValueError("Unable to determine audio duration")@@ -160,7 +159,7 @@ async def audio_question_answering(audio_path_or_url: str, question: str) -> strtry:apply_audio_model_config_from_yaml(get_config())except Exception:- _log.debug("Failed to apply audio model config from yaml", exc_info=True)+ logger.debug("Failed to apply audio model config from yaml", exc_info=True)api_key, api_base, client = _create_openai_client_for_audio()if not api_key:diff --git a/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/openjiuwen_monkeypatch.py b/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/openjiuwen_monkeypatch.pyindex c9d6776c1c..762bd97319 100644--- a/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/openjiuwen_monkeypatch.py+++ b/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/openjiuwen_monkeypatch.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport importlibimport importlib.abcimport importlib.util+import inspectimport loggingimport osimport sys@@ -360,8 +361,20 @@ def _patch_base_model_client(base_model_client_mod: Any) -> None:original_convert_tools = base_cls._convert_tools_to_dict+ try:+ sig = inspect.signature(original_convert_tools)+ param_count = len(sig.parameters)+ needs_self = param_count == 2 and "self" in sig.parameters+ except Exception:+ # Fallback: try with self first+ needs_self = True+def _convert_tools_to_dict_dedup(self: Any, tools: Any) -> Any:- tool_dicts = original_convert_tools(self, tools)+ if needs_self:+ tool_dicts = original_convert_tools(self, tools)+ else:+ tool_dicts = original_convert_tools(tools)+if not tool_dicts:return tool_dictsdiff --git a/jiuwenclaw/agentserver/tools/image_tools.py b/jiuwenclaw/agentserver/tools/image_tools.pyindex 70d4dc2fe6..3b5e4d16e0 100644--- a/jiuwenclaw/agentserver/tools/image_tools.py+++ b/jiuwenclaw/agentserver/tools/image_tools.py@@ -16,15 +16,15 @@ from openjiuwen.core.foundation.tool import McpServerConfig, toolfrom openjiuwen.core.runner import Runnerimport requests-from jiuwenclaw.utils import loggerfrom jiuwenclaw.agentserver.tools.multimodal_config import apply_vision_model_config_from_yaml++logger = logging.getLogger(__name__)load_dotenv(verbose=True)_SANDBOX_MARKER = "home/user"mcp = FastMCP("vision-mcp-server")-_log = logging.getLogger(__name__)class _PathHelper:@@ -283,15 +283,15 @@ async def visual_question_answering(image_path_or_url: str, question: str) -> sttry:apply_vision_model_config_from_yaml(get_config())except Exception:- _log.debug("Failed to apply vision model config from yaml", exc_info=True)+ logger.debug("Failed to apply vision model config from yaml", exc_info=True)vision_api_key, vision_api_base, vision_model = _get_vision_api_credentials()logger.info("[visual_question_answering] using model: %s (api_base: %s)", vision_model, vision_api_base)ocr_out = await _invoke_openai_vision(image_path_or_url, _OCR_INSTRUCTIONS)vqa_out = await _invoke_openai_vision(image_path_or_url, _build_vqa_prompt(ocr_out, question))- _log.info("Visual Question Answering tool called via OpenRouter (Gemini model)")- _log.info(f"OCR results: {ocr_out}")- _log.info(f"VQA results: {vqa_out}")+ logger.info("Visual Question Answering tool called via OpenRouter (Gemini model)")+ logger.info(f"OCR results: {ocr_out}")+ logger.info(f"VQA results: {vqa_out}")return f"OCR results:\n{ocr_out}\n\nVQA result:\n{vqa_out}"diff --git a/jiuwenclaw/agentserver/tools/memory_tools.py b/jiuwenclaw/agentserver/tools/memory_tools.pyindex db563b587f..bdb0891816 100644--- a/jiuwenclaw/agentserver/tools/memory_tools.py+++ b/jiuwenclaw/agentserver/tools/memory_tools.py@@ -2,6 +2,7 @@"""Memory tools for JiuWenClaw - Using @tool decorator for openjiuwen."""+import loggingimport osimport refrom typing import Optional, Dict, Any, List@@ -14,7 +15,8 @@ from ..memory import (create_memory_settings,is_memory_enabled,)-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)_global_manager: Optional[MemoryIndexManager] = None_global_workspace_dir: str = "."diff --git a/jiuwenclaw/agentserver/tools/multi_session_toolkits.py b/jiuwenclaw/agentserver/tools/multi_session_toolkits.pyindex deb4404daf..939943bdba 100644--- a/jiuwenclaw/agentserver/tools/multi_session_toolkits.py+++ b/jiuwenclaw/agentserver/tools/multi_session_toolkits.py@@ -2,6 +2,7 @@"""Session Toolkit生命周期:Agent创建新session开始,到所有session协程结束+在结束后,MultiSessionToolkit所有内容Agent 可以通过以下工具操控协程@@ -22,6 +23,7 @@ from __future__ import annotationsimport asyncioimport json+import loggingimport secretsimport timefrom enum import Enum@@ -38,7 +40,8 @@ from jiuwenclaw.agentserver.tools.mcp_toolkits import get_mcp_toolsfrom jiuwenclaw.gateway.message_handler import MessageHandlerfrom jiuwenclaw.schema import AgentResponseChunkfrom jiuwenclaw.schema.message import EventType, Message-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)class Status(str, Enum):diff --git a/jiuwenclaw/agentserver/tools/send_file_to_user.py b/jiuwenclaw/agentserver/tools/send_file_to_user.pyindex 1961535db5..01ff954ebc 100644--- a/jiuwenclaw/agentserver/tools/send_file_to_user.py+++ b/jiuwenclaw/agentserver/tools/send_file_to_user.py@@ -13,12 +13,14 @@from __future__ import annotationsimport json+import loggingfrom typing import List, Unionfrom openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCardfrom jiuwenclaw.agentserver.agent_ws_server import AgentWebSocketServer-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)class SendFileToolkit:diff --git a/jiuwenclaw/agentserver/tools/task_tools.py b/jiuwenclaw/agentserver/tools/task_tools.pyindex 9dcaf280a4..538dce64f5 100644--- a/jiuwenclaw/agentserver/tools/task_tools.py+++ b/jiuwenclaw/agentserver/tools/task_tools.py@@ -2,6 +2,7 @@"""Task tools - wraps TaskMemoryService as @tool decorated functions."""+import loggingimport osfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -15,7 +16,9 @@ from jiuwenclaw.agentserver.tools import (tool,)-from jiuwenclaw.utils import USER_WORKSPACE_DIR, logger+from jiuwenclaw.utils import USER_WORKSPACE_DIR++logger = logging.getLogger(__name__)@dataclassdiff --git a/jiuwenclaw/agentserver/tools/video_tools.py b/jiuwenclaw/agentserver/tools/video_tools.pyindex 2a11d447c0..7bdd36dd19 100644--- a/jiuwenclaw/agentserver/tools/video_tools.py+++ b/jiuwenclaw/agentserver/tools/video_tools.py@@ -3,6 +3,7 @@from __future__ import annotations+import loggingimport asyncioimport base64import mimetypes@@ -15,9 +16,11 @@ import requestsfrom openjiuwen.core.foundation.tool import toolfrom jiuwenclaw.config import get_config-from jiuwenclaw.utils import get_config_file, logger+from jiuwenclaw.utils import get_config_filefrom jiuwenclaw.agentserver.tools.multimodal_config import apply_video_model_config_from_yaml++logger = logging.getLogger(__name__)_USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) "diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.pyindex 87b4c92395..19eb18e63d 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py@@ -12,17 +12,19 @@from __future__ import annotationsimport json+import loggingfrom typing import Any, Dict, List, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="create_alarm",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.pyindex 0636766cb9..cdbda5ef8f 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py@@ -11,11 +11,13 @@from __future__ import annotationsimport asyncio+import loggingfrom typing import Any, Callable, Dict, Optional-from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.xiaoyi_channel import get_xiaoyi_channel+logger = logging.getLogger(__name__)+class ToolInputError(Exception):"""工具输入参数错误.@@ -102,7 +104,10 @@ async def execute_device_command(result_event.set()else:- logger.debug(f"[{intent_name}_TOOL] Intent name mismatch: expected={intent_name}, got={event.intent_name}")+ logger.debug(+ f"[%s_TOOL] Intent name mismatch: expected=%s, got=%s",+ intent_name, intent_name, event.intent_name+ )# 注册处理器channel.register_data_event_handler(intent_name, on_data_event)diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.pyindex 7e0da7e34e..a4a16eafab 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py@@ -9,11 +9,14 @@from __future__ import annotations+import loggingfrom datetime import datetimefrom typing import Any, Dict, List, Optionalfrom openjiuwen.core.foundation.tool import tool+logger = logging.getLogger(__name__)+def _format_timestamp_to_datetime(timestamp_ms: int) -> str:"""将毫秒时间戳转换为 yyyy-mm-dd hh:mm:ss 格式.@@ -46,7 +49,6 @@ def _convert_event_timestamps(event: Dict[str, Any]) -> Dict[str, Any]:result["dtEnd"] = _format_timestamp_to_datetime(result["dtEnd"])return result-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,validate_required_params,diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.pyindex 85db8067bf..0fc837e1a6 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py@@ -8,17 +8,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="xiaoyi_collection",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.pyindex ef95b23b36..7f3991b7ab 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py@@ -8,17 +8,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="search_contacts",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.pyindex 7dcdb48606..837ae2e055 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py@@ -10,17 +10,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dict, List, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="search_files",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.pyindex 97f54a8dd5..b00c9a0c70 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py@@ -10,13 +10,15 @@ from __future__ import annotationsimport asyncioimport json+import loggingfrom typing import Any, Dict, Listfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import execute_device_command, format_success_response+logger = logging.getLogger(__name__)+@tool(name="get_user_location",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.pyindex bc75c7c78b..34058c0c53 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py@@ -8,17 +8,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="search_messages",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.pyindex 83e259b93f..dcd1ef917c 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py@@ -10,11 +10,11 @@from __future__ import annotations+import loggingfrom typing import Any, Dict, List, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,validate_required_params,@@ -23,6 +23,8 @@ from .base import (ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="create_note",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.pyindex eca808d239..92ab960a46 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py@@ -8,17 +8,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dictfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="call_phone",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.pyindex b2e2f9ba9a..dcf4a0aa1e 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py@@ -10,17 +10,19 @@from __future__ import annotationsimport json+import loggingfrom typing import Any, Dict, List, Optionalfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="search_photo_gallery",diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.pyindex f3d16a44d4..cc0a60a9b5 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py@@ -8,17 +8,19 @@from __future__ import annotations+import loggingfrom typing import Any, Dictfrom openjiuwen.core.foundation.tool import tool-from jiuwenclaw.utils import loggerfrom .base import (execute_device_command,format_success_response,ToolInputError,)+logger = logging.getLogger(__name__)+@tool(name="send_message",diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex 62ff29ccef..09bbb87db8 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -52,7 +52,6 @@ from jiuwenclaw.utils import (get_config_file,get_env_file,get_root_dir,- logger,)from jiuwenclaw.config import (get_config,@@ -68,6 +67,8 @@ from jiuwenclaw.config import (from jiuwenclaw.updater import WindowsUpdaterServicefrom jiuwenclaw.version import __version__+logger = logging.getLogger(__name__)+_PROJECT_ROOT = get_root_dir()_ENV_FILE = get_env_file()load_dotenv(dotenv_path=_ENV_FILE)diff --git a/jiuwenclaw/app_web.py b/jiuwenclaw/app_web.pyindex c9cfa7d424..7e02f23cc6 100644--- a/jiuwenclaw/app_web.py+++ b/jiuwenclaw/app_web.py@@ -136,7 +136,7 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):project_root = Path(".").resolve()workspace_root = Path(".").resolve()logs_root = Path(".").resolve()- logger = logging.getLogger("jiuwenclaw.web.static")+ logger = logging.getLogger(__name__)_HOP_BY_HOP_HEADERS = {"connection",@@ -770,25 +770,22 @@ def _normalize_ws_target(value: str) -> str:def _setup_logger(logs_root: Path, log_level: str) -> logging.Logger:logs_root.mkdir(parents=True, exist_ok=True)- logger = logging.getLogger("jiuwenclaw.web.static")- logger.setLevel(getattr(logging, log_level.upper(), logging.INFO))- logger.propagate = False- logger.handlers.clear()+ lg = logging.getLogger(__name__)+ lg.setLevel(getattr(logging, log_level.upper(), logging.INFO))+ lg.propagate = True+ for h in lg.handlers[:]:+ h.close()+ lg.removeHandler(h)formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d %(levelname)s %(name)s: %(message)s",datefmt="%Y-%m-%d %H:%M:%S",)- stream_handler = logging.StreamHandler()- stream_handler.setFormatter(formatter)-file_handler = logging.FileHandler(logs_root / "ws-dev.log", mode="w", encoding="utf-8")file_handler.setFormatter(formatter)-- logger.addHandler(stream_handler)- logger.addHandler(file_handler)- return logger+ lg.addHandler(file_handler)+ return lgdef main() -> None:diff --git a/jiuwenclaw/channel/base.py b/jiuwenclaw/channel/base.pyindex 2ed73389c4..bb1657eaa3 100644--- a/jiuwenclaw/channel/base.py+++ b/jiuwenclaw/channel/base.py@@ -1,5 +1,6 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+import loggingimport asyncioimport timefrom abc import ABC, abstractmethod@@ -7,9 +8,10 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import TYPE_CHECKING, Any, Callable, Awaitable-from jiuwenclaw.utils import loggerfrom jiuwenclaw.schema.message import Message++logger = logging.getLogger(__name__)if TYPE_CHECKING:passdiff --git a/jiuwenclaw/channel/dingding.py b/jiuwenclaw/channel/dingding.pyindex 01cc80cbc3..d79b4fff2e 100644--- a/jiuwenclaw/channel/dingding.py+++ b/jiuwenclaw/channel/dingding.py@@ -1,9 +1,9 @@import asyncioimport json+import loggingimport timefrom typing import Any, Callable-from loguru import loggerfrom pydantic import BaseModel, Fieldimport httpx@@ -11,6 +11,8 @@ import httpxfrom jiuwenclaw.channel.base import RobotMessageRouter, BaseChannelfrom jiuwenclaw.schema.message import Message, ReqMethod+logger = logging.getLogger(__name__)+class DingTalkConfig(BaseModel):"""钉钉通道配置(使用Stream模式)"""@@ -420,7 +422,7 @@ class DingTalkChannel(BaseChannel):if resp.status_code != 200:logger.error(f"钉钉消息发送失败: {resp.text}")else:- logger.debug(f"钉钉消息已发送至 {chat_id}")+ logger.debug("钉钉消息已发送至 %s", chat_id)except Exception as e:logger.error(f"发送钉钉消息时出错: {e}")diff --git a/jiuwenclaw/channel/discord_channel.py b/jiuwenclaw/channel/discord_channel.pyindex 6f9130809c..4abe2c59af 100644--- a/jiuwenclaw/channel/discord_channel.py+++ b/jiuwenclaw/channel/discord_channel.py@@ -2,6 +2,7 @@from __future__ import annotations+import loggingimport asyncioimport timefrom dataclasses import dataclass, field@@ -9,7 +10,8 @@ from typing import Any, Callablefrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import EventType, Message, ReqMethod-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)try:import discorddiff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.pyindex 8d3152cce4..60e10dd1cf 100644--- a/jiuwenclaw/channel/feishu.py+++ b/jiuwenclaw/channel/feishu.py@@ -1,5 +1,6 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+import loggingimport asyncioimport concurrent.futuresimport types@@ -12,11 +13,14 @@ from typing import Any, Callablefrom pydantic import BaseModel, Field-from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.base import RobotMessageRouter, BaseChannelfrom jiuwenclaw.schema.message import Message, ReqMethod, EventType++logger = logging.getLogger(__name__)++class FeishuConfig(BaseModel):"""飞书通道配置模型,使用WebSocket长连接接收消息。"""@@ -408,7 +412,7 @@ class FeishuChannel(BaseChannel):f"添加消息反应失败: 错误码={response.code}, 消息={response.msg}")else:- logger.debug(f"已为消息 {message_id} 添加 {emoji_type} 表情")+ logger.debug("已为消息 %s 添加 %s 表情", message_id, emoji_type)except Exception as e:logger.warning(f"添加消息反应时发生异常: {e}")@@ -964,7 +968,7 @@ class FeishuChannel(BaseChannel):f"消息={response.msg}, 日志ID={response.get_log_id()}")else:- logger.debug(f"已向 {msg_id} 发送飞书消息")+ logger.debug("已向 %s 发送飞书消息", msg_id)def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:"""diff --git a/jiuwenclaw/channel/telegram_channel.py b/jiuwenclaw/channel/telegram_channel.pyindex bd8a53c0bb..688ab2ce75 100644--- a/jiuwenclaw/channel/telegram_channel.py+++ b/jiuwenclaw/channel/telegram_channel.py@@ -9,11 +9,13 @@ import timefrom dataclasses import dataclass, fieldfrom typing import Any, Callable-from loguru import logger+import loggingfrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import Message, ReqMethod+logger = logging.getLogger(__name__)+try:from telegram import Updatefrom telegram.ext import (@@ -136,7 +138,7 @@ class TelegramChannel(BaseChannel):await asyncio.sleep(1)except Exception as e:- logger.error("Telegram Bot 启动失败: {}", e)+ logger.error("Telegram Bot 启动失败: %s", e)self._running = Falseraise@@ -151,7 +153,7 @@ class TelegramChannel(BaseChannel):await self._application.stop()await self._application.shutdown()except Exception as e:- logger.warning("Error stopping Telegram Bot: {}", e)+ logger.warning("Error stopping Telegram Bot: %s", e)logger.info("Telegram Bot 已停止")@@ -198,7 +200,7 @@ class TelegramChannel(BaseChannel):else:raise- logger.debug(f"Telegram message sent to chat_id={chat_id}")+ logger.debug("Telegram message sent to chat_id=%s", chat_id)except Exception as e:logger.error(f"Error sending Telegram message: {type(e).__name__}: {e}")@@ -301,7 +303,8 @@ class TelegramChannel(BaseChannel):# off 模式: 不响应群聊消息if group_mode == "off":logger.debug(- f"Telegram group chat mode is 'off', ignoring message from chat_id={chat_id}"+ "Telegram group chat mode is 'off', ignoring message from chat_id=%s",+ chat_id)return@@ -346,7 +349,7 @@ class TelegramChannel(BaseChannel):try:await update.message.set_reaction("👀") # 使用眼睛表情表示"正在查看"except Exception as e:- logger.debug(f"Failed to set reaction: {e}")+ logger.debug("Failed to set reaction: %s", e)# 生成或获取 session_idsession_id = self._chat_sessions.get(chat_id)diff --git a/jiuwenclaw/channel/web_channel.py b/jiuwenclaw/channel/web_channel.pyindex 62b2dc9218..c30ab4708a 100644--- a/jiuwenclaw/channel/web_channel.py+++ b/jiuwenclaw/channel/web_channel.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport inspectimport json+import loggingimport osimport secretsimport time@@ -20,10 +21,12 @@ from urllib.parse import parse_qs, urlparseimport aiohttp-from jiuwenclaw.utils import get_workspace_dir, logger+from jiuwenclaw.utils import get_workspace_dirfrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import Message, Mode, ReqMethod+logger = logging.getLogger(__name__)+# ── 类型别名 ──────────────────────────────────────────────# 方法处理器签名: (ws, req_id, params, session_id) -> NoneMethodHandler = Callable[..., Awaitable[None]]diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.pyindex b149c14aa0..08457d2247 100644--- a/jiuwenclaw/channel/wecom_channel.py+++ b/jiuwenclaw/channel/wecom_channel.py@@ -4,6 +4,7 @@from __future__ import annotations+import loggingimport asyncioimport reimport time@@ -11,10 +12,11 @@ from typing import Any, Callablefrom pydantic import BaseModel, Field-from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import Message, ReqMethod, EventType+logger = logging.getLogger(__name__)+try:from wecom_aibot_sdk import WSClientfrom wecom_aibot_sdk.utils import generate_req_iddiff --git a/jiuwenclaw/channel/whatsapp_channel.py b/jiuwenclaw/channel/whatsapp_channel.pyindex 8442578d93..688ee16c74 100644--- a/jiuwenclaw/channel/whatsapp_channel.py+++ b/jiuwenclaw/channel/whatsapp_channel.py@@ -2,6 +2,7 @@from __future__ import annotations+import loggingimport asyncioimport inspectimport json@@ -13,7 +14,9 @@ from typing import Any, Callablefrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import EventType, Message, ReqMethod-from jiuwenclaw.utils import logger+++logger = logging.getLogger(__name__)@dataclassdiff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex f4f0c5cd17..6b134a3555 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -4,6 +4,7 @@from __future__ import annotations+import loggingimport asyncioimport base64import hmac@@ -19,7 +20,6 @@ from urllib.parse import urlparseimport aiohttp-from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import EventType, Message, ReqMethodfrom jiuwenclaw.channel.xiaoyi_utils.push import XiaoYiPushService, PushConfig@@ -29,6 +29,8 @@ from jiuwenclaw.channel.xiaoyi_utils.formatter import (should_send_as_status_update,)+logger = logging.getLogger(__name__)+FILE_TYPE_TO_MIME_TYPE: dict[str, str] = {"txt": "text/plain",@@ -1239,7 +1241,7 @@ class XiaoyiChannel(BaseChannel):async def _handle_data_event(self, event: DataEvent) -> None:"""分发 data-event 到注册的处理器."""logger.info(f"[XiaoyiChannel] 分发 data-event: intent={event.intent_name}, status={event.status}")- logger.debug(f"[XiaoyiChannel] 已注册处理器: {list(self._data_event_handlers.keys())}")+ logger.info(f"[XiaoyiChannel] 已注册处理器: {list(self._data_event_handlers.keys())}")handlers = self._data_event_handlers.get(event.intent_name, [])if not handlers:@@ -1275,7 +1277,6 @@ class XiaoyiChannel(BaseChannel):# 参考 xy_channel websocket.ts:569-606msg_type = message.get("msgType")method = message.get("method")- logger.debug(f"[XiaoyiChannel] _extract_data_event: msg_type={msg_type}, method={method}")if msg_type == "data":try:# 从 msgDetail 解析 A2A JSON-RPC 请求diff --git a/jiuwenclaw/channel/xiaoyi_utils/formatter.py b/jiuwenclaw/channel/xiaoyi_utils/formatter.pyindex 98ec90d525..cc23018803 100644--- a/jiuwenclaw/channel/xiaoyi_utils/formatter.py+++ b/jiuwenclaw/channel/xiaoyi_utils/formatter.py@@ -10,7 +10,6 @@ import uuidfrom dataclasses import dataclassfrom typing import Any-from jiuwenclaw.utils import loggerfrom jiuwenclaw.schema.message import EventType, Messagediff --git a/jiuwenclaw/channel/xiaoyi_utils/media.py b/jiuwenclaw/channel/xiaoyi_utils/media.pyindex 4aeddf6110..a9c5934c5a 100644--- a/jiuwenclaw/channel/xiaoyi_utils/media.py+++ b/jiuwenclaw/channel/xiaoyi_utils/media.py@@ -7,12 +7,15 @@import asyncioimport base64from dataclasses import dataclass+import loggingimport osfrom typing import Anyimport aiohttp-from jiuwenclaw.utils import logger, get_xy_tmp_dir+from jiuwenclaw.utils import get_xy_tmp_dir++logger = logging.getLogger(__name__)_TMP_MEDIA_PATH = get_xy_tmp_dir()diff --git a/jiuwenclaw/channel/xiaoyi_utils/push.py b/jiuwenclaw/channel/xiaoyi_utils/push.pyindex 856457b75a..0ad9ef397d 100644--- a/jiuwenclaw/channel/xiaoyi_utils/push.py+++ b/jiuwenclaw/channel/xiaoyi_utils/push.py@@ -2,6 +2,7 @@"""XiaoYi Push Message Service - 主动推送消息服务."""+import loggingimport base64import hashlibimport hmac@@ -12,7 +13,8 @@ from typing import Anyimport aiohttp-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)PUSH_URL = "https://hag.cloud.huawei.com/open-ability-agent/v1/agent-webhook"@@ -75,13 +77,13 @@ class XiaoYiPushService:"id": self._generate_uuid(),"apiId": self.config.api_id,"pushId": self.config.push_id,- "pushText": push_text,+ "pushText": text,"kind": "task","artifacts": [{"artifactId": self._generate_uuid(),"parts": [{"kind": "text",- "text": text,+ "text": push_text,}]}],"status": {"state": "completed"}diff --git a/jiuwenclaw/evolution/evolver.py b/jiuwenclaw/evolution/evolver.pyindex 18ffd346f9..f3758b23bb 100644--- a/jiuwenclaw/evolution/evolver.py+++ b/jiuwenclaw/evolution/evolver.py@@ -3,6 +3,7 @@"""SkillEvolver - LLM-based experience generation with deduplication."""from __future__ import annotations+import loggingimport jsonimport refrom typing import Any, List, Optional@@ -15,7 +16,8 @@ from jiuwenclaw.evolution.schema import (ExperienceTarget,VALID_SECTIONS,)-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)_GENERATE_PROMPT = """\你是一个 Skill 优化专家。根据对话中发现的问题信号和对话历史,为 Skill 生成演进经验。diff --git a/jiuwenclaw/evolution/service.py b/jiuwenclaw/evolution/service.pyindex 55c9fcc71b..22d8f554bc 100644--- a/jiuwenclaw/evolution/service.py+++ b/jiuwenclaw/evolution/service.py@@ -3,6 +3,7 @@"""EvolutionService - Unified facade for the skill evolution system."""from __future__ import annotations+import loggingimport asyncioimport jsonimport uuid@@ -17,7 +18,8 @@ from jiuwenclaw.evolution.schema import ()from jiuwenclaw.evolution.signal_detector import SignalDetectorfrom jiuwenclaw.evolution.store import EvolutionStore-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)_APPROVAL_TIMEOUT = 300 # seconds_MAX_PROCESSED_SIGNAL_KEYS = 500 # safety cap to prevent unbounded growth across sessionsdiff --git a/jiuwenclaw/evolution/store.py b/jiuwenclaw/evolution/store.pyindex a3e94b8d2e..9acc6cdc1a 100644--- a/jiuwenclaw/evolution/store.py+++ b/jiuwenclaw/evolution/store.py@@ -3,6 +3,7 @@"""EvolutionStore - Pure IO layer for skill evolution data."""from __future__ import annotations+import loggingimport jsonimport refrom datetime import datetime, timezone@@ -15,7 +16,8 @@ from jiuwenclaw.evolution.schema import (EvolutionFile,ExperienceTarget,)-from jiuwenclaw.utils import logger++logger = logging.getLogger(__name__)_EVOLUTION_FILENAME = "evolutions.json"diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.pyindex 077fa10391..52ad4b8fa5 100644--- a/jiuwenclaw/gateway/agent_client.py+++ b/jiuwenclaw/gateway/agent_client.py@@ -4,16 +4,19 @@from __future__ import annotations+import loggingimport asyncioimport jsonfrom abc import ABC, abstractmethodfrom dataclasses import asdictfrom typing import Any, AsyncIterator-from jiuwenclaw.utils import loggerfrom jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+logger = logging.getLogger(__name__)++def _to_json(data: Any) -> str:"""将任意对象序列化为日志友好的 JSON 字符串."""try:diff --git a/jiuwenclaw/gateway/channel_manager.py b/jiuwenclaw/gateway/channel_manager.pyindex 369597b465..f677f7ba2d 100644--- a/jiuwenclaw/gateway/channel_manager.py+++ b/jiuwenclaw/gateway/channel_manager.py@@ -4,16 +4,18 @@from __future__ import annotations+import loggingimport asynciofrom abc import ABCfrom typing import TYPE_CHECKING, Any, Awaitable, Callable+logger = logging.getLogger(__name__)+if TYPE_CHECKING:from jiuwenclaw.channel.base import BaseChannelfrom jiuwenclaw.gateway.message_handler import MessageHandlerfrom jiuwenclaw.schema.message import Message-from jiuwenclaw.utils import loggerclass ChannelManager(ABC):diff --git a/jiuwenclaw/gateway/heartbeat.py b/jiuwenclaw/gateway/heartbeat.pyindex d45935abf7..d9c9a5cef4 100644--- a/jiuwenclaw/gateway/heartbeat.py+++ b/jiuwenclaw/gateway/heartbeat.py@@ -4,13 +4,15 @@from __future__ import annotations+import loggingimport asyncioimport timefrom abc import ABC, abstractmethodfrom dataclasses import dataclassfrom typing import TYPE_CHECKING-from jiuwenclaw.utils import logger+logger = logging.getLogger(__name__)+if TYPE_CHECKING:from jiuwenclaw.gateway.agent_client import AgentServerClientfrom jiuwenclaw.gateway.message_handler import MessageHandlerdiff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.pyindex a42907086f..df6dde8b9f 100644--- a/jiuwenclaw/gateway/message_handler.py+++ b/jiuwenclaw/gateway/message_handler.py@@ -4,6 +4,7 @@from __future__ import annotations+import loggingimport asyncioimport secretsimport time@@ -12,7 +13,9 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import TYPE_CHECKING, Any, Dict-from jiuwenclaw.utils import logger+++logger = logging.getLogger(__name__)class ChannelMode(str, Enum):diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 4057a89a57..8486a15ee1 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -1,6 +1,18 @@# 前端显示语言:zh(中文)/ en(英文),与 Web 界面语言切换同步preferred_language: zh+# 日志目录:~/.jiuwenclaw/.logs/+# gateway.log / channel.log / agent_server.log 按源码路径分流;full.log 为汇总。+# level:未单独指定时的默认级别。console_level:控制台;可省略则用 level。+# 环境变量 LOG_LEVEL 仅覆盖控制台级别(不覆盖各日志文件)。+logging:+ level: INFO+ console_level: INFO+ gateway: INFO+ channel: INFO+ agent_server: INFO+ full: INFO+models:default:model_client_config:diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.pyindex 3052cf2411..b636365618 100644--- a/jiuwenclaw/utils.py+++ b/jiuwenclaw/utils.py@@ -11,21 +11,199 @@ Runtime layout:- ~/.jiuwenclaw/agent/sessions- ~/.jiuwenclaw/agent/workspace(运行时文件与 agent-data.json)- ~/.jiuwenclaw/.checkpoint-- ~/.jiuwenclaw/.logs+- ~/.jiuwenclaw/.logs(gateway.log / channel.log / agent_server.log / full.log)内置模板位于包内 ``jiuwenclaw/resources/``(含 ``agent/`` 下 HEARTBEAT_ZH/EN、PRINCIPLE、TONE 等,以及 ``skills_state.json``)。"""-import importlib.util-import loggingimport os-import shutilimport sys+import datetime+import shutilfrom pathlib import Path+from dataclasses import dataclassfrom typing import Any, Literal, Optional-from logging.handlers import RotatingFileHandler+import logging+from logging.handlers import BaseRotatingHandlerfrom ruamel.yaml import YAML+_LOG_FILE_MAX_BYTES = 20 * 1024 * 1024+_LOG_FILE_BACKUP_COUNT = 20+++@dataclass+class LoggingLevels:+ """Container for logging level configuration."""+ logger: int+ console: int+ gateway: int+ channel: int+ agent_server: int+ full: int+++class SafeRotatingFileHandler(BaseRotatingHandler):+ """Safe rotating file handler"""++ def __init__(self, filename, maxBytes=0, backupCount=0, encoding=None,+ delay=False, errors=None):+ """Initialize the handler."""+ super().__init__(filename, 'a', encoding, errors)+ self.max_bytes = maxBytes+ self.backup_count = backupCount+ self._current_filename = filename++ if delay:+ self.stream = None++ def shouldRollover(self, record):+ """+ Determine if rollover should occur.++ Returns True if the log file size exceeds maxBytes.+ """+ if self.stream is None:+ return False+ if self.max_bytes > 0:+ msg = "%s\n" % self.format(record)+ self.stream.seek(0, 2) # Seek to end of file+ if self.stream.tell() + len(msg) >= self.max_bytes:+ return True+ return False++ def doRollover(self):+ """+ Perform log rotation to keep app.log as the active log file.+ """+ base_path = Path(self.baseFilename)++ timestamp = datetime.datetime.now(tz=datetime.timezone.utc).strftime("%Y%m%d_%H%M%S")+ backup_filename = base_path.parent / f"{base_path.stem}_{timestamp}{base_path.suffix}"++ try:+ if base_path.exists():+ shutil.copy2(base_path, backup_filename)+ except OSError as e:+ print(f"WARNING: Could not copy log file to backup: {e}", file=sys.stderr)++ # Clean up old backup files+ self._cleanup_old_backups()++ try:+ if self.stream:+ self.stream.seek(0) # Seek to beginning+ self.stream.truncate(0) # Truncate to 0 bytes+ except OSError as e:+ print(f"WARNING: Could not truncate log file: {e}", file=sys.stderr)++ def _cleanup_old_backups(self):+ """+ Remove old backup files if they exceed backupCount.++ Backup files are sorted by modification time (oldest first).+ """+ if self.backup_count <= 0:+ return++ try:+ base_path = Path(self.baseFilename)+ log_dir = base_path.parent++ backup_files = []+ for f in log_dir.glob(f"{base_path.stem}_*{base_path.suffix}"):+ if f.is_file() and f != base_path:+ backup_files.append(f)++ # Sort by modification time (oldest first)+ backup_files.sort(key=lambda x: x.stat().st_mtime)++ # Remove excess files+ files_to_delete = len(backup_files) - self.backup_count+ if files_to_delete > 0:+ for f in backup_files[:files_to_delete]:+ try:+ f.unlink()+ except OSError as e:+ print(f"WARNING: Could not delete old log file {f}: {e}", file=sys.stderr)+ except Exception as e:+ print(f"WARNING: Error during backup cleanup: {e}", file=sys.stderr)+++def _parse_log_level(name: str, default: int = logging.INFO) -> int:+ """Parse level name to logging module constant."""+ if not name or not isinstance(name, str):+ return default+ return getattr(logging, name.strip().upper(), default)+++def _log_component_from_logger_name(name: str) -> str:+ """按 ``logging.getLogger(__name__)`` 的 logger 名划分 gateway / channel / agent_server。"""+ if name.startswith("jiuwenclaw.channel"):+ return "channel"+ if name.startswith("jiuwenclaw.agentserver"):+ return "agent_server"+ return "gateway"+++class _ComponentNameFilter(logging.Filter):+ """仅放行指定组件(由 logger 名判定)的日志记录。"""++ def __init__(self, component: str) -> None:+ super().__init__()+ self.component = component++ def filter(self, record: logging.LogRecord) -> bool:+ return _log_component_from_logger_name(record.name) == self.component+++def _load_logging_config_from_yaml() -> dict[str, Any]:+ """读取 ~/.jiuwenclaw/config/config.yaml 中的 logging 段(无则空)。"""+ try:+ cf = get_config_file()+ if not cf.exists():+ return {}+ rt = YAML()+ with open(cf, "r", encoding="utf-8") as f:+ data = rt.load(f) or {}+ raw = data.get("logging")+ if isinstance(raw, dict):+ return raw+ except Exception as e:+ logger.error(f"load logging config failed, caused by={e}")+ return {}+++def _resolve_logging_levels(+ log_level_override: Optional[str],+) -> LoggingLevels:+ """返回日志级别配置。"""+ cfg = _load_logging_config_from_yaml()+ base = _parse_log_level(str(cfg.get("level", "INFO")))++ def _coerce(key: str) -> int:+ if key in cfg and cfg[key] is not None:+ return _parse_log_level(str(cfg[key]), base)+ return base++ console = _coerce("console_level")+ env_console = os.getenv("LOG_LEVEL")+ if env_console:+ console = _parse_log_level(env_console, console)++ gateway = _coerce("gateway")+ channel = _coerce("channel")+ agent_server = _coerce("agent_server")+ full = _coerce("full")++ if log_level_override is not None:+ v = _parse_log_level(log_level_override)+ console = gateway = channel = agent_server = full = v+ logger_level = v+ else:+ logger_level = min(gateway, channel, agent_server, full)++ return LoggingLevels(logger_level, console, gateway, channel, agent_server, full)+# User home directory@@ -400,36 +578,64 @@ def is_package_installation() -> bool:return _detect_installation_mode()-def setup_logger(log_level: str = "INFO") -> logging.Logger:- """Setup logger with console and file handlers."""+def setup_logger(log_level: Optional[str] = None) -> logging.Logger:+ """配置 ``jiuwenclaw`` 根日志:控制台 + 分组件文件 + 汇总 full.log。++ 各模块应使用 ``logging.getLogger(__name__)``,分文件规则:+ - ``jiuwenclaw.channel.*`` → channel.log+ - ``jiuwenclaw.agentserver.*`` → agent_server.log+ - 其余 ``jiuwenclaw.*``(含 ``jiuwenclaw.app``、gateway、evolution、utils 等)→ gateway.log++ 所有分类日志同时写入 ``full.log``。输出目录:``~/.jiuwenclaw/.logs/``。++ 级别由 ``config.yaml`` 的 ``logging`` 段控制;环境变量 ``LOG_LEVEL`` 仅覆盖**控制台**级别+ (``log_level`` 参数为 ``None`` 时)。若传入 ``log_level``(如单测),则控制台与各文件级别均为该值。+ """logs_root = get_logs_dir()logs_root.mkdir(parents=True, exist_ok=True)- logger = logging.getLogger("jiuwenclaw.app")- logger.setLevel(getattr(logging, log_level.upper(), logging.INFO))- logger.propagate = False- for handler in logger.handlers[:]:+ levels = _resolve_logging_levels(log_level)++ root = logging.getLogger("jiuwenclaw")+ root.setLevel(levels.logger)+ root.propagate = False+ for handler in root.handlers[:]:handler.close()- logger.removeHandler(handler)+ root.removeHandler(handler)formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d %(levelname)s %(name)s: %(message)s",datefmt="%Y-%m-%d %H:%M:%S",)+ def _add_rotating(+ filename: str,+ level: int,+ name_filter: Optional[_ComponentNameFilter] = None,+ ) -> None:+ h = SafeRotatingFileHandler(+ filename=logs_root / filename,+ maxBytes=_LOG_FILE_MAX_BYTES,+ backupCount=_LOG_FILE_BACKUP_COUNT,+ encoding="utf-8",+ )+ h.setLevel(level)+ h.setFormatter(formatter)+ if name_filter is not None:+ h.addFilter(name_filter)+ root.addHandler(h)++ _add_rotating("gateway.log", levels.gateway, _ComponentNameFilter("gateway"))+ _add_rotating("channel.log", levels.channel, _ComponentNameFilter("channel"))+ _add_rotating("agent_server.log", levels.agent_server, _ComponentNameFilter("agent_server"))+ _add_rotating("full.log", levels.full, None)+stream_handler = logging.StreamHandler()+ stream_handler.setLevel(levels.console)stream_handler.setFormatter(formatter)+ root.addHandler(stream_handler)+ return root- file_handler = RotatingFileHandler(- filename=logs_root / "app.log",- maxBytes=20 * 1024 * 1024,- backupCount=20,- encoding="utf-8"- )- file_handler.setFormatter(formatter)-- logger.addHandler(stream_handler)- logger.addHandler(file_handler)- return logger-logger = setup_logger(os.getenv("LOG_LEVEL", "INFO"))+setup_logger()+logger = logging.getLogger(__name__)diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsxindex 251475941b..ac92e011ed 100644--- a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx@@ -44,6 +44,7 @@ type XiaoyiConfig = {ak: string;sk: string;agent_id: string;+ api_id: string;enable_streaming: boolean;};@@ -52,6 +53,7 @@ type XiaoyiDraft = {ak: string;sk: string;agent_id: string;+ api_id: string;enable_streaming: boolean;};@@ -164,6 +166,7 @@ const DEFAULT_XIAOYI_CONF: XiaoyiConfig = {ak: '',sk: '',agent_id: '',+ api_id: '',enable_streaming: true,};@@ -340,6 +343,7 @@ function normalizeXiaoyiConfig(input: unknown): XiaoyiConfig {ak: String(data.ak ?? '').trim(),sk: String(data.sk ?? '').trim(),agent_id: String(data.agent_id ?? '').trim(),+ api_id: String(data.api_id ?? '').trim(),enable_streaming: data.enable_streaming === undefined ? true : Boolean(data.enable_streaming),};}@@ -350,6 +354,7 @@ function draftFromXiaoyiConfig(conf: XiaoyiConfig): XiaoyiDraft {ak: conf.ak,sk: conf.sk,agent_id: conf.agent_id,+ api_id: conf.api_id,enable_streaming: conf.enable_streaming,};}@@ -360,6 +365,7 @@ function buildXiaoyiPayload(draft: XiaoyiDraft): Record<string, unknown> {ak: draft.ak.trim(),sk: draft.sk.trim(),agent_id: draft.agent_id.trim(),+ api_id: draft.api_id.trim(),enable_streaming: draft.enable_streaming,};}@@ -898,6 +904,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {baseDraft.ak !== xiaoyiDraft.ak ||baseDraft.sk !== xiaoyiDraft.sk ||baseDraft.agent_id !== xiaoyiDraft.agent_id ||+ baseDraft.api_id !== xiaoyiDraft.api_id ||baseDraft.enable_streaming !== xiaoyiDraft.enable_streaming);}, [xiaoyiConfig, xiaoyiDraft]);@@ -1467,7 +1474,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {</button></td></tr>- {(['ak', 'sk', 'agent_id'] as const).map((field) => (+ {(['ak', 'sk', 'agent_id', 'api_id'] as const).map((field) => (<tr key={field} className="border-t border-border first:border-t-0 even:bg-secondary/10"><td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{field}</td><td className="px-4 py-2.5 break-all text-[13px] align-middle">diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.pyindex 69bb5ed06f..95ecf56448 100644--- a/tests/unit/test_utils.py+++ b/tests/unit/test_utils.py@@ -74,9 +74,9 @@ class TestLoggerSetup:@staticmethoddef test_setup_logger_default():- """Test logger setup with default level."""- logger = utils.setup_logger()- assert logger.name == "jiuwenclaw.app"+ """Test logger setup with default level from explicit override."""+ logger = utils.setup_logger("INFO")+ assert logger.name == "jiuwenclaw"assert logger.level == 20 # INFO level@staticmethod@@ -93,11 +93,11 @@ class TestLoggerSetup:@staticmethoddef test_logger_handlers():- """Test that logger has both console and file handlers."""- logger = utils.setup_logger()+ """Test that logger has console and four rotating log files."""+ logger = utils.setup_logger("INFO")handler_types = [type(h).__name__ for h in logger.handlers]assert "StreamHandler" in handler_types- assert "RotatingFileHandler" in handler_types+ assert handler_types.count("SafeRotatingFileHandler") == 4class TestUserWorkspace: