@ynhcj/xiaoyi-channel 0.0.75-beta → 0.0.77-beta

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.
@@ -24,11 +24,11 @@ import { sendFileToUserTool } from "./tools/send-file-to-user-tool.js";
24
24
  import { viewPushResultTool } from "./tools/view-push-result-tool.js";
25
25
  import { imageReadingTool } from "./tools/image-reading-tool.js";
26
26
  import { timestampToUtc8Tool } from "./tools/timestamp-to-utc8-tool.js";
27
- import { sendCommandToCarTool } from "./tools/send-command-to-car-tool.js";
28
27
  import { xiaoyiCollectionTool } from "./tools/xiaoyi-collection-tool.js";
29
28
  import { xiaoyiAddCollectionTool } from "./tools/xiaoyi-add-collection-tool.js";
30
29
  import { xiaoyiDeleteCollectionTool } from "./tools/xiaoyi-delete-collection-tool.js";
31
30
  import { saveMediaToGalleryTool } from "./tools/save-media-to-gallery-tool.js";
31
+ import { saveFileToPhoneTool } from "./tools/save-file-to-phone-tool.js";
32
32
  import { filterToolsByDevice } from "./tools/device-tool-map.js";
33
33
  import { getCurrentSessionContext } from "./tools/session-manager.js";
34
34
  import { logger } from "./utils/logger.js";
@@ -71,7 +71,7 @@ export const xyPlugin = {
71
71
  },
72
72
  outbound: xyOutbound,
73
73
  agentTools: () => {
74
- const allTools = [locationTool, noteTool, searchNoteTool, modifyNoteTool, calendarTool, searchCalendarTool, searchContactTool, searchPhotoGalleryTool, uploadPhotoTool, xiaoyiGuiTool, callPhoneTool, searchMessageTool, sendMessageTool, searchFileTool, uploadFileTool, createAlarmTool, searchAlarmTool, modifyAlarmTool, deleteAlarmTool, sendFileToUserTool, viewPushResultTool, imageReadingTool, timestampToUtc8Tool, sendCommandToCarTool, xiaoyiCollectionTool, xiaoyiAddCollectionTool, xiaoyiDeleteCollectionTool, saveMediaToGalleryTool];
74
+ const allTools = [locationTool, noteTool, searchNoteTool, modifyNoteTool, calendarTool, searchCalendarTool, searchContactTool, searchPhotoGalleryTool, uploadPhotoTool, xiaoyiGuiTool, callPhoneTool, searchMessageTool, sendMessageTool, searchFileTool, uploadFileTool, createAlarmTool, searchAlarmTool, modifyAlarmTool, deleteAlarmTool, sendFileToUserTool, viewPushResultTool, imageReadingTool, timestampToUtc8Tool, xiaoyiCollectionTool, xiaoyiAddCollectionTool, xiaoyiDeleteCollectionTool, saveMediaToGalleryTool, saveFileToPhoneTool];
75
75
  const ctx = getCurrentSessionContext();
76
76
  const filtered = filterToolsByDevice(allTools, ctx?.deviceType);
77
77
  logger.log(`[DEVICE-FILTER] deviceType=${ctx?.deviceType ?? "(none)"}, tools: ${allTools.length} → ${filtered.length} (${filtered.map(t => t.name).join(", ")})`);
@@ -1,3 +1,13 @@
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";
1
11
  import { getCurrentSessionContext } from "./tools/session-manager.js";
2
12
  /**
3
13
  * Dynamic header keys injected via extraParams and forwarded to the HTTP request.
@@ -8,10 +18,10 @@ const HEADER_TRACE_ID = "x-hag-trace-id";
8
18
  const HEADER_SESSION_ID = "x-session-id";
9
19
  const HEADER_INTERACTION_ID = "x-interaction-id";
10
20
  /**
11
- * Encode uid to base64 and take first 32 chars.
21
+ * Encode uid via SHA-256 and take first 32 hex chars.
12
22
  */
13
23
  function encodeUid(uid) {
14
- return Buffer.from(uid).toString("base64").slice(0, 32);
24
+ return createHash("sha256").update(uid).digest("hex").slice(0, 32);
15
25
  }
16
26
  /**
17
27
  * Get uid from plugin config (OpenClawConfig -> plugins -> xiaoyi-channel -> config).
@@ -31,7 +41,7 @@ export const xiaoyiProvider = {
31
41
  *
32
42
  * Priority:
33
43
  * 1. Session context (from AsyncLocalStorage, set by bot.ts)
34
- * 2. uid-based fallback: base64(uid)[:32]_timestamp
44
+ * 2. uid-based fallback: sha256(uid).hex[:32]_timestamp
35
45
  * 3. No uid available → return undefined (no headers injected)
36
46
  */
37
47
  prepareExtraParams: (ctx) => {
@@ -72,21 +82,20 @@ export const xiaoyiProvider = {
72
82
  const underlying = ctx.streamFn;
73
83
  if (!underlying)
74
84
  return underlying;
75
- const dynamicHeaders = {};
76
- if (ctx.extraParams) {
77
- const traceId = ctx.extraParams[HEADER_TRACE_ID];
78
- const sessionId = ctx.extraParams[HEADER_SESSION_ID];
79
- const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
80
- if (typeof traceId === "string")
81
- dynamicHeaders[HEADER_TRACE_ID] = traceId;
82
- if (typeof sessionId === "string")
83
- dynamicHeaders[HEADER_SESSION_ID] = sessionId;
84
- if (typeof interactionId === "string")
85
- dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
86
- }
87
- if (Object.keys(dynamicHeaders).length === 0)
88
- return underlying;
89
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
+ }
90
99
  // 记录输入
91
100
  console.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
92
101
  if (context.systemPrompt) {
@@ -13,7 +13,6 @@ const DEVICE_TOOL_POLICY = {
13
13
  "call_phone",
14
14
  "send_message",
15
15
  "search_message",
16
- "send_command_to_car",
17
16
  "search_contact",
18
17
  "QueryCollection",
19
18
  "AddCollection",
@@ -0,0 +1,5 @@
1
+ /**
2
+ * XY save file to phone tool - saves files to user's device file manager.
3
+ * Supports local file paths (auto-uploaded to get public URL) and public URLs.
4
+ */
5
+ export declare const saveFileToPhoneTool: any;
@@ -0,0 +1,170 @@
1
+ import { getXYWebSocketManager } from "../client.js";
2
+ import { sendCommand } from "../formatter.js";
3
+ import { getCurrentSessionContext } from "./session-manager.js";
4
+ import { XYFileUploadService } from "../file-upload.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 save file to phone tool - saves files to user's device file manager.
19
+ * Supports local file paths (auto-uploaded to get public URL) and public URLs.
20
+ */
21
+ export const saveFileToPhoneTool = {
22
+ name: "SaveFileToFileManager",
23
+ label: "Save File to Phone",
24
+ description: `将文件保存到手机文件管理器。
25
+ 工具参数说明:
26
+ a. fileName:必填,string类型,文件名称。
27
+ b. url:必填,string类型,支持本地路径或者公网url路径。如果是本地路径,会先上传获取公网url再保存到手机。
28
+ c. suffix:必填,string类型,文件后缀,例如 ppt、doc、pdf 等。
29
+
30
+ 注意:
31
+ a. 操作超时时间为60秒,请勿重复调用此工具
32
+ b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。
33
+ c. 调用工具前需认真检查调用参数是否满足工具要求
34
+
35
+ 回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。
36
+ `,
37
+ parameters: {
38
+ type: "object",
39
+ properties: {
40
+ fileName: {
41
+ type: "string",
42
+ description: "必填,文件名称。",
43
+ },
44
+ url: {
45
+ type: "string",
46
+ description: "必填,支持本地路径或者公网url路径。如果是本地路径会先上传获取公网url。",
47
+ },
48
+ suffix: {
49
+ type: "string",
50
+ description: "必填,文件后缀,例如 ppt、doc、pdf 等。",
51
+ },
52
+ },
53
+ required: ["fileName", "url", "suffix"],
54
+ },
55
+ async execute(toolCallId, params) {
56
+ // Validate parameters
57
+ const { fileName, url, suffix } = params;
58
+ if (!url || typeof url !== "string") {
59
+ throw new ToolInputError("缺少必填参数: url");
60
+ }
61
+ if (!fileName || typeof fileName !== "string") {
62
+ throw new ToolInputError("缺少必填参数: fileName");
63
+ }
64
+ if (!suffix || typeof suffix !== "string") {
65
+ throw new ToolInputError("缺少必填参数: suffix");
66
+ }
67
+ // Get session context
68
+ const sessionContext = getCurrentSessionContext();
69
+ if (!sessionContext) {
70
+ throw new Error("No active XY session found. SaveFileToFileManager tool can only be used during an active conversation.");
71
+ }
72
+ const { config, sessionId, taskId, messageId } = sessionContext;
73
+ // Get WebSocket manager
74
+ const wsManager = getXYWebSocketManager(config);
75
+ // Determine the URL: if it's a local path, upload first to get public URL
76
+ let publicUrl = url;
77
+ if (!url.startsWith("http://") && !url.startsWith("https://")) {
78
+ // Local file path - upload to get public URL
79
+ const uploadService = new XYFileUploadService(config.fileUploadUrl, config.apiKey, config.uid);
80
+ publicUrl = await uploadService.uploadFileAndGetUrl(url);
81
+ if (!publicUrl) {
82
+ throw new Error("本地文件上传失败,无法获取公网URL");
83
+ }
84
+ }
85
+ // Build intentParam
86
+ const intentParam = {
87
+ fileName: fileName,
88
+ url: publicUrl,
89
+ suffix: suffix,
90
+ };
91
+ // Build SaveFileToFileManager command
92
+ const command = {
93
+ header: {
94
+ namespace: "Common",
95
+ name: "Action",
96
+ },
97
+ payload: {
98
+ cardParam: {},
99
+ executeParam: {
100
+ executeMode: "background",
101
+ intentName: "SaveFileToFileManager",
102
+ bundleName: "com.huawei.hmos.vassistant",
103
+ dimension: "",
104
+ needUnlock: true,
105
+ actionResponse: true,
106
+ appType: "OHOS_APP",
107
+ timeOut: 5,
108
+ timeout: 1000,
109
+ intentParam,
110
+ permissionId: ["ohos.permission.WRITE_IMAGEVIDEO"],
111
+ achieveType: "INTENT",
112
+ },
113
+ responses: [
114
+ {
115
+ resultCode: "",
116
+ displayText: "",
117
+ ttsText: "",
118
+ },
119
+ ],
120
+ needUploadResult: true,
121
+ noHalfPage: false,
122
+ pageControlRelated: false,
123
+ },
124
+ };
125
+ // Send command and wait for response (60 second timeout)
126
+ return new Promise((resolve, reject) => {
127
+ const timeout = setTimeout(() => {
128
+ wsManager.off("data-event", handler);
129
+ reject(new Error("保存文件到手机超时(60秒)"));
130
+ }, 60000);
131
+ // Listen for data events from WebSocket
132
+ const handler = (event) => {
133
+ if (event.intentName === "SaveFileToFileManager") {
134
+ clearTimeout(timeout);
135
+ wsManager.off("data-event", handler);
136
+ if (event.status === "success" && event.outputs) {
137
+ resolve({
138
+ content: [
139
+ {
140
+ type: "text",
141
+ text: JSON.stringify(event.outputs),
142
+ }
143
+ ]
144
+ });
145
+ }
146
+ else {
147
+ reject(new Error(`保存文件到手机失败: ${event.status}`));
148
+ }
149
+ }
150
+ };
151
+ // Register event handler
152
+ wsManager.on("data-event", handler);
153
+ // Send the command
154
+ sendCommand({
155
+ config,
156
+ sessionId,
157
+ taskId,
158
+ messageId,
159
+ command,
160
+ })
161
+ .then(() => {
162
+ })
163
+ .catch((error) => {
164
+ clearTimeout(timeout);
165
+ wsManager.off("data-event", handler);
166
+ reject(error);
167
+ });
168
+ });
169
+ },
170
+ };
@@ -20,7 +20,14 @@ class ToolInputError extends Error {
20
20
  export const xiaoyiAddCollectionTool = {
21
21
  name: "AddCollection",
22
22
  label: "Add XiaoYi Collection",
23
- description: `向小艺收藏中添加公共知识数据,可以给用户提供个性化体验。用户希望保存到个人化知识库中的数据都可以调用本技能。不同类型的数据对应的数据要求如下:
23
+ description: `向小艺收藏中添加公共知识数据,可以给用户提供个性化体验。任何用户希望保存到个人化知识库中的数据都可以调用本技能。不同类型的数据对应的数据要求如下:
24
+ 请求入参说明:
25
+ ● content:必填字段,数据类型为string,功能描述是该字段是用户添加收藏的链接url或文本原文。适用于HYPER_LINK和TEXT类型。
26
+ ● uri:必填字段,数据类型为string,功能描述是该字段是图片或文件的端存储地址链接。适用于IMAGE和FILE类型。
27
+ ● sourceAppBundleName:非必填字段,数据类型为string,功能描述是标识该数据的来源应用。
28
+ ● dataType:必填字段,数据类型为string,功能描述是标识数据类型。HYPER_LINK标识网页,TEXT标识文本,IMAGE标识图片,FILE标识文件。
29
+ ● title:非必填字段,数据类型为string,功能描述是标识文件类型数据的文件名称。适用于FILE类型。
30
+ 说明:如果dataType为HYPER_LINK或TEXT,则content字段必填且不能为空;如果dataType为IMAGE或FILE,则uri字段必填且不能为空。当用户希望收藏海报、截图等图片类数据时,请将数据以图片IMAGE的形式存入到小艺帮记;当用户希望收藏电子书、笔记、报告、素材、文档、合同、协议、简历、证书、报表、日志、安装包、压缩包等描述的文件时,请将数据以文件FILE的形式存入到小艺帮记。
24
31
  注意:
25
32
  a. 操作超时时间为60秒,请勿重复调用此工具
26
33
  b. 如果遇到各类调用失败场景,最多只能重试一次,不可以重复调用多次。
@@ -47,12 +54,16 @@ export const xiaoyiAddCollectionTool = {
47
54
  type: "string",
48
55
  description: "必填字段。标识数据类型:HYPER_LINK表示网页,TEXT表示文本,IMAGE表示图片,FILE表示文件。",
49
56
  },
57
+ title: {
58
+ type: "string",
59
+ description: "非必填字段。标识文件类型数据的文件名称。适用于FILE类型。",
60
+ },
50
61
  },
51
62
  required: ["dataType"],
52
63
  },
53
64
  async execute(toolCallId, params) {
54
65
  // Validate parameters
55
- const { content, uri, sourceAppBundleName, dataType } = params;
66
+ const { content, uri, sourceAppBundleName, dataType, title } = params;
56
67
  const validTypes = ["HYPER_LINK", "TEXT", "IMAGE", "FILE"];
57
68
  if (!dataType || !validTypes.includes(dataType)) {
58
69
  throw new ToolInputError(`dataType必填且必须为 HYPER_LINK、TEXT、IMAGE、FILE 之一,当前值: ${dataType}`);
@@ -93,6 +104,9 @@ export const xiaoyiAddCollectionTool = {
93
104
  if (sourceAppBundleName) {
94
105
  intentParam.sourceAppBundleName = sourceAppBundleName;
95
106
  }
107
+ if (title) {
108
+ intentParam.title = title;
109
+ }
96
110
  // Build AddCollection command
97
111
  const command = {
98
112
  header: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ynhcj/xiaoyi-channel",
3
- "version": "0.0.75-beta",
3
+ "version": "0.0.77-beta",
4
4
  "description": "OpenClaw Xiaoyi Channel plugin - Xiaoyi A2A protocol integration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",