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: 小艺 channel 流式模式 & 推送文件
ray_le4d0c6467afcd
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 28275c0451..39cf4f6c6c 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -1019,7 +1019,7 @@ class JiuWenClaw:yield AgentResponseChunk(request_id=request.request_id,channel_id=request.channel_id,- payload={"event_type": "chat.error", "error": "模型未正确配置,请先配置模型信息"},+ payload={"event_type": "chat.error", "error": "模型未正确配置,请先配置模型信息", "is_complete": True},is_complete=True,)return@@ -1130,14 +1130,14 @@ class JiuWenClaw:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=None,+ payload={"is_complete": True},is_complete=True,)else:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=None,+ payload={"is_complete": True},is_complete=True and self._session_tool.all_tasks_done(),)@@ -1248,13 +1248,6 @@ class JiuWenClaw:"current_task": "thinking",}- # llm_reasoning:模型推理/思考内容,不转为 chat.delta,避免发到企业微信- if chunk_type == "llm_reasoning":- return {- "event_type": "chat.processing_status",- "is_processing": True,- "current_task": "thinking",- }if chunk_type == "processing_complete":return {"event_type": "chat.processing_status",diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex 4f2f92bfe1..ce745ed4ac 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -1531,16 +1531,17 @@ async def _run() -> None:if not enabled:logger.info("[App] channels.xiaoyi.%s,XiaoyiChannel 未启用", reason)else:- if xiaoyi_conf.get("mode") == "xiaoyi_channel":+ if xiaoyi_conf.get("mode") == "xiaoyi_claw":xiaoyi_config = XiaoyiChannelConfig(enabled=True,- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_channel").strip(),- ak=str(xiaoyi_conf.get("ak") or "").strip(),- sk=str(xiaoyi_conf.get("sk") or "").strip(),+ mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),api_id=str(xiaoyi_conf.get("api_id") or "").strip(),push_id=str(xiaoyi_conf.get("push_id") or "").strip(),push_url=str(xiaoyi_conf.get("push_url") or "").strip(),agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),+ uid=str(xiaoyi_conf.get("uid") or "").strip(),+ api_key=str(xiaoyi_conf.get("api_key") or "").strip(),+ file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),@@ -1548,16 +1549,17 @@ async def _run() -> None:else:xiaoyi_config = XiaoyiChannelConfig(enabled=True,- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),+ mode=str(xiaoyi_conf.get("mode") or "xiaoyi_channel").strip(),+ ak=str(xiaoyi_conf.get("ak") or "").strip(),+ sk=str(xiaoyi_conf.get("sk") or "").strip(),api_id=str(xiaoyi_conf.get("api_id") or "").strip(),push_id=str(xiaoyi_conf.get("push_id") or "").strip(),push_url=str(xiaoyi_conf.get("push_url") or "").strip(),agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),- uid=str(xiaoyi_conf.get("uid") or "").strip(),- api_key=str(xiaoyi_conf.get("api_key") or "").strip(),- file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),- ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),- ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),+ ws_url1=str(xiaoyi_conf.get("ws_url1") or "").strip() \+ or "wss://hag.cloud.huawei.com/openclaw/v1/ws/link",+ ws_url2=str(xiaoyi_conf.get("ws_url2") or "").strip() \+ or "wss://116.63.174.231/openclaw/v1/ws/link",enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),)xiaoyi_channel = XiaoyiChannel(xiaoyi_config, _DummyBus())diff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex 525e311dcb..ff31f1986c 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -48,10 +48,6 @@ class XiaoyiChannelConfig:task_timeout_ms: int = 3600000# Session cleanup timeout in milliseconds (default: 1 hour)session_cleanup_timeout_ms: int = 3600000- # File upload service configuration- file_upload_base_url: str = ""- file_upload_api_key: str = ""- file_upload_uid: str = ""def _generate_signature(sk: str, timestamp: str) -> str:@@ -97,7 +93,7 @@ class XYFileUploadService:"uid": self.uid,"teamId": self.uid,},- "useEdge": False,+ "useEdge": True,}headers = {@@ -205,9 +201,9 @@ class XiaoyiChannel(BaseChannel):self._sessions_marked_for_cleanup: dict[str, dict[str, Any]] = {} # Session cleanup state# File upload service configurationself.file_upload_config = {- "baseUrl": config.file_upload_base_url,- "apiKey": config.file_upload_api_key,- "uid": config.file_upload_uid,+ "baseUrl": config.file_upload_url,+ "apiKey": config.api_key,+ "uid": config.uid,}# Save additional configuration fieldsself.api_id = config.api_id@@ -313,9 +309,8 @@ class XiaoyiChannel(BaseChannel):if not self._ws_connections:returnsession_id, task_id = self._extract_platform_receive_info(msg)-# Handle chat.file event- if msg.event_type == EventType.CHAT_FILE:+ if self.config.mode == "xiaoyi_claw" and msg.event_type == EventType.CHAT_FILE:files = msg.payload.get("files", []) if isinstance(msg.payload, dict) else []if files:for file_info in files:@@ -364,7 +359,9 @@ class XiaoyiChannel(BaseChannel):# 流式模式 - 类似 TS 版本的实现# 判断事件类型is_delta = msg.event_type == EventType.CHAT_DELTA- is_final = msg.event_type == EventType.CHAT_FINAL+ last_chunk = msg.event_type == EventType.CHAT_FINAL+ is_final = msg.payload.get("is_complete", False)+ last_chunk = True if is_final else last_chunk# 获取之前发送的文本previous_text = self._accumulated_texts.get(session_id, "")@@ -381,7 +378,7 @@ class XiaoyiChannel(BaseChannel):# 在消息流中,总是使用 append=true, isFinal=falseappend = Truefinal = False- last_chunk = is_final+ last_chunk = last_chunkfinal = is_final# Get accumulated text for this session (for push notification)@@ -718,7 +715,7 @@ class XiaoyiChannel(BaseChannel):await self.bus.route_user_message(user_message)# Start session heartbeat to prevent xiaoyi client timeout- if session_id:+ if not self.config.enable_streaming and session_id:await self._start_session_heartbeat(session_id, task_id)async def _start_session_heartbeat(self, session_id: str, task_id: str) -> None:@@ -937,170 +934,63 @@ class XiaoyiChannel(BaseChannel):if file_size > 20 * 1024 * 1024: # 20MB limitlogger.error(f"XiaoyiChannel 文件过大,使用OSMS上传: {file_path}")# Use OSMS upload for large files- base_url = self.file_upload_config.get("baseUrl")- api_key = self.file_upload_config.get("apiKey")- uid = self.file_upload_config.get("uid")-- if not all([base_url, api_key, uid]):- logger.error("XiaoyiChannel OSMS配置不完整,无法上传大文件")- return-- async with XYFileUploadService(base_url, api_key, uid) as upload_service:- object_id = await upload_service.upload_file(file_path)- if object_id:- # Send file reference response- response = {- "jsonrpc": "2.0",- "id": f"msg_{int(time.time() * 1000)}",- "result": {- "taskId": task_id,- "kind": "artifact-update",- "append": False,- "lastChunk": True,- "isFinal": True,- "artifact": {- "artifactId": f"artifact_{int(time.time() * 1000)}",- "parts": [- {- "kind": "artifact",- "artifact": {- "kind": "file",- "file": {- "objectId": object_id,- "fileName": file_name,- "contentType": "application/octet-stream"- }- }+ base_url = self.file_upload_config.get("baseUrl")+ api_key = self.file_upload_config.get("apiKey")+ uid = self.file_upload_config.get("uid")++ if not all([base_url, api_key, uid]):+ logger.error("XiaoyiChannel OSMS配置不完整,无法上传大文件")+ return++ object_id = ""+ async with XYFileUploadService(base_url, api_key, uid) as upload_service:+ object_id = await upload_service.upload_file(file_path)+ logger.info(f"file upload success: {object_id}")+ if object_id:+ # Send file reference response+ payload = {+ "jsonrpc": "2.0",+ "id": f"msg_{int(time.time() * 1000)}",+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": True,+ "lastChunk": False,+ "isFinal": False,+ "artifact": {+ "artifactId": task_id,+ "parts": [+ {+ "kind": "file",+ "file": {+ "fieldId": object_id,+ "name": file_name,+ "mimeType": file_name.split(".")[-1]}- ],- },+ }+ ],},+ },+ }+ response = {+ "msgType": "agent_response",+ "agentId": self.config.agent_id,+ "session_id": session_id,+ "task_id": task_id,+ "msgDetail": json.dumps(payload)}- await self._safe_ws_send(url_key, response)- return-- # Read file content as Base64- with open(file_path, "rb") as f:- file_content = f.read()-- base64_content = base64.b64encode(file_content).decode("utf-8")-- # Guess content type- import mimetypes- content_type, _ = mimetypes.guess_type(file_name)- if not content_type:- content_type = "application/octet-stream"-- # Send file response- response = {- "jsonrpc": "2.0",- "id": f"msg_{int(time.time() * 1000)}",- "result": {- "taskId": task_id,- "kind": "artifact-update",- "append": False,- "lastChunk": True,- "isFinal": True,- "artifact": {- "artifactId": f"artifact_{int(time.time() * 1000)}",- "parts": [- {- "kind": "file",- "file": {- "name": file_name,- "contentType": content_type,- "data": base64_content- }- }- ],- },- },- }- await self._safe_ws_send(url_key, response)+ await self._safe_ws_send(url_key, response)+ return object_idexcept Exception as e:logger.error(f"XiaoyiChannel 发送文件响应失败: {e}")async def _send_file_response(self, session_id: str, task_id: str, file_info: dict, url_key: str) -> None:"""发送文件响应到指定通道."""- try:- # Check if file info has content (Base64)- if file_info.get("content") and isinstance(file_info["content"], str):- # This is a file with Base64 content- file_name = file_info.get("fileName", "file.txt")- content_type = file_info.get("contentType", "application/octet-stream")- base64_content = file_info["content"]-- # Send file response with Base64 content- response = {- "jsonrpc": "2.0",- "id": f"msg_{int(time.time() * 1000)}",- "result": {- "taskId": task_id,- "kind": "artifact-update",- "append": False,- "lastChunk": True,- "isFinal": True,- "artifact": {- "artifactId": f"artifact_{int(time.time() * 1000)}",- "parts": [- {- "kind": "file",- "file": {- "name": file_name,- "contentType": content_type,- "data": base64_content- }- }- ],- },- },- }- await self._safe_ws_send(url_key, response)- return-+ try:# If file is available locally, send as Base64if file_info.get("fullPath") or file_info.get("path"):await self._send_file_response_base64(session_id, task_id, file_info, url_key)return-- # If file is already uploaded to OSMS- if file_info.get("objectId"):- file_name = file_info.get("fileName", "file.txt")- content_type = file_info.get("contentType", "application/octet-stream")- object_id = file_info["objectId"]-- # Send file reference response- response = {- "jsonrpc": "2.0",- "id": f"msg_{int(time.time() * 1000)}",- "result": {- "taskId": task_id,- "kind": "artifact-update",- "append": False,- "lastChunk": True,- "isFinal": True,- "artifact": {- "artifactId": f"artifact_{int(time.time() * 1000)}",- "parts": [- {- "kind": "artifact",- "artifact": {- "kind": "file",- "file": {- "objectId": object_id,- "fileName": file_name,- "contentType": content_type- }- }- }- ],- },- },- }- await self._safe_ws_send(url_key, response)- return-- logger.error(f"XiaoyiChannel 无法发送文件:无效的文件信息")except Exception as e:logger.error(f"XiaoyiChannel 发送文件响应失败: {e}")@@ -1140,11 +1030,14 @@ class XiaoyiChannel(BaseChannel):try:push_config = PushConfig(+ mode=self.config.mode,api_id=self.config.api_id,push_id=self.config.push_id,push_url=self.config.push_url,ak=self.config.ak,sk=self.config.sk,+ uid=self.config.uid,+ api_key=self.config.api_key)push_service = XiaoYiPushService(push_config)result = await push_service.send_push(text, push_text)diff --git a/jiuwenclaw/channel/xiaoyi_utils/formatter.py b/jiuwenclaw/channel/xiaoyi_utils/formatter.pynew file mode 100644index 0000000000..83b3678c71--- /dev/null+++ b/jiuwenclaw/channel/xiaoyi_utils/formatter.py@@ -0,0 +1,637 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""XiaoYi Formatter - 消息格式化和发送模块。+基于 TypeScript formatter.ts 实现。+"""++import json+import time+import uuid+from dataclasses import dataclass+from typing import Any++from jiuwenclaw.utils import logger+from jiuwenclaw.schema.message import EventType, Message+++# ==================== Data Classes ====================++@dataclass+class FileInfo:+ """文件信息."""+ file_name: str+ file_type: str+ file_id: str+++# ==================== A2A Protocol Builders ====================++def _build_agent_response_wrapper(+ agent_id: str,+ session_id: str,+ task_id: str,+ response_body: dict[str, Any],+) -> dict[str, Any]:+ """+ 构建 agent_response 包装消息(A2A 格式)。++ Args:+ agent_id: Agent ID+ session_id: Session ID+ task_id: Task ID+ response_body: JSON-RPC 响应体++ Returns:+ dict: agent_response 包装的消息+ """+ return {+ "msgType": "agent_response",+ "agentId": agent_id,+ "sessionId": session_id,+ "taskId": task_id,+ "msgDetail": json.dumps(response_body, ensure_ascii=False),+ }+++def _build_json_rpc_response(+ message_id: str,+ result: dict[str, Any],+) -> dict[str, Any]:+ """+ 构建 JSON-RPC 2.0 响应。++ Args:+ message_id: 消息 ID+ result: 结果对象++ Returns:+ dict: JSON-RPC 2.0 响应+ """+ return {+ "jsonrpc": "2.0",+ "id": message_id,+ "result": result,+ }+++def build_status_update_response(+ task_id: str,+ text: str,+ state: str,+) -> dict[str, Any]:+ """+ 构建 A2A status-update 事件。++ Args:+ task_id: Task ID+ text: 状态文本+ state: 状态值++ Returns:+ dict: status-update 事件+ """+ return {+ "taskId": task_id,+ "kind": "status-update",+ "final": False,+ "status": {+ "message": {+ "role": "agent",+ "parts": [+ {+ "kind": "text",+ "text": text,+ },+ ],+ },+ "state": state,+ },+ }+++def build_clear_context_response() -> dict[str, Any]:+ """+ 构建 clearContext 响应。++ Returns:+ dict: clearContext 响应+ """+ return {+ "status": {+ "state": "cleared",+ },+ "error": {+ "code": 0,+ "message": "",+ },+ }+++def build_tasks_cancel_response(task_id: str) -> dict[str, Any]:+ """+ 构建 tasks/cancel 响应。++ Args:+ task_id: Task ID++ Returns:+ dict: tasks/cancel 响应+ """+ return {+ "id": task_id,+ "status": {+ "state": "canceled",+ },+ "error": {+ "code": 0,+ "message": "",+ },+ }+++# ==================== Message Part Builders ====================++def build_text_part(text: str) -> dict[str, Any]:+ """+ 构建文本消息部分。++ Args:+ text: 文本内容++ Returns:+ dict: 文本消息部分+ """+ return {+ "kind": "text",+ "text": text,+ }+++def build_reasoning_text_part(text: str) -> dict[str, Any]:+ """+ 构建推理文本消息部分(reasoningText)。++ Args:+ text: 推理文本内容++ Returns:+ dict: 推理文本消息部分+ """+ return {+ "kind": "reasoningText",+ "reasoningText": text,+ }+++def build_file_part(files: list[FileInfo]) -> dict[str, Any]:+ """+ 构建文件消息部分。++ Args:+ files: 文件信息列表++ Returns:+ dict: 文件消息部分+ """+ return {+ "kind": "data",+ "data": {+ "fileInfo": [+ {+ "fileName": f.file_name,+ "fileType": f.file_type,+ "fileId": f.file_id,+ }+ for f in files+ ],+ },+ }+++def build_command_part(command: dict[str, Any]) -> dict[str, Any]:+ """+ 构建命令消息部分。++ Args:+ command: 命令对象++ Returns:+ dict: 命令消息部分+ """+ return {+ "kind": "data",+ "data": {+ "commands": [command],+ },+ }+++# ==================== Main Formatter Functions ====================++class MessageFormatter:+ """消息格式化器,用于将 JiuwenClaw 消息转换为 A2A 格式。"""++ def __init__(self, agent_id: str):+ self.agent_id = agent_id+ self._accumulated_texts: dict[str, str] = {}+ self._last_text_lengths: dict[str, int] = {}++ @staticmethod+ def get_message_id(self) -> str:+ """生成消息 ID。"""+ return f"msg_{int(time.time() * 1000)}"++ @staticmethod+ def get_artifact_id(self) -> str:+ """生成 artifact ID。"""+ return str(uuid.uuid4())++ def get_accumulated_text(self, session_id: str) -> str:+ """获取累积的文本。"""+ return self._accumulated_texts.get(session_id, "")++ def update_accumulated_text(self, session_id: str, text: str) -> None:+ """更新累积的文本。"""+ self._accumulated_texts[session_id] = text++ def clear_accumulated_text(self, session_id: str) -> None:+ """清除累积的文本。"""+ self._accumulated_texts.pop(session_id, None)+ self._last_text_lengths.pop(session_id, None)++ def calculate_delta_text(self, session_id: str, current_text: str) -> str:+ """+ 计算增量文本。++ Args:+ session_id: Session ID+ current_text: 当前完整文本++ Returns:+ str: 增量文本+ """+ previous_text = self._accumulated_texts.get(session_id, "")+ self._accumulated_texts[session_id] = current_text++ if current_text.startswith(previous_text):+ return current_text[len(previous_text):]+ else:+ # 如果不是追加模式,返回完整文本+ return current_text++ def format_text_response(+ self,+ session_id: str,+ task_id: str,+ text: str,+ *,+ append: bool = False,+ last_chunk: bool = True,+ is_final: bool = True,+ message_id: str | None = None,+ artifact_id: str | None = None,+ ) -> dict[str, Any]:+ """+ 格式化文本响应(A2A artifact-update)。++ Args:+ session_id: Session ID+ task_id: Task ID+ text: 文本内容+ append: 是否追加+ last_chunk: 是否为最后一块+ is_final: 是否为最终消息+ message_id: 消息 ID(可选,默认自动生成)+ artifact_id: Artifact ID(可选,默认自动生成)++ Returns:+ dict: agent_response 包装的消息+ """+ if message_id is None:+ message_id = self.get_message_id()+ if artifact_id is None:+ artifact_id = self.get_artifact_id()++ # 根据 last_chunk 选择使用 text 或 reasoningText+ if last_chunk:+ data_part = build_text_part(text)+ else:+ data_part = build_reasoning_text_part(text)++ artifact_update = {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": append,+ "lastChunk": last_chunk,+ "final": is_final,+ "artifact": {+ "artifactId": artifact_id,+ "parts": [data_part],+ },+ }++ json_rpc_response = _build_json_rpc_response(message_id, artifact_update)++ return _build_agent_response_wrapper(+ agent_id=self.agent_id,+ session_id=session_id,+ task_id=task_id,+ response_body=json_rpc_response,+ )++ def format_status_update(+ self,+ session_id: str,+ task_id: str,+ text: str,+ state: str,+ *,+ message_id: str | None = None,+ ) -> dict[str, Any]:+ """+ 格式化状态更新(A2A status-update)。++ Args:+ session_id: Session ID+ task_id: Task ID+ text: 状态文本+ state: 状态值+ message_id: 消息 ID(可选,默认自动生成)++ Returns:+ dict: agent_response 包装的消息+ """+ if message_id is None:+ message_id = self.get_message_id()++ status_update = build_status_update_response(task_id, text, state)+ json_rpc_response = _build_json_rpc_response(message_id, status_update)++ return _build_agent_response_wrapper(+ agent_id=self.agent_id,+ session_id=session_id,+ task_id=task_id,+ response_body=json_rpc_response,+ )++ def format_command(+ self,+ session_id: str,+ task_id: str,+ command: dict[str, Any],+ *,+ message_id: str | None = None,+ artifact_id: str | None = None,+ ) -> dict[str, Any]:+ """+ 格式化命令(A2A artifact-update with command)。++ Args:+ session_id: Session ID+ task_id: Task ID+ command: 命令对象+ message_id: 消息 ID(可选,默认自动生成)+ artifact_id: Artifact ID(可选,默认自动生成)++ Returns:+ dict: agent_response 包装的消息+ """+ if message_id is None:+ message_id = self.get_message_id()+ if artifact_id is None:+ artifact_id = self.get_artifact_id()++ artifact_update = {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": True,+ "final": False,+ "artifact": {+ "artifactId": artifact_id,+ "parts": [build_command_part(command)],+ },+ }++ json_rpc_response = _build_json_rpc_response(message_id, artifact_update)++ return _build_agent_response_wrapper(+ agent_id=self.agent_id,+ session_id=session_id,+ task_id=task_id,+ response_body=json_rpc_response,+ )++ def format_clear_context(+ self,+ session_id: str,+ message_id: str | None = None,+ ) -> dict[str, Any]:+ """+ 格式化 clearContext 响应。++ Args:+ session_id: Session ID+ message_id: 消息 ID(可选,默认自动生成)++ Returns:+ dict: agent_response 包装的消息+ """+ if message_id is None:+ message_id = self.get_message_id()++ clear_context_response = build_clear_context_response()+ json_rpc_response = _build_json_rpc_response(message_id, clear_context_response)++ return _build_agent_response_wrapper(+ agent_id=self.agent_id,+ session_id=session_id,+ task_id=session_id, # Use sessionId as taskId for clearContext+ response_body=json_rpc_response,+ )++ def format_tasks_cancel(+ self,+ session_id: str,+ task_id: str,+ message_id: str | None = None,+ ) -> dict[str, Any]:+ """+ 格式化 tasks/cancel 响应。++ Args:+ session_id: Session ID+ task_id: Task ID+ message_id: 消息 ID(可选,默认自动生成)++ Returns:+ dict: agent_response 包装的消息+ """+ if message_id is None:+ message_id = self.get_message_id()++ cancel_response = build_tasks_cancel_response(task_id)+ json_rpc_response = _build_json_rpc_response(message_id, cancel_response)++ return _build_agent_response_wrapper(+ agent_id=self.agent_id,+ session_id=session_id,+ task_id=task_id,+ response_body=json_rpc_response,+ )+++# ==================== Event Type Utilities ====================++def should_send_as_reasoning_text(event_type: EventType | None) -> bool:+ """+ 判断是否应该将消息作为 reasoningText 发送。++ Args:+ event_type: 事件类型++ Returns:+ bool: 是否应该作为 reasoningText 发送+ """+ if event_type is None:+ return False++ # Reasoning text 用于以下事件:+ # - CHAT_DELTA: 流式输出中的增量文本+ # - CHAT_TOOL_RESULT: 工具结果+ # - CHAT_SUBTASK_UPDATE: 子任务更新+ # - CHAT_PROCESSING_STATUS: 处理状态+ reasoning_text_events = {+ EventType.CHAT_DELTA,+ EventType.CHAT_SUBTASK_UPDATE,+ EventType.CHAT_PROCESSING_STATUS,+ }++ return event_type in reasoning_text_events+++def should_send_as_text(event_type: EventType | None) -> bool:+ """+ 判断是否应该将消息作为 text 发送。++ Args:+ event_type: 事件类型++ Returns:+ bool: 是否应该作为 text 发送+ """+ if event_type is None:+ return True # Default to text++ # Text 用于以下事件:+ # - CHAT_FINAL: 最终完整回复+ # - CHAT_MEDIA: 媒体消息+ # - CHAT_ERROR: 错误消息+ # - CHAT_INTERRUPT_RESULT: 中断结果+ text_events = {+ EventType.CHAT_FINAL,+ EventType.CHAT_MEDIA,+ EventType.CHAT_ERROR,+ EventType.CHAT_INTERRUPT_RESULT,+ }++ return event_type in text_events+++def should_send_as_status_update(event_type: EventType | None) -> bool:+ """+ 判断是否应该作为 status update 发送。++ Args:+ event_type: 事件类型++ Returns:+ bool: 是否应该作为 status update 发送+ """+ if event_type is None:+ return False++ # Status update 用于以下事件:+ # - CHAT_TOOL_CALL: 工具调用+ status_events = {+ EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_RESULT+ }++ return event_type in status_events+++def get_status_state_for_event(event_type: EventType | None) -> str:+ """+ 根据事件类型获取状态值。++ Args:+ event_type: 事件类型++ Returns:+ str: 状态值+ """+ if event_type is None:+ return "unknown"++ status_map = {+ EventType.CHAT_TOOL_CALL: "working",+ EventType.CHAT_PROCESSING_STATUS: "working",+ EventType.CHAT_FINAL: "completed",+ EventType.CHAT_ERROR: "failed",+ }++ return status_map.get(event_type, "unknown")+++def get_status_text_for_event(event_type: EventType | None, payload: dict | None = None) -> str:+ """+ 根据事件类型获取状态文本。++ Args:+ event_type: 事件类型+ payload: 消息载荷++ Returns:+ str: 状态文本+ """+ if event_type is None:+ return "处理中"++ if payload:+ # 尝试从 payload 中提取自定义状态文本+ if isinstance(payload, dict):+ content = payload.get("content", "")+ if isinstance(content, str) and content:+ return content+ if isinstance(content, dict):+ return content.get("output", "处理中")++ status_text_map = {+ EventType.CHAT_TOOL_CALL: "正在使用工具...",+ EventType.CHAT_TOOL_RESULT: "工具执行完成",+ EventType.CHAT_PROCESSING_STATUS: "任务正在处理中",+ EventType.CHAT_FINAL: "任务已完成",+ EventType.CHAT_ERROR: "处理失败,请稍后重试",+ EventType.CHAT_INTERRUPT_RESULT: "任务已中断",+ }++ return status_text_map.get(event_type, "处理中")+++def extract_msg_content(msg: Message) -> str:+ """提取msg 信息"""+ content = ""+ payload = msg.payload if msg.payload else {}+ if not isinstance(payload, dict):+ return str(msg.payload)+ if msg.event_type == EventType.CHAT_TOOL_CALL:+ content = payload.get("tool_call", {}).get("name", "")+ elif msg.event_type == EventType.CHAT_TOOL_RESULT:+ content = payload.get("result", "")+ else:+ content = msg.payload.get("content", "")+ if isinstance(content, dict):+ content = content.get("output", str(content))+ content = str(content)+ return content\ No newline at end of filediff --git a/jiuwenclaw/channel/xiaoyi_utils/push.py b/jiuwenclaw/channel/xiaoyi_utils/push.pyindex 7dad9af7e3..7b85d457ae 100644--- a/jiuwenclaw/channel/xiaoyi_utils/push.py+++ b/jiuwenclaw/channel/xiaoyi_utils/push.py@@ -20,20 +20,15 @@ PUSH_URL = "https://hag.cloud.huawei.com/open-ability-agent/v1/agent-webhook"@dataclassclass PushConfig:"""Push 消息配置."""+ mode: str = ""api_id: str = ""push_id: str = ""ak: str = ""sk: str = ""+ uid: str = ""+ api_key: str = ""push_url: str = ""- @property- def is_configured(self) -> bool:- """检查是否已配置."""- return bool(- self.api_id.strip()- and self.push_id.strip()- )-class XiaoYiPushService:"""@@ -68,13 +63,9 @@ class XiaoYiPushService:Returns:bool: 是否发送成功"""- if not self.config.is_configured:- logger.info("[PUSH] Push not configured, skipping")- return Falsetry:timestamp = str(int(time.time() * 1000))- signature = self._generate_signature(timestamp)message_id = self._generate_uuid()payload = {@@ -98,16 +89,25 @@ class XiaoYiPushService:}logger.info(f"[PUSH] Sending push notification: {push_text}")-- headers = {- "Content-Type": "application/json",- "Accept": "application/json",- "x-hag-trace-id": self._generate_uuid(),- "X-Access-Key": self.config.ak,- "X-Sign": signature,- "X-Ts": timestamp,- }-+ if self.config.mode == "xiaoi_claw":+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json",+ "x-hag-trace-id": self._generate_uuid(),+ "x-uid": self.config.uid,+ "x-api-key": self.config.api_key,+ "x-request-from": "openclaw"+ }+ else:+ signature = self._generate_signature(timestamp)+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json",+ "x-hag-trace-id": self._generate_uuid(),+ "X-Access-Key": self.config.ak,+ "X-Sign": signature,+ "X-Ts": timestamp,+ }timeout = aiohttp.ClientTimeout(total=30)async with aiohttp.ClientSession() as session:async with session.post(diff --git a/jiuwenclaw/jiuwen_core_patch.py b/jiuwenclaw/jiuwen_core_patch.pyindex 3c4248947b..55f77030c0 100644--- a/jiuwenclaw/jiuwen_core_patch.py+++ b/jiuwenclaw/jiuwen_core_patch.py@@ -1,4 +1,5 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+import jsonimport osfrom typing import Any, Optional@@ -39,14 +40,19 @@ class PatchOpenAIModelClient(OpenAIModelClient):timeout=final_timeout,max_retries=self.model_client_config.max_retries)-+ default_headers = os.getenv("default_headers", None)+ try:+ default_headers = json.loads(default_headers)+ except json.decoder.JSONDecodeError as error:+ llm_logger.warning(f"Model default headers parse failed: {error}")+ default_headers = Nonereturn AsyncOpenAI(api_key=self.model_client_config.api_key,base_url=self.model_client_config.api_base,http_client=http_client,timeout=final_timeout,max_retries=self.model_client_config.max_retries,- default_headers=os.getenv("default_headers", None),+ default_headers=default_headers)def _parse_stream_chunk(self, chunk: Any) -> Optional[AssistantMessageChunk]:diff --git a/jiuwenclaw/resources/.env.template b/jiuwenclaw/resources/.env.templateindex 669b4d26b6..0ad360c479 100644--- a/jiuwenclaw/resources/.env.template+++ b/jiuwenclaw/resources/.env.template@@ -87,4 +87,6 @@ EVOLUTION_AUTO_SCAN="false"# SkillNet timeout configurationSKILLNET_DOWNLOAD_TIMEOUT=60-SKILLNET_MAX_RETRIES=3\ No newline at end of file+SKILLNET_MAX_RETRIES=3++NO_PROXY=localhost,127.0.0.1,api.openai.rnd.huawei.com\ No newline at end of filediff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 008aad5681..18e80f9017 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -115,12 +115,13 @@ channels:agent_id:ws_url1: wss://hag.cloud.huawei.com/openclaw/v1/ws/linkws_url2: wss://116.63.174.231/openclaw/v1/ws/link+ enable_streaming: true+ enabled: false+ # xiaoyi_claw配置uid:api_key:push_url:file_upload_url:- enable_streaming: true- enabled: falsedingtalk:# 钉钉应用配置client_id: