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: 小艺端插件功能修正
shenwei21c9886f2033bb
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex effbfc8bf4..702e3371a3 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -62,14 +62,16 @@ from jiuwenclaw.agentserver.tools.video_tools import video_understandingfrom jiuwenclaw.agentserver.tools.xiaoyi_phone_tools import (get_user_location,create_note, search_notes, modify_note,- create_calendar_event, search_calendar,- search_contacts,+ create_calendar_event, search_calendar_event,+ search_contact,search_photo_gallery, upload_photo,- search_files, upload_files, send_file_to_user,+ search_file, upload_file,call_phone,- send_message, search_messages,+ send_message, search_message,create_alarm, search_alarms, modify_alarm, delete_alarm,xiaoyi_collection,+ image_reading,+ xiaoyi_gui_agent,)from jiuwenclaw.agentserver.tools.multimodal_config import (apply_audio_model_config_from_yaml,@@ -430,14 +432,16 @@ class JiuWenClaw:phone_tools = [get_user_location,create_note, search_notes, modify_note,- create_calendar_event, search_calendar,- search_contacts,+ create_calendar_event, search_calendar_event,+ search_contact,search_photo_gallery, upload_photo,- search_files, upload_files, send_file_to_user,+ search_file, upload_file,call_phone,- send_message, search_messages,+ send_message, search_message,create_alarm, search_alarms, modify_alarm, delete_alarm,xiaoyi_collection,+ image_reading,+ xiaoyi_gui_agent,]for tool in phone_tools:@@ -577,14 +581,16 @@ class JiuWenClaw:phone_tools = [get_user_location,create_note, search_notes, modify_note,- create_calendar_event, search_calendar,- search_contacts,+ create_calendar_event, search_calendar_event,+ search_contact,search_photo_gallery, upload_photo,- search_files, upload_files, send_file_to_user,+ search_file, upload_file,call_phone,- send_message, search_messages,+ send_message, search_message,create_alarm, search_alarms, modify_alarm, delete_alarm,xiaoyi_collection,+ image_reading,+ xiaoyi_gui_agent,]for tool in phone_tools:diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.pyindex f8a48697db..8ebfc29475 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py@@ -8,28 +8,32 @@工具分类:- 定位: get_user_location- 备忘录: create_note, search_notes, modify_note-- 日历: create_calendar_event, search_calendar-- 联系人: search_contacts+- 日历: create_calendar_event, search_calendar_event+- 联系人: search_contact- 相册: search_photo_gallery, upload_photo-- 文件: search_files, upload_files, send_file_to_user+- 文件: search_file, upload_file- 电话: call_phone-- 短信: send_message-- 消息: search_messages+- 短信/消息: send_message, search_message- 闹钟: create_alarm, search_alarms, modify_alarm, delete_alarm- 收藏: xiaoyi_collection+- 推送记录: view_push_result+- GUI 自动化: xiaoyi_gui_agent+- 图像理解: image_reading+- 本地上传公网 URL: upload_file_and_get_url"""from .location_tool import get_user_locationfrom .note_tools import create_note, search_notes, modify_note-from .calendar_tools import create_calendar_event, search_calendar-from .contact_tools import search_contacts+from .calendar_tools import create_calendar_event, search_calendar_event+from .contact_tools import search_contactfrom .photo_tools import search_photo_gallery, upload_photo-from .file_tools import search_files, upload_files, send_file_to_user+from .file_tools import search_file, upload_filefrom .phone_tools import call_phone-from .send_message_tool import send_message-from .message_tools import search_messages+from .message_tools import send_message, search_messagefrom .alarm_tools import create_alarm, search_alarms, modify_alarm, delete_alarm-from .collection_tool import xiaoyi_collection+from .xiaoyi_collection_tool import xiaoyi_collection+from .xiaoyi_gui_tool import xiaoyi_gui_agent+from .image_reading_tool import image_reading__all__ = ["get_user_location",@@ -37,20 +41,21 @@ __all__ = ["search_notes","modify_note","create_calendar_event",- "search_calendar",- "search_contacts",+ "search_calendar_event",+ "search_contact","search_photo_gallery","upload_photo",- "search_files",- "upload_files",- "send_file_to_user",+ "search_file",+ "upload_file","call_phone","send_message",- "search_messages",+ "search_message","create_alarm","search_alarms","modify_alarm","delete_alarm","xiaoyi_collection",+ "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 19eb18e63d..056707131e 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py@@ -2,6 +2,12 @@"""Alarm tools - 闹钟工具.+与 HarmonyOS 时钟 Intent 约定一致(intentParam 使用 camelCase 字段名):+- create_alarm: entityName + alarmTime(毫秒) + 可选响铃/重复等+- search_alarms: rangeType / alarmState / daysOfWakeType / timeInterval+- modify_alarm: entityId + 与创建相同的可选字段+- delete_alarm: items[{ entityId }]+包含:- create_alarm: 创建闹钟- search_alarms: 搜索闹钟@@ -12,76 +18,254 @@from __future__ import annotationsimport json-import logging-from typing import Any, Dict, List, Optional+from datetime import datetime, timedelta, timezone+from typing import Any, Dict, List, Optional, Sequence, Unionfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,format_success_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)+# 设备侧允许的枚举取值(时钟 Intent)+_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")+_ALARM_STATE = frozenset({0, 1})+_RANGE_TYPE = frozenset({"all", "next", "current"})+++def _alarm_display_timezone():+ """闹钟挂钟时区:优先 Asia/Shanghai,不可用时为 UTC+8(均带 tzinfo)."""+ try:+ from zoneinfo import ZoneInfo++ return ZoneInfo("Asia/Shanghai")+ except Exception:+ return timezone(timedelta(hours=8))+++def _is_valid_alarm_calendar_date(month: int, day: int) -> bool:+ """月、日是否在常见取值范围内(细粒度合法性由 datetime 构造校验)."""+ if month < 1 or month > 12:+ return False+ return 1 <= day <= 31+++def _is_valid_alarm_clock_time(hour: int, minute: int, second: int) -> bool:+ """时、分、秒是否在 24 小时制取值范围内."""+ if hour < 0 or hour > 23:+ return False+ if minute < 0 or minute > 59:+ return False+ return 0 <= second <= 59+++def _parse_alarm_time_to_ms(alarm_time: str) -> Optional[int]:+ """将 YYYYMMDD hhmmss 解析为毫秒时间戳(挂钟时区同 _alarm_display_timezone)."""+ trimmed = alarm_time.strip()+ if len(trimmed) < 13:+ return None+ date_part = trimmed[:8]+ time_part = trimmed[8:].strip()+ if len(date_part) != 8 or len(time_part) != 6:+ return None+ try:+ year = int(date_part[0:4])+ month = int(date_part[4:6])+ day = int(date_part[6:8])+ hour = int(time_part[0:2])+ minute = int(time_part[2:4])+ second = int(time_part[4:6])+ except ValueError:+ return None+ if not _is_valid_alarm_calendar_date(month, day):+ return None+ if not _is_valid_alarm_clock_time(hour, minute, second):+ return None+ tz = _alarm_display_timezone()+ dt = datetime(year, month, day, hour, minute, second, tzinfo=tz)+ ms = int(dt.timestamp() * 1000)+ return ms+++def _alarm_time_ms_from_hour_minute(hour: int, minute: int) -> int:+ """仅提供时分时:取下一次该时刻(与 YYYYMMDD 解析同一挂钟时区,秒为 0)."""+ tz = _alarm_display_timezone()+ now = datetime.now(tz)+ target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)+ if target <= now:+ target += timedelta(days=1)+ return int(target.timestamp() * 1000)+++def _normalize_days_of_week(+ raw: Union[str, Sequence[str], None],+) -> List[str]:+ """daysOfWeek:仅 daysOfWakeType=3 时有效;支持 JSON 字符串或单元素列表."""+ if raw is None:+ return []+ if isinstance(raw, str):+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError as e:+ raise ToolInputError(f"days_of_week 不是合法 JSON 数组字符串: {e}") from e+ if not isinstance(parsed, list):+ raise ToolInputError("days_of_week JSON 须为数组")+ days = parsed+ else:+ 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:+ raise ToolInputError(+ f"days_of_week 元素须为: {', '.join(_DAYS_OF_WEEK)},当前: {d!r}"+ )+ out.append(d)+ return out+++def _normalize_delete_items(+ items: Optional[Union[str, List[Any]]],+ alarm_id: Optional[str],+) -> List[Dict[str, str]]:+ """解析 delete 的 items;支持 JSON 字符串或列表,元素含 entityId 或 entity_id."""+ if items is None and alarm_id:+ return [{"entityId": str(alarm_id)}]+ if items is None:+ raise ToolInputError("须提供 items(列表或 JSON 字符串)或 alarm_id(单个删除)")++ parsed_list: List[Any]+ if isinstance(items, str):+ try:+ parsed = json.loads(items)+ except json.JSONDecodeError as e:+ raise ToolInputError(f"items 不是合法 JSON 数组: {e}") from e+ if not isinstance(parsed, list):+ raise ToolInputError("items JSON 须为数组")+ parsed_list = parsed+ elif isinstance(items, list):+ parsed_list = items+ else:+ raise ToolInputError("items 须为列表或 JSON 数组字符串")++ if not parsed_list:+ raise ToolInputError("items 不能为空")++ result: List[Dict[str, str]] = []+ for i, item in enumerate(parsed_list):+ if not isinstance(item, dict):+ raise ToolInputError(f"items[{i}] 须为对象")+ eid = item.get("entityId") or item.get("entity_id")+ if not eid or not isinstance(eid, str):+ raise ToolInputError(f"items[{i}] 缺少有效 entityId/entity_id")+ result.append({"entityId": eid})+ return result@tool(name="create_alarm",- description="""在用户设备上创建闹钟。需要提供闹钟时间和可选的重复设置。+ description="""在用户设备上创建闹钟。-时间格式:hh:mm(24小时制,例如 07:30 或 14:00)+时间(二选一,优先 alarm_time):+- alarm_time: 字符串 YYYYMMDD hhmmss(例如 20240315 143000)+- hour + minute: 仅时分时使用,将取「下一次」该时刻(本地时间)-参数说明:-- hour: 小时(0-23)-- minute: 分钟(0-59)-- repeat: 重复设置,如 "monday,tuesday"(可选)-- label: 闹钟标签/名称(可选)+可选:+- 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+- days_of_wake_type: 0 单次 1 法定节假日 2 每天 3 自定义 4 法定工作日,默认 0+- days_of_week: 仅当 days_of_wake_type=3 时必填;JSON 字符串或单元素列表,值 Mon..Sun-注意:-- 操作超时时间为60秒,请勿重复调用-- 如果创建失败,最多只能重试一次+注意:操作约 60 秒超时;失败最多重试一次;创建前宜确认当前真实日期时间。""",)async def create_alarm(- hour: int,- minute: int,- repeat: Optional[str] = None,+ hour: Optional[int] = None,+ minute: Optional[int] = None,+ alarm_time: Optional[str] = None,+ alarm_title: Optional[str] = None,label: Optional[str] = None,+ alarm_snooze_duration: Optional[int] = None,+ alarm_snooze_total: Optional[int] = None,+ alarm_ring_duration: Optional[int] = None,+ days_of_wake_type: Optional[int] = None,+ days_of_week: Optional[Union[str, List[str]]] = None,) -> Dict[str, Any]:- """创建闹钟.+ """创建闹钟"""+ try:+ title = alarm_title if alarm_title is not None else label+ if title is None or title == "":+ title = "闹钟"++ snooze_d = 10 if alarm_snooze_duration is None else alarm_snooze_duration+ snooze_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+ wake_t = 0 if days_of_wake_type is None else days_of_wake_type++ if snooze_d not in _ALARM_SNOOZE_DURATION:+ raise ToolInputError(f"alarm_snooze_duration 须为: {sorted(_ALARM_SNOOZE_DURATION)}")+ if snooze_t not in _ALARM_SNOOZE_TOTAL:+ raise ToolInputError(f"alarm_snooze_total 须为: {sorted(_ALARM_SNOOZE_TOTAL)}")+ if ring_d not in _ALARM_RING_DURATION:+ raise ToolInputError(f"alarm_ring_duration 须为: {sorted(_ALARM_RING_DURATION)}")+ if wake_t not in _DAYS_OF_WAKE_TYPE:+ raise ToolInputError(f"days_of_wake_type 须为: {sorted(_DAYS_OF_WAKE_TYPE)}")++ alarm_ms: Optional[int] = None+ if alarm_time:+ alarm_ms = _parse_alarm_time_to_ms(alarm_time)+ if alarm_ms is None:+ raise ToolInputError(+ "alarm_time 格式须为 YYYYMMDD hhmmss(例如 20240315 143000)"+ )+ elif hour is not None and minute is not None:+ if not isinstance(hour, int) or hour < 0 or hour > 23:+ raise ToolInputError("hour 须为 0-23 的整数")+ if not isinstance(minute, int) or minute < 0 or minute > 59:+ raise ToolInputError("minute 须为 0-59 的整数")+ alarm_ms = _alarm_time_ms_from_hour_minute(hour, minute)+ else:+ raise ToolInputError("请提供 alarm_time(YYYYMMDD hhmmss)或同时提供 hour 与 minute")++ week_list: List[str] = []+ if wake_t == 3:+ week_list = _normalize_days_of_week(days_of_week)+ elif days_of_week:+ logger.warning(+ "[ALARM_TOOL] 已忽略 days_of_week(仅当 days_of_wake_type=3 时有效),"+ "当前 days_of_wake_type=%s",+ wake_t,+ )++ intent_param: Dict[str, Any] = {+ "entityName": "Alarm",+ "alarmTime": alarm_ms,+ "alarmTitle": title,+ "alarmSnoozeDuration": snooze_d,+ "alarmSnoozeTotal": snooze_t,+ "alarmRingDuration": ring_d,+ "daysOfWakeType": wake_t,+ }+ if wake_t == 3 and week_list:+ intent_param["daysOfWeek"] = week_list- Args:- hour: 小时(0-23),必填- minute: 分钟(0-59),必填- repeat: 重复设置,如 "monday,tuesday,weekday,weekend,everyday"(可选)- label: 闹钟标签(可选)+ logger.info("[ALARM_TOOL] Creating alarm, alarmTime(ms)=%s", alarm_ms)- Returns:- 包含创建结果的响应字典- """- try:- logger.info(f"[ALARM_TOOL] Creating alarm - time: {hour:02d}:{minute:02d}")-- # 验证参数- if not isinstance(hour, int) or hour < 0 or hour > 23:- raise ToolInputError("hour 必须是 0-23 的整数")- if not isinstance(minute, int) or minute < 0 or minute > 59:- raise ToolInputError("minute 必须是 0-59 的整数")-- # 构建参数- intent_param = {"hour": hour, "minute": minute}- if repeat:- intent_param["repeat"] = repeat- if label:- intent_param["label"] = label-- # 构建命令 - 与 xy_channel 保持一致command = {- "header": {- "namespace": "Common",- "name": "Action",- },+ "header": {"namespace": "Common", "name": "Action"},"payload": {"cardParam": {},"executeParam": {@@ -103,17 +287,13 @@ async def create_alarm(},}- # 执行命令outputs = await execute_device_command("CreateAlarm", command)- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"创建闹钟失败: {error_msg} (错误代码: {code})")+ raise_if_device_error(outputs, "创建闹钟失败")result = outputs.get("result", {})- time_str = f"{hour:02d}:{minute:02d}"- logger.info(f"[ALARM_TOOL] Alarm created successfully at {time_str}")+ code = outputs.get("code")+ logger.info("[ALARM_TOOL] Alarm created successfully")return format_success_response({@@ -131,7 +311,7 @@ async def create_alarm(},"code": code,},- f"闹钟 {time_str} 创建成功"+ "闹钟创建成功",)except ToolInputError:@@ -143,28 +323,67 @@ async def create_alarm(@tool(name="search_alarms",- description="""在用户设备上搜索闹钟。+ description="""检索用户设备上的闹钟。至少满足一种检索条件(默认查询全部)。-注意:-- 操作超时时间为60秒,请勿重复调用-- 返回设备上所有闹钟的列表+条件(可组合):+- range_type: all / next / current+- alarm_state: 0 关闭 1 开启+- days_of_wake_type: 0-4(与创建时含义相同)+- start_time + end_time: 时间区间,格式均为 YYYYMMDD hhmmss,须成对出现;+ 设备侧为 timeInterval: [startMs, endMs]++注意:操作约 60 秒超时;检索前宜确认当前时间。""",)-async def search_alarms() -> Dict[str, Any]:- """搜索闹钟.-- Returns:- 包含闹钟列表的响应字典- """+async def search_alarms(+ range_type: Optional[str] = None,+ alarm_state: Optional[int] = None,+ days_of_wake_type: Optional[int] = None,+ start_time: Optional[str] = None,+ end_time: Optional[str] = None,+) -> Dict[str, Any]:+ """搜索闹钟."""try:- logger.info("[ALARM_TOOL] Searching alarms")+ has_range = range_type is not None+ has_as = alarm_state is not None+ has_wake = days_of_wake_type is not None+ has_start = start_time is not None+ has_end = end_time is not None++ if has_start != has_end:+ raise ToolInputError("start_time 与 end_time 须同时提供或同时省略")++ if not (has_range or has_as or has_wake or (has_start and has_end)):+ range_type = "all"++ intent_param: Dict[str, Any] = {}+ if range_type is not None:+ if range_type not in _RANGE_TYPE:+ raise ToolInputError(f"range_type 须为: {sorted(_RANGE_TYPE)}")+ intent_param["rangeType"] = range_type+ if alarm_state is not None:+ if alarm_state not in _ALARM_STATE:+ raise ToolInputError("alarm_state 须为 0 或 1")+ intent_param["alarmState"] = alarm_state+ if days_of_wake_type is not None:+ if days_of_wake_type not in _DAYS_OF_WAKE_TYPE:+ raise ToolInputError(f"days_of_wake_type 须为: {sorted(_DAYS_OF_WAKE_TYPE)}")+ intent_param["daysOfWakeType"] = days_of_wake_type+ if has_start and has_end:+ sm = _parse_alarm_time_to_ms(start_time or "")+ em = _parse_alarm_time_to_ms(end_time or "")+ if sm is None:+ raise ToolInputError("start_time 格式须为 YYYYMMDD hhmmss")+ if em is None:+ raise ToolInputError("end_time 格式须为 YYYYMMDD hhmmss")+ if sm >= em:+ raise ToolInputError("start_time 须早于 end_time")+ intent_param["timeInterval"] = [sm, em]++ logger.info("[ALARM_TOOL] Searching alarms, intent keys=%s", list(intent_param.keys()))- # 构建命令 - 与 xy_channel 保持一致command = {- "header": {- "namespace": "Common",- "name": "Action",- },+ "header": {"namespace": "Common", "name": "Action"},"payload": {"cardParam": {},"executeParam": {@@ -175,7 +394,7 @@ async def search_alarms() -> Dict[str, Any]:"actionResponse": True,"appType": "OHOS_APP","timeOut": 5,- "intentParam": {"rangeType": "all"}, # 查询所有闹钟+ "intentParam": intent_param,"permissionId": [],"achieveType": "INTENT",},@@ -186,28 +405,24 @@ async def search_alarms() -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("SearchAlarm", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"检索闹钟失败: {error_msg} (错误代码: {code})")+ raise_if_device_error(outputs, "检索闹钟失败")- # 提取结果(items 可能是 JSON 字符串数组,需要解析)result = outputs.get("result", {})items = result.get("items", []) if isinstance(result, dict) else []- # 解析 JSON 字符串- parsed_alarms = []+ parsed_alarms: List[Any] = []for item in items:if isinstance(item, str):try:- parsed = json.loads(item)- parsed_alarms.append(parsed)- except json.JSONDecodeError:- logger.warning(f"[ALARM_TOOL] 无法解析闹钟项: {item}")+ parsed_alarms.append(json.loads(item))+ except json.JSONDecodeError as e:+ logger.warning(+ "[ALARM_TOOL] 无法解析闹钟项: %s, error: %s",+ item,+ e,+ )elif isinstance(item, dict):parsed_alarms.append(item)@@ -215,9 +430,11 @@ async def search_alarms() -> Dict[str, Any]:return format_success_response({"alarms": parsed_alarms, "count": len(parsed_alarms)},- f"找到 {len(parsed_alarms)} 个闹钟"+ f"找到 {len(parsed_alarms)} 个闹钟",)+ except ToolInputError:+ raiseexcept Exception as e:logger.error(f"[ALARM_TOOL] Failed to search alarms: {e}")raise RuntimeError(f"搜索闹钟失败: {str(e)}") from e@@ -225,67 +442,98 @@ async def search_alarms() -> Dict[str, Any]:@tool(name="modify_alarm",- description="""在用户设备上修改闹钟。需要提供闹钟ID和要修改的参数。--参数说明:-- alarm_id: 闹钟ID(必填)-- hour: 新小时(可选)-- minute: 新分钟(可选)-- repeat: 新重复设置(可选)-- label: 新标签(可选)-- enabled: 是否启用(可选,true/false)--注意:-- 操作超时时间为60秒,请勿重复调用+ description="""修改用户设备上已有闹钟。须提供 entity_id(设备返回的 entityId)。++可选字段(与创建一致,仅填需要修改的项):+- alarm_time: YYYYMMDD hhmmss+- alarm_title: 标题+- alarm_state: 0 关 1 开+- alarm_snooze_duration / alarm_snooze_total / alarm_ring_duration: 枚举同创建+- days_of_wake_type / days_of_week: 自定义星期规则同创建++兼容:alarm_id 与 entity_id 二选一(同为设备侧闹钟实体 ID)。+enabled: true/false 与 alarm_state 二选一(enabled 映射为 1/0)。++注意:修改未涉及的字段时,若希望保持原值,宜先 search_alarms 取原值再一并传入,避免默认覆盖。""",)async def modify_alarm(- alarm_id: str,- hour: Optional[int] = None,- minute: Optional[int] = None,- repeat: Optional[str] = None,- label: Optional[str] = None,+ entity_id: Optional[str] = None,+ alarm_id: Optional[str] = None,+ alarm_time: Optional[str] = None,+ alarm_title: Optional[str] = None,+ alarm_state: Optional[int] = None,enabled: Optional[bool] = None,+ alarm_snooze_duration: Optional[int] = None,+ alarm_snooze_total: Optional[int] = None,+ alarm_ring_duration: Optional[int] = None,+ days_of_wake_type: Optional[int] = None,+ days_of_week: Optional[Union[str, List[str]]] = None,) -> Dict[str, Any]:- """修改闹钟.-- Args:- alarm_id: 闹钟ID,必填- hour: 新小时(可选)- minute: 新分钟(可选)- repeat: 新重复设置(可选)- label: 新标签(可选)- enabled: 是否启用(可选)-- Returns:- 包含修改结果的响应字典- """+ """修改闹钟."""try:- logger.info(f"[ALARM_TOOL] Modifying alarm - alarm_id: {alarm_id}")-- # 验证参数- if not alarm_id:- raise ToolInputError("缺少必填参数 alarm_id(闹钟ID)")-- # 构建参数- intent_param = {"alarmId": alarm_id}- if hour is not None:- intent_param["hour"] = hour- if minute is not None:- intent_param["minute"] = minute- if repeat:- intent_param["repeat"] = repeat- if label:- intent_param["label"] = label- if enabled is not None:- intent_param["enabled"] = enabled-- # 构建命令+ eid = (entity_id or alarm_id or "").strip()+ if not eid:+ raise ToolInputError("缺少 entity_id 或 alarm_id(设备侧闹钟 entityId)")++ intent_param: Dict[str, Any] = {+ "entityName": "Alarm",+ "entityId": eid,+ }++ if alarm_time is not None:+ ms = _parse_alarm_time_to_ms(alarm_time)+ if ms is None:+ raise ToolInputError("alarm_time 格式须为 YYYYMMDD hhmmss")+ intent_param["alarmTime"] = ms++ if alarm_title is not None:+ intent_param["alarmTitle"] = alarm_title++ eff_state = alarm_state+ if eff_state is None and enabled is not None:+ eff_state = 1 if enabled else 0+ if eff_state is not None:+ if eff_state not in _ALARM_STATE:+ raise ToolInputError("alarm_state 须为 0 或 1")+ intent_param["alarmState"] = eff_state++ if alarm_snooze_duration is not None:+ if alarm_snooze_duration not in _ALARM_SNOOZE_DURATION:+ raise ToolInputError(f"alarm_snooze_duration 须为: {sorted(_ALARM_SNOOZE_DURATION)}")+ intent_param["alarmSnoozeDuration"] = alarm_snooze_duration++ if alarm_snooze_total is not None:+ if alarm_snooze_total not in _ALARM_SNOOZE_TOTAL:+ raise ToolInputError(f"alarm_snooze_total 须为: {sorted(_ALARM_SNOOZE_TOTAL)}")+ intent_param["alarmSnoozeTotal"] = alarm_snooze_total++ if alarm_ring_duration is not None:+ if alarm_ring_duration not in _ALARM_RING_DURATION:+ raise ToolInputError(f"alarm_ring_duration 须为: {sorted(_ALARM_RING_DURATION)}")+ intent_param["alarmRingDuration"] = alarm_ring_duration++ if days_of_wake_type is not None:+ if days_of_wake_type not in _DAYS_OF_WAKE_TYPE:+ raise ToolInputError(f"days_of_wake_type 须为: {sorted(_DAYS_OF_WAKE_TYPE)}")+ intent_param["daysOfWakeType"] = days_of_wake_type++ if days_of_week is not None:+ if days_of_wake_type != 3:+ if days_of_wake_type is None:+ raise ToolInputError("使用 days_of_week 时请同时指定 days_of_wake_type=3")+ logger.warning(+ "[ALARM_TOOL] 已忽略 days_of_week(仅当 days_of_wake_type=3 时有效)"+ )+ else:+ week_list = _normalize_days_of_week(days_of_week)+ if week_list:+ intent_param["daysOfWeek"] = week_list++ logger.info("[ALARM_TOOL] Modifying alarm entityId=%s", eid)+command = {- "header": {- "namespace": "Common",- "name": "Action",- },+ "header": {"namespace": "Common", "name": "Action"},"payload": {"cardParam": {},"executeParam": {@@ -307,27 +555,25 @@ async def modify_alarm(},}- # 执行命令outputs = await execute_device_command("ModifyAlarm", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"修改闹钟失败: {error_msg} (错误代码: {code})")+ raise_if_device_error(outputs, "修改闹钟失败")result = outputs.get("result", {})- logger.info("[ALARM_TOOL] Alarm modified successfully")-return format_success_response({- "alarm_id": alarm_id,+ "entity_id": eid,"entityId": result.get("entityId"),"alarmTitle": result.get("alarmTitle"),+ "alarmTime": result.get("alarmTime"),"alarmState": result.get("alarmState"),+ "alarmRingDuration": result.get("alarmRingDuration"),+ "alarmSnoozeDuration": result.get("alarmSnoozeDuration"),+ "alarmSnoozeTotal": result.get("alarmSnoozeTotal"),+ "daysOfWakeType": result.get("daysOfWakeType"),},- "闹钟修改成功"+ "闹钟修改成功",)except ToolInputError:@@ -339,39 +585,27 @@ async def modify_alarm(@tool(name="delete_alarm",- description="""在用户设备上删除闹钟。+ description="""删除用户设备上的闹钟。-参数说明:-- alarm_id: 要删除的闹钟ID(必填)+参数(二选一):+- items: 待删列表,每项含 entityId(或 entity_id);可为 JSON 数组字符串+- alarm_id: 仅删一个时可直接传实体 ID-注意:-- 操作超时时间为60秒,请勿重复调用-- 删除后无法恢复+注意:删除不可恢复;操作约 60 秒超时。""",)-async def delete_alarm(alarm_id: str) -> Dict[str, Any]:- """删除闹钟.-- Args:- alarm_id: 闹钟ID,必填-- Returns:- 包含删除结果的响应字典- """+async def delete_alarm(+ items: Optional[Union[str, List[Dict[str, Any]]]] = None,+ alarm_id: Optional[str] = None,+) -> Dict[str, Any]:+ """删除闹钟."""try:- logger.info("[ALARM_TOOL] 🗑️ Deleting alarm")- logger.info(f"[ALARM_TOOL] - alarm_id: {alarm_id}")+ norm_items = _normalize_delete_items(items, alarm_id)- # 验证参数- if not alarm_id:- raise ToolInputError("缺少必填参数 alarm_id(闹钟ID)")+ logger.info("[ALARM_TOOL] Deleting %s alarm(s)", len(norm_items))- # 构建命令command = {- "header": {- "namespace": "Common",- "name": "Action",- },+ "header": {"namespace": "Common", "name": "Action"},"payload": {"cardParam": {},"executeParam": {@@ -382,7 +616,7 @@ async def delete_alarm(alarm_id: str) -> Dict[str, Any]:"actionResponse": True,"appType": "OHOS_APP","timeOut": 5,- "intentParam": {"alarmId": alarm_id},+ "intentParam": {"items": norm_items},"permissionId": [],"achieveType": "INTENT",},@@ -393,26 +627,19 @@ async def delete_alarm(alarm_id: str) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("DeleteAlarm", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"删除闹钟失败: {error_msg} (错误代码: {code})")+ raise_if_device_error(outputs, "删除闹钟失败")result = outputs.get("result", {})- logger.info("[ALARM_TOOL] Alarm deleted successfully")-return format_success_response({- "alarm_id": alarm_id,+ "items": norm_items,"entityId": result.get("entityId"),"success": True,},- "闹钟已删除"+ "闹钟已删除",)except ToolInputError:diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.pyindex a4a16eafab..223560d399 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py@@ -4,18 +4,24 @@包含:- create_calendar_event: 创建日程-- search_calendar: 搜索日程+- search_calendar_event: 检索日程"""from __future__ import annotations-import loggingfrom datetime import datetime-from typing import Any, Dict, List, Optional+from typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-logger = logging.getLogger(__name__)+from jiuwenclaw.utils import logger++from .utils import (+ execute_device_command,+ format_success_response,+ raise_if_device_error,+ ToolInputError,+)def _format_timestamp_to_datetime(timestamp_ms: int) -> str:@@ -49,33 +55,43 @@ def _convert_event_timestamps(event: Dict[str, Any]) -> Dict[str, Any]:result["dtEnd"] = _format_timestamp_to_datetime(result["dtEnd"])return result-from .base import (- execute_device_command,- validate_required_params,- format_success_response,- format_error_response,- ToolInputError,-)++def _parse_time_string_ymd_hhmmss(time_str: str) -> int:+ """解析 YYYYMMDD hhmmss 格式为毫秒时间戳."""+ cleaned = " ".join(time_str.strip().split())+ parts = cleaned.split(" ")+ if len(parts) != 2:+ raise ValueError(+ f"Invalid time format: {time_str}. Expected format: YYYYMMDD hhmmss"+ )+ date_part, time_part = parts[0], parts[1]+ if len(date_part) != 8 or len(time_part) != 6:+ raise ValueError(+ f"Invalid time format: {time_str}. Expected format: YYYYMMDD hhmmss"+ )+ year = int(date_part[0:4])+ month = int(date_part[4:6])+ day = int(date_part[6:8])+ hours = int(time_part[0:2])+ minutes = int(time_part[2:4])+ seconds = int(time_part[4:6])+ dt = datetime(year, month, day, hours, minutes, seconds)+ return int(dt.timestamp() * 1000)@tool(name="create_calendar_event",- description="""在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。--时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。--注意:-- 该工具执行时间较长(最多60秒),请勿重复调用-- 超时或失败时最多重试一次-- 使用该工具之前需获取当前真实时间-""",+ description=(+ "在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。"+ "时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。"+ "注意:该工具执行时间较长(最多60秒),请勿重复调用,超时或失败时最多重试一次。\n"+ " 注意事项:使用该工具之前需获取当前真实时间\n"+ ),)async def create_calendar_event(title: str,dt_start: str,dt_end: str,- location: Optional[str] = None,- description: Optional[str] = None,) -> Dict[str, Any]:"""创建日程.@@ -83,14 +99,15 @@ async def create_calendar_event(title: 日程标题/名称,必填dt_start: 开始时间,格式 yyyy-mm-dd hh:mm:ssdt_end: 结束时间,格式 yyyy-mm-dd hh:mm:ss- location: 地点(可选)- description: 描述(可选)Returns:包含创建结果的响应字典"""try:- logger.info(f"[CALENDAR_TOOL] Create calendar event - title: {title}, dt_start: {dt_start}, dt_end: {dt_end}")+ logger.info(+ f"[CALENDAR_TOOL] Create calendar event - title: {title}, "+ f"dt_start: {dt_start}, dt_end: {dt_end}"+ )# 验证参数if not title:@@ -111,18 +128,13 @@ async def create_calendar_event("时间格式错误。必须使用:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)") from ValueError- # 构建参数intent_param = {"title": title,"dtStart": dt_start_ms,"dtEnd": dt_end_ms,}- if location:- intent_param["location"] = location- if description:- intent_param["description"] = description- # 构建命令+ # CreateCalendarEvent:executeParam 不含 appType、permissionIdcommand = {"header": {"namespace": "Common",@@ -137,10 +149,8 @@ async def create_calendar_event("dimension": "","needUnlock": True,"actionResponse": True,- "appType": "OHOS_APP","timeOut": 5,"intentParam": intent_param,- "permissionId": [],"achieveType": "INTENT",},"responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],@@ -153,10 +163,13 @@ async def create_calendar_event(# 执行命令result = await execute_device_command("CreateCalendarEvent", command)+ if isinstance(result, dict):+ raise_if_device_error(result, "创建日程失败")+logger.info("[CALENDAR_TOOL] Calendar event created successfully")return format_success_response({"title": title, "dt_start": dt_start, "dt_end": dt_end, "result": result},- f"日程 '{title}' 创建成功"+ f"日程 '{title}' 创建成功",)except ToolInputError:@@ -167,65 +180,60 @@ async def create_calendar_event(@tool(- name="search_calendar",- description="""在用户设备上搜索日程。可以按标题、时间范围搜索。+ name="search_calendar_event",+ description="""检索用户日历中的日程安排。根据时间范围和可选的日程标题进行检索。时间格式必须为:YYYYMMDD hhmmss(例如:20240115 143000)。-时间格式:yyyy-mm-dd hh:mm:ss+时间范围说明:+- 查询某一天的日程:使用该天的 00:00:00 到 23:59:59(例如:20240115 000000 到 20240115 235959)+- 查询上午的日程:使用 06:00:00 到 12:00:00+- 查询下午的日程:使用 12:00:00 到 18:00:00+- 查询晚上的日程:使用 18:00:00 到 23:59:59+- 查询某个时刻附近的日程:使用该时刻前后1小时的区间(例如:查询3点左右的日程,使用 14:00:00 到 16:00:00)注意:-- 操作超时时间为60秒,请勿重复调用-- 如果搜索失败,最多只能重试一次+a. 该工具执行时间较长(最多60秒),请勿重复调用,超时或失败时最多重试一次。+b. 使用该工具之前需获取当前真实时间""",)-async def search_calendar(- keyword: Optional[str] = None,- start_time: Optional[str] = None,- end_time: Optional[str] = None,- max_results: int = 10,+async def search_calendar_event(+ start_time: str,+ end_time: str,+ title: Optional[str] = None,) -> Dict[str, Any]:- """搜索日程.+ """检索日程.Args:- keyword: 搜索关键词(可选)- start_time: 开始时间范围(可选)- end_time: 结束时间范围(可选)- max_results: 最大返回结果数,默认10+ start_time: 起始时间,格式 YYYYMMDD hhmmss+ end_time: 结束时间,格式 YYYYMMDD hhmmss+ title: 日程标题过滤(可选)Returns:包含日程列表的响应字典"""try:- logger.info(f"[CALENDAR_TOOL] Searching calendar events - keyword: {keyword}")-- # 构建参数 - 使用 timeInterval 数组格式(与 xy_channel 一致)- intent_param: Dict[str, Any] = {}-- # 转换时间格式- start_time_ms = 0- end_time_ms = 0-- if start_time:- try:- start_dt = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")- start_time_ms = int(start_dt.timestamp() * 1000)- except ValueError:- raise ToolInputError("start_time 格式错误,必须使用:yyyy-mm-dd hh:mm:ss") from ValueError+ logger.info(+ f"[SEARCH_CALENDAR_TOOL] Searching calendar events - "+ f"start_time: {start_time}, end_time: {end_time}, title: {title}"+ )- if end_time:- try:- end_dt = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")- end_time_ms = int(end_dt.timestamp() * 1000)- except ValueError:- raise ToolInputError("end_time 格式错误,必须使用:yyyy-mm-dd hh:mm:ss") from ValueError+ if not start_time or not end_time:+ raise ToolInputError("缺少必填参数 start_time 与 end_time")- # 使用 timeInterval 数组格式- if start_time_ms and end_time_ms:- intent_param["timeInterval"] = [start_time_ms, end_time_ms]+ try:+ start_time_ms = _parse_time_string_ymd_hhmmss(start_time)+ end_time_ms = _parse_time_string_ymd_hhmmss(end_time)+ except ValueError as e:+ raise ToolInputError(+ "时间格式错误。必须使用:YYYYMMDD hhmmss(例如:20240115 143000)。"+ f" {e}"+ ) from e- if keyword:- intent_param["title"] = keyword+ intent_param: Dict[str, Any] = {+ "timeInterval": [start_time_ms, end_time_ms],+ }+ if title:+ intent_param["title"] = title- # 构建命令command = {"header": {"namespace": "Common",@@ -256,10 +264,7 @@ async def search_calendar(# 执行命令outputs = await execute_device_command("SearchCalendarEvent", command)- # 检查错误码- if outputs.get("retErrCode") and outputs.get("retErrCode") != "0":- err_msg = outputs.get("errMsg", "未知错误")- raise RuntimeError(f"检索日程失败: {err_msg} (错误代码: {outputs['retErrCode']})")+ raise_if_device_error(outputs, "检索日程失败")# 获取结果result = outputs.get("result", {})@@ -268,15 +273,15 @@ async def search_calendar(# 转换时间戳为可读格式formatted_items = [_convert_event_timestamps(item) for item in items]- logger.info(f"[CALENDAR_TOOL] Found {len(formatted_items)} events")+ logger.info(f"[SEARCH_CALENDAR_TOOL] Found {len(formatted_items)} events")return format_success_response({"events": formatted_items, "count": len(formatted_items)},- f"搜索到 {len(formatted_items)} 条日程"+ f"搜索到 {len(formatted_items)} 条日程",)except ToolInputError:raiseexcept Exception as e:- logger.error(f"[CALENDAR_TOOL] Failed to search calendar: {e}")+ logger.error(f"[SEARCH_CALENDAR_TOOL] Failed to search calendar: {e}")raise RuntimeError(f"搜索日程失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.pydeleted file mode 100644index 0fc837e1a6..0000000000--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py+++ /dev/null@@ -1,143 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""Collection tool - 小艺收藏工具.--包含:-- xiaoyi_collection: 检索用户在小艺收藏中记下来的公共知识数据-"""--from __future__ import annotations--import logging-from typing import Any, Dict, Optional--from openjiuwen.core.foundation.tool import tool--from .base import (- execute_device_command,- format_success_response,- ToolInputError,-)--logger = logging.getLogger(__name__)---@tool(- name="xiaoyi_collection",- description="""检索用户在小艺收藏中记下来的公共知识数据,可以给用户提供个性化体验。--使用场景:-- 当用户语料中涉及"从我的小艺收藏"、"查看我的收藏"、"我xx时候收藏的xxx帮我看一下"等语料时需要使用此工具-- 用户想查看自己之前收藏的信息时--参数:-- query_all: 是否查询所有收藏数据,默认为"true"--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多重试一次-""",-)-async def xiaoyi_collection(query_all: str = "true") -> Dict[str, Any]:- """检索小艺收藏.-- Args:- query_all: 是否查询所有收藏数据,默认为"true"-- Returns:- 包含收藏列表的响应字典- """- try:- logger.info(f"[COLLECTION_TOOL] Starting execution - query_all: {query_all}")-- # 构建命令- command = {- "header": {- "namespace": "Common",- "name": "Action",- },- "payload": {- "cardParam": {},- "executeParam": {- "executeMode": "background",- "intentName": "QueryCollection",- "bundleName": "com.huawei.hmos.vassistant",- "needUnlock": True,- "actionResponse": True,- "appType": "OHOS_APP",- "timeOut": 5,- "intentParam": {- "queryAll": query_all,- },- "permissionId": [],- "achieveType": "INTENT",- },- "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],- "needUploadResult": True,- "noHalfPage": False,- "pageControlRelated": False,- },- }-- # 执行命令- outputs = await execute_device_command("QueryCollection", command)-- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- raise RuntimeError(f"查询小艺收藏失败 (错误码: {code})")-- # 提取结果- result = outputs.get("result", {})-- if not result:- logger.warning("[COLLECTION_TOOL] No collection data found")- return format_success_response(- {- "success": True,- "memoryInfo": [],- "message": "未找到收藏数据"- },- "未找到收藏数据"- )-- # 提取 memoryInfo 从嵌套结构- memory_info = result.get("result", {}).get("memoryInfo", []) if isinstance(result, dict) else []-- logger.info(f"[COLLECTION_TOOL] Found {len(memory_info)} collections")-- # 简化和格式化收藏数据- simplified_collections = []- for item in memory_info:- simplified_collections.append({- "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"),- })-- return format_success_response(- {- "success": True,- "totalResults": len(simplified_collections),- "collections": simplified_collections,- "message": result.get("message") if isinstance(result, dict) else None,- },- f"找到 {len(simplified_collections)} 条收藏记录"- )-- except ToolInputError:- raise- except Exception as e:- logger.error(f"[COLLECTION_TOOL] Failed to query collection: {e}")- raise RuntimeError(f"查询小艺收藏失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.pyindex 7f3991b7ab..d8e0ece6e7 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py@@ -2,58 +2,57 @@"""Contact tools - 联系人工具.+命令结构要点:+- executeParam:intentName SearchContactLocal、bundleName aidispatchservice、appType OHOS_APP 等+- intentParam:name+包含:-- search_contacts: 搜索联系人+- search_contact: 搜索联系人"""from __future__ import annotations-import logging-from typing import Any, Dict, Optional+import json+from typing import Any, Dictfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,format_success_response,ToolInputError,)-logger = logging.getLogger(__name__)-@tool(- name="search_contacts",- description="""搜索用户设备上的联系人信息。根据姓名在通讯录中检索联系人详细信息(包括姓名、电话号码、邮箱、组织、职位等)。--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多重试一次-""",+ name="search_contact",+ description=(+ "搜索用户设备上的联系人信息。根据姓名在通讯录中检索联系人详细信息"+ "(包括姓名、电话号码、邮箱、组织、职位等)。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),)-async def search_contacts(- name: str,-) -> Dict[str, Any]:- """搜索联系人.+async def search_contact(name: str) -> Dict[str, Any]:+ """搜索联系人Args:name: 联系人姓名,用于在通讯录中检索联系人信息Returns:- 包含联系人列表的响应字典+ content[0].text 为设备 outputs 的 JSON 字符串"""try:- logger.info(f"[CONTACT_TOOL] Searching contacts - name: {name}")+ if not isinstance(name, str) or not name.strip():+ raise ToolInputError("缺少必填参数 name")- # 验证参数- if not name or not isinstance(name, str):- raise ToolInputError("缺少必填参数 name(联系人姓名)")+ name_clean = name.strip()- name = name.strip()- if not name:- raise ToolInputError("name 不能为空")+ logger.info(+ "[SEARCH_CONTACT_TOOL] Searching contacts - name=%r",+ name_clean,+ )- # 构建命令command = {"header": {"namespace": "Common",@@ -69,9 +68,7 @@ async def search_contacts("actionResponse": True,"appType": "OHOS_APP","timeOut": 5,- "intentParam": {- "name": name,- },+ "intentParam": {"name": name_clean},"permissionId": [],"achieveType": "INTENT",},@@ -82,27 +79,24 @@ async def search_contacts(},}- # 执行命令outputs = await execute_device_command("SearchContactLocal", command)- # 检查错误码- ret_err_code = outputs.get("retErrCode")- if ret_err_code and ret_err_code != "0":- err_msg = outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"搜索联系人失败: {err_msg} (错误码: {ret_err_code})")-- # 提取结果- result = outputs.get("result", {})+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- logger.info(f"[CONTACT_TOOL] found {len(result.get('items', [])) if isinstance(result, dict) else 0} contacts")+ result = outputs.get("result")+ if not isinstance(result, dict):+ result = {}+ n = len(result.get("items", []))+ logger.info("[SEARCH_CONTACT_TOOL] found %s contacts", n)return format_success_response(- {"result": result},- f"搜索到联系人信息"+ dict(outputs),+ f"搜索到联系人信息({n} 条)",)except ToolInputError:raiseexcept Exception as e:- logger.error(f"[CONTACT_TOOL] Failed to search contacts: {e}")+ logger.error(f"[SEARCH_CONTACT_TOOL] Failed to search contacts: {e}")raise RuntimeError(f"搜索联系人失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.pyindex 837ae2e055..f547b4191c 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py@@ -3,29 +3,54 @@"""File tools - 文件工具.包含:-- search_files: 搜索文件-- upload_files: 上传文件-- send_file_to_user: 发送文件给用户+- search_file: 搜索手机文件+- upload_file: 上传手机文件获取公网 URL+- send_file_to_user: 通过手机端 SendFileToUser 协议发文件给用户++send_file_to_user 与「本机路径/公网 URL → 上传服务 → 会话回传」类实现不同,此处仅封装设备 Intent。"""from __future__ import annotations-import logging-from typing import Any, Dict, List, Optional+import json+from typing import Any, Dict, List, Unionfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,format_success_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)++def _normalize_file_infos(param: Any) -> List[Dict[str, Any]]:+ """将 fileInfos 规范为数组(支持数组或 JSON 数组字符串)。"""+ if param is None:+ raise ToolInputError("缺少必填参数 fileInfos")+ if isinstance(param, list):+ return param+ if isinstance(param, str):+ try:+ parsed = json.loads(param)+ except json.JSONDecodeError as e:+ raise ToolInputError(+ f"fileInfos 必须是合法 JSON 数组字符串。解析错误: {e}"+ ) from e+ if not isinstance(parsed, list):+ raise ToolInputError(+ "fileInfos 必须是数组或表示数组的 JSON 字符串(解析结果不是数组)"+ )+ return parsed+ raise ToolInputError(+ f"fileInfos 必须是数组或 JSON 数组字符串,当前类型: {type(param).__name__}"+ )@tool(- name="search_files",+ name="search_file",description="""搜索手机文件系统的文件。【重要】使用约束:此工具仅在用户显著说明要从手机搜索时才执行,例如:@@ -38,11 +63,9 @@ logger = logging.getLogger(__name__)功能说明:根据关键词搜索文件名称或内容,返回匹配的文件列表(包括文件名、路径、大小、修改时间等信息)。-注意:-- 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次-""",+注意事项:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。""",)-async def search_files(+async def search_file(query: str,) -> Dict[str, Any]:"""搜索文件.@@ -51,12 +74,11 @@ async def search_files(query: 搜索关键词,用于匹配文件名称、后缀名或文件内容Returns:- 包含文件列表的响应字典+ 设备返回的完整 outputs(JSON 序列化后置于 content)"""try:- logger.info(f"[FILE_TOOL] Searching files - query: {query}")+ logger.info(f"[SEARCH_FILE_TOOL] Searching files - query: {query}")- # 验证参数if not query or not isinstance(query, str):raise ToolInputError("缺少必填参数 query(搜索关键词)")@@ -64,7 +86,6 @@ async def search_files(if not query:raise ToolInputError("query 不能为空")- # 构建命令command = {"header": {"namespace": "Common",@@ -93,79 +114,82 @@ async def search_files(},}- # 执行命令+ # 成功时返回完整 outputs,不在此处按 code 拦截outputs = await execute_device_command("SearchFile", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"搜索文件失败: {error_msg} (错误代码: {code})")+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- # 提取结果- result = outputs.get("result", {})- files = result.get("items", []) if isinstance(result, dict) else []+ raise_if_device_error(outputs, "搜索文件失败")- logger.info(f"[FILE_TOOL] Found {len(files)} files")+ result = outputs.get("result")+ if not isinstance(result, dict):+ result = {}+ n = len(result.get("items", []))+ logger.info(f"[SEARCH_FILE_TOOL] Found {n} files")- return format_success_response(- {"files": files, "count": len(files)},- f"搜索到 {len(files)} 个文件"- )+ return format_success_response(dict(outputs), f"搜索到 {n} 个文件")except ToolInputError:raiseexcept Exception as e:- logger.error(f"[FILE_TOOL] Failed to search files: {e}")+ logger.error(f"[SEARCH_FILE_TOOL] Failed to search files: {e}")raise RuntimeError(f"搜索文件失败: {str(e)}") from e@tool(- name="upload_files",- description="""将手机本地文件上传并获取可公网访问的 URL。+ name="upload_file",+ description="""工具能力描述:将手机本地文件上传并获取可公网访问的 URL。-前置工具调用:此工具使用前必须先调用 search_files 工具获取文件的 uri+ 前置工具调用:此工具使用前必须先调用 search_file 工具获取文件的 uri-工具参数说明:-a. 入参中的fileInfos数组,每个元素必须包含mediaUri字段(对应于search_file工具返回结果中的uri),必须与search_file结果中对应的uri完全保持一致,不要自行修改。-b. fileInfos中的timeout字段是可选的,表示上传文件超时时间,单位是毫秒,默认是20000(20秒)。-c. fileInfos 是文件在手机本地的信息数组(从 search_file 工具响应中获取)。限制:每次最多支持传入 5 条文件信息。+ 工具参数说明:+ a. 入参中的file_Infos数组,每个元素必须包含mediaUri字段(对应于search_file工具返回结果中的uri),必须与search_file结果中对应的uri完全保持一致,不要自行修改。+ b. file_infos 中的timeout字段是可选的,表示上传文件超时时间,单位是毫秒,默认是20000(20秒)。+ c. file_infos 是文件在手机本地的信息数组(从 search_file 工具响应中获取)。限制:每次最多支持传入 5 条文件信息。-注意:-- 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次-- 此工具返回的文件链接为用户公网可访问的链接,如果需要对文件进行额外的操作,需要先根据返回的url下载文件,然后进行下一步处理-""",+ 注意事项:+ a. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。+ b. 此工具返回的文件链接为用户公网可访问的链接,如果需要对文件进行额外的操作,需要先根据返回的url下载文件,然后进行下一步处理。""",)-async def upload_files(file_infos: List[Dict[str, Any]]) -> Dict[str, Any]:- """上传文件.+async def upload_file(file_infos: Union[str, List[Dict[str, Any]]]) -> Dict[str, Any]:+ """上传文件Args:- file_infos: 文件信息数组,每个元素包含mediaUri(必需)和timeout(可选,默认20000)+ file_infos: 文件信息数组或 JSON 数组字符串;每项含 mediaUri(必需)、timeout(可选,默认 20000 毫秒)Returns:- 包含上传URL的响应字典+ content[0].text 为 JSON:fileUrls、count、message"""try:- logger.info(f"[FILE_TOOL] Uploading files - file_infos count: {len(file_infos)}")+ file_infos_list = _normalize_file_infos(file_infos)+ logger.info(+ "[UPLOAD_FILE_TOOL] Uploading files - fileInfos count: %s",+ len(file_infos_list),+ )- # 验证参数- if not file_infos or not isinstance(file_infos, list):- raise ToolInputError("file_infos 必须是包含文件信息的数组")+ if len(file_infos_list) == 0:+ raise ToolInputError("fileInfos 数组不能为空")- if len(file_infos) > 5:- raise ToolInputError(f"每次最多支持上传 5 个文件,当前提供了 {len(file_infos)} 个")+ if len(file_infos_list) > 5:+ raise ToolInputError(+ f"最多支持 5 条文件信息,当前提供了 {len(file_infos_list)} 条。请分批处理。"+ )- # 验证每个文件信息- for i, file_info in enumerate(file_infos):+ for i, file_info in enumerate(file_infos_list):if not isinstance(file_info, dict):- raise ToolInputError(f"file_infos[{i}] 必须是对象")- if not file_info.get("mediaUri") or not isinstance(file_info["mediaUri"], str):- raise ToolInputError(f"file_infos[{i}] 必须包含有效的 mediaUri 字符串")- # 设置默认超时+ raise ToolInputError(+ f"fileInfos[{i}] 必须是包含 mediaUri 的对象"+ )+ if not file_info.get("mediaUri") or not isinstance(+ file_info["mediaUri"], str+ ):+ raise ToolInputError(+ f"fileInfos[{i}] 必须包含有效的 mediaUri 字符串"+ )if not file_info.get("timeout"):file_info["timeout"] = "20000"- # 构建命令 - 与 xy_channel 保持一致command = {"header": {"namespace": "Common",@@ -181,7 +205,7 @@ async def upload_files(file_infos: List[Dict[str, Any]]) -> Dict[str, Any]:"actionResponse": True,"appType": "OHOS_APP","timeOut": 5,- "intentParam": {"fileInfos": file_infos},+ "intentParam": {"fileInfos": file_infos_list},"permissionId": [],"achieveType": "INTENT",},@@ -192,129 +216,54 @@ async def upload_files(file_infos: List[Dict[str, Any]]) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("FileUploadForClaw", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"获取文件URL失败: {error_msg} (错误代码: {code})")+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- # 提取结果并解码URL- result = outputs.get("result", {})- file_urls = result.get("fileUrls", []) if isinstance(result, dict) else []+ raise_if_device_error(outputs, "获取文件 URL 失败")- # 解码 Unicode 转义序列- decoded_urls = []- for url in file_urls:- if isinstance(url, str):- decoded_url = url.replace("\\u003d", "=").replace("\\u0026", "&")- decoded_urls.append(decoded_url)-- logger.info(f"[FILE_TOOL] Uploaded {len(decoded_urls)} files")+ result = outputs.get("result", {}) if isinstance(outputs, dict) else {}+ file_urls: List[Any] = []+ if isinstance(result, dict):+ raw = result.get("fileUrls")+ if isinstance(raw, list):+ file_urls = raw- return format_success_response(- {- "fileUrls": decoded_urls,- "count": len(decoded_urls),- "message": f"成功获取 {len(decoded_urls)} 个文件的公网访问 URL"- },- f"成功上传 {len(decoded_urls)} 个文件"+ decoded_urls: List[str] = []+ for url in file_urls:+ if not isinstance(url, str):+ logger.warning(+ "[UPLOAD_FILE_TOOL] URL 不是字符串: %s",+ type(url),+ )+ continue+ decoded = url.replace("\\u003d", "=").replace("\\u0026", "&")+ if decoded:+ decoded_urls.append(decoded)++ logger.info(+ "[UPLOAD_FILE_TOOL] Retrieved %s file URLs",+ len(decoded_urls),)- except ToolInputError:- raise- except Exception as e:- logger.error(f"[FILE_TOOL] Failed to upload files: {e}")- raise RuntimeError(f"上传文件失败: {str(e)}") from e---@tool(- name="send_file_to_user",- description="""将手机上的文件发送给用户(通过当前会话渠道)。--前置条件:-- 必须先调用 search_files 工具获取文件的 fileUri-- 文件会被发送到当前会话中--注意:-- 操作超时时间为60秒,请勿重复调用-""",-)-async def send_file_to_user(file_uri: str, file_name: Optional[str] = None) -> Dict[str, Any]:- """发送文件给用户.-- Args:- file_uri: 文件URI,必填- file_name: 文件名(可选,用于显示)-- Returns:- 包含发送结果的响应字典- """- try:- logger.info(f"[FILE_TOOL] Sending file to user - file_uri: {file_uri}")-- # 验证参数- if not file_uri or not isinstance(file_uri, str):- raise ToolInputError("缺少必填参数 file_uri(文件URI)")-- if not file_uri.startswith("file://"):- raise ToolInputError("file_uri 必须以 file:// 开头")-- # 构建参数- intent_param = {"fileUri": file_uri}- if file_name:- intent_param["fileName"] = file_name-- # 构建命令- command = {- "header": {- "namespace": "Common",- "name": "Action",- },- "payload": {- "cardParam": {},- "executeParam": {- "executeMode": "background",- "intentName": "SendFileToUser",- "bundleName": "com.huawei.hmos.vassistant",- "dimension": "",- "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,- },+ # 与 upload-file-tool.ts 一致:content[0].text 仅为 { fileUrls, count, message }+ payload = {+ "fileUrls": decoded_urls,+ "count": len(decoded_urls),+ "message": f"成功获取 {len(decoded_urls)} 个文件的公网访问 URL",+ }+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(payload, ensure_ascii=False),+ }+ ]}-- # 执行命令- outputs = await execute_device_command("SendFileToUser", command)-- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"发送文件失败: {error_msg} (错误代码: {code})")-- result = outputs.get("result", {}) if isinstance(outputs, dict) else {}-- logger.info("[FILE_TOOL] File sent successfully")-- return format_success_response(- {"file_uri": file_uri, "file_name": file_name or "unknown", "result": result},- f"文件已发送给用户"- )except ToolInputError:raiseexcept Exception as e:- logger.error(f"[FILE_TOOL] Failed to send file: {e}")- raise RuntimeError(f"发送文件失败: {str(e)}") from e+ logger.error(f"[UPLOAD_FILE_TOOL] Failed to upload files: {e}")+ raise RuntimeError(f"上传文件失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_upload_helpers.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_upload_helpers.pynew file mode 100644index 0000000000..dbe0fa7016--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_upload_helpers.py@@ -0,0 +1,97 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""OBS 上传辅助:prepare、upload、completeAndQuery 获取公网 URL."""++from __future__ import annotations++import hashlib+import os+from dataclasses import dataclass++import aiohttp++from jiuwenclaw.utils import logger+++@dataclass+class XiaoyiObsUploadConfig:+ """小艺 OBS 上传:服务端点与鉴权(对应 channels.xiaoyi 配置项)."""++ base_url: str+ api_key: str+ uid: str+++async def upload_local_file_public_url(+ session: aiohttp.ClientSession,+ config: XiaoyiObsUploadConfig,+ file_path: str,+ object_type: str = "TEMPORARY_MATERIAL_DOC",+) -> str:+ """上传本地文件并通过 completeAndQuery 返回可公网访问的 URL.++ Raises:+ RuntimeError: 任一步骤失败(prepare、上传、completeAndQuery 或缺少 url)。+ """+ base = config.base_url.rstrip("/")+ uid = config.uid+ try:+ with open(file_path, "rb") as f:+ file_content = f.read()+ file_name = os.path.basename(file_path)+ file_size = len(file_content)+ file_sha256 = hashlib.sha256(file_content).hexdigest()++ prepare_url = f"{base}/osms/v1/file/manager/prepare"+ prepare_data = {+ "objectType": object_type,+ "fileName": file_name,+ "fileSha256": file_sha256,+ "fileSize": file_size,+ "fileOwnerInfo": {"uid": uid, "teamId": uid},+ "useEdge": False,+ }+ headers = {+ "Content-Type": "application/json",+ "x-uid": uid,+ "x-api-key": config.api_key,+ "x-request-from": "openclaw",+ }+ async with session.post(prepare_url, json=prepare_data, headers=headers) as resp:+ if not resp.ok:+ raise RuntimeError(f"Prepare failed: HTTP {resp.status}")+ prepare_resp = await resp.json()+ if prepare_resp.get("code") != "0":+ raise RuntimeError(+ f"Prepare failed: {prepare_resp.get('desc', 'Unknown error')}"+ )+ object_id = prepare_resp.get("objectId")+ draft_id = prepare_resp.get("draftId")+ upload_infos = prepare_resp.get("uploadInfos", [])+ if not upload_infos:+ raise RuntimeError("No upload information returned")+ upload_info = upload_infos[0]+ async with session.request(+ upload_info.get("method", "PUT"),+ upload_info.get("url"),+ data=file_content,+ headers=upload_info.get("headers", {}),+ ) as resp:+ if not resp.ok:+ raise RuntimeError(f"Upload failed: HTTP {resp.status}")++ cq_url = f"{base}/osms/v1/file/manager/completeAndQuery"+ cq_data = {"objectId": object_id, "draftId": draft_id}+ async with session.post(cq_url, json=cq_data, headers=headers) as resp:+ if not resp.ok:+ raise RuntimeError(f"completeAndQuery failed: HTTP {resp.status}")+ cq_resp = await resp.json()+ file_url = (cq_resp.get("fileDetailInfo") or {}).get("url") or ""+ if not file_url:+ raise RuntimeError("completeAndQuery 未返回 fileDetailInfo.url")+ return file_url+ except RuntimeError:+ raise+ except Exception as e:+ logger.error("[upload_local_file_public_url] %s", e)+ raise RuntimeError(f"OBS 上传失败: {e}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.pynew file mode 100644index 0000000000..66161082f9--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/image_reading_tool.py@@ -0,0 +1,293 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""image_reading:++依赖配置 channels.xiaoyi:file_upload_url、api_key、uid+"""++from __future__ import annotations++import json+import os+import tempfile+import uuid+from typing import Any, Dict, Optional+from urllib.parse import unquote, urlparse++import aiohttp++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger++from .file_upload_helpers import XiaoyiObsUploadConfig, upload_local_file_public_url+from .utils import ToolInputError+++def _is_remote_url(value: str) -> bool:+ try:+ u = urlparse(value.strip())+ return u.scheme in ("http", "https")+ except Exception:+ return False+++def _suffix_from_url(url: str) -> str:+ """从 URL 取扩展名,缺省 .jpg。"""+ try:+ path = urlparse(url).path+ name = unquote(path.rsplit("/", 1)[-1] or "downloaded_image")+ name = name.split("?")[0]+ ext = os.path.splitext(name)[1]+ return ext if ext else ".jpg"+ except Exception:+ return ".jpg"+++async def _download_remote_to_temp(url: str) -> str:+ """下载远程图片到临时文件;调用方负责删除。"""+ suffix = _suffix_from_url(url)+ 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()++ tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)+ path = tmp.name+ try:+ tmp.write(data)+ tmp.flush()+ except Exception:+ tmp.close()+ try:+ os.unlink(path)+ except OSError:+ pass+ raise+ tmp.close()+ return path+++async def _call_image_understanding_api(+ image_url: str, text: str, api_key: str, uid: str+) -> str:+ api_url = (+ "https://hag-drcn.op.dbankcloud.com/celia-claw/v1/sse-api/skill/execute"+ )+ trace_id = str(uuid.uuid4())+ headers = {+ "Content-Type": "application/json",+ "Accept": "text/event-stream",+ "x-hag-trace-id": trace_id,+ "x-api-key": api_key,+ "x-request-from": "openclaw",+ "x-uid": uid,+ "x-skill-id": "image_comprehension",+ "x-prd-pkg-name": "com.huawei.hag",+ }+ payload: Dict[str, Any] = {+ "version": "1.0",+ "session": {+ "isNew": False,+ "sessionId": "wangyu202410241921",+ "interactionId": 0,+ },+ "endpoint": {+ "device": {+ "sid": "3df83a4a8124d7600f66206f96ea1e7e4e21c593adc4246bd20d450d8404cbf3",+ "deviceId": "3f35019f-ba4c-4ed5-80c0-6ddcef741200",+ "prdVer": "99.0.64.303",+ "phoneType": "WLZ-AL10",+ "sysVer": "HarmonyOS_2.0.0",+ "deviceType": 0,+ "timezone": "GMT+08:00",+ },+ "locale": "zh-CN",+ "sysLocale": "zh",+ "countryCode": "CN",+ },+ "utterance": {"type": "text", "original": text},+ "actions": [+ {+ "actionSn": str(uuid.uuid4()),+ "actionExecutorTask": {+ "pluginId": "aeac4e92c32949c1b7fc02de262615e6",+ "agentState": "OnShelf",+ "actionName": "imageUnderStandStream",+ "content": {"imageUrl": image_url, "text": text},+ },+ }+ ],+ }++ last_caption = ""+ buffer = ""++ async with aiohttp.ClientSession() as session:+ async with session.post(+ api_url,+ json=payload,+ headers=headers,+ timeout=aiohttp.ClientTimeout(total=120),+ ) as resp:+ if not resp.ok:+ body = await resp.text()+ raise RuntimeError(f"API request failed: {resp.status} {body[:500]}")+ async for chunk in resp.content.iter_chunked(4096):+ if not chunk:+ continue+ buffer += chunk.decode("utf-8", errors="replace")+ while "\n" in buffer:+ line, buffer = buffer.split("\n", 1)+ line = line.rstrip("\r")+ if not line or not line.startswith("data:"):+ continue+ data_content = line[5:].strip()+ if not data_content or data_content == "[DONE]":+ continue+ try:+ data_json = json.loads(data_content)+ except json.JSONDecodeError:+ continue+ for info in data_json.get("abilityInfos") or []:+ reply = (info.get("actionExecutorResult") or {}).get("reply") or {}+ si = reply.get("streamInfo") or {}+ sc = si.get("streamContent")+ if sc:+ last_caption = sc+ if not last_caption:+ raise RuntimeError("No caption received from image understanding API")+ return last_caption+++def _content_payload(payload: Dict[str, Any]) -> Dict[str, Any]:+ """与 TS 一致:content[0].text 为 JSON 字符串。"""+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(payload, ensure_ascii=False),+ }+ ]+ }+++@tool(+ name="image_reading",+ description="""+工具使用场景:+【必须调用此工具的情况】+1. 用户消息中包含 mediaPath 字段且不为空(表示用户发送了图片)+2. 用户希望理解图片内容,询问图片是什么,例如:+ - "这是什么?"+ - "图片里有什么?"+ - "帮我看看这张图"+ - "描述一下这张图片"+ - "分析一下这张照片"+ - "这个图片是什么意思"+ - "识别一下图片内容"+ - 或任何关于图片内容的理解、识别、分析类询问++当同时满足以上两个条件时,必须优先调用此工具进行图像理解。++工具能力描述:对图片进行理解和分析,返回图片的描述内容。++工具参数说明:+a. local_url:本地图片文件路径(可选,通常从用户消息的 mediaPath 字段获取)+b. remote_url:公网图片地址(可选)+c. prompt:对图片的提示问题,默认为"描述这张图片内容",可根据用户的具体问题自定义+d. local_url 与 remote_url 任意一个不为空即可,优先使用 local_url++注意事项:+a. 支持常见图片格式(jpg, png, gif等)+b. 远程图片会先下载到本地再处理+c. 操作超时时间为2分钟(120秒)+d. 返回图像理解的文本描述内容+""",+)+async def image_reading(+ local_url: Optional[str] = None,+ remote_url: Optional[str] = None,+ prompt: Optional[str] = None,+) -> Dict[str, Any]:+ """图像理解(与 image-reading-tool.ts 对齐)."""+ lu_sel = local_url if isinstance(local_url, str) and local_url else ""+ ru_sel = remote_url if isinstance(remote_url, str) and remote_url else ""+ if not lu_sel and not ru_sel:+ raise ToolInputError("须至少提供 localUrl 或 remoteUrl 之一")++ # 与 TS:params.prompt || "描述这张图片内容"+ text = prompt if isinstance(prompt, str) and prompt else "描述这张图片内容"++ from jiuwenclaw.config import get_config++ 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()+ if not base or not api_key or not uid:+ raise ToolInputError(+ "缺少 channels.xiaoyi 的 file_upload_url / api_key / uid 配置,无法上传图片"+ )++ obs_cfg = XiaoyiObsUploadConfig(base_url=base, api_key=api_key, uid=uid)+ image_input = lu_sel or ru_sel+ image_source = "local" if lu_sel else "remote"++ downloaded: Optional[str] = None+ image_obs_url: Optional[str] = None+ try:+ async with aiohttp.ClientSession() as session:+ # 与 processImageInput:先远程 URL,再本地文件+ if _is_remote_url(image_input):+ logger.info("[IMAGE_READING_TOOL] remote URL, download then upload")+ downloaded = await _download_remote_to_temp(image_input)+ image_obs_url = await upload_local_file_public_url(+ session, obs_cfg, downloaded+ )+ elif os.path.isfile(image_input):+ logger.info("[IMAGE_READING_TOOL] local file upload")+ image_obs_url = await upload_local_file_public_url(+ session, obs_cfg, image_input+ )+ else:+ raise RuntimeError(+ f"Invalid image input: must be a remote URL or local file path, "+ f"got: {image_input}"+ )++ if not image_obs_url:+ raise RuntimeError("图片上传失败:无法获取图片访问地址")++ caption = await _call_image_understanding_api(+ image_obs_url, text, api_key, uid+ )+ return _content_payload(+ {+ "caption": caption,+ "prompt": text,+ "imageSource": image_source,+ "success": True,+ }+ )+ except ToolInputError:+ raise+ except Exception as e:+ logger.error("[IMAGE_READING_TOOL] execution failed: %s", e)+ msg = str(e) if str(e) else "图片分析失败"+ return _content_payload(+ {+ "error": msg,+ "prompt": text,+ "imageSource": image_source,+ "success": False,+ }+ )+ finally:+ if downloaded and os.path.isfile(downloaded):+ try:+ os.unlink(downloaded)+ except OSError:+ passdiff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.pyindex b00c9a0c70..cbed270b45 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py@@ -2,41 +2,34 @@"""Location tool - 获取手机当前定位.-通过 WebSocket 发送 GetCurrentLocation 指令到手机端,-手机端执行系统定位后返回经纬度坐标。+通过 WebSocket 发送 GetCurrentLocation 指令到手机端,返回设备 outputs 的 JSON。"""from __future__ import annotations-import asyncioimport json-import logging-from typing import Any, Dict, List+from typing import Any, Dictfrom openjiuwen.core.foundation.tool import tool-from .base import execute_device_command, format_success_response--logger = logging.getLogger(__name__)+from jiuwenclaw.utils import logger+from .utils import execute_device_command, raise_if_device_error@tool(name="get_user_location",description=(- "获取用户当前位置(经纬度坐标,WGS84坐标系)。"- "需要用户设备授权位置访问权限。"+ "获取用户当前位置(经纬度坐标,WGS84坐标系)。需要用户设备授权位置访问权限。""注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"),)-async def get_user_location() -> Dict[str, List[Dict[str, str]]]:+async def get_user_location() -> Dict[str, Any]:"""获取用户当前地理位置.Returns:- 包含 content 数组的字典,content 中包含 type 和 text 字段- text 字段是 JSON 字符串,包含 latitude、longitude 和 coordinateSystem+ content[0].text 为设备 outputs 的 JSON 字符串"""- # Build GetCurrentLocation commandlogger.info("[LOCATION_TOOL] Starting execution - Building GetCurrentLocation command...")command = {"header": {@@ -52,41 +45,42 @@ async def get_user_location() -> Dict[str, List[Dict[str, str]]]:"dimension": "","executeMode": "background","intentName": "GetCurrentLocation",- "intentParam": {},+ "intentParam": {+ "isNeedGeoAddress": True,+ },"needUnlock": True,- "appType": "OHOS_APP","permissionId": [],"timeOut": 5,},"needUploadResult": True,- "noHalfPage": False,"pageControlRelated": False,- "responses": [{- "displayText": "",- "resultCode": "",- "ttsText": "",- }],+ "responses": [+ {+ "displayText": "",+ "resultCode": "",+ "ttsText": "",+ }+ ],},}- # Execute command and get resultlogger.info("[LOCATION_TOOL] Waiting for location response...")outputs = await execute_device_command("GetCurrentLocation", command)- latitude = outputs.get("latitude")- longitude = outputs.get("longitude")+ if not isinstance(outputs, dict):+ outputs = {"value": outputs}++ raise_if_device_error(outputs, "获取位置失败")- logger.info(f"[LOCATION_TOOL] Location retrieved successfully - latitude: {latitude}, longitude: {longitude}")+ logger.info(+ f"[LOCATION_TOOL] Location retrieved successfully - outputs keys: {list(outputs.keys())}"+ )return {"content": [{"type": "text",- "text": json.dumps({- "latitude": latitude,- "longitude": longitude,- "coordinateSystem": "WGS84",- })+ "text": json.dumps(outputs, ensure_ascii=False),}]}diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.pyindex 34058c0c53..3fed17721f 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py@@ -1,59 +1,113 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Message tools - 消息工具.+"""Message tools - 短信/消息工具.包含:-- search_messages: 搜索消息+- send_message: 发送短信+- search_message: 搜索短信"""from __future__ import annotations-import logging+import jsonfrom typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (+ _outputs_top_level_code_ok,execute_device_command,format_success_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)+def _mask_phone_for_log(phone: str) -> str:+ """日志中脱敏手机号."""+ p = (phone or "").strip()+ if len(p) <= 7:+ return "***"+ return f"{p[:3]}***{p[-4:]}"-@tool(- name="search_messages",- description="""搜索手机短信。根据关键词搜索短信内容。-注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多重试一次-""",+def _nested_result_error_message(outputs: Dict[str, Any]) -> Optional[str]:+ """部分 Intent 在 result 子对象中带 code/errMsg,与顶层 outputs 分离."""+ r = outputs.get("result")+ if not isinstance(r, dict):+ return None+ c = r.get("code")+ if c is None or _outputs_top_level_code_ok(c):+ return None+ msg = r.get("errorMsg") or r.get("errMsg") or str(c)+ return str(msg)+++def _log_outputs_summary(intent: str, outputs: Dict[str, Any]) -> None:+ try:+ blob = json.dumps(outputs, ensure_ascii=False)+ except Exception:+ blob = str(outputs)+ logger.info(+ "[%s_TOOL] outputs summary len=%s preview=%s",+ intent,+ len(blob),+ blob[:800],+ )+++@tool(+ name="send_message",+ description=(+ "通过手机发送短信。需要提供接收方手机号码和短信内容。"+ "手机号码会自动添加+86前缀(如果没有的话)。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),)-async def search_messages(- content: str,-) -> Dict[str, Any]:- """搜索短信消息.+async def send_message(phone_number: str, content: str) -> Dict[str, Any]:+ """发送短信.Args:- content: 搜索关键词,用于在短信内容中进行匹配+ phone_number: 接收方手机号码(会自动规范为 +86 前缀)+ content: 短信内容Returns:- 包含消息列表的响应字典+ 设备返回的完整 outputs,经 format_success_response 包装"""try:- logger.info(f"[MESSAGE_TOOL] Searching messages - content: {content}")+ logger.info(+ f"[SEND_MESSAGE_TOOL] Starting exec - phone_number: {phone_number}, content len: {len(content)}"+ )++ if not phone_number or not isinstance(phone_number, str):+ raise ToolInputError("缺少必填参数 phone_number(接收方手机号码)")- # 验证参数if not content or not isinstance(content, str):- raise ToolInputError("缺少必填参数 content(搜索关键词)")+ raise ToolInputError("缺少必填参数 content(短信内容)")+ phone_number = phone_number.strip()content = content.strip()++ if not phone_number:+ raise ToolInputError("phone_number 不能为空")+if not content:raise ToolInputError("content 不能为空")- # 构建命令+ # 未带 +86 时:去掉前导 0、再去 86 前缀,再加 +86+ if not phone_number.startswith("+86"):+ if phone_number.startswith("0"):+ phone_number = phone_number[1:]+ if phone_number.startswith("86"):+ phone_number = phone_number[2:]+ phone_number = f"+86{phone_number}"++ logger.info(+ "[SEND_MESSAGE_TOOL] Normalized phone -> %s",+ _mask_phone_for_log(phone_number),+ )+command = {"header": {"namespace": "Common",@@ -63,13 +117,14 @@ async def search_messages("cardParam": {},"executeParam": {"executeMode": "background",- "intentName": "SearchMessage",+ "intentName": "SendShortMessage","bundleName": "com.huawei.hmos.aidispatchservice","needUnlock": True,"actionResponse": True,"appType": "OHOS_APP","timeOut": 5,"intentParam": {+ "phoneNumber": phone_number,"content": content,},"permissionId": [],@@ -82,28 +137,111 @@ async def search_messages(},}- # 执行命令- outputs = await execute_device_command("SearchMessage", command)+ outputs = await execute_device_command("SendShortMessage", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"搜索短信失败: {error_msg} (错误代码: {code})")+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- # 提取结果- result = outputs.get("result", {})- messages = result.get("items", []) if isinstance(result, dict) else []+ _log_outputs_summary("SEND_MESSAGE", dict(outputs))+ raise_if_device_error(outputs, "发送短信失败")+ nested_err = _nested_result_error_message(outputs)+ if nested_err:+ logger.error(+ "[SEND_MESSAGE_TOOL] nested result error: %s",+ nested_err,+ )+ raise RuntimeError(f"发送短信失败: {nested_err}") from None- logger.info(f"[MESSAGE_TOOL] Found {len(messages)} messages")+ logger.info("[SEND_MESSAGE_TOOL] Message send completed")++ return format_success_response(dict(outputs), f"短信已发送至 {phone_number}")++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[SEND_MESSAGE_TOOL] Failed to send message: {e}")+ raise RuntimeError(f"发送短信失败: {str(e)}") from e+++@tool(+ name="search_message",+ description=(+ "搜索手机短信。根据关键词搜索短信内容。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),+)+async def search_message(+ content: str,+) -> Dict[str, Any]:+ """搜索短信++ Args:+ content: 搜索关键词,用于在短信内容中进行匹配++ Returns:+ content[0].text 为设备 outputs 的 JSON 字符串+ """+ try:+ if (+ not content+ or not isinstance(content, str)+ or content.strip() == ""+ ):+ raise ToolInputError("缺少必填参数 content(须为非空字符串)")- return format_success_response(- {"messages": messages, "count": len(messages)},- f"搜索到 {len(messages)} 条消息"+ content = content.strip()+ logger.info(+ "[SEARCH_MESSAGE_TOOL] Searching messages - keyword=%r",+ content,)+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchMessage",+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "content": content,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ outputs = await execute_device_command("SearchMessage", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ _log_outputs_summary("SEARCH_MESSAGE", dict(outputs))++ # 与 search-message-tool.ts 一致:text 为完整 event.outputs 的 JSON+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(outputs, ensure_ascii=False),+ }+ ]+ }+except ToolInputError:raiseexcept Exception as e:- logger.error(f"[MESSAGE_TOOL] Failed to search messages: {e}")- raise RuntimeError(f"搜索消息失败: {str(e)}") from e+ logger.error(f"[SEARCH_MESSAGE_TOOL] Failed to search messages: {e}")+ raise RuntimeError(f"搜索短信失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.pyindex dcd1ef917c..e047b073fc 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py@@ -10,31 +10,27 @@from __future__ import annotations-import logging-from typing import Any, Dict, List, Optional+from typing import Any, Dictfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,- validate_required_params,format_success_response,- format_error_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)-@tool(name="create_note",description="""在用户设备上创建备忘录。需要提供备忘录标题和内容。--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次-- 调用工具前需认真检查调用参数是否满足工具要求-""",+ 注意:+ a. 操作超时时间为60秒,请勿重复调用此工具+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。+ c. 调用工具前需认真检查调用参数是否满足工具要求+ """,)async def create_note(title: str, content: str) -> Dict[str, Any]:"""创建备忘录.@@ -44,18 +40,17 @@ async def create_note(title: str, content: str) -> Dict[str, Any]:content: 备忘录内容,必填Returns:- 包含创建结果的响应字典+ 设备返回的完整 outputs,经 format_success_response 包装"""try:- logger.info(f"[NOTE_TOOL] Creating note - title: {title}")+ logger.info(f"[CREATE_NOTE_TOOL] Creating note - title: {title}")- # 验证参数if not title or not isinstance(title, str):raise ToolInputError("缺少必填参数 title(备忘录标题)")if not content or not isinstance(content, str):raise ToolInputError("缺少必填参数 content(备忘录内容)")- # 构建命令+ # CreateNote:executeParam 不含 appType、permissionIdcommand = {"header": {"namespace": "Common",@@ -70,13 +65,11 @@ async def create_note(title: str, content: str) -> Dict[str, Any]:"dimension": "","needUnlock": True,"actionResponse": True,- "appType": "OHOS_APP","timeOut": 5,"intentParam": {"title": title,"content": content,},- "permissionId": [],"achieveType": "INTENT",},"responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],@@ -86,60 +79,51 @@ async def create_note(title: str, content: str) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("CreateNote", command)- # 提取结果(与 xy_channel 一致)- result = outputs.get("result", {})- code = outputs.get("code", "")-- logger.info(f"[NOTE_TOOL] Note created: title={result.get('title')}, id={result.get('entityId')}")-- return format_success_response(- {- "success": True,- "note": {- "entityId": result.get("entityId"),- "title": result.get("title"),- "content": result.get("content"),- "entityName": result.get("entityName"),- "modifiedDate": result.get("modifiedDate"),- },- "code": code,- },- f"备忘录 '{title}' 创建成功"- )+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "创建备忘录失败")++ logger.info("[CREATE_NOTE_TOOL] Note create completed")++ return format_success_response(dict(outputs), f"备忘录 '{title}' 创建成功")except ToolInputError:raiseexcept Exception as e:- logger.error(f"[NOTE_TOOL] Failed to create note: {e}")+ logger.error(f"[CREATE_NOTE_TOOL] Failed to create note: {e}")raise RuntimeError(f"创建备忘录失败: {str(e)}") from e@tool(name="search_notes",- description="""在用户设备上搜索备忘录。可以通过关键词搜索标题或内容。--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果搜索失败,最多只能重试一次-""",+ description=(+ "搜索用户设备上的备忘录内容。根据关键词在备忘录的标题、内容和附件名称中进行检索。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),)-async def search_notes(keyword: str, max_results: int = 10) -> Dict[str, Any]:+async def search_notes(query: str) -> Dict[str, Any]:"""搜索备忘录.Args:- keyword: 搜索关键词- max_results: 最大返回结果数,默认10+ query: 搜索关键词Returns:- 包含备忘录列表的响应字典+ 设备返回的完整 outputs,经 format_success_response 包装"""try:- logger.info(f"[NOTE_TOOL] Searching notes - keyword: {keyword}")+ logger.info(f"[SEARCH_NOTE_TOOL] Searching notes - query: {query}")- # 构建命令 - 与 xy_channel search-note-tool.ts 保持一致+ if not query or not isinstance(query, str):+ raise ToolInputError("缺少必填参数 query(搜索关键词)")++ query = query.strip()+ if not query:+ raise ToolInputError("query 不能为空")++ # SearchNote:executeParam 不含 appType、permissionIdcommand = {"header": {"namespace": "Common",@@ -154,12 +138,10 @@ async def search_notes(keyword: str, max_results: int = 10) -> Dict[str, Any]:"dimension": "","needUnlock": True,"actionResponse": True,- "appType": "OHOS_APP","timeOut": 5,"intentParam": {- "query": keyword, # xy_channel 使用 query 而非 keyword+ "query": query,},- "permissionId": [],"achieveType": "INTENT",},"responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],@@ -169,54 +151,36 @@ async def search_notes(keyword: str, max_results: int = 10) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("SearchNote", command)- # 检查结果结构(与 xy_channel 一致)- result = outputs.get("result", {})- items = result.get("items", []) if isinstance(result, dict) else []-- logger.info(f"[NOTE_TOOL] Found {len(items)} notes")-- # 格式化结果(移除 <em> 标签等)- formatted_notes = []- for item in items:- formatted_notes.append({- "entityId": item.get("entityId"),- "entityName": item.get("entityName"),- "title": item.get("title", "").replace("</?em>", ""), # 移除 <em> 标签- "content": item.get("content"),- "createdDate": item.get("createdDate"),- "modifiedDate": item.get("modifiedDate"),- })-- return format_success_response(- {- "notes": formatted_notes,- "count": len(formatted_notes),- "query": keyword,- "totalResults": len(formatted_notes),- },- f"搜索到 {len(formatted_notes)} 条备忘录"- )+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ raise_if_device_error(outputs, "搜索备忘录失败")+ result = outputs.get("result")+ if not isinstance(result, dict):+ result = {}+ n = len(result.get("items", []))+ logger.info(f"[SEARCH_NOTE_TOOL] Search completed, items={n}")++ return format_success_response(dict(outputs), f"搜索到 {n} 条备忘录")++ except ToolInputError:+ raiseexcept Exception as e:- logger.error(f"[NOTE_TOOL] Failed to search notes: {e}")+ logger.error(f"[SEARCH_NOTE_TOOL] Failed to search notes: {e}")raise RuntimeError(f"搜索备忘录失败: {str(e)}") from e@tool(name="modify_note",- description="""在指定备忘录中追加新内容。使用前必须先调用 search_notes 工具获取备忘录的 entityId。--参数说明:-- entity_id: 备忘录的唯一标识符(从 search_notes 工具获取)-- text: 要追加的文本内容--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多只能重试一次-""",+ description=(+ "在指定备忘录中追加新内容。使用前必须先调用 search_notes 工具获取备忘录的 entityId。"+ "参数说明:entityId 是备忘录的唯一标识符(从 search_notes 工具获取),"+ "text 是要追加的文本内容。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),)async def modify_note(entity_id: str,@@ -225,22 +189,20 @@ async def modify_note("""修改备忘录(追加模式).Args:- entity_id: 备忘录的唯一标识符(从 search_notes 获取),必填- text: 要追加的文本内容,必填+ entity_id: 备忘录实体 ID(设备侧字段名为 entityId)+ text: 要追加的文本Returns:- 包含修改结果的响应字典+ 设备返回的完整 outputs,经 format_success_response 包装"""try:- logger.info(f"[NOTE_TOOL] Modifying note - entity_id: {entity_id}")+ logger.info(f"[MODIFY_NOTE_TOOL] Modifying note - entity_id: {entity_id}")- # 验证参数- if not entity_id:- raise ToolInputError("缺少必填参数 entity_id(备忘录ID)")+ if not entity_id or not isinstance(entity_id, str):+ raise ToolInputError("缺少必填参数 entity_id(设备侧 entityId)")if not text or not isinstance(text, str):raise ToolInputError("缺少必填参数 text(要追加的文本内容)")- # 构建命令command = {"header": {"namespace": "Common",@@ -257,7 +219,7 @@ async def modify_note("appType": "OHOS_APP","timeOut": 5,"intentParam": {- "contentType": "1", # 1 = 追加模式 (append mode)+ "contentType": "1","text": text,"entityId": entity_id,},@@ -271,25 +233,19 @@ async def modify_note(},}- # 执行命令outputs = await execute_device_command("ModifyNote", command)- # 提取结果- result = outputs.get("result", {})+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- logger.info("[NOTE_TOOL] Note modified successfully")- return format_success_response(- {- "entity_id": entity_id,- "entityId": result.get("entityId"),- "title": result.get("title"),- "modifiedDate": result.get("modifiedDate"),- },- "备忘录修改成功"- )+ raise_if_device_error(outputs, "修改备忘录失败")++ logger.info("[MODIFY_NOTE_TOOL] Note modified successfully")++ return format_success_response(dict(outputs), "备忘录修改成功")except ToolInputError:raiseexcept Exception as e:- logger.error(f"[NOTE_TOOL] Failed to modify note: {e}")+ logger.error(f"[MODIFY_NOTE_TOOL] Failed to modify note: {e}")raise RuntimeError(f"修改备忘录失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.pyindex 92ab960a46..ee506607e2 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py@@ -8,59 +8,58 @@from __future__ import annotations-import logging-from typing import Any, Dict+from typing import Any, Dict, Optionalfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,format_success_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)-@tool(name="call_phone",- description="""拨打电话。需要提供要拨打的电话号码。--参数说明:-- phoneNumber: 要拨打的电话号码(必填)-- slotId: SIM卡槽ID,默认为0(主卡),设置为1表示副卡。仅当用户明确要求使用副卡时才设置为1--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多重试一次-""",+ description=(+ "拨打电话。需要提供要拨打的电话号码。"+ "slotId参数可选,默认为0(主卡),如果用户明确要求使用副卡则设置为1。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),)-async def call_phone(phone_number: str, slot_id: int = 0) -> Dict[str, Any]:+async def call_phone(+ phone_number: str,+ slot_id: Optional[int] = None,+) -> Dict[str, Any]:"""拨打电话.Args:phone_number: 要拨打的电话号码,必填- slot_id: SIM卡槽ID,0=主卡(默认),1=副卡+ slot_id: SIM 卡槽(设备字段 slotId);未传时按 0Returns:- 包含拨打结果的响应字典+ success、code、phoneNumber、slotId、message(与设备成功回调字段一致)"""try:- logger.info(f"[PHONE_TOOL] Calling phone number - phone_number: {phone_number}, slot_id: {slot_id}")+ if slot_id is None:+ slot_id = 0++ logger.info(+ f"[CALL_PHONE_TOOL] Calling - phone_number: {phone_number}, slotId: {slot_id}"+ )- # 验证参数if not phone_number or not isinstance(phone_number, str):- raise ToolInputError("缺少必填参数 phoneNumber(电话号码)")+ raise ToolInputError("缺少必填参数 phone_number(电话号码)")phone_number = phone_number.strip()if not phone_number:- raise ToolInputError("phoneNumber 不能为空")+ raise ToolInputError("phone_number 不能为空")- # 验证 slot_id- if slot_id not in [0, 1]:- raise ToolInputError("slotId 必须是 0(主卡)或 1(副卡)")+ if slot_id not in (0, 1):+ raise ToolInputError("slot_id 必须是 0(主卡)或 1(副卡)")- # 构建命令 - 与 xy_channel 保持一致command = {"header": {"namespace": "Common",@@ -90,39 +89,30 @@ async def call_phone(phone_number: str, slot_id: int = 0) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("StartCall", command)- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"拨打电话失败: {error_msg} (错误代码: {code})")-- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"拨打电话失败: {error_msg} (错误代码: {code})")+ if not isinstance(outputs, dict):+ outputs = {}- result = outputs.get("result", {})+ raise_if_device_error(outputs, "拨打电话失败")+ code = outputs.get("code")sim_name = "主卡" if slot_id == 0 else "副卡"- logger.info(f"[PHONE_TOOL] Call initiated successfully via {sim_name}")+ logger.info(f"[CALL_PHONE_TOOL] Call initiated successfully via {sim_name}")return format_success_response({- "phone_number": phone_number,- "slot_id": slot_id,- "sim": sim_name,"success": True,- "callState": result.get("callState"),+ "code": code,+ "phoneNumber": phone_number,+ "slotId": slot_id,+ "message": "电话拨打成功",},- f"正在使用{sim_name}拨打 {phone_number}..."+ f"正在使用{sim_name}拨打 {phone_number}...",)except ToolInputError:raiseexcept Exception as e:- logger.error(f"[PHONE_TOOL] Failed to initiate call: {e}")+ logger.error(f"[CALL_PHONE_TOOL] Failed to initiate call: {e}")raise RuntimeError(f"拨打电话失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.pyindex dcf4a0aa1e..03e1eafc5b 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py@@ -3,43 +3,61 @@"""Photo tools - 相册工具.包含:-- search_photos: 搜索照片-- upload_photos: 上传照片+- search_photo_gallery: 搜索图库+- upload_photo: 上传照片获取公网 URL"""from __future__ import annotationsimport json-import logging-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Unionfrom openjiuwen.core.foundation.tool import tool-from .base import (+from jiuwenclaw.utils import logger+from .utils import (execute_device_command,format_success_response,+ raise_if_device_error,ToolInputError,)-logger = logging.getLogger(__name__)-@tool(name="search_photo_gallery",- description="""搜索用户手机图库中的照片。--根据图像描述语料检索匹配的照片,返回照片在手机本地的 mediaUri 以及 thumbnailUri。-注意:返回的 mediaUri 和 thumbnailUri 是本地路径,无法直接下载或访问。如果需要下载、查看、使用或展示照片,请使用 upload_photos 工具将 mediaUri 或 thumbnailUri 转换为可访问的公网 URL。-- mediaUri 代表手机相册中的图片原图路径,图片大小比较大,清晰度比较高-- thumbnailUri 代表手机相册中的图片缩略图路径,图片大小比较小,清晰度适中,建议在 upload_photos 工具的入参中优先使用此路径,不容易引起上传超时等问题--参数说明:-- query: 图像描述语料,用于检索匹配的照片(例如:'小狗的照片'、'带有键盘的图片'等)--注意:-- 只有当用户明确表达从手机相册搜索或者从图库搜索时才执行此工具-- 操作超时时间为60秒,请勿重复调用,如果超时或失败,最多重试一次-""",+ description="""插件功能描述:搜索用户手机图库中的照片++ 工具使用约束:如果用户说从手机图库中或者从相册中查询xx图片时调用此工具,注意此工具仅支持从本地图库检索,不支持云空间相册检索。++ 工具输入输出简介:+ a. 根据图像描述语料检索匹配的照片,返回照片在手机本地的 mediaUri以及thumbnailUri。+ b. 返回的 mediaUri以及thumbnailUri 是本地路径,无法直接下载或访问。+ 如需下载、查看、使用或展示照片,请使用 upload_photo 工具将 mediaUri或者thumbnailUri 转换为可访问的公网 URL。+ c. mediaUri代表手机相册中的图片原图路径,图片大小比较大,清晰度比较高+ d. thumbnailUri代表手机相册中的图片缩略图路径,图片大小比较小,清晰度适中,建议在upload_photo 工具的入参中优先使用此路径,不容易引起上传超时等问题++ 搜索能力边界:+ a. 支持口语化输入:改写模型会自动提取姓名、种类、地点等实体,可以使用自然语言描述(如"小狗的照片"、"南京拍的风景")+ b. 支持相册搜索:可以在query中包含相册名称(如"西安之行相册的照片")+ c. 支持人像搜索:前提是照片有人像tag,且需要口语化描述(如"张三的照片")+ d. 不支持时间相对词:不支持"最新"、"最旧"、"最早"等表述,需要使用具体时间(如"2024年的照片"而非"去年的照片")+ e. 不支持多实体查询:不支持"或"逻辑和时间范围(如"南京或上海的照片"、"近三年的照片"),需要拆分成多次独立查询+ f. 不支持POI逆地理映射:照片的location是门牌号,用真实场地名称可能搜不到+ g. 不支持收藏感知:无法感知照片是否被收藏+ h. 不支持细粒度品种:对于动物、植物等的具体品种识别能力有限+ i. 注意:POI提取可能不准确:地名可能作为语义搜索条件,可能导致"xx湖"搜到"yy江"或"zz湾"的照片++ 查询优化建议:+ a. 时间查询:将"最新"、"去年"、"近三年"等转换为具体年份(如"2024年"、"2023年到2025年"需拆分成"2023年"、"2024年"、"2025年"三次查询)+ b. 多条件查询:将"或"逻辑拆分成多次查询(如"南京或上海的照片"→先查"南京的照片",再查"上海的照片")+ c. 实体原子化:确保每个query只包含一个原子实体(地点、人名、物品等)+ d. 相册名称:如果知道相册名,直接在query中包含相册名可以提高准确度++ 注意事项:+ a. 只有当用户明确表达从手机相册搜索或者从图库搜索时才执行此工具,如果用户仅表达要搜索xxx图片,并没有说明搜索数据源,则不要贸然调用此插件,可以优先尝试websearch或者询问用户是否要从手机图库中搜索。+ b. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。+ c. 如果用户请求包含多个实体或时间范围,需要主动拆分成多次查询并告知用户。+ """,)async def search_photo_gallery(query: str,@@ -47,19 +65,21 @@ async def search_photo_gallery("""搜索照片.Args:- query: 图像描述语料,用于检索匹配的照片+ query: 图像描述语料Returns:- 包含照片列表的响应字典+ 设备返回的完整 outputs,经 format_success_response 包装"""try:- logger.info(f"[PHOTO_TOOL] Searching photos - query: {query}")+ logger.info(f"[SEARCH_PHOTO_GALLERY_TOOL] Searching photos - query: {query}")- # 验证参数- if not query:+ if not query or not isinstance(query, str):raise ToolInputError("缺少必填参数 query(搜索关键词)")- # 构建命令 - 与 xy_channel search-photo-gallery-tool.ts 保持一致+ query = query.strip()+ if not query:+ raise ToolInputError("query 不能为空")+command = {"header": {"namespace": "Common",@@ -69,7 +89,7 @@ async def search_photo_gallery("cardParam": {},"executeParam": {"executeMode": "background",- "intentName": "SearchPhotoVideo", # 注意:xy_channel 使用 SearchPhotoVideo+ "intentName": "SearchPhotoVideo","bundleName": "com.huawei.hmos.aidispatchservice","needUnlock": True,"actionResponse": True,@@ -88,99 +108,98 @@ async def search_photo_gallery(},}- # 执行命令outputs = await execute_device_command("SearchPhotoVideo", command)- # 提取结果(与 xy_channel 一致)- result = outputs.get("result", {})- items = result.get("items", []) if isinstance(result, dict) else []+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- logger.info(f"[PHOTO_TOOL] Found {len(items)} photos")+ raise_if_device_error(outputs, "搜索照片失败")- return format_success_response(- {- "items": items,- "count": len(items),- "message": f"找到 {len(items)} 张照片。注意:mediaUri 和 thumbnailUri 是本地路径,无法直接访问。"- f"如需下载或查看,请使用 upload_photos 工具。"- },- f"搜索到 {len(items)} 张照片"- )+ result = outputs.get("result")+ if not isinstance(result, dict):+ result = {}+ n = len(result.get("items", []))+ logger.info(f"[SEARCH_PHOTO_GALLERY_TOOL] Search completed, items={n}")++ return format_success_response(dict(outputs), f"搜索到 {n} 张照片")except ToolInputError:raiseexcept Exception as e:- logger.error(f"[PHOTO_TOOL] Failed to search photos: {e}")+ logger.error(f"[SEARCH_PHOTO_GALLERY_TOOL] Failed to search photos: {e}")raise RuntimeError(f"搜索照片失败: {str(e)}") from e+def _normalize_media_uris(param: Any) -> List[str]:+ """将 media_uris 规范为字符串列表(支持数组或 JSON 数组字符串)。"""+ if param is None:+ raise ToolInputError("缺少必填参数 media_uris")+ if isinstance(param, list):+ return param+ if isinstance(param, str):+ try:+ parsed = json.loads(param)+ except json.JSONDecodeError as e:+ raise ToolInputError(+ f"media_uris 必须是合法 JSON 数组字符串。解析错误: {e}"+ ) from e+ if not isinstance(parsed, list):+ raise ToolInputError("media_uris 解析后必须是数组")+ return parsed+ raise ToolInputError(+ f"media_uris 必须是数组或 JSON 数组字符串,当前类型: {type(param).__name__}"+ )+++def _decode_image_url_escapes(url: str) -> str:+ """与 upload-photo-tool.ts getPhotoUrls 一致:替换 URL 中的 \\u003d、\\u0026。"""+ return url.replace("\\u003d", "=").replace("\\u0026", "&")++@tool(name="upload_photo",- description="""将手机本地文件回传并获取可公网访问的 URL。--前置工具调用:此工具使用前必须先调用 search_photo_gallery 工具获取照片的 mediaUri 或者 thumbnailUri-工具参数说明:-- 入参中的 mediaUris 中的 mediaUri 必须与 search_photo_gallery 结果中对应的 mediaUri 或者 thumbnailUri 完全保持一致,不要自行修改,必须是 file:// 开头的路径-- 优先使用 search_photo_gallery 结果中的 thumbnailUri 作为入参,thumbnailUri 是缩略图,清晰度与文件大小都非常合适展示给用户,如果 thumbnailUri 不存在或者用户要求使用原图,则使用 search_photo_gallery 结果中对应的 mediaUri-- mediaUris 是照片在手机本地的 URI 数组(从 search_photo_gallery 工具响应中获取)。限制:每次最多支持传入 3 条 mediaUri--注意:-- 操作超时时间为60秒,请勿重复调用,如果超时或失败,最多重试一次-- 此工具返回的图片链接为用户公网可访问的链接,如果需要后续操作需要下载到本地,如果需要返回给用户查看则直接以图片 markdown 的形式返回给用户-""",+ description="""工具能力描述:将手机本地文件回传并获取可公网访问的 URL。++ 前置工具调用:此工具使用前必须先调用 search_photo_gallery 工具获取照片的 mediaUri或者thumbnailUri+ 工具参数说明:+ a. 入参中的mediaUris中的mediaUri必须与search_photo_gallery结果中对应的mediaUri或者thumbnailUri完全保持一致,不要自行修改,必须是file://开头的路径。+ b. 优先使用search_photo_gallery结果中的thumbnailUri作为入参,thumbnailUri是缩略图,清晰度与文件大小都非常合适展示给用户,如果thumbnailUri不存在或者用户要求使用原图,则使用search_photo_gallery结果中对应的mediaUri+ c. media_uris 是照片在手机本地的 URI 数组(从 search_photo_gallery 工具响应中获取)。限制:每次最多支持传入 5 条 mediaUri++ 注意事项:+ a. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。+ b. 此工具返回的图片链接为用户公网可访问的链接,如果需要后续操作需要下载到本地,如果需要返回给用户查看则直接以图片markdown的形式返回给用户""",)-async def upload_photo(media_uris: List[str]) -> Dict[str, Any]:- """上传照片.+async def upload_photo(media_uris: Union[str, List[str]]) -> Dict[str, Any]:+ """上传照片Args:- media_uris: 照片媒体URI列表,每次最多3个(建议优先使用 thumbnailUri)+ media_uris:本地 URI 列表,或 JSON 数组字符串Returns:- 包含上传URL的响应字典+ imageUrls、count、message;单次最多 5 条 URI"""try:- logger.info(f"[PHOTO_TOOL] Uploading photos - media_uris count: {len(media_uris)}")-- # ===== 参数规范化:兼容数组和 JSON 字符串 =====- normalized_uris: List[str]-- if not media_uris:- raise ToolInputError("缺少必填参数 media_uris")-- # 情况1: 已经是数组- if isinstance(media_uris, list):- normalized_uris = media_uris- # 情况2: 是字符串,尝试解析为 JSON 数组- elif isinstance(media_uris, str):- try:- parsed = json.loads(media_uris)- if isinstance(parsed, list):- normalized_uris = parsed- else:- raise ToolInputError("media_uris 必须是数组或 JSON 数组字符串")- except json.JSONDecodeError as e:- raise ToolInputError(f"media_uris JSON 解析失败: {e}") from e- else:- raise ToolInputError(f"media_uris 类型错误: {type(media_uris)}")-- if len(normalized_uris) == 0:- raise ToolInputError("media_uris 数组不能为空")-- # 限制最多3条- if len(normalized_uris) > 3:- raise ToolInputError(f"每次最多支持上传 3 张照片,当前提供了 {len(normalized_uris)} 张")-- # 验证URI格式- for uri in normalized_uris:- if not isinstance(uri, str) or not uri.startswith("file://"):- raise ToolInputError(f"无效的 mediaUri: {uri},必须以 file:// 开头")-- logger.info(f"[PHOTO_TOOL] 验证通过,准备上传 {len(normalized_uris)} 张照片")-- # 构建参数- image_infos = [{"mediaUri": uri} for uri in normalized_uris]-- # 构建命令+ normalized = _normalize_media_uris(media_uris)+ logger.info(+ "[UPLOAD_PHOTO_TOOL] Normalized mediaUris count=%s",+ len(normalized),+ )++ if len(normalized) == 0:+ raise ToolInputError("mediaUris 数组不能为空")++ if len(normalized) > 5:+ raise ToolInputError(+ f"最多支持 5 条 mediaUri,当前提供了 {len(normalized)} 条。请分批处理。"+ )++ for uri in normalized:+ if not isinstance(uri, str) or not uri.strip():+ raise ToolInputError("media_uris 中每项必须为非空字符串")++ image_infos = [{"mediaUri": u.strip()} for u in normalized]+command = {"header": {"namespace": "Common",@@ -207,33 +226,56 @@ async def upload_photo(media_uris: List[str]) -> Dict[str, Any]:},}- # 执行命令outputs = await execute_device_command("ImageUploadForClaw", command)- # 提取结果- result = outputs.get("result", {})- image_urls = result.get("imageUrls", []) if isinstance(result, dict) else []+ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}- # 解码 URL 中的 Unicode 转义序列(如 \u003d -> =, \u0026 -> &)- decoded_urls = []- for url in image_urls:- decoded_url = url.replace("\\u003d", "=").replace("\\u0026", "&")- decoded_urls.append(decoded_url)- logger.info(f"[PHOTO_TOOL] Decoded URL: {url} -> {decoded_url}")+ result = outputs.get("result") if isinstance(outputs, dict) else None+ if not isinstance(result, dict):+ result = {}+ image_urls = result.get("imageUrls", [])+ if not isinstance(image_urls, list):+ image_urls = []- logger.info(f"[PHOTO_TOOL] Uploaded {len(decoded_urls)} photos")-- return format_success_response(- {- "imageUrls": decoded_urls,- "count": len(decoded_urls),- "message": f"成功获取 {len(decoded_urls)} 张照片的公网访问 URL"- },- f"成功上传 {len(decoded_urls)} 张照片"+ decoded_urls: List[str] = []+ for url in image_urls:+ if not isinstance(url, str):+ logger.warning(+ "[UPLOAD_PHOTO_TOOL] imageUrl 非字符串: %s",+ type(url),+ )+ continue+ decoded = _decode_image_url_escapes(url)+ if decoded != url:+ logger.info(+ "[UPLOAD_PHOTO_TOOL] Decoded URL: %s -> %s",+ url[:120] + ("..." if len(url) > 120 else ""),+ decoded[:120] + ("..." if len(decoded) > 120 else ""),+ )+ decoded_urls.append(decoded)++ logger.info(+ "[UPLOAD_PHOTO_TOOL] Retrieved %s image URLs",+ len(decoded_urls),)+ payload = {+ "imageUrls": decoded_urls,+ "count": len(decoded_urls),+ "message": f"成功获取 {len(decoded_urls)} 张照片的公网访问 URL",+ }+ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(payload, ensure_ascii=False),+ }+ ]+ }+except ToolInputError:raiseexcept Exception as e:- logger.error(f"[PHOTO_TOOL] Failed to upload photos: {e}")+ logger.error(f"[UPLOAD_PHOTO_TOOL] Failed to upload photos: {e}")raise RuntimeError(f"上传照片失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.pydeleted file mode 100644index cc0a60a9b5..0000000000--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py+++ /dev/null@@ -1,140 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""Send Message tool - 发送短信工具.--包含:-- send_message: 通过手机发送短信-"""--from __future__ import annotations--import logging-from typing import Any, Dict--from openjiuwen.core.foundation.tool import tool--from .base import (- execute_device_command,- format_success_response,- ToolInputError,-)--logger = logging.getLogger(__name__)---@tool(- name="send_message",- description="""通过手机发送短信。需要提供接收方手机号码和短信内容。--功能说明:-- 手机号码会自动添加+86前缀(如果没有的话)-- 支持发送给国内手机号码--参数:-- phone_number: 接收方手机号码(会自动添加+86前缀)-- content: 短信内容--注意:-- 操作超时时间为60秒,请勿重复调用此工具-- 如果超时或失败,最多重试一次-""",-)-async def send_message(phone_number: str, content: str) -> Dict[str, Any]:- """发送短信.-- Args:- phone_number: 接收方手机号码(会自动添加+86前缀)- content: 短信内容-- Returns:- 包含发送结果的响应字典- """- try:- logger.info(f"[SEND_MESSAGE_TOOL] Starting exec - phone_number: {phone_number}, content len: {len(content)}")-- # 验证参数- if not phone_number or not isinstance(phone_number, str):- raise ToolInputError("缺少必填参数 phone_number(接收方手机号码)")-- if not content or not isinstance(content, str):- raise ToolInputError("缺少必填参数 content(短信内容)")-- phone_number = phone_number.strip()- content = content.strip()-- if not phone_number:- raise ToolInputError("phone_number 不能为空")-- if not content:- raise ToolInputError("content 不能为空")-- # 规范化手机号码:添加 +86 前缀- if not phone_number.startswith("+86"):- # 移除开头的 0- if phone_number.startswith("0"):- phone_number = phone_number[1:]- # 避免重复添加 86 前缀- if phone_number.startswith("86"):- phone_number = phone_number[2:]- phone_number = f"+86{phone_number}"-- logger.info(f"[SEND_MESSAGE_TOOL] Normalized phone number: {phone_number}")-- # 构建命令- command = {- "header": {- "namespace": "Common",- "name": "Action",- },- "payload": {- "cardParam": {},- "executeParam": {- "executeMode": "background",- "intentName": "SendShortMessage",- "bundleName": "com.huawei.hmos.aidispatchservice",- "needUnlock": True,- "actionResponse": True,- "appType": "OHOS_APP",- "timeOut": 5,- "intentParam": {- "phoneNumber": phone_number,- "content": content,- },- "permissionId": [],- "achieveType": "INTENT",- },- "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],- "needUploadResult": True,- "noHalfPage": False,- "pageControlRelated": False,- },- }-- # 执行命令- outputs = await execute_device_command("SendShortMessage", command)-- # 检查错误码- code = outputs.get("code")- if code is not None and code != 0:- error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"- raise RuntimeError(f"发送短信失败: {error_msg} (错误代码: {code})")-- # 提取结果- result = outputs.get("result", {})-- logger.info("[SEND_MESSAGE_TOOL] Message sent successfully")-- return format_success_response(- {- "success": True,- "phoneNumber": phone_number,- "result": result,- },- f"短信已发送至 {phone_number}"- )-- except ToolInputError:- raise- except Exception as e:- logger.error(f"[SEND_MESSAGE_TOOL] Failed to send message: {e}")- raise RuntimeError(f"发送短信失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/utils.pysimilarity index 53%rename from jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.pyrename to jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/utils.pyindex cdbda5ef8f..8e4b414371 100644--- a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/utils.py@@ -1,6 +1,6 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Base utilities for xiaoyi handset tools.+"""Utilities for xiaoyi handset tools.提供设备侧工具的通用功能:- 获取 channel 实例@@ -11,12 +11,36 @@from __future__ import annotationsimport asyncio-import logging-from typing import Any, Callable, Dict, Optional+import json+from typing import Any, Dict, Optional+from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.xiaoyi_channel import get_xiaoyi_channel+from jiuwenclaw.config import get_config-logger = logging.getLogger(__name__)++def _is_data_event_status_success(status: Any) -> bool:+ """设备 data-event 的 status 是否为成功(兼容大小写及部分别名)."""+ if status is True:+ return True+ if status is None or status is False:+ return False+ s = str(status).strip().lower()+ return s in ("success", "succeed", "successful", "ok")+++def _outputs_top_level_code_ok(code: Any) -> bool:+ """outputs.code 表示成功或未携带错误码(None 视为不按 code 判失败)."""+ if code is None:+ return True+ if isinstance(code, bool):+ return bool(code)+ try:+ if isinstance(code, (int, float)) and int(code) == 0:+ return True+ except (TypeError, ValueError):+ pass+ return str(code).strip() == "0"class ToolInputError(Exception):@@ -60,13 +84,12 @@ async def execute_device_command(f"No active XY session found. {intent_name} tool can only be used during an active conversation.")- # 获取会话信息(从 config.yaml,与已验证的 location_tool.py 保持一致)+ # 从 config 读取 xiaoyi 通道的会话与任务标识session_id = ""task_id = ""message_id = f"cmd_{int(asyncio.get_event_loop().time() * 1000)}"try:- from jiuwenclaw.config import get_configconfig = get_config()xiaoyi_conf = config.get("channels", {}).get("xiaoyi", {})session_id = xiaoyi_conf.get("last_session_id", "")@@ -80,7 +103,10 @@ async def execute_device_command(f"No active XY session found. {intent_name} tool can only be used during an active conversation.")- logger.info(f"[{intent_name}_TOOL] Session context found: {session_id}")+ logger.info(+ f"[{intent_name}_TOOL] Session context: session_id={session_id!r} "+ f"task_id={task_id!r} message_id={message_id!r}"+ )# 创建事件等待结果result_event = asyncio.Event()@@ -90,23 +116,53 @@ async def execute_device_command(# 定义 data-event 处理器def on_data_event(event):nonlocal result_data, error_result- logger.info(f"[{intent_name}_TOOL] Received data event: intent={event.intent_name}, status={event.status}")-+ logger.info(+ f"[{intent_name}_TOOL] Received data event: intent={event.intent_name}, "+ f"status={event.status}"+ )+if event.intent_name == intent_name:logger.info(f"[{intent_name}_TOOL] Intent name matched! status={event.status}")- if event.status == "success" and event.outputs:- result_data = event.outputs- logger.info(f"[{intent_name}_TOOL] Execution successful, outputs={list(event.outputs.keys())}")+ # 设备在无短信等场景常返回 outputs: {},此处必须用「outputs is not None」判断。+ if _is_data_event_status_success(event.status):+ if event.outputs is None:+ error_result = RuntimeError(+ "执行失败: status=success 但 outputs 为 null"+ )+ logger.error(+ f"[{intent_name}_TOOL] success 但 outputs 为 null"+ )+ else:+ result_data = event.outputs+ keys = (+ list(event.outputs.keys())+ if isinstance(event.outputs, dict)+ else []+ )+ logger.info(+ f"[{intent_name}_TOOL] Execution successful, outputs keys={keys}"+ )else:error_result = RuntimeError(f"执行失败: {event.status}")- logger.error(f"[{intent_name}_TOOL] Execution failed: {event.status}")+ out_preview = ""+ if isinstance(event.outputs, dict):+ try:+ out_preview = json.dumps(+ event.outputs, ensure_ascii=False+ )[:600]+ except Exception:+ out_preview = str(event.outputs)[:600]+ logger.error(+ f"[{intent_name}_TOOL] Execution failed: status={event.status!r} "+ f"outputs_preview={out_preview}"+ )result_event.set()else:logger.debug(- f"[%s_TOOL] Intent name mismatch: expected=%s, got=%s",- intent_name, intent_name, event.intent_name+ f"[{intent_name}_TOOL] Intent name mismatch: expected={intent_name}, "+ f"got={event.intent_name}")# 注册处理器@@ -130,17 +186,48 @@ async def execute_device_command(await asyncio.wait_for(result_event.wait(), timeout=timeout)if error_result:+ logger.info(f"[{intent_name}_TOOL] Response error_result = {error_result}")raise error_result- return result_data or {}+ logger.info(f"[{intent_name}_TOOL] Response result_event = {result_event}")+ logger.info(f"[{intent_name}_TOOL] Response result_data = {result_data}")- except asyncio.TimeoutError:- logger.error(f"[{intent_name}_TOOL] Timeout: No response received within {timeout} seconds")+ # 成功时 outputs 可能为 {},勿用「or」短路(空 dict 在 Python 中为假)+ return {} if result_data is None else result_data++ except asyncio.TimeoutError as e:+ logger.error(+ f"[{intent_name}_TOOL] Timeout: no response within {timeout}s"+ )+ raise RuntimeError(+ f"设备命令超时({timeout}s 内未收到 {intent_name} 响应)"+ ) from efinally:channel.unregister_data_event_handler(intent_name, on_data_event)+def raise_if_device_error(outputs: Any, what_failed: str) -> None:+ """若设备 outputs 含失败 code 或 retErrCode,抛出 RuntimeError.++ 部分 Intent 使用 code,部分使用 retErrCode(字符串 \"0\" 表示成功)。+ """+ if not isinstance(outputs, dict):+ return+ code = outputs.get("code")+ if not _outputs_top_level_code_ok(code):+ error_msg = outputs.get("errorMsg") or outputs.get("errMsg") or "未知错误"+ raise RuntimeError(+ f"{what_failed}: {error_msg} (错误代码: {code})"+ ) from None+ ret = outputs.get("retErrCode")+ if ret is not None and str(ret) != "0":+ err_msg = outputs.get("errMsg", "未知错误")+ raise RuntimeError(+ f"{what_failed}: {err_msg} (retErrCode: {ret})"+ ) from None++def validate_required_params(params: Dict[str, Any], required: list[str]) -> None:"""验证必填参数.@@ -167,7 +254,6 @@ def format_success_response(data: Dict[str, Any], message: str = "") -> Dict[strReturns:包含 content 的响应字典"""- import jsonresponse = {"success": True, **data}if message:@@ -192,7 +278,6 @@ def format_error_response(error: str) -> Dict[str, Any]:Returns:包含 content 的错误响应字典"""- import jsonreturn {"content": [diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.pynew file mode 100644index 0000000000..4d08e18290--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_collection_tool.py@@ -0,0 +1,161 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Collection tool - 小艺收藏工具.++包含:+- xiaoyi_collection: 检索用户在小艺收藏中记下来的公共知识数据+"""++from __future__ import annotations++import json+from typing import Any, Dict++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .utils import execute_device_command, raise_if_device_error+++@tool(+ name="xiaoyi_collection",+ description=(+ "检索用户在小艺收藏中记下来的公共知识数据,可以给用户提供个性化体验。"+ "当用户语料中涉及从我的小艺收藏或者查看我的收藏或者我xx时候收藏的xxx帮我看一下这种类型的语料的时候需要使用此工具。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),+)+async def xiaoyi_collection(query_all: str = "true") -> Dict[str, Any]:+ """检索小艺收藏(与 xy_channel xiaoyi-collection-tool.ts 行为对齐).++ Args:+ query_all: 是否查询全部收藏,默认 \"true\"++ Returns:+ content[0].text: JSON 字符串(success / memoryInfo 或 totalResults+collections+message)+ """+ try:+ query_all_value = query_all or "true"++ logger.info(+ "[XIAOYI_COLLECTION_TOOL] Starting execution - queryAll=%r",+ query_all_value,+ )++ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "QueryCollection",+ "bundleName": "com.huawei.hmos.vassistant",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "queryAll": query_all_value,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ outputs = await execute_device_command("QueryCollection", command)++ if not isinstance(outputs, dict):+ outputs = {"outputs": outputs}++ 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(+ "[XIAOYI_COLLECTION_TOOL] Collections found: %s items",+ len(memory_info),+ )++ simplified_collections = []+ for item in memory_info:+ if not isinstance(item, dict):+ continue+ simplified_collections.append(+ {+ "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"),+ }+ )++ payload: Dict[str, Any] = {+ "success": True,+ "totalResults": len(simplified_collections),+ "collections": simplified_collections,+ }+ if isinstance(result, dict) and "message" in result:+ payload["message"] = result["message"]++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(payload, ensure_ascii=False),+ }+ ]+ }++ except Exception as e:+ logger.error(f"[XIAOYI_COLLECTION_TOOL] Failed to query collection: {e}")+ raise RuntimeError(f"查询小艺收藏失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_gui_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_gui_tool.pynew file mode 100644index 0000000000..9ab316417e--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/xiaoyi_gui_tool.py@@ -0,0 +1,156 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""小艺 GUI 自动化(xiaoyi_gui_agent):通过 InvokeJarvisGUIAgent 与设备协同完成屏幕操作."""++from __future__ import annotations++import asyncio+import time+import uuid+from typing import Any, Dict++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from jiuwenclaw.channel.xiaoyi_channel import get_xiaoyi_channel++from .utils import ToolInputError, format_success_response+++def _payload_is_gui_final(payload: Dict[str, Any]) -> bool:+ """兼容设备 isFinal 为 bool / 1 / \"true\" 等."""+ v = payload.get("isFinal")+ if v is True:+ return True+ if isinstance(v, (int, float)) and int(v) == 1:+ return True+ if isinstance(v, str) and v.strip().lower() in ("1", "true", "yes"):+ return True+ return False+++@tool(+ name="xiaoyi_gui_agent",+ description=(+ "通过模拟手机屏幕交互(点击、滑动、输入等)完成仅能在 App 内完成的操作。\n\n"+ "注意:超时约 3 分钟;执行期间勿并行调用其他工具;备忘录/日程请用专用工具而非写入 query。"+ "参数 query:自然语言操作指令与期望结果。"+ ),+)+async def xiaoyi_gui_agent(query: str) -> Dict[str, Any]:+ """执行 GUI Agent 指令."""+ if not query or not isinstance(query, str) or not query.strip():+ raise ToolInputError("缺少有效参数 query(非空字符串)")++ query = query.strip()+ channel = get_xiaoyi_channel()+ if channel is None:+ raise RuntimeError(+ "无活跃小艺会话,xiaoyi_gui_agent 仅能在小艺会话活跃时使用。"+ )++ session_id = ""+ task_id = ""+ last_message_id = ""+ try:+ from jiuwenclaw.config import get_config++ cfg = get_config()+ xiaoyi_conf = cfg.get("channels", {}).get("xiaoyi", {})+ session_id = (xiaoyi_conf.get("last_session_id") or "").strip()+ task_id = (xiaoyi_conf.get("last_task_id") or "").strip()+ last_message_id = (xiaoyi_conf.get("last_message_id") or "").strip()+ except Exception as e:+ logger.warning("[XIAOYI_GUI_TOOL] 读取会话配置失败: %s", e)++ if not session_id:+ raise RuntimeError(+ "无活跃小艺会话,xiaoyi_gui_agent 仅能在小艺会话活跃时使用。"+ )++ # 与 TS xiaoyi-gui-tool 一致:优先 taskId;空则回退 sessionId,避免 interactionId 为空+ interaction_id = task_id if task_id else session_id+ # JSON-RPC id 与当前用户轮次对齐(见 XiaoyiChannel message/stream 写入的配置)+ message_id = last_message_id or f"gui_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"++ logger.info(+ "[XIAOYI_GUI_TOOL] call session_id=%s interaction_id=%s rpc_id=%s",+ session_id[:12] + "..." if len(session_id) > 12 else session_id,+ interaction_id[:12] + "..." if len(interaction_id) > 12 else interaction_id,+ message_id[:32] + "..." if len(message_id) > 32 else message_id,+ )++ done = asyncio.Event()+ result_holder: Dict[str, Any] = {}++ def on_gui(item: dict[str, Any]) -> None:+ try:+ payload = item.get("payload") or {}+ riid = payload.get("interactionId")+ if riid is not None and str(riid).strip() != "":+ if str(riid).strip() != str(interaction_id).strip():+ logger.debug(+ "[XIAOYI_GUI_TOOL] 忽略非本单回包 interactionId=%r expected=%r",+ riid,+ interaction_id,+ )+ return+ if not _payload_is_gui_final(payload):+ logger.debug("[XIAOYI_GUI_TOOL] 非终帧,继续等待 isFinal")+ return+ sc = (payload.get("streamInfo") or {}).get("streamContent")+ if sc:+ result_holder["streamContent"] = sc+ else:+ result_holder["error"] = "GUI 响应缺少 streamContent"+ done.set()+ except Exception as ex:+ logger.warning("[XIAOYI_GUI_TOOL] on_gui 异常(已隔离): %s", ex, exc_info=True)+ result_holder["error"] = f"GUI 回调异常: {ex}"+ done.set()++ # 与 channel 层锁配合:同一时间仅一单 GUI,避免多 handler 共收同一 WS 帧+ async with channel.gui_tool_lock:+ channel.register_gui_agent_handler(on_gui)+ try:+ command = {+ "header": {+ "namespace": "ClawAgent",+ "name": "InvokeJarvisGUIAgentRequest",+ },+ "payload": {+ "query": query,+ "sessionId": session_id,+ "interactionId": interaction_id,+ },+ }+ logger.info("[XIAOYI_GUI_TOOL] sending InvokeJarvisGUIAgentRequest")+ sent = await channel.send_xiaoyi_phone_tools_command(+ session_id=session_id,+ task_id=task_id or session_id,+ message_id=message_id,+ command=command,+ )+ if not sent:+ raise RuntimeError("发送 GUI 指令失败,WebSocket 未连接")++ await asyncio.wait_for(done.wait(), timeout=180.0)++ err = result_holder.get("error")+ if err:+ raise RuntimeError(str(err))+ text = result_holder.get("streamContent", "")+ return format_success_response(+ {"success": True, "result": text},+ "GUI 操作完成",+ )+ except asyncio.TimeoutError as e:+ raise RuntimeError("小艺 GUI Agent 操作超时(3 分钟)") from e+ finally:+ try:+ channel.unregister_gui_agent_handler(on_gui)+ except Exception as unreg_err:+ logger.warning(+ "[XIAOYI_GUI_TOOL] unregister_gui_agent_handler: %s",+ unreg_err,+ )diff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex 6b134a3555..04ed53711b 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -14,6 +14,7 @@ import jsonimport osimport sslimport time+import uuidfrom dataclasses import dataclassfrom typing import Any, Callable, List, Optionalfrom urllib.parse import urlparse@@ -155,17 +156,17 @@ class XYFileUploadService:async with self.session.post(prepare_url, json=prepare_data, headers=headers) as resp:if not resp.ok:raise Exception(f"Prepare failed: HTTP {resp}")-+prepare_resp = await resp.json()if prepare_resp.get("code") != "0":- raise Exception(f"Prepare failed: {prepare_resp.get('desc', 'Unknown error')}")+ raise RuntimeError(f"Prepare failed: {prepare_resp.get('desc', 'Unknown error')}")object_id = prepare_resp.get("objectId")draft_id = prepare_resp.get("draftId")upload_infos = prepare_resp.get("uploadInfos", [])if not upload_infos:- raise Exception("No upload information returned")+ raise RuntimeError("No upload information returned")upload_info = upload_infos[0]upload_url = upload_info.get("url")@@ -179,7 +180,7 @@ class XYFileUploadService:headers=upload_headers) as resp:if not resp.ok:- raise Exception(f"Upload failed: HTTP {resp.status}")+ raise RuntimeError(f"Upload failed: HTTP {resp.status}")complete_url = f"{self.base_url}/osms/v1/file/manager/complete"complete_data = {@@ -189,11 +190,11 @@ class XYFileUploadService:async with self.session.post(complete_url, json=complete_data, headers=headers) as resp:if not resp.ok:- raise Exception(f"Complete failed: HTTP {resp.status}")+ raise RuntimeError(f"Complete failed: HTTP {resp.status}")complete_resp = await resp.json()if complete_resp.get("code") != "0":- raise Exception(f"Complete failed: {complete_resp.get('desc', 'Unknown error')}")+ raise RuntimeError(f"Complete failed: {complete_resp.get('desc', 'Unknown error')}")return object_id@@ -258,11 +259,20 @@ class XiaoyiChannel(BaseChannel):self._accumulated_texts: dict[str, str] = {} # Accumulated text per session for push notification# Data-event 处理器:intent_name -> list of handlersself._data_event_handlers: dict[str, List[Callable[[DataEvent], Any]]] = {}+ # InvokeJarvisGUIAgentResponse 原始事件回调列表+ self._gui_agent_handlers: List[Callable[[dict[str, Any]], Any]] = []+ # GUI 工具互斥:避免并发注册多个 handler 导致回包串单;不影响其他工具并发+ self._gui_tool_lock = asyncio.Lock()@propertydef channel_id(self) -> str:return self.name+ @property+ def gui_tool_lock(self) -> asyncio.Lock:+ """供 xiaoyi_gui_agent 串行执行,避免多路 GUI 回包互相唤醒。"""+ return self._gui_tool_lock+@propertydef clients(self) -> set[Any]:return set()@@ -424,8 +434,7 @@ class XiaoyiChannel(BaseChannel):last_chunk = Truefinal = Trueelse:- # 流式模式 - 类似 TS 版本的实现- # 判断事件类型+ # 流式模式:按事件类型计算增量与是否结束is_delta = msg.event_type == EventType.CHAT_DELTAlast_chunk = msg.event_type == EventType.CHAT_FINALis_final = msg.payload.get("is_complete", False)@@ -599,8 +608,8 @@ class XiaoyiChannel(BaseChannel):if isinstance(raw, bytes):raw = raw.decode("utf-8")message = json.loads(raw)- except (json.JSONDecodeError, UnicodeDecodeError):- logger.warning("XiaoyiChannel JSON 解析失败")+ except (json.JSONDecodeError, UnicodeDecodeError) as e:+ logger.warning(f"XiaoyiChannel JSON 解析失败: {e}")returnmsg_type = message.get("msgType")@@ -614,6 +623,8 @@ class XiaoyiChannel(BaseChannel):if msg_type == "heartbeat":return+ await self._dispatch_gui_agent_events(message)+# 检查是否是 data-only 消息(工具执行结果)data_event = self._extract_data_event(message)if data_event:@@ -629,6 +640,11 @@ class XiaoyiChannel(BaseChannel):elif method == "tasks/cancel":await self._handle_tasks_cancel(message)else:+ # 服务端 JSON-RPC 仅含 data parts 的工具回包(如纯 GUI 响应)无 method 字段+ if not method and not msg_type and message.get("jsonrpc") == "2.0":+ parts = self._get_a2a_parts(message)+ if parts and all(p.get("kind") == "data" for p in parts):+ returnlogger.warning(f"XiaoyiChannel 未知方法: {method}")async def _handle_message_stream(self, message: dict[str, Any]) -> None:@@ -715,11 +731,13 @@ class XiaoyiChannel(BaseChannel):try:from jiuwenclaw.config import update_channel_in_config+ rpc_id = message.get("id")update_channel_in_config("xiaoyi",{"last_session_id": session_id or "","last_task_id": task_id or "",+ "last_message_id": str(rpc_id) if rpc_id is not None else "",},)except Exception as config_error:@@ -1167,7 +1185,6 @@ class XiaoyiChannel(BaseChannel):Returns:是否发送成功"""- # 构建 A2A artifact-update 响应response = {"jsonrpc": "2.0","id": message_id,@@ -1175,22 +1192,22 @@ class XiaoyiChannel(BaseChannel):"taskId": task_id,"kind": "artifact-update","append": False,- "lastChunk": False,+ "lastChunk": True,"final": False,"artifact": {- "artifactId": f"artifact_{int(time.time() * 1000)}",+ "artifactId": str(uuid.uuid4()),"parts": [{"kind": "data", "data": {"commands": [command]}}],},},}- # 构建 WebSocket 包装消息+ # OutboundWebSocketMessage:msgType/agentId/sessionId/taskId/msgDetail(msgDetail 为 JSON 字符串)wrapper = {"msgType": "agent_response","agentId": self.config.agent_id,"sessionId": session_id,"taskId": task_id,- "msgDetail": json.dumps(response),+ "msgDetail": json.dumps(response, ensure_ascii=False),}# 发送到所有活跃连接@@ -1199,7 +1216,9 @@ class XiaoyiChannel(BaseChannel):if ws:try:await self._safe_ws_send(url_key, wrapper)- intent_name = command.get('payload', {}).get('executeParam', {}).get('intentName', 'unknown')+ intent_name = command.get("payload", {}).get("executeParam", {}).get("intentName") or command.get(+ "header", {}+ ).get("name", "unknown")logger.info(f"XiaoyiChannel 发送 command 成功 ({url_key}):intent={intent_name}")sent = Trueexcept Exception as e:@@ -1207,6 +1226,69 @@ class XiaoyiChannel(BaseChannel):return sent+ def _get_a2a_parts(self, message: dict[str, Any]) -> list[dict[str, Any]]:+ """从直连或 Wrapped A2A 消息中取出 message.parts."""+ msg_type = message.get("msgType")+ if msg_type == "data":+ try:+ a2a_request = json.loads(message.get("msgDetail", "{}"))+ except json.JSONDecodeError:+ return []+ params = a2a_request.get("params", {})+ else:+ params = message.get("params", {})+ msg = params.get("message", {})+ parts = msg.get("parts", [])+ return parts if isinstance(parts, list) else []++ async def _dispatch_gui_agent_events(self, message: dict[str, Any]) -> None:+ """分发 InvokeJarvisGUIAgentResponse(data.events 内).++ 各 handler 独立 try/except,单个工具回调异常不影响同帧其他 handler 及后续 data-event。+ """+ if len(self._gui_agent_handlers) > 1:+ logger.warning(+ "XiaoyiChannel GUI handler 数量=%s,可能存在并发未串行化",+ len(self._gui_agent_handlers),+ )+ for part in self._get_a2a_parts(message):+ if part.get("kind") != "data":+ continue+ events = part.get("data", {}).get("events", [])+ if not isinstance(events, list):+ continue+ for item in events:+ if (+ item.get("header", {}).get("namespace") == "ClawAgent"+ and item.get("header", {}).get("name") == "InvokeJarvisGUIAgentResponse"+ ):+ for h in list(self._gui_agent_handlers):+ try:+ if asyncio.iscoroutinefunction(h):+ await h(item)+ else:+ h(item)+ except Exception as e:+ logger.warning(+ "XiaoyiChannel GUI agent 处理器异常(已隔离): %s",+ e,+ exc_info=True,+ )++ def register_gui_agent_handler(self, handler: Callable[[dict[str, Any]], Any]) -> None:+ """注册 InvokeJarvisGUIAgentResponse 处理器."""+ if handler not in self._gui_agent_handlers:+ self._gui_agent_handlers.append(handler)+ logger.info("XiaoyiChannel 注册 GUI agent 处理器")++ def unregister_gui_agent_handler(self, handler: Callable[[dict[str, Any]], Any]) -> None:+ """注销 GUI agent 处理器."""+ try:+ self._gui_agent_handlers.remove(handler)+ logger.info("XiaoyiChannel 注销 GUI agent 处理器")+ except ValueError:+ pass+def register_data_event_handler(self, intent_name: str, handler: Callable[[DataEvent], Any]) -> None:@@ -1273,8 +1355,7 @@ class XiaoyiChannel(BaseChannel):Returns:DataEvent 或 None(如果不是 data-only 消息)"""- # 检查是否是 Wrapped format (msgType="data")- # 参考 xy_channel websocket.ts:569-606+ # Wrapped format:msgType="data",msgDetail 为嵌套的 A2A JSON-RPC 字符串msg_type = message.get("msgType")method = message.get("method")if msg_type == "data":@@ -1285,7 +1366,15 @@ class XiaoyiChannel(BaseChannel):msg = params.get("message", {})parts = msg.get("parts", [])session_id = message.get("sessionId", "")- except (json.JSONDecodeError, KeyError):+ except json.JSONDecodeError as e:+ logger.info(+ f"[XiaoyiChannel] _extract_data_event: msgDetail JSON 解析失败: {e}"+ )+ return None+ except KeyError as e:+ logger.info(+ f"[XiaoyiChannel] _extract_data_event: Wrapped A2A 缺少字段: {e}"+ )return Noneelse:# Direct A2A format@@ -1295,13 +1384,11 @@ class XiaoyiChannel(BaseChannel):session_id = message.get("sessionId", "")if not parts:- logger.debug(f"[XiaoyiChannel] _extract_data_event: no parts found")return None# 检查是否所有 parts 都是 data 类型data_parts = [p for p in parts if p.get("kind") == "data"]if not data_parts or len(data_parts) != len(parts):- logger.debug(f"[XiaoyiChannel] _extract_data_event: not all parts are data kind ")return None# 提取 data 内容@@ -1314,7 +1401,7 @@ class XiaoyiChannel(BaseChannel):for event in events:intent_name = ""outputs = {}- status = "success" # 默认为 success(与 xy_channel 一致)+ status = "success" # 未显式给出时与直接格式默认一致# 格式 1: 直接格式 (events[].intentName)if event.get("intentName"):