@ynhcj/xiaoyi-channel 0.0.142-beta → 0.0.142-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 (77) hide show
  1. package/dist/index.js +3 -69
  2. package/dist/src/approval-bridge.d.ts +48 -0
  3. package/dist/src/approval-bridge.js +382 -0
  4. package/dist/src/bot.js +75 -73
  5. package/dist/src/client.js +13 -23
  6. package/dist/src/cspl/call_api.d.ts +2 -0
  7. package/dist/src/cspl/call_api.js +107 -0
  8. package/dist/src/cspl/config.d.ts +4 -17
  9. package/dist/src/cspl/config.js +80 -70
  10. package/dist/src/cspl/configs.json +10 -0
  11. package/dist/src/cspl/constants.d.ts +46 -24
  12. package/dist/src/cspl/constants.js +41 -16
  13. package/dist/src/cspl/sentinel_hook.d.ts +2 -0
  14. package/dist/src/cspl/sentinel_hook.js +84 -0
  15. package/dist/src/cspl/steer-context.js +1 -1
  16. package/dist/src/cspl/upload_file.d.ts +1 -0
  17. package/dist/src/cspl/upload_file.js +211 -0
  18. package/dist/src/cspl/utils.d.ts +11 -2
  19. package/dist/src/cspl/utils.js +265 -15
  20. package/dist/src/formatter.js +92 -37
  21. package/dist/src/monitor.js +18 -21
  22. package/dist/src/outbound.js +8 -9
  23. package/dist/src/provider.js +50 -70
  24. package/dist/src/push.js +8 -15
  25. package/dist/src/reply-dispatcher.js +39 -48
  26. package/dist/src/self-evolution-handler.js +1 -1
  27. package/dist/src/sensitive-redactor.d.ts +4 -0
  28. package/dist/src/sensitive-redactor.js +364 -0
  29. package/dist/src/task-manager.js +6 -10
  30. package/dist/src/tools/agent-as-skill-tool.d.ts +7 -0
  31. package/dist/src/tools/agent-as-skill-tool.js +138 -0
  32. package/dist/src/tools/calendar-tool.js +1 -1
  33. package/dist/src/tools/call-device-tool.js +3 -0
  34. package/dist/src/tools/call-phone-tool.js +1 -1
  35. package/dist/src/tools/create-alarm-tool.js +1 -1
  36. package/dist/src/tools/create-all-tools.js +5 -1
  37. package/dist/src/tools/delete-alarm-tool.js +1 -1
  38. package/dist/src/tools/find-pc-devices-tool.d.ts +2 -1
  39. package/dist/src/tools/find-pc-devices-tool.js +84 -88
  40. package/dist/src/tools/get-device-file-tool-schema.js +3 -2
  41. package/dist/src/tools/image-reading-tool.js +7 -6
  42. package/dist/src/tools/location-tool.js +1 -1
  43. package/dist/src/tools/modify-alarm-tool.js +1 -1
  44. package/dist/src/tools/modify-note-tool.js +1 -1
  45. package/dist/src/tools/note-tool.js +1 -1
  46. package/dist/src/tools/query-app-message-tool.js +1 -1
  47. package/dist/src/tools/query-memory-data-tool.js +1 -1
  48. package/dist/src/tools/query-todo-task-tool.js +1 -1
  49. package/dist/src/tools/save-file-to-phone-tool.js +1 -1
  50. package/dist/src/tools/save-media-to-gallery-tool.js +1 -1
  51. package/dist/src/tools/search-alarm-tool.js +1 -1
  52. package/dist/src/tools/search-calendar-tool.js +1 -1
  53. package/dist/src/tools/search-contact-tool.js +1 -1
  54. package/dist/src/tools/search-email-tool.js +1 -1
  55. package/dist/src/tools/search-file-tool.js +11 -8
  56. package/dist/src/tools/search-message-tool.js +1 -1
  57. package/dist/src/tools/search-note-tool.js +1 -1
  58. package/dist/src/tools/search-photo-gallery-tool.js +1 -1
  59. package/dist/src/tools/send-email-tool.js +1 -1
  60. package/dist/src/tools/send-file-to-user-tool.js +2 -2
  61. package/dist/src/tools/send-message-tool.js +1 -1
  62. package/dist/src/tools/session-manager.js +5 -0
  63. package/dist/src/tools/upload-file-tool.js +15 -5
  64. package/dist/src/tools/upload-photo-tool.js +1 -1
  65. package/dist/src/tools/xiaoyi-add-collection-tool.js +1 -1
  66. package/dist/src/tools/xiaoyi-collection-tool.js +1 -1
  67. package/dist/src/tools/xiaoyi-delete-collection-tool.js +1 -1
  68. package/dist/src/tools/xiaoyi-gui-tool.js +1 -1
  69. package/dist/src/trigger-handler.js +4 -7
  70. package/dist/src/utils/config-manager.js +3 -6
  71. package/dist/src/utils/logger.d.ts +8 -0
  72. package/dist/src/utils/logger.js +69 -34
  73. package/dist/src/utils/pushdata-manager.js +1 -5
  74. package/dist/src/utils/pushid-manager.js +1 -2
  75. package/dist/src/utils/runtime-manager.js +1 -4
  76. package/dist/src/websocket.js +37 -25
  77. package/package.json +1 -1
@@ -3,11 +3,48 @@ import { v4 as uuidv4 } from "uuid";
3
3
  import { getXYWebSocketManager } from "./client.js";
4
4
  import { logger } from "./utils/logger.js";
5
5
  import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
6
+ import { redactSensitiveText, containsSensitiveInfo } from "./sensitive-redactor.js";
7
+ import { rewriteOutboundApprovalText } from "./approval-bridge.js";
8
+ // ─────────────────────────────────────────────────────────────
9
+ // 敏感信息脱敏辅助函数
10
+ // ─────────────────────────────────────────────────────────────
11
+ const MESSAGE_CONTENT_KEYS = new Set(["text", "reasoningText", "content", "message"]);
12
+ function redactMessagePayload(value, currentKey) {
13
+ if (value === null || value === undefined) {
14
+ return value;
15
+ }
16
+ if (typeof value === "string") {
17
+ if (currentKey === undefined || MESSAGE_CONTENT_KEYS.has(currentKey)) {
18
+ return redactSensitiveText(value);
19
+ }
20
+ return value;
21
+ }
22
+ if (Array.isArray(value)) {
23
+ return value.map(item => redactMessagePayload(item, currentKey));
24
+ }
25
+ if (typeof value === "object") {
26
+ const result = {};
27
+ for (const key of Object.keys(value)) {
28
+ result[key] = redactMessagePayload(value[key], key);
29
+ }
30
+ return result;
31
+ }
32
+ return value;
33
+ }
34
+ function buildTextPreview(text) {
35
+ if (typeof text !== "string" || text.length === 0) {
36
+ return "";
37
+ }
38
+ return text.length <= 10 ? text : `${text.slice(0, 5)}***${text.slice(-5)}`;
39
+ }
6
40
  /**
7
41
  * Send an A2A artifact update response.
8
42
  */
9
43
  export async function sendA2AResponse(params) {
10
44
  const { config, sessionId, taskId, messageId, text, append, final, files, errorCode, errorMessage } = params;
45
+ const log = logger.withContext(sessionId, taskId);
46
+ // 审批桥接:将 OpenClaw 的审批提示翻译成用户友好的确认文案
47
+ const bridgedText = text === undefined ? text : rewriteOutboundApprovalText(sessionId, text);
11
48
  // Build artifact update event
12
49
  const artifact = {
13
50
  taskId,
@@ -21,10 +58,10 @@ export async function sendA2AResponse(params) {
21
58
  },
22
59
  };
23
60
  // Add text part (even if empty string, to maintain parts structure)
24
- if (text !== undefined) {
61
+ if (bridgedText !== undefined) {
25
62
  artifact.artifact.parts.push({
26
63
  kind: "text",
27
- text,
64
+ text: bridgedText,
28
65
  });
29
66
  }
30
67
  // Add file parts if provided
@@ -34,6 +71,8 @@ export async function sendA2AResponse(params) {
34
71
  data: { fileInfo: files },
35
72
  });
36
73
  }
74
+ // 对消息内容字段做敏感信息脱敏,不修改协议层的 id 等字段
75
+ artifact.artifact.parts = redactMessagePayload(artifact.artifact.parts, "parts");
37
76
  // Build JSON-RPC response
38
77
  const jsonRpcResponse = {
39
78
  jsonrpc: "2.0",
@@ -46,7 +85,7 @@ export async function sendA2AResponse(params) {
46
85
  code: errorCode,
47
86
  message: errorMessage ?? "任务执行异常,请重试",
48
87
  };
49
- logger.log(`[A2A_RESPONSE] ⚠️ Including error code: ${errorCode}`);
88
+ log.log(`[A2A_RESPONSE] Including error code: ${errorCode}`);
50
89
  }
51
90
  // Send via WebSocket
52
91
  const wsManager = getXYWebSocketManager(config);
@@ -57,14 +96,11 @@ export async function sendA2AResponse(params) {
57
96
  taskId,
58
97
  msgDetail: JSON.stringify(jsonRpcResponse),
59
98
  };
60
- // 📋 Log complete response body
61
- logger.log(`[A2A_RESPONSE] 📤 Sending A2A artifact-update response: taskId: ${taskId}`);
62
- logger.log(`[A2A_RESPONSE] - append: ${append}`);
63
- logger.log(`[A2A_RESPONSE] - final: ${final}`);
64
- logger.log(`[A2A_RESPONSE] - text: ${text.length <= 10 ? text : text.slice(0, 5) + '***' + text.slice(-5)}`);
65
- logger.log(`[A2A_RESPONSE] - files count: ${files?.length ?? 0}`);
99
+ // Log complete response body
100
+ const redactedText = redactSensitiveText(bridgedText ?? "");
101
+ log.log(`[A2A_RESPONSE] Sending artifact-update, append=${append}, final=${final}, text=${buildTextPreview(redactedText)}, files=${files?.length ?? 0}, sensitive=${containsSensitiveInfo(bridgedText ?? "")}`);
66
102
  await wsManager.sendMessage(sessionId, outboundMessage);
67
- logger.log(`[A2A_RESPONSE] ✅ Message sent successfully`);
103
+ log.log(`[A2A_RESPONSE] Message sent successfully`);
68
104
  }
69
105
  /**
70
106
  * Send an A2A artifact-update with reasoningText part.
@@ -73,6 +109,9 @@ export async function sendA2AResponse(params) {
73
109
  */
74
110
  export async function sendReasoningTextUpdate(params) {
75
111
  const { config, sessionId, taskId, messageId, text, append = true } = params;
112
+ const log = logger.withContext(sessionId, taskId);
113
+ // 审批桥接
114
+ const bridgedText = rewriteOutboundApprovalText(sessionId, text);
76
115
  const artifact = {
77
116
  taskId,
78
117
  kind: "artifact-update",
@@ -84,11 +123,13 @@ export async function sendReasoningTextUpdate(params) {
84
123
  parts: [
85
124
  {
86
125
  kind: "reasoningText",
87
- reasoningText: text,
126
+ reasoningText: bridgedText,
88
127
  },
89
128
  ],
90
129
  },
91
130
  };
131
+ // 对消息内容字段做敏感信息脱敏
132
+ artifact.artifact.parts = redactMessagePayload(artifact.artifact.parts, "parts");
92
133
  const jsonRpcResponse = {
93
134
  jsonrpc: "2.0",
94
135
  id: messageId,
@@ -114,21 +155,26 @@ export async function sendStatusUpdate(params) {
114
155
  // fall back to closure-captured values
115
156
  const currentTaskId = getCurrentTaskId(sessionId) ?? taskId;
116
157
  const currentMessageId = getCurrentMessageId(sessionId) ?? messageId;
158
+ const log = logger.withContext(sessionId, currentTaskId);
159
+ // 审批桥接和脱敏
160
+ const bridgedText = rewriteOutboundApprovalText(sessionId, text);
161
+ const redactedText = redactSensitiveText(bridgedText);
117
162
  // Build status update event following A2A protocol standard
163
+ const statusMessage = redactMessagePayload({
164
+ role: "agent",
165
+ parts: [
166
+ {
167
+ kind: "text",
168
+ text: bridgedText,
169
+ },
170
+ ],
171
+ });
118
172
  const statusUpdate = {
119
173
  taskId: currentTaskId,
120
174
  kind: "status-update",
121
175
  final: false, // Status updates should not end the stream
122
176
  status: {
123
- message: {
124
- role: "agent",
125
- parts: [
126
- {
127
- kind: "text",
128
- text,
129
- },
130
- ],
131
- },
177
+ message: statusMessage,
132
178
  state,
133
179
  },
134
180
  };
@@ -147,10 +193,8 @@ export async function sendStatusUpdate(params) {
147
193
  taskId: currentTaskId,
148
194
  msgDetail: JSON.stringify(jsonRpcResponse),
149
195
  };
150
- // 📋 Log complete response body
151
- logger.log(`[A2A_STATUS] 📤 Sending A2A status-update:`);
152
- logger.log(`[A2A_STATUS] - taskId: ${currentTaskId}`);
153
- logger.log(`[A2A_STATUS] - text: "${text}"`);
196
+ // Log complete response body
197
+ log.log(`[A2A_STATUS] Sending status-update, text="${redactedText}"`);
154
198
  await wsManager.sendMessage(sessionId, outboundMessage);
155
199
  }
156
200
  /**
@@ -162,6 +206,7 @@ export async function sendCommand(params) {
162
206
  // fall back to closure-captured values
163
207
  const currentTaskId = getCurrentTaskId(sessionId) ?? taskId;
164
208
  const currentMessageId = getCurrentMessageId(sessionId) ?? messageId;
209
+ const log = logger.withContext(sessionId, currentTaskId);
165
210
  // Build artifact update with command as data
166
211
  // Wrap command in commands array as per protocol requirement
167
212
  const artifact = {
@@ -182,6 +227,8 @@ export async function sendCommand(params) {
182
227
  ],
183
228
  },
184
229
  };
230
+ // 对消息内容字段做敏感信息脱敏
231
+ artifact.artifact.parts = redactMessagePayload(artifact.artifact.parts, "parts");
185
232
  // Build JSON-RPC response
186
233
  const jsonRpcResponse = {
187
234
  jsonrpc: "2.0",
@@ -197,16 +244,17 @@ export async function sendCommand(params) {
197
244
  taskId: currentTaskId,
198
245
  msgDetail: JSON.stringify(jsonRpcResponse),
199
246
  };
200
- // 📋 Log complete response body
201
- logger.log(`[A2A_COMMAND] 📤 Sending A2A command: taskId: ${currentTaskId}`);
247
+ // Log complete response body
248
+ log.log(`[A2A_COMMAND] Sending command`);
202
249
  await wsManager.sendMessage(sessionId, outboundMessage);
203
- logger.log(`[A2A_COMMAND] ✅ Command sent successfully`);
250
+ log.log(`[A2A_COMMAND] Command sent successfully`);
204
251
  }
205
252
  /**
206
253
  * Send a clearContext response.
207
254
  */
208
255
  export async function sendClearContextResponse(params) {
209
256
  const { config, sessionId, messageId } = params;
257
+ const log = logger.withContext(sessionId, "");
210
258
  // Build JSON-RPC response for clearContext
211
259
  const jsonRpcResponse = {
212
260
  jsonrpc: "2.0",
@@ -232,13 +280,14 @@ export async function sendClearContextResponse(params) {
232
280
  msgDetail: JSON.stringify(jsonRpcResponse),
233
281
  };
234
282
  await wsManager.sendMessage(sessionId, outboundMessage);
235
- logger.log(`Sent clearContext response: sessionId=${sessionId}`);
283
+ log.log(`[CLEAR_CONTEXT] Sent clearContext response`);
236
284
  }
237
285
  /**
238
286
  * Send a tasks/cancel response.
239
287
  */
240
288
  export async function sendTasksCancelResponse(params) {
241
289
  const { config, sessionId, taskId, messageId } = params;
290
+ const log = logger.withContext(sessionId, taskId);
242
291
  // Build JSON-RPC response for tasks/cancel
243
292
  // Note: Using any to bypass type check as the response format differs from standard A2A types
244
293
  const jsonRpcResponse = {
@@ -265,13 +314,24 @@ export async function sendTasksCancelResponse(params) {
265
314
  msgDetail: JSON.stringify(jsonRpcResponse),
266
315
  };
267
316
  await wsManager.sendMessage(sessionId, outboundMessage);
268
- logger.log(`Sent tasks/cancel response: sessionId=${sessionId}, taskId=${taskId}`);
317
+ log.log(`[TASKS_CANCEL] Sent tasks/cancel response`);
269
318
  }
270
319
  /**
271
320
  * Send a Trigger response with pushData content.
272
321
  */
273
322
  export async function sendTriggerResponse(params) {
274
323
  const { config, sessionId, taskId, messageId, content } = params;
324
+ const log = logger.withContext(sessionId, taskId);
325
+ // 审批桥接和脱敏
326
+ const bridgedContent = rewriteOutboundApprovalText(sessionId, content);
327
+ const redactedContent = redactSensitiveText(bridgedContent);
328
+ // 对消息内容做敏感信息脱敏
329
+ const artifactParts = redactMessagePayload([
330
+ {
331
+ kind: "text",
332
+ text: bridgedContent,
333
+ },
334
+ ], "parts");
275
335
  // Build JSON-RPC response for Trigger
276
336
  const jsonRpcResponse = {
277
337
  jsonrpc: "2.0",
@@ -284,12 +344,7 @@ export async function sendTriggerResponse(params) {
284
344
  final: true,
285
345
  artifact: {
286
346
  artifactId: uuidv4(),
287
- parts: [
288
- {
289
- kind: "text",
290
- text: content,
291
- },
292
- ],
347
+ parts: artifactParts,
293
348
  },
294
349
  },
295
350
  error: {
@@ -306,7 +361,7 @@ export async function sendTriggerResponse(params) {
306
361
  taskId,
307
362
  msgDetail: JSON.stringify(jsonRpcResponse),
308
363
  };
309
- logger.log(`[TRIGGER_RESPONSE] Sending Trigger response: sessionId=${sessionId}, taskId=${taskId}`);
364
+ log.log(`[TRIGGER_RESPONSE] Sending Trigger response, text=${buildTextPreview(redactedContent)}`);
310
365
  await wsManager.sendMessage(sessionId, outboundMessage);
311
- logger.log(`[TRIGGER_RESPONSE] Trigger response sent successfully`);
366
+ log.log(`[TRIGGER_RESPONSE] Trigger response sent successfully`);
312
367
  }
@@ -51,7 +51,7 @@ export async function monitorXYProvider(opts = {}) {
51
51
  }
52
52
  : undefined;
53
53
  // 🔍 Diagnose WebSocket managers before gateway start
54
- logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
54
+ logger.log("[DIAGNOSTICS] Checking WebSocket managers before gateway start...");
55
55
  diagnoseAllManagers();
56
56
  // Get WebSocket manager (cached)
57
57
  const wsManager = getXYWebSocketManager(account, runtime);
@@ -77,12 +77,12 @@ export async function monitorXYProvider(opts = {}) {
77
77
  // Event handlers (defined early so they can be referenced in cleanup)
78
78
  const messageHandler = (message, sessionId, serverId) => {
79
79
  const messageKey = `${sessionId}::${message.id}`;
80
- logger.log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
80
+ logger.log(`[MONITOR-HANDLER] messageHandler triggered: messageId=${message.id}`);
81
81
  // ✅ Report health: received a message
82
82
  trackEvent?.();
83
83
  // Check for duplicate message handling
84
84
  if (activeMessages.has(messageKey)) {
85
- logger.error(`[MONITOR-HANDLER] ⚠️ WARNING: Duplicate message detected! messageKey=${messageKey}, this may cause duplicate dispatchers!`);
85
+ logger.error(`[MONITOR-HANDLER] WARNING: Duplicate message detected, messageKey=${messageKey}`);
86
86
  }
87
87
  activeMessages.add(messageKey);
88
88
  const task = async () => {
@@ -119,8 +119,7 @@ export async function monitorXYProvider(opts = {}) {
119
119
  const hasActiveRun = hasActiveTask(parsed.sessionId);
120
120
  if (steerMode && hasActiveRun) {
121
121
  // Steer模式且有活跃任务:不入队列,直接并发执行
122
- logger.log(`[MONITOR-HANDLER] 🔄 STEER MODE: Executing concurrently for messageKey=${messageKey}`);
123
- logger.log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
122
+ logger.log(`[MONITOR-HANDLER] STEER MODE: Executing concurrently for messageKey=${messageKey}`);
124
123
  void task().catch((err) => {
125
124
  logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
126
125
  activeMessages.delete(messageKey);
@@ -129,7 +128,7 @@ export async function monitorXYProvider(opts = {}) {
129
128
  else {
130
129
  // 正常模式:入队列串行执行
131
130
  void enqueue(sessionId, task).catch((err) => {
132
- logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
131
+ logger.error(`XY gateway: queue processing failed: ${String(err)}`);
133
132
  activeMessages.delete(messageKey);
134
133
  });
135
134
  }
@@ -138,7 +137,7 @@ export async function monitorXYProvider(opts = {}) {
138
137
  // 解析失败,回退到正常队列模式
139
138
  logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
140
139
  void enqueue(sessionId, task).catch((err) => {
141
- logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
140
+ logger.error(`XY gateway: queue processing failed: ${String(err)}`);
142
141
  activeMessages.delete(messageKey);
143
142
  });
144
143
  }
@@ -164,9 +163,7 @@ export async function monitorXYProvider(opts = {}) {
164
163
  logger.error(`XY gateway: ${serverId} error: ${String(err)}`);
165
164
  };
166
165
  const triggerEventHandler = (context) => {
167
- logger.log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
168
- logger.log(`[MONITOR] - sessionId: ${context.sessionId}`);
169
- logger.log(`[MONITOR] - taskId: ${context.taskId}`);
166
+ logger.log(`[MONITOR] Received trigger-event, dispatching to handler...`);
170
167
  // 异步处理 Trigger 事件,不阻塞主流程
171
168
  handleTriggerEvent(context, cfg, runtime, accountId).catch((err) => {
172
169
  logger.error(`[MONITOR] Failed to handle trigger-event:`, err);
@@ -189,13 +186,13 @@ export async function monitorXYProvider(opts = {}) {
189
186
  const cleanup = () => {
190
187
  logger.log("XY gateway: cleaning up...");
191
188
  // 🔍 Diagnose before cleanup
192
- logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
189
+ logger.log("[DIAGNOSTICS] Checking WebSocket managers before cleanup...");
193
190
  diagnoseAllManagers();
194
191
  // Stop health check interval
195
192
  if (healthCheckInterval) {
196
193
  clearInterval(healthCheckInterval);
197
194
  healthCheckInterval = null;
198
- logger.log("⏸️ Stopped periodic health check");
195
+ logger.log("Stopped periodic health check");
199
196
  }
200
197
  // Remove event handlers to prevent duplicate calls on gateway restart
201
198
  wsManager.off("message", messageHandler);
@@ -215,9 +212,9 @@ export async function monitorXYProvider(opts = {}) {
215
212
  cleanupAllSessions();
216
213
  loggedServers.clear();
217
214
  activeMessages.clear();
218
- logger.log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
215
+ logger.log(`[MONITOR-HANDLER] Cleanup complete, cleared active messages and sessions`);
219
216
  // 🔍 Diagnose after cleanup
220
- logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
217
+ logger.log("[DIAGNOSTICS] Checking WebSocket managers after cleanup...");
221
218
  diagnoseAllManagers();
222
219
  };
223
220
  const handleAbort = async () => {
@@ -228,7 +225,7 @@ export async function monitorXYProvider(opts = {}) {
228
225
  if (activeBindings.length > 0) {
229
226
  const config = resolveXYConfig(cfg);
230
227
  const notificationText = "Gateway即将重启,重启期间可能短暂出现\u201c环境异常\u201d提示,请稍候并耐心重试~";
231
- logger.log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
228
+ logger.log(`[MONITOR] Sending restart notifications to ${activeBindings.length} active session(s)`);
232
229
  const sendPromises = activeBindings.map(binding => sendA2AResponse({
233
230
  config,
234
231
  sessionId: binding.sessionId,
@@ -238,10 +235,10 @@ export async function monitorXYProvider(opts = {}) {
238
235
  append: false,
239
236
  final: true,
240
237
  }).catch(err => {
241
- logger.error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
238
+ logger.error(`[MONITOR] Failed to send restart notification: ${String(err)}`);
242
239
  }));
243
240
  await Promise.all(sendPromises);
244
- logger.log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
241
+ logger.log(`[MONITOR] Restart notifications sent to ${activeBindings.length} session(s)`);
245
242
  }
246
243
  else {
247
244
  logger.log(`[MONITOR] No active sessions, skipping restart notifications`);
@@ -270,20 +267,20 @@ export async function monitorXYProvider(opts = {}) {
270
267
  wsManager.on("self-evolution-state-get-event", selfEvolutionStateGetHandler);
271
268
  wsManager.on("login-token-event", loginTokenEventHandler);
272
269
  // Start periodic health check (every 6 hours)
273
- logger.log("🏥 Starting periodic health check (every 6 hours)...");
270
+ logger.log("Starting periodic health check (every 6 hours)...");
274
271
  healthCheckInterval = setInterval(() => {
275
- logger.log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
272
+ logger.log("[HEALTH CHECK] Periodic WebSocket diagnostics...");
276
273
  diagnoseAllManagers();
277
274
  // Auto-cleanup orphan connections
278
275
  const cleaned = cleanupOrphanConnections();
279
276
  if (cleaned > 0) {
280
- logger.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
277
+ logger.log(`[HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
281
278
  }
282
279
  // Cleanup stale sessions (older than 10min TTL)
283
280
  const cleanedSessions = cleanupStaleSessions();
284
281
  const remainingSessions = getActiveSessionCount();
285
282
  if (cleanedSessions > 0 || remainingSessions > 0) {
286
- logger.log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
283
+ logger.log(`[HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
287
284
  }
288
285
  // Cleanup stale temp files (older than 24 hours)
289
286
  void cleanupStaleTempFiles();
@@ -106,10 +106,10 @@ export const xyOutbound = {
106
106
  let pushDataId;
107
107
  try {
108
108
  pushDataId = await savePushData(text);
109
- logger.log(`[xyOutbound.sendText] ✅ Push data saved with ID: ${pushDataId.substring(0, 20)}`);
109
+ logger.log(`[xyOutbound.sendText] Push data saved with ID: ${pushDataId.substring(0, 20)}`);
110
110
  }
111
111
  catch (error) {
112
- logger.error(`[xyOutbound.sendText] ❌ Failed to save push data:`, error);
112
+ logger.error(`[xyOutbound.sendText] Failed to save push data:`, error);
113
113
  // 如果持久化失败,仍然继续发送(不阻塞主流程)
114
114
  pushDataId = "";
115
115
  }
@@ -118,14 +118,14 @@ export const xyOutbound = {
118
118
  let pushIdList = [];
119
119
  try {
120
120
  pushIdList = await getAllPushIds();
121
- logger.log(`[xyOutbound.sendText] ✅ Loaded ${pushIdList.length} pushIds`);
121
+ logger.log(`[xyOutbound.sendText] Loaded ${pushIdList.length} pushIds`);
122
122
  }
123
123
  catch (error) {
124
- logger.error(`[xyOutbound.sendText] ❌ Failed to load pushIds:`, error);
124
+ logger.error(`[xyOutbound.sendText] Failed to load pushIds:`, error);
125
125
  }
126
126
  // 3. 如果 pushIdList 为空,回退到原有逻辑(使用 config pushId)
127
127
  if (pushIdList.length === 0) {
128
- logger.log(`[xyOutbound.sendText] ⚠️ No pushIds found, falling back to config pushId`);
128
+ logger.log(`[xyOutbound.sendText] No pushIds found, falling back to config pushId`);
129
129
  pushIdList = [config.pushId];
130
130
  }
131
131
  // Create push service
@@ -135,7 +135,7 @@ export const xyOutbound = {
135
135
  // Truncate push content to max length 1000
136
136
  const pushText = text.length > 1000 ? text.slice(0, 1000) : text;
137
137
  // 4. 遍历所有 pushId,依次发送推送通知
138
- logger.log(`[xyOutbound.sendText] 📤 Broadcasting to ${pushIdList.length} pushId(s)...`);
138
+ logger.log(`[xyOutbound.sendText] Broadcasting to ${pushIdList.length} pushId(s)...`);
139
139
  let successCount = 0;
140
140
  let failureCount = 0;
141
141
  for (const pushId of pushIdList) {
@@ -143,11 +143,11 @@ export const xyOutbound = {
143
143
  // 传入 pushId 和 pushDataId,使用 kind="data" 格式
144
144
  await pushService.sendPush(pushText, title, undefined, actualTo, pushDataId, pushId);
145
145
  successCount++;
146
- logger.log(`[xyOutbound.sendText] ✅ Sent successfully to pushId: ${pushId.substring(0, 20)}...`);
146
+ logger.log(`[xyOutbound.sendText] Sent successfully to pushId: ${pushId.substring(0, 20)}...`);
147
147
  }
148
148
  catch (error) {
149
149
  failureCount++;
150
- logger.error(`[xyOutbound.sendText] ❌ Failed to send to pushId: ${pushId.substring(0, 20)}...`, error);
150
+ logger.error(`[xyOutbound.sendText] Failed to send to pushId: ${pushId.substring(0, 20)}...`, error);
151
151
  // 单个 pushId 发送失败不影响其他,继续处理下一个
152
152
  }
153
153
  }
@@ -184,7 +184,6 @@ export const xyOutbound = {
184
184
  }
185
185
  logger.log(`[xyOutbound.sendMedia] File uploaded:`, {
186
186
  fileId,
187
- sessionId,
188
187
  taskId,
189
188
  });
190
189
  // Get filename and mime type from mediaUrl
@@ -46,6 +46,11 @@ function getFirstUserText(messages) {
46
46
  }
47
47
  /** Regex to match `[cron:<uuid> <title>]` anywhere in text. */
48
48
  const CRON_TAG_RE = /\[cron:[^\s\]]+\s+([^\]]+)\]/;
49
+ /** Extract the cron job UUID from the first user message, e.g. `[cron:abc123 ...]` → `abc123`. */
50
+ function extractCronUuid(messages) {
51
+ const match = getFirstUserText(messages).match(/\[cron:([^\s\]]+)/i);
52
+ return match ? match[1] : undefined;
53
+ }
49
54
  /** Check if the request is triggered by a cron job by inspecting the first user message. */
50
55
  function isCronTriggered(messages) {
51
56
  return /\[cron:/i.test(getFirstUserText(messages));
@@ -231,8 +236,6 @@ const HEADER_SESSION_ID = "x-session-id";
231
236
  const HEADER_INTERACTION_ID = "x-interaction-id";
232
237
  /** Internal key for passing fallback uid prefix from prepareExtraParams to wrapStreamFn. */
233
238
  const FALLBACK_PREFIX_KEY = "_xiaoyi_fallback_prefix";
234
- /** Internal key for passing deviceType from prepareExtraParams to wrapStreamFn. */
235
- const DEVICE_TYPE_KEY = "_xiaoyi_device_type";
236
239
  const SELF_EVOLUTION_PROMPT_BEGIN = "<self_evolution_prompt>";
237
240
  const SELF_EVOLUTION_PROMPT_END = "</self_evolution_prompt>";
238
241
  const SELF_EVOLUTION_ENABLED_PROMPT_SECTION = `
@@ -392,7 +395,9 @@ function trimUserMetadata(text) {
392
395
  }
393
396
  /**
394
397
  * Extract A2A taskId and deviceType from Conversation info JSON.
395
- * bot.ts stores them as MessageSid = "taskId_deviceType".
398
+ * bot.ts stores them as MessageSid = "xiaoyi_taskId_deviceType".
399
+ * The "xiaoyi_" prefix ensures extraction only happens for messages
400
+ * routed through xiaoyi-channel, not other channels sharing the provider.
396
401
  */
397
402
  function extractA2AFromConversationInfo(text) {
398
403
  const match = text.match(/Conversation info \(untrusted metadata\):\n```json\n([\s\S]*?)\n```/);
@@ -402,9 +407,9 @@ function extractA2AFromConversationInfo(text) {
402
407
  if (!msgIdMatch)
403
408
  return null;
404
409
  const parts = msgIdMatch[1].split("_");
405
- if (parts.length < 2)
410
+ if (parts.length < 3 || parts[0] !== "xiaoyi")
406
411
  return null;
407
- return { taskId: parts[0], deviceType: parts[1] };
412
+ return { taskId: parts[1], deviceType: parts[2] };
408
413
  }
409
414
  export const xiaoyiProvider = {
410
415
  id: "xiaoyiprovider",
@@ -413,31 +418,12 @@ export const xiaoyiProvider = {
413
418
  auth: [],
414
419
  isCacheTtlEligible: () => true,
415
420
  /**
416
- * Inject dynamic session params into extraParams so they flow
417
- * through to wrapStreamFn's ctx.extraParams.
418
- *
419
- * Priority:
420
- * 1. Session context (from AsyncLocalStorage, set by bot.ts)
421
- * 2. uid-based fallback: sha256(uid).hex[:32]_timestamp
422
- * 3. No uid available → return undefined (no headers injected)
421
+ * Store uid-based fallback prefix for lazy timestamp generation in wrapStreamFn.
422
+ * Session-level headers (traceId / sessionId / interactionId) are resolved
423
+ * directly in wrapStreamFn via cron detection, Conversation info extraction,
424
+ * or uid fallback.
423
425
  */
424
426
  prepareExtraParams: (ctx) => {
425
- const sessionCtx = getCurrentSessionContext();
426
- if (sessionCtx) {
427
- const taskId = sessionCtx.taskId;
428
- const sessionId = taskId.split("&")[0];
429
- const interactionId = taskId.split("&")[1] || "";
430
- return {
431
- ...ctx.extraParams,
432
- [HEADER_TRACE_ID]: taskId,
433
- [HEADER_SESSION_ID]: sessionId,
434
- [HEADER_INTERACTION_ID]: interactionId,
435
- [DEVICE_TYPE_KEY]: sessionCtx.deviceType ?? "",
436
- };
437
- }
438
- // Fallback: store uid prefix for lazy timestamp generation in wrapStreamFn.
439
- // This ensures each model call gets a fresh timestamp instead of reusing
440
- // the same one across tool-use loops and retries.
441
427
  const uid = getUidFromConfig(ctx.config);
442
428
  if (!uid)
443
429
  return undefined;
@@ -488,51 +474,46 @@ export const xiaoyiProvider = {
488
474
  }
489
475
  }
490
476
  // ── Build dynamic headers ────────────────────────────
491
- if (ctx.extraParams) {
492
- const fallbackPrefix = ctx.extraParams[FALLBACK_PREFIX_KEY];
477
+ // Priority:
478
+ // 1. Cron-triggered: uid → cronUuid, with cron-specific headers
479
+ // 2. Xiaoyi A2A: taskId extracted from Conversation info (xiaoyi_ prefix)
480
+ // 3. UID-based fallback: sha256(uid).hex[:32]_timestamp
481
+ const isCron = isCronTriggered(context.messages);
482
+ if (isCron) {
483
+ const fallbackPrefix = ctx.extraParams?.[FALLBACK_PREFIX_KEY];
493
484
  if (typeof fallbackPrefix === "string") {
494
- // Fallback mode: generate fresh timestamp per request
495
- const isCron = isCronTriggered(context.messages);
496
485
  const fallbackValue = `${fallbackPrefix}_${Date.now()}`;
497
- dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${fallbackValue}` : fallbackValue;
486
+ dynamicHeaders[HEADER_TRACE_ID] = `cron_${fallbackValue}`;
498
487
  dynamicHeaders[HEADER_SESSION_ID] = fallbackValue;
499
488
  dynamicHeaders[HEADER_INTERACTION_ID] = fallbackValue;
500
- if (isCron) {
501
- const cronTitle = extractCronTitle(context.messages);
502
- if (cronTitle)
503
- dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
504
- if (context.messages?.length === 1)
505
- dynamicHeaders["x-cron-flag"] = "begin";
506
- }
507
- }
508
- else if (extractedTaskId) {
509
- // Session mode: taskId extracted from Conversation info
510
- const traceId = extractedTaskId;
511
- const sessionId = traceId.split("&")[0];
512
- const interactionId = traceId.split("&")[1] ?? "";
513
- const isCron = isCronTriggered(context.messages);
514
- dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
515
- if (isCron) {
516
- const cronTitle = extractCronTitle(context.messages);
517
- if (cronTitle)
518
- dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
519
- if (context.messages?.length === 1)
520
- dynamicHeaders["x-cron-flag"] = "begin";
521
- }
522
- dynamicHeaders[HEADER_SESSION_ID] = sessionId;
523
- dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
524
489
  }
525
490
  else {
526
- // Fallback: use extraParams cached values
527
- const traceId = ctx.extraParams[HEADER_TRACE_ID];
528
- const sessionId = ctx.extraParams[HEADER_SESSION_ID];
529
- const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
530
- if (typeof traceId === "string")
531
- dynamicHeaders[HEADER_TRACE_ID] = traceId;
532
- if (typeof sessionId === "string")
533
- dynamicHeaders[HEADER_SESSION_ID] = sessionId;
534
- if (typeof interactionId === "string")
535
- dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
491
+ const cronUuid = extractCronUuid(context.messages) ?? "cron";
492
+ const cronSessionId = `cron_${cronUuid}_${Date.now()}`;
493
+ dynamicHeaders[HEADER_TRACE_ID] = cronSessionId;
494
+ dynamicHeaders[HEADER_SESSION_ID] = cronUuid;
495
+ dynamicHeaders[HEADER_INTERACTION_ID] = cronSessionId;
496
+ }
497
+ const cronTitle = extractCronTitle(context.messages);
498
+ if (cronTitle)
499
+ dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
500
+ if (context.messages?.length === 1)
501
+ dynamicHeaders["x-cron-flag"] = "begin";
502
+ }
503
+ else if (extractedTaskId) {
504
+ const sessionId = extractedTaskId.split("&")[0];
505
+ const interactionId = extractedTaskId.split("&")[1] ?? "";
506
+ dynamicHeaders[HEADER_TRACE_ID] = extractedTaskId;
507
+ dynamicHeaders[HEADER_SESSION_ID] = sessionId;
508
+ dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
509
+ }
510
+ else {
511
+ const fallbackPrefix = ctx.extraParams?.[FALLBACK_PREFIX_KEY];
512
+ if (typeof fallbackPrefix === "string") {
513
+ const fallbackValue = `${fallbackPrefix}_${Date.now()}`;
514
+ dynamicHeaders[HEADER_TRACE_ID] = fallbackValue;
515
+ dynamicHeaders[HEADER_SESSION_ID] = fallbackValue;
516
+ dynamicHeaders[HEADER_INTERACTION_ID] = fallbackValue;
536
517
  }
537
518
  }
538
519
  // 记录输入
@@ -546,9 +527,8 @@ export const xiaoyiProvider = {
546
527
  logger.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
547
528
  }
548
529
  // deviceType: prefer value extracted from Conversation info,
549
- // then extraParams, then ALS fallback.
550
- const extraParamsDeviceType = ctx.extraParams?.[DEVICE_TYPE_KEY] || undefined;
551
- const deviceType = (extractedDeviceType || extraParamsDeviceType)
530
+ // then ALS fallback.
531
+ const deviceType = extractedDeviceType
552
532
  ?? getCurrentSessionContext()?.deviceType;
553
533
  // 在发送给模型前,优化 systemPrompt 结构
554
534
  if (context.systemPrompt) {