@ynhcj/xiaoyi-channel 0.0.115-beta → 0.0.115-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 (132) hide show
  1. package/dist/index.d.ts +4 -5
  2. package/dist/index.js +72 -82
  3. package/dist/provider-discovery.d.ts +2 -0
  4. package/dist/provider-discovery.js +4 -0
  5. package/dist/src/bot.d.ts +2 -0
  6. package/dist/src/bot.js +80 -72
  7. package/dist/src/channel.js +2 -17
  8. package/dist/src/client.d.ts +1 -5
  9. package/dist/src/client.js +32 -37
  10. package/dist/src/cspl/call-api.js +6 -5
  11. package/dist/src/file-download.js +4 -3
  12. package/dist/src/file-upload.js +19 -18
  13. package/dist/src/formatter.js +32 -44
  14. package/dist/src/heartbeat.js +4 -3
  15. package/dist/src/login-token-handler.js +7 -8
  16. package/dist/src/message-queue.js +2 -1
  17. package/dist/src/monitor.js +62 -41
  18. package/dist/src/outbound.js +22 -18
  19. package/dist/src/provider.d.ts +1 -1
  20. package/dist/src/provider.js +124 -34
  21. package/dist/src/push.js +16 -15
  22. package/dist/src/reply-dispatcher.js +47 -48
  23. package/dist/src/runtime.d.ts +3 -11
  24. package/dist/src/runtime.js +6 -18
  25. package/dist/src/self-evolution-handler.js +11 -14
  26. package/dist/src/self-evolution-tool-result-nudge.d.ts +3 -0
  27. package/dist/src/self-evolution-tool-result-nudge.js +96 -0
  28. package/dist/src/skill-retriever/hooks.js +7 -15
  29. package/dist/src/skill-retriever/tool-search.js +13 -9
  30. package/dist/src/steer-injector.js +1 -1
  31. package/dist/src/task-manager.js +6 -1
  32. package/dist/src/tools/calendar-tool.d.ts +2 -1
  33. package/dist/src/tools/calendar-tool.js +112 -116
  34. package/dist/src/tools/call-device-tool.d.ts +2 -1
  35. package/dist/src/tools/call-device-tool.js +126 -103
  36. package/dist/src/tools/call-phone-tool.d.ts +2 -1
  37. package/dist/src/tools/call-phone-tool.js +109 -113
  38. package/dist/src/tools/create-alarm-tool.d.ts +2 -1
  39. package/dist/src/tools/create-alarm-tool.js +227 -231
  40. package/dist/src/tools/create-all-tools.d.ts +16 -0
  41. package/dist/src/tools/create-all-tools.js +50 -0
  42. package/dist/src/tools/delete-alarm-tool.d.ts +2 -1
  43. package/dist/src/tools/delete-alarm-tool.js +131 -135
  44. package/dist/src/tools/get-alarm-tool-schema.d.ts +2 -1
  45. package/dist/src/tools/get-alarm-tool-schema.js +16 -10
  46. package/dist/src/tools/get-calendar-tool-schema.d.ts +2 -1
  47. package/dist/src/tools/get-calendar-tool-schema.js +12 -8
  48. package/dist/src/tools/get-collection-tool-schema.d.ts +2 -1
  49. package/dist/src/tools/get-collection-tool-schema.js +11 -9
  50. package/dist/src/tools/get-contact-tool-schema.d.ts +2 -1
  51. package/dist/src/tools/get-contact-tool-schema.js +16 -10
  52. package/dist/src/tools/get-device-file-tool-schema.d.ts +2 -1
  53. package/dist/src/tools/get-device-file-tool-schema.js +13 -9
  54. package/dist/src/tools/get-email-tool-schema.d.ts +2 -1
  55. package/dist/src/tools/get-email-tool-schema.js +11 -8
  56. package/dist/src/tools/get-note-tool-schema.d.ts +2 -1
  57. package/dist/src/tools/get-note-tool-schema.js +14 -9
  58. package/dist/src/tools/get-photo-tool-schema.d.ts +2 -1
  59. package/dist/src/tools/get-photo-tool-schema.js +12 -9
  60. package/dist/src/tools/image-reading-tool.d.ts +3 -2
  61. package/dist/src/tools/image-reading-tool.js +82 -162
  62. package/dist/src/tools/location-tool.d.ts +2 -1
  63. package/dist/src/tools/location-tool.js +87 -91
  64. package/dist/src/tools/login-token-tool.d.ts +2 -1
  65. package/dist/src/tools/login-token-tool.js +113 -116
  66. package/dist/src/tools/modify-alarm-tool.d.ts +2 -1
  67. package/dist/src/tools/modify-alarm-tool.js +232 -236
  68. package/dist/src/tools/modify-note-tool.d.ts +2 -1
  69. package/dist/src/tools/modify-note-tool.js +104 -108
  70. package/dist/src/tools/note-tool.d.ts +2 -1
  71. package/dist/src/tools/note-tool.js +103 -107
  72. package/dist/src/tools/query-app-message-tool.d.ts +2 -1
  73. package/dist/src/tools/query-app-message-tool.js +108 -111
  74. package/dist/src/tools/query-memory-data-tool.d.ts +2 -1
  75. package/dist/src/tools/query-memory-data-tool.js +109 -112
  76. package/dist/src/tools/query-todo-task-tool.d.ts +2 -1
  77. package/dist/src/tools/query-todo-task-tool.js +103 -106
  78. package/dist/src/tools/save-file-to-phone-tool.d.ts +2 -1
  79. package/dist/src/tools/save-file-to-phone-tool.js +127 -131
  80. package/dist/src/tools/save-media-to-gallery-tool.d.ts +2 -1
  81. package/dist/src/tools/save-media-to-gallery-tool.js +134 -138
  82. package/dist/src/tools/save-self-evolution-skill-tool.d.ts +2 -1
  83. package/dist/src/tools/save-self-evolution-skill-tool.js +194 -196
  84. package/dist/src/tools/search-alarm-tool.d.ts +2 -1
  85. package/dist/src/tools/search-alarm-tool.js +171 -175
  86. package/dist/src/tools/search-calendar-tool.d.ts +2 -1
  87. package/dist/src/tools/search-calendar-tool.js +145 -149
  88. package/dist/src/tools/search-contact-tool.d.ts +2 -1
  89. package/dist/src/tools/search-contact-tool.js +98 -102
  90. package/dist/src/tools/search-email-tool.d.ts +2 -1
  91. package/dist/src/tools/search-email-tool.js +107 -111
  92. package/dist/src/tools/search-file-tool.d.ts +2 -1
  93. package/dist/src/tools/search-file-tool.js +99 -103
  94. package/dist/src/tools/search-message-tool.d.ts +2 -1
  95. package/dist/src/tools/search-message-tool.js +100 -104
  96. package/dist/src/tools/search-note-tool.d.ts +2 -1
  97. package/dist/src/tools/search-note-tool.js +95 -99
  98. package/dist/src/tools/search-photo-gallery-tool.d.ts +2 -1
  99. package/dist/src/tools/search-photo-gallery-tool.js +34 -38
  100. package/dist/src/tools/send-email-tool.d.ts +2 -1
  101. package/dist/src/tools/send-email-tool.js +105 -108
  102. package/dist/src/tools/send-file-to-user-tool.d.ts +2 -1
  103. package/dist/src/tools/send-file-to-user-tool.js +157 -155
  104. package/dist/src/tools/send-message-tool.d.ts +2 -1
  105. package/dist/src/tools/send-message-tool.js +119 -123
  106. package/dist/src/tools/session-helper.d.ts +24 -0
  107. package/dist/src/tools/session-helper.js +45 -0
  108. package/dist/src/tools/session-manager.d.ts +29 -6
  109. package/dist/src/tools/session-manager.js +134 -19
  110. package/dist/src/tools/upload-file-tool.d.ts +2 -1
  111. package/dist/src/tools/upload-file-tool.js +78 -82
  112. package/dist/src/tools/upload-photo-tool.d.ts +2 -1
  113. package/dist/src/tools/upload-photo-tool.js +69 -73
  114. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +2 -1
  115. package/dist/src/tools/xiaoyi-add-collection-tool.js +143 -147
  116. package/dist/src/tools/xiaoyi-collection-tool.d.ts +2 -1
  117. package/dist/src/tools/xiaoyi-collection-tool.js +111 -115
  118. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +2 -1
  119. package/dist/src/tools/xiaoyi-delete-collection-tool.js +124 -128
  120. package/dist/src/tools/xiaoyi-gui-tool.d.ts +2 -1
  121. package/dist/src/tools/xiaoyi-gui-tool.js +87 -88
  122. package/dist/src/trigger-handler.js +8 -9
  123. package/dist/src/utils/logger.js +105 -19
  124. package/dist/src/utils/self-evolution-manager.d.ts +5 -0
  125. package/dist/src/utils/self-evolution-manager.js +45 -23
  126. package/dist/src/utils/throw.d.ts +5 -0
  127. package/dist/src/utils/throw.js +10 -0
  128. package/dist/src/websocket.js +35 -31
  129. package/dist/src/xy-session-store.d.ts +79 -0
  130. package/dist/src/xy-session-store.js +153 -0
  131. package/openclaw.plugin.json +22 -0
  132. package/package.json +7 -6
@@ -8,6 +8,8 @@ import { handleTriggerEvent } from "./trigger-handler.js";
8
8
  import { handleSelfEvolutionEvent, handleSelfEvolutionStateGetEvent } from "./self-evolution-handler.js";
9
9
  import { handleLoginTokenEvent } from "./login-token-handler.js";
10
10
  import { cleanupStaleTempFiles } from "./reply-dispatcher.js";
11
+ import { cleanupStaleSessions, getActiveSessionCount, cleanupAllSessions } from "./tools/session-manager.js";
12
+ import { logger } from "./utils/logger.js";
11
13
  /**
12
14
  * Per-session serial queue that ensures messages from the same session are processed
13
15
  * in arrival order while allowing different sessions to run concurrently.
@@ -37,8 +39,6 @@ export async function monitorXYProvider(opts = {}) {
37
39
  throw new Error("Config is required for XY monitor");
38
40
  }
39
41
  const runtime = opts.runtime;
40
- const log = runtime?.log ?? console.log;
41
- const error = runtime?.error ?? console.error;
42
42
  const account = resolveXYConfig(cfg);
43
43
  if (!account.enabled) {
44
44
  throw new Error(`XY account is disabled`);
@@ -51,10 +51,10 @@ export async function monitorXYProvider(opts = {}) {
51
51
  }
52
52
  : undefined;
53
53
  // 🔍 Diagnose WebSocket managers before gateway start
54
- console.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
- const wsManager = getXYWebSocketManager(account);
57
+ const wsManager = getXYWebSocketManager(account, runtime);
58
58
  // ✅ Set health event callback for heartbeat reporting
59
59
  if (trackEvent) {
60
60
  wsManager.setHealthEventCallback(trackEvent);
@@ -65,21 +65,32 @@ export async function monitorXYProvider(opts = {}) {
65
65
  const activeMessages = new Set();
66
66
  // Create session queue for ordered message processing
67
67
  const enqueue = createSessionQueue();
68
+ // Global gate that serializes dispatch initialization across sessions.
69
+ // When a new session starts dispatching, it acquires this gate and holds it
70
+ // until agent setup (agentTools + wrapStreamFn) is complete, then releases it.
71
+ // This prevents lastRegisteredKey races when multiple sessions initialize
72
+ // concurrently.
73
+ let globalDispatchInitGate = Promise.resolve();
68
74
  // Health check interval
69
75
  let healthCheckInterval = null;
70
76
  return new Promise((resolve, reject) => {
71
77
  // Event handlers (defined early so they can be referenced in cleanup)
72
78
  const messageHandler = (message, sessionId, serverId) => {
73
79
  const messageKey = `${sessionId}::${message.id}`;
74
- log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
80
+ logger.log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
75
81
  // ✅ Report health: received a message
76
82
  trackEvent?.();
77
83
  // Check for duplicate message handling
78
84
  if (activeMessages.has(messageKey)) {
79
- 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}, this may cause duplicate dispatchers!`);
80
86
  }
81
87
  activeMessages.add(messageKey);
82
88
  const task = async () => {
89
+ // Wait for the previous session's init to complete (global gate),
90
+ // then acquire the gate for this session's init.
91
+ await globalDispatchInitGate;
92
+ let releaseGate;
93
+ globalDispatchInitGate = new Promise((r) => { releaseGate = r; });
83
94
  try {
84
95
  await handleXYMessage({
85
96
  cfg,
@@ -87,11 +98,13 @@ export async function monitorXYProvider(opts = {}) {
87
98
  message,
88
99
  accountId, // ✅ Pass accountId ("default")
89
100
  webSocketSessionId: sessionId, // ✅ 传递 WebSocket 层级的 sessionId
101
+ onInitComplete: () => releaseGate(),
90
102
  });
91
103
  }
92
104
  catch (err) {
93
105
  // ✅ Only log error, don't re-throw to prevent gateway restart
94
- error(`XY gateway: error handling message from ${serverId}: ${String(err)}`);
106
+ releaseGate();
107
+ logger.error(`XY gateway: error handling message from ${serverId}: ${String(err)}`);
95
108
  }
96
109
  finally {
97
110
  // Remove from active messages when done
@@ -106,33 +119,33 @@ export async function monitorXYProvider(opts = {}) {
106
119
  const hasActiveRun = hasActiveTask(parsed.sessionId);
107
120
  if (steerMode && hasActiveRun) {
108
121
  // Steer模式且有活跃任务:不入队列,直接并发执行
109
- log(`[MONITOR-HANDLER] 🔄 STEER MODE: Executing concurrently for messageKey=${messageKey}`);
110
- log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
122
+ logger.log(`[MONITOR-HANDLER] 🔄 STEER MODE: Executing concurrently for messageKey=${messageKey}`);
123
+ logger.log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
111
124
  void task().catch((err) => {
112
- error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
125
+ logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
113
126
  activeMessages.delete(messageKey);
114
127
  });
115
128
  }
116
129
  else {
117
130
  // 正常模式:入队列串行执行
118
131
  void enqueue(sessionId, task).catch((err) => {
119
- error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
132
+ logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
120
133
  activeMessages.delete(messageKey);
121
134
  });
122
135
  }
123
136
  }
124
137
  catch (parseErr) {
125
138
  // 解析失败,回退到正常队列模式
126
- error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
139
+ logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
127
140
  void enqueue(sessionId, task).catch((err) => {
128
- error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
141
+ logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
129
142
  activeMessages.delete(messageKey);
130
143
  });
131
144
  }
132
145
  };
133
146
  const connectedHandler = (serverId) => {
134
147
  if (!loggedServers.has(serverId)) {
135
- log(`XY gateway: ${serverId} connected`);
148
+ logger.log(`XY gateway: ${serverId} connected`);
136
149
  loggedServers.add(serverId);
137
150
  }
138
151
  // ✅ Report health: connection established
@@ -140,7 +153,7 @@ export async function monitorXYProvider(opts = {}) {
140
153
  opts.setStatus?.({ connected: true });
141
154
  };
142
155
  const disconnectedHandler = (serverId) => {
143
- console.warn(`XY gateway: ${serverId} disconnected`);
156
+ logger.log(`XY gateway: ${serverId} disconnected`);
144
157
  loggedServers.delete(serverId);
145
158
  // ✅ Report disconnection status (only if all servers disconnected)
146
159
  if (loggedServers.size === 0) {
@@ -148,41 +161,41 @@ export async function monitorXYProvider(opts = {}) {
148
161
  }
149
162
  };
150
163
  const errorHandler = (err, serverId) => {
151
- error(`XY gateway: ${serverId} error: ${String(err)}`);
164
+ logger.error(`XY gateway: ${serverId} error: ${String(err)}`);
152
165
  };
153
166
  const triggerEventHandler = (context) => {
154
- log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
155
- log(`[MONITOR] - sessionId: ${context.sessionId}`);
156
- log(`[MONITOR] - taskId: ${context.taskId}`);
167
+ logger.log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
168
+ logger.log(`[MONITOR] - sessionId: ${context.sessionId}`);
169
+ logger.log(`[MONITOR] - taskId: ${context.taskId}`);
157
170
  // 异步处理 Trigger 事件,不阻塞主流程
158
171
  handleTriggerEvent(context, cfg, runtime, accountId).catch((err) => {
159
- error(`[MONITOR] Failed to handle trigger-event:`, err);
172
+ logger.error(`[MONITOR] Failed to handle trigger-event:`, err);
160
173
  });
161
174
  };
162
175
  const selfEvolutionHandler = (context) => {
163
- log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
176
+ logger.log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
164
177
  handleSelfEvolutionEvent(context, runtime);
165
178
  };
166
179
  const selfEvolutionStateGetHandler = (context) => {
167
- log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
180
+ logger.log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
168
181
  handleSelfEvolutionStateGetEvent(context, account, runtime, wsManager).catch((err) => {
169
- error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
182
+ logger.error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
170
183
  });
171
184
  };
172
185
  const loginTokenEventHandler = (context) => {
173
- log(`[MONITOR] Received login-token-event, dispatching to handler...`);
186
+ logger.log(`[MONITOR] Received login-token-event, dispatching to handler...`);
174
187
  handleLoginTokenEvent(context, runtime);
175
188
  };
176
189
  const cleanup = () => {
177
- log("XY gateway: cleaning up...");
190
+ logger.log("XY gateway: cleaning up...");
178
191
  // 🔍 Diagnose before cleanup
179
- console.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
192
+ logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
180
193
  diagnoseAllManagers();
181
194
  // Stop health check interval
182
195
  if (healthCheckInterval) {
183
196
  clearInterval(healthCheckInterval);
184
197
  healthCheckInterval = null;
185
- console.log("⏸️ Stopped periodic health check");
198
+ logger.log("⏸️ Stopped periodic health check");
186
199
  }
187
200
  // Remove event handlers to prevent duplicate calls on gateway restart
188
201
  wsManager.off("message", messageHandler);
@@ -198,22 +211,24 @@ export async function monitorXYProvider(opts = {}) {
198
211
  wsManager.disconnect();
199
212
  // ✅ Remove manager from cache to prevent reusing dirty state
200
213
  removeXYWebSocketManager(account);
214
+ // Clean up all active sessions
215
+ cleanupAllSessions();
201
216
  loggedServers.clear();
202
217
  activeMessages.clear();
203
- log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages`);
218
+ logger.log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
204
219
  // 🔍 Diagnose after cleanup
205
- console.log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
220
+ logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
206
221
  diagnoseAllManagers();
207
222
  };
208
223
  const handleAbort = async () => {
209
- log("XY gateway: abort signal received, sending notifications before stopping");
224
+ logger.log("XY gateway: abort signal received, sending notifications before stopping");
210
225
  // 📤 Send restart notification to all active sessions before disconnecting
211
226
  try {
212
227
  const activeBindings = getAllActiveTaskBindings();
213
228
  if (activeBindings.length > 0) {
214
229
  const config = resolveXYConfig(cfg);
215
230
  const notificationText = "Gateway即将重启,重启期间可能短暂出现\u201c环境异常\u201d提示,请稍候并耐心重试~";
216
- log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
231
+ logger.log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
217
232
  const sendPromises = activeBindings.map(binding => sendA2AResponse({
218
233
  config,
219
234
  sessionId: binding.sessionId,
@@ -223,20 +238,20 @@ export async function monitorXYProvider(opts = {}) {
223
238
  append: false,
224
239
  final: true,
225
240
  }).catch(err => {
226
- error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
241
+ logger.error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
227
242
  }));
228
243
  await Promise.all(sendPromises);
229
- log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
244
+ logger.log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
230
245
  }
231
246
  else {
232
- log(`[MONITOR] No active sessions, skipping restart notifications`);
247
+ logger.log(`[MONITOR] No active sessions, skipping restart notifications`);
233
248
  }
234
249
  }
235
250
  catch (err) {
236
- error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
251
+ logger.error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
237
252
  }
238
253
  cleanup();
239
- log("XY gateway stopped");
254
+ logger.log("XY gateway stopped");
240
255
  resolve();
241
256
  };
242
257
  if (opts.abortSignal?.aborted) {
@@ -255,14 +270,20 @@ export async function monitorXYProvider(opts = {}) {
255
270
  wsManager.on("self-evolution-state-get-event", selfEvolutionStateGetHandler);
256
271
  wsManager.on("login-token-event", loginTokenEventHandler);
257
272
  // Start periodic health check (every 6 hours)
258
- console.log("🏥 Starting periodic health check (every 6 hours)...");
273
+ logger.log("🏥 Starting periodic health check (every 6 hours)...");
259
274
  healthCheckInterval = setInterval(() => {
260
- console.log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
275
+ logger.log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
261
276
  diagnoseAllManagers();
262
277
  // Auto-cleanup orphan connections
263
278
  const cleaned = cleanupOrphanConnections();
264
279
  if (cleaned > 0) {
265
- console.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
280
+ logger.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
281
+ }
282
+ // Cleanup stale sessions (older than 10min TTL)
283
+ const cleanedSessions = cleanupStaleSessions();
284
+ const remainingSessions = getActiveSessionCount();
285
+ if (cleanedSessions > 0 || remainingSessions > 0) {
286
+ logger.log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
266
287
  }
267
288
  // Cleanup stale temp files (older than 24 hours)
268
289
  void cleanupStaleTempFiles();
@@ -270,11 +291,11 @@ export async function monitorXYProvider(opts = {}) {
270
291
  // Connect to WebSocket servers
271
292
  wsManager.connect()
272
293
  .then(() => {
273
- log("XY gateway: started successfully");
294
+ logger.log("XY gateway: started successfully");
274
295
  })
275
296
  .catch((err) => {
276
297
  // Connection failed but don't reject - continue monitoring for reconnection
277
- error(`XY gateway: initial connection failed: ${String(err)}`);
298
+ logger.error(`XY gateway: initial connection failed: ${String(err)}`);
278
299
  // Still resolve successfully so plugin starts
279
300
  resolve();
280
301
  });
@@ -4,6 +4,7 @@ import { XYPushService } from "./push.js";
4
4
  import { getCurrentSessionContext } from "./tools/session-manager.js";
5
5
  import { savePushData } from "./utils/pushdata-manager.js";
6
6
  import { getAllPushIds } from "./utils/pushid-manager.js";
7
+ import { logger } from "./utils/logger.js";
7
8
  // Special marker for default push delivery when no target is specified
8
9
  const DEFAULT_PUSH_MARKER = "default";
9
10
  // File extension to MIME type mapping
@@ -57,7 +58,7 @@ export const xyOutbound = {
57
58
  resolveTarget: ({ cfg, to, accountId, mode }) => {
58
59
  // If no target provided, use default marker for push delivery
59
60
  if (!to || to.trim() === "") {
60
- console.log(`[xyOutbound.resolveTarget] No target specified, using default push marker`);
61
+ logger.log(`[xyOutbound.resolveTarget] No target specified, using default push marker`);
61
62
  return {
62
63
  ok: true,
63
64
  to: DEFAULT_PUSH_MARKER,
@@ -66,24 +67,24 @@ export const xyOutbound = {
66
67
  const trimmedTo = to.trim();
67
68
  // If the target doesn't contain "::", try to enhance it with taskId from session context
68
69
  if (!trimmedTo.includes("::")) {
69
- console.log(`[xyOutbound.resolveTarget] Target "${trimmedTo}" missing taskId, looking up session context`);
70
+ logger.log(`[xyOutbound.resolveTarget] Target "${trimmedTo}" missing taskId, looking up session context`);
70
71
  // Try to get the current session context
71
72
  const sessionContext = getCurrentSessionContext();
72
73
  if (sessionContext && sessionContext.sessionId === trimmedTo) {
73
74
  const enhancedTarget = `${trimmedTo}::${sessionContext.taskId}`;
74
- console.log(`[xyOutbound.resolveTarget] Enhanced target: ${enhancedTarget}`);
75
+ logger.log(`[xyOutbound.resolveTarget] Enhanced target: ${enhancedTarget}`);
75
76
  return {
76
77
  ok: true,
77
78
  to: enhancedTarget,
78
79
  };
79
80
  }
80
81
  else {
81
- console.log(`[xyOutbound.resolveTarget] Could not find matching session context for "${trimmedTo}"`);
82
+ logger.log(`[xyOutbound.resolveTarget] Could not find matching session context for "${trimmedTo}"`);
82
83
  // Still return the original target, but it may fail in sendMedia
83
84
  }
84
85
  }
85
86
  // Otherwise, use the provided target (either already in correct format or for sendText)
86
- console.log(`[xyOutbound.resolveTarget] Using provided target:`, trimmedTo);
87
+ logger.log(`[xyOutbound.resolveTarget] Using provided target:`, trimmedTo);
87
88
  return {
88
89
  ok: true,
89
90
  to: trimmedTo,
@@ -95,36 +96,36 @@ export const xyOutbound = {
95
96
  // Handle default push marker (for cron jobs without explicit target)
96
97
  let actualTo = to;
97
98
  if (to === DEFAULT_PUSH_MARKER) {
98
- console.log(`[xyOutbound.sendText] Using default push delivery (no specific target)`);
99
+ logger.log(`[xyOutbound.sendText] Using default push delivery (no specific target)`);
99
100
  // For push notifications, we don't need a specific target
100
101
  // The push service will handle it based on config
101
102
  actualTo = config.defaultSessionId || "";
102
103
  }
103
104
  // 1. 持久化推送消息内容,获取 pushDataId
104
- console.log(`[xyOutbound.sendText] Saving push data to local storage...`);
105
+ logger.log(`[xyOutbound.sendText] Saving push data to local storage...`);
105
106
  let pushDataId;
106
107
  try {
107
108
  pushDataId = await savePushData(text);
108
- console.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)}`);
109
110
  }
110
111
  catch (error) {
111
- console.error(`[xyOutbound.sendText] ❌ Failed to save push data:`, error);
112
+ logger.error(`[xyOutbound.sendText] ❌ Failed to save push data:`, error);
112
113
  // 如果持久化失败,仍然继续发送(不阻塞主流程)
113
114
  pushDataId = "";
114
115
  }
115
116
  // 2. 读取所有 pushId
116
- console.log(`[xyOutbound.sendText] Loading all pushIds...`);
117
+ logger.log(`[xyOutbound.sendText] Loading all pushIds...`);
117
118
  let pushIdList = [];
118
119
  try {
119
120
  pushIdList = await getAllPushIds();
120
- console.log(`[xyOutbound.sendText] ✅ Loaded ${pushIdList.length} pushIds`);
121
+ logger.log(`[xyOutbound.sendText] ✅ Loaded ${pushIdList.length} pushIds`);
121
122
  }
122
123
  catch (error) {
123
- console.error(`[xyOutbound.sendText] ❌ Failed to load pushIds:`, error);
124
+ logger.error(`[xyOutbound.sendText] ❌ Failed to load pushIds:`, error);
124
125
  }
125
126
  // 3. 如果 pushIdList 为空,回退到原有逻辑(使用 config pushId)
126
127
  if (pushIdList.length === 0) {
127
- console.log(`[xyOutbound.sendText] ⚠️ No pushIds found, falling back to config pushId`);
128
+ logger.log(`[xyOutbound.sendText] ⚠️ No pushIds found, falling back to config pushId`);
128
129
  pushIdList = [config.pushId];
129
130
  }
130
131
  // Create push service
@@ -134,7 +135,7 @@ export const xyOutbound = {
134
135
  // Truncate push content to max length 1000
135
136
  const pushText = text.length > 1000 ? text.slice(0, 1000) : text;
136
137
  // 4. 遍历所有 pushId,依次发送推送通知
137
- console.log(`[xyOutbound.sendText] 📤 Broadcasting to ${pushIdList.length} pushId(s)...`);
138
+ logger.log(`[xyOutbound.sendText] 📤 Broadcasting to ${pushIdList.length} pushId(s)...`);
138
139
  let successCount = 0;
139
140
  let failureCount = 0;
140
141
  for (const pushId of pushIdList) {
@@ -142,11 +143,11 @@ export const xyOutbound = {
142
143
  // 传入 pushId 和 pushDataId,使用 kind="data" 格式
143
144
  await pushService.sendPush(pushText, title, undefined, actualTo, pushDataId, pushId);
144
145
  successCount++;
145
- console.log(`[xyOutbound.sendText] ✅ Sent successfully to pushId: ${pushId.substring(0, 20)}...`);
146
+ logger.log(`[xyOutbound.sendText] ✅ Sent successfully to pushId: ${pushId.substring(0, 20)}...`);
146
147
  }
147
148
  catch (error) {
148
149
  failureCount++;
149
- console.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);
150
151
  // 单个 pushId 发送失败不影响其他,继续处理下一个
151
152
  }
152
153
  }
@@ -161,6 +162,7 @@ export const xyOutbound = {
161
162
  // Parse to: "sessionId::taskId"
162
163
  const parts = to.split("::");
163
164
  if (parts.length !== 2) {
165
+ logger.error(`Invalid to format: "${to}". Expected "sessionId::taskId"`);
164
166
  throw new Error(`Invalid to format: "${to}". Expected "sessionId::taskId"`);
165
167
  }
166
168
  const [sessionId, taskId] = parts;
@@ -170,15 +172,17 @@ export const xyOutbound = {
170
172
  const uploadService = new XYFileUploadService(config.fileUploadUrl, config.apiKey, config.uid);
171
173
  // Validate mediaUrl
172
174
  if (!mediaUrl) {
175
+ logger.error("mediaUrl is required for sendMedia");
173
176
  throw new Error("mediaUrl is required for sendMedia");
174
177
  }
175
178
  // Upload file
176
179
  const fileId = await uploadService.uploadFile(mediaUrl);
177
180
  // Check if fileId is empty (should not happen if uploadFile throws on failure)
178
181
  if (!fileId) {
182
+ logger.error(`File upload returned empty fileId for: ${mediaUrl}`);
179
183
  throw new Error(`File upload returned empty fileId for: ${mediaUrl}`);
180
184
  }
181
- console.log(`[xyOutbound.sendMedia] File uploaded:`, {
185
+ logger.log(`[xyOutbound.sendMedia] File uploaded:`, {
182
186
  fileId,
183
187
  sessionId,
184
188
  taskId,
@@ -222,7 +226,7 @@ export const xyOutbound = {
222
226
  const { getXYWebSocketManager } = await import("./client.js");
223
227
  const wsManager = getXYWebSocketManager(config);
224
228
  await wsManager.sendMessage(sessionId, agentResponse);
225
- console.log(`[xyOutbound.sendMedia] WebSocket message sent successfully`);
229
+ logger.log(`[xyOutbound.sendMedia] WebSocket message sent successfully`);
226
230
  // Return message info
227
231
  return {
228
232
  channel: "xiaoyi-channel",
@@ -1,3 +1,3 @@
1
- import type { ProviderPlugin } from "openclaw/plugin-sdk/provider-models";
1
+ import type { ProviderPlugin } from "openclaw/plugin-sdk/provider-model-shared";
2
2
  export declare function applySelfEvolutionPrompt(systemPrompt: string | undefined, enabled: boolean): string;
3
3
  export declare const xiaoyiProvider: ProviderPlugin;