@ynhcj/xiaoyi-channel 0.0.30-beta → 0.0.30-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 (75) hide show
  1. package/dist/index.d.ts +0 -2
  2. package/dist/index.js +42 -2
  3. package/dist/src/bot.js +55 -25
  4. package/dist/src/channel.js +24 -8
  5. package/dist/src/client.js +11 -27
  6. package/dist/src/config.js +2 -2
  7. package/dist/src/cspl/call-api.d.ts +3 -0
  8. package/dist/src/cspl/call-api.js +107 -0
  9. package/dist/src/cspl/config.d.ts +19 -0
  10. package/dist/src/cspl/config.js +50 -0
  11. package/dist/src/cspl/constants.d.ts +43 -0
  12. package/dist/src/cspl/constants.js +22 -0
  13. package/dist/src/cspl/utils.d.ts +10 -0
  14. package/dist/src/cspl/utils.js +57 -0
  15. package/dist/src/file-upload.d.ts +5 -0
  16. package/dist/src/file-upload.js +92 -0
  17. package/dist/src/formatter.d.ts +14 -0
  18. package/dist/src/formatter.js +49 -25
  19. package/dist/src/heartbeat.js +0 -4
  20. package/dist/src/monitor.js +12 -0
  21. package/dist/src/onboarding.d.ts +3 -4
  22. package/dist/src/onboarding.js +2 -2
  23. package/dist/src/outbound.d.ts +2 -1
  24. package/dist/src/outbound.js +122 -88
  25. package/dist/src/parser.d.ts +7 -0
  26. package/dist/src/parser.js +22 -0
  27. package/dist/src/push.d.ts +8 -1
  28. package/dist/src/push.js +30 -22
  29. package/dist/src/reply-dispatcher.js +39 -5
  30. package/dist/src/steer-injector.d.ts +16 -0
  31. package/dist/src/steer-injector.js +74 -0
  32. package/dist/src/thread-bindings.d.ts +54 -0
  33. package/dist/src/thread-bindings.js +214 -0
  34. package/dist/src/tools/calendar-tool.js +5 -38
  35. package/dist/src/tools/call-phone-tool.js +1 -42
  36. package/dist/src/tools/create-alarm-tool.js +9 -104
  37. package/dist/src/tools/delete-alarm-tool.js +5 -69
  38. package/dist/src/tools/image-reading-tool.d.ts +5 -0
  39. package/dist/src/tools/image-reading-tool.js +328 -0
  40. package/dist/src/tools/location-tool.js +6 -40
  41. package/dist/src/tools/modify-alarm-tool.js +8 -117
  42. package/dist/src/tools/modify-note-tool.js +3 -41
  43. package/dist/src/tools/note-tool.js +31 -22
  44. package/dist/src/tools/search-alarm-tool.js +14 -118
  45. package/dist/src/tools/search-calendar-tool.js +8 -82
  46. package/dist/src/tools/search-contact-tool.js +2 -55
  47. package/dist/src/tools/search-file-tool.js +4 -61
  48. package/dist/src/tools/search-message-tool.js +2 -59
  49. package/dist/src/tools/search-note-tool.js +4 -22
  50. package/dist/src/tools/search-photo-gallery-tool.js +38 -59
  51. package/dist/src/tools/send-file-to-user-tool.js +0 -39
  52. package/dist/src/tools/send-message-tool.js +5 -56
  53. package/dist/src/tools/session-manager.js +0 -45
  54. package/dist/src/tools/upload-file-tool.js +0 -49
  55. package/dist/src/tools/upload-photo-tool.js +0 -42
  56. package/dist/src/tools/view-push-result-tool.d.ts +5 -0
  57. package/dist/src/tools/view-push-result-tool.js +107 -0
  58. package/dist/src/tools/xiaoyi-collection-tool.d.ts +5 -0
  59. package/dist/src/tools/xiaoyi-collection-tool.js +112 -0
  60. package/dist/src/tools/xiaoyi-gui-tool.js +0 -34
  61. package/dist/src/trigger-handler.d.ts +22 -0
  62. package/dist/src/trigger-handler.js +59 -0
  63. package/dist/src/types.d.ts +1 -8
  64. package/dist/src/types.js +4 -0
  65. package/dist/src/utils/pushdata-manager.d.ts +28 -0
  66. package/dist/src/utils/pushdata-manager.js +171 -0
  67. package/dist/src/utils/pushid-manager.d.ts +12 -0
  68. package/dist/src/utils/pushid-manager.js +105 -0
  69. package/dist/src/websocket.d.ts +25 -31
  70. package/dist/src/websocket.js +233 -271
  71. package/package.json +2 -2
  72. package/dist/src/tools/search-photo-tool.d.ts +0 -9
  73. package/dist/src/tools/search-photo-tool.js +0 -270
  74. package/dist/src/utils/session.d.ts +0 -34
  75. package/dist/src/utils/session.js +0 -50
@@ -1,7 +1,6 @@
1
1
  import { getXYWebSocketManager } from "../client.js";
2
2
  import { sendCommand } from "../formatter.js";
3
3
  import { getCurrentSessionContext } from "./session-manager.js";
4
- import { logger } from "../utils/logger.js";
5
4
  /**
6
5
  * XY calendar event tool - creates a calendar event on user's device.
7
6
  * Requires title, dtStart (start time), and dtEnd (end time) parameters.
@@ -10,7 +9,11 @@ import { logger } from "../utils/logger.js";
10
9
  export const calendarTool = {
11
10
  name: "create_calendar_event",
12
11
  label: "Create Calendar Event",
13
- description: "在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。注意:该工具执行时间较长(最多60秒),请勿重复调用,超时或失败时最多重试一次。",
12
+ description: `在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。注意:该工具执行时间较长(最多60秒),请勿重复调用,超时或失败时最多重试一次。
13
+ 注意事项:使用该工具之前需获取当前真实时间
14
+
15
+ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。
16
+ `,
14
17
  parameters: {
15
18
  type: "object",
16
19
  properties: {
@@ -30,47 +33,25 @@ export const calendarTool = {
30
33
  required: ["title", "dtStart", "dtEnd"],
31
34
  },
32
35
  async execute(toolCallId, params) {
33
- logger.log(`[CALENDAR_TOOL] 🚀 Starting execution`);
34
- logger.log(`[CALENDAR_TOOL] - toolCallId: ${toolCallId}`);
35
- logger.log(`[CALENDAR_TOOL] - params:`, JSON.stringify(params));
36
- logger.log(`[CALENDAR_TOOL] - timestamp: ${new Date().toISOString()}`);
37
36
  // Validate parameters
38
37
  if (!params.title || !params.dtStart || !params.dtEnd) {
39
- logger.error(`[CALENDAR_TOOL] ❌ Missing required parameters`);
40
38
  throw new Error("Missing required parameters: title, dtStart, and dtEnd are required");
41
39
  }
42
40
  // Convert time strings to millisecond timestamps
43
- logger.log(`[CALENDAR_TOOL] 🕒 Converting time strings to timestamps...`);
44
- logger.log(`[CALENDAR_TOOL] - dtStart input: ${params.dtStart}`);
45
- logger.log(`[CALENDAR_TOOL] - dtEnd input: ${params.dtEnd}`);
46
41
  const dtStartMs = new Date(params.dtStart).getTime();
47
42
  const dtEndMs = new Date(params.dtEnd).getTime();
48
43
  if (isNaN(dtStartMs) || isNaN(dtEndMs)) {
49
- logger.error(`[CALENDAR_TOOL] ❌ Invalid time format`);
50
44
  throw new Error("Invalid time format. Required format: yyyy-mm-dd hh:mm:ss (e.g., 2024-01-15 14:30:00)");
51
45
  }
52
- logger.log(`[CALENDAR_TOOL] ✅ Time conversion successful`);
53
- logger.log(`[CALENDAR_TOOL] - dtStart timestamp: ${dtStartMs}`);
54
- logger.log(`[CALENDAR_TOOL] - dtEnd timestamp: ${dtEndMs}`);
55
46
  // Get session context
56
- logger.log(`[CALENDAR_TOOL] 🔍 Attempting to get session context...`);
57
47
  const sessionContext = getCurrentSessionContext();
58
48
  if (!sessionContext) {
59
- logger.error(`[CALENDAR_TOOL] ❌ FAILED: No active session found!`);
60
- logger.error(`[CALENDAR_TOOL] - toolCallId: ${toolCallId}`);
61
49
  throw new Error("No active XY session found. Calendar tool can only be used during an active conversation.");
62
50
  }
63
- logger.log(`[CALENDAR_TOOL] ✅ Session context found`);
64
- logger.log(`[CALENDAR_TOOL] - sessionId: ${sessionContext.sessionId}`);
65
- logger.log(`[CALENDAR_TOOL] - taskId: ${sessionContext.taskId}`);
66
- logger.log(`[CALENDAR_TOOL] - messageId: ${sessionContext.messageId}`);
67
51
  const { config, sessionId, taskId, messageId } = sessionContext;
68
52
  // Get WebSocket manager
69
- logger.log(`[CALENDAR_TOOL] 🔌 Getting WebSocket manager...`);
70
53
  const wsManager = getXYWebSocketManager(config);
71
- logger.log(`[CALENDAR_TOOL] ✅ WebSocket manager obtained`);
72
54
  // Build CreateCalendarEvent command
73
- logger.log(`[CALENDAR_TOOL] 📦 Building CreateCalendarEvent command...`);
74
55
  const command = {
75
56
  header: {
76
57
  namespace: "Common",
@@ -106,25 +87,17 @@ export const calendarTool = {
106
87
  },
107
88
  };
108
89
  // Send command and wait for response (60 second timeout)
109
- logger.log(`[CALENDAR_TOOL] ⏳ Setting up promise to wait for calendar event response...`);
110
- logger.log(`[CALENDAR_TOOL] - Timeout: 60 seconds`);
111
90
  return new Promise((resolve, reject) => {
112
91
  const timeout = setTimeout(() => {
113
- logger.error(`[CALENDAR_TOOL] ⏰ Timeout: No response received within 60 seconds`);
114
92
  wsManager.off("data-event", handler);
115
93
  reject(new Error("创建日程超时(60秒)"));
116
94
  }, 60000);
117
95
  // Listen for data events from WebSocket
118
96
  const handler = (event) => {
119
- logger.log(`[CALENDAR_TOOL] 📨 Received data event:`, JSON.stringify(event));
120
97
  if (event.intentName === "CreateCalendarEvent") {
121
- logger.log(`[CALENDAR_TOOL] 🎯 CreateCalendarEvent event received`);
122
- logger.log(`[CALENDAR_TOOL] - status: ${event.status}`);
123
98
  clearTimeout(timeout);
124
99
  wsManager.off("data-event", handler);
125
100
  if (event.status === "success" && event.outputs) {
126
- logger.log(`[CALENDAR_TOOL] ✅ Calendar event created successfully`);
127
- logger.log(`[CALENDAR_TOOL] - outputs:`, JSON.stringify(event.outputs));
128
101
  resolve({
129
102
  content: [
130
103
  {
@@ -135,17 +108,13 @@ export const calendarTool = {
135
108
  });
136
109
  }
137
110
  else {
138
- logger.error(`[CALENDAR_TOOL] ❌ Calendar event creation failed`);
139
- logger.error(`[CALENDAR_TOOL] - status: ${event.status}`);
140
111
  reject(new Error(`创建日程失败: ${event.status}`));
141
112
  }
142
113
  }
143
114
  };
144
115
  // Register event handler
145
- logger.log(`[CALENDAR_TOOL] 📡 Registering data-event handler on WebSocket manager`);
146
116
  wsManager.on("data-event", handler);
147
117
  // Send the command
148
- logger.log(`[CALENDAR_TOOL] 📤 Sending CreateCalendarEvent command...`);
149
118
  sendCommand({
150
119
  config,
151
120
  sessionId,
@@ -154,10 +123,8 @@ export const calendarTool = {
154
123
  command,
155
124
  })
156
125
  .then(() => {
157
- logger.log(`[CALENDAR_TOOL] ✅ Command sent successfully, waiting for response...`);
158
126
  })
159
127
  .catch((error) => {
160
- logger.error(`[CALENDAR_TOOL] ❌ Failed to send command:`, error);
161
128
  clearTimeout(timeout);
162
129
  wsManager.off("data-event", handler);
163
130
  reject(error);
@@ -1,7 +1,6 @@
1
1
  import { getXYWebSocketManager } from "../client.js";
2
2
  import { sendCommand } from "../formatter.js";
3
3
  import { getCurrentSessionContext } from "./session-manager.js";
4
- import { logger } from "../utils/logger.js";
5
4
  /**
6
5
  * XY call phone tool - makes a phone call on user's device.
7
6
  * Requires phoneNumber parameter and optional slotId (0 for primary SIM, 1 for secondary SIM).
@@ -9,7 +8,7 @@ import { logger } from "../utils/logger.js";
9
8
  export const callPhoneTool = {
10
9
  name: "call_phone",
11
10
  label: "Call Phone",
12
- description: "拨打电话。需要提供要拨打的电话号码。slotId参数可选,默认为0(主卡),如果用户明确要求使用副卡则设置为1。注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。",
11
+ description: "拨打电话。需要提供要拨打的电话号码。slotId参数可选,默认为0(主卡),如果用户明确要求使用副卡则设置为1。注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。",
13
12
  parameters: {
14
13
  type: "object",
15
14
  properties: {
@@ -26,43 +25,25 @@ export const callPhoneTool = {
26
25
  required: ["phoneNumber"],
27
26
  },
28
27
  async execute(toolCallId, params) {
29
- logger.log(`[CALL_PHONE_TOOL] 🚀 Starting execution`);
30
- logger.log(`[CALL_PHONE_TOOL] - toolCallId: ${toolCallId}`);
31
- logger.log(`[CALL_PHONE_TOOL] - params:`, JSON.stringify(params));
32
- logger.log(`[CALL_PHONE_TOOL] - timestamp: ${new Date().toISOString()}`);
33
28
  // Validate phoneNumber parameter
34
29
  if (!params.phoneNumber || typeof params.phoneNumber !== "string" || params.phoneNumber.trim() === "") {
35
- logger.error(`[CALL_PHONE_TOOL] ❌ Missing or invalid phoneNumber parameter`);
36
30
  throw new Error("Missing required parameter: phoneNumber must be a non-empty string");
37
31
  }
38
32
  // Set default slotId if not provided
39
33
  const slotId = params.slotId !== undefined && params.slotId !== null ? params.slotId : 0;
40
34
  // Validate slotId (must be 0 or 1)
41
35
  if (slotId !== 0 && slotId !== 1) {
42
- logger.error(`[CALL_PHONE_TOOL] ❌ Invalid slotId: ${slotId}`);
43
36
  throw new Error("Invalid slotId: must be 0 (primary SIM) or 1 (secondary SIM)");
44
37
  }
45
- logger.log(`[CALL_PHONE_TOOL] 📞 Preparing to call phone number: ${params.phoneNumber}`);
46
- logger.log(`[CALL_PHONE_TOOL] - slotId: ${slotId} (${slotId === 0 ? "主卡" : "副卡"})`);
47
38
  // Get session context
48
- logger.log(`[CALL_PHONE_TOOL] 🔍 Attempting to get session context...`);
49
39
  const sessionContext = getCurrentSessionContext();
50
40
  if (!sessionContext) {
51
- logger.error(`[CALL_PHONE_TOOL] ❌ FAILED: No active session found!`);
52
- logger.error(`[CALL_PHONE_TOOL] - toolCallId: ${toolCallId}`);
53
41
  throw new Error("No active XY session found. Call phone tool can only be used during an active conversation.");
54
42
  }
55
- logger.log(`[CALL_PHONE_TOOL] ✅ Session context found`);
56
- logger.log(`[CALL_PHONE_TOOL] - sessionId: ${sessionContext.sessionId}`);
57
- logger.log(`[CALL_PHONE_TOOL] - taskId: ${sessionContext.taskId}`);
58
- logger.log(`[CALL_PHONE_TOOL] - messageId: ${sessionContext.messageId}`);
59
43
  const { config, sessionId, taskId, messageId } = sessionContext;
60
44
  // Get WebSocket manager
61
- logger.log(`[CALL_PHONE_TOOL] 🔌 Getting WebSocket manager...`);
62
45
  const wsManager = getXYWebSocketManager(config);
63
- logger.log(`[CALL_PHONE_TOOL] ✅ WebSocket manager obtained`);
64
46
  // Build StartCall command
65
- logger.log(`[CALL_PHONE_TOOL] 📦 Building StartCall command...`);
66
47
  const command = {
67
48
  header: {
68
49
  namespace: "Common",
@@ -97,34 +78,22 @@ export const callPhoneTool = {
97
78
  pageControlRelated: false,
98
79
  },
99
80
  };
100
- logger.log(`[CALL_PHONE_TOOL] 📋 Command details:`, JSON.stringify(command, null, 2));
101
81
  // Send command and wait for response (60 second timeout)
102
- logger.log(`[CALL_PHONE_TOOL] ⏳ Setting up promise to wait for call response...`);
103
- logger.log(`[CALL_PHONE_TOOL] - Timeout: 60 seconds`);
104
82
  return new Promise((resolve, reject) => {
105
83
  const timeout = setTimeout(() => {
106
- logger.error(`[CALL_PHONE_TOOL] ⏰ Timeout: No response received within 60 seconds`);
107
84
  wsManager.off("data-event", handler);
108
85
  reject(new Error("拨打电话超时(60秒)"));
109
86
  }, 60000);
110
87
  // Listen for data events from WebSocket
111
88
  const handler = (event) => {
112
- logger.log(`[CALL_PHONE_TOOL] 📨 Received data event:`, JSON.stringify(event));
113
89
  if (event.intentName === "StartCall") {
114
- logger.log(`[CALL_PHONE_TOOL] 🎯 StartCall event received`);
115
- logger.log(`[CALL_PHONE_TOOL] - status: ${event.status}`);
116
90
  clearTimeout(timeout);
117
91
  wsManager.off("data-event", handler);
118
92
  if (event.status === "success" && event.outputs) {
119
- logger.log(`[CALL_PHONE_TOOL] ✅ Call response received`);
120
- logger.log(`[CALL_PHONE_TOOL] - outputs:`, JSON.stringify(event.outputs));
121
93
  // Check for error code in outputs
122
94
  const code = event.outputs.code !== undefined ? event.outputs.code : null;
123
95
  if (code !== null && code !== 0) {
124
- logger.error(`[CALL_PHONE_TOOL] ❌ Device returned error`);
125
- logger.error(`[CALL_PHONE_TOOL] - code: ${code}`);
126
96
  const errorMsg = event.outputs.errorMsg || event.outputs.errMsg || "未知错误";
127
- logger.error(`[CALL_PHONE_TOOL] - errorMsg: ${errorMsg}`);
128
97
  reject(new Error(`拨打电话失败: ${errorMsg} (错误代码: ${code})`));
129
98
  return;
130
99
  }
@@ -136,9 +105,6 @@ export const callPhoneTool = {
136
105
  slotId: slotId,
137
106
  message: "电话拨打成功",
138
107
  };
139
- logger.log(`[CALL_PHONE_TOOL] 🎉 Call initiated successfully`);
140
- logger.log(`[CALL_PHONE_TOOL] - phoneNumber: ${params.phoneNumber}`);
141
- logger.log(`[CALL_PHONE_TOOL] - slotId: ${slotId}`);
142
108
  resolve({
143
109
  content: [
144
110
  {
@@ -149,19 +115,14 @@ export const callPhoneTool = {
149
115
  });
150
116
  }
151
117
  else {
152
- logger.error(`[CALL_PHONE_TOOL] ❌ Call failed`);
153
- logger.error(`[CALL_PHONE_TOOL] - status: ${event.status}`);
154
- logger.error(`[CALL_PHONE_TOOL] - outputs:`, JSON.stringify(event.outputs || {}));
155
118
  const errorDetail = event.outputs ? JSON.stringify(event.outputs) : event.status;
156
119
  reject(new Error(`拨打电话失败: ${errorDetail}`));
157
120
  }
158
121
  }
159
122
  };
160
123
  // Register event handler
161
- logger.log(`[CALL_PHONE_TOOL] 📡 Registering data-event handler on WebSocket manager`);
162
124
  wsManager.on("data-event", handler);
163
125
  // Send the command
164
- logger.log(`[CALL_PHONE_TOOL] 📤 Sending StartCall command...`);
165
126
  sendCommand({
166
127
  config,
167
128
  sessionId,
@@ -170,10 +131,8 @@ export const callPhoneTool = {
170
131
  command,
171
132
  })
172
133
  .then(() => {
173
- logger.log(`[CALL_PHONE_TOOL] ✅ Command sent successfully, waiting for response...`);
174
134
  })
175
135
  .catch((error) => {
176
- logger.error(`[CALL_PHONE_TOOL] ❌ Failed to send command:`, error);
177
136
  clearTimeout(timeout);
178
137
  wsManager.off("data-event", handler);
179
138
  reject(error);
@@ -1,7 +1,6 @@
1
1
  import { getXYWebSocketManager } from "../client.js";
2
2
  import { sendCommand } from "../formatter.js";
3
3
  import { getCurrentSessionContext } from "./session-manager.js";
4
- import { logger } from "../utils/logger.js";
5
4
  // Enum definitions for alarm parameters
6
5
  const ALARM_SNOOZE_DURATION_VALUES = [5, 10, 15, 20, 25, 30];
7
6
  const ALARM_SNOOZE_TOTAL_VALUES = [0, 1, 3, 5, 10];
@@ -22,15 +21,19 @@ export const createAlarmTool = {
22
21
  必需参数:
23
22
  - alarmTime: 闹钟时间,格式必须为:YYYYMMDD hhmmss(例如:20240315 143000,表示2024年3月15日14:30:00)
24
23
 
25
- 可选参数:
24
+ 可选参数(针对用户没有提及的参数,如果有默认参数,则发送请求时使用默认参数):
26
25
  - alarmTitle: 闹钟名称/标题,默认为"闹钟"
27
26
  - alarmSnoozeDuration: 小睡间隔(分钟),枚举值:5,10,15,20,25,30,默认10
28
27
  - alarmSnoozeTotal: 再响次数,枚举值:0,1,3,5,10,默认0(表示不再响)
29
- - alarmRingDuration: 响铃时长(分钟),枚举值:1,5,10,15,20,30,默认20
28
+ - alarmRingDuration: 响铃时长(分钟),枚举值:1,5,10,15,20,30,默认5
30
29
  - daysOfWakeType: 闹钟响铃类型,枚举值:0=单次响铃,1=法定节假日,2=每天,3=自定义时间,4=法定工作日,默认0
31
30
  - daysOfWeek: 自定义响铃星期,仅当daysOfWakeType=3(自定义时间)时必需且有效,其他情况不要传递此参数。数组或JSON字符串,枚举值:Mon,Tue,Wed,Thu,Fri,Sat,Sun。注意:仅支持长度为1的数组,如果需要一周中不同的几天,需要多次调用此工具
32
31
 
33
- 注意事项:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。`,
32
+ 注意事项:
33
+ a. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。
34
+ b. 使用该工具之前需获取当前真实时间
35
+
36
+ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。`,
34
37
  parameters: {
35
38
  type: "object",
36
39
  properties: {
@@ -67,170 +70,127 @@ export const createAlarmTool = {
67
70
  required: ["alarmTime"],
68
71
  },
69
72
  async execute(toolCallId, params) {
70
- logger.log(`[CREATE_ALARM_TOOL] 🚀 Starting execution`);
71
- logger.log(`[CREATE_ALARM_TOOL] - toolCallId: ${toolCallId}`);
72
- logger.log(`[CREATE_ALARM_TOOL] - params:`, JSON.stringify(params));
73
- logger.log(`[CREATE_ALARM_TOOL] - timestamp: ${new Date().toISOString()}`);
74
73
  // ===== Validate required parameter: alarmTime =====
75
74
  if (!params.alarmTime || typeof params.alarmTime !== "string") {
76
- logger.error(`[CREATE_ALARM_TOOL] ❌ Missing or invalid alarmTime`);
77
75
  throw new Error("Missing required parameter: alarmTime must be a string in format YYYYMMDD hhmmss");
78
76
  }
79
77
  // Parse and convert alarmTime to timestamp
80
- logger.log(`[CREATE_ALARM_TOOL] 🕒 Parsing alarmTime: ${params.alarmTime}`);
81
78
  const alarmTimeMs = parseAlarmTimeToTimestamp(params.alarmTime);
82
79
  if (alarmTimeMs === null) {
83
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmTime format`);
84
80
  throw new Error("Invalid alarmTime format. Required format: YYYYMMDD hhmmss (e.g., 20240315 143000)");
85
81
  }
86
- logger.log(`[CREATE_ALARM_TOOL] ✅ alarmTime converted to timestamp: ${alarmTimeMs}`);
87
82
  // ===== Validate and set optional parameters with defaults =====
88
83
  // alarmTitle - default to "闹钟"
89
84
  const alarmTitle = params.alarmTitle && typeof params.alarmTitle === "string"
90
85
  ? params.alarmTitle
91
86
  : "闹钟";
92
- logger.log(`[CREATE_ALARM_TOOL] - alarmTitle: ${alarmTitle}`);
93
87
  // alarmSnoozeDuration - default 10
94
88
  let alarmSnoozeDuration = 10;
95
89
  if (params.alarmSnoozeDuration !== undefined && params.alarmSnoozeDuration !== null) {
96
90
  if (typeof params.alarmSnoozeDuration !== "number") {
97
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmSnoozeDuration type`);
98
91
  throw new Error("alarmSnoozeDuration must be a number");
99
92
  }
100
93
  if (!ALARM_SNOOZE_DURATION_VALUES.includes(params.alarmSnoozeDuration)) {
101
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmSnoozeDuration value: ${params.alarmSnoozeDuration}`);
102
94
  throw new Error(`alarmSnoozeDuration must be one of: ${ALARM_SNOOZE_DURATION_VALUES.join(", ")}`);
103
95
  }
104
96
  alarmSnoozeDuration = params.alarmSnoozeDuration;
105
97
  }
106
- logger.log(`[CREATE_ALARM_TOOL] - alarmSnoozeDuration: ${alarmSnoozeDuration}`);
107
98
  // alarmSnoozeTotal - default 0
108
99
  let alarmSnoozeTotal = 0;
109
100
  if (params.alarmSnoozeTotal !== undefined && params.alarmSnoozeTotal !== null) {
110
101
  if (typeof params.alarmSnoozeTotal !== "number") {
111
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmSnoozeTotal type`);
112
102
  throw new Error("alarmSnoozeTotal must be a number");
113
103
  }
114
104
  if (!ALARM_SNOOZE_TOTAL_VALUES.includes(params.alarmSnoozeTotal)) {
115
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmSnoozeTotal value: ${params.alarmSnoozeTotal}`);
116
105
  throw new Error(`alarmSnoozeTotal must be one of: ${ALARM_SNOOZE_TOTAL_VALUES.join(", ")}`);
117
106
  }
118
107
  alarmSnoozeTotal = params.alarmSnoozeTotal;
119
108
  }
120
- logger.log(`[CREATE_ALARM_TOOL] - alarmSnoozeTotal: ${alarmSnoozeTotal}`);
121
109
  // alarmRingDuration - default 20
122
110
  let alarmRingDuration = 20;
123
111
  if (params.alarmRingDuration !== undefined && params.alarmRingDuration !== null) {
124
112
  if (typeof params.alarmRingDuration !== "number") {
125
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmRingDuration type`);
126
113
  throw new Error("alarmRingDuration must be a number");
127
114
  }
128
115
  if (!ALARM_RING_DURATION_VALUES.includes(params.alarmRingDuration)) {
129
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid alarmRingDuration value: ${params.alarmRingDuration}`);
130
116
  throw new Error(`alarmRingDuration must be one of: ${ALARM_RING_DURATION_VALUES.join(", ")}`);
131
117
  }
132
118
  alarmRingDuration = params.alarmRingDuration;
133
119
  }
134
- logger.log(`[CREATE_ALARM_TOOL] - alarmRingDuration: ${alarmRingDuration}`);
135
120
  // daysOfWakeType - default 0
136
121
  let daysOfWakeType = 0;
137
122
  if (params.daysOfWakeType !== undefined && params.daysOfWakeType !== null) {
138
123
  if (typeof params.daysOfWakeType !== "number") {
139
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid daysOfWakeType type`);
140
124
  throw new Error("daysOfWakeType must be a number");
141
125
  }
142
126
  if (!DAYS_OF_WAKE_TYPE_VALUES.includes(params.daysOfWakeType)) {
143
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid daysOfWakeType value: ${params.daysOfWakeType}`);
144
127
  throw new Error(`daysOfWakeType must be one of: ${DAYS_OF_WAKE_TYPE_VALUES.join(", ")}`);
145
128
  }
146
129
  daysOfWakeType = params.daysOfWakeType;
147
130
  }
148
- logger.log(`[CREATE_ALARM_TOOL] - daysOfWakeType: ${daysOfWakeType}`);
149
131
  // daysOfWeek - only required when daysOfWakeType is 3
150
132
  let daysOfWeek = [];
151
133
  if (daysOfWakeType === 3) {
152
134
  if (!params.daysOfWeek) {
153
- logger.error(`[CREATE_ALARM_TOOL] ❌ Missing daysOfWeek when daysOfWakeType=3`);
154
135
  throw new Error("daysOfWeek is required when daysOfWakeType is 3 (custom)");
155
136
  }
156
137
  // ===== 参数规范化:兼容数组和 JSON 字符串 =====
157
138
  let normalizedDaysOfWeek = null;
158
139
  // 情况1: 已经是数组
159
140
  if (Array.isArray(params.daysOfWeek)) {
160
- logger.log(`[CREATE_ALARM_TOOL] ✅ daysOfWeek is already an array`);
161
141
  normalizedDaysOfWeek = params.daysOfWeek;
162
142
  }
163
143
  // 情况2: 是字符串,尝试解析为 JSON 数组
164
144
  else if (typeof params.daysOfWeek === 'string') {
165
- logger.log(`[CREATE_ALARM_TOOL] 🔄 daysOfWeek is a string, attempting to parse as JSON...`);
166
145
  try {
167
146
  const parsed = JSON.parse(params.daysOfWeek);
168
147
  if (Array.isArray(parsed)) {
169
- logger.log(`[CREATE_ALARM_TOOL] ✅ Successfully parsed JSON string to array`);
170
148
  normalizedDaysOfWeek = parsed;
171
149
  }
172
150
  else {
173
- logger.error(`[CREATE_ALARM_TOOL] ❌ Parsed JSON is not an array:`, typeof parsed);
174
151
  throw new Error("daysOfWeek must be an array or a JSON string representing an array");
175
152
  }
176
153
  }
177
154
  catch (parseError) {
178
- logger.error(`[CREATE_ALARM_TOOL] ❌ Failed to parse daysOfWeek as JSON:`, parseError);
179
155
  throw new Error(`daysOfWeek must be a valid JSON array string. Parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
180
156
  }
181
157
  }
182
158
  // 情况3: 其他类型,报错
183
159
  else {
184
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid daysOfWeek type:`, typeof params.daysOfWeek);
185
160
  throw new Error(`daysOfWeek must be an array or a JSON string, got ${typeof params.daysOfWeek}`);
186
161
  }
187
162
  // 验证数组非空
188
163
  if (!normalizedDaysOfWeek || normalizedDaysOfWeek.length === 0) {
189
- logger.error(`[CREATE_ALARM_TOOL] ❌ daysOfWeek array is empty`);
190
164
  throw new Error("daysOfWeek array cannot be empty");
191
165
  }
192
166
  // 验证数组长度必须为1
193
167
  if (normalizedDaysOfWeek.length !== 1) {
194
- logger.error(`[CREATE_ALARM_TOOL] ❌ daysOfWeek array length must be 1, got ${normalizedDaysOfWeek.length}`);
195
168
  throw new Error("daysOfWeek 仅支持长度为1的数组。如果需要一周中不同的几天,需要多次调用此工具");
196
169
  }
197
170
  // Validate each day
198
171
  for (const day of normalizedDaysOfWeek) {
199
172
  if (typeof day !== "string" || !DAYS_OF_WEEK_VALUES.includes(day)) {
200
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid day value: ${day}`);
201
173
  throw new Error(`daysOfWeek must contain only: ${DAYS_OF_WEEK_VALUES.join(", ")}`);
202
174
  }
203
175
  }
204
176
  daysOfWeek = normalizedDaysOfWeek;
205
- logger.log(`[CREATE_ALARM_TOOL] - daysOfWeek: ${daysOfWeek.join(", ")}`);
206
177
  }
207
178
  else {
208
179
  // daysOfWakeType is not 3, daysOfWeek should not be provided
209
180
  if (params.daysOfWeek) {
210
- logger.warn(`[CREATE_ALARM_TOOL] ⚠️ daysOfWeek parameter is ignored when daysOfWakeType is not 3 (current: ${daysOfWakeType}). Please remove daysOfWeek parameter.`);
211
181
  }
212
182
  // Explicitly set to empty array
213
183
  daysOfWeek = [];
214
184
  }
215
185
  // Get session context
216
- logger.log(`[CREATE_ALARM_TOOL] 🔍 Attempting to get session context...`);
217
186
  const sessionContext = getCurrentSessionContext();
218
187
  if (!sessionContext) {
219
- logger.error(`[CREATE_ALARM_TOOL] ❌ FAILED: No active session found!`);
220
- logger.error(`[CREATE_ALARM_TOOL] - toolCallId: ${toolCallId}`);
221
188
  throw new Error("No active XY session found. Create alarm tool can only be used during an active conversation.");
222
189
  }
223
- logger.log(`[CREATE_ALARM_TOOL] ✅ Session context found`);
224
- logger.log(`[CREATE_ALARM_TOOL] - sessionId: ${sessionContext.sessionId}`);
225
- logger.log(`[CREATE_ALARM_TOOL] - taskId: ${sessionContext.taskId}`);
226
- logger.log(`[CREATE_ALARM_TOOL] - messageId: ${sessionContext.messageId}`);
227
190
  const { config, sessionId, taskId, messageId } = sessionContext;
228
191
  // Get WebSocket manager
229
- logger.log(`[CREATE_ALARM_TOOL] 🔌 Getting WebSocket manager...`);
230
192
  const wsManager = getXYWebSocketManager(config);
231
- logger.log(`[CREATE_ALARM_TOOL] ✅ WebSocket manager obtained`);
232
193
  // Build CreateAlarm command
233
- logger.log(`[CREATE_ALARM_TOOL] 📦 Building CreateAlarm command...`);
234
194
  // Build intentParam - only include daysOfWeek when daysOfWakeType is 3
235
195
  const intentParam = {
236
196
  entityName: "Alarm",
@@ -244,10 +204,8 @@ export const createAlarmTool = {
244
204
  // Only include daysOfWeek when daysOfWakeType is 3
245
205
  if (daysOfWakeType === 3 && daysOfWeek.length > 0) {
246
206
  intentParam.daysOfWeek = daysOfWeek;
247
- logger.log(`[CREATE_ALARM_TOOL] - Including daysOfWeek in intentParam: ${daysOfWeek.join(", ")}`);
248
207
  }
249
208
  else {
250
- logger.log(`[CREATE_ALARM_TOOL] - Excluding daysOfWeek from intentParam (daysOfWakeType=${daysOfWakeType})`);
251
209
  }
252
210
  const command = {
253
211
  header: {
@@ -281,74 +239,35 @@ export const createAlarmTool = {
281
239
  },
282
240
  };
283
241
  // Send command and wait for response (60 second timeout)
284
- logger.log(`[CREATE_ALARM_TOOL] ⏳ Setting up promise to wait for alarm creation response...`);
285
- logger.log(`[CREATE_ALARM_TOOL] - Timeout: 60 seconds`);
286
242
  return new Promise((resolve, reject) => {
287
243
  const timeout = setTimeout(() => {
288
- logger.error(`[CREATE_ALARM_TOOL] ⏰ Timeout: No response received within 60 seconds`);
289
244
  wsManager.off("data-event", handler);
290
245
  reject(new Error("创建闹钟超时(60秒)"));
291
246
  }, 60000);
292
247
  // Listen for data events from WebSocket
293
248
  const handler = (event) => {
294
- logger.log(`[CREATE_ALARM_TOOL] 📨 Received data event:`, JSON.stringify(event));
295
249
  if (event.intentName === "CreateAlarm") {
296
- logger.log(`[CREATE_ALARM_TOOL] 🎯 CreateAlarm event received`);
297
- logger.log(`[CREATE_ALARM_TOOL] - status: ${event.status}`);
298
250
  clearTimeout(timeout);
299
251
  wsManager.off("data-event", handler);
300
252
  if (event.status === "success" && event.outputs) {
301
- logger.log(`[CREATE_ALARM_TOOL] ✅ Alarm creation completed successfully`);
302
- logger.log(`[CREATE_ALARM_TOOL] - outputs:`, JSON.stringify(event.outputs));
303
- // Check for error code in outputs
304
- const code = event.outputs.code !== undefined ? event.outputs.code : null;
305
- if (code !== null && code !== 0) {
306
- logger.error(`[CREATE_ALARM_TOOL] ❌ Device returned error`);
307
- logger.error(`[CREATE_ALARM_TOOL] - code: ${code}`);
308
- const errorMsg = event.outputs.errorMsg || event.outputs.errMsg || "未知错误";
309
- logger.error(`[CREATE_ALARM_TOOL] - errorMsg: ${errorMsg}`);
310
- reject(new Error(`创建闹钟失败: ${errorMsg} (错误代码: ${code})`));
311
- return;
312
- }
313
- // Extract result with safe navigation
314
- const result = event.outputs.result || {};
315
- logger.log(`[CREATE_ALARM_TOOL] 📋 Alarm result:`, JSON.stringify(result));
253
+ // 成功,直接返回完整的 event.outputs JSON 字符串
316
254
  resolve({
317
255
  content: [
318
256
  {
319
257
  type: "text",
320
- text: JSON.stringify({
321
- success: true,
322
- alarm: {
323
- entityId: result.entityId,
324
- entityName: result.entityName,
325
- alarmTitle: result.alarmTitle,
326
- alarmTime: result.alarmTime,
327
- alarmState: result.alarmState,
328
- alarmRingDuration: result.alarmRingDuration,
329
- alarmSnoozeDuration: result.alarmSnoozeDuration,
330
- alarmSnoozeTotal: result.alarmSnoozeTotal,
331
- daysOfWakeType: result.daysOfWakeType,
332
- },
333
- code,
334
- }),
258
+ text: JSON.stringify(event.outputs),
335
259
  },
336
260
  ],
337
261
  });
338
262
  }
339
263
  else {
340
- logger.error(`[CREATE_ALARM_TOOL] ❌ Alarm creation failed`);
341
- logger.error(`[CREATE_ALARM_TOOL] - status: ${event.status}`);
342
- logger.error(`[CREATE_ALARM_TOOL] - outputs:`, JSON.stringify(event.outputs || {}));
343
264
  reject(new Error(`创建闹钟失败: ${event.status}`));
344
265
  }
345
266
  }
346
267
  };
347
268
  // Register event handler
348
- logger.log(`[CREATE_ALARM_TOOL] 📡 Registering data-event handler on WebSocket manager`);
349
269
  wsManager.on("data-event", handler);
350
270
  // Send the command
351
- logger.log(`[CREATE_ALARM_TOOL] 📤 Sending CreateAlarm command...`);
352
271
  sendCommand({
353
272
  config,
354
273
  sessionId,
@@ -357,10 +276,8 @@ export const createAlarmTool = {
357
276
  command,
358
277
  })
359
278
  .then(() => {
360
- logger.log(`[CREATE_ALARM_TOOL] ✅ Command sent successfully, waiting for response...`);
361
279
  })
362
280
  .catch((error) => {
363
- logger.error(`[CREATE_ALARM_TOOL] ❌ Failed to send command:`, error);
364
281
  clearTimeout(timeout);
365
282
  wsManager.off("data-event", handler);
366
283
  reject(error);
@@ -380,17 +297,14 @@ function parseAlarmTimeToTimestamp(alarmTime) {
380
297
  const trimmed = alarmTime.trim();
381
298
  // Check basic format (should have at least 13 characters: YYYYMMDD hhmmss)
382
299
  if (trimmed.length < 13) {
383
- logger.error(`[CREATE_ALARM_TOOL] ❌ alarmTime too short: ${trimmed}`);
384
300
  return null;
385
301
  }
386
302
  // Extract date and time parts
387
303
  // Format: YYYYMMDD hhmmss
388
304
  const datePart = trimmed.substring(0, 8); // YYYYMMDD
389
305
  const timePart = trimmed.substring(8).trim(); // hhmmss (may have leading space)
390
- logger.log(`[CREATE_ALARM_TOOL] - datePart: ${datePart}, timePart: ${timePart}`);
391
306
  // Validate lengths
392
307
  if (datePart.length !== 8 || timePart.length !== 6) {
393
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid part lengths: datePart=${datePart.length}, timePart=${timePart.length}`);
394
308
  return null;
395
309
  }
396
310
  // Parse components
@@ -400,45 +314,36 @@ function parseAlarmTimeToTimestamp(alarmTime) {
400
314
  const hour = parseInt(timePart.substring(0, 2), 10);
401
315
  const minute = parseInt(timePart.substring(2, 4), 10);
402
316
  const second = parseInt(timePart.substring(4, 6), 10);
403
- logger.log(`[CREATE_ALARM_TOOL] - Parsed: ${year}-${month}-${day} ${hour}:${minute}:${second}`);
404
317
  // Validate values
405
318
  if (isNaN(year) || isNaN(month) || isNaN(day) ||
406
319
  isNaN(hour) || isNaN(minute) || isNaN(second)) {
407
- logger.error(`[CREATE_ALARM_TOOL] ❌ NaN detected in parsed values`);
408
320
  return null;
409
321
  }
410
322
  // Validate ranges
411
323
  if (month < 1 || month > 12) {
412
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid month: ${month}`);
413
324
  return null;
414
325
  }
415
326
  if (day < 1 || day > 31) {
416
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid day: ${day}`);
417
327
  return null;
418
328
  }
419
329
  if (hour < 0 || hour > 23) {
420
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid hour: ${hour}`);
421
330
  return null;
422
331
  }
423
332
  if (minute < 0 || minute > 59) {
424
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid minute: ${minute}`);
425
333
  return null;
426
334
  }
427
335
  if (second < 0 || second > 59) {
428
- logger.error(`[CREATE_ALARM_TOOL] ❌ Invalid second: ${second}`);
429
336
  return null;
430
337
  }
431
338
  // Create Date object and get timestamp
432
339
  const date = new Date(year, month - 1, day, hour, minute, second);
433
340
  const timestamp = date.getTime();
434
341
  if (isNaN(timestamp)) {
435
- logger.error(`[CREATE_ALARM_TOOL] ❌ Generated timestamp is NaN`);
436
342
  return null;
437
343
  }
438
344
  return timestamp;
439
345
  }
440
346
  catch (error) {
441
- logger.error(`[CREATE_ALARM_TOOL] ❌ Exception in parseAlarmTimeToTimestamp:`, error);
442
347
  return null;
443
348
  }
444
349
  }