@ynhcj/xiaoyi-channel 0.0.41-beta → 0.0.41-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 (76) hide show
  1. package/dist/index.d.ts +0 -2
  2. package/dist/index.js +42 -2
  3. package/dist/src/bot.d.ts +1 -0
  4. package/dist/src/bot.js +97 -60
  5. package/dist/src/channel.js +30 -4
  6. package/dist/src/client.js +0 -9
  7. package/dist/src/cspl/call-api.d.ts +3 -0
  8. package/dist/src/cspl/call-api.js +86 -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 +88 -6
  17. package/dist/src/formatter.d.ts +16 -0
  18. package/dist/src/formatter.js +59 -30
  19. package/dist/src/heartbeat.js +0 -4
  20. package/dist/src/monitor.js +8 -10
  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 +3 -21
  25. package/dist/src/parser.d.ts +13 -0
  26. package/dist/src/parser.js +38 -0
  27. package/dist/src/push.d.ts +2 -1
  28. package/dist/src/push.js +6 -34
  29. package/dist/src/reply-dispatcher.d.ts +4 -0
  30. package/dist/src/reply-dispatcher.js +46 -8
  31. package/dist/src/steer-injector.d.ts +16 -0
  32. package/dist/src/steer-injector.js +74 -0
  33. package/dist/src/thread-bindings.d.ts +54 -0
  34. package/dist/src/thread-bindings.js +214 -0
  35. package/dist/src/tools/calendar-tool.js +2 -37
  36. package/dist/src/tools/call-phone-tool.js +3 -60
  37. package/dist/src/tools/create-alarm-tool.js +8 -109
  38. package/dist/src/tools/delete-alarm-tool.js +5 -69
  39. package/dist/src/tools/device-tool-map.d.ts +4 -0
  40. package/dist/src/tools/device-tool-map.js +23 -0
  41. package/dist/src/tools/image-reading-tool.d.ts +5 -0
  42. package/dist/src/tools/image-reading-tool.js +328 -0
  43. package/dist/src/tools/location-tool.js +6 -40
  44. package/dist/src/tools/modify-alarm-tool.js +8 -114
  45. package/dist/src/tools/modify-note-tool.js +3 -41
  46. package/dist/src/tools/note-tool.js +4 -16
  47. package/dist/src/tools/search-alarm-tool.js +12 -118
  48. package/dist/src/tools/search-calendar-tool.js +4 -81
  49. package/dist/src/tools/search-contact-tool.js +2 -55
  50. package/dist/src/tools/search-file-tool.js +4 -61
  51. package/dist/src/tools/search-message-tool.js +2 -59
  52. package/dist/src/tools/search-note-tool.js +4 -22
  53. package/dist/src/tools/search-photo-gallery-tool.js +8 -57
  54. package/dist/src/tools/send-command-to-car-tool.d.ts +5 -0
  55. package/dist/src/tools/send-command-to-car-tool.js +85 -0
  56. package/dist/src/tools/send-file-to-user-tool.js +1 -39
  57. package/dist/src/tools/send-message-tool.js +5 -56
  58. package/dist/src/tools/session-manager.d.ts +1 -0
  59. package/dist/src/tools/session-manager.js +0 -45
  60. package/dist/src/tools/timestamp-to-utc8-tool.d.ts +12 -0
  61. package/dist/src/tools/timestamp-to-utc8-tool.js +104 -0
  62. package/dist/src/tools/upload-file-tool.js +0 -49
  63. package/dist/src/tools/upload-photo-tool.js +0 -42
  64. package/dist/src/tools/view-push-result-tool.js +0 -11
  65. package/dist/src/tools/xiaoyi-collection-tool.js +4 -82
  66. package/dist/src/tools/xiaoyi-gui-tool.js +0 -34
  67. package/dist/src/trigger-handler.d.ts +3 -0
  68. package/dist/src/trigger-handler.js +18 -50
  69. package/dist/src/utils/runtime-manager.d.ts +7 -0
  70. package/dist/src/utils/runtime-manager.js +42 -0
  71. package/dist/src/websocket.js +33 -13
  72. package/package.json +3 -4
  73. package/dist/src/tools/search-photo-tool.d.ts +0 -9
  74. package/dist/src/tools/search-photo-tool.js +0 -270
  75. package/dist/src/utils/session.d.ts +0 -34
  76. package/dist/src/utils/session.js +0 -50
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
- import { xyPlugin } from "./src/channel.js";
3
2
  /**
4
3
  * Xiaoyi Channel Plugin Entry Point.
5
4
  * Exports the plugin for OpenClaw to load.
@@ -13,4 +12,3 @@ declare const plugin: {
13
12
  register(api: OpenClawPluginApi): void;
14
13
  };
15
14
  export default plugin;
16
- export { xyPlugin };
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
2
2
  import { xyPlugin } from "./src/channel.js";
3
3
  import { setXYRuntime } from "./src/runtime.js";
4
+ import { tryInjectSteer } from "./src/steer-injector.js";
5
+ import { callCsplApi } from "./src/cspl/call-api.js";
6
+ import { extractResultText, processText, parseSecurityResult, validateAndTruncateText } from "./src/cspl/utils.js";
7
+ import { ALLOWED_TOOLS, MIN_TEXT_LENGTH, MAX_TOTAL_LENGTH, MAX_TEXT_LENGTH, STEER_ABORT_MESSAGE, } from "./src/cspl/constants.js";
4
8
  /**
5
9
  * Xiaoyi Channel Plugin Entry Point.
6
10
  * Exports the plugin for OpenClaw to load.
@@ -14,8 +18,44 @@ const plugin = {
14
18
  register(api) {
15
19
  setXYRuntime(api.runtime);
16
20
  api.registerChannel({ plugin: xyPlugin });
21
+ // CSPL after_tool_call hook: 监听工具结果,发送至 CSPL API 进行安全检测
22
+ // 如果响应为 REJECT,注入 steer 消息中止当前对话
23
+ api.on("after_tool_call", async (event, ctx) => {
24
+ if (!ALLOWED_TOOLS.includes(event.toolName)) {
25
+ return;
26
+ }
27
+ console.log(`[CSPL] after_tool_call triggered: toolName=${event.toolName}, sessionKey=${ctx.sessionKey ?? "none"}`);
28
+ try {
29
+ const resultText = extractResultText(event, event.toolName);
30
+ const resultLength = resultText.length;
31
+ if (resultLength <= MIN_TEXT_LENGTH || resultLength > MAX_TOTAL_LENGTH) {
32
+ return;
33
+ }
34
+ // 构造 sentinel_hook 格式的 payload: { tool, output: [{ content }] }
35
+ const questionText = {
36
+ tool: event.toolName,
37
+ output: [{ content: "" }],
38
+ };
39
+ const originText = processText(resultText);
40
+ questionText.output[0].content = originText;
41
+ let finalJson = JSON.stringify(questionText);
42
+ if (finalJson.length > MAX_TEXT_LENGTH) {
43
+ const diff = finalJson.length - MAX_TEXT_LENGTH;
44
+ const { text: trimmed } = validateAndTruncateText(originText, MAX_TEXT_LENGTH - diff);
45
+ questionText.output[0].content = trimmed;
46
+ finalJson = JSON.stringify(questionText);
47
+ }
48
+ const response = await callCsplApi(finalJson, api.config);
49
+ const result = parseSecurityResult(response);
50
+ console.log(`[CSPL] Security result: status=${result.status}`);
51
+ if (result.status === "REJECT") {
52
+ await tryInjectSteer(ctx.sessionKey, STEER_ABORT_MESSAGE);
53
+ }
54
+ }
55
+ catch (err) {
56
+ api.logger.error(`[CSPL] after_tool_call error: ${err}`);
57
+ }
58
+ });
17
59
  },
18
60
  };
19
61
  export default plugin;
20
- // Also export the plugin directly for testing
21
- export { xyPlugin };
package/dist/src/bot.d.ts CHANGED
@@ -8,6 +8,7 @@ export interface HandleXYMessageParams {
8
8
  runtime: RuntimeEnv;
9
9
  message: A2AJsonRpcRequest;
10
10
  accountId: string;
11
+ webSocketSessionId?: string;
11
12
  }
12
13
  /**
13
14
  * Handle an incoming A2A message.
package/dist/src/bot.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import { getXYRuntime } from "./runtime.js";
2
+ import { setCachedContext } from "./steer-injector.js";
2
3
  import { createXYReplyDispatcher } from "./reply-dispatcher.js";
3
- import { parseA2AMessage, extractTextFromParts, extractFileParts, extractPushId } from "./parser.js";
4
+ import { parseA2AMessage, extractTextFromParts, extractFileParts, extractPushId, extractDeviceType, extractTriggerData } from "./parser.js";
5
+ import { downloadFilesFromParts } from "./file-download.js";
4
6
  import { resolveXYConfig } from "./config.js";
5
- import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse } from "./formatter.js";
7
+ import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse, sendA2AResponse } from "./formatter.js";
6
8
  import { registerSession, unregisterSession, runWithSessionContext } from "./tools/session-manager.js";
7
9
  import { configManager } from "./utils/config-manager.js";
8
10
  import { addPushId } from "./utils/pushid-manager.js";
11
+ import { getPushDataById } from "./utils/pushdata-manager.js";
12
+ import { saveRuntimeInfo } from "./utils/runtime-manager.js";
9
13
  import { registerTaskId, decrementTaskIdRef, lockTaskId, unlockTaskId, hasActiveTask, } from "./task-manager.js";
10
14
  /**
11
15
  * Handle an incoming A2A message.
@@ -13,16 +17,16 @@ import { registerTaskId, decrementTaskIdRef, lockTaskId, unlockTaskId, hasActive
13
17
  * Runtime is expected to be validated before calling this function.
14
18
  */
15
19
  export async function handleXYMessage(params) {
16
- const { cfg, runtime, message, accountId } = params;
20
+ const { cfg, runtime, message, accountId, webSocketSessionId } = params;
17
21
  const log = runtime?.log ?? console.log;
18
22
  const error = runtime?.error ?? console.error;
23
+ // 每次收到消息时更新缓存,供 steer 注入使用
24
+ setCachedContext(cfg, runtime, accountId);
19
25
  // Get runtime (already validated in monitor.ts, but get reference for use)
20
26
  const core = getXYRuntime();
21
27
  try {
22
28
  // Check for special messages BEFORE parsing (these have different param structures)
23
29
  const messageMethod = message.method;
24
- log(`[BOT-ENTRY] <<<<<<< Received message with method: ${messageMethod}, id: ${message.id} >>>>>>>`);
25
- log(`[BOT-ENTRY] Stack trace for debugging:`, new Error().stack?.split('\n').slice(1, 4).join('\n'));
26
30
  // Handle clearContext messages (params only has sessionId)
27
31
  if (messageMethod === "clearContext" || messageMethod === "clear_context") {
28
32
  const sessionId = message.params?.sessionId;
@@ -57,6 +61,42 @@ export async function handleXYMessage(params) {
57
61
  }
58
62
  // Parse the A2A message (for regular messages)
59
63
  const parsed = parseA2AMessage(message);
64
+ // ========== 检测 Trigger 消息 ==========
65
+ // 如果消息中包含 Trigger 事件数据,直接返回 pushData 内容,不走正常流程
66
+ const triggerData = extractTriggerData(parsed.parts);
67
+ if (triggerData) {
68
+ log(`[BOT] 📌 Detected Trigger message with pushDataId: ${triggerData.pushDataId}`);
69
+ log(`[BOT] - Session ID: ${parsed.sessionId}`);
70
+ log(`[BOT] - Task ID: ${parsed.taskId}`);
71
+ try {
72
+ // 读取 pushData
73
+ const pushDataItem = await getPushDataById(triggerData.pushDataId);
74
+ if (!pushDataItem) {
75
+ error(`[BOT] ❌ pushData not found for ID: ${triggerData.pushDataId}`);
76
+ return;
77
+ }
78
+ log(`[BOT] ✅ Found pushData, sending direct response`);
79
+ log(`[BOT] - pushDataId: ${pushDataItem.pushDataId}`);
80
+ const config = resolveXYConfig(cfg);
81
+ // 直接发送响应(final=true,不走 openclaw 流程)
82
+ await sendA2AResponse({
83
+ config,
84
+ sessionId: parsed.sessionId,
85
+ taskId: parsed.taskId,
86
+ messageId: parsed.messageId,
87
+ text: pushDataItem.dataDetail,
88
+ append: false,
89
+ final: true,
90
+ });
91
+ log(`[BOT] ✅ Trigger response sent successfully, exiting early`);
92
+ return; // 提前返回,不继续处理
93
+ }
94
+ catch (err) {
95
+ error(`[BOT] ❌ Failed to handle Trigger message:`, err);
96
+ return;
97
+ }
98
+ }
99
+ // ========================================
60
100
  // 🔑 检测steer模式和是否是第二条消息
61
101
  const isSteerMode = cfg.messages?.queue?.mode === "steer";
62
102
  const isSecondMessage = isSteerMode && hasActiveTask(parsed.sessionId);
@@ -77,9 +117,6 @@ export async function handleXYMessage(params) {
77
117
  const pushId = extractPushId(parsed.parts);
78
118
  if (pushId) {
79
119
  log(`[BOT] 📌 Extracted push_id from user message`);
80
- log(`[BOT] - Session ID: ${parsed.sessionId}`);
81
- log(`[BOT] - Push ID preview: ${pushId.substring(0, 20)}...`);
82
- log(`[BOT] - Full push_id: ${pushId}`);
83
120
  configManager.updatePushId(parsed.sessionId, pushId);
84
121
  // 持久化 pushId 到本地文件(异步,不阻塞主流程)
85
122
  addPushId(pushId).catch((err) => {
@@ -89,6 +126,18 @@ export async function handleXYMessage(params) {
89
126
  else {
90
127
  log(`[BOT] ℹ️ No push_id found in message, will use config default`);
91
128
  }
129
+ // Extract deviceType if present (same level as push_id in systemVariables)
130
+ const deviceType = extractDeviceType(parsed.parts);
131
+ if (deviceType) {
132
+ log(`[BOT] 📱 Extracted deviceType from user message: ${deviceType}`);
133
+ }
134
+ // 保存 runtime 信息到 .xiaoyiruntime 文件(异步,不阻塞主流程)
135
+ saveRuntimeInfo(webSocketSessionId || parsed.sessionId, // SESSION_ID (WebSocket 层级,如果没有则 fallback)
136
+ parsed.sessionId, // CONVERSATION_ID (param 里的 sessionId)
137
+ parsed.taskId // TASK_ID (param.id)
138
+ ).catch((err) => {
139
+ error(`[BOT] Failed to save runtime info:`, err);
140
+ });
92
141
  // Resolve configuration (needed for status updates)
93
142
  const config = resolveXYConfig(cfg);
94
143
  // ✅ Resolve agent route (following feishu pattern)
@@ -104,12 +153,6 @@ export async function handleXYMessage(params) {
104
153
  },
105
154
  });
106
155
  log(`xy: resolved route accountId=${route.accountId}, sessionKey=${route.sessionKey}`);
107
- // 🔑 注册session(带引用计数)
108
- log(`[BOT] 📝 About to register session for tools...`);
109
- log(`[BOT] - sessionKey: ${route.sessionKey}`);
110
- log(`[BOT] - sessionId: ${parsed.sessionId}`);
111
- log(`[BOT] - taskId: ${parsed.taskId}`);
112
- log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
113
156
  registerSession(route.sessionKey, {
114
157
  config,
115
158
  sessionId: parsed.sessionId,
@@ -117,7 +160,6 @@ export async function handleXYMessage(params) {
117
160
  messageId: parsed.messageId,
118
161
  agentId: route.accountId,
119
162
  });
120
- log(`[BOT] ✅ Session registered for tools`);
121
163
  // 🔑 发送初始状态更新(第二条消息也要发,用新taskId)
122
164
  log(`[STATUS] Sending initial status update for session ${parsed.sessionId}`);
123
165
  void sendStatusUpdate({
@@ -125,7 +167,7 @@ export async function handleXYMessage(params) {
125
167
  sessionId: parsed.sessionId,
126
168
  taskId: parsed.taskId,
127
169
  messageId: parsed.messageId,
128
- text: isSecondMessage ? "新消息已接收,正在处理..." : "任务正在处理中,请稍后~",
170
+ text: isSecondMessage ? "新消息已接收,正在处理..." : "任务正在处理中,请稍候~",
129
171
  state: "working",
130
172
  }).catch((err) => {
131
173
  error(`Failed to send initial status update:`, err);
@@ -133,9 +175,9 @@ export async function handleXYMessage(params) {
133
175
  // Extract text and files from parts
134
176
  const text = extractTextFromParts(parsed.parts);
135
177
  const fileParts = extractFileParts(parsed.parts);
136
- // Build media payload directly from file URIs (openclaw can download them)
137
- // No need to download files locally - pass URIs directly to openclaw
138
- const mediaPayload = buildXYMediaPayload(fileParts);
178
+ // Download files to local disk
179
+ const downloadedFiles = await downloadFilesFromParts(fileParts);
180
+ const mediaPayload = buildXYMediaPayload(downloadedFiles);
139
181
  // Resolve envelope format options (following feishu pattern)
140
182
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
141
183
  // Build message body with speaker prefix (following feishu pattern)
@@ -178,9 +220,7 @@ export async function handleXYMessage(params) {
178
220
  });
179
221
  // 🔑 创建dispatcher(dispatcher会自动使用动态taskId)
180
222
  log(`[BOT-DISPATCHER] 🎯 Creating reply dispatcher`);
181
- log(`[BOT-DISPATCHER] - session: ${parsed.sessionId}`);
182
223
  log(`[BOT-DISPATCHER] - taskId: ${parsed.taskId}`);
183
- log(`[BOT-DISPATCHER] - isSecondMessage: ${isSecondMessage}`);
184
224
  const { dispatcher, replyOptions, markDispatchIdle, startStatusInterval } = createXYReplyDispatcher({
185
225
  cfg,
186
226
  runtime,
@@ -190,19 +230,12 @@ export async function handleXYMessage(params) {
190
230
  accountId: route.accountId,
191
231
  isSteerFollower: isSecondMessage, // 🔑 标记第二条消息
192
232
  });
193
- log(`[BOT-DISPATCHER] ✅ Reply dispatcher created successfully`);
194
233
  // 🔑 只有第一条消息启动状态定时器
195
234
  // 第二条消息会很快返回,不需要定时器
196
235
  if (!isSecondMessage) {
197
236
  startStatusInterval();
198
237
  log(`[BOT-DISPATCHER] ✅ Status interval started for first message`);
199
238
  }
200
- else {
201
- log(`[BOT-DISPATCHER] ⏭️ Skipped status interval for steer follower`);
202
- }
203
- log(`xy: dispatching to agent (session=${parsed.sessionId})`);
204
- // Dispatch to OpenClaw core using correct API (following feishu pattern)
205
- log(`[BOT] 🚀 Starting dispatcher with session: ${route.sessionKey}`);
206
239
  // Build session context for AsyncLocalStorage
207
240
  const sessionContext = {
208
241
  config,
@@ -210,13 +243,14 @@ export async function handleXYMessage(params) {
210
243
  taskId: parsed.taskId,
211
244
  messageId: parsed.messageId,
212
245
  agentId: route.accountId,
246
+ deviceType,
213
247
  };
248
+ log(`[BOT-DISPATCH] ⏳ withReplyDispatcher starting, sessionKey=${route.sessionKey}`);
214
249
  await core.channel.reply.withReplyDispatcher({
215
250
  dispatcher,
216
251
  onSettled: () => {
217
252
  log(`[BOT] 🏁 onSettled called for session: ${route.sessionKey}`);
218
253
  log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
219
- markDispatchIdle();
220
254
  // 🔑 减少引用计数
221
255
  decrementTaskIdRef(parsed.sessionId);
222
256
  // 🔑 如果是第一条消息完成,解锁
@@ -230,12 +264,32 @@ export async function handleXYMessage(params) {
230
264
  },
231
265
  run: () =>
232
266
  // 🔐 Use AsyncLocalStorage to provide session context to tools
233
- runWithSessionContext(sessionContext, () => core.channel.reply.dispatchReplyFromConfig({
234
- ctx: ctxPayload,
235
- cfg,
236
- dispatcher,
237
- replyOptions,
238
- })),
267
+ runWithSessionContext(sessionContext, async () => {
268
+ log(`[BOT-DISPATCH] ⏳ dispatchReplyFromConfig starting...`);
269
+ log(`[BOT-DISPATCH] - sessionKey: ${ctxPayload.SessionKey}`);
270
+ log(`[BOT-DISPATCH] - provider: ${ctxPayload.Provider}`);
271
+ log(`[BOT-DISPATCH] - surface: ${ctxPayload.Surface}`);
272
+ log(`[BOT-DISPATCH] - from: ${ctxPayload.From}`);
273
+ log(`[BOT-DISPATCH] - body length: ${ctxPayload.Body?.length ?? 0}`);
274
+ try {
275
+ const result = await core.channel.reply.dispatchReplyFromConfig({
276
+ ctx: ctxPayload,
277
+ cfg,
278
+ dispatcher,
279
+ replyOptions,
280
+ });
281
+ log(`[BOT-DISPATCH] ✅ dispatchReplyFromConfig returned`);
282
+ log(`[BOT-DISPATCH] - result: ${JSON.stringify(result)}`);
283
+ return result;
284
+ }
285
+ catch (dispatchErr) {
286
+ error(`[BOT-DISPATCH] ❌ dispatchReplyFromConfig threw`);
287
+ error(`[BOT-DISPATCH] - error name: ${dispatchErr instanceof Error ? dispatchErr.name : "unknown"}`);
288
+ error(`[BOT-DISPATCH] - error message: ${String(dispatchErr)}`);
289
+ error(`[BOT-DISPATCH] - error stack: ${dispatchErr instanceof Error ? dispatchErr.stack?.slice(0, 500) : "N/A"}`);
290
+ throw dispatchErr;
291
+ }
292
+ }),
239
293
  });
240
294
  log(`[BOT] ✅ Dispatcher completed for session: ${parsed.sessionId}`);
241
295
  log(`xy: dispatch complete (session=${parsed.sessionId})`);
@@ -279,34 +333,17 @@ export async function handleXYMessage(params) {
279
333
  /**
280
334
  * Build media payload for inbound context.
281
335
  * Following feishu pattern: buildFeishuMediaPayload().
282
- * Uses remote URIs directly - openclaw will download them.
336
+ *
337
+ * @param mediaList - Downloaded files with local paths
283
338
  */
284
- function buildXYMediaPayload(fileParts) {
285
- const first = fileParts[0];
286
- const uris = fileParts.map((file) => file.uri);
287
- const mediaTypes = fileParts.map((file) => file.mimeType).filter(Boolean);
339
+ function buildXYMediaPayload(mediaList) {
340
+ const first = mediaList[0];
341
+ const mediaPaths = mediaList.map((media) => media.path);
342
+ const mediaTypes = mediaList.map((media) => media.mimeType).filter(Boolean);
288
343
  return {
289
- MediaPath: first?.uri,
344
+ MediaPath: first?.path,
290
345
  MediaType: first?.mimeType,
291
- MediaUrl: first?.uri,
292
- MediaPaths: uris.length > 0 ? uris : undefined,
293
- MediaUrls: uris.length > 0 ? uris : undefined,
346
+ MediaPaths: mediaPaths.length > 0 ? mediaPaths : undefined,
294
347
  MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
295
348
  };
296
349
  }
297
- /**
298
- * Infer OpenClaw media type from file type string.
299
- */
300
- function inferMediaType(fileType) {
301
- const lower = fileType.toLowerCase();
302
- if (lower.includes("image") || /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(lower)) {
303
- return "image";
304
- }
305
- if (lower.includes("video") || /\.(mp4|avi|mov|mkv|webm)$/i.test(lower)) {
306
- return "video";
307
- }
308
- if (lower.includes("audio") || /\.(mp3|wav|ogg|m4a)$/i.test(lower)) {
309
- return "audio";
310
- }
311
- return "file";
312
- }
@@ -1,7 +1,6 @@
1
1
  import { resolveXYConfig, listXYAccountIds, getDefaultXYAccountId } from "./config.js";
2
2
  import { xyConfigSchema } from "./config-schema.js";
3
3
  import { xyOutbound } from "./outbound.js";
4
- import { xyOnboardingAdapter } from "./onboarding.js";
5
4
  import { locationTool } from "./tools/location-tool.js";
6
5
  import { noteTool } from "./tools/note-tool.js";
7
6
  import { searchNoteTool } from "./tools/search-note-tool.js";
@@ -14,6 +13,7 @@ import { uploadPhotoTool } from "./tools/upload-photo-tool.js";
14
13
  import { xiaoyiGuiTool } from "./tools/xiaoyi-gui-tool.js";
15
14
  import { callPhoneTool } from "./tools/call-phone-tool.js";
16
15
  import { searchMessageTool } from "./tools/search-message-tool.js";
16
+ import { sendMessageTool } from "./tools/send-message-tool.js";
17
17
  import { searchFileTool } from "./tools/search-file-tool.js";
18
18
  import { uploadFileTool } from "./tools/upload-file-tool.js";
19
19
  import { createAlarmTool } from "./tools/create-alarm-tool.js";
@@ -21,8 +21,13 @@ import { searchAlarmTool } from "./tools/search-alarm-tool.js";
21
21
  import { modifyAlarmTool } from "./tools/modify-alarm-tool.js";
22
22
  import { deleteAlarmTool } from "./tools/delete-alarm-tool.js";
23
23
  import { sendFileToUserTool } from "./tools/send-file-to-user-tool.js";
24
- import { xiaoyiCollectionTool } from "./tools/xiaoyi-collection-tool.js";
25
24
  import { viewPushResultTool } from "./tools/view-push-result-tool.js";
25
+ import { imageReadingTool } from "./tools/image-reading-tool.js";
26
+ import { timestampToUtc8Tool } from "./tools/timestamp-to-utc8-tool.js";
27
+ import { sendCommandToCarTool } from "./tools/send-command-to-car-tool.js";
28
+ import { filterToolsByDevice } from "./tools/device-tool-map.js";
29
+ import { getCurrentSessionContext } from "./tools/session-manager.js";
30
+ import { logger } from "./utils/logger.js";
26
31
  /**
27
32
  * Xiaoyi Channel Plugin for OpenClaw.
28
33
  * Implements Xiaoyi A2A protocol with dual WebSocket connections.
@@ -61,8 +66,13 @@ export const xyPlugin = {
61
66
  schema: xyConfigSchema,
62
67
  },
63
68
  outbound: xyOutbound,
64
- onboarding: xyOnboardingAdapter,
65
- agentTools: [locationTool, noteTool, searchNoteTool, modifyNoteTool, calendarTool, searchCalendarTool, searchContactTool, searchPhotoGalleryTool, uploadPhotoTool, xiaoyiGuiTool, callPhoneTool, searchMessageTool, searchFileTool, uploadFileTool, createAlarmTool, searchAlarmTool, modifyAlarmTool, deleteAlarmTool, sendFileToUserTool, xiaoyiCollectionTool, viewPushResultTool],
69
+ agentTools: () => {
70
+ 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];
71
+ const ctx = getCurrentSessionContext();
72
+ const filtered = filterToolsByDevice(allTools, ctx?.deviceType);
73
+ logger.log(`[DEVICE-FILTER] deviceType=${ctx?.deviceType ?? "(none)"}, tools: ${allTools.length} → ${filtered.length} (${filtered.map(t => t.name).join(", ")})`);
74
+ return filtered;
75
+ },
66
76
  messaging: {
67
77
  normalizeTarget: (raw) => {
68
78
  const trimmed = raw.trim();
@@ -79,6 +89,22 @@ export const xyPlugin = {
79
89
  hint: "<sessionId>",
80
90
  },
81
91
  },
92
+ bindings: {
93
+ compileConfiguredBinding: ({ conversationId }) => {
94
+ const sessionId = conversationId.trim();
95
+ if (!sessionId)
96
+ return null;
97
+ return {
98
+ conversationId: sessionId,
99
+ parentConversationId: undefined,
100
+ };
101
+ },
102
+ matchInboundConversation: ({ compiledBinding, conversationId }) => {
103
+ return compiledBinding.conversationId === conversationId
104
+ ? { conversationId, matchPriority: 2 }
105
+ : null;
106
+ },
107
+ },
82
108
  reload: {
83
109
  configPrefixes: ["channels.xiaoyi-channel"],
84
110
  },
@@ -23,7 +23,6 @@ export function getXYWebSocketManager(config) {
23
23
  let cached = wsManagerCache.get(cacheKey);
24
24
  if (cached && cached.isConfigMatch(config)) {
25
25
  const log = runtime?.log ?? console.log;
26
- log(`[WS-MANAGER-CACHE] ✅ Reusing cached WebSocket manager: ${cacheKey}, total managers: ${wsManagerCache.size}`);
27
26
  return cached;
28
27
  }
29
28
  // Create new manager
@@ -73,21 +72,14 @@ export function getCachedManagerCount() {
73
72
  * Helps identify connection issues and orphan connections.
74
73
  */
75
74
  export function diagnoseAllManagers() {
76
- console.log("========================================");
77
- console.log("📊 WebSocket Manager Global Diagnostics");
78
- console.log("========================================");
79
75
  console.log(`Total cached managers: ${wsManagerCache.size}`);
80
- console.log("");
81
76
  if (wsManagerCache.size === 0) {
82
77
  console.log("ℹ️ No managers in cache");
83
- console.log("========================================");
84
78
  return;
85
79
  }
86
80
  let orphanCount = 0;
87
81
  wsManagerCache.forEach((manager, key) => {
88
82
  const diag = manager.getConnectionDiagnostics();
89
- console.log(`📌 Manager: ${key}`);
90
- console.log(` Shutting down: ${diag.isShuttingDown}`);
91
83
  console.log(` Total event listeners on manager: ${diag.totalEventListeners}`);
92
84
  // Connection
93
85
  console.log(` 🔌 Connection:`);
@@ -111,7 +103,6 @@ export function diagnoseAllManagers() {
111
103
  else {
112
104
  console.log(`✅ No orphan connections found`);
113
105
  }
114
- console.log("========================================");
115
106
  }
116
107
  /**
117
108
  * Clean up orphan connections across all managers.
@@ -0,0 +1,3 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import type { ApiResponse } from "./constants.js";
3
+ export declare function callCsplApi(questionText: string, cfg: ClawdbotConfig): Promise<ApiResponse>;
@@ -0,0 +1,86 @@
1
+ // CSPL API 请求模块
2
+ import https from "node:https";
3
+ import { URL } from "node:url";
4
+ import { randomBytes } from "node:crypto";
5
+ import { getCsplConfig } from "./config.js";
6
+ import { DEFAULT_HTTP_PORT, HTTP_STATUS_BAD_REQUEST } from "./constants.js";
7
+ function generateTraceId() {
8
+ return randomBytes(16).toString("hex");
9
+ }
10
+ function buildHeaders(config) {
11
+ return {
12
+ "x-hag-trace-id": generateTraceId(),
13
+ "x-uid": config.uid,
14
+ "x-api-key": config.apiKey,
15
+ "x-request-from": config.requestFrom,
16
+ "x-skill-id": config.skillId,
17
+ "content-type": "application/json",
18
+ };
19
+ }
20
+ function buildRequestOptions(url, headers, timeout) {
21
+ const urlObj = new URL(url);
22
+ return {
23
+ hostname: urlObj.hostname,
24
+ port: urlObj.port || DEFAULT_HTTP_PORT,
25
+ path: urlObj.pathname,
26
+ method: "POST",
27
+ headers: headers,
28
+ timeout,
29
+ };
30
+ }
31
+ function parseResponse(data) {
32
+ if (!data?.trim())
33
+ throw new Error("[CSPL] API response is empty");
34
+ const json = JSON.parse(data);
35
+ if (json.retCode && json.retCode !== "0") {
36
+ throw new Error(`[CSPL] API error: ${json.retMsg || "unknown"}`);
37
+ }
38
+ if (!json.retCode && json.code) {
39
+ throw new Error(`[CSPL] Backend error: ${json.desc || "unknown"}`);
40
+ }
41
+ return json;
42
+ }
43
+ export async function callCsplApi(questionText, cfg) {
44
+ const config = getCsplConfig(cfg);
45
+ const headers = buildHeaders(config);
46
+ const payload = {
47
+ questionText,
48
+ textSource: config.textSource,
49
+ action: config.action,
50
+ };
51
+ return new Promise((resolve, reject) => {
52
+ const options = buildRequestOptions(config.api.url, headers, config.api.timeout);
53
+ const req = https.request(options, (res) => {
54
+ if (res.statusCode && res.statusCode >= HTTP_STATUS_BAD_REQUEST) {
55
+ reject(new Error(`[CSPL] HTTP error: ${res.statusCode}`));
56
+ return;
57
+ }
58
+ let data = "";
59
+ res.on("data", (chunk) => {
60
+ data += chunk;
61
+ });
62
+ res.on("end", () => {
63
+ try {
64
+ const result = parseResponse(data);
65
+ console.log(`[CSPL API] ✅ 请求成功`);
66
+ resolve(result);
67
+ }
68
+ catch (e) {
69
+ console.error(`[CSPL API] ❌ 请求失败: ${e instanceof Error ? e.message : String(e)}`);
70
+ reject(e);
71
+ }
72
+ });
73
+ });
74
+ req.on("error", (error) => {
75
+ console.error(`[CSPL API] ❌ 请求错误: ${error instanceof Error ? error.message : String(error)}`);
76
+ reject(error);
77
+ });
78
+ req.on("timeout", () => {
79
+ console.error(`[CSPL API] ⏰ 请求超时 (${config.api.timeout}ms)`);
80
+ req.destroy();
81
+ reject(new Error("[CSPL] Request timeout"));
82
+ });
83
+ req.write(JSON.stringify(payload));
84
+ req.end();
85
+ });
86
+ }
@@ -0,0 +1,19 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ export interface ApiConfig {
3
+ url: string;
4
+ timeout: number;
5
+ }
6
+ export interface CsplConfig {
7
+ api: ApiConfig;
8
+ uid: string;
9
+ apiKey: string;
10
+ skillId: string;
11
+ requestFrom: string;
12
+ textSource: string;
13
+ action: string;
14
+ }
15
+ /**
16
+ * 构建 CSPL 配置。uid 和 apiKey 复用 XYChannelConfig,避免重复配置。
17
+ * serviceUrl 从 .xiaoyienv 文件读取,skillId 写死在常量中。
18
+ */
19
+ export declare function getCsplConfig(cfg: ClawdbotConfig): CsplConfig;
@@ -0,0 +1,50 @@
1
+ // CSPL Hook 配置管理
2
+ // uid 和 apiKey 复用 XYChannelConfig,skillId 写死在常量中
3
+ import { resolveXYConfig } from "../config.js";
4
+ import { CSPL_STATIC_CONFIG, API_URL_SUFFIX, ENV_FILE_PATH } from "./constants.js";
5
+ import fs from "node:fs";
6
+ import { logger } from "../utils/logger.js";
7
+ let cachedConfig = null;
8
+ function readServiceUrl() {
9
+ if (!fs.existsSync(ENV_FILE_PATH)) {
10
+ throw new Error(`[CSPL] Environment file not found: ${ENV_FILE_PATH}`);
11
+ }
12
+ const envData = fs.readFileSync(ENV_FILE_PATH, "utf-8");
13
+ for (const line of envData.split("\n")) {
14
+ const trimmed = line.trim();
15
+ if (!trimmed || trimmed.startsWith("#"))
16
+ continue;
17
+ const eqIdx = trimmed.indexOf("=");
18
+ if (eqIdx === -1)
19
+ continue;
20
+ const key = trimmed.substring(0, eqIdx).trim();
21
+ const value = trimmed.substring(eqIdx + 1).trim();
22
+ if (key === "SERVICE_URL" && value)
23
+ return value;
24
+ }
25
+ throw new Error("[CSPL] Missing SERVICE_URL in env file");
26
+ }
27
+ /**
28
+ * 构建 CSPL 配置。uid 和 apiKey 复用 XYChannelConfig,避免重复配置。
29
+ * serviceUrl 从 .xiaoyienv 文件读取,skillId 写死在常量中。
30
+ */
31
+ export function getCsplConfig(cfg) {
32
+ if (cachedConfig)
33
+ return cachedConfig;
34
+ const xyConfig = resolveXYConfig(cfg);
35
+ const serviceUrl = readServiceUrl();
36
+ cachedConfig = {
37
+ api: {
38
+ url: `${serviceUrl}${API_URL_SUFFIX}`,
39
+ timeout: CSPL_STATIC_CONFIG.api.timeout,
40
+ },
41
+ uid: xyConfig.uid,
42
+ apiKey: xyConfig.apiKey,
43
+ skillId: CSPL_STATIC_CONFIG.skillId,
44
+ requestFrom: CSPL_STATIC_CONFIG.requestFrom,
45
+ textSource: CSPL_STATIC_CONFIG.textSource,
46
+ action: CSPL_STATIC_CONFIG.action,
47
+ };
48
+ logger.log("[CSPL] Config loaded (uid/apiKey from XYChannelConfig)");
49
+ return cachedConfig;
50
+ }
@@ -0,0 +1,43 @@
1
+ export interface HttpHeaders {
2
+ "x-hag-trace-id": string;
3
+ "x-uid": string;
4
+ "x-api-key": string;
5
+ "x-request-from": string;
6
+ "x-skill-id": string;
7
+ "content-type": string;
8
+ }
9
+ export interface ApiPayload {
10
+ questionText: string;
11
+ textSource: string;
12
+ action: string;
13
+ }
14
+ export interface ApiResponse {
15
+ data?: {
16
+ securityResult?: string;
17
+ };
18
+ retCode?: string;
19
+ retMsg?: string;
20
+ code?: string;
21
+ desc?: string;
22
+ [key: string]: any;
23
+ }
24
+ export declare const MIN_TEXT_LENGTH = 0;
25
+ export declare const MAX_TEXT_LENGTH = 4096;
26
+ export declare const MAX_TOTAL_LENGTH = 40960;
27
+ export declare const regex: RegExp;
28
+ export declare const DEFAULT_HTTP_PORT = 443;
29
+ export declare const HTTP_STATUS_BAD_REQUEST = 400;
30
+ export declare const ENV_FILE_PATH = "/home/sandbox/.openclaw/.xiaoyienv";
31
+ export declare const API_URL_SUFFIX = "/celia-claw/v1/rest-api/skill/execute";
32
+ export declare const REQUIRED_ENV_VARS: string[];
33
+ export declare const ALLOWED_TOOLS: string[];
34
+ export declare const CSPL_STATIC_CONFIG: {
35
+ readonly api: {
36
+ readonly timeout: 5000;
37
+ };
38
+ readonly skillId: "skill-scope";
39
+ readonly requestFrom: "openclaw";
40
+ readonly textSource: "question";
41
+ readonly action: "TOOL_OUTPUT_SCAN";
42
+ };
43
+ export declare const STEER_ABORT_MESSAGE = "\u5F53\u524D\u884C\u4E3A\u5B58\u5728\u5B89\u5168\u9690\u60A3\uFF0C\u7EC8\u6B62\u6240\u6709\u64CD\u4F5C\uFF0C\u5E76\u4E14\u5728\u6700\u7EC8\u56DE\u590D\u4E2D\u8BF4\u660E\uFF0C\u8BC6\u522B\u5230\u5F53\u524D\u6D41\u7A0B\u4E2D\u5B58\u5728\u6F5C\u5728\u5B89\u5168\u98CE\u9669\uFF0C\u5DF2\u5E2E\u60A8\u4E2D\u6B62\u5F53\u524D\u6D41\u7A0B\uFF0C\u8BF7\u6E05\u7A7A\u4E0A\u4E0B\u6587\u540E\u91CD\u8BD5";