@ynhcj/xiaoyi-channel 0.0.103-beta β†’ 0.0.103-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 (133) hide show
  1. package/dist/index.d.ts +4 -5
  2. package/dist/index.js +77 -136
  3. package/dist/provider-discovery.d.ts +2 -0
  4. package/dist/provider-discovery.js +4 -0
  5. package/dist/src/bot.js +30 -4
  6. package/dist/src/channel.js +2 -21
  7. package/dist/src/client.js +31 -22
  8. package/dist/src/cspl/call-api.js +6 -5
  9. package/dist/src/file-download.js +4 -3
  10. package/dist/src/file-upload.js +19 -18
  11. package/dist/src/formatter.d.ts +2 -0
  12. package/dist/src/formatter.js +25 -35
  13. package/dist/src/heartbeat.js +1 -1
  14. package/dist/src/message-queue.d.ts +17 -0
  15. package/dist/src/message-queue.js +51 -0
  16. package/dist/src/monitor.js +63 -14
  17. package/dist/src/outbound.js +19 -18
  18. package/dist/src/provider.d.ts +2 -1
  19. package/dist/src/provider.js +215 -68
  20. package/dist/src/push.js +16 -15
  21. package/dist/src/reply-dispatcher.js +12 -3
  22. package/dist/src/runtime.d.ts +3 -11
  23. package/dist/src/runtime.js +6 -18
  24. package/dist/src/self-evolution-handler.d.ts +6 -0
  25. package/dist/src/self-evolution-handler.js +100 -7
  26. package/dist/src/self-evolution-keyword.d.ts +9 -0
  27. package/dist/src/self-evolution-keyword.js +147 -0
  28. package/dist/src/self-evolution-tool-result-nudge.d.ts +3 -0
  29. package/dist/src/self-evolution-tool-result-nudge.js +96 -0
  30. package/dist/src/skill-retriever/hooks.js +7 -15
  31. package/dist/src/skill-retriever/tool-search.js +22 -8
  32. package/dist/src/skill-retriever/types.d.ts +2 -0
  33. package/dist/src/steer-injector.js +1 -1
  34. package/dist/src/task-manager.d.ts +4 -0
  35. package/dist/src/task-manager.js +12 -1
  36. package/dist/src/tools/calendar-tool.d.ts +2 -1
  37. package/dist/src/tools/calendar-tool.js +112 -116
  38. package/dist/src/tools/call-device-tool.d.ts +2 -1
  39. package/dist/src/tools/call-device-tool.js +126 -103
  40. package/dist/src/tools/call-phone-tool.d.ts +2 -1
  41. package/dist/src/tools/call-phone-tool.js +109 -113
  42. package/dist/src/tools/create-alarm-tool.d.ts +2 -1
  43. package/dist/src/tools/create-alarm-tool.js +227 -231
  44. package/dist/src/tools/create-all-tools.d.ts +16 -0
  45. package/dist/src/tools/create-all-tools.js +50 -0
  46. package/dist/src/tools/delete-alarm-tool.d.ts +2 -1
  47. package/dist/src/tools/delete-alarm-tool.js +131 -135
  48. package/dist/src/tools/get-alarm-tool-schema.d.ts +2 -1
  49. package/dist/src/tools/get-alarm-tool-schema.js +16 -10
  50. package/dist/src/tools/get-calendar-tool-schema.d.ts +2 -1
  51. package/dist/src/tools/get-calendar-tool-schema.js +12 -8
  52. package/dist/src/tools/get-collection-tool-schema.d.ts +2 -1
  53. package/dist/src/tools/get-collection-tool-schema.js +11 -9
  54. package/dist/src/tools/get-contact-tool-schema.d.ts +2 -1
  55. package/dist/src/tools/get-contact-tool-schema.js +16 -10
  56. package/dist/src/tools/get-device-file-tool-schema.d.ts +2 -1
  57. package/dist/src/tools/get-device-file-tool-schema.js +13 -9
  58. package/dist/src/tools/get-email-tool-schema.d.ts +2 -1
  59. package/dist/src/tools/get-email-tool-schema.js +11 -8
  60. package/dist/src/tools/get-note-tool-schema.d.ts +2 -1
  61. package/dist/src/tools/get-note-tool-schema.js +14 -9
  62. package/dist/src/tools/get-photo-tool-schema.d.ts +2 -1
  63. package/dist/src/tools/get-photo-tool-schema.js +12 -9
  64. package/dist/src/tools/image-reading-tool.d.ts +3 -2
  65. package/dist/src/tools/image-reading-tool.js +82 -162
  66. package/dist/src/tools/location-tool.d.ts +2 -1
  67. package/dist/src/tools/location-tool.js +87 -91
  68. package/dist/src/tools/login-token-tool.d.ts +3 -2
  69. package/dist/src/tools/login-token-tool.js +114 -117
  70. package/dist/src/tools/modify-alarm-tool.d.ts +2 -1
  71. package/dist/src/tools/modify-alarm-tool.js +232 -236
  72. package/dist/src/tools/modify-note-tool.d.ts +2 -1
  73. package/dist/src/tools/modify-note-tool.js +104 -108
  74. package/dist/src/tools/note-tool.d.ts +2 -1
  75. package/dist/src/tools/note-tool.js +103 -107
  76. package/dist/src/tools/query-app-message-tool.d.ts +2 -1
  77. package/dist/src/tools/query-app-message-tool.js +108 -111
  78. package/dist/src/tools/query-memory-data-tool.d.ts +2 -1
  79. package/dist/src/tools/query-memory-data-tool.js +109 -112
  80. package/dist/src/tools/query-todo-task-tool.d.ts +2 -1
  81. package/dist/src/tools/query-todo-task-tool.js +103 -106
  82. package/dist/src/tools/save-file-to-phone-tool.d.ts +2 -1
  83. package/dist/src/tools/save-file-to-phone-tool.js +127 -131
  84. package/dist/src/tools/save-media-to-gallery-tool.d.ts +2 -1
  85. package/dist/src/tools/save-media-to-gallery-tool.js +134 -138
  86. package/dist/src/tools/save-self-evolution-skill-tool.d.ts +2 -1
  87. package/dist/src/tools/save-self-evolution-skill-tool.js +346 -125
  88. package/dist/src/tools/search-alarm-tool.d.ts +2 -1
  89. package/dist/src/tools/search-alarm-tool.js +171 -175
  90. package/dist/src/tools/search-calendar-tool.d.ts +2 -1
  91. package/dist/src/tools/search-calendar-tool.js +145 -149
  92. package/dist/src/tools/search-contact-tool.d.ts +2 -1
  93. package/dist/src/tools/search-contact-tool.js +98 -102
  94. package/dist/src/tools/search-email-tool.d.ts +2 -1
  95. package/dist/src/tools/search-email-tool.js +107 -111
  96. package/dist/src/tools/search-file-tool.d.ts +2 -1
  97. package/dist/src/tools/search-file-tool.js +99 -103
  98. package/dist/src/tools/search-message-tool.d.ts +2 -1
  99. package/dist/src/tools/search-message-tool.js +100 -104
  100. package/dist/src/tools/search-note-tool.d.ts +2 -1
  101. package/dist/src/tools/search-note-tool.js +95 -99
  102. package/dist/src/tools/search-photo-gallery-tool.d.ts +2 -1
  103. package/dist/src/tools/search-photo-gallery-tool.js +34 -38
  104. package/dist/src/tools/send-email-tool.d.ts +2 -1
  105. package/dist/src/tools/send-email-tool.js +105 -108
  106. package/dist/src/tools/send-file-to-user-tool.d.ts +2 -1
  107. package/dist/src/tools/send-file-to-user-tool.js +158 -155
  108. package/dist/src/tools/send-message-tool.d.ts +2 -1
  109. package/dist/src/tools/send-message-tool.js +119 -123
  110. package/dist/src/tools/session-manager.d.ts +21 -6
  111. package/dist/src/tools/session-manager.js +145 -18
  112. package/dist/src/tools/upload-file-tool.d.ts +2 -1
  113. package/dist/src/tools/upload-file-tool.js +78 -82
  114. package/dist/src/tools/upload-photo-tool.d.ts +2 -1
  115. package/dist/src/tools/upload-photo-tool.js +69 -73
  116. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +2 -1
  117. package/dist/src/tools/xiaoyi-add-collection-tool.js +143 -147
  118. package/dist/src/tools/xiaoyi-collection-tool.d.ts +2 -1
  119. package/dist/src/tools/xiaoyi-collection-tool.js +111 -115
  120. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +2 -1
  121. package/dist/src/tools/xiaoyi-delete-collection-tool.js +124 -128
  122. package/dist/src/tools/xiaoyi-gui-tool.d.ts +2 -1
  123. package/dist/src/tools/xiaoyi-gui-tool.js +87 -88
  124. package/dist/src/utils/logger.js +20 -18
  125. package/dist/src/utils/runtime-manager.js +24 -2
  126. package/dist/src/utils/self-evolution-manager.d.ts +5 -0
  127. package/dist/src/utils/self-evolution-manager.js +46 -24
  128. package/dist/src/utils/tool-call-nudge-manager.d.ts +1 -1
  129. package/dist/src/utils/tool-call-nudge-manager.js +1 -1
  130. package/dist/src/websocket.d.ts +3 -0
  131. package/dist/src/websocket.js +81 -28
  132. package/openclaw.plugin.json +22 -0
  133. package/package.json +3 -3
@@ -3,13 +3,14 @@
3
3
  import fetch from "node-fetch";
4
4
  import fs from "fs/promises";
5
5
  import os from "os";
6
+ import { logger } from "./utils/logger.js";
6
7
  import path from "path";
7
8
  import { calculateSHA256 } from "./utils/crypto.js";
8
9
  function isRemoteUrl(filePath) {
9
10
  return filePath.startsWith("http://") || filePath.startsWith("https://");
10
11
  }
11
12
  async function downloadToTempFile(url) {
12
- console.log(`[XY File Upload] Downloading remote file: ${url}`);
13
+ logger.log(`[XY File Upload] Downloading remote file: ${url}`);
13
14
  const response = await fetch(url);
14
15
  if (!response.ok) {
15
16
  throw new Error(`Failed to download remote file: HTTP ${response.status}`);
@@ -18,7 +19,7 @@ async function downloadToTempFile(url) {
18
19
  const urlFileName = path.basename(new URL(url).pathname) || "download";
19
20
  const tempPath = path.join(os.tmpdir(), `xy-upload-${Date.now()}-${urlFileName}`);
20
21
  await fs.writeFile(tempPath, buffer);
21
- console.log(`[XY File Upload] Downloaded to temp file: ${tempPath}`);
22
+ logger.log(`[XY File Upload] Downloaded to temp file: ${tempPath}`);
22
23
  return tempPath;
23
24
  }
24
25
  /**
@@ -39,7 +40,7 @@ export class XYFileUploadService {
39
40
  * Returns the objectId (as fileId) for use in A2A messages.
40
41
  */
41
42
  async uploadFile(filePath, objectType = "TEMPORARY_MATERIAL_DOC") {
42
- console.log(`[XY File Upload] Starting file upload: ${filePath}`);
43
+ logger.log(`[XY File Upload] Starting file upload: ${filePath}`);
43
44
  let localFilePath = filePath;
44
45
  let isTempFile = false;
45
46
  try {
@@ -54,7 +55,7 @@ export class XYFileUploadService {
54
55
  const fileSha256 = calculateSHA256(fileBuffer);
55
56
  const fileSize = fileBuffer.length;
56
57
  // Phase 1: Prepare
57
- console.log(`[XY File Upload] Phase 1: Prepare upload for ${fileName}`);
58
+ logger.log(`[XY File Upload] Phase 1: Prepare upload for ${fileName}`);
58
59
  const prepareResp = await fetch(`${this.baseUrl}/osms/v1/file/manager/prepare`, {
59
60
  method: "POST",
60
61
  headers: {
@@ -84,7 +85,7 @@ export class XYFileUploadService {
84
85
  }
85
86
  const { objectId, draftId, uploadInfos } = prepareData;
86
87
  // Phase 2: Upload
87
- console.log(`[XY File Upload] Phase 2: Upload file data`);
88
+ logger.log(`[XY File Upload] Phase 2: Upload file data`);
88
89
  const uploadInfo = uploadInfos[0]; // Single-part upload
89
90
  const uploadResp = await fetch(uploadInfo.url, {
90
91
  method: uploadInfo.method,
@@ -95,9 +96,9 @@ export class XYFileUploadService {
95
96
  const uploadErrorText = await uploadResp.text();
96
97
  throw new Error(`Upload failed: HTTP ${uploadResp.status}`);
97
98
  }
98
- console.log(`[XY File Upload] Upload complete`);
99
+ logger.log(`[XY File Upload] Upload complete`);
99
100
  // Phase 3: Complete
100
- console.log(`[XY File Upload] Phase 3: Complete upload`);
101
+ logger.log(`[XY File Upload] Phase 3: Complete upload`);
101
102
  const completeResp = await fetch(`${this.baseUrl}/osms/v1/file/manager/complete`, {
102
103
  method: "POST",
103
104
  headers: {
@@ -115,11 +116,11 @@ export class XYFileUploadService {
115
116
  throw new Error(`Complete failed: HTTP ${completeResp.status}`);
116
117
  }
117
118
  const completeData = await completeResp.json();
118
- console.log(`[XY File Upload] File upload successful: ${fileName} β†’ objectId=${objectId}`);
119
+ logger.log(`[XY File Upload] File upload successful: ${fileName} β†’ objectId=${objectId}`);
119
120
  return objectId;
120
121
  }
121
122
  catch (error) {
122
- console.error(`[XY File Upload] File upload failed for ${filePath}:`, error);
123
+ logger.error(`[XY File Upload] File upload failed for ${filePath}:`, error);
123
124
  throw error;
124
125
  }
125
126
  finally {
@@ -150,7 +151,7 @@ export class XYFileUploadService {
150
151
  const fileSha256 = calculateSHA256(fileBuffer);
151
152
  const fileSize = fileBuffer.length;
152
153
  // Phase 1: Prepare
153
- console.log(`[XY File Upload] Phase 1: Prepare upload for ${fileName}`);
154
+ logger.log(`[XY File Upload] Phase 1: Prepare upload for ${fileName}`);
154
155
  const prepareResp = await fetch(`${this.baseUrl}/osms/v1/file/manager/prepare`, {
155
156
  method: "POST",
156
157
  headers: {
@@ -179,23 +180,23 @@ export class XYFileUploadService {
179
180
  throw new Error(`Prepare failed: ${prepareData.desc}`);
180
181
  }
181
182
  const { objectId, draftId, uploadInfos } = prepareData;
182
- console.log(`[XY File Upload] Prepare complete: objectId=${objectId}, draftId=${draftId}`);
183
+ logger.log(`[XY File Upload] Prepare complete: objectId=${objectId}, draftId=${draftId}`);
183
184
  // Phase 2: Upload
184
- console.log(`[XY File Upload] Phase 2: Upload file data`);
185
+ logger.log(`[XY File Upload] Phase 2: Upload file data`);
185
186
  const uploadInfo = uploadInfos[0]; // Single-part upload
186
187
  const uploadResp = await fetch(uploadInfo.url, {
187
188
  method: uploadInfo.method,
188
189
  headers: uploadInfo.headers,
189
190
  body: fileBuffer,
190
191
  });
191
- console.log(`[XY File Upload] Upload response status: ${uploadResp.status}`);
192
+ logger.log(`[XY File Upload] Upload response status: ${uploadResp.status}`);
192
193
  if (!uploadResp.ok) {
193
194
  const uploadErrorText = await uploadResp.text();
194
195
  throw new Error(`Upload failed: HTTP ${uploadResp.status}`);
195
196
  }
196
- console.log(`[XY File Upload] Upload complete`);
197
+ logger.log(`[XY File Upload] Upload complete`);
197
198
  // Phase 3: CompleteAndQuery - get file URL
198
- console.log(`[XY File Upload] Phase 3: CompleteAndQuery to get file URL`);
199
+ logger.log(`[XY File Upload] Phase 3: CompleteAndQuery to get file URL`);
199
200
  const completeResp = await fetch(`${this.baseUrl}/osms/v1/file/manager/completeAndQuery`, {
200
201
  method: "POST",
201
202
  headers: {
@@ -218,11 +219,11 @@ export class XYFileUploadService {
218
219
  if (!fileUrl) {
219
220
  throw new Error("No file URL returned from completeAndQuery");
220
221
  }
221
- console.log(`[XY File Upload] File upload successful`);
222
+ logger.log(`[XY File Upload] File upload successful`);
222
223
  return fileUrl;
223
224
  }
224
225
  catch (error) {
225
- console.error(`[XY File Upload] File upload with URL retrieval failed for ${filePath}:`, error);
226
+ logger.error(`[XY File Upload] File upload with URL retrieval failed for ${filePath}:`, error);
226
227
  throw error;
227
228
  }
228
229
  finally {
@@ -249,7 +250,7 @@ export class XYFileUploadService {
249
250
  });
250
251
  }
251
252
  catch (error) {
252
- console.error(`[XY File Upload] Failed to upload ${filePath}, skipping:`, error);
253
+ logger.error(`[XY File Upload] Failed to upload ${filePath}, skipping:`, error);
253
254
  // Continue with other files
254
255
  }
255
256
  }
@@ -17,6 +17,7 @@ export interface SendA2AResponseParams {
17
17
  }>;
18
18
  errorCode?: number | string;
19
19
  errorMessage?: string;
20
+ runtime?: any;
20
21
  }
21
22
  /**
22
23
  * Send an A2A artifact update response.
@@ -49,6 +50,7 @@ export interface SendStatusUpdateParams {
49
50
  messageId: string;
50
51
  text: string;
51
52
  state: "submitted" | "working" | "input-required" | "completed" | "canceled" | "failed" | "unknown";
53
+ runtime?: any;
52
54
  }
53
55
  /**
54
56
  * Send an A2A task status update.
@@ -1,15 +1,14 @@
1
1
  // OpenClaw β†’ A2A format conversion
2
2
  import { v4 as uuidv4 } from "uuid";
3
3
  import { getXYWebSocketManager } from "./client.js";
4
- import { getXYRuntime } from "./runtime.js";
4
+ import { logger } from "./utils/logger.js";
5
+ import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
5
6
  /**
6
7
  * Send an A2A artifact update response.
7
8
  */
8
9
  export async function sendA2AResponse(params) {
9
- const { config, sessionId, taskId, messageId, text, append, final, files, errorCode, errorMessage } = params;
10
- const runtime = getXYRuntime();
10
+ const { config, sessionId, taskId, messageId, text, append, final, files, errorCode, errorMessage, runtime } = params;
11
11
  const log = runtime?.log ?? console.log;
12
- const errorFn = runtime?.error ?? console.error;
13
12
  // Build artifact update event
14
13
  const artifact = {
15
14
  taskId,
@@ -75,9 +74,6 @@ export async function sendA2AResponse(params) {
75
74
  */
76
75
  export async function sendReasoningTextUpdate(params) {
77
76
  const { config, sessionId, taskId, messageId, text, append = true } = params;
78
- const runtime = getXYRuntime();
79
- const log = runtime?.log ?? console.log;
80
- const error = runtime?.error ?? console.error;
81
77
  const artifact = {
82
78
  taskId,
83
79
  kind: "artifact-update",
@@ -114,13 +110,15 @@ export async function sendReasoningTextUpdate(params) {
114
110
  * Follows A2A protocol standard format with nested status object.
115
111
  */
116
112
  export async function sendStatusUpdate(params) {
117
- const { config, sessionId, taskId, messageId, text, state } = params;
118
- const runtime = getXYRuntime();
113
+ const { config, sessionId, taskId, messageId, text, state, runtime } = params;
119
114
  const log = runtime?.log ?? console.log;
120
- const error = runtime?.error ?? console.error;
115
+ // Dynamic lookup: use latest taskId/messageId from task-manager (handles steer/interrupt),
116
+ // fall back to closure-captured values
117
+ const currentTaskId = getCurrentTaskId(sessionId) ?? taskId;
118
+ const currentMessageId = getCurrentMessageId(sessionId) ?? messageId;
121
119
  // Build status update event following A2A protocol standard
122
120
  const statusUpdate = {
123
- taskId,
121
+ taskId: currentTaskId,
124
122
  kind: "status-update",
125
123
  final: false, // Status updates should not end the stream
126
124
  status: {
@@ -139,7 +137,7 @@ export async function sendStatusUpdate(params) {
139
137
  // Build JSON-RPC response
140
138
  const jsonRpcResponse = {
141
139
  jsonrpc: "2.0",
142
- id: messageId,
140
+ id: currentMessageId,
143
141
  result: statusUpdate,
144
142
  };
145
143
  // Send via WebSocket
@@ -148,12 +146,12 @@ export async function sendStatusUpdate(params) {
148
146
  msgType: "agent_response",
149
147
  agentId: config.agentId,
150
148
  sessionId,
151
- taskId,
149
+ taskId: currentTaskId,
152
150
  msgDetail: JSON.stringify(jsonRpcResponse),
153
151
  };
154
152
  // πŸ“‹ Log complete response body
155
153
  log(`[A2A_STATUS] πŸ“€ Sending A2A status-update:`);
156
- log(`[A2A_STATUS] - taskId: ${taskId}`);
154
+ log(`[A2A_STATUS] - taskId: ${currentTaskId}`);
157
155
  log(`[A2A_STATUS] - text: "${text}"`);
158
156
  await wsManager.sendMessage(sessionId, outboundMessage);
159
157
  }
@@ -162,13 +160,14 @@ export async function sendStatusUpdate(params) {
162
160
  */
163
161
  export async function sendCommand(params) {
164
162
  const { config, sessionId, taskId, messageId, command } = params;
165
- const runtime = getXYRuntime();
166
- const log = runtime?.log ?? console.log;
167
- const error = runtime?.error ?? console.error;
163
+ // Dynamic lookup: use latest taskId/messageId from task-manager (handles steer/interrupt),
164
+ // fall back to closure-captured values
165
+ const currentTaskId = getCurrentTaskId(sessionId) ?? taskId;
166
+ const currentMessageId = getCurrentMessageId(sessionId) ?? messageId;
168
167
  // Build artifact update with command as data
169
168
  // Wrap command in commands array as per protocol requirement
170
169
  const artifact = {
171
- taskId,
170
+ taskId: currentTaskId,
172
171
  kind: "artifact-update",
173
172
  append: false,
174
173
  lastChunk: true,
@@ -188,7 +187,7 @@ export async function sendCommand(params) {
188
187
  // Build JSON-RPC response
189
188
  const jsonRpcResponse = {
190
189
  jsonrpc: "2.0",
191
- id: messageId,
190
+ id: currentMessageId,
192
191
  result: artifact,
193
192
  };
194
193
  // Send via WebSocket
@@ -197,22 +196,19 @@ export async function sendCommand(params) {
197
196
  msgType: "agent_response",
198
197
  agentId: config.agentId,
199
198
  sessionId,
200
- taskId,
199
+ taskId: currentTaskId,
201
200
  msgDetail: JSON.stringify(jsonRpcResponse),
202
201
  };
203
202
  // πŸ“‹ Log complete response body
204
- log(`[A2A_COMMAND] πŸ“€ Sending A2A command: taskId: ${taskId}`);
203
+ logger.log(`[A2A_COMMAND] πŸ“€ Sending A2A command: taskId: ${currentTaskId}`);
205
204
  await wsManager.sendMessage(sessionId, outboundMessage);
206
- log(`[A2A_COMMAND] βœ… Command sent successfully`);
205
+ logger.log(`[A2A_COMMAND] βœ… Command sent successfully`);
207
206
  }
208
207
  /**
209
208
  * Send a clearContext response.
210
209
  */
211
210
  export async function sendClearContextResponse(params) {
212
211
  const { config, sessionId, messageId } = params;
213
- const runtime = getXYRuntime();
214
- const log = runtime?.log ?? console.log;
215
- const error = runtime?.error ?? console.error;
216
212
  // Build JSON-RPC response for clearContext
217
213
  const jsonRpcResponse = {
218
214
  jsonrpc: "2.0",
@@ -238,16 +234,13 @@ export async function sendClearContextResponse(params) {
238
234
  msgDetail: JSON.stringify(jsonRpcResponse),
239
235
  };
240
236
  await wsManager.sendMessage(sessionId, outboundMessage);
241
- log(`Sent clearContext response: sessionId=${sessionId}`);
237
+ logger.log(`Sent clearContext response: sessionId=${sessionId}`);
242
238
  }
243
239
  /**
244
240
  * Send a tasks/cancel response.
245
241
  */
246
242
  export async function sendTasksCancelResponse(params) {
247
243
  const { config, sessionId, taskId, messageId } = params;
248
- const runtime = getXYRuntime();
249
- const log = runtime?.log ?? console.log;
250
- const error = runtime?.error ?? console.error;
251
244
  // Build JSON-RPC response for tasks/cancel
252
245
  // Note: Using any to bypass type check as the response format differs from standard A2A types
253
246
  const jsonRpcResponse = {
@@ -274,16 +267,13 @@ export async function sendTasksCancelResponse(params) {
274
267
  msgDetail: JSON.stringify(jsonRpcResponse),
275
268
  };
276
269
  await wsManager.sendMessage(sessionId, outboundMessage);
277
- log(`Sent tasks/cancel response: sessionId=${sessionId}, taskId=${taskId}`);
270
+ logger.log(`Sent tasks/cancel response: sessionId=${sessionId}, taskId=${taskId}`);
278
271
  }
279
272
  /**
280
273
  * Send a Trigger response with pushData content.
281
274
  */
282
275
  export async function sendTriggerResponse(params) {
283
276
  const { config, sessionId, taskId, messageId, content } = params;
284
- const runtime = getXYRuntime();
285
- const log = runtime?.log ?? console.log;
286
- const error = runtime?.error ?? console.error;
287
277
  // Build JSON-RPC response for Trigger
288
278
  const jsonRpcResponse = {
289
279
  jsonrpc: "2.0",
@@ -318,7 +308,7 @@ export async function sendTriggerResponse(params) {
318
308
  taskId,
319
309
  msgDetail: JSON.stringify(jsonRpcResponse),
320
310
  };
321
- log(`[TRIGGER_RESPONSE] Sending Trigger response: sessionId=${sessionId}, taskId=${taskId}`);
311
+ logger.log(`[TRIGGER_RESPONSE] Sending Trigger response: sessionId=${sessionId}, taskId=${taskId}`);
322
312
  await wsManager.sendMessage(sessionId, outboundMessage);
323
- log(`[TRIGGER_RESPONSE] Trigger response sent successfully`);
313
+ logger.log(`[TRIGGER_RESPONSE] Trigger response sent successfully`);
324
314
  }
@@ -67,7 +67,7 @@ export class HeartbeatManager {
67
67
  */
68
68
  sendHeartbeat() {
69
69
  if (this.ws.readyState !== WebSocket.OPEN) {
70
- console.warn(`Cannot send heartbeat for ${this.serverName}: WebSocket not open`);
70
+ this.log(`Cannot send heartbeat for ${this.serverName}: WebSocket not open`);
71
71
  return;
72
72
  }
73
73
  try {
@@ -0,0 +1,17 @@
1
+ import type { OutboundWebSocketMessage } from "./types.js";
2
+ /**
3
+ * Simple message queue for buffering outbound WebSocket messages
4
+ * during disconnection and reconnection stabilization period.
5
+ */
6
+ export declare class MessageQueue {
7
+ private items;
8
+ private log;
9
+ constructor(log?: (msg: string, ...args: any[]) => void);
10
+ /** Enqueue a message. Drops oldest if over limit. */
11
+ enqueue(message: OutboundWebSocketMessage): void;
12
+ /** Flush all queued messages by calling sendFn for each, then clear. */
13
+ flush(sendFn: (message: OutboundWebSocketMessage) => void): void;
14
+ /** Clear all queued messages without sending. */
15
+ clear(): void;
16
+ get size(): number;
17
+ }
@@ -0,0 +1,51 @@
1
+ const MAX_QUEUE_SIZE = 1000;
2
+ /**
3
+ * Simple message queue for buffering outbound WebSocket messages
4
+ * during disconnection and reconnection stabilization period.
5
+ */
6
+ export class MessageQueue {
7
+ items = [];
8
+ log;
9
+ constructor(log) {
10
+ this.log = log ?? console.log;
11
+ }
12
+ /** Enqueue a message. Drops oldest if over limit. */
13
+ enqueue(message) {
14
+ if (this.items.length >= MAX_QUEUE_SIZE) {
15
+ this.log(`[MessageQueue] Queue full (${MAX_QUEUE_SIZE}), dropping oldest message`);
16
+ this.items.shift();
17
+ }
18
+ this.items.push(message);
19
+ this.log(`[MessageQueue] Enqueued message, queue size: ${this.items.length}`);
20
+ }
21
+ /** Flush all queued messages by calling sendFn for each, then clear. */
22
+ flush(sendFn) {
23
+ const count = this.items.length;
24
+ if (count === 0) {
25
+ this.log("[MessageQueue] Queue empty, nothing to flush");
26
+ return;
27
+ }
28
+ this.log(`[MessageQueue] Flushing ${count} queued messages`);
29
+ for (const msg of this.items) {
30
+ try {
31
+ sendFn(msg);
32
+ }
33
+ catch (err) {
34
+ this.log(`[MessageQueue] Error flushing message: ${err}`);
35
+ }
36
+ }
37
+ this.items = [];
38
+ this.log(`[MessageQueue] Flush complete`);
39
+ }
40
+ /** Clear all queued messages without sending. */
41
+ clear() {
42
+ const count = this.items.length;
43
+ this.items = [];
44
+ if (count > 0) {
45
+ this.log(`[MessageQueue] Cleared ${count} messages`);
46
+ }
47
+ }
48
+ get size() {
49
+ return this.items.length;
50
+ }
51
+ }
@@ -1,12 +1,14 @@
1
1
  import { resolveXYConfig } from "./config.js";
2
- import { getXYWebSocketManager, diagnoseAllManagers, cleanupOrphanConnections, removeXYWebSocketManager } from "./client.js";
2
+ import { getXYWebSocketManager, setClientRuntime, diagnoseAllManagers, cleanupOrphanConnections, removeXYWebSocketManager } from "./client.js";
3
3
  import { handleXYMessage } from "./bot.js";
4
4
  import { parseA2AMessage } from "./parser.js";
5
- import { hasActiveTask } from "./task-manager.js";
5
+ import { hasActiveTask, getAllActiveTaskBindings } from "./task-manager.js";
6
+ import { sendA2AResponse } from "./formatter.js";
6
7
  import { handleTriggerEvent } from "./trigger-handler.js";
7
- import { handleSelfEvolutionEvent } from "./self-evolution-handler.js";
8
+ import { handleSelfEvolutionEvent, handleSelfEvolutionStateGetEvent } from "./self-evolution-handler.js";
8
9
  import { handleLoginTokenEvent } from "./login-token-handler.js";
9
10
  import { cleanupStaleTempFiles } from "./reply-dispatcher.js";
11
+ import { cleanupStaleSessions, getActiveSessionCount, cleanupAllSessions } from "./tools/session-manager.js";
10
12
  /**
11
13
  * Per-session serial queue that ensures messages from the same session are processed
12
14
  * in arrival order while allowing different sessions to run concurrently.
@@ -49,8 +51,10 @@ export async function monitorXYProvider(opts = {}) {
49
51
  opts.setStatus({ lastEventAt: Date.now(), lastInboundAt: Date.now() });
50
52
  }
51
53
  : undefined;
54
+ // βœ… Set runtime for WebSocket manager logging before creating/getting manager
55
+ setClientRuntime(runtime);
52
56
  // πŸ” Diagnose WebSocket managers before gateway start
53
- console.log("πŸ” [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
57
+ log("πŸ” [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
54
58
  diagnoseAllManagers();
55
59
  // Get WebSocket manager (cached)
56
60
  const wsManager = getXYWebSocketManager(account);
@@ -139,7 +143,7 @@ export async function monitorXYProvider(opts = {}) {
139
143
  opts.setStatus?.({ connected: true });
140
144
  };
141
145
  const disconnectedHandler = (serverId) => {
142
- console.warn(`XY gateway: ${serverId} disconnected`);
146
+ log(`XY gateway: ${serverId} disconnected`);
143
147
  loggedServers.delete(serverId);
144
148
  // βœ… Report disconnection status (only if all servers disconnected)
145
149
  if (loggedServers.size === 0) {
@@ -162,6 +166,12 @@ export async function monitorXYProvider(opts = {}) {
162
166
  log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
163
167
  handleSelfEvolutionEvent(context, runtime);
164
168
  };
169
+ const selfEvolutionStateGetHandler = (context) => {
170
+ log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
171
+ handleSelfEvolutionStateGetEvent(context, account, runtime, wsManager).catch((err) => {
172
+ error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
173
+ });
174
+ };
165
175
  const loginTokenEventHandler = (context) => {
166
176
  log(`[MONITOR] Received login-token-event, dispatching to handler...`);
167
177
  handleLoginTokenEvent(context, runtime);
@@ -169,13 +179,13 @@ export async function monitorXYProvider(opts = {}) {
169
179
  const cleanup = () => {
170
180
  log("XY gateway: cleaning up...");
171
181
  // πŸ” Diagnose before cleanup
172
- console.log("πŸ” [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
182
+ log("πŸ” [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
173
183
  diagnoseAllManagers();
174
184
  // Stop health check interval
175
185
  if (healthCheckInterval) {
176
186
  clearInterval(healthCheckInterval);
177
187
  healthCheckInterval = null;
178
- console.log("⏸️ Stopped periodic health check");
188
+ log("⏸️ Stopped periodic health check");
179
189
  }
180
190
  // Remove event handlers to prevent duplicate calls on gateway restart
181
191
  wsManager.off("message", messageHandler);
@@ -184,21 +194,53 @@ export async function monitorXYProvider(opts = {}) {
184
194
  wsManager.off("error", errorHandler);
185
195
  wsManager.off("trigger-event", triggerEventHandler);
186
196
  wsManager.off("self-evolution-event", selfEvolutionHandler);
197
+ wsManager.off("self-evolution-state-get-event", selfEvolutionStateGetHandler);
187
198
  wsManager.off("login-token-event", loginTokenEventHandler);
188
199
  // βœ… Disconnect the wsManager to prevent connection leaks
189
200
  // This is safe because each gateway lifecycle should have clean connections
190
201
  wsManager.disconnect();
191
202
  // βœ… Remove manager from cache to prevent reusing dirty state
192
203
  removeXYWebSocketManager(account);
204
+ // Clean up all active sessions
205
+ cleanupAllSessions();
193
206
  loggedServers.clear();
194
207
  activeMessages.clear();
195
- log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages`);
208
+ log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
196
209
  // πŸ” Diagnose after cleanup
197
- console.log("πŸ” [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
210
+ log("πŸ” [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
198
211
  diagnoseAllManagers();
199
212
  };
200
- const handleAbort = () => {
201
- log("XY gateway: abort signal received, stopping");
213
+ const handleAbort = async () => {
214
+ log("XY gateway: abort signal received, sending notifications before stopping");
215
+ // πŸ“€ Send restart notification to all active sessions before disconnecting
216
+ try {
217
+ const activeBindings = getAllActiveTaskBindings();
218
+ if (activeBindings.length > 0) {
219
+ const config = resolveXYConfig(cfg);
220
+ const notificationText = "Gatewayε³ε°†ι‡ε―οΌŒι‡ε―ζœŸι—΄ε―θƒ½ηŸ­ζš‚ε‡ΊηŽ°\u201cηŽ―ε’ƒεΌ‚εΈΈ\u201dζη€ΊοΌŒθ―·η¨ε€™εΉΆθ€εΏƒι‡θ―•~";
221
+ log(`[MONITOR] πŸ“€ Sending restart notifications to ${activeBindings.length} active session(s)`);
222
+ const sendPromises = activeBindings.map(binding => sendA2AResponse({
223
+ config,
224
+ sessionId: binding.sessionId,
225
+ taskId: binding.currentTaskId,
226
+ messageId: binding.currentMessageId,
227
+ text: notificationText,
228
+ append: false,
229
+ final: true,
230
+ runtime,
231
+ }).catch(err => {
232
+ error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
233
+ }));
234
+ await Promise.all(sendPromises);
235
+ log(`[MONITOR] βœ… Restart notifications sent to ${activeBindings.length} session(s)`);
236
+ }
237
+ else {
238
+ log(`[MONITOR] No active sessions, skipping restart notifications`);
239
+ }
240
+ }
241
+ catch (err) {
242
+ error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
243
+ }
202
244
  cleanup();
203
245
  log("XY gateway stopped");
204
246
  resolve();
@@ -216,16 +258,23 @@ export async function monitorXYProvider(opts = {}) {
216
258
  wsManager.on("error", errorHandler);
217
259
  wsManager.on("trigger-event", triggerEventHandler);
218
260
  wsManager.on("self-evolution-event", selfEvolutionHandler);
261
+ wsManager.on("self-evolution-state-get-event", selfEvolutionStateGetHandler);
219
262
  wsManager.on("login-token-event", loginTokenEventHandler);
220
263
  // Start periodic health check (every 6 hours)
221
- console.log("πŸ₯ Starting periodic health check (every 6 hours)...");
264
+ log("πŸ₯ Starting periodic health check (every 6 hours)...");
222
265
  healthCheckInterval = setInterval(() => {
223
- console.log("πŸ₯ [HEALTH CHECK] Periodic WebSocket diagnostics...");
266
+ log("πŸ₯ [HEALTH CHECK] Periodic WebSocket diagnostics...");
224
267
  diagnoseAllManagers();
225
268
  // Auto-cleanup orphan connections
226
269
  const cleaned = cleanupOrphanConnections();
227
270
  if (cleaned > 0) {
228
- console.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
271
+ log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
272
+ }
273
+ // Cleanup stale sessions (older than 10min TTL)
274
+ const cleanedSessions = cleanupStaleSessions();
275
+ const remainingSessions = getActiveSessionCount();
276
+ if (cleanedSessions > 0 || remainingSessions > 0) {
277
+ log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
229
278
  }
230
279
  // Cleanup stale temp files (older than 24 hours)
231
280
  void cleanupStaleTempFiles();