@ynhcj/xiaoyi-channel 0.0.2 → 0.0.3-next

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/src/bot.js +115 -35
  2. package/dist/src/channel.js +22 -1
  3. package/dist/src/client.d.ts +15 -0
  4. package/dist/src/client.js +97 -2
  5. package/dist/src/file-download.js +10 -1
  6. package/dist/src/file-upload.js +1 -1
  7. package/dist/src/formatter.d.ts +17 -0
  8. package/dist/src/formatter.js +86 -6
  9. package/dist/src/heartbeat.d.ts +2 -1
  10. package/dist/src/heartbeat.js +9 -1
  11. package/dist/src/monitor.d.ts +5 -0
  12. package/dist/src/monitor.js +131 -25
  13. package/dist/src/onboarding.js +7 -7
  14. package/dist/src/outbound.js +150 -71
  15. package/dist/src/parser.d.ts +5 -0
  16. package/dist/src/parser.js +15 -0
  17. package/dist/src/push.d.ts +7 -1
  18. package/dist/src/push.js +110 -19
  19. package/dist/src/reply-dispatcher.d.ts +1 -0
  20. package/dist/src/reply-dispatcher.js +210 -57
  21. package/dist/src/task-manager.d.ts +55 -0
  22. package/dist/src/task-manager.js +136 -0
  23. package/dist/src/tools/calendar-tool.d.ts +6 -0
  24. package/dist/src/tools/calendar-tool.js +167 -0
  25. package/dist/src/tools/call-phone-tool.d.ts +5 -0
  26. package/dist/src/tools/call-phone-tool.js +183 -0
  27. package/dist/src/tools/create-alarm-tool.d.ts +7 -0
  28. package/dist/src/tools/create-alarm-tool.js +444 -0
  29. package/dist/src/tools/delete-alarm-tool.d.ts +11 -0
  30. package/dist/src/tools/delete-alarm-tool.js +238 -0
  31. package/dist/src/tools/location-tool.js +48 -9
  32. package/dist/src/tools/modify-alarm-tool.d.ts +9 -0
  33. package/dist/src/tools/modify-alarm-tool.js +474 -0
  34. package/dist/src/tools/modify-note-tool.d.ts +9 -0
  35. package/dist/src/tools/modify-note-tool.js +163 -0
  36. package/dist/src/tools/note-tool.d.ts +5 -0
  37. package/dist/src/tools/note-tool.js +146 -0
  38. package/dist/src/tools/search-alarm-tool.d.ts +8 -0
  39. package/dist/src/tools/search-alarm-tool.js +389 -0
  40. package/dist/src/tools/search-calendar-tool.d.ts +12 -0
  41. package/dist/src/tools/search-calendar-tool.js +259 -0
  42. package/dist/src/tools/search-contact-tool.d.ts +5 -0
  43. package/dist/src/tools/search-contact-tool.js +168 -0
  44. package/dist/src/tools/search-file-tool.d.ts +5 -0
  45. package/dist/src/tools/search-file-tool.js +185 -0
  46. package/dist/src/tools/search-message-tool.d.ts +5 -0
  47. package/dist/src/tools/search-message-tool.js +173 -0
  48. package/dist/src/tools/search-note-tool.d.ts +5 -0
  49. package/dist/src/tools/search-note-tool.js +130 -0
  50. package/dist/src/tools/search-photo-gallery-tool.d.ts +8 -0
  51. package/dist/src/tools/search-photo-gallery-tool.js +184 -0
  52. package/dist/src/tools/search-photo-tool.d.ts +9 -0
  53. package/dist/src/tools/search-photo-tool.js +270 -0
  54. package/dist/src/tools/send-file-to-user-tool.d.ts +5 -0
  55. package/dist/src/tools/send-file-to-user-tool.js +318 -0
  56. package/dist/src/tools/send-message-tool.d.ts +5 -0
  57. package/dist/src/tools/send-message-tool.js +189 -0
  58. package/dist/src/tools/session-manager.d.ts +15 -0
  59. package/dist/src/tools/session-manager.js +126 -6
  60. package/dist/src/tools/upload-file-tool.d.ts +13 -0
  61. package/dist/src/tools/upload-file-tool.js +265 -0
  62. package/dist/src/tools/upload-photo-tool.d.ts +9 -0
  63. package/dist/src/tools/upload-photo-tool.js +223 -0
  64. package/dist/src/tools/xiaoyi-gui-tool.d.ts +6 -0
  65. package/dist/src/tools/xiaoyi-gui-tool.js +151 -0
  66. package/dist/src/types.d.ts +5 -9
  67. package/dist/src/utils/config-manager.d.ts +26 -0
  68. package/dist/src/utils/config-manager.js +56 -0
  69. package/dist/src/websocket.d.ts +41 -0
  70. package/dist/src/websocket.js +192 -9
  71. package/package.json +1 -2
@@ -0,0 +1,146 @@
1
+ import { getXYWebSocketManager } from "../client.js";
2
+ import { sendCommand } from "../formatter.js";
3
+ import { getCurrentSessionContext } from "./session-manager.js";
4
+ import { logger } from "../utils/logger.js";
5
+ /**
6
+ * Duck-typed ToolInputError: openclaw 按 .name 字段匹配,不用 instanceof。
7
+ * 抛出此错误会让 openclaw 返回 HTTP 400 而非 500,
8
+ * LLM 会将其识别为参数错误而非瞬时故障,不会触发重试。
9
+ */
10
+ class ToolInputError extends Error {
11
+ status = 400;
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "ToolInputError";
15
+ }
16
+ }
17
+ /**
18
+ * XY note tool - creates a note on user's device.
19
+ * Requires title and content parameters.
20
+ */
21
+ export const noteTool = {
22
+ name: "create_note",
23
+ label: "Create Note",
24
+ description: "在用户设备上创建备忘录。需要提供备忘录标题和内容。注意:操作超时时间为60秒,请勿重复调用此工具,如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。",
25
+ parameters: {
26
+ type: "object",
27
+ properties: {
28
+ title: {
29
+ type: "string",
30
+ description: "备忘录标题",
31
+ },
32
+ content: {
33
+ type: "string",
34
+ description: "备忘录内容",
35
+ },
36
+ },
37
+ required: ["title", "content"],
38
+ },
39
+ async execute(toolCallId, params) {
40
+ logger.debug("Executing note tool, toolCallId:", toolCallId);
41
+ // Validate parameters — 抛 ToolInputError 而非普通 Error,
42
+ // 让 openclaw 返回 400 而非 500,明确告知 LLM 这是参数错误,不应重试。
43
+ if (typeof params.title !== "string" || !params.title) {
44
+ throw new ToolInputError("缺少必填参数 title(备忘录标题)");
45
+ }
46
+ if (typeof params.content !== "string" || !params.content) {
47
+ throw new ToolInputError("缺少必填参数 content(备忘录内容)");
48
+ }
49
+ // Get session context
50
+ const sessionContext = getCurrentSessionContext();
51
+ if (!sessionContext) {
52
+ throw new Error("No active XY session found. Note tool can only be used during an active conversation.");
53
+ }
54
+ const { config, sessionId, taskId, messageId } = sessionContext;
55
+ // Get WebSocket manager
56
+ const wsManager = getXYWebSocketManager(config);
57
+ // Build CreateNote command
58
+ const command = {
59
+ header: {
60
+ namespace: "Common",
61
+ name: "Action",
62
+ },
63
+ payload: {
64
+ cardParam: {},
65
+ executeParam: {
66
+ executeMode: "background",
67
+ intentName: "CreateNote",
68
+ bundleName: "com.huawei.hmos.notepad",
69
+ dimension: "",
70
+ needUnlock: true,
71
+ actionResponse: true,
72
+ timeOut: 5,
73
+ intentParam: {
74
+ title: params.title,
75
+ content: params.content,
76
+ },
77
+ achieveType: "INTENT",
78
+ },
79
+ responses: [
80
+ {
81
+ resultCode: "",
82
+ displayText: "",
83
+ ttsText: "",
84
+ },
85
+ ],
86
+ needUploadResult: true,
87
+ noHalfPage: false,
88
+ pageControlRelated: false,
89
+ },
90
+ };
91
+ // Send command and wait for response (60 second timeout)
92
+ return new Promise((resolve, reject) => {
93
+ const timeout = setTimeout(() => {
94
+ wsManager.off("data-event", handler);
95
+ reject(new Error("创建备忘录超时(60秒)"));
96
+ }, 60000);
97
+ // Listen for data events from WebSocket
98
+ const handler = (event) => {
99
+ logger.debug("Received data event:", event);
100
+ if (event.intentName === "CreateNote") {
101
+ clearTimeout(timeout);
102
+ wsManager.off("data-event", handler);
103
+ if (event.status === "success" && event.outputs) {
104
+ const { result, code } = event.outputs;
105
+ logger.log(`Note created: title=${result?.title}, id=${result?.entityId}`);
106
+ resolve({
107
+ content: [
108
+ {
109
+ type: "text",
110
+ text: JSON.stringify({
111
+ success: true,
112
+ note: {
113
+ entityId: result?.entityId,
114
+ title: result?.title,
115
+ content: result?.content,
116
+ entityName: result?.entityName,
117
+ modifiedDate: result?.modifiedDate,
118
+ },
119
+ code,
120
+ }),
121
+ },
122
+ ],
123
+ });
124
+ }
125
+ else {
126
+ reject(new Error(`创建备忘录失败: ${event.status}`));
127
+ }
128
+ }
129
+ };
130
+ // Register event handler
131
+ wsManager.on("data-event", handler);
132
+ // Send the command
133
+ sendCommand({
134
+ config,
135
+ sessionId,
136
+ taskId,
137
+ messageId,
138
+ command,
139
+ }).catch((error) => {
140
+ clearTimeout(timeout);
141
+ wsManager.off("data-event", handler);
142
+ reject(error);
143
+ });
144
+ });
145
+ },
146
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * XY search alarm tool - searches alarms on user's device.
3
+ * Returns matching alarms based on various filter criteria.
4
+ *
5
+ * At least one search criterion must be provided.
6
+ * Multiple criteria can be combined.
7
+ */
8
+ export declare const searchAlarmTool: any;
@@ -0,0 +1,389 @@
1
+ import { getXYWebSocketManager } from "../client.js";
2
+ import { sendCommand } from "../formatter.js";
3
+ import { getCurrentSessionContext } from "./session-manager.js";
4
+ import { logger } from "../utils/logger.js";
5
+ // Enum definitions for alarm search parameters
6
+ const RANGE_TYPE_VALUES = ["all", "next", "current"];
7
+ const ALARM_STATE_VALUES = [0, 1];
8
+ const DAYS_OF_WAKE_TYPE_VALUES = [0, 1, 2, 3, 4];
9
+ /**
10
+ * XY search alarm tool - searches alarms on user's device.
11
+ * Returns matching alarms based on various filter criteria.
12
+ *
13
+ * At least one search criterion must be provided.
14
+ * Multiple criteria can be combined.
15
+ */
16
+ export const searchAlarmTool = {
17
+ name: "search_alarm",
18
+ label: "Search Alarm",
19
+ description: `检索用户设备上的闹钟。支持多种检索条件,至少需要提供一个检索条件,多个条件可以组合使用。
20
+
21
+ 检索条件(至少提供一个):
22
+ - rangeType: 查询范围,枚举值:all=查询所有闹钟,next=查找下一个响铃闹钟,current=一小时内最近一次增查改的闹钟
23
+ - alarmState: 闹钟开启状态,0=关闭,1=开启
24
+ - daysOfWakeType: 闹钟响铃类型,0=单次响铃,1=法定节假日,2=每天,3=自定义时间,4=法定工作日
25
+ - startTime: 时间间隔开始,格式 YYYYMMDD hhmmss(例如:20240315 000000),需要与 endTime 一起使用
26
+ - endTime: 时间间隔结束,格式 YYYYMMDD hhmmss(例如:20240315 235959),需要与 startTime 一起使用
27
+
28
+ 使用示例:
29
+ - 查询所有闹钟:{"rangeType": "all"}
30
+ - 查询已开启的闹钟:{"alarmState": 1}
31
+ - 查询每天响铃的闹钟:{"daysOfWakeType": 2}
32
+ - 查询某个时间段的闹钟:{"startTime": "20240315 000000", "endTime": "20240315 235959"}
33
+
34
+ 注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。`,
35
+ parameters: {
36
+ type: "object",
37
+ properties: {
38
+ rangeType: {
39
+ type: "string",
40
+ enum: ["all", "next", "current"],
41
+ description: "查询范围:all=所有闹钟,next=下一个响铃闹钟,current=一小时内最近修改的闹钟",
42
+ },
43
+ alarmState: {
44
+ type: "number",
45
+ enum: [0, 1],
46
+ description: "闹钟开启状态:0=关闭,1=开启",
47
+ },
48
+ daysOfWakeType: {
49
+ type: "number",
50
+ enum: [0, 1, 2, 3, 4],
51
+ description: "闹钟响铃类型:0=单次,1=法定节假日,2=每天,3=自定义,4=法定工作日",
52
+ },
53
+ startTime: {
54
+ type: "string",
55
+ description: "时间间隔开始,格式 YYYYMMDD hhmmss(例如:20240315 000000),必须与 endTime 一起使用",
56
+ },
57
+ endTime: {
58
+ type: "string",
59
+ description: "时间间隔结束,格式 YYYYMMDD hhmmss(例如:20240315 235959),必须与 startTime 一起使用",
60
+ },
61
+ },
62
+ },
63
+ async execute(toolCallId, params) {
64
+ logger.log(`[SEARCH_ALARM_TOOL] 🚀 Starting execution`);
65
+ logger.log(`[SEARCH_ALARM_TOOL] - toolCallId: ${toolCallId}`);
66
+ logger.log(`[SEARCH_ALARM_TOOL] - params:`, JSON.stringify(params));
67
+ logger.log(`[SEARCH_ALARM_TOOL] - timestamp: ${new Date().toISOString()}`);
68
+ // ===== Validate at least one search criterion is provided =====
69
+ const hasRangeType = params.rangeType !== undefined && params.rangeType !== null;
70
+ const hasAlarmState = params.alarmState !== undefined && params.alarmState !== null;
71
+ const hasDaysOfWakeType = params.daysOfWakeType !== undefined && params.daysOfWakeType !== null;
72
+ const hasStartTime = params.startTime !== undefined && params.startTime !== null;
73
+ const hasEndTime = params.endTime !== undefined && params.endTime !== null;
74
+ if (!hasRangeType && !hasAlarmState && !hasDaysOfWakeType && !hasStartTime && !hasEndTime) {
75
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ No search criteria provided`);
76
+ throw new Error("至少需要提供一个检索条件:rangeType、alarmState、daysOfWakeType 或时间范围(startTime + endTime)");
77
+ }
78
+ // ===== Validate rangeType =====
79
+ if (hasRangeType) {
80
+ if (typeof params.rangeType !== "string") {
81
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid rangeType type`);
82
+ throw new Error("rangeType must be a string");
83
+ }
84
+ if (!RANGE_TYPE_VALUES.includes(params.rangeType)) {
85
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid rangeType value: ${params.rangeType}`);
86
+ throw new Error(`rangeType must be one of: ${RANGE_TYPE_VALUES.join(", ")}`);
87
+ }
88
+ logger.log(`[SEARCH_ALARM_TOOL] - rangeType: ${params.rangeType}`);
89
+ }
90
+ // ===== Validate alarmState =====
91
+ if (hasAlarmState) {
92
+ if (typeof params.alarmState !== "number") {
93
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid alarmState type`);
94
+ throw new Error("alarmState must be a number");
95
+ }
96
+ if (!ALARM_STATE_VALUES.includes(params.alarmState)) {
97
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid alarmState value: ${params.alarmState}`);
98
+ throw new Error(`alarmState must be one of: ${ALARM_STATE_VALUES.join(", ")}`);
99
+ }
100
+ logger.log(`[SEARCH_ALARM_TOOL] - alarmState: ${params.alarmState}`);
101
+ }
102
+ // ===== Validate daysOfWakeType =====
103
+ if (hasDaysOfWakeType) {
104
+ if (typeof params.daysOfWakeType !== "number") {
105
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid daysOfWakeType type`);
106
+ throw new Error("daysOfWakeType must be a number");
107
+ }
108
+ if (!DAYS_OF_WAKE_TYPE_VALUES.includes(params.daysOfWakeType)) {
109
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid daysOfWakeType value: ${params.daysOfWakeType}`);
110
+ throw new Error(`daysOfWakeType must be one of: ${DAYS_OF_WAKE_TYPE_VALUES.join(", ")}`);
111
+ }
112
+ logger.log(`[SEARCH_ALARM_TOOL] - daysOfWakeType: ${params.daysOfWakeType}`);
113
+ }
114
+ // ===== Validate time interval (startTime and endTime must be provided together) =====
115
+ if (hasStartTime !== hasEndTime) {
116
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ startTime and endTime must be provided together`);
117
+ throw new Error("startTime 和 endTime 必须一起提供");
118
+ }
119
+ let timeInterval = null;
120
+ if (hasStartTime && hasEndTime) {
121
+ // Parse and convert startTime and endTime to timestamps
122
+ logger.log(`[SEARCH_ALARM_TOOL] 🕒 Parsing time interval...`);
123
+ logger.log(`[SEARCH_ALARM_TOOL] - startTime input: ${params.startTime}`);
124
+ logger.log(`[SEARCH_ALARM_TOOL] - endTime input: ${params.endTime}`);
125
+ const startTimeMs = parseAlarmTimeToTimestamp(params.startTime);
126
+ const endTimeMs = parseAlarmTimeToTimestamp(params.endTime);
127
+ if (startTimeMs === null) {
128
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid startTime format`);
129
+ throw new Error("Invalid startTime format. Required format: YYYYMMDD hhmmss (e.g., 20240315 000000)");
130
+ }
131
+ if (endTimeMs === null) {
132
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid endTime format`);
133
+ throw new Error("Invalid endTime format. Required format: YYYYMMDD hhmmss (e.g., 20240315 235959)");
134
+ }
135
+ if (startTimeMs >= endTimeMs) {
136
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ startTime must be before endTime`);
137
+ throw new Error("startTime 必须早于 endTime");
138
+ }
139
+ timeInterval = [startTimeMs, endTimeMs];
140
+ logger.log(`[SEARCH_ALARM_TOOL] ✅ Time interval parsed: [${startTimeMs}, ${endTimeMs}]`);
141
+ }
142
+ // Get session context
143
+ logger.log(`[SEARCH_ALARM_TOOL] 🔍 Attempting to get session context...`);
144
+ const sessionContext = getCurrentSessionContext();
145
+ if (!sessionContext) {
146
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ FAILED: No active session found!`);
147
+ logger.error(`[SEARCH_ALARM_TOOL] - toolCallId: ${toolCallId}`);
148
+ throw new Error("No active XY session found. Search alarm tool can only be used during an active conversation.");
149
+ }
150
+ logger.log(`[SEARCH_ALARM_TOOL] ✅ Session context found`);
151
+ logger.log(`[SEARCH_ALARM_TOOL] - sessionId: ${sessionContext.sessionId}`);
152
+ logger.log(`[SEARCH_ALARM_TOOL] - taskId: ${sessionContext.taskId}`);
153
+ logger.log(`[SEARCH_ALARM_TOOL] - messageId: ${sessionContext.messageId}`);
154
+ const { config, sessionId, taskId, messageId } = sessionContext;
155
+ // Get WebSocket manager
156
+ logger.log(`[SEARCH_ALARM_TOOL] 🔌 Getting WebSocket manager...`);
157
+ const wsManager = getXYWebSocketManager(config);
158
+ logger.log(`[SEARCH_ALARM_TOOL] ✅ WebSocket manager obtained`);
159
+ // Build SearchAlarm command
160
+ logger.log(`[SEARCH_ALARM_TOOL] 📦 Building SearchAlarm command...`);
161
+ // Build intentParam with provided search criteria
162
+ const intentParam = {};
163
+ if (hasRangeType) {
164
+ intentParam.rangeType = params.rangeType;
165
+ }
166
+ if (hasAlarmState) {
167
+ intentParam.alarmState = params.alarmState;
168
+ }
169
+ if (hasDaysOfWakeType) {
170
+ intentParam.daysOfWakeType = params.daysOfWakeType;
171
+ }
172
+ if (timeInterval) {
173
+ intentParam.timeInterval = timeInterval;
174
+ }
175
+ const command = {
176
+ header: {
177
+ namespace: "Common",
178
+ name: "Action",
179
+ },
180
+ payload: {
181
+ cardParam: {},
182
+ executeParam: {
183
+ executeMode: "background",
184
+ intentName: "SearchAlarm",
185
+ bundleName: "com.huawei.hmos.clock",
186
+ needUnlock: true,
187
+ actionResponse: true,
188
+ appType: "OHOS_APP",
189
+ timeOut: 5,
190
+ intentParam,
191
+ permissionId: [],
192
+ achieveType: "INTENT",
193
+ },
194
+ responses: [
195
+ {
196
+ resultCode: "",
197
+ displayText: "",
198
+ ttsText: "",
199
+ },
200
+ ],
201
+ needUploadResult: true,
202
+ noHalfPage: false,
203
+ pageControlRelated: false,
204
+ },
205
+ };
206
+ // Send command and wait for response (60 second timeout)
207
+ logger.log(`[SEARCH_ALARM_TOOL] ⏳ Setting up promise to wait for alarm search response...`);
208
+ logger.log(`[SEARCH_ALARM_TOOL] - Timeout: 60 seconds`);
209
+ return new Promise((resolve, reject) => {
210
+ const timeout = setTimeout(() => {
211
+ logger.error(`[SEARCH_ALARM_TOOL] ⏰ Timeout: No response received within 60 seconds`);
212
+ wsManager.off("data-event", handler);
213
+ reject(new Error("检索闹钟超时(60秒)"));
214
+ }, 60000);
215
+ // Listen for data events from WebSocket
216
+ const handler = (event) => {
217
+ logger.log(`[SEARCH_ALARM_TOOL] 📨 Received data event:`, JSON.stringify(event));
218
+ if (event.intentName === "SearchAlarm") {
219
+ logger.log(`[SEARCH_ALARM_TOOL] 🎯 SearchAlarm event received`);
220
+ logger.log(`[SEARCH_ALARM_TOOL] - status: ${event.status}`);
221
+ clearTimeout(timeout);
222
+ wsManager.off("data-event", handler);
223
+ if (event.status === "success" && event.outputs) {
224
+ logger.log(`[SEARCH_ALARM_TOOL] ✅ Alarm search completed successfully`);
225
+ logger.log(`[SEARCH_ALARM_TOOL] - outputs:`, JSON.stringify(event.outputs));
226
+ // Check for error code in outputs
227
+ const code = event.outputs.code !== undefined ? event.outputs.code : null;
228
+ if (code !== null && code !== 0) {
229
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Device returned error`);
230
+ logger.error(`[SEARCH_ALARM_TOOL] - code: ${code}`);
231
+ const errorMsg = event.outputs.errorMsg || event.outputs.errMsg || "未知错误";
232
+ logger.error(`[SEARCH_ALARM_TOOL] - errorMsg: ${errorMsg}`);
233
+ reject(new Error(`检索闹钟失败: ${errorMsg} (错误代码: ${code})`));
234
+ return;
235
+ }
236
+ // Extract result.items with safe checks
237
+ const result = event.outputs.result;
238
+ let items = [];
239
+ if (result && typeof result === "object" && Array.isArray(result.items)) {
240
+ items = result.items;
241
+ logger.log(`[SEARCH_ALARM_TOOL] 📋 Found ${items.length} alarm(s)`);
242
+ // Parse JSON strings in items array
243
+ // Items are returned as JSON strings that need to be parsed
244
+ const parsedItems = items.map((itemStr, index) => {
245
+ if (typeof itemStr !== "string") {
246
+ logger.warn(`[SEARCH_ALARM_TOOL] ⚠️ Item at index ${index} is not a string:`, typeof itemStr);
247
+ return null;
248
+ }
249
+ try {
250
+ const parsed = JSON.parse(itemStr);
251
+ logger.log(`[SEARCH_ALARM_TOOL] 📋 Parsed alarm [${index}]:`, JSON.stringify(parsed));
252
+ return parsed;
253
+ }
254
+ catch (parseError) {
255
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Failed to parse item at index ${index}:`, parseError);
256
+ logger.error(`[SEARCH_ALARM_TOOL] - itemStr: ${itemStr}`);
257
+ return null;
258
+ }
259
+ }).filter((item) => item !== null);
260
+ logger.log(`[SEARCH_ALARM_TOOL] 🎉 Successfully parsed ${parsedItems.length} alarm(s)`);
261
+ resolve({
262
+ content: [
263
+ {
264
+ type: "text",
265
+ text: JSON.stringify(parsedItems),
266
+ },
267
+ ],
268
+ });
269
+ }
270
+ else {
271
+ logger.warn(`[SEARCH_ALARM_TOOL] ⚠️ No items found in result or result is invalid`);
272
+ logger.warn(`[SEARCH_ALARM_TOOL] - result:`, JSON.stringify(result || {}));
273
+ // Return empty array
274
+ resolve({
275
+ content: [
276
+ {
277
+ type: "text",
278
+ text: "[]",
279
+ },
280
+ ],
281
+ });
282
+ }
283
+ }
284
+ else {
285
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Alarm search failed`);
286
+ logger.error(`[SEARCH_ALARM_TOOL] - status: ${event.status}`);
287
+ logger.error(`[SEARCH_ALARM_TOOL] - outputs:`, JSON.stringify(event.outputs || {}));
288
+ reject(new Error(`检索闹钟失败: ${event.status}`));
289
+ }
290
+ }
291
+ };
292
+ // Register event handler
293
+ logger.log(`[SEARCH_ALARM_TOOL] 📡 Registering data-event handler on WebSocket manager`);
294
+ wsManager.on("data-event", handler);
295
+ // Send the command
296
+ logger.log(`[SEARCH_ALARM_TOOL] 📤 Sending SearchAlarm command...`);
297
+ sendCommand({
298
+ config,
299
+ sessionId,
300
+ taskId,
301
+ messageId,
302
+ command,
303
+ })
304
+ .then(() => {
305
+ logger.log(`[SEARCH_ALARM_TOOL] ✅ Command sent successfully, waiting for response...`);
306
+ })
307
+ .catch((error) => {
308
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Failed to send command:`, error);
309
+ clearTimeout(timeout);
310
+ wsManager.off("data-event", handler);
311
+ reject(error);
312
+ });
313
+ });
314
+ },
315
+ };
316
+ /**
317
+ * Parse alarmTime string (YYYYMMDD hhmmss) to timestamp in milliseconds
318
+ * @param alarmTime - Time string in format "YYYYMMDD hhmmss" (e.g., "20240315 143000")
319
+ * @returns Timestamp in milliseconds, or null if parsing fails
320
+ */
321
+ function parseAlarmTimeToTimestamp(alarmTime) {
322
+ try {
323
+ // Expected format: YYYYMMDD hhmmss
324
+ // Example: 20240315 143000
325
+ const trimmed = alarmTime.trim();
326
+ // Check basic format (should have at least 13 characters: YYYYMMDD hhmmss)
327
+ if (trimmed.length < 13) {
328
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ alarmTime too short: ${trimmed}`);
329
+ return null;
330
+ }
331
+ // Extract date and time parts
332
+ // Format: YYYYMMDD hhmmss
333
+ const datePart = trimmed.substring(0, 8); // YYYYMMDD
334
+ const timePart = trimmed.substring(8).trim(); // hhmmss (may have leading space)
335
+ logger.log(`[SEARCH_ALARM_TOOL] - datePart: ${datePart}, timePart: ${timePart}`);
336
+ // Validate lengths
337
+ if (datePart.length !== 8 || timePart.length !== 6) {
338
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid part lengths: datePart=${datePart.length}, timePart=${timePart.length}`);
339
+ return null;
340
+ }
341
+ // Parse components
342
+ const year = parseInt(datePart.substring(0, 4), 10);
343
+ const month = parseInt(datePart.substring(4, 6), 10);
344
+ const day = parseInt(datePart.substring(6, 8), 10);
345
+ const hour = parseInt(timePart.substring(0, 2), 10);
346
+ const minute = parseInt(timePart.substring(2, 4), 10);
347
+ const second = parseInt(timePart.substring(4, 6), 10);
348
+ logger.log(`[SEARCH_ALARM_TOOL] - Parsed: ${year}-${month}-${day} ${hour}:${minute}:${second}`);
349
+ // Validate values
350
+ if (isNaN(year) || isNaN(month) || isNaN(day) ||
351
+ isNaN(hour) || isNaN(minute) || isNaN(second)) {
352
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ NaN detected in parsed values`);
353
+ return null;
354
+ }
355
+ // Validate ranges
356
+ if (month < 1 || month > 12) {
357
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid month: ${month}`);
358
+ return null;
359
+ }
360
+ if (day < 1 || day > 31) {
361
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid day: ${day}`);
362
+ return null;
363
+ }
364
+ if (hour < 0 || hour > 23) {
365
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid hour: ${hour}`);
366
+ return null;
367
+ }
368
+ if (minute < 0 || minute > 59) {
369
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid minute: ${minute}`);
370
+ return null;
371
+ }
372
+ if (second < 0 || second > 59) {
373
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Invalid second: ${second}`);
374
+ return null;
375
+ }
376
+ // Create Date object and get timestamp
377
+ const date = new Date(year, month - 1, day, hour, minute, second);
378
+ const timestamp = date.getTime();
379
+ if (isNaN(timestamp)) {
380
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Generated timestamp is NaN`);
381
+ return null;
382
+ }
383
+ return timestamp;
384
+ }
385
+ catch (error) {
386
+ logger.error(`[SEARCH_ALARM_TOOL] ❌ Exception in parseAlarmTimeToTimestamp:`, error);
387
+ return null;
388
+ }
389
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * XY search calendar event tool - searches calendar events on user's device.
3
+ * Returns matching events based on time range and optional title filter.
4
+ *
5
+ * Time range guidelines:
6
+ * - For a specific day: use 00:00:00 to 23:59:59 of that day
7
+ * - For morning: 06:00:00 to 12:00:00
8
+ * - For afternoon: 12:00:00 to 18:00:00
9
+ * - For evening: 18:00:00 to 24:00:00
10
+ * - For a specific time: use ±1 hour range (e.g., for 3PM, use 14:00:00 to 16:00:00)
11
+ */
12
+ export declare const searchCalendarTool: any;