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
feat: 小艺channel支持端插件tool(小艺claw场景),并预置位置、备忘录等11个端插件tools
shenwei21ae36dc874114
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 1ca49e7b8f..e724765207 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -52,6 +52,18 @@ from jiuwenclaw.agentserver.tools.memory_tools import (read_memory,)from jiuwenclaw.agentserver.tools.video_tools import video_understanding+from jiuwenclaw.agentserver.tools.xiaoyi_phone_tools import (+ get_user_location,+ create_note, search_notes, modify_note,+ create_calendar_event, search_calendar,+ search_contacts,+ search_photo_gallery, upload_photo,+ search_files, upload_files, send_file_to_user,+ call_phone,+ send_message, search_messages,+ create_alarm, search_alarms, modify_alarm, delete_alarm,+ xiaoyi_collection,+)from jiuwenclaw.agentserver.tools.multimodal_config import (apply_audio_model_config_from_yaml,apply_vision_model_config_from_yaml,@@ -146,6 +158,7 @@ class JiuWenClaw:self._mcp_tools_registered: bool = Falseself._video_tool_registered: bool = Falseself._send_file_tool_registered: bool = False+ self._xiaoyi_phone_tools_registered: bool = Falseself._todo_tool_sessions_registered: set[str] = set()self._sysop_card_id: str | None = None@@ -372,6 +385,42 @@ class JiuWenClaw:except Exception as exc:logger.warning("[JiuWenClaw] audio tools registration skipped: %s", exc)+ # add device-side plugins (xiaoyi phone tools)+ config_base = get_config()+ channels_cfg = config_base.get("channels", {})+ xiaoyi_cfg = channels_cfg.get("xiaoyi", {})+ xiaoyi_phone_tools_enabled = xiaoyi_cfg.get("phone_tools_enabled", False)++ if xiaoyi_phone_tools_enabled:+ try:+ # 批量注册所有设备侧工具+ phone_tools = [+ get_user_location,+ create_note, search_notes, modify_note,+ create_calendar_event, search_calendar,+ search_contacts,+ search_photo_gallery, upload_photo,+ search_files, upload_files, send_file_to_user,+ call_phone,+ send_message, search_messages,+ create_alarm, search_alarms, modify_alarm, delete_alarm,+ xiaoyi_collection,+ ]++ for tool in phone_tools:+ try:+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ except Exception as tool_exc:+ logger.warning(f"[JiuWenClaw] Failed to register tool {tool.card.name}: {tool_exc}")++ self._xiaoyi_phone_tools_registered = True+ logger.info(f"[JiuWenClaw] {len(phone_tools)} xiaoyi phone tools registered successfully")+ except Exception as exc:+ logger.warning("[JiuWenClaw] xiaoyi phone tools registration skipped: %s", exc)+ else:+ logger.info("[JiuWenClaw] xiaoyi channel not enabled, skipping phone tools")+# add cron toolstry:cron_controller = CronController.get_instance()@@ -470,6 +519,38 @@ class JiuWenClaw:Runner.resource_mgr.add_tool(cron_tool)self._instance.ability_manager.add(cron_tool.card)+ # 小艺手机端插件(xiaoyi phone tools)未生效时重新加载+ config_base = get_config()+ channels_cfg = config_base.get("channels", {})+ xiaoyi_cfg = channels_cfg.get("xiaoyi", {})+ xiaoyi_phone_tools_enabled = xiaoyi_cfg.get("phone_tools_enabled", False)++ if xiaoyi_phone_tools_enabled and not self._xiaoyi_phone_tools_registered:+ try:+ phone_tools = [+ get_user_location,+ create_note, search_notes, modify_note,+ create_calendar_event, search_calendar,+ search_contacts,+ search_photo_gallery, upload_photo,+ search_files, upload_files, send_file_to_user,+ call_phone,+ send_message, search_messages,+ create_alarm, search_alarms, modify_alarm, delete_alarm,+ xiaoyi_collection,+ ]++ for tool in phone_tools:+ try:+ if not Runner.resource_mgr.get_tool(tool.card.id):+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ except Exception as tool_exc:+ logger.debug(f"[JiuWenClaw] Tool {tool.card.name} may already exist: {tool_exc}")++ except Exception as exc:+ logger.warning(f"[JiuWenClaw] xiaoyi phone tools runtime registration skipped: {exc}")+effective_session_id = session_id or "default"if mode == "plan":todo_toolkit = TodoToolkit(session_id=effective_session_id)@@ -1328,4 +1409,4 @@ class JiuWenClaw:return Nonedef _prepare_instance_by_session(self):- pass\ No newline at end of file+ passdiff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.pynew file mode 100644index 0000000000..f8a48697db--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/__init__.py@@ -0,0 +1,56 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Xiaoyi Handset Tools - 小艺手机端设备工具.++该目录包含需要连接小艺手机端设备才能使用的工具。+这些工具通过 WebSocket 与手机端通信,调用设备原生能力。++工具分类:+- 定位: get_user_location+- 备忘录: create_note, search_notes, modify_note+- 日历: create_calendar_event, search_calendar+- 联系人: search_contacts+- 相册: search_photo_gallery, upload_photo+- 文件: search_files, upload_files, send_file_to_user+- 电话: call_phone+- 短信: send_message+- 消息: search_messages+- 闹钟: create_alarm, search_alarms, modify_alarm, delete_alarm+- 收藏: xiaoyi_collection+"""++from .location_tool import get_user_location+from .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 .photo_tools import search_photo_gallery, upload_photo+from .file_tools import search_files, upload_files, send_file_to_user+from .phone_tools import call_phone+from .send_message_tool import send_message+from .message_tools import search_messages+from .alarm_tools import create_alarm, search_alarms, modify_alarm, delete_alarm+from .collection_tool import xiaoyi_collection++__all__ = [+ "get_user_location",+ "create_note",+ "search_notes",+ "modify_note",+ "create_calendar_event",+ "search_calendar",+ "search_contacts",+ "search_photo_gallery",+ "upload_photo",+ "search_files",+ "upload_files",+ "send_file_to_user",+ "call_phone",+ "send_message",+ "search_messages",+ "create_alarm",+ "search_alarms",+ "modify_alarm",+ "delete_alarm",+ "xiaoyi_collection",+]+diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.pynew file mode 100644index 0000000000..87b4c92395--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/alarm_tools.py@@ -0,0 +1,420 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Alarm tools - 闹钟工具.++包含:+- create_alarm: 创建闹钟+- search_alarms: 搜索闹钟+- modify_alarm: 修改闹钟+- delete_alarm: 删除闹钟+"""++from __future__ import annotations++import json+from typing import Any, Dict, List, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="create_alarm",+ description="""在用户设备上创建闹钟。需要提供闹钟时间和可选的重复设置。++时间格式:hh:mm(24小时制,例如 07:30 或 14:00)++参数说明:+- hour: 小时(0-23)+- minute: 分钟(0-59)+- repeat: 重复设置,如 "monday,tuesday"(可选)+- label: 闹钟标签/名称(可选)++注意:+- 操作超时时间为60秒,请勿重复调用+- 如果创建失败,最多只能重试一次+""",+)+async def create_alarm(+ hour: int,+ minute: int,+ repeat: Optional[str] = None,+ label: Optional[str] = None,+) -> Dict[str, Any]:+ """创建闹钟.++ Args:+ hour: 小时(0-23),必填+ minute: 分钟(0-59),必填+ repeat: 重复设置,如 "monday,tuesday,weekday,weekend,everyday"(可选)+ label: 闹钟标签(可选)++ 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",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "CreateAlarm",+ "bundleName": "com.huawei.hmos.clock",+ "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,+ },+ }++ # 执行命令+ 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})")++ result = outputs.get("result", {})+ time_str = f"{hour:02d}:{minute:02d}"+ logger.info(f"[ALARM_TOOL] Alarm created successfully at {time_str}")++ return format_success_response(+ {+ "success": True,+ "alarm": {+ "entityId": result.get("entityId"),+ "entityName": result.get("entityName"),+ "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"),+ },+ "code": code,+ },+ f"闹钟 {time_str} 创建成功"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[ALARM_TOOL] Failed to create alarm: {e}")+ raise RuntimeError(f"创建闹钟失败: {str(e)}") from e+++@tool(+ name="search_alarms",+ description="""在用户设备上搜索闹钟。++注意:+- 操作超时时间为60秒,请勿重复调用+- 返回设备上所有闹钟的列表+""",+)+async def search_alarms() -> Dict[str, Any]:+ """搜索闹钟.++ Returns:+ 包含闹钟列表的响应字典+ """+ try:+ logger.info("[ALARM_TOOL] Searching alarms")++ # 构建命令 - 与 xy_channel 保持一致+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchAlarm",+ "bundleName": "com.huawei.hmos.clock",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {"rangeType": "all"}, # 查询所有闹钟+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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})")++ # 提取结果(items 可能是 JSON 字符串数组,需要解析)+ result = outputs.get("result", {})+ items = result.get("items", []) if isinstance(result, dict) else []++ # 解析 JSON 字符串+ parsed_alarms = []+ 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}")+ elif isinstance(item, dict):+ parsed_alarms.append(item)++ logger.info(f"[ALARM_TOOL] Found {len(parsed_alarms)} alarms")++ return format_success_response(+ {"alarms": parsed_alarms, "count": len(parsed_alarms)},+ f"找到 {len(parsed_alarms)} 个闹钟"+ )++ except Exception as e:+ logger.error(f"[ALARM_TOOL] Failed to search alarms: {e}")+ raise RuntimeError(f"搜索闹钟失败: {str(e)}") from e+++@tool(+ name="modify_alarm",+ description="""在用户设备上修改闹钟。需要提供闹钟ID和要修改的参数。++参数说明:+- alarm_id: 闹钟ID(必填)+- hour: 新小时(可选)+- minute: 新分钟(可选)+- repeat: 新重复设置(可选)+- label: 新标签(可选)+- enabled: 是否启用(可选,true/false)++注意:+- 操作超时时间为60秒,请勿重复调用+""",+)+async def modify_alarm(+ alarm_id: str,+ hour: Optional[int] = None,+ minute: Optional[int] = None,+ repeat: Optional[str] = None,+ label: Optional[str] = None,+ enabled: Optional[bool] = 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++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "ModifyAlarm",+ "bundleName": "com.huawei.hmos.clock",+ "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,+ },+ }++ # 执行命令+ 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})")++ result = outputs.get("result", {})++ logger.info("[ALARM_TOOL] Alarm modified successfully")++ return format_success_response(+ {+ "alarm_id": alarm_id,+ "entityId": result.get("entityId"),+ "alarmTitle": result.get("alarmTitle"),+ "alarmState": result.get("alarmState"),+ },+ "闹钟修改成功"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[ALARM_TOOL] Failed to modify alarm: {e}")+ raise RuntimeError(f"修改闹钟失败: {str(e)}") from e+++@tool(+ name="delete_alarm",+ description="""在用户设备上删除闹钟。++参数说明:+- alarm_id: 要删除的闹钟ID(必填)++注意:+- 操作超时时间为60秒,请勿重复调用+- 删除后无法恢复+""",+)+async def delete_alarm(alarm_id: str) -> Dict[str, Any]:+ """删除闹钟.++ Args:+ alarm_id: 闹钟ID,必填++ Returns:+ 包含删除结果的响应字典+ """+ try:+ logger.info("[ALARM_TOOL] 🗑️ Deleting alarm")+ logger.info(f"[ALARM_TOOL] - alarm_id: {alarm_id}")++ # 验证参数+ if not alarm_id:+ raise ToolInputError("缺少必填参数 alarm_id(闹钟ID)")++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "DeleteAlarm",+ "bundleName": "com.huawei.hmos.clock",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {"alarmId": alarm_id},+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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})")++ result = outputs.get("result", {})++ logger.info("[ALARM_TOOL] Alarm deleted successfully")++ return format_success_response(+ {+ "alarm_id": alarm_id,+ "entityId": result.get("entityId"),+ "success": True,+ },+ "闹钟已删除"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[ALARM_TOOL] Failed to delete alarm: {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/base.pynew file mode 100644index 0000000000..0636766cb9--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/base.py@@ -0,0 +1,199 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Base utilities for xiaoyi handset tools.++提供设备侧工具的通用功能:+- 获取 channel 实例+- 发送 command 并等待响应+- 参数验证+"""++from __future__ import annotations++import asyncio+from typing import Any, Callable, Dict, Optional++from jiuwenclaw.utils import logger+from jiuwenclaw.channel.xiaoyi_channel import get_xiaoyi_channel+++class ToolInputError(Exception):+ """工具输入参数错误.++ 抛出此错误会让框架返回 HTTP 400 而非 500,+ LLM 会将其识别为参数错误而非瞬时故障。+ """++ def __init__(self, message: str):+ super().__init__(message)+ self.status = 400+++async def execute_device_command(+ intent_name: str,+ command: Dict[str, Any],+ timeout: float = 60.0,+) -> Dict[str, Any]:+ """执行设备命令并等待响应.++ Args:+ intent_name: Intent 名称,用于匹配响应+ command: Command 数据结构+ timeout: 超时时间(秒)++ Returns:+ 包含 content 字段的响应字典++ Raises:+ RuntimeError: 会话不存在或执行失败+ ToolInputError: 参数错误+ """+ logger.info(f"[{intent_name}_TOOL] Starting execution")++ # 获取 XiaoyiChannel 实例+ channel = get_xiaoyi_channel()+ if channel is None:+ logger.error(f"[{intent_name}_TOOL] FAILED: No active session found!")+ raise RuntimeError(+ f"No active XY session found. {intent_name} tool can only be used during an active conversation."+ )++ # 获取会话信息(从 config.yaml,与已验证的 location_tool.py 保持一致)+ session_id = ""+ task_id = ""+ message_id = f"cmd_{int(asyncio.get_event_loop().time() * 1000)}"++ try:+ from jiuwenclaw.config import get_config+ config = get_config()+ xiaoyi_conf = config.get("channels", {}).get("xiaoyi", {})+ session_id = xiaoyi_conf.get("last_session_id", "")+ task_id = xiaoyi_conf.get("last_task_id", "")+ except Exception as e:+ logger.warning(f"[{intent_name}_TOOL] 获取会话信息失败: {e}")++ if not session_id:+ logger.error(f"[{intent_name}_TOOL] FAILED: No valid session found!")+ raise RuntimeError(+ 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}")++ # 创建事件等待结果+ result_event = asyncio.Event()+ result_data: Optional[Dict[str, Any]] = None+ error_result: Optional[Exception] = None++ # 定义 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}")++ 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())}")+ else:+ error_result = RuntimeError(f"执行失败: {event.status}")+ logger.error(f"[{intent_name}_TOOL] Execution failed: {event.status}")++ result_event.set()+ else:+ logger.debug(f"[{intent_name}_TOOL] Intent name mismatch: expected={intent_name}, got={event.intent_name}")++ # 注册处理器+ channel.register_data_event_handler(intent_name, on_data_event)++ try:+ # 发送命令+ logger.info(f"[{intent_name}_TOOL] Sending command...")+ 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("发送指令失败,WebSocket 未连接")++ # 等待响应+ logger.info(f"[{intent_name}_TOOL] Waiting for response (timeout: {timeout}s)...")+ await asyncio.wait_for(result_event.wait(), timeout=timeout)++ if error_result:+ raise error_result++ return result_data or {}++ except asyncio.TimeoutError:+ logger.error(f"[{intent_name}_TOOL] Timeout: No response received within {timeout} seconds")++ finally:+ channel.unregister_data_event_handler(intent_name, on_data_event)+++def validate_required_params(params: Dict[str, Any], required: list[str]) -> None:+ """验证必填参数.++ Args:+ params: 参数字典+ required: 必填参数名列表++ Raises:+ ToolInputError: 缺少必填参数+ """+ for param_name in required:+ value = params.get(param_name)+ if value is None or (isinstance(value, str) and not value.strip()):+ raise ToolInputError(f"缺少必填参数 {param_name}")+++def format_success_response(data: Dict[str, Any], message: str = "") -> Dict[str, Any]:+ """格式化成功响应.++ Args:+ data: 响应数据+ message: 可选的消息++ Returns:+ 包含 content 的响应字典+ """+ import json++ response = {"success": True, **data}+ if message:+ response["message"] = message++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps(response, ensure_ascii=False),+ }+ ]+ }+++def format_error_response(error: str) -> Dict[str, Any]:+ """格式化错误响应.++ Args:+ error: 错误信息++ Returns:+ 包含 content 的错误响应字典+ """+ import json++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps({"success": False, "error": error}, ensure_ascii=False),+ }+ ]+ }diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.pynew file mode 100644index 0000000000..7e0da7e34e--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/calendar_tools.py@@ -0,0 +1,280 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Calendar tools - 日历工具.++包含:+- create_calendar_event: 创建日程+- search_calendar: 搜索日程+"""++from __future__ import annotations++from datetime import datetime+from typing import Any, Dict, List, Optional++from openjiuwen.core.foundation.tool import tool+++def _format_timestamp_to_datetime(timestamp_ms: int) -> str:+ """将毫秒时间戳转换为 yyyy-mm-dd hh:mm:ss 格式.++ Args:+ timestamp_ms: 毫秒时间戳++ Returns:+ 格式化的日期时间字符串+ """+ if not timestamp_ms:+ return ""+ dt = datetime.fromtimestamp(timestamp_ms / 1000)+ return dt.strftime("%Y-%m-%d %H:%M:%S")+++def _convert_event_timestamps(event: Dict[str, Any]) -> Dict[str, Any]:+ """将事件中的时间戳转换为可读格式.++ Args:+ event: 日程事件字典++ Returns:+ 转换后的事件字典+ """+ result = dict(event)+ if "dtStart" in result and result["dtStart"]:+ result["dtStart"] = _format_timestamp_to_datetime(result["dtStart"])+ if "dtEnd" in result and result["dtEnd"]:+ result["dtEnd"] = _format_timestamp_to_datetime(result["dtEnd"])+ return result++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ validate_required_params,+ format_success_response,+ format_error_response,+ ToolInputError,+)+++@tool(+ name="create_calendar_event",+ description="""在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。++时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。++注意:+- 该工具执行时间较长(最多60秒),请勿重复调用+- 超时或失败时最多重试一次+- 使用该工具之前需获取当前真实时间+""",+)+async def create_calendar_event(+ title: str,+ dt_start: str,+ dt_end: str,+ location: Optional[str] = None,+ description: Optional[str] = None,+) -> Dict[str, Any]:+ """创建日程.++ Args:+ title: 日程标题/名称,必填+ dt_start: 开始时间,格式 yyyy-mm-dd hh:mm:ss+ dt_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}")++ # 验证参数+ if not title:+ raise ToolInputError("缺少必填参数 title(日程标题)")+ if not dt_start:+ raise ToolInputError("缺少必填参数 dt_start(开始时间)")+ if not dt_end:+ raise ToolInputError("缺少必填参数 dt_end(结束时间)")++ # 转换时间字符串为时间戳+ try:+ start_dt = datetime.strptime(dt_start, "%Y-%m-%d %H:%M:%S")+ end_dt = datetime.strptime(dt_end, "%Y-%m-%d %H:%M:%S")+ dt_start_ms = int(start_dt.timestamp() * 1000)+ dt_end_ms = int(end_dt.timestamp() * 1000)+ except ValueError:+ raise ToolInputError(+ "时间格式错误。必须使用: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++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "ActionAndResult",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "CreateCalendarEvent",+ "bundleName": "com.huawei.hmos.calendardata",+ "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,+ },+ }++ # 执行命令+ result = await execute_device_command("CreateCalendarEvent", command)++ 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}' 创建成功"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[CALENDAR_TOOL] Failed to create calendar event: {e}")+ raise RuntimeError(f"创建日程失败: {str(e)}") from e+++@tool(+ name="search_calendar",+ description="""在用户设备上搜索日程。可以按标题、时间范围搜索。++时间格式:yyyy-mm-dd hh:mm:ss++注意:+- 操作超时时间为60秒,请勿重复调用+- 如果搜索失败,最多只能重试一次+""",+)+async def search_calendar(+ keyword: Optional[str] = None,+ start_time: Optional[str] = None,+ end_time: Optional[str] = None,+ max_results: int = 10,+) -> Dict[str, Any]:+ """搜索日程.++ Args:+ keyword: 搜索关键词(可选)+ start_time: 开始时间范围(可选)+ end_time: 结束时间范围(可选)+ max_results: 最大返回结果数,默认10++ 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++ 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++ # 使用 timeInterval 数组格式+ if start_time_ms and end_time_ms:+ intent_param["timeInterval"] = [start_time_ms, end_time_ms]++ if keyword:+ intent_param["title"] = keyword++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchCalendarEvent",+ "bundleName": "com.huawei.hmos.calendardata",+ "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,+ },+ }++ # 执行命令+ 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']})")++ # 获取结果+ result = outputs.get("result", {})+ items = result.get("items", []) if isinstance(result, dict) else []++ # 转换时间戳为可读格式+ formatted_items = [_convert_event_timestamps(item) for item in items]++ logger.info(f"[CALENDAR_TOOL] Found {len(formatted_items)} events")++ return format_success_response(+ {"events": formatted_items, "count": len(formatted_items)},+ f"搜索到 {len(formatted_items)} 条日程"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..85db8067bf--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/collection_tool.py@@ -0,0 +1,141 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Collection tool - 小艺收藏工具.++包含:+- xiaoyi_collection: 检索用户在小艺收藏中记下来的公共知识数据+"""++from __future__ import annotations++from typing import Any, Dict, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@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.pynew file mode 100644index 0000000000..ef95b23b36--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/contact_tools.py@@ -0,0 +1,106 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Contact tools - 联系人工具.++包含:+- search_contacts: 搜索联系人+"""++from __future__ import annotations++from typing import Any, Dict, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="search_contacts",+ description="""搜索用户设备上的联系人信息。根据姓名在通讯录中检索联系人详细信息(包括姓名、电话号码、邮箱、组织、职位等)。++注意:+- 操作超时时间为60秒,请勿重复调用此工具+- 如果超时或失败,最多重试一次+""",+)+async def search_contacts(+ name: str,+) -> Dict[str, Any]:+ """搜索联系人.++ Args:+ name: 联系人姓名,用于在通讯录中检索联系人信息++ Returns:+ 包含联系人列表的响应字典+ """+ try:+ logger.info(f"[CONTACT_TOOL] Searching contacts - name: {name}")++ # 验证参数+ if not name or not isinstance(name, str):+ raise ToolInputError("缺少必填参数 name(联系人姓名)")++ name = name.strip()+ if not name:+ raise ToolInputError("name 不能为空")++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchContactLocal",+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "name": name,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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", {})++ logger.info(f"[CONTACT_TOOL] found {len(result.get('items', [])) if isinstance(result, dict) else 0} contacts")++ return format_success_response(+ {"result": result},+ f"搜索到联系人信息"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..7dcdb48606--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/file_tools.py@@ -0,0 +1,318 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""File tools - 文件工具.++包含:+- search_files: 搜索文件+- upload_files: 上传文件+- send_file_to_user: 发送文件给用户+"""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="search_files",+ description="""搜索手机文件系统的文件。++【重要】使用约束:此工具仅在用户显著说明要从手机搜索时才执行,例如:+- "从我手机里面搜索xxxx"+- "从手机文件系统找一下xxxx"+- "在手机上查找文件xxxx"+- "搜索手机里的文件"++如果用户没有明确说明从手机搜索(如仅说"搜索文件"、"找一下xxxx"),应默认从 openclaw 本地的文件系统查询,不要调用此工具。++功能说明:根据关键词搜索文件名称或内容,返回匹配的文件列表(包括文件名、路径、大小、修改时间等信息)。++注意:+- 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次+""",+)+async def search_files(+ query: str,+) -> Dict[str, Any]:+ """搜索文件.++ Args:+ query: 搜索关键词,用于匹配文件名称、后缀名或文件内容++ Returns:+ 包含文件列表的响应字典+ """+ try:+ logger.info(f"[FILE_TOOL] Searching files - query: {query}")++ # 验证参数+ if not query or not isinstance(query, str):+ raise ToolInputError("缺少必填参数 query(搜索关键词)")++ query = query.strip()+ if not query:+ raise ToolInputError("query 不能为空")++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchFile",+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "query": query,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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})")++ # 提取结果+ result = outputs.get("result", {})+ files = result.get("items", []) if isinstance(result, dict) else []++ logger.info(f"[FILE_TOOL] Found {len(files)} files")++ return format_success_response(+ {"files": files, "count": len(files)},+ f"搜索到 {len(files)} 个文件"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[FILE_TOOL] Failed to search files: {e}")+ raise RuntimeError(f"搜索文件失败: {str(e)}") from e+++@tool(+ name="upload_files",+ description="""将手机本地文件上传并获取可公网访问的 URL。++前置工具调用:此工具使用前必须先调用 search_files 工具获取文件的 uri++工具参数说明:+a. 入参中的fileInfos数组,每个元素必须包含mediaUri字段(对应于search_file工具返回结果中的uri),必须与search_file结果中对应的uri完全保持一致,不要自行修改。+b. fileInfos中的timeout字段是可选的,表示上传文件超时时间,单位是毫秒,默认是20000(20秒)。+c. fileInfos 是文件在手机本地的信息数组(从 search_file 工具响应中获取)。限制:每次最多支持传入 5 条文件信息。++注意:+- 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次+- 此工具返回的文件链接为用户公网可访问的链接,如果需要对文件进行额外的操作,需要先根据返回的url下载文件,然后进行下一步处理+""",+)+async def upload_files(file_infos: List[Dict[str, Any]]) -> Dict[str, Any]:+ """上传文件.++ Args:+ file_infos: 文件信息数组,每个元素包含mediaUri(必需)和timeout(可选,默认20000)++ Returns:+ 包含上传URL的响应字典+ """+ try:+ logger.info(f"[FILE_TOOL] Uploading files - file_infos count: {len(file_infos)}")++ # 验证参数+ if not file_infos or not isinstance(file_infos, list):+ raise ToolInputError("file_infos 必须是包含文件信息的数组")++ if len(file_infos) > 5:+ raise ToolInputError(f"每次最多支持上传 5 个文件,当前提供了 {len(file_infos)} 个")++ # 验证每个文件信息+ for i, file_info in enumerate(file_infos):+ 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 字符串")+ # 设置默认超时+ if not file_info.get("timeout"):+ file_info["timeout"] = "20000"++ # 构建命令 - 与 xy_channel 保持一致+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "FileUploadForClaw",+ "bundleName": "com.huawei.hmos.vassistant",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {"fileInfos": file_infos},+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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})")++ # 提取结果并解码URL+ result = outputs.get("result", {})+ file_urls = result.get("fileUrls", []) if isinstance(result, dict) else []++ # 解码 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")++ return format_success_response(+ {+ "fileUrls": decoded_urls,+ "count": len(decoded_urls),+ "message": f"成功获取 {len(decoded_urls)} 个文件的公网访问 URL"+ },+ f"成功上传 {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,+ },+ }++ # 执行命令+ 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:+ raise+ except Exception as e:+ logger.error(f"[FILE_TOOL] Failed to send file: {e}")+ raise RuntimeError(f"发送文件失败: {str(e)}") from ediff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.pynew file mode 100644index 0000000000..97f54a8dd5--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/location_tool.py@@ -0,0 +1,90 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Location tool - 获取手机当前定位.++通过 WebSocket 发送 GetCurrentLocation 指令到手机端,+手机端执行系统定位后返回经纬度坐标。+"""++from __future__ import annotations++import asyncio+import json+from typing import Any, Dict, List++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import execute_device_command, format_success_response+++@tool(+ name="get_user_location",+ description=(+ "获取用户当前位置(经纬度坐标,WGS84坐标系)。"+ "需要用户设备授权位置访问权限。"+ "注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。"+ ),+)+async def get_user_location() -> Dict[str, List[Dict[str, str]]]:+ """获取用户当前地理位置.++ Returns:+ 包含 content 数组的字典,content 中包含 type 和 text 字段+ text 字段是 JSON 字符串,包含 latitude、longitude 和 coordinateSystem+ """++ # Build GetCurrentLocation command+ logger.info("[LOCATION_TOOL] Starting execution - Building GetCurrentLocation command...")+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "achieveType": "INTENT",+ "actionResponse": True,+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "dimension": "",+ "executeMode": "background",+ "intentName": "GetCurrentLocation",+ "intentParam": {},+ "needUnlock": True,+ "appType": "OHOS_APP",+ "permissionId": [],+ "timeOut": 5,+ },+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ "responses": [{+ "displayText": "",+ "resultCode": "",+ "ttsText": "",+ }],+ },+ }++ # Execute command and get result+ logger.info("[LOCATION_TOOL] Waiting for location response...")+ outputs = await execute_device_command("GetCurrentLocation", command)++ latitude = outputs.get("latitude")+ longitude = outputs.get("longitude")++ logger.info(f"[LOCATION_TOOL] Location retrieved successfully - latitude: {latitude}, longitude: {longitude}")++ return {+ "content": [+ {+ "type": "text",+ "text": json.dumps({+ "latitude": latitude,+ "longitude": longitude,+ "coordinateSystem": "WGS84",+ })+ }+ ]+ }diff --git a/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.pynew file mode 100644index 0000000000..bc75c7c78b--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/message_tools.py@@ -0,0 +1,107 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Message tools - 消息工具.++包含:+- search_messages: 搜索消息+"""++from __future__ import annotations++from typing import Any, Dict, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="search_messages",+ description="""搜索手机短信。根据关键词搜索短信内容。++注意:+- 操作超时时间为60秒,请勿重复调用此工具+- 如果超时或失败,最多重试一次+""",+)+async def search_messages(+ content: str,+) -> Dict[str, Any]:+ """搜索短信消息.++ Args:+ content: 搜索关键词,用于在短信内容中进行匹配++ Returns:+ 包含消息列表的响应字典+ """+ try:+ logger.info(f"[MESSAGE_TOOL] Searching messages - content: {content}")++ # 验证参数+ if not content or not isinstance(content, str):+ raise ToolInputError("缺少必填参数 content(搜索关键词)")++ content = content.strip()+ if not content:+ raise ToolInputError("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)++ # 检查错误码+ 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", {})+ messages = result.get("items", []) if isinstance(result, dict) else []++ logger.info(f"[MESSAGE_TOOL] Found {len(messages)} messages")++ return format_success_response(+ {"messages": messages, "count": len(messages)},+ f"搜索到 {len(messages)} 条消息"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..83e259b93f--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/note_tools.py@@ -0,0 +1,293 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Note tools - 备忘录工具.++包含:+- create_note: 创建备忘录+- search_notes: 搜索备忘录+- modify_note: 修改备忘录+"""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ validate_required_params,+ format_success_response,+ format_error_response,+ ToolInputError,+)+++@tool(+ name="create_note",+ description="""在用户设备上创建备忘录。需要提供备忘录标题和内容。++注意:+- 操作超时时间为60秒,请勿重复调用此工具+- 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次+- 调用工具前需认真检查调用参数是否满足工具要求+""",+)+async def create_note(title: str, content: str) -> Dict[str, Any]:+ """创建备忘录.++ Args:+ title: 备忘录标题,必填+ content: 备忘录内容,必填++ Returns:+ 包含创建结果的响应字典+ """+ try:+ logger.info(f"[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(备忘录内容)")++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "CreateNote",+ "bundleName": "com.huawei.hmos.notepad",+ "dimension": "",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "title": title,+ "content": content,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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}' 创建成功"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[NOTE_TOOL] Failed to create note: {e}")+ raise RuntimeError(f"创建备忘录失败: {str(e)}") from e+++@tool(+ name="search_notes",+ description="""在用户设备上搜索备忘录。可以通过关键词搜索标题或内容。++注意:+- 操作超时时间为60秒,请勿重复调用此工具+- 如果搜索失败,最多只能重试一次+""",+)+async def search_notes(keyword: str, max_results: int = 10) -> Dict[str, Any]:+ """搜索备忘录.++ Args:+ keyword: 搜索关键词+ max_results: 最大返回结果数,默认10++ Returns:+ 包含备忘录列表的响应字典+ """+ try:+ logger.info(f"[NOTE_TOOL] Searching notes - keyword: {keyword}")++ # 构建命令 - 与 xy_channel search-note-tool.ts 保持一致+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchNote",+ "bundleName": "com.huawei.hmos.notepad",+ "dimension": "",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "query": keyword, # xy_channel 使用 query 而非 keyword+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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)} 条备忘录"+ )++ except Exception as e:+ logger.error(f"[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秒,请勿重复调用此工具+- 如果超时或失败,最多只能重试一次+""",+)+async def modify_note(+ entity_id: str,+ text: str,+) -> Dict[str, Any]:+ """修改备忘录(追加模式).++ Args:+ entity_id: 备忘录的唯一标识符(从 search_notes 获取),必填+ text: 要追加的文本内容,必填++ Returns:+ 包含修改结果的响应字典+ """+ try:+ logger.info(f"[NOTE_TOOL] Modifying note - entity_id: {entity_id}")++ # 验证参数+ if not entity_id:+ raise ToolInputError("缺少必填参数 entity_id(备忘录ID)")+ if not text or not isinstance(text, str):+ raise ToolInputError("缺少必填参数 text(要追加的文本内容)")++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "ModifyNote",+ "bundleName": "com.huawei.hmos.notepad",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "contentType": "1", # 1 = 追加模式 (append mode)+ "text": text,+ "entityId": entity_id,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ outputs = await execute_device_command("ModifyNote", command)++ # 提取结果+ result = outputs.get("result", {})++ 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"),+ },+ "备忘录修改成功"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..eca808d239--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/phone_tools.py@@ -0,0 +1,126 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Phone tools - 电话工具.++包含:+- call_phone: 拨打电话+"""++from __future__ import annotations++from typing import Any, Dict++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="call_phone",+ description="""拨打电话。需要提供要拨打的电话号码。++参数说明:+- phoneNumber: 要拨打的电话号码(必填)+- slotId: SIM卡槽ID,默认为0(主卡),设置为1表示副卡。仅当用户明确要求使用副卡时才设置为1++注意:+- 操作超时时间为60秒,请勿重复调用此工具+- 如果超时或失败,最多重试一次+""",+)+async def call_phone(phone_number: str, slot_id: int = 0) -> Dict[str, Any]:+ """拨打电话.++ Args:+ phone_number: 要拨打的电话号码,必填+ slot_id: SIM卡槽ID,0=主卡(默认),1=副卡++ Returns:+ 包含拨打结果的响应字典+ """+ try:+ logger.info(f"[PHONE_TOOL] Calling phone number - phone_number: {phone_number}, slot_id: {slot_id}")++ # 验证参数+ if not phone_number or not isinstance(phone_number, str):+ raise ToolInputError("缺少必填参数 phoneNumber(电话号码)")++ phone_number = phone_number.strip()+ if not phone_number:+ raise ToolInputError("phoneNumber 不能为空")++ # 验证 slot_id+ if slot_id not in [0, 1]:+ raise ToolInputError("slotId 必须是 0(主卡)或 1(副卡)")++ # 构建命令 - 与 xy_channel 保持一致+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "StartCall",+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "dimension": "",+ "needUnlock": True,+ "actionResponse": True,+ "timeOut": 5,+ "intentParam": {+ "phoneNumber": phone_number,+ "slotId": slot_id,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ 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})")++ result = outputs.get("result", {})++ sim_name = "主卡" if slot_id == 0 else "副卡"+ logger.info(f"[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"),+ },+ f"正在使用{sim_name}拨打 {phone_number}..."+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..b2e2f9ba9a--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/photo_tools.py@@ -0,0 +1,237 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Photo tools - 相册工具.++包含:+- search_photos: 搜索照片+- upload_photos: 上传照片+"""++from __future__ import annotations++import json+from typing import Any, Dict, List, Optional++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@tool(+ name="search_photo_gallery",+ description="""搜索用户手机图库中的照片。++根据图像描述语料检索匹配的照片,返回照片在手机本地的 mediaUri 以及 thumbnailUri。+注意:返回的 mediaUri 和 thumbnailUri 是本地路径,无法直接下载或访问。如果需要下载、查看、使用或展示照片,请使用 upload_photos 工具将 mediaUri 或 thumbnailUri 转换为可访问的公网 URL。+- mediaUri 代表手机相册中的图片原图路径,图片大小比较大,清晰度比较高+- thumbnailUri 代表手机相册中的图片缩略图路径,图片大小比较小,清晰度适中,建议在 upload_photos 工具的入参中优先使用此路径,不容易引起上传超时等问题++参数说明:+- query: 图像描述语料,用于检索匹配的照片(例如:'小狗的照片'、'带有键盘的图片'等)++注意:+- 只有当用户明确表达从手机相册搜索或者从图库搜索时才执行此工具+- 操作超时时间为60秒,请勿重复调用,如果超时或失败,最多重试一次+""",+)+async def search_photo_gallery(+ query: str,+) -> Dict[str, Any]:+ """搜索照片.++ Args:+ query: 图像描述语料,用于检索匹配的照片++ Returns:+ 包含照片列表的响应字典+ """+ try:+ logger.info(f"[PHOTO_TOOL] Searching photos - query: {query}")++ # 验证参数+ if not query:+ raise ToolInputError("缺少必填参数 query(搜索关键词)")++ # 构建命令 - 与 xy_channel search-photo-gallery-tool.ts 保持一致+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "SearchPhotoVideo", # 注意:xy_channel 使用 SearchPhotoVideo+ "bundleName": "com.huawei.hmos.aidispatchservice",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {+ "query": query,+ },+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ outputs = await execute_device_command("SearchPhotoVideo", command)++ # 提取结果(与 xy_channel 一致)+ result = outputs.get("result", {})+ items = result.get("items", []) if isinstance(result, dict) else []++ logger.info(f"[PHOTO_TOOL] Found {len(items)} photos")++ return format_success_response(+ {+ "items": items,+ "count": len(items),+ "message": f"找到 {len(items)} 张照片。注意:mediaUri 和 thumbnailUri 是本地路径,无法直接访问。"+ f"如需下载或查看,请使用 upload_photos 工具。"+ },+ f"搜索到 {len(items)} 张照片"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[PHOTO_TOOL] Failed to search photos: {e}")+ raise RuntimeError(f"搜索照片失败: {str(e)}") from e+++@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 的形式返回给用户+""",+)+async def upload_photo(media_uris: List[str]) -> Dict[str, Any]:+ """上传照片.++ Args:+ media_uris: 照片媒体URI列表,每次最多3个(建议优先使用 thumbnailUri)++ Returns:+ 包含上传URL的响应字典+ """+ 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]++ # 构建命令+ command = {+ "header": {+ "namespace": "Common",+ "name": "Action",+ },+ "payload": {+ "cardParam": {},+ "executeParam": {+ "executeMode": "background",+ "intentName": "ImageUploadForClaw",+ "bundleName": "com.huawei.hmos.vassistant",+ "needUnlock": True,+ "actionResponse": True,+ "appType": "OHOS_APP",+ "timeOut": 5,+ "intentParam": {"imageInfos": image_infos},+ "permissionId": [],+ "achieveType": "INTENT",+ },+ "responses": [{"resultCode": "", "displayText": "", "ttsText": ""}],+ "needUploadResult": True,+ "noHalfPage": False,+ "pageControlRelated": False,+ },+ }++ # 执行命令+ outputs = await execute_device_command("ImageUploadForClaw", command)++ # 提取结果+ result = outputs.get("result", {})+ image_urls = result.get("imageUrls", []) if isinstance(result, dict) else []++ # 解码 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}")++ 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)} 张照片"+ )++ except ToolInputError:+ raise+ except Exception as e:+ logger.error(f"[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.pynew file mode 100644index 0000000000..f3d16a44d4--- /dev/null+++ b/jiuwenclaw/agentserver/tools/xiaoyi_phone_tools/send_message_tool.py@@ -0,0 +1,138 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Send Message tool - 发送短信工具.++包含:+- send_message: 通过手机发送短信+"""++from __future__ import annotations++from typing import Any, Dict++from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.utils import logger+from .base import (+ execute_device_command,+ format_success_response,+ ToolInputError,+)+++@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/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex e97c7787d9..6e92c3e0a1 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -14,7 +14,7 @@ import osimport sslimport timefrom dataclasses import dataclass-from typing import Any, Callable, Optional+from typing import Any, Callable, List, Optionalfrom urllib.parse import urlparseimport aiohttp@@ -25,6 +25,25 @@ from jiuwenclaw.schema.message import EventType, Message, ReqMethodfrom jiuwenclaw.channel.xiaoyi_utils.push import XiaoYiPushService, PushConfig+# 全局 XiaoyiChannel 实例引用(供手机端工具调用使用)+_xiaoyi_channel_instance: Optional["XiaoyiChannel"] = None+++def get_xiaoyi_channel() -> Optional["XiaoyiChannel"]:+ """获取全局 XiaoyiChannel 实例(供手机端工具调用使用)."""+ return _xiaoyi_channel_instance+++@dataclass+class DataEvent:+ """Data-only 事件数据结构(工具执行结果)."""+ intent_name: str+ outputs: dict+ status: str+ session_id: str = ""+ task_id: str = ""++@dataclassclass XiaoyiChannelConfig:"""小艺通道配置(客户端模式)."""@@ -209,6 +228,8 @@ class XiaoyiChannel(BaseChannel):self.api_id = config.api_idself.push_id = config.push_idself._accumulated_texts: dict[str, str] = {} # Accumulated text per session for push notification+ # Data-event 处理器:intent_name -> list of handlers+ self._data_event_handlers: dict[str, List[Callable[[DataEvent], Any]]] = {}@propertydef channel_id(self) -> str:@@ -234,6 +255,11 @@ class XiaoyiChannel(BaseChannel):returnself._running = True+ # 注册全局实例(供 tools 使用)+ global _xiaoyi_channel_instance+ _xiaoyi_channel_instance = self+ logger.info("XiaoyiChannel 已注册为全局实例")+# Start dual channel connectionsfor url_key, url in [("ws_url1", self.config.ws_url1), ("ws_url2", self.config.ws_url2)]:if url:@@ -241,7 +267,13 @@ class XiaoyiChannel(BaseChannel):logger.info("XiaoyiChannel 已启动(客户端模式,双通道)")async def stop(self) -> None:+ global _xiaoyi_channel_instance+self._running = False+ # 注销全局实例+ if _xiaoyi_channel_instance is self:+ _xiaoyi_channel_instance = None+ logger.info("XiaoyiChannel 已注销全局实例")# Cancel all heartbeat tasksfor url_key in list(self._heartbeat_tasks.keys()):if self._heartbeat_tasks[url_key]:@@ -535,9 +567,23 @@ class XiaoyiChannel(BaseChannel):returnmsg_type = message.get("msgType")+ method = message.get("method")++ # 添加详细日志用于诊断工具消息+ if method or (msg_type and msg_type != "heartbeat"):+ logger.info(f"[XiaoyiChannel] _handle_raw_message: msg_type={msg_type},"+ f"method={method}, sessionId={message.get('sessionId', 'N/A')}")+if msg_type == "heartbeat":return+ # 检查是否是 data-only 消息(工具执行结果)+ data_event = self._extract_data_event(message)+ if data_event:+ logger.info(f"XiaoyiChannel 收到 data-event: {data_event.intent_name}, status={data_event.status}")+ await self._handle_data_event(data_event)+ return+method = message.get("method")if method == "message/stream":await self._handle_message_stream(message)@@ -679,7 +725,7 @@ class XiaoyiChannel(BaseChannel):logger.info(f"[TASK TIMEOUT] 1-hour timeout triggered for session {session_id}")# Send default message with is_final=truefor url_key in list(self._ws_connections.keys()):- await self._send_text_response(session_id, task_id, "任务还在处理中,完成后将提醒您~", url_key, is_final=True)+ await self._send_text_response(session_id, task_id, "任务还在处理中~", url_key, is_final=True)# Mark session as waiting for push stateself._mark_session_waiting_for_push(session_id, task_id)except asyncio.CancelledError:@@ -1046,3 +1092,203 @@ class XiaoyiChannel(BaseChannel):except Exception as e:logger.error(f"[PUSH] Error sending push: {e}")return False++ async def send_xiaoyi_phone_tools_command(+ self,+ session_id: str,+ task_id: str,+ message_id: str,+ command: dict[str, Any],+ ) -> bool:+ """发送 Command 指令到手机端(A2A artifact-update 格式).++ Args:+ session_id: 会话 ID+ task_id: 任务 ID+ message_id: 消息 ID(用于 JSON-RPC id)+ command: Command 数据结构,包含 header 和 payload++ Returns:+ 是否发送成功+ """+ # 构建 A2A artifact-update 响应+ response = {+ "jsonrpc": "2.0",+ "id": message_id,+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": False,+ "final": False,+ "artifact": {+ "artifactId": f"artifact_{int(time.time() * 1000)}",+ "parts": [{"kind": "data", "data": {"commands": [command]}}],+ },+ },+ }++ # 构建 WebSocket 包装消息+ wrapper = {+ "msgType": "agent_response",+ "agentId": self.config.agent_id,+ "sessionId": session_id,+ "taskId": task_id,+ "msgDetail": json.dumps(response),+ }++ # 发送到所有活跃连接+ sent = False+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._safe_ws_send(url_key, wrapper)+ logger.info(f"XiaoyiChannel 发送 command 成功 ({url_key}):intent={command.get('payload', {})+ .get('executeParam', {}).get('intentName', 'unknown')}")+ sent = True+ except Exception as e:+ logger.warning(f"XiaoyiChannel 发送 command 失败 ({url_key}): {e}")++ return sent++ def register_data_event_handler(+ self, intent_name: str, handler: Callable[[DataEvent], Any]+ ) -> None:+ """注册 data-event 处理器.++ Args:+ intent_name: 要监听的 intent 名称(如 "GetCurrentLocation")+ handler: 处理函数,接收 DataEvent 参数+ """+ if intent_name not in self._data_event_handlers:+ self._data_event_handlers[intent_name] = []+ if handler not in self._data_event_handlers[intent_name]:+ self._data_event_handlers[intent_name].append(handler)+ logger.info(f"XiaoyiChannel 注册 data-event 处理器: {intent_name}")++ def unregister_data_event_handler(+ self, intent_name: str, handler: Callable[[DataEvent], Any]+ ) -> None:+ """注销 data-event 处理器.++ Args:+ intent_name: intent 名称+ handler: 要移除的处理函数+ """+ if intent_name in self._data_event_handlers:+ try:+ self._data_event_handlers[intent_name].remove(handler)+ logger.info(f"XiaoyiChannel 注销 data-event 处理器: {intent_name}")+ except ValueError:+ pass++ async def _handle_data_event(self, event: DataEvent) -> None:+ """分发 data-event 到注册的处理器."""+ logger.info(f"[XiaoyiChannel] 分发 data-event: intent={event.intent_name}, status={event.status}")+ logger.debug(f"[XiaoyiChannel] 已注册处理器: {list(self._data_event_handlers.keys())}")++ handlers = self._data_event_handlers.get(event.intent_name, [])+ if not handlers:+ logger.warning(f"[XiaoyiChannel] 无处理器处理 data-event: {event.intent_name}")+ return++ logger.info(f"[XiaoyiChannel] 找到 {len(handlers)} 个处理器 for {event.intent_name}")++ for handler in handlers:+ try:+ if asyncio.iscoroutinefunction(handler):+ await handler(event)+ else:+ handler(event)+ except Exception as e:+ logger.warning(f"XiaoyiChannel data-event 处理器异常 ({event.intent_name}): {e}")++ def _extract_data_event(self, message: dict[str, Any]) -> DataEvent | None:+ """从 A2A 消息中提取 data-event(如果是 data-only 消息).++ 支持三种消息格式:+ 1. Direct A2A format: 直接包含 params.message.parts+ 2. Wrapped format (msgType="data"): A2A 内容在 msgDetail 中+ 3. UploadExeResult 格式: header.name="UploadExeResult" + payload.intentName + payload.outputs++ Args:+ message: 解析后的 A2A 消息++ Returns:+ DataEvent 或 None(如果不是 data-only 消息)+ """+ # 检查是否是 Wrapped format (msgType="data")+ # 参考 xy_channel websocket.ts:569-606+ msg_type = message.get("msgType")+ method = message.get("method")+ logger.debug(f"[XiaoyiChannel] _extract_data_event: msg_type={msg_type}, method={method}")+ if msg_type == "data":+ try:+ # 从 msgDetail 解析 A2A JSON-RPC 请求+ a2a_request = json.loads(message.get("msgDetail", "{}"))+ params = a2a_request.get("params", {})+ msg = params.get("message", {})+ parts = msg.get("parts", [])+ session_id = message.get("sessionId", "")+ except (json.JSONDecodeError, KeyError):+ return None+ else:+ # Direct A2A format+ params = message.get("params", {})+ msg = params.get("message", {})+ parts = msg.get("parts", [])+ 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 内容+ for part in data_parts:+ data = part.get("data", {})+ events = data.get("events", [])+ if not isinstance(events, list):+ continue++ for event in events:+ intent_name = ""+ outputs = {}+ status = "success" # 默认为 success(与 xy_channel 一致)++ # 格式 1: 直接格式 (events[].intentName)+ if event.get("intentName"):+ intent_name = event.get("intentName", "")+ outputs = event.get("outputs", {})+ status = event.get("status", "success")++ # 格式 2: UploadExeResult 包装格式 (header.name + payload)+ elif event.get("header", {}).get("name") == "UploadExeResult":+ payload = event.get("payload", {})+ intent_name = payload.get("intentName", "")+ outputs = payload.get("outputs", {})+ # UploadExeResult 格式默认 status 为 success+ status = payload.get("status", "success") or "success"++ # 格式 3: InvokeJarvisGUIAgentResponse(GUI 工具响应,跳过)+ elif event.get("header", {}).get("namespace") == "ClawAgent" and \+ event.get("header", {}).get("name") == "InvokeJarvisGUIAgentResponse":+ # GUI 响应不处理,继续检查下一个 event+ continue++ if intent_name:+ logger.info(f"[XiaoyiChannel] Extracted data-event: intent={intent_name}, status={status}, outputs_keys={list(outputs.keys())}")+ return DataEvent(+ intent_name=intent_name,+ outputs=outputs,+ status=status,+ session_id=message.get("sessionId", ""),+ task_id=params.get("id", ""),+ )++ return Nonediff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 18e80f9017..992f9ee56b 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -122,6 +122,8 @@ channels:api_key:push_url:file_upload_url:+ # 小艺手机端插件tools调用,会添加相关tools到系统提示词+ phone_tools_enabled: falsedingtalk:# 钉钉应用配置client_id: