@ynhcj/xiaoyi-channel 0.0.6 → 0.0.7-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 (81) hide show
  1. package/dist/src/bot.js +121 -52
  2. package/dist/src/channel.js +23 -4
  3. package/dist/src/client.d.ts +15 -0
  4. package/dist/src/client.js +84 -2
  5. package/dist/src/config.js +2 -2
  6. package/dist/src/file-download.js +10 -1
  7. package/dist/src/file-upload.js +1 -1
  8. package/dist/src/formatter.d.ts +17 -0
  9. package/dist/src/formatter.js +47 -1
  10. package/dist/src/heartbeat.d.ts +2 -1
  11. package/dist/src/heartbeat.js +9 -1
  12. package/dist/src/monitor.d.ts +5 -0
  13. package/dist/src/monitor.js +143 -25
  14. package/dist/src/onboarding.js +7 -7
  15. package/dist/src/outbound.js +122 -9
  16. package/dist/src/parser.d.ts +5 -0
  17. package/dist/src/parser.js +15 -0
  18. package/dist/src/push.d.ts +13 -1
  19. package/dist/src/push.js +125 -19
  20. package/dist/src/reply-dispatcher.d.ts +1 -0
  21. package/dist/src/reply-dispatcher.js +210 -57
  22. package/dist/src/task-manager.d.ts +55 -0
  23. package/dist/src/task-manager.js +136 -0
  24. package/dist/src/tools/calendar-tool.d.ts +6 -0
  25. package/dist/src/tools/calendar-tool.js +169 -0
  26. package/dist/src/tools/call-phone-tool.d.ts +5 -0
  27. package/dist/src/tools/call-phone-tool.js +183 -0
  28. package/dist/src/tools/create-alarm-tool.d.ts +7 -0
  29. package/dist/src/tools/create-alarm-tool.js +446 -0
  30. package/dist/src/tools/delete-alarm-tool.d.ts +11 -0
  31. package/dist/src/tools/delete-alarm-tool.js +238 -0
  32. package/dist/src/tools/location-tool.js +18 -8
  33. package/dist/src/tools/modify-alarm-tool.d.ts +9 -0
  34. package/dist/src/tools/modify-alarm-tool.js +467 -0
  35. package/dist/src/tools/modify-note-tool.d.ts +9 -0
  36. package/dist/src/tools/modify-note-tool.js +163 -0
  37. package/dist/src/tools/note-tool.js +32 -11
  38. package/dist/src/tools/search-alarm-tool.d.ts +8 -0
  39. package/dist/src/tools/search-alarm-tool.js +391 -0
  40. package/dist/src/tools/search-calendar-tool.d.ts +12 -0
  41. package/dist/src/tools/search-calendar-tool.js +262 -0
  42. package/dist/src/tools/search-contact-tool.d.ts +5 -0
  43. package/dist/src/tools/search-contact-tool.js +168 -0
  44. package/dist/src/tools/search-file-tool.d.ts +5 -0
  45. package/dist/src/tools/search-file-tool.js +185 -0
  46. package/dist/src/tools/search-message-tool.d.ts +5 -0
  47. package/dist/src/tools/search-message-tool.js +173 -0
  48. package/dist/src/tools/search-note-tool.js +6 -6
  49. package/dist/src/tools/search-photo-gallery-tool.d.ts +8 -0
  50. package/dist/src/tools/search-photo-gallery-tool.js +212 -0
  51. package/dist/src/tools/search-photo-tool.d.ts +9 -0
  52. package/dist/src/tools/search-photo-tool.js +270 -0
  53. package/dist/src/tools/send-file-to-user-tool.d.ts +5 -0
  54. package/dist/src/tools/send-file-to-user-tool.js +318 -0
  55. package/dist/src/tools/send-message-tool.d.ts +5 -0
  56. package/dist/src/tools/send-message-tool.js +189 -0
  57. package/dist/src/tools/session-manager.d.ts +15 -0
  58. package/dist/src/tools/session-manager.js +101 -13
  59. package/dist/src/tools/upload-file-tool.d.ts +13 -0
  60. package/dist/src/tools/upload-file-tool.js +265 -0
  61. package/dist/src/tools/upload-photo-tool.d.ts +9 -0
  62. package/dist/src/tools/upload-photo-tool.js +223 -0
  63. package/dist/src/tools/view-push-result-tool.d.ts +5 -0
  64. package/dist/src/tools/view-push-result-tool.js +118 -0
  65. package/dist/src/tools/xiaoyi-collection-tool.d.ts +5 -0
  66. package/dist/src/tools/xiaoyi-collection-tool.js +190 -0
  67. package/dist/src/tools/xiaoyi-gui-tool.d.ts +6 -0
  68. package/dist/src/tools/xiaoyi-gui-tool.js +151 -0
  69. package/dist/src/trigger-handler.d.ts +19 -0
  70. package/dist/src/trigger-handler.js +91 -0
  71. package/dist/src/types.d.ts +6 -17
  72. package/dist/src/types.js +4 -0
  73. package/dist/src/utils/config-manager.d.ts +26 -0
  74. package/dist/src/utils/config-manager.js +56 -0
  75. package/dist/src/utils/pushdata-manager.d.ts +28 -0
  76. package/dist/src/utils/pushdata-manager.js +171 -0
  77. package/dist/src/utils/pushid-manager.d.ts +12 -0
  78. package/dist/src/utils/pushid-manager.js +105 -0
  79. package/dist/src/websocket.d.ts +59 -25
  80. package/dist/src/websocket.js +317 -245
  81. package/package.json +1 -1
package/dist/src/bot.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { getXYRuntime } from "./runtime.js";
2
2
  import { createXYReplyDispatcher } from "./reply-dispatcher.js";
3
- import { parseA2AMessage, extractTextFromParts, extractFileParts } from "./parser.js";
4
- import { downloadFilesFromParts } from "./file-download.js";
3
+ import { parseA2AMessage, extractTextFromParts, extractFileParts, extractPushId } from "./parser.js";
5
4
  import { resolveXYConfig } from "./config.js";
6
5
  import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse } from "./formatter.js";
7
- import { registerSession, unregisterSession } from "./tools/session-manager.js";
6
+ import { registerSession, unregisterSession, runWithSessionContext } from "./tools/session-manager.js";
7
+ import { configManager } from "./utils/config-manager.js";
8
+ import { addPushId } from "./utils/pushid-manager.js";
9
+ import { registerTaskId, decrementTaskIdRef, lockTaskId, unlockTaskId, hasActiveTask, } from "./task-manager.js";
8
10
  /**
9
11
  * Handle an incoming A2A message.
10
12
  * This is the main entry point for message processing.
@@ -19,7 +21,8 @@ export async function handleXYMessage(params) {
19
21
  try {
20
22
  // Check for special messages BEFORE parsing (these have different param structures)
21
23
  const messageMethod = message.method;
22
- log(`[DEBUG] Received message with method: ${messageMethod}, id: ${message.id}`);
24
+ log(`[BOT-ENTRY] <<<<<<< Received message with method: ${messageMethod}, id: ${message.id} >>>>>>>`);
25
+ log(`[BOT-ENTRY] Stack trace for debugging:`, new Error().stack?.split('\n').slice(1, 4).join('\n'));
23
26
  // Handle clearContext messages (params only has sessionId)
24
27
  if (messageMethod === "clearContext" || messageMethod === "clear_context") {
25
28
  const sessionId = message.params?.sessionId;
@@ -54,6 +57,38 @@ export async function handleXYMessage(params) {
54
57
  }
55
58
  // Parse the A2A message (for regular messages)
56
59
  const parsed = parseA2AMessage(message);
60
+ // 🔑 检测steer模式和是否是第二条消息
61
+ const isSteerMode = cfg.messages?.queue?.mode === "steer";
62
+ const isSecondMessage = isSteerMode && hasActiveTask(parsed.sessionId);
63
+ if (isSecondMessage) {
64
+ log(`[BOT] 🔄 STEER MODE - Second message detected (will be follower)`);
65
+ log(`[BOT] - Session: ${parsed.sessionId}`);
66
+ log(`[BOT] - New taskId: ${parsed.taskId} (will replace current)`);
67
+ }
68
+ // 🔑 注册taskId(第二条消息会覆盖第一条的taskId)
69
+ const { isUpdate, refCount } = registerTaskId(parsed.sessionId, parsed.taskId, parsed.messageId, { incrementRef: true } // 增加引用计数
70
+ );
71
+ // 🔑 如果是第一条消息,锁定taskId防止被过早清理
72
+ if (!isUpdate) {
73
+ lockTaskId(parsed.sessionId);
74
+ log(`[BOT] 🔒 Locked taskId for first message`);
75
+ }
76
+ // Extract and update push_id if present
77
+ const pushId = extractPushId(parsed.parts);
78
+ if (pushId) {
79
+ log(`[BOT] 📌 Extracted push_id from user message`);
80
+ log(`[BOT] - Session ID: ${parsed.sessionId}`);
81
+ log(`[BOT] - Push ID preview: ${pushId.substring(0, 20)}...`);
82
+ log(`[BOT] - Full push_id: ${pushId}`);
83
+ configManager.updatePushId(parsed.sessionId, pushId);
84
+ // 持久化 pushId 到本地文件(异步,不阻塞主流程)
85
+ addPushId(pushId).catch((err) => {
86
+ error(`[BOT] Failed to persist pushId:`, err);
87
+ });
88
+ }
89
+ else {
90
+ log(`[BOT] ℹ️ No push_id found in message, will use config default`);
91
+ }
57
92
  // Resolve configuration (needed for status updates)
58
93
  const config = resolveXYConfig(cfg);
59
94
  // ✅ Resolve agent route (following feishu pattern)
@@ -61,7 +96,7 @@ export async function handleXYMessage(params) {
61
96
  // Use sessionId as peer.id to ensure all messages in the same session share context
62
97
  let route = core.channel.routing.resolveAgentRoute({
63
98
  cfg,
64
- channel: "xy",
99
+ channel: "xiaoyi-channel",
65
100
  accountId, // "default"
66
101
  peer: {
67
102
  kind: "direct",
@@ -69,11 +104,12 @@ export async function handleXYMessage(params) {
69
104
  },
70
105
  });
71
106
  log(`xy: resolved route accountId=${route.accountId}, sessionKey=${route.sessionKey}`);
72
- // Register session context for tools
107
+ // 🔑 注册session(带引用计数)
73
108
  log(`[BOT] 📝 About to register session for tools...`);
74
109
  log(`[BOT] - sessionKey: ${route.sessionKey}`);
75
110
  log(`[BOT] - sessionId: ${parsed.sessionId}`);
76
111
  log(`[BOT] - taskId: ${parsed.taskId}`);
112
+ log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
77
113
  registerSession(route.sessionKey, {
78
114
  config,
79
115
  sessionId: parsed.sessionId,
@@ -82,13 +118,24 @@ export async function handleXYMessage(params) {
82
118
  agentId: route.accountId,
83
119
  });
84
120
  log(`[BOT] ✅ Session registered for tools`);
121
+ // 🔑 发送初始状态更新(第二条消息也要发,用新taskId)
122
+ log(`[STATUS] Sending initial status update for session ${parsed.sessionId}`);
123
+ void sendStatusUpdate({
124
+ config,
125
+ sessionId: parsed.sessionId,
126
+ taskId: parsed.taskId,
127
+ messageId: parsed.messageId,
128
+ text: isSecondMessage ? "新消息已接收,正在处理..." : "任务正在处理中,请稍后~",
129
+ state: "working",
130
+ }).catch((err) => {
131
+ error(`Failed to send initial status update:`, err);
132
+ });
85
133
  // Extract text and files from parts
86
134
  const text = extractTextFromParts(parsed.parts);
87
135
  const fileParts = extractFileParts(parsed.parts);
88
- // Download files if present (using core's media download)
89
- const mediaList = await downloadFilesFromParts(fileParts);
90
- // Build media payload for inbound context (following feishu pattern)
91
- const mediaPayload = buildXYMediaPayload(mediaList);
136
+ // Build media payload directly from file URIs (openclaw can download them)
137
+ // No need to download files locally - pass URIs directly to openclaw
138
+ const mediaPayload = buildXYMediaPayload(fileParts);
92
139
  // Resolve envelope format options (following feishu pattern)
93
140
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
94
141
  // Build message body with speaker prefix (following feishu pattern)
@@ -98,7 +145,7 @@ export async function handleXYMessage(params) {
98
145
  messageBody = `${speaker}: ${messageBody}`;
99
146
  // Format agent envelope (following feishu pattern)
100
147
  const body = core.channel.reply.formatAgentEnvelope({
101
- channel: "XY",
148
+ channel: "xiaoyi-channel",
102
149
  from: speaker,
103
150
  timestamp: new Date(),
104
151
  envelope: envelopeOptions,
@@ -118,110 +165,132 @@ export async function handleXYMessage(params) {
118
165
  GroupSubject: undefined,
119
166
  SenderName: parsed.sessionId,
120
167
  SenderId: parsed.sessionId,
121
- Provider: "xy",
122
- Surface: "xy",
168
+ Provider: "xiaoyi-channel",
169
+ Surface: "xiaoyi-channel",
123
170
  MessageSid: parsed.messageId,
124
171
  Timestamp: Date.now(),
125
172
  WasMentioned: false,
126
173
  CommandAuthorized: true,
127
- OriginatingChannel: "xy",
174
+ OriginatingChannel: "xiaoyi-channel",
128
175
  OriginatingTo: parsed.sessionId, // Original message target
129
176
  ReplyToBody: undefined, // A2A protocol doesn't support reply/quote
130
177
  ...mediaPayload,
131
178
  });
132
- // Send initial status update immediately after parsing message
133
- log(`[STATUS] Sending initial status update for session ${parsed.sessionId}`);
134
- void sendStatusUpdate({
135
- config,
136
- sessionId: parsed.sessionId,
137
- taskId: parsed.taskId,
138
- messageId: parsed.messageId,
139
- text: "任务正在处理中,请稍后~",
140
- state: "working",
141
- }).catch((err) => {
142
- error(`Failed to send initial status update:`, err);
143
- });
144
- // Create reply dispatcher (following feishu pattern)
179
+ // 🔑 创建dispatcher(dispatcher会自动使用动态taskId)
180
+ log(`[BOT-DISPATCHER] 🎯 Creating reply dispatcher`);
181
+ log(`[BOT-DISPATCHER] - session: ${parsed.sessionId}`);
182
+ log(`[BOT-DISPATCHER] - taskId: ${parsed.taskId}`);
183
+ log(`[BOT-DISPATCHER] - isSecondMessage: ${isSecondMessage}`);
145
184
  const { dispatcher, replyOptions, markDispatchIdle, startStatusInterval } = createXYReplyDispatcher({
146
185
  cfg,
147
186
  runtime,
148
187
  sessionId: parsed.sessionId,
149
188
  taskId: parsed.taskId,
150
189
  messageId: parsed.messageId,
151
- accountId: route.accountId, // ✅ Use route.accountId
190
+ accountId: route.accountId,
191
+ isSteerFollower: isSecondMessage, // 🔑 标记第二条消息
152
192
  });
153
- // Start status update interval (will send updates every 60 seconds)
154
- // Interval will be automatically stopped when onIdle/onCleanup is triggered
155
- startStatusInterval();
193
+ log(`[BOT-DISPATCHER] Reply dispatcher created successfully`);
194
+ // 🔑 只有第一条消息启动状态定时器
195
+ // 第二条消息会很快返回,不需要定时器
196
+ if (!isSecondMessage) {
197
+ startStatusInterval();
198
+ log(`[BOT-DISPATCHER] ✅ Status interval started for first message`);
199
+ }
200
+ else {
201
+ log(`[BOT-DISPATCHER] ⏭️ Skipped status interval for steer follower`);
202
+ }
156
203
  log(`xy: dispatching to agent (session=${parsed.sessionId})`);
157
204
  // Dispatch to OpenClaw core using correct API (following feishu pattern)
158
205
  log(`[BOT] 🚀 Starting dispatcher with session: ${route.sessionKey}`);
206
+ // Build session context for AsyncLocalStorage
207
+ const sessionContext = {
208
+ config,
209
+ sessionId: parsed.sessionId,
210
+ taskId: parsed.taskId,
211
+ messageId: parsed.messageId,
212
+ agentId: route.accountId,
213
+ };
159
214
  await core.channel.reply.withReplyDispatcher({
160
215
  dispatcher,
161
216
  onSettled: () => {
162
217
  log(`[BOT] 🏁 onSettled called for session: ${route.sessionKey}`);
163
- log(`[BOT] - About to unregister session...`);
218
+ log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
164
219
  markDispatchIdle();
165
- // Unregister session context when done
220
+ // 🔑 减少引用计数
221
+ decrementTaskIdRef(parsed.sessionId);
222
+ // 🔑 如果是第一条消息完成,解锁
223
+ if (!isSecondMessage) {
224
+ unlockTaskId(parsed.sessionId);
225
+ log(`[BOT] 🔓 Unlocked taskId (first message completed)`);
226
+ }
227
+ // 减少session引用计数
166
228
  unregisterSession(route.sessionKey);
167
- log(`[BOT] ✅ Session unregistered in onSettled`);
229
+ log(`[BOT] ✅ Cleanup completed`);
168
230
  },
169
- run: () => core.channel.reply.dispatchReplyFromConfig({
231
+ run: () =>
232
+ // 🔐 Use AsyncLocalStorage to provide session context to tools
233
+ runWithSessionContext(sessionContext, () => core.channel.reply.dispatchReplyFromConfig({
170
234
  ctx: ctxPayload,
171
235
  cfg,
172
236
  dispatcher,
173
237
  replyOptions,
174
- }),
238
+ })),
175
239
  });
176
240
  log(`[BOT] ✅ Dispatcher completed for session: ${parsed.sessionId}`);
177
241
  log(`xy: dispatch complete (session=${parsed.sessionId})`);
178
242
  }
179
243
  catch (err) {
244
+ // ✅ Only log error, don't re-throw to prevent gateway restart
180
245
  error("Failed to handle XY message:", err);
181
246
  runtime.error?.(`xy: Failed to handle message: ${String(err)}`);
182
247
  log(`[BOT] ❌ Error occurred, attempting cleanup...`);
183
- // Try to unregister session on error (if route was established)
248
+ // 🔑 错误时也要清理taskId和session
184
249
  try {
185
- const core = getXYRuntime();
186
250
  const params = message.params;
187
251
  const sessionId = params?.sessionId;
188
252
  if (sessionId) {
189
- log(`[BOT] 🧹 Cleaning up session after error: ${sessionId}`);
253
+ log(`[BOT] 🧹 Cleaning up after error: ${sessionId}`);
254
+ // 清理 taskId
255
+ decrementTaskIdRef(sessionId);
256
+ unlockTaskId(sessionId);
257
+ // 清理 session
258
+ const core = getXYRuntime();
190
259
  const route = core.channel.routing.resolveAgentRoute({
191
260
  cfg,
192
- channel: "xy",
261
+ channel: "xiaoyi-channel",
193
262
  accountId,
194
263
  peer: {
195
264
  kind: "direct",
196
- id: sessionId, // ✅ Use sessionId for cleanup consistency
265
+ id: sessionId,
197
266
  },
198
267
  });
199
- log(`[BOT] - Unregistering session: ${route.sessionKey}`);
200
268
  unregisterSession(route.sessionKey);
201
- log(`[BOT] ✅ Session unregistered after error`);
269
+ log(`[BOT] ✅ Cleanup completed after error`);
202
270
  }
203
271
  }
204
272
  catch (cleanupErr) {
205
273
  log(`[BOT] ⚠️ Cleanup failed:`, cleanupErr);
206
274
  // Ignore cleanup errors
207
275
  }
208
- throw err;
276
+ // ❌ Don't re-throw: message processing error should not affect gateway stability
209
277
  }
210
278
  }
211
279
  /**
212
280
  * Build media payload for inbound context.
213
281
  * Following feishu pattern: buildFeishuMediaPayload().
282
+ * Uses remote URIs directly - openclaw will download them.
214
283
  */
215
- function buildXYMediaPayload(mediaList) {
216
- const first = mediaList[0];
217
- const mediaPaths = mediaList.map((media) => media.path);
218
- const mediaTypes = mediaList.map((media) => media.mimeType).filter(Boolean);
284
+ function buildXYMediaPayload(fileParts) {
285
+ const first = fileParts[0];
286
+ const uris = fileParts.map((file) => file.uri);
287
+ const mediaTypes = fileParts.map((file) => file.mimeType).filter(Boolean);
219
288
  return {
220
- MediaPath: first?.path,
289
+ MediaPath: first?.uri,
221
290
  MediaType: first?.mimeType,
222
- MediaUrl: first?.path,
223
- MediaPaths: mediaPaths.length > 0 ? mediaPaths : undefined,
224
- MediaUrls: mediaPaths.length > 0 ? mediaPaths : undefined,
291
+ MediaUrl: first?.uri,
292
+ MediaPaths: uris.length > 0 ? uris : undefined,
293
+ MediaUrls: uris.length > 0 ? uris : undefined,
225
294
  MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
226
295
  };
227
296
  }
@@ -5,6 +5,24 @@ import { xyOnboardingAdapter } from "./onboarding.js";
5
5
  import { locationTool } from "./tools/location-tool.js";
6
6
  import { noteTool } from "./tools/note-tool.js";
7
7
  import { searchNoteTool } from "./tools/search-note-tool.js";
8
+ import { modifyNoteTool } from "./tools/modify-note-tool.js";
9
+ import { calendarTool } from "./tools/calendar-tool.js";
10
+ import { searchCalendarTool } from "./tools/search-calendar-tool.js";
11
+ import { searchContactTool } from "./tools/search-contact-tool.js";
12
+ import { searchPhotoGalleryTool } from "./tools/search-photo-gallery-tool.js";
13
+ import { uploadPhotoTool } from "./tools/upload-photo-tool.js";
14
+ import { xiaoyiGuiTool } from "./tools/xiaoyi-gui-tool.js";
15
+ import { callPhoneTool } from "./tools/call-phone-tool.js";
16
+ import { searchMessageTool } from "./tools/search-message-tool.js";
17
+ import { searchFileTool } from "./tools/search-file-tool.js";
18
+ import { uploadFileTool } from "./tools/upload-file-tool.js";
19
+ import { createAlarmTool } from "./tools/create-alarm-tool.js";
20
+ import { searchAlarmTool } from "./tools/search-alarm-tool.js";
21
+ import { modifyAlarmTool } from "./tools/modify-alarm-tool.js";
22
+ import { deleteAlarmTool } from "./tools/delete-alarm-tool.js";
23
+ import { sendFileToUserTool } from "./tools/send-file-to-user-tool.js";
24
+ import { xiaoyiCollectionTool } from "./tools/xiaoyi-collection-tool.js";
25
+ import { viewPushResultTool } from "./tools/view-push-result-tool.js";
8
26
  /**
9
27
  * Xiaoyi Channel Plugin for OpenClaw.
10
28
  * Implements Xiaoyi A2A protocol with dual WebSocket connections.
@@ -22,6 +40,7 @@ export const xyPlugin = {
22
40
  agentPrompt: {
23
41
  messageToolHints: () => [
24
42
  "- xiaoyi targeting: omit `target` to reply to the current conversation (auto-inferred). Explicit targets: `default`",
43
+ "- If the user requests a file, you can call the message tool with the xiaoyi-channel channel to return it. Note: sendMedia requires a text reply."
25
44
  ],
26
45
  },
27
46
  capabilities: {
@@ -43,7 +62,7 @@ export const xyPlugin = {
43
62
  },
44
63
  outbound: xyOutbound,
45
64
  onboarding: xyOnboardingAdapter,
46
- agentTools: [locationTool, noteTool, searchNoteTool],
65
+ agentTools: [locationTool, noteTool, searchNoteTool, modifyNoteTool, calendarTool, searchCalendarTool, searchContactTool, searchPhotoGalleryTool, uploadPhotoTool, xiaoyiGuiTool, callPhoneTool, searchMessageTool, searchFileTool, uploadFileTool, createAlarmTool, searchAlarmTool, modifyAlarmTool, deleteAlarmTool, sendFileToUserTool, xiaoyiCollectionTool, viewPushResultTool],
47
66
  messaging: {
48
67
  normalizeTarget: (raw) => {
49
68
  const trimmed = raw.trim();
@@ -70,15 +89,15 @@ export const xyPlugin = {
70
89
  const account = resolveXYConfig(context.cfg);
71
90
  context.setStatus?.({
72
91
  accountId: context.accountId,
73
- wsUrl1: account.wsUrl1,
74
- wsUrl2: account.wsUrl2,
92
+ wsUrl: account.wsUrl,
75
93
  });
76
- context.log?.info(`[${context.accountId}] starting xiaoyi channel (wsUrl1: ${account.wsUrl1}, wsUrl2: ${account.wsUrl2})`);
94
+ context.log?.info(`[${context.accountId}] starting xiaoyi channel (wsUrl: ${account.wsUrl})`);
77
95
  return monitorXYProvider({
78
96
  config: context.cfg,
79
97
  runtime: context.runtime,
80
98
  abortSignal: context.abortSignal,
81
99
  accountId: context.accountId,
100
+ setStatus: context.setStatus,
82
101
  });
83
102
  },
84
103
  },
@@ -10,6 +10,11 @@ export declare function setClientRuntime(rt: RuntimeEnv | undefined): void;
10
10
  * Reuses existing managers if config matches.
11
11
  */
12
12
  export declare function getXYWebSocketManager(config: XYChannelConfig): XYWebSocketManager;
13
+ /**
14
+ * Remove a specific WebSocket manager from cache.
15
+ * Disconnects the manager and removes it from the cache.
16
+ */
17
+ export declare function removeXYWebSocketManager(config: XYChannelConfig): void;
13
18
  /**
14
19
  * Clear all cached WebSocket managers.
15
20
  */
@@ -18,3 +23,13 @@ export declare function clearXYWebSocketManagers(): void;
18
23
  * Get the number of cached managers.
19
24
  */
20
25
  export declare function getCachedManagerCount(): number;
26
+ /**
27
+ * Diagnose all cached WebSocket managers.
28
+ * Helps identify connection issues and orphan connections.
29
+ */
30
+ export declare function diagnoseAllManagers(): void;
31
+ /**
32
+ * Clean up orphan connections across all managers.
33
+ * Returns the number of managers that had orphan connections.
34
+ */
35
+ export declare function cleanupOrphanConnections(): number;
@@ -23,16 +23,34 @@ export function getXYWebSocketManager(config) {
23
23
  let cached = wsManagerCache.get(cacheKey);
24
24
  if (cached && cached.isConfigMatch(config)) {
25
25
  const log = runtime?.log ?? console.log;
26
- log(`[DEBUG] Reusing cached WebSocket manager: ${cacheKey}`);
26
+ log(`[WS-MANAGER-CACHE] Reusing cached WebSocket manager: ${cacheKey}, total managers: ${wsManagerCache.size}`);
27
27
  return cached;
28
28
  }
29
29
  // Create new manager
30
30
  const log = runtime?.log ?? console.log;
31
- log(`Creating new WebSocket manager: ${cacheKey}`);
31
+ log(`[WS-MANAGER-CACHE] 🆕 Creating new WebSocket manager: ${cacheKey}, total managers before: ${wsManagerCache.size}`);
32
32
  cached = new XYWebSocketManager(config, runtime);
33
33
  wsManagerCache.set(cacheKey, cached);
34
+ log(`[WS-MANAGER-CACHE] 📊 Total managers after creation: ${wsManagerCache.size}`);
34
35
  return cached;
35
36
  }
37
+ /**
38
+ * Remove a specific WebSocket manager from cache.
39
+ * Disconnects the manager and removes it from the cache.
40
+ */
41
+ export function removeXYWebSocketManager(config) {
42
+ const cacheKey = `${config.apiKey}-${config.agentId}`;
43
+ const manager = wsManagerCache.get(cacheKey);
44
+ if (manager) {
45
+ console.log(`🗑️ [WS-MANAGER-CACHE] Removing manager from cache: ${cacheKey}`);
46
+ manager.disconnect();
47
+ wsManagerCache.delete(cacheKey);
48
+ console.log(`🗑️ [WS-MANAGER-CACHE] Manager removed, remaining managers: ${wsManagerCache.size}`);
49
+ }
50
+ else {
51
+ console.log(`⚠️ [WS-MANAGER-CACHE] Manager not found in cache: ${cacheKey}`);
52
+ }
53
+ }
36
54
  /**
37
55
  * Clear all cached WebSocket managers.
38
56
  */
@@ -50,3 +68,67 @@ export function clearXYWebSocketManagers() {
50
68
  export function getCachedManagerCount() {
51
69
  return wsManagerCache.size;
52
70
  }
71
+ /**
72
+ * Diagnose all cached WebSocket managers.
73
+ * Helps identify connection issues and orphan connections.
74
+ */
75
+ export function diagnoseAllManagers() {
76
+ console.log("========================================");
77
+ console.log("📊 WebSocket Manager Global Diagnostics");
78
+ console.log("========================================");
79
+ console.log(`Total cached managers: ${wsManagerCache.size}`);
80
+ console.log("");
81
+ if (wsManagerCache.size === 0) {
82
+ console.log("ℹ️ No managers in cache");
83
+ console.log("========================================");
84
+ return;
85
+ }
86
+ let orphanCount = 0;
87
+ wsManagerCache.forEach((manager, key) => {
88
+ const diag = manager.getConnectionDiagnostics();
89
+ console.log(`📌 Manager: ${key}`);
90
+ console.log(` Shutting down: ${diag.isShuttingDown}`);
91
+ console.log(` Total event listeners on manager: ${diag.totalEventListeners}`);
92
+ // Connection
93
+ console.log(` 🔌 Connection:`);
94
+ console.log(` - Exists: ${diag.connection.exists}`);
95
+ console.log(` - ReadyState: ${diag.connection.readyState}`);
96
+ console.log(` - State connected/ready: ${diag.connection.stateConnected}/${diag.connection.stateReady}`);
97
+ console.log(` - Reconnect attempts: ${diag.connection.reconnectAttempts}`);
98
+ console.log(` - Listeners on WebSocket: ${diag.connection.listenerCount}`);
99
+ console.log(` - Heartbeat active: ${diag.connection.heartbeatActive}`);
100
+ console.log(` - Has reconnect timer: ${diag.connection.hasReconnectTimer}`);
101
+ if (diag.connection.isOrphan) {
102
+ console.log(` ⚠️ ORPHAN CONNECTION DETECTED!`);
103
+ orphanCount++;
104
+ }
105
+ console.log("");
106
+ });
107
+ if (orphanCount > 0) {
108
+ console.log(`⚠️ Total orphan connections found: ${orphanCount}`);
109
+ console.log(`💡 Suggestion: These connections should be cleaned up`);
110
+ }
111
+ else {
112
+ console.log(`✅ No orphan connections found`);
113
+ }
114
+ console.log("========================================");
115
+ }
116
+ /**
117
+ * Clean up orphan connections across all managers.
118
+ * Returns the number of managers that had orphan connections.
119
+ */
120
+ export function cleanupOrphanConnections() {
121
+ let cleanedCount = 0;
122
+ wsManagerCache.forEach((manager, key) => {
123
+ const diag = manager.getConnectionDiagnostics();
124
+ if (diag.connection.isOrphan) {
125
+ console.log(`🧹 Cleaning up orphan connections in manager: ${key}`);
126
+ manager.disconnect();
127
+ cleanedCount++;
128
+ }
129
+ });
130
+ if (cleanedCount > 0) {
131
+ console.log(`🧹 Cleaned up ${cleanedCount} manager(s) with orphan connections`);
132
+ }
133
+ return cleanedCount;
134
+ }
@@ -17,8 +17,8 @@ export function resolveXYConfig(cfg) {
17
17
  // Return configuration with defaults
18
18
  return {
19
19
  enabled: xyConfig.enabled ?? false,
20
- wsUrl1: xyConfig.wsUrl1 ?? "ws://localhost:8765/ws/link",
21
- wsUrl2: xyConfig.wsUrl2 ?? "ws://localhost:8768/ws/link",
20
+ // ✅ 兼容旧配置:优先使用 wsUrl,然后 wsUrl2(wsUrl1 被忽略)
21
+ wsUrl: xyConfig.wsUrl ?? xyConfig.wsUrl2 ?? "ws://localhost:8768/ws/link",
22
22
  apiKey: xyConfig.apiKey,
23
23
  uid: xyConfig.uid,
24
24
  agentId: xyConfig.agentId,
@@ -8,8 +8,10 @@ import { logger } from "./utils/logger.js";
8
8
  */
9
9
  export async function downloadFile(url, destPath) {
10
10
  logger.debug(`Downloading file from ${url} to ${destPath}`);
11
+ const controller = new AbortController();
12
+ const timeout = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
11
13
  try {
12
- const response = await fetch(url);
14
+ const response = await fetch(url, { signal: controller.signal });
13
15
  if (!response.ok) {
14
16
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
15
17
  }
@@ -19,9 +21,16 @@ export async function downloadFile(url, destPath) {
19
21
  logger.debug(`File downloaded successfully: ${destPath}`);
20
22
  }
21
23
  catch (error) {
24
+ if (error.name === 'AbortError') {
25
+ logger.error(`Download timeout (30s) for ${url}`);
26
+ throw new Error(`Download timeout after 30 seconds`);
27
+ }
22
28
  logger.error(`Failed to download file from ${url}:`, error);
23
29
  throw error;
24
30
  }
31
+ finally {
32
+ clearTimeout(timeout);
33
+ }
25
34
  }
26
35
  /**
27
36
  * Download files from A2A file parts.
@@ -48,7 +48,7 @@ export class XYFileUploadService {
48
48
  uid: this.uid,
49
49
  teamId: this.uid,
50
50
  },
51
- useEdge: true,
51
+ useEdge: false,
52
52
  }),
53
53
  });
54
54
  if (!prepareResp.ok) {
@@ -20,6 +20,23 @@ export interface SendA2AResponseParams {
20
20
  * Send an A2A artifact update response.
21
21
  */
22
22
  export declare function sendA2AResponse(params: SendA2AResponseParams): Promise<void>;
23
+ /**
24
+ * Parameters for sending a reasoning text update (intermediate, streamed).
25
+ */
26
+ export interface SendReasoningTextUpdateParams {
27
+ config: XYChannelConfig;
28
+ sessionId: string;
29
+ taskId: string;
30
+ messageId: string;
31
+ text: string;
32
+ append?: boolean;
33
+ }
34
+ /**
35
+ * Send an A2A artifact-update with reasoningText part.
36
+ * Used for onToolStart, onToolResult, onReasoningStream, onReasoningEnd, onPartialReply.
37
+ * append=true, final=false, lastChunk=true, text is suffixed with newline for markdown rendering.
38
+ */
39
+ export declare function sendReasoningTextUpdate(params: SendReasoningTextUpdateParams): Promise<void>;
23
40
  /**
24
41
  * Parameters for sending a status update.
25
42
  */
@@ -67,6 +67,49 @@ export async function sendA2AResponse(params) {
67
67
  await wsManager.sendMessage(sessionId, outboundMessage);
68
68
  log(`[A2A_RESPONSE] ✅ Message sent successfully`);
69
69
  }
70
+ /**
71
+ * Send an A2A artifact-update with reasoningText part.
72
+ * Used for onToolStart, onToolResult, onReasoningStream, onReasoningEnd, onPartialReply.
73
+ * append=true, final=false, lastChunk=true, text is suffixed with newline for markdown rendering.
74
+ */
75
+ export async function sendReasoningTextUpdate(params) {
76
+ const { config, sessionId, taskId, messageId, text, append = true } = params;
77
+ const runtime = getXYRuntime();
78
+ const log = runtime?.log ?? console.log;
79
+ const error = runtime?.error ?? console.error;
80
+ const artifact = {
81
+ taskId,
82
+ kind: "artifact-update",
83
+ append,
84
+ lastChunk: true,
85
+ final: false,
86
+ artifact: {
87
+ artifactId: uuidv4(),
88
+ parts: [
89
+ {
90
+ kind: "reasoningText",
91
+ reasoningText: text,
92
+ },
93
+ ],
94
+ },
95
+ };
96
+ const jsonRpcResponse = {
97
+ jsonrpc: "2.0",
98
+ id: messageId,
99
+ result: artifact,
100
+ };
101
+ const wsManager = getXYWebSocketManager(config);
102
+ const outboundMessage = {
103
+ msgType: "agent_response",
104
+ agentId: config.agentId,
105
+ sessionId,
106
+ taskId,
107
+ msgDetail: JSON.stringify(jsonRpcResponse),
108
+ };
109
+ log(`[REASONING_TEXT] 📤 Sending reasoningText update: sessionId=${sessionId}, taskId=${taskId}, text.length=${text.length}`);
110
+ await wsManager.sendMessage(sessionId, outboundMessage);
111
+ log(`[REASONING_TEXT] ✅ Sent successfully`);
112
+ }
70
113
  /**
71
114
  * Send an A2A task status update.
72
115
  * Follows A2A protocol standard format with nested status object.
@@ -132,6 +175,7 @@ export async function sendCommand(params) {
132
175
  const log = runtime?.log ?? console.log;
133
176
  const error = runtime?.error ?? console.error;
134
177
  // Build artifact update with command as data
178
+ // Wrap command in commands array as per protocol requirement
135
179
  const artifact = {
136
180
  taskId,
137
181
  kind: "artifact-update",
@@ -143,7 +187,9 @@ export async function sendCommand(params) {
143
187
  parts: [
144
188
  {
145
189
  kind: "data",
146
- data: command,
190
+ data: {
191
+ commands: [command],
192
+ },
147
193
  },
148
194
  ],
149
195
  },
@@ -13,12 +13,13 @@ export declare class HeartbeatManager {
13
13
  private config;
14
14
  private onTimeout;
15
15
  private serverName;
16
+ private onHeartbeatSuccess?;
16
17
  private intervalTimer;
17
18
  private timeoutTimer;
18
19
  private lastPongTime;
19
20
  private log;
20
21
  private error;
21
- constructor(ws: WebSocket, config: HeartbeatConfig, onTimeout: () => void, serverName?: string, logFn?: (msg: string, ...args: any[]) => void, errorFn?: (msg: string, ...args: any[]) => void);
22
+ constructor(ws: WebSocket, config: HeartbeatConfig, onTimeout: () => void, serverName?: string, logFn?: (msg: string, ...args: any[]) => void, errorFn?: (msg: string, ...args: any[]) => void, onHeartbeatSuccess?: () => void);
22
23
  /**
23
24
  * Start heartbeat monitoring.
24
25
  */