@ynhcj/xiaoyi-channel 0.0.55-beta → 0.0.55-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.js +7 -4
  2. package/dist/src/bot.d.ts +1 -0
  3. package/dist/src/bot.js +44 -8
  4. package/dist/src/channel.js +20 -19
  5. package/dist/src/cspl/call-api.js +14 -11
  6. package/dist/src/cspl/config.js +3 -3
  7. package/dist/src/cspl/constants.d.ts +2 -0
  8. package/dist/src/cspl/constants.js +12 -0
  9. package/dist/src/cspl/utils.js +4 -2
  10. package/dist/src/file-download.js +3 -6
  11. package/dist/src/file-upload.js +52 -5
  12. package/dist/src/formatter.d.ts +2 -0
  13. package/dist/src/formatter.js +10 -2
  14. package/dist/src/monitor.js +1 -0
  15. package/dist/src/outbound.js +2 -7
  16. package/dist/src/parser.d.ts +6 -0
  17. package/dist/src/parser.js +16 -0
  18. package/dist/src/provider.d.ts +2 -0
  19. package/dist/src/provider.js +155 -0
  20. package/dist/src/reply-dispatcher.js +8 -1
  21. package/dist/src/tools/call-device-tool.d.ts +5 -0
  22. package/dist/src/tools/call-device-tool.js +126 -0
  23. package/dist/src/tools/call-phone-tool.js +2 -18
  24. package/dist/src/tools/create-alarm-tool.js +6 -21
  25. package/dist/src/tools/delete-alarm-tool.js +1 -4
  26. package/dist/src/tools/device-tool-map.d.ts +4 -0
  27. package/dist/src/tools/device-tool-map.js +37 -0
  28. package/dist/src/tools/find-pc-devices-tool.d.ts +5 -0
  29. package/dist/src/tools/find-pc-devices-tool.js +98 -0
  30. package/dist/src/tools/get-alarm-tool-schema.d.ts +16 -0
  31. package/dist/src/tools/get-alarm-tool-schema.js +11 -0
  32. package/dist/src/tools/get-calendar-tool-schema.d.ts +16 -0
  33. package/dist/src/tools/get-calendar-tool-schema.js +9 -0
  34. package/dist/src/tools/get-collection-tool-schema.d.ts +16 -0
  35. package/dist/src/tools/get-collection-tool-schema.js +10 -0
  36. package/dist/src/tools/get-contact-tool-schema.d.ts +16 -0
  37. package/dist/src/tools/get-contact-tool-schema.js +11 -0
  38. package/dist/src/tools/get-device-file-tool-schema.d.ts +16 -0
  39. package/dist/src/tools/get-device-file-tool-schema.js +10 -0
  40. package/dist/src/tools/get-note-tool-schema.d.ts +16 -0
  41. package/dist/src/tools/get-note-tool-schema.js +10 -0
  42. package/dist/src/tools/get-photo-tool-schema.d.ts +16 -0
  43. package/dist/src/tools/get-photo-tool-schema.js +10 -0
  44. package/dist/src/tools/image-reading-tool.js +7 -10
  45. package/dist/src/tools/modify-alarm-tool.js +11 -28
  46. package/dist/src/tools/save-file-to-phone-tool.d.ts +5 -0
  47. package/dist/src/tools/save-file-to-phone-tool.js +166 -0
  48. package/dist/src/tools/save-media-to-gallery-tool.d.ts +5 -0
  49. package/dist/src/tools/save-media-to-gallery-tool.js +174 -0
  50. package/dist/src/tools/schema-tool-factory.d.ts +27 -0
  51. package/dist/src/tools/schema-tool-factory.js +32 -0
  52. package/dist/src/tools/search-alarm-tool.js +6 -13
  53. package/dist/src/tools/search-calendar-tool.js +2 -0
  54. package/dist/src/tools/search-email-tool.d.ts +5 -0
  55. package/dist/src/tools/search-email-tool.js +137 -0
  56. package/dist/src/tools/search-file-tool.js +4 -4
  57. package/dist/src/tools/search-message-tool.js +1 -0
  58. package/dist/src/tools/search-photo-gallery-tool.js +2 -2
  59. package/dist/src/tools/send-command-to-car-tool.d.ts +5 -0
  60. package/dist/src/tools/send-command-to-car-tool.js +85 -0
  61. package/dist/src/tools/send-file-to-user-tool.js +2 -4
  62. package/dist/src/tools/session-manager.d.ts +1 -0
  63. package/dist/src/tools/timestamp-to-utc8-tool.d.ts +12 -0
  64. package/dist/src/tools/timestamp-to-utc8-tool.js +104 -0
  65. package/dist/src/tools/upload-file-tool.js +4 -4
  66. package/dist/src/tools/upload-photo-tool.js +2 -2
  67. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +4 -0
  68. package/dist/src/tools/xiaoyi-add-collection-tool.js +192 -0
  69. package/dist/src/tools/xiaoyi-collection-tool.js +43 -7
  70. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +4 -0
  71. package/dist/src/tools/xiaoyi-delete-collection-tool.js +163 -0
  72. package/dist/src/utils/runtime-manager.d.ts +7 -0
  73. package/dist/src/utils/runtime-manager.js +42 -0
  74. package/openclaw.plugin.json +1 -0
  75. package/package.json +2 -3
@@ -0,0 +1,155 @@
1
+ // Xiaoyi Provider
2
+ // Wraps any OpenAI-compatible endpoint and injects dynamic headers
3
+ // (taskId, sessionId, conversationId) from the current XY channel session.
4
+ // Falls back to uid-based values when no session context is available.
5
+ //
6
+ // Users configure the underlying model in config:
7
+ // models.providers.xiaoyiprovider.baseUrl = "https://..."
8
+ // models.providers.xiaoyiprovider.api = "openai-completions"
9
+ // models.providers.xiaoyiprovider.models = [...]
10
+ import { createHash } from "crypto";
11
+ import { getCurrentSessionContext } from "./tools/session-manager.js";
12
+ /**
13
+ * Dynamic header keys injected via extraParams and forwarded to the HTTP request.
14
+ * Correspond to the three fields written to .xiaoyiruntime:
15
+ * TASK_ID, SESSION_ID, CONVERSATION_ID
16
+ */
17
+ const HEADER_TRACE_ID = "x-hag-trace-id";
18
+ const HEADER_SESSION_ID = "x-session-id";
19
+ const HEADER_INTERACTION_ID = "x-interaction-id";
20
+ /**
21
+ * Encode uid via SHA-256 and take first 32 hex chars.
22
+ */
23
+ function encodeUid(uid) {
24
+ return createHash("sha256").update(uid).digest("hex").slice(0, 32);
25
+ }
26
+ /**
27
+ * Get uid from channel config (OpenClawConfig -> channels -> xiaoyi-channel -> uid).
28
+ */
29
+ function getUidFromConfig(config) {
30
+ return config?.channels?.["xiaoyi-channel"]?.uid;
31
+ }
32
+ export const xiaoyiProvider = {
33
+ id: "xiaoyiprovider",
34
+ label: "Xiaoyi Provider",
35
+ docsPath: "/providers/models",
36
+ auth: [],
37
+ isCacheTtlEligible: () => true,
38
+ /**
39
+ * Inject dynamic session params into extraParams so they flow
40
+ * through to wrapStreamFn's ctx.extraParams.
41
+ *
42
+ * Priority:
43
+ * 1. Session context (from AsyncLocalStorage, set by bot.ts)
44
+ * 2. uid-based fallback: sha256(uid).hex[:32]_timestamp
45
+ * 3. No uid available → return undefined (no headers injected)
46
+ */
47
+ prepareExtraParams: (ctx) => {
48
+ const sessionCtx = getCurrentSessionContext();
49
+ if (sessionCtx) {
50
+ const taskId = sessionCtx.taskId;
51
+ const sessionId = taskId.split("&")[0];
52
+ const interactionId = taskId.split("&")[1] || "";
53
+ return {
54
+ ...ctx.extraParams,
55
+ [HEADER_TRACE_ID]: taskId,
56
+ [HEADER_SESSION_ID]: sessionId,
57
+ [HEADER_INTERACTION_ID]: interactionId,
58
+ };
59
+ }
60
+ // Fallback: uid-based values
61
+ const uid = getUidFromConfig(ctx.config);
62
+ if (!uid)
63
+ return undefined;
64
+ const prefix = encodeUid(uid);
65
+ const ts = Date.now();
66
+ const fallbackValue = `${prefix}_${ts}`;
67
+ return {
68
+ ...ctx.extraParams,
69
+ [HEADER_TRACE_ID]: fallbackValue,
70
+ [HEADER_SESSION_ID]: fallbackValue,
71
+ [HEADER_INTERACTION_ID]: fallbackValue,
72
+ };
73
+ },
74
+ /**
75
+ * Wrap the stream function to inject dynamic headers into every
76
+ * HTTP request to the model provider.
77
+ *
78
+ * Reads the values injected by prepareExtraParams and adds them
79
+ * as HTTP headers on the outgoing request.
80
+ */
81
+ wrapStreamFn: (ctx) => {
82
+ const underlying = ctx.streamFn;
83
+ if (!underlying)
84
+ return underlying;
85
+ return async (model, context, options) => {
86
+ // 每次请求时从 ctx.extraParams 动态读取 header
87
+ const dynamicHeaders = {};
88
+ if (ctx.extraParams) {
89
+ const traceId = ctx.extraParams[HEADER_TRACE_ID];
90
+ const sessionId = ctx.extraParams[HEADER_SESSION_ID];
91
+ const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
92
+ if (typeof traceId === "string")
93
+ dynamicHeaders[HEADER_TRACE_ID] = traceId;
94
+ if (typeof sessionId === "string")
95
+ dynamicHeaders[HEADER_SESSION_ID] = sessionId;
96
+ if (typeof interactionId === "string")
97
+ dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
98
+ }
99
+ // 记录输入
100
+ console.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
101
+ if (context.systemPrompt) {
102
+ console.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
103
+ }
104
+ // 在发送给模型前,优化 systemPrompt 结构
105
+ if (context.systemPrompt) {
106
+ let sp = context.systemPrompt;
107
+ const beforeLen = sp.length;
108
+ // 删除 ## Tooling 与 TOOLS.md 声明之间的内容
109
+ sp = sp.replace(/(## Tooling)[\s\S]*?(TOOLS\.md does not control tool availability; it is user guidance for how to use external tools\.)/, "$1\n\n$2");
110
+ // (1) 提取 ## Skills (mandatory) 到 </available_skills> 作为第一部分
111
+ const skillsMatch = sp.match(/(## Skills \(mandatory\)[\s\S]*?<\/available_skills>)/);
112
+ const part1 = skillsMatch ? skillsMatch[0] : '';
113
+ // (2) 提取 ## /home/sandbox/.openclaw/workspace/SOUL.md 到 ## /home/sandbox/.openclaw/workspace/TOOLS.md 之前的内容作为第二部分
114
+ const soulMatch = sp.match(/(## \/home\/sandbox\/\.openclaw\/workspace\/SOUL\.md[\s\S]*?)(?=## \/home\/sandbox\/\.openclaw\/workspace\/TOOLS\.md)/);
115
+ const part2 = soulMatch ? soulMatch[1].trim() : '';
116
+ if (part1 || part2) {
117
+ // 从原始位置删除已提取的部分
118
+ if (skillsMatch)
119
+ sp = sp.replace(skillsMatch[0], '');
120
+ if (soulMatch)
121
+ sp = sp.replace(soulMatch[1], '');
122
+ // 清理多余空行
123
+ sp = sp.replace(/\n{3,}/g, '\n\n');
124
+ // (3) 将 第二部分 + 第一部分 插入到 ## Runtime 上面
125
+ const combined = (part2 + '\n\n' + part1).trim();
126
+ if (combined && sp.includes('## Runtime')) {
127
+ sp = sp.replace('## Runtime', combined + '\n\n## Runtime');
128
+ }
129
+ }
130
+ console.log(`[xiaoyiprovider] system prompt optimized: ${beforeLen} -> ${sp.length}`);
131
+ context.systemPrompt = sp;
132
+ }
133
+ // Append device context to systemPrompt
134
+ const sessionCtx = getCurrentSessionContext();
135
+ if (sessionCtx?.deviceType) {
136
+ const rawDevice = sessionCtx.deviceType;
137
+ const displayDevice = (rawDevice === "2in1") ? "鸿蒙PC" : rawDevice;
138
+ const deviceSection = `\n\n## Current User Device Context\nThe current user is using the following device: ${displayDevice}\nYou need to be aware of the user’s current device and provide guidance accordingly. If the response involves device-related tools or actions, you must tailor the reply based on the user’s current device, using device-specific references such as “saved to the Notes/Calendar on your {deviceType}.\n”`;
139
+ context.systemPrompt = (context.systemPrompt ?? "") + deviceSection;
140
+ }
141
+ const stream = await underlying(model, context, {
142
+ ...options,
143
+ headers: {
144
+ ...options?.headers,
145
+ ...dynamicHeaders,
146
+ },
147
+ });
148
+ // 异步监听输出(不阻塞 stream 返回)
149
+ stream.result().then((result) => {
150
+ console.log(`[xiaoyiprovider] stream completed, usage: input=${result.usage?.input} output=${result.usage?.output}`);
151
+ }, (err) => console.log(`[xiaoyiprovider] stream error: ${JSON.stringify(err)}`));
152
+ return stream;
153
+ };
154
+ },
155
+ };
@@ -235,9 +235,11 @@ export function createXYReplyDispatcher(params) {
235
235
  text: "任务执行异常,请重试~",
236
236
  append: false,
237
237
  final: true,
238
+ errorCode: 99921111,
239
+ errorMessage: "任务执行异常,请重试",
238
240
  });
239
241
  finalSent = true;
240
- log(`[ON_IDLE] ✅ Sent error response`);
242
+ log(`[ON_IDLE] ✅ Sent error response with code: 99921111`);
241
243
  }
242
244
  catch (err) {
243
245
  error(`[ON_IDLE] Failed to send error response:`, err);
@@ -265,6 +267,11 @@ export function createXYReplyDispatcher(params) {
265
267
  log(`[TOOL START] Tool: ${name}, phase: ${phase}, taskId: ${currentTaskId}`);
266
268
  if (phase === "start") {
267
269
  const toolName = name || "unknown";
270
+ // call_device_tool 由自身 execute() 内部发送具体子工具名的状态更新
271
+ if (toolName === "call_device_tool") {
272
+ log(`[TOOL START] Skipping generic status for call_device_tool, will be handled by execute()`);
273
+ return;
274
+ }
268
275
  try {
269
276
  await sendStatusUpdate({
270
277
  config,
@@ -0,0 +1,5 @@
1
+ /**
2
+ * call_device_tool - 通用端工具调度器。
3
+ * LLM 必须先通过 get_xxx_tool_schema 获取具体工具 schema,再用本工具执行。
4
+ */
5
+ export declare const callDeviceTool: any;
@@ -0,0 +1,126 @@
1
+ import { noteTool } from "./note-tool.js";
2
+ import { searchNoteTool } from "./search-note-tool.js";
3
+ import { modifyNoteTool } from "./modify-note-tool.js";
4
+ import { createAlarmTool } from "./create-alarm-tool.js";
5
+ import { searchAlarmTool } from "./search-alarm-tool.js";
6
+ import { modifyAlarmTool } from "./modify-alarm-tool.js";
7
+ import { deleteAlarmTool } from "./delete-alarm-tool.js";
8
+ import { searchContactTool } from "./search-contact-tool.js";
9
+ import { callPhoneTool } from "./call-phone-tool.js";
10
+ import { searchMessageTool } from "./search-message-tool.js";
11
+ import { sendMessageTool } from "./send-message-tool.js";
12
+ import { xiaoyiAddCollectionTool } from "./xiaoyi-add-collection-tool.js";
13
+ import { xiaoyiCollectionTool } from "./xiaoyi-collection-tool.js";
14
+ import { xiaoyiDeleteCollectionTool } from "./xiaoyi-delete-collection-tool.js";
15
+ import { calendarTool } from "./calendar-tool.js";
16
+ import { searchCalendarTool } from "./search-calendar-tool.js";
17
+ import { searchPhotoGalleryTool } from "./search-photo-gallery-tool.js";
18
+ import { uploadPhotoTool } from "./upload-photo-tool.js";
19
+ import { saveMediaToGalleryTool } from "./save-media-to-gallery-tool.js";
20
+ import { searchFileTool } from "./search-file-tool.js";
21
+ import { uploadFileTool } from "./upload-file-tool.js";
22
+ import { saveFileToPhoneTool } from "./save-file-to-phone-tool.js";
23
+ import { sendStatusUpdate } from "../formatter.js";
24
+ import { getCurrentSessionContext } from "./session-manager.js";
25
+ import { getCurrentTaskId, getCurrentMessageId } from "../task-manager.js";
26
+ /**
27
+ * 端工具注册表 —— 按 name 索引所有可通过 call_device_tool 调度的工具。
28
+ */
29
+ const deviceToolRegistry = new Map([
30
+ [noteTool.name, noteTool],
31
+ [searchNoteTool.name, searchNoteTool],
32
+ [modifyNoteTool.name, modifyNoteTool],
33
+ [createAlarmTool.name, createAlarmTool],
34
+ [searchAlarmTool.name, searchAlarmTool],
35
+ [modifyAlarmTool.name, modifyAlarmTool],
36
+ [deleteAlarmTool.name, deleteAlarmTool],
37
+ [searchContactTool.name, searchContactTool],
38
+ [callPhoneTool.name, callPhoneTool],
39
+ [searchMessageTool.name, searchMessageTool],
40
+ [sendMessageTool.name, sendMessageTool],
41
+ [xiaoyiAddCollectionTool.name, xiaoyiAddCollectionTool],
42
+ [xiaoyiCollectionTool.name, xiaoyiCollectionTool],
43
+ [xiaoyiDeleteCollectionTool.name, xiaoyiDeleteCollectionTool],
44
+ [calendarTool.name, calendarTool],
45
+ [searchCalendarTool.name, searchCalendarTool],
46
+ [searchPhotoGalleryTool.name, searchPhotoGalleryTool],
47
+ [uploadPhotoTool.name, uploadPhotoTool],
48
+ [saveMediaToGalleryTool.name, saveMediaToGalleryTool],
49
+ [searchFileTool.name, searchFileTool],
50
+ [uploadFileTool.name, uploadFileTool],
51
+ [saveFileToPhoneTool.name, saveFileToPhoneTool],
52
+ ]);
53
+ /**
54
+ * call_device_tool - 通用端工具调度器。
55
+ * LLM 必须先通过 get_xxx_tool_schema 获取具体工具 schema,再用本工具执行。
56
+ */
57
+ export const callDeviceTool = {
58
+ name: "call_device_tool",
59
+ label: "Call Device Tool",
60
+ description: "用户设备侧工具调用。必须先调用get_xxx_tool_schema获取了具体的工具schema,才能使用本工具执行对应设备侧工具。",
61
+ parameters: {
62
+ type: "object",
63
+ properties: {
64
+ toolName: {
65
+ type: "string",
66
+ description: "要调用的具体端工具名称,即get_xxx_tool_schema返回的工具的name",
67
+ },
68
+ arguments: {
69
+ type: "object",
70
+ description: "工具所需的具体参数JSON键值对",
71
+ },
72
+ },
73
+ required: ["toolName", "arguments"],
74
+ },
75
+ async execute(toolCallId, params) {
76
+ const { toolName, arguments: toolArgs } = params;
77
+ // 向用户端发送具体工具名的状态更新
78
+ const ctx = getCurrentSessionContext();
79
+ if (ctx) {
80
+ const currentTaskId = getCurrentTaskId(ctx.sessionId) ?? ctx.taskId;
81
+ const currentMessageId = getCurrentMessageId(ctx.sessionId) ?? ctx.messageId;
82
+ try {
83
+ await sendStatusUpdate({
84
+ config: ctx.config,
85
+ sessionId: ctx.sessionId,
86
+ taskId: currentTaskId,
87
+ messageId: currentMessageId,
88
+ text: `正在使用工具: ${toolName}...`,
89
+ state: "working",
90
+ });
91
+ }
92
+ catch (_) {
93
+ // 状态更新失败不影响工具执行
94
+ }
95
+ }
96
+ const tool = deviceToolRegistry.get(toolName);
97
+ if (!tool) {
98
+ return {
99
+ content: [
100
+ {
101
+ type: "text",
102
+ text: `端工具${toolName}不存在。请确保toolName为get_xxx_tool_schema返回的工具的name。`,
103
+ },
104
+ ],
105
+ };
106
+ }
107
+ try {
108
+ return await tool.execute(toolCallId, toolArgs);
109
+ }
110
+ catch (error) {
111
+ // ToolInputError (.name === "ToolInputError") 或其他参数校验错误
112
+ if (error.name === "ToolInputError") {
113
+ return {
114
+ content: [
115
+ {
116
+ type: "text",
117
+ text: `端工具参数错误:${error.message}。请确保arguments符合get_xxx_tool_schema返回的工具schema。`,
118
+ },
119
+ ],
120
+ };
121
+ }
122
+ // 非参数错误(网络超时等),直接向上抛出
123
+ throw error;
124
+ }
125
+ },
126
+ };
@@ -90,33 +90,17 @@ export const callPhoneTool = {
90
90
  clearTimeout(timeout);
91
91
  wsManager.off("data-event", handler);
92
92
  if (event.status === "success" && event.outputs) {
93
- // Check for error code in outputs
94
- const code = event.outputs.code !== undefined ? event.outputs.code : null;
95
- if (code !== null && code !== 0) {
96
- const errorMsg = event.outputs.errorMsg || event.outputs.errMsg || "未知错误";
97
- reject(new Error(`拨打电话失败: ${errorMsg} (错误代码: ${code})`));
98
- return;
99
- }
100
- // Return the outputs directly
101
- const result = {
102
- success: true,
103
- code: code,
104
- phoneNumber: params.phoneNumber,
105
- slotId: slotId,
106
- message: "电话拨打成功",
107
- };
108
93
  resolve({
109
94
  content: [
110
95
  {
111
96
  type: "text",
112
- text: JSON.stringify(result),
97
+ text: JSON.stringify(event.outputs),
113
98
  },
114
99
  ],
115
100
  });
116
101
  }
117
102
  else {
118
- const errorDetail = event.outputs ? JSON.stringify(event.outputs) : event.status;
119
- reject(new Error(`拨打电话失败: ${errorDetail}`));
103
+ reject(new Error(`拨打电话失败: ${event.status}`));
120
104
  }
121
105
  }
122
106
  };
@@ -6,7 +6,7 @@ const ALARM_SNOOZE_DURATION_VALUES = [5, 10, 15, 20, 25, 30];
6
6
  const ALARM_SNOOZE_TOTAL_VALUES = [0, 1, 3, 5, 10];
7
7
  const ALARM_RING_DURATION_VALUES = [1, 5, 10, 15, 20, 30];
8
8
  const DAYS_OF_WAKE_TYPE_VALUES = [0, 1, 2, 3, 4];
9
- const DAYS_OF_WEEK_VALUES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
9
+ const DAYS_OF_WEEK_VALUES = ["Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"];
10
10
  /**
11
11
  * XY create alarm tool - creates an alarm on user's device.
12
12
  * Requires alarmTime parameter. Other parameters are optional with sensible defaults.
@@ -17,18 +17,7 @@ export const createAlarmTool = {
17
17
  name: "create_alarm",
18
18
  label: "Create Alarm",
19
19
  description: `在用户设备上创建闹钟。
20
-
21
- 必需参数:
22
- - alarmTime: 闹钟时间,格式必须为:YYYYMMDD hhmmss(例如:20240315 143000,表示2024年3月15日14:30:00)
23
-
24
- 可选参数(针对用户没有提及的参数,如果有默认参数,则发送请求时使用默认参数):
25
- - alarmTitle: 闹钟名称/标题,默认为"闹钟"
26
- - alarmSnoozeDuration: 小睡间隔(分钟),枚举值:5,10,15,20,25,30,默认10
27
- - alarmSnoozeTotal: 再响次数,枚举值:0,1,3,5,10,默认0(表示不再响)
28
- - alarmRingDuration: 响铃时长(分钟),枚举值:1,5,10,15,20,30,默认5
29
- - daysOfWakeType: 闹钟响铃类型,枚举值:0=单次响铃,1=法定节假日,2=每天,3=自定义时间,4=法定工作日,默认0
30
- - daysOfWeek: 自定义响铃星期,仅当daysOfWakeType=3(自定义时间)时必需且有效,其他情况不要传递此参数。数组或JSON字符串,枚举值:Mon,Tue,Wed,Thu,Fri,Sat,Sun。注意:仅支持长度为1的数组,如果需要一周中不同的几天,需要多次调用此工具
31
-
20
+
32
21
  注意事项:
33
22
  a. 操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。
34
23
  b. 使用该工具之前需获取当前真实时间
@@ -39,7 +28,7 @@ b. 使用该工具之前需获取当前真实时间
39
28
  properties: {
40
29
  alarmTime: {
41
30
  type: "string",
42
- description: "闹钟时间,格式必须为:YYYYMMDD hhmmss(例如:20240315 143000)",
31
+ description: "闹钟时间,格式必须为:YYYYMMDD hhmmss(例如:20240315 143000,表示2024年3月15日14:30:00)",
43
32
  },
44
33
  alarmTitle: {
45
34
  type: "string",
@@ -51,7 +40,7 @@ b. 使用该工具之前需获取当前真实时间
51
40
  },
52
41
  alarmSnoozeTotal: {
53
42
  type: "number",
54
- description: "再响次数,枚举值:0,1,3,5,10,默认0",
43
+ description: "再响次数,枚举值:0,1,3,5,10,默认0(表示不再响)",
55
44
  },
56
45
  alarmRingDuration: {
57
46
  type: "number",
@@ -59,12 +48,12 @@ b. 使用该工具之前需获取当前真实时间
59
48
  },
60
49
  daysOfWakeType: {
61
50
  type: "number",
62
- description: "闹钟响铃类型:0=单次,1=法定节假日,2=每天,3=自定义,4=法定工作日,默认0",
51
+ description: "闹钟响铃类型,枚举值:0=单次响铃,1=法定节假日,2=每天,3=自定义时间,4=法定工作日,默认0",
63
52
  },
64
53
  daysOfWeek: {
65
54
  // 不指定 type,允许传入数组或 JSON 字符串
66
55
  // 具体的类型验证和转换在 execute 函数内部进行
67
- description: "自定义响铃星期(仅当daysOfWakeType=3时需要,其他情况不要传递),数组或JSON字符串,枚举值:Mon,Tue,Wed,Thu,Fri,Sat,Sun。注意:仅支持长度为1的数组,如果需要一周中不同的几天,需要多次调用此工具",
56
+ description: "自定义响铃星期,仅当daysOfWakeType=3(自定义时间)时必需且有效,其他情况不要传递此参数。数组或JSON字符串,枚举值:Mon,Tues,Wed,Thur,Fri,Sat,Sun",
68
57
  },
69
58
  },
70
59
  required: ["alarmTime"],
@@ -163,10 +152,6 @@ b. 使用该工具之前需获取当前真实时间
163
152
  if (!normalizedDaysOfWeek || normalizedDaysOfWeek.length === 0) {
164
153
  throw new Error("daysOfWeek array cannot be empty");
165
154
  }
166
- // 验证数组长度必须为1
167
- if (normalizedDaysOfWeek.length !== 1) {
168
- throw new Error("daysOfWeek 仅支持长度为1的数组。如果需要一周中不同的几天,需要多次调用此工具");
169
- }
170
155
  // Validate each day
171
156
  for (const day of normalizedDaysOfWeek) {
172
157
  if (typeof day !== "string" || !DAYS_OF_WEEK_VALUES.includes(day)) {
@@ -16,9 +16,6 @@ export const deleteAlarmTool = {
16
16
  label: "Delete Alarm",
17
17
  description: `删除用户设备上的闹钟。使用前必须先调用 search_alarm 或 create_alarm 工具获取闹钟的 entityId。
18
18
 
19
- 工具参数:
20
- - items: 要删除的闹钟列表,每个元素包含 entityId 字段。支持数组或 JSON 字符串格式。entityId 是闹钟的唯一标识符(从 search_alarm 或 create_alarm 工具获取)。
21
-
22
19
  使用示例:
23
20
  - 删除单个闹钟:{"items": [{"entityId": "6"}]}
24
21
  - 删除多个闹钟:{"items": [{"entityId": "6"}, {"entityId": "8"}]}
@@ -35,7 +32,7 @@ export const deleteAlarmTool = {
35
32
  items: {
36
33
  // 不指定 type,允许传入数组或 JSON 字符串
37
34
  // 具体的类型验证和转换在 execute 函数内部进行
38
- description: "要删除的闹钟列表,每个元素包含 entityId 字段。支持数组或 JSON 字符串格式。",
35
+ description: "要删除的闹钟列表,每个元素包含 entityId 字段。支持数组或 JSON 字符串格式。entityId 是闹钟的唯一标识符(从 search_alarm 或 create_alarm 工具获取)。",
39
36
  },
40
37
  },
41
38
  required: ["items"],
@@ -0,0 +1,4 @@
1
+ /** Known device type enum. */
2
+ export declare const DEVICE_TYPES: readonly ["car", "2in1", "phone"];
3
+ export type DeviceType = (typeof DEVICE_TYPES)[number];
4
+ export declare function filterToolsByDevice(tools: any[], deviceType?: string): any[];
@@ -0,0 +1,37 @@
1
+ // Device type to tool name mapping.
2
+ // Supports two modes:
3
+ // - allowlist: only listed tools are available (used for restrictive devices like car)
4
+ // - denylist: listed tools are blocked, everything else is available (used for permissive devices like pc)
5
+ // Tools NOT listed in any device entry → available to all devices (no restriction).
6
+ /** Known device type enum. */
7
+ export const DEVICE_TYPES = ["car", "2in1", "phone"];
8
+ const DEVICE_TOOL_POLICY = {
9
+ "2in1": {
10
+ allowlist: false,
11
+ tools: [
12
+ "xiaoyi_gui_agent",
13
+ "call_phone",
14
+ "send_message",
15
+ "search_message",
16
+ "search_contact",
17
+ "get_contact_tool_schema",
18
+ "query_collection",
19
+ "add_collection",
20
+ "delete_collection",
21
+ "get_collection_tool_schema",
22
+ ],
23
+ },
24
+ };
25
+ export function filterToolsByDevice(tools, deviceType) {
26
+ if (!deviceType)
27
+ return tools;
28
+ const policy = DEVICE_TOOL_POLICY[deviceType];
29
+ if (!policy)
30
+ return tools; // unrecognized device → no filtering
31
+ if (policy.allowlist) {
32
+ return tools.filter((tool) => policy.tools.includes(tool.name));
33
+ }
34
+ else {
35
+ return tools.filter((tool) => !policy.tools.includes(tool.name));
36
+ }
37
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * XY find PC devices tool - finds all PC devices associated with the user.
3
+ * Returns device IDs for use in subsequent file search operations.
4
+ */
5
+ export declare const findPcDevicesTool: any;
@@ -0,0 +1,98 @@
1
+ import { getXYWebSocketManager } from "../client.js";
2
+ import { sendCommand } from "../formatter.js";
3
+ import { getCurrentSessionContext } from "./session-manager.js";
4
+ /**
5
+ * XY find PC devices tool - finds all PC devices associated with the user.
6
+ * Returns device IDs for use in subsequent file search operations.
7
+ */
8
+ export const findPcDevicesTool = {
9
+ name: "find_pc_devices",
10
+ label: "Find PC Devices",
11
+ description: `查找用户所有PC/电脑设备,获取设备ID列表。当用户说"帮我找一下PC/电脑上的xxx文件"、"帮我搜索电脑上的xxx"等涉及PC设备的请求时,先调用此工具获取设备ID,再进行后续操作。注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,请严格遵守。`,
12
+ parameters: {
13
+ type: "object",
14
+ properties: {},
15
+ required: [],
16
+ },
17
+ async execute(toolCallId, params) {
18
+ // Get session context
19
+ const sessionContext = getCurrentSessionContext();
20
+ if (!sessionContext) {
21
+ throw new Error("No active XY session found. Find PC devices tool can only be used during an active conversation.");
22
+ }
23
+ const { config, sessionId, taskId, messageId } = sessionContext;
24
+ // Get WebSocket manager
25
+ const wsManager = getXYWebSocketManager(config);
26
+ // Build GetAllDevice command
27
+ const command = {
28
+ header: {
29
+ namespace: "Common",
30
+ name: "Action",
31
+ },
32
+ payload: {
33
+ cardParam: {},
34
+ executeParam: {
35
+ achieveType: "INTENT",
36
+ actionResponse: true,
37
+ bundleName: "com.huawei.hmos.aidispatchservice",
38
+ dimension: "",
39
+ executeMode: "background",
40
+ intentName: "GetAllDevice",
41
+ intentParam: {},
42
+ needUnlock: true,
43
+ permissionId: [],
44
+ timeOut: 5,
45
+ },
46
+ needUploadResult: true,
47
+ pageControlRelated: false,
48
+ responses: [{
49
+ displayText: "",
50
+ resultCode: "",
51
+ ttsText: "",
52
+ }],
53
+ },
54
+ };
55
+ // Send command and wait for response (60 second timeout)
56
+ return new Promise((resolve, reject) => {
57
+ const timeout = setTimeout(() => {
58
+ wsManager.off("data-event", handler);
59
+ reject(new Error("查找PC设备超时(60秒)"));
60
+ }, 60000);
61
+ // Listen for data events from WebSocket
62
+ const handler = (event) => {
63
+ if (event.intentName === "GetAllDevice") {
64
+ clearTimeout(timeout);
65
+ wsManager.off("data-event", handler);
66
+ if (event.status === "success" && event.outputs) {
67
+ resolve({
68
+ content: [
69
+ {
70
+ type: "text",
71
+ text: JSON.stringify(event.outputs),
72
+ }
73
+ ]
74
+ });
75
+ }
76
+ else {
77
+ reject(new Error(`查找PC设备失败: ${event.status}`));
78
+ }
79
+ }
80
+ };
81
+ // Register event handler
82
+ wsManager.on("data-event", handler);
83
+ // Send the command
84
+ sendCommand({
85
+ config,
86
+ sessionId,
87
+ taskId,
88
+ messageId,
89
+ command,
90
+ }).then(() => {
91
+ }).catch((error) => {
92
+ clearTimeout(timeout);
93
+ wsManager.off("data-event", handler);
94
+ reject(error);
95
+ });
96
+ });
97
+ },
98
+ };
@@ -0,0 +1,16 @@
1
+ export declare const getAlarmToolSchemaTool: {
2
+ name: string;
3
+ label: string;
4
+ description: string;
5
+ parameters: {
6
+ type: "object";
7
+ properties: {};
8
+ required: string[];
9
+ };
10
+ execute(_toolCallId: string, _params: any): Promise<{
11
+ content: {
12
+ type: "text";
13
+ text: string;
14
+ }[];
15
+ }>;
16
+ };
@@ -0,0 +1,11 @@
1
+ import { createSchemaTool } from "./schema-tool-factory.js";
2
+ import { createAlarmTool } from "./create-alarm-tool.js";
3
+ import { searchAlarmTool } from "./search-alarm-tool.js";
4
+ import { modifyAlarmTool } from "./modify-alarm-tool.js";
5
+ import { deleteAlarmTool } from "./delete-alarm-tool.js";
6
+ export const getAlarmToolSchemaTool = createSchemaTool({
7
+ name: "get_alarm_tool_schema",
8
+ label: "Get Alarm Tool Schema",
9
+ description: "获取可在用户设备上创建、检索、修改、删除闹钟的相关端工具列表。",
10
+ tools: [createAlarmTool, searchAlarmTool, modifyAlarmTool, deleteAlarmTool],
11
+ });
@@ -0,0 +1,16 @@
1
+ export declare const getCalendarToolSchemaTool: {
2
+ name: string;
3
+ label: string;
4
+ description: string;
5
+ parameters: {
6
+ type: "object";
7
+ properties: {};
8
+ required: string[];
9
+ };
10
+ execute(_toolCallId: string, _params: any): Promise<{
11
+ content: {
12
+ type: "text";
13
+ text: string;
14
+ }[];
15
+ }>;
16
+ };
@@ -0,0 +1,9 @@
1
+ import { createSchemaTool } from "./schema-tool-factory.js";
2
+ import { calendarTool } from "./calendar-tool.js";
3
+ import { searchCalendarTool } from "./search-calendar-tool.js";
4
+ export const getCalendarToolSchemaTool = createSchemaTool({
5
+ name: "get_calendar_tool_schema",
6
+ label: "Get Calendar Tool Schema",
7
+ description: "获取可在用户设备上创建、检索日程的相关端工具列表。",
8
+ tools: [calendarTool, searchCalendarTool],
9
+ });