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
update: support xy channel new tools
tan-wei-chengb35db344d203
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex f9c5727812..99828a99c6 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -114,7 +114,13 @@ from jiuwenclaw.agentserver.tools.xiaoyi_phone_tools import (search_alarms,modify_alarm,delete_alarm,- xiaoyi_collection,+ query_collection,+ add_collection,+ delete_collection,+ save_media_to_gallery,+ save_file_to_file_manager,+ convert_timestamp_to_utc8_time,+ view_push_result,xiaoyi_gui_agent,image_reading,)@@ -1297,7 +1303,10 @@ class JiuWenClawDeepAdapter:call_phone,send_message, search_message,create_alarm, search_alarms, modify_alarm, delete_alarm,- xiaoyi_collection,+ query_collection, add_collection, delete_collection,+ save_media_to_gallery, save_file_to_file_manager,+ convert_timestamp_to_utc8_time,+ view_push_result,image_reading,xiaoyi_gui_agent,]diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.pyindex 8ebfc29475..6d93467960 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py@@ -11,15 +11,16 @@- 日历: create_calendar_event, search_calendar_event- 联系人: search_contact- 相册: search_photo_gallery, upload_photo-- 文件: search_file, upload_file+- 文件: search_file, upload_file, send_file_to_user- 电话: call_phone- 短信/消息: send_message, search_message- 闹钟: create_alarm, search_alarms, modify_alarm, delete_alarm-- 收藏: xiaoyi_collection+- 收藏: query_collection, add_collection, delete_collection+- 保存: save_media_to_gallery, save_file_to_file_manager- 推送记录: view_push_result- GUI 自动化: xiaoyi_gui_agent- 图像理解: image_reading-- 本地上传公网 URL: upload_file_and_get_url+- 时间戳转换: convert_timestamp_to_utc8_time"""from .location_tool import get_user_location@@ -31,7 +32,10 @@ from .file_tools import search_file, upload_filefrom .phone_tools import call_phonefrom .message_tools import send_message, search_messagefrom .alarm_tools import create_alarm, search_alarms, modify_alarm, delete_alarm-from .xiaoyi_collection_tool import xiaoyi_collection+from .xiaoyi_collection_tool import query_collection, add_collection, delete_collection+from .save_tools import save_media_to_gallery, save_file_to_file_manager+from .push_result_tool import view_push_result+from .timestamp_tool import convert_timestamp_to_utc8_timefrom .xiaoyi_gui_tool import xiaoyi_gui_agentfrom .image_reading_tool import image_reading@@ -54,8 +58,13 @@ __all__ = ["search_alarms","modify_alarm","delete_alarm",- "xiaoyi_collection",+ "query_collection",+ "add_collection",+ "delete_collection",+ "save_media_to_gallery",+ "save_file_to_file_manager",+ "view_push_result",+ "convert_timestamp_to_utc8_time","xiaoyi_gui_agent","image_reading",]-diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.pyindex 056707131e..f9a6c2a48d 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py@@ -36,7 +36,7 @@ _ALARM_SNOOZE_DURATION = frozenset({5, 10, 15, 20, 25, 30})_ALARM_SNOOZE_TOTAL = frozenset({0, 1, 3, 5, 10})_ALARM_RING_DURATION = frozenset({1, 5, 10, 15, 20, 30})_DAYS_OF_WAKE_TYPE = frozenset({0, 1, 2, 3, 4})-_DAYS_OF_WEEK = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")+_DAYS_OF_WEEK = ("Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun")_ALARM_STATE = frozenset({0, 1})_RANGE_TYPE = frozenset({"all", "next", "current"})@@ -108,7 +108,7 @@ def _alarm_time_ms_from_hour_minute(hour: int, minute: int) -> int:def _normalize_days_of_week(raw: Union[str, Sequence[str], None],) -> List[str]:- """daysOfWeek:仅 daysOfWakeType=3 时有效;支持 JSON 字符串或单元素列表."""+ """daysOfWeek:仅 daysOfWakeType=3 时有效;支持 JSON 字符串或列表."""if raw is None:return []if isinstance(raw, str):@@ -121,10 +121,6 @@ def _normalize_days_of_week(days = parsedelse:days = list(raw)- if len(days) != 1:- raise ToolInputError(- "days_of_week 仅支持长度为 1 的数组;需多天请多次调用创建/修改"- )out: List[str] = []for d in days:if not isinstance(d, str) or d not in _DAYS_OF_WEEK:@@ -185,7 +181,7 @@ def _normalize_delete_items(- alarm_title / label: 标题,默认「闹钟」(label 为 alarm_title 的别名)- alarm_snooze_duration: 小睡间隔(分钟),5/10/15/20/25/30,默认 10- alarm_snooze_total: 再响次数,0/1/3/5/10,默认 0-- alarm_ring_duration: 响铃时长(分钟),1/5/10/15/20/30,默认 20+- alarm_ring_duration: 响铃时长(分钟),1/5/10/15/20/30,默认 5- days_of_wake_type: 0 单次 1 法定节假日 2 每天 3 自定义 4 法定工作日,默认 0- days_of_week: 仅当 days_of_wake_type=3 时必填;JSON 字符串或单元素列表,值 Mon..Sun@@ -212,7 +208,7 @@ async def create_alarm(snooze_d = 10 if alarm_snooze_duration is None else alarm_snooze_durationsnooze_t = 0 if alarm_snooze_total is None else alarm_snooze_total- ring_d = 20 if alarm_ring_duration is None else alarm_ring_duration+ ring_d = 5 if alarm_ring_duration is None else alarm_ring_durationwake_t = 0 if days_of_wake_type is None else days_of_wake_typeif snooze_d not in _ALARM_SNOOZE_DURATION:diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.pyindex f547b4191c..b0df6b4497 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py@@ -5,24 +5,30 @@包含:- search_file: 搜索手机文件- upload_file: 上传手机文件获取公网 URL-- send_file_to_user: 通过手机端 SendFileToUser 协议发文件给用户--send_file_to_user 与「本机路径/公网 URL → 上传服务 → 会话回传」类实现不同,此处仅封装设备 Intent。+- send_file_to_user: 将本地文件或公网文件传到用户手机"""from __future__ import annotations+import asyncioimport json-from typing import Any, Dict, List, Union+import os+import tempfile+import time+import uuid+from typing import Any, Dict, List, Optional, Union+from urllib.parse import urlparse++import aiohttpfrom openjiuwen.core.foundation.tool import toolfrom jiuwenclaw.utils import loggerfrom .utils import (+ ToolInputError,execute_device_command,format_success_response,raise_if_device_error,- ToolInputError,)@@ -141,12 +147,12 @@ async def search_file(name="upload_file",description="""工具能力描述:将手机本地文件上传并获取可公网访问的 URL。- 前置工具调用:此工具使用前必须先调用 search_file 工具获取文件的 uri+ 前置工具调用:此工具使用前必须先调用 search_file 或者 query_collection 工具获取文件的 uri工具参数说明:- a. 入参中的file_Infos数组,每个元素必须包含mediaUri字段(对应于search_file工具返回结果中的uri),必须与search_file结果中对应的uri完全保持一致,不要自行修改。+ a. 入参中的file_Infos数组,每个元素必须包含mediaUri字段(对应于search_file工具或者query_collection返回结果中的uri),必须与search_file结果中对应的uri完全保持一致,不要自行修改。b. file_infos 中的timeout字段是可选的,表示上传文件超时时间,单位是毫秒,默认是20000(20秒)。- c. file_infos 是文件在手机本地的信息数组(从 search_file 工具响应中获取)。限制:每次最多支持传入 5 条文件信息。+ c. file_infos 是文件在手机本地的信息数组(从 search_file 工具或者 query_collection 响应中获取)。限制:每次最多支持传入 5 条文件信息。注意事项:a. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。@@ -267,3 +273,68 @@ async def upload_file(file_infos: Union[str, List[Dict[str, Any]]]) -> Dict[str,except Exception as e:logger.error(f"[UPLOAD_FILE_TOOL] Failed to upload files: {e}")raise RuntimeError(f"上传文件失败: {str(e)}") from e+++# ---------------------------------------------------------------------------+# send_file_to_user - 将本地文件或公网文件传到用户手机+# ---------------------------------------------------------------------------++_FILE_TYPE_TO_MIME_TYPE: Dict[str, str] = {+ "txt": "text/plain",+ "html": "text/html",+ "css": "text/css",+ "js": "application/javascript",+ "json": "application/json",+ "png": "image/png",+ "jpeg": "image/jpeg",+ "jpg": "image/jpeg",+ "gif": "image/gif",+ "svg": "image/svg+xml",+ "pdf": "application/pdf",+ "zip": "application/zip",+ "doc": "application/msword",+ "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "xls": "application/vnd.ms-excel",+ "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "ppt": "application/vnd.ms-powerpoint",+ "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "mp3": "audio/mpeg",+ "mp4": "video/mp4",+}+++def _get_mime_type(filename: str) -> str:+ """根据文件扩展名获取 MIME 类型."""+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""+ return _FILE_TYPE_TO_MIME_TYPE.get(ext, "text/plain")+++async def _download_remote_file(url: str) -> str:+ """下载远程文件到临时文件,返回本地路径.++ Raises:+ RuntimeError: 下载失败+ """+ async with aiohttp.ClientSession() as session:+ async with session.get(url, timeout=aiohttp.ClientTimeout(total=120)) as resp:+ if not resp.ok:+ raise RuntimeError(f"HTTP {resp.status}: {resp.reason}")+ data = await resp.read()++ # 从 URL 提取文件名+ parsed = urlparse(url)+ raw_name = os.path.basename(parsed.path) or "downloaded_file"+ raw_name = raw_name.split("?")[0]++ suffix = os.path.splitext(raw_name)[1] or ""+ base_name = os.path.splitext(raw_name)[0] or "downloaded_file"+ unique_name = f"{base_name}_{int(time.time())}{suffix}"++ tmp_dir = tempfile.gettempdir()+ local_path = os.path.join(tmp_dir, unique_name)++ with open(local_path, "wb") as f:+ f.write(data)++ logger.info("[SEND_FILE_TO_USER] Downloaded remote file: %s -> %s", url, local_path)+ return local_pathdiff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.pyindex 66161082f9..b9f2eaf01c 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.py@@ -70,10 +70,10 @@ async def _download_remote_to_temp(url: str) -> str:async def _call_image_understanding_api(- image_url: str, text: str, api_key: str, uid: str+ image_url: str, text: str, api_key: str, uid: str, file_upload_url: str) -> str:api_url = (- "https://hag-drcn.op.dbankcloud.com/celia-claw/v1/sse-api/skill/execute"+ f"{file_upload_url}/celia-claw/v1/sse-api/skill/execute")trace_id = str(uuid.uuid4())headers = {@@ -224,9 +224,9 @@ async def image_reading(cfg = get_config()xc = cfg.get("channels", {}).get("xiaoyi", {})- base = (xc.get("file_upload_url") or "").strip()- api_key = (xc.get("api_key") or "").strip()- uid = (xc.get("uid") or "").strip()+ base = xc.get("file_upload_url")+ api_key = xc.get("api_key")+ uid = str(xc.get("uid"))if not base or not api_key or not uid:raise ToolInputError("缺少 channels.xiaoyi 的 file_upload_url / api_key / uid 配置,无法上传图片"@@ -262,7 +262,7 @@ async def image_reading(raise RuntimeError("图片上传失败:无法获取图片访问地址")caption = await _call_image_understanding_api(- image_obs_url, text, api_key, uid+ image_obs_url, text, api_key, uid, base)return _content_payload({diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.pyindex ee506607e2..a4aa7fd8fd 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py@@ -8,6 +8,7 @@from __future__ import annotations+import jsonfrom typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool@@ -15,7 +16,6 @@ from openjiuwen.core.foundation.tool import toolfrom jiuwenclaw.utils import loggerfrom .utils import (execute_device_command,- format_success_response,raise_if_device_error,ToolInputError,)@@ -79,7 +79,6 @@ async def call_phone("phoneNumber": phone_number,"slotId": slot_id,},- "permissionId": [],"achieveType": "INTENT",},"responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],@@ -96,20 +95,16 @@ async def call_phone(raise_if_device_error(outputs, "拨打电话失败")- code = outputs.get("code")- sim_name = "主卡" if slot_id == 0 else "副卡"- logger.info(f"[CALL_PHONE_TOOL] Call initiated successfully via {sim_name}")-- return format_success_response(- {- "success": True,- "code": code,- "phoneNumber": phone_number,- "slotId": slot_id,- "message": "电话拨打成功",- },- f"正在使用{sim_name}拨打 {phone_number}...",- )+ logger.info("[CALL_PHONE_TOOL] Call initiated successfully")++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),+ }+ ]+ }except ToolInputError:raisediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/push_result_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/push_result_tool.pynew file mode 100644index 0000000000..27819ad054--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/push_result_tool.py@@ -0,0 +1,152 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Push result tool - 查看推送记录工具.++包含:+- view_push_result: 查看定时任务或推送消息的执行结果+"""++from __future__ import annotations++import json+from typing import Any, Dict, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger++from .pushdata_manager import search_push_data, get_all_push_data+++@tool(+ name="view_push_result",+ description="""查看定时任务或推送消息的执行结果。当用户说"查看我xxx的定时任务执行结果"、"查看我的xxxx的推送消息"或类似语料时调用此工具。++功能说明:+- 支持关键词搜索:如果用户提到具体任务名称或内容,可以按关键词筛选+- 无关键词时:返回最近的推送记录(默认10条)+- 返回内容包括:推送ID、时间、内容摘要++使用场景:+- "查看我昨天的定时任务执行结果"+- "帮我看看天气推送消息"+- "查看最近的推送记录"+- "我的提醒任务执行了吗" """,+)+def view_push_result(+ keywords: Optional[str] = None,+ limit: Optional[int] = None,+) -> Dict[str, Any]:+ """查看推送记录(与 xy_channel view-push-result-tool.ts 对齐).++ Args:+ keywords: 可选的搜索关键词,用于筛选推送记录+ limit: 返回的最大记录数,默认10条,最多50条++ Returns:+ content[0].text: JSON 字符串(success, count, items, message)+ """+ try:+ effective_limit = min(limit or 10, 50)+ kw = keywords.strip() if keywords and isinstance(keywords, str) else None+ logger.info(+ "[VIEW_PUSH_RESULT_TOOL] 开始查询 keywords=%s limit=%s",+ kw, effective_limit,+ )++ # 根据是否有关键词决定调用哪个方法+ results = search_push_data(kw) if kw else get_all_push_data()+ logger.info(+ "[VIEW_PUSH_RESULT_TOOL] 数据源返回 %d 条记录, 查询方式=%s",+ len(results), "关键词搜索" if kw else "全量查询",+ )++ # 按时间倒序排序(最新的在前)+ results.sort(key=lambda x: x.get("time", ""), reverse=True)++ # 限制返回条数+ results = results[:effective_limit]+ logger.info("[VIEW_PUSH_RESULT_TOOL] 截取后返回 %d 条记录", len(results))++ if not results:+ logger.info("[VIEW_PUSH_RESULT_TOOL] 无匹配记录, keywords=%s", kw)+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(+ {+ "success": True,+ "count": 0,+ "items": [],+ "message": (+ f'未找到包含关键词"{kw}"的推送记录'+ if kw+ else "暂无推送记录"+ ),+ },+ ensure_ascii=False,+ ),+ }+ ]+ }++ # 格式化返回结果+ formatted_items = []+ for item in results:+ detail = item.get("dataDetail", "")+ formatted_items.append(+ {+ "pushDataId": item.get("pushDataId", "")[:8],+ "fullPushDataId": item.get("pushDataId", ""),+ "time": item.get("time", ""),+ "dataDetail": (+ detail[:200] + "..." if len(detail) > 200 else detail+ ),+ "fullLength": len(detail),+ }+ )++ logger.info(+ "[VIEW_PUSH_RESULT_TOOL] 查询完成, 返回 %d 条记录",+ len(formatted_items),+ )+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(+ {+ "success": True,+ "count": len(formatted_items),+ "totalMatched": len(results),+ "items": formatted_items,+ "message": (+ f'找到 {len(formatted_items)} 条包含"{kw}"的推送记录'+ if kw+ else f"返回最近 {len(formatted_items)} 条推送记录"+ ),+ },+ ensure_ascii=False,+ ),+ }+ ]+ }++ except Exception as e:+ logger.error("[VIEW_PUSH_RESULT_TOOL] Failed: %s", e)+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(+ {+ "success": False,+ "error": str(e),+ "message": "查询推送记录失败",+ },+ ensure_ascii=False,+ ),+ }+ ]+ }diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/pushdata_manager.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/pushdata_manager.pynew file mode 100644index 0000000000..58984e640a--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/pushdata_manager.py@@ -0,0 +1,147 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""PushData 持久化管理器.++与 xy_channel pushdata-manager.ts 对齐,使用 JSON 文件存储推送记录。+"""++from __future__ import annotations++import json+import os+import uuid+from datetime import datetime, timedelta, timezone+from typing import Any, Dict, List, Optional++from jiuwenclaw.utils import logger++PUSHDATA_FILE = os.path.expanduser("~/.openclaw/pushData.json")+MAX_PUSHDATA_ITEMS = 1000+++def _format_beijing_time() -> str:+ """格式化当前时间为 YYYYMMDD HHmmss(北京时间)."""+ utc8 = timezone(timedelta(hours=8))+ return datetime.now(utc8).strftime("%Y%m%d %H%M%S")+++def _ensure_directory_exists(file_path: str) -> None:+ """确保目录存在."""+ directory = os.path.dirname(file_path)+ os.makedirs(directory, exist_ok=True)+++def _read_pushdata_list() -> List[Dict[str, str]]:+ """读取 pushData 列表."""+ try:+ _ensure_directory_exists(PUSHDATA_FILE)+ if not os.path.exists(PUSHDATA_FILE):+ return []+ with open(PUSHDATA_FILE, "r", encoding="utf-8") as f:+ content = f.read()+ if not content.strip():+ return []+ data = json.loads(content)+ if not isinstance(data, list):+ logger.warning("[PushDataManager] pushData.json is not an array")+ return []+ return data+ except (json.JSONDecodeError, OSError) as e:+ logger.error("[PushDataManager] Failed to read pushData: %s", e)+ return []+++def _write_pushdata_list(items: List[Dict[str, str]]) -> None:+ """写入 pushData 列表(限制最多 MAX_PUSHDATA_ITEMS 条)."""+ try:+ _ensure_directory_exists(PUSHDATA_FILE)+ limited = items[-MAX_PUSHDATA_ITEMS:]+ with open(PUSHDATA_FILE, "w", encoding="utf-8") as f:+ json.dump(limited, f, ensure_ascii=False, indent=2)+ if len(items) > MAX_PUSHDATA_ITEMS:+ logger.info(+ "[PushDataManager] Trimmed pushData list from %s to %s items",+ len(items),+ len(limited),+ )+ except OSError as e:+ logger.error("[PushDataManager] Failed to write pushData: %s", e)+ raise+++def save_push_data(data_detail: str) -> str:+ """保存推送数据,返回 pushDataId.++ Args:+ data_detail: 推送内容详情++ Returns:+ pushDataId (UUID)+ """+ push_data_id = str(uuid.uuid4())+ time_str = _format_beijing_time()++ item = {+ "pushDataId": push_data_id,+ "dataDetail": data_detail,+ "time": time_str,+ }++ items = _read_pushdata_list()+ items.append(item)+ _write_pushdata_list(items)++ logger.info(+ "[PushDataManager] Saved pushData: id=%s, time=%s, detail_len=%s",+ push_data_id[:8],+ time_str,+ len(data_detail),+ )+ return push_data_id+++def _match_push_item(item: Dict[str, str], keyword: str) -> bool:+ """判断推送条目是否匹配关键词(忽略大小写)."""+ for field in ("dataDetail", "pushDataId"):+ value = item.get(field, "") or ""+ if keyword in value.lower():+ return True+ return False+++def search_push_data(keywords: Optional[str] = None) -> List[Dict[str, str]]:+ """搜索推送数据(支持关键词模糊匹配).++ Args:+ keywords: 搜索关键词,None 或空字符串时返回全部++ Returns:+ 匹配的推送数据列表+ """+ items = _read_pushdata_list()++ if not keywords or not keywords.strip():+ return items++ lower = keywords.lower().strip()+ results = [item for item in items if _match_push_item(item, lower)]++ logger.info(+ "[PushDataManager] Search with keywords %r: found %s items",+ keywords,+ len(results),+ )+ return results+++def get_all_push_data() -> List[Dict[str, str]]:+ """获取所有推送数据."""+ items = _read_pushdata_list()+ logger.info("[PushDataManager] Retrieved %s pushData items", len(items))+ return items+++def clear_all_push_data() -> None:+ """清空所有推送数据."""+ _write_pushdata_list([])+ logger.info("[PushDataManager] Cleared all pushData")diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/save_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/save_tools.pynew file mode 100644index 0000000000..3256baca8a--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/save_tools.py@@ -0,0 +1,277 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Save tools - 保存到手机工具.++包含:+- save_media_to_gallery: 将图片/视频保存到手机图库+- save_file_to_file_manager: 将文件保存到手机文件管理器+"""++from __future__ import annotations++import json+import os+from typing import Any, Dict, Optional++import aiohttp++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .utils import (+ execute_device_command,+ raise_if_device_error,+ ToolInputError,+)+from .file_upload_helpers import XiaoyiObsUploadConfig, upload_local_file_public_url+++async def _ensure_public_url(+ url: str,+ obs_cfg: XiaoyiObsUploadConfig,+ session: aiohttp.ClientSession,+) -> str:+ """如果 url 是本地路径,上传获取公网 URL;否则直接返回."""+ if url.startswith("http://") or url.startswith("https://"):+ return url+ public_url = await upload_local_file_public_url(session, obs_cfg, url)+ if not public_url:+ raise RuntimeError("本地文件上传失败,无法获取公网URL")+ return public_url+++def _get_obs_config() -> XiaoyiObsUploadConfig:+ """从配置中读取 OBS 上传配置."""+ from jiuwenclaw.config import get_config++ cfg = get_config()+ xc = cfg.get("channels", {}).get("xiaoyi", {})+ base = xc.get("file_upload_url")+ api_key = xc.get("api_key")+ uid = str(xc.get("uid"))+ if not base or not api_key or not uid:+ raise ToolInputError("缺少 channels.xiaoyi 的 file_upload_url / api_key / uid 配置,无法上传文件")+ return XiaoyiObsUploadConfig(base_url=base, api_key=api_key, uid=uid)+++@tool(+ name="save_media_to_gallery",+ description="""将图片文件或者视频文件保存到手机图库。+ 工具参数说明:+ a. mediaType:非必填,string类型,不传端侧默认为pic。支持传 pic(图片) 或 video(视频)。+ b. fileName:非必填,string类型,文件名称,不传手机侧默认生成随机uuid。+ c. url:必填,string类型,支持本地路径或者公网url路径。如果是本地路径,会先上传获取公网url再保存到图库。++ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。+ c. 调用工具前需认真检查调用参数是否满足工具要求++ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。+ """,+)+async def save_media_to_gallery(+ url: str,+ media_type: Optional[str] = None,+ file_name: Optional[str] = None,+) -> Dict[str, Any]:+ """保存图片/视频到手机图库(与 xy_channel save-media-to-gallery-tool.ts 对齐).++ Args:+ url: 本地路径或公网 URL(必填)+ media_type: pic 或 video(可选,默认 pic)+ file_name: 文件名称(可选,自动去除后缀)++ Returns:+ content[0].text: JSON 字符串(event.outputs)+ """+ try:+ if not url or not isinstance(url, str):+ raise ToolInputError("缺少必填参数: url")++ if media_type and media_type not in ("pic", "video"):+ raise ToolInputError(f"mediaType只支持 pic 或 video,当前值: {media_type}")++ # 去除 fileName 后缀+ sanitized_name = file_name+ if sanitized_name and isinstance(sanitized_name, str):+ last_dot = sanitized_name.rfind(".")+ if last_dot > 0:+ sanitized_name = sanitized_name[:last_dot]++ obs_cfg = _get_obs_config()++ async with aiohttp.ClientSession() as session:+ public_url = await _ensure_public_url(url, obs_cfg, session)++ intent_param: Dict[str, str] = {"url": public_url}+ if media_type:+ intent_param["mediaType"] = media_type+ if sanitized_name:+ intent_param["fileName"] = sanitized_name++ logger.info(+ "[SAVE_MEDIA_TO_GALLERY_TOOL] Saving media - type=%s, url=%s",+ media_type or "pic",+ public_url[:100] + "..." if len(public_url) > 100 else public_url,+ )++ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SaveMediaToGallery",+ "bundleName": "com.huawei.hmos.vassistant",+ "dimension": "",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": intent_param,+ "permissionId": ["ohos.permission.WRITE_IMAGEVIDEO"],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ outputs = await execute_device_command("SaveMediaToGallery", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "保存媒体到图库失败")++ logger.info("[SAVE_MEDIA_TO_GALLERY_TOOL] Save completed successfully")++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),+ }+ ]+ }++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[SAVE_MEDIA_TO_GALLERY_TOOL] Failed to save media: {e}")+ raise RuntimeError(f"保存媒体到图库失败: {str(e)}") from e+++@tool(+ name="save_file_to_file_manager",+ description="""将文件保存到手机文件管理器。+ 工具参数说明:+ a. fileName:必填,string类型,文件名称。+ b. url:必填,string类型,支持本地路径或者公网url路径。如果是本地路径,会先上传获取公网url再保存到手机。+ c. suffix:必填,string类型,文件后缀,例如 ppt、doc、pdf 等。++ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,不可以重试,直接返回错误。+ c. 调用工具前需认真检查调用参数是否满足工具要求++ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。+ """,+)+async def save_file_to_file_manager(+ file_name: str,+ url: str,+ suffix: str,+) -> Dict[str, Any]:+ """保存文件到手机文件管理器(与 xy_channel save-file-to-phone-tool.ts 对齐).++ Args:+ file_name: 文件名称(必填)+ url: 本地路径或公网 URL(必填)+ suffix: 文件后缀,例如 ppt、doc、pdf(必填)++ Returns:+ content[0].text: JSON 字符串(event.outputs)+ """+ try:+ if not url or not isinstance(url, str):+ raise ToolInputError("缺少必填参数: url")+ if not file_name or not isinstance(file_name, str):+ raise ToolInputError("缺少必填参数: fileName")+ if not suffix or not isinstance(suffix, str):+ raise ToolInputError("缺少必填参数: suffix")++ obs_cfg = _get_obs_config()++ async with aiohttp.ClientSession() as session:+ public_url = await _ensure_public_url(url, obs_cfg, session)++ intent_param: Dict[str, str] = {+ "fileName": file_name,+ "url": public_url,+ "suffix": suffix,+ }++ logger.info(+ "[SAVE_FILE_TO_PHONE_TOOL] Saving file - name=%s, suffix=%s",+ file_name,+ suffix,+ )++ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SaveFileToFileManager",+ "bundleName": "com.huawei.hmos.vassistant",+ "dimension": "",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "timeout": 55000,+ "intentParam": intent_param,+ "permissionId": ["ohos.permission.WRITE_IMAGEVIDEO"],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ outputs = await execute_device_command("SaveFileToFileManager", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "保存文件到手机失败")++ logger.info("[SAVE_FILE_TO_PHONE_TOOL] Save completed successfully")++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),+ }+ ]+ }++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[SAVE_FILE_TO_PHONE_TOOL] Failed to save file: {e}")+ raise RuntimeError(f"保存文件到手机失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/timestamp_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/timestamp_tool.pynew file mode 100644index 0000000000..22a1509082--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/timestamp_tool.py@@ -0,0 +1,84 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Timestamp tool - 时间戳转换工具.++包含:+- convert_timestamp_to_utc8_time: 将时间戳转换为 UTC+8 时间格式+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .utils import ToolInputError+++@tool(+ name="convert_timestamp_to_utc8_time",+ description="""将时间戳转换为标准 UTC+8 时间格式。支持秒级时间戳和毫秒级时间戳。++输入参数:+- timestamp: 时间戳(数字类型),可以是秒级(10位)或毫秒级(13位)++输出格式:+- YYYYMMDD hhmmss(例如:20240315 143000 表示 2024年3月15日 14:30:00 北京时间)++重要说明:+搜索日程工具(search_calendar_event)和搜索闹钟工具(search_alarm)等工具中返回结果如果包含时间戳。+建议优先调用本时间戳转换工具,将时间戳转换为标准北京时间格式,再基于标准时间进行用户回答或下一步操作。++示例:+- 输入:1710498600(秒级)或 1710498600000(毫秒级)+- 输出:20240315 143000""",+)+def convert_timestamp_to_utc8_time(timestamp: float) -> dict:+ """将时间戳转换为 UTC+8 时间格式."""+ if timestamp is None:+ raise ToolInputError("缺少必需参数:timestamp")++ if not isinstance(timestamp, (int, float)):+ raise ToolInputError("timestamp 必须是数字类型")++ import math+ if math.isnan(timestamp) or math.isinf(timestamp):+ raise ToolInputError("timestamp 不是有效数字")++ # 判断秒级还是毫秒级+ ts_abs = abs(timestamp)+ ts_str = str(int(ts_abs))++ if len(ts_str) == 13:+ timestamp_in_ms = timestamp+ elif len(ts_str) == 10:+ timestamp_in_ms = timestamp * 1000+ elif ts_abs > 1000000000000:+ timestamp_in_ms = timestamp+ else:+ timestamp_in_ms = timestamp * 1000++ # 转换为 UTC+8+ utc8_tz = timezone(timedelta(hours=8))+ try:+ dt = datetime.fromtimestamp(timestamp_in_ms / 1000, tz=utc8_tz)+ except (OSError, OverflowError, ValueError) as e:+ raise ToolInputError(f"无效的时间戳,无法转换为日期: {e}") from e++ formatted = dt.strftime("%Y%m%d %H%M%S")++ logger.info(+ "[TIMESTAMP_TOOL] Converted timestamp %s -> %s",+ timestamp,+ formatted,+ )++ return {+ "content": [+ {+ "type": "text",+ "text": formatted,+ }+ ]+ }diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.pyindex 4d08e18290..323ecd3838 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.py@@ -1,47 +1,77 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Collection tool - 小艺收藏工具.+"""Collection tools - 小艺收藏工具.包含:-- xiaoyi_collection: 检索用户在小艺收藏中记下来的公共知识数据+- query_collection: 检索用户在小艺收藏中记下来的公共知识数据+- add_collection: 向小艺收藏中添加公共知识数据+- delete_collection: 从小艺收藏中删除已保存的公共知识数据"""from __future__ import annotationsimport json-from typing import Any, Dict+from typing import Any, Dict, List, Optional, Unionfrom openjiuwen.core.foundation.tool import toolfrom jiuwenclaw.utils import logger-from .utils import execute_device_command, raise_if_device_error+from .utils import (+ execute_device_command,+ raise_if_device_error,+ ToolInputError,+)+from .file_upload_helpers import XiaoyiObsUploadConfig, upload_local_file_public_url@tool(- name="xiaoyi_collection",- description=(- "检索用户在小艺收藏中记下来的公共知识数据,可以给用户提供个性化体验。"- "当用户语料中涉及从我的小艺收藏或者查看我的收藏或者我xx时候收藏的xxx帮我看一下这种类型的语料的时候需要使用此工具。"- "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"- ),+ name="query_collection",+ description="""检索用户在小艺收藏中记下来的公共知识数据,本技能支持查询用户收藏的+公共知识数据,也可以根据特定语义化描述进行特定内容的检索,通过参数进行控制。+本技能返回结果+中,linkTitle是收藏内容的标题,description是对收藏内容的总结,label是收藏内容的标签,+linkUrl是可以直接访问的原始内容链接。如果你认为某条数据对用户交互有用,可以通过+linkUrl抓取更加丰富的原始数据。+ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。+ c. 调用工具前需认真检查调用参数是否满足工具要求++ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错+内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是+不需要的,请严格遵守。+ """,)-async def xiaoyi_collection(query_all: str = "true") -> Dict[str, Any]:+async def query_collection(+ query_all: str = "true",+ query: Optional[str] = None,+) -> Dict[str, Any]:"""检索小艺收藏(与 xy_channel xiaoyi-collection-tool.ts 行为对齐).Args:- query_all: 是否查询全部收藏,默认 \"true\"+ query_all: 是否查询全部收藏,默认 "true"+ query: 查询条件,queryAll 不为 "true" 时必填Returns:- content[0].text: JSON 字符串(success / memoryInfo 或 totalResults+collections+message)+ content[0].text: JSON 字符串(event.outputs)"""try:- query_all_value = query_all or "true"-logger.info(- "[XIAOYI_COLLECTION_TOOL] Starting execution - queryAll=%r",- query_all_value,+ "[QUERY_COLLECTION_TOOL] Starting execution - queryAll=%r, query=%r",+ query_all,+ query,)+ if query_all != "true" and (not query or not isinstance(query, str)):+ raise ToolInputError("queryAll不为true时,query参数必填")++ intent_param: Dict[str, str] = {}+ if query_all == "true":+ intent_param["queryAll"] = "true"+ else:+ intent_param["queryAll"] = "false"+ intent_param["query"] = query+command = {"header": {"namespace": "Common",@@ -57,9 +87,7 @@ async def xiaoyi_collection(query_all: str = "true") -> Dict[str, Any]:"actionResponse": True,"appType": "OHOS_APP","timeOut": 5,- "intentParam": {- "queryAll": query_all_value,- },+ "intentParam": intent_param,"permissionId": [],"achieveType": "INTENT",},@@ -77,85 +105,286 @@ async def xiaoyi_collection(query_all: str = "true") -> Dict[str, Any]:raise_if_device_error(outputs, "查询小艺收藏失败")- result = outputs.get("result")-- if result is None:- logger.warning("[XIAOYI_COLLECTION_TOOL] No collection data found")- payload = {- "success": True,- "memoryInfo": [],- "message": "未找到收藏数据",- }- return {- "content": [- {- "type": "text",- "text": json.dumps(payload, ensure_ascii=False),- }- ]- }-- nested = result.get("result") if isinstance(result, dict) else None- if isinstance(nested, dict):- memory_info = nested.get("memoryInfo") or []- else:- memory_info = []- if not isinstance(memory_info, list):- memory_info = []+ logger.info("[QUERY_COLLECTION_TOOL] Query completed successfully")++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),+ }+ ]+ }++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[QUERY_COLLECTION_TOOL] Failed to query collection: {e}")+ raise RuntimeError(f"查询小艺收藏失败: {str(e)}") from e+++def _normalize_item_ids(param: Any) -> List[str]:+ """将 item_ids 规范为字符串列表(支持数组或 JSON 数组字符串)。"""+ if param is None:+ raise ToolInputError("缺少必填参数 itemIds")+ if isinstance(param, list):+ return param+ if isinstance(param, str):+ try:+ parsed = json.loads(param)+ except json.JSONDecodeError as e:+ raise ToolInputError(+ f"itemIds must be a valid JSON array string. Parse error: {e}"+ ) from e+ if not isinstance(parsed, list):+ raise ToolInputError(+ "itemIds must be an array or a JSON string representing an array"+ )+ return parsed+ raise ToolInputError(+ f"itemIds must be an array or a JSON string, got {type(param).__name__}"+ )+++@tool(+ name="delete_collection",+ description="""从小艺收藏中删除之前已保存的公共知识数据。任何用户希望删除已保存到+个人+知识库的数据都可以调用本技能。如果用户想更新之前的收藏数据,需要先query获取itemId+然后再delete,最后执行Add,按照这个步骤完成收藏数据更新。+ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。+ c. 调用工具前需认真检查调用参数是否满足工具要求++ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错+内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是+不需要的,请严格遵守。+ """,+)+async def delete_collection(+ item_ids: Union[str, List[str]],+) -> Dict[str, Any]:+ """删除小艺收藏(与 xy_channel xiaoyi-delete-collection-tool.ts 对齐).++ Args:+ item_ids: 待删除的数据的 itemId 合集,支持数组或 JSON 字符串++ Returns:+ content[0].text: JSON 字符串(event.outputs)+ """+ try:+ normalized = _normalize_item_ids(item_ids)++ if not normalized or len(normalized) == 0:+ raise ToolInputError("itemIds array cannot be empty")logger.info(- "[XIAOYI_COLLECTION_TOOL] Collections found: %s items",- len(memory_info),+ "[DELETE_COLLECTION_TOOL] Deleting %s collection item(s)",+ len(normalized),)- simplified_collections = []- for item in memory_info:- if not isinstance(item, dict):- continue- simplified_collections.append(+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "DeleteCollection",+ "bundleName": "com.huawei.hmos.vassistant",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "itemIds": normalized,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ outputs = await execute_device_command("DeleteCollection", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "删除小艺收藏失败")++ logger.info("[DELETE_COLLECTION_TOOL] Delete completed successfully")++ return {+ "content": [{- "uuid": item.get("uuid"),- "type": item.get("type"),- "status": item.get("status"),- "collectionTime": item.get("collectionTime"),- "editTime": item.get("editTime"),- "title": item.get("linkTitle")- or item.get("aiTitle")- or item.get("textTitle")- or item.get("imageTitle")- or item.get("podcastTitle")- or "",- "description": item.get("description")- or item.get("abstract")- or "",- "content": item.get("textContent") or "",- "linkUrl": item.get("linkUrl"),- "linkType": item.get("linkType"),- "appName": item.get("appNameFromPab")- or item.get("appName")- or "",- "labels": item.get("label") or [],- "collectionMethod": item.get("collectionMethod"),+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),}+ ]+ }++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[DELETE_COLLECTION_TOOL] Failed to delete collection: {e}")+ raise RuntimeError(f"删除小艺收藏失败: {str(e)}") from e+++@tool(+ name="add_collection",+ description="""向小艺收藏中添加公共知识数据,可以给用户提供个性化体验。任何用户+希望+保存到个人化知识库中的数据都可以调用本技能。不同类型的数据对应的数据要求如下:+请求入参说明:+● content:必填字段,数据类型为string,功能描述是该字段是用户添加收藏的链接url或+ 文本原文。适用于HYPER_LINK和TEXT类型。+● uri:必填字段,数据类型为string,功能描述是该字段是图片或文件的端存储地址链接。+ 适用于IMAGE和FILE类型。+● sourceAppBundleName:非必填字段,数据类型为string,功能描述是标识该数据的来源+ 应用。+● dataType:必填字段,数据类型为string,功能描述是标识数据类型。HYPER_LINK标识+ 网页,TEXT标识文本,IMAGE标识图片,FILE标识文件。+● title:非必填字段,数据类型为string,功能描述是标识文件类型数据的文件名称。+ 适用于FILE类型。+说明:如果dataType为HYPER_LINK或TEXT,则content字段必填且不能为空;如果dataType+为IMAGE或FILE,则uri字段必填且不能为空。当用户希望收藏海报、截图等图片类数据时,+请将数据以图片IMAGE的形式存入到小艺帮记;当用户希望收藏电子书、笔记、报告、素材、+文档、合同、协议、简历、证书、报表、日志、安装包、压缩包等描述的文件时,请将数据+以文件FILE的形式存入到小艺帮记。+当你成功收藏这个数据到小艺帮记后,请在最后显示"已成功把数据添加到[小艺帮记]+(vassistant://voice/main?page=CollectionPage&jumpHomePageTab=myCollection)",+ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。+ c. 调用工具前需认真检查调用参数是否满足工具要求++ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错+内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是+不需要的,请严格遵守。+ """,+)+async def add_collection(+ data_type: str,+ content: Optional[str] = None,+ uri: Optional[str] = None,+ source_app_bundle_name: Optional[str] = None,+ title: Optional[str] = None,+) -> Dict[str, Any]:+ """添加小艺收藏(与 xy_channel xiaoyi-add-collection-tool.ts 对齐).++ Args:+ data_type: 数据类型,HYPER_LINK/TEXT/IMAGE/FILE+ content: 链接url或文本原文(HYPER_LINK/TEXT 类型时必填)+ uri: 图片或文件的地址链接(IMAGE/FILE 类型时必填)+ source_app_bundle_name: 来源应用标识+ title: 文件名称(FILE 类型时使用)++ Returns:+ content[0].text: JSON 字符串(event.outputs)+ """+ try:+ valid_types = ("HYPER_LINK", "TEXT", "IMAGE", "FILE")+ if not data_type or data_type not in valid_types:+ raise ToolInputError(+ f"dataType必填且必须为 HYPER_LINK、TEXT、IMAGE、FILE 之一,当前值: {data_type}")- payload: Dict[str, Any] = {- "success": True,- "totalResults": len(simplified_collections),- "collections": simplified_collections,+ if data_type in ("HYPER_LINK", "TEXT") and (not content or not isinstance(content, str)):+ raise ToolInputError(f"dataType为{data_type}时,content字段必填且不能为空")++ if data_type in ("IMAGE", "FILE") and (not uri or not isinstance(uri, str)):+ raise ToolInputError(f"dataType为{data_type}时,uri字段必填且不能为空")++ logger.info(+ "[ADD_COLLECTION_TOOL] Adding collection - dataType=%s",+ data_type,+ )++ # 如果 uri 是本地路径,上传获取公网 URL+ public_uri = uri+ _remote_prefixes = ("http://", "https://", "file://")+ if uri and not uri.startswith(_remote_prefixes):+ import aiohttp+ from jiuwenclaw.config import get_config++ cfg = get_config()+ xc = cfg.get("channels", {}).get("xiaoyi", {})+ base = xc.get("file_upload_url")+ api_key = xc.get("api_key")+ uid = str(xc.get("uid"))+ if not base or not api_key or not uid:+ raise RuntimeError("缺少 channels.xiaoyi 的 file_upload_url / api_key / uid 配置")++ obs_cfg = XiaoyiObsUploadConfig(base_url=base, api_key=api_key, uid=uid)+ async with aiohttp.ClientSession() as session:+ public_uri = await upload_local_file_public_url(session, obs_cfg, uri)++ if not public_uri:+ raise RuntimeError("本地文件上传失败,无法获取公网URL")++ intent_param: Dict[str, str] = {"dataType": data_type}+ if content:+ intent_param["content"] = content+ if public_uri:+ intent_param["uri"] = public_uri+ if source_app_bundle_name:+ intent_param["sourceAppBundleName"] = source_app_bundle_name+ if title:+ intent_param["title"] = title++ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "AddCollection",+ "bundleName": "com.huawei.hmos.vassistant",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": intent_param,+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },}- if isinstance(result, dict) and "message" in result:- payload["message"] = result["message"]++ outputs = await execute_device_command("AddCollection", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "添加小艺收藏失败")++ logger.info("[ADD_COLLECTION_TOOL] Add completed successfully")return {"content": [{"type": "text",- "text": json.dumps(payload, ensure_ascii=False),+ "text": json.dumps(outputs, ensure_ascii=False),}]}+ except ToolInputError:+ raiseexcept Exception as e:- logger.error(f"[XIAOYI_COLLECTION_TOOL] Failed to query collection: {e}")- raise RuntimeError(f"查询小艺收藏失败: {str(e)}") from e+ logger.error(f"[ADD_COLLECTION_TOOL] Failed to add collection: {e}")+ raise RuntimeError(f"添加小艺收藏失败: {str(e)}") from ediff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex d685c397c5..9509aa75f7 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -1146,6 +1146,30 @@ class XiaoyiChannel(BaseChannel):async with lock:await ws.send(data)+ async def send_agent_response_to_all(+ self, session_id: str, task_id: str, response: dict[str, Any]+ ) -> None:+ """向所有活跃 WebSocket 连接发送预构建的 agent_response 消息.++ Args:+ session_id: 会话 ID+ task_id: 任务 ID+ response: 已包含 msgType、agentId 等字段的完整消息体+ """+ sent = False+ for url_key in list(self._ws_connections.keys()):+ try:+ await self._safe_ws_send(url_key, response)+ sent = True+ except Exception as e:+ logger.warning(+ "XiaoyiChannel send_agent_response_to_all 失败 (%s): %s",+ url_key,+ e,+ )+ if not sent:+ raise RuntimeError("发送文件消息失败,WebSocket 未连接")+def _clear_task_timeout(self, session_id: str) -> None:"""清除任务超时任务."""if session_id in self._task_timeout_tasks: