@ynhcj/xiaoyi-channel 0.0.7 → 0.0.8-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.
- package/dist/src/bot.js +114 -46
- package/dist/src/channel.js +23 -4
- package/dist/src/client.d.ts +15 -0
- package/dist/src/client.js +84 -2
- package/dist/src/config.js +2 -2
- package/dist/src/file-download.js +10 -1
- package/dist/src/file-upload.js +1 -1
- package/dist/src/formatter.d.ts +17 -0
- package/dist/src/formatter.js +47 -1
- package/dist/src/heartbeat.d.ts +2 -1
- package/dist/src/heartbeat.js +9 -1
- package/dist/src/monitor.d.ts +5 -0
- package/dist/src/monitor.js +119 -8
- package/dist/src/outbound.js +97 -7
- package/dist/src/parser.d.ts +5 -0
- package/dist/src/parser.js +15 -0
- package/dist/src/push.d.ts +13 -1
- package/dist/src/push.js +125 -19
- package/dist/src/reply-dispatcher.d.ts +1 -0
- package/dist/src/reply-dispatcher.js +206 -51
- package/dist/src/task-manager.d.ts +55 -0
- package/dist/src/task-manager.js +136 -0
- package/dist/src/tools/calendar-tool.d.ts +6 -0
- package/dist/src/tools/calendar-tool.js +169 -0
- package/dist/src/tools/call-phone-tool.d.ts +5 -0
- package/dist/src/tools/call-phone-tool.js +183 -0
- package/dist/src/tools/create-alarm-tool.d.ts +7 -0
- package/dist/src/tools/create-alarm-tool.js +446 -0
- package/dist/src/tools/delete-alarm-tool.d.ts +11 -0
- package/dist/src/tools/delete-alarm-tool.js +238 -0
- package/dist/src/tools/location-tool.js +18 -8
- package/dist/src/tools/modify-alarm-tool.d.ts +9 -0
- package/dist/src/tools/modify-alarm-tool.js +467 -0
- package/dist/src/tools/modify-note-tool.d.ts +9 -0
- package/dist/src/tools/modify-note-tool.js +163 -0
- package/dist/src/tools/note-tool.js +32 -11
- package/dist/src/tools/search-alarm-tool.d.ts +8 -0
- package/dist/src/tools/search-alarm-tool.js +391 -0
- package/dist/src/tools/search-calendar-tool.d.ts +12 -0
- package/dist/src/tools/search-calendar-tool.js +262 -0
- package/dist/src/tools/search-contact-tool.d.ts +5 -0
- package/dist/src/tools/search-contact-tool.js +168 -0
- package/dist/src/tools/search-file-tool.d.ts +5 -0
- package/dist/src/tools/search-file-tool.js +185 -0
- package/dist/src/tools/search-message-tool.d.ts +5 -0
- package/dist/src/tools/search-message-tool.js +173 -0
- package/dist/src/tools/search-note-tool.js +6 -6
- package/dist/src/tools/search-photo-gallery-tool.d.ts +8 -0
- package/dist/src/tools/search-photo-gallery-tool.js +212 -0
- package/dist/src/tools/search-photo-tool.d.ts +9 -0
- package/dist/src/tools/search-photo-tool.js +270 -0
- package/dist/src/tools/send-file-to-user-tool.d.ts +5 -0
- package/dist/src/tools/send-file-to-user-tool.js +318 -0
- package/dist/src/tools/send-message-tool.d.ts +5 -0
- package/dist/src/tools/send-message-tool.js +189 -0
- package/dist/src/tools/session-manager.d.ts +15 -0
- package/dist/src/tools/session-manager.js +101 -13
- package/dist/src/tools/upload-file-tool.d.ts +13 -0
- package/dist/src/tools/upload-file-tool.js +265 -0
- package/dist/src/tools/upload-photo-tool.d.ts +9 -0
- package/dist/src/tools/upload-photo-tool.js +223 -0
- package/dist/src/tools/view-push-result-tool.d.ts +5 -0
- package/dist/src/tools/view-push-result-tool.js +118 -0
- package/dist/src/tools/xiaoyi-collection-tool.d.ts +5 -0
- package/dist/src/tools/xiaoyi-collection-tool.js +190 -0
- package/dist/src/tools/xiaoyi-gui-tool.d.ts +6 -0
- package/dist/src/tools/xiaoyi-gui-tool.js +151 -0
- package/dist/src/trigger-handler.d.ts +19 -0
- package/dist/src/trigger-handler.js +96 -0
- package/dist/src/types.d.ts +6 -17
- package/dist/src/types.js +4 -0
- package/dist/src/utils/config-manager.d.ts +26 -0
- package/dist/src/utils/config-manager.js +56 -0
- package/dist/src/utils/pushdata-manager.d.ts +28 -0
- package/dist/src/utils/pushdata-manager.js +171 -0
- package/dist/src/utils/pushid-manager.d.ts +12 -0
- package/dist/src/utils/pushid-manager.js +105 -0
- package/dist/src/websocket.d.ts +59 -25
- package/dist/src/websocket.js +317 -248
- 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.
|
|
@@ -55,6 +57,38 @@ export async function handleXYMessage(params) {
|
|
|
55
57
|
}
|
|
56
58
|
// Parse the A2A message (for regular messages)
|
|
57
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
|
+
}
|
|
58
92
|
// Resolve configuration (needed for status updates)
|
|
59
93
|
const config = resolveXYConfig(cfg);
|
|
60
94
|
// ✅ Resolve agent route (following feishu pattern)
|
|
@@ -70,11 +104,12 @@ export async function handleXYMessage(params) {
|
|
|
70
104
|
},
|
|
71
105
|
});
|
|
72
106
|
log(`xy: resolved route accountId=${route.accountId}, sessionKey=${route.sessionKey}`);
|
|
73
|
-
//
|
|
107
|
+
// 🔑 注册session(带引用计数)
|
|
74
108
|
log(`[BOT] 📝 About to register session for tools...`);
|
|
75
109
|
log(`[BOT] - sessionKey: ${route.sessionKey}`);
|
|
76
110
|
log(`[BOT] - sessionId: ${parsed.sessionId}`);
|
|
77
111
|
log(`[BOT] - taskId: ${parsed.taskId}`);
|
|
112
|
+
log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
|
|
78
113
|
registerSession(route.sessionKey, {
|
|
79
114
|
config,
|
|
80
115
|
sessionId: parsed.sessionId,
|
|
@@ -83,13 +118,24 @@ export async function handleXYMessage(params) {
|
|
|
83
118
|
agentId: route.accountId,
|
|
84
119
|
});
|
|
85
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
|
+
});
|
|
86
133
|
// Extract text and files from parts
|
|
87
134
|
const text = extractTextFromParts(parsed.parts);
|
|
88
135
|
const fileParts = extractFileParts(parsed.parts);
|
|
89
|
-
//
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
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);
|
|
93
139
|
// Resolve envelope format options (following feishu pattern)
|
|
94
140
|
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
|
|
95
141
|
// Build message body with speaker prefix (following feishu pattern)
|
|
@@ -99,7 +145,7 @@ export async function handleXYMessage(params) {
|
|
|
99
145
|
messageBody = `${speaker}: ${messageBody}`;
|
|
100
146
|
// Format agent envelope (following feishu pattern)
|
|
101
147
|
const body = core.channel.reply.formatAgentEnvelope({
|
|
102
|
-
channel: "
|
|
148
|
+
channel: "xiaoyi-channel",
|
|
103
149
|
from: speaker,
|
|
104
150
|
timestamp: new Date(),
|
|
105
151
|
envelope: envelopeOptions,
|
|
@@ -130,99 +176,121 @@ export async function handleXYMessage(params) {
|
|
|
130
176
|
ReplyToBody: undefined, // A2A protocol doesn't support reply/quote
|
|
131
177
|
...mediaPayload,
|
|
132
178
|
});
|
|
133
|
-
//
|
|
134
|
-
log(`[
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
taskId: parsed.taskId,
|
|
139
|
-
messageId: parsed.messageId,
|
|
140
|
-
text: "任务正在处理中,请稍后~",
|
|
141
|
-
state: "working",
|
|
142
|
-
}).catch((err) => {
|
|
143
|
-
error(`Failed to send initial status update:`, err);
|
|
144
|
-
});
|
|
145
|
-
// 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}`);
|
|
146
184
|
const { dispatcher, replyOptions, markDispatchIdle, startStatusInterval } = createXYReplyDispatcher({
|
|
147
185
|
cfg,
|
|
148
186
|
runtime,
|
|
149
187
|
sessionId: parsed.sessionId,
|
|
150
188
|
taskId: parsed.taskId,
|
|
151
189
|
messageId: parsed.messageId,
|
|
152
|
-
accountId: route.accountId,
|
|
190
|
+
accountId: route.accountId,
|
|
191
|
+
isSteerFollower: isSecondMessage, // 🔑 标记第二条消息
|
|
153
192
|
});
|
|
154
|
-
|
|
155
|
-
//
|
|
156
|
-
|
|
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
|
+
}
|
|
157
203
|
log(`xy: dispatching to agent (session=${parsed.sessionId})`);
|
|
158
204
|
// Dispatch to OpenClaw core using correct API (following feishu pattern)
|
|
159
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
|
+
};
|
|
160
214
|
await core.channel.reply.withReplyDispatcher({
|
|
161
215
|
dispatcher,
|
|
162
216
|
onSettled: () => {
|
|
163
217
|
log(`[BOT] 🏁 onSettled called for session: ${route.sessionKey}`);
|
|
164
|
-
log(`[BOT] -
|
|
218
|
+
log(`[BOT] - isSecondMessage: ${isSecondMessage}`);
|
|
165
219
|
markDispatchIdle();
|
|
166
|
-
//
|
|
220
|
+
// 🔑 减少引用计数
|
|
221
|
+
decrementTaskIdRef(parsed.sessionId);
|
|
222
|
+
// 🔑 如果是第一条消息完成,解锁
|
|
223
|
+
if (!isSecondMessage) {
|
|
224
|
+
unlockTaskId(parsed.sessionId);
|
|
225
|
+
log(`[BOT] 🔓 Unlocked taskId (first message completed)`);
|
|
226
|
+
}
|
|
227
|
+
// 减少session引用计数
|
|
167
228
|
unregisterSession(route.sessionKey);
|
|
168
|
-
log(`[BOT] ✅
|
|
229
|
+
log(`[BOT] ✅ Cleanup completed`);
|
|
169
230
|
},
|
|
170
|
-
run: () =>
|
|
231
|
+
run: () =>
|
|
232
|
+
// 🔐 Use AsyncLocalStorage to provide session context to tools
|
|
233
|
+
runWithSessionContext(sessionContext, () => core.channel.reply.dispatchReplyFromConfig({
|
|
171
234
|
ctx: ctxPayload,
|
|
172
235
|
cfg,
|
|
173
236
|
dispatcher,
|
|
174
237
|
replyOptions,
|
|
175
|
-
}),
|
|
238
|
+
})),
|
|
176
239
|
});
|
|
177
240
|
log(`[BOT] ✅ Dispatcher completed for session: ${parsed.sessionId}`);
|
|
178
241
|
log(`xy: dispatch complete (session=${parsed.sessionId})`);
|
|
179
242
|
}
|
|
180
243
|
catch (err) {
|
|
244
|
+
// ✅ Only log error, don't re-throw to prevent gateway restart
|
|
181
245
|
error("Failed to handle XY message:", err);
|
|
182
246
|
runtime.error?.(`xy: Failed to handle message: ${String(err)}`);
|
|
183
247
|
log(`[BOT] ❌ Error occurred, attempting cleanup...`);
|
|
184
|
-
//
|
|
248
|
+
// 🔑 错误时也要清理taskId和session
|
|
185
249
|
try {
|
|
186
|
-
const core = getXYRuntime();
|
|
187
250
|
const params = message.params;
|
|
188
251
|
const sessionId = params?.sessionId;
|
|
189
252
|
if (sessionId) {
|
|
190
|
-
log(`[BOT] 🧹 Cleaning up
|
|
253
|
+
log(`[BOT] 🧹 Cleaning up after error: ${sessionId}`);
|
|
254
|
+
// 清理 taskId
|
|
255
|
+
decrementTaskIdRef(sessionId);
|
|
256
|
+
unlockTaskId(sessionId);
|
|
257
|
+
// 清理 session
|
|
258
|
+
const core = getXYRuntime();
|
|
191
259
|
const route = core.channel.routing.resolveAgentRoute({
|
|
192
260
|
cfg,
|
|
193
261
|
channel: "xiaoyi-channel",
|
|
194
262
|
accountId,
|
|
195
263
|
peer: {
|
|
196
264
|
kind: "direct",
|
|
197
|
-
id: sessionId,
|
|
265
|
+
id: sessionId,
|
|
198
266
|
},
|
|
199
267
|
});
|
|
200
|
-
log(`[BOT] - Unregistering session: ${route.sessionKey}`);
|
|
201
268
|
unregisterSession(route.sessionKey);
|
|
202
|
-
log(`[BOT] ✅
|
|
269
|
+
log(`[BOT] ✅ Cleanup completed after error`);
|
|
203
270
|
}
|
|
204
271
|
}
|
|
205
272
|
catch (cleanupErr) {
|
|
206
273
|
log(`[BOT] ⚠️ Cleanup failed:`, cleanupErr);
|
|
207
274
|
// Ignore cleanup errors
|
|
208
275
|
}
|
|
209
|
-
throw
|
|
276
|
+
// ❌ Don't re-throw: message processing error should not affect gateway stability
|
|
210
277
|
}
|
|
211
278
|
}
|
|
212
279
|
/**
|
|
213
280
|
* Build media payload for inbound context.
|
|
214
281
|
* Following feishu pattern: buildFeishuMediaPayload().
|
|
282
|
+
* Uses remote URIs directly - openclaw will download them.
|
|
215
283
|
*/
|
|
216
|
-
function buildXYMediaPayload(
|
|
217
|
-
const first =
|
|
218
|
-
const
|
|
219
|
-
const mediaTypes =
|
|
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);
|
|
220
288
|
return {
|
|
221
|
-
MediaPath: first?.
|
|
289
|
+
MediaPath: first?.uri,
|
|
222
290
|
MediaType: first?.mimeType,
|
|
223
|
-
MediaUrl: first?.
|
|
224
|
-
MediaPaths:
|
|
225
|
-
MediaUrls:
|
|
291
|
+
MediaUrl: first?.uri,
|
|
292
|
+
MediaPaths: uris.length > 0 ? uris : undefined,
|
|
293
|
+
MediaUrls: uris.length > 0 ? uris : undefined,
|
|
226
294
|
MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
|
|
227
295
|
};
|
|
228
296
|
}
|
package/dist/src/channel.js
CHANGED
|
@@ -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
|
-
|
|
74
|
-
wsUrl2: account.wsUrl2,
|
|
92
|
+
wsUrl: account.wsUrl,
|
|
75
93
|
});
|
|
76
|
-
context.log?.info(`[${context.accountId}] starting xiaoyi channel (
|
|
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
|
},
|
package/dist/src/client.d.ts
CHANGED
|
@@ -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;
|
package/dist/src/client.js
CHANGED
|
@@ -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(`[
|
|
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
|
+
}
|
package/dist/src/config.js
CHANGED
|
@@ -17,8 +17,8 @@ export function resolveXYConfig(cfg) {
|
|
|
17
17
|
// Return configuration with defaults
|
|
18
18
|
return {
|
|
19
19
|
enabled: xyConfig.enabled ?? false,
|
|
20
|
-
|
|
21
|
-
|
|
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.
|
package/dist/src/file-upload.js
CHANGED
package/dist/src/formatter.d.ts
CHANGED
|
@@ -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
|
*/
|
package/dist/src/formatter.js
CHANGED
|
@@ -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:
|
|
190
|
+
data: {
|
|
191
|
+
commands: [command],
|
|
192
|
+
},
|
|
147
193
|
},
|
|
148
194
|
],
|
|
149
195
|
},
|
package/dist/src/heartbeat.d.ts
CHANGED
|
@@ -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
|
*/
|
package/dist/src/heartbeat.js
CHANGED
|
@@ -9,17 +9,20 @@ export class HeartbeatManager {
|
|
|
9
9
|
config;
|
|
10
10
|
onTimeout;
|
|
11
11
|
serverName;
|
|
12
|
+
onHeartbeatSuccess;
|
|
12
13
|
intervalTimer = null;
|
|
13
14
|
timeoutTimer = null;
|
|
14
15
|
lastPongTime = 0;
|
|
15
16
|
// Logging functions following feishu pattern
|
|
16
17
|
log;
|
|
17
18
|
error;
|
|
18
|
-
constructor(ws, config, onTimeout, serverName = "unknown", logFn, errorFn
|
|
19
|
+
constructor(ws, config, onTimeout, serverName = "unknown", logFn, errorFn, onHeartbeatSuccess // ✅ 新增:心跳成功回调
|
|
20
|
+
) {
|
|
19
21
|
this.ws = ws;
|
|
20
22
|
this.config = config;
|
|
21
23
|
this.onTimeout = onTimeout;
|
|
22
24
|
this.serverName = serverName;
|
|
25
|
+
this.onHeartbeatSuccess = onHeartbeatSuccess;
|
|
23
26
|
this.log = logFn ?? console.log;
|
|
24
27
|
this.error = errorFn ?? console.error;
|
|
25
28
|
}
|
|
@@ -36,6 +39,8 @@ export class HeartbeatManager {
|
|
|
36
39
|
clearTimeout(this.timeoutTimer);
|
|
37
40
|
this.timeoutTimer = null;
|
|
38
41
|
}
|
|
42
|
+
// ✅ Report health: heartbeat successful
|
|
43
|
+
this.onHeartbeatSuccess?.();
|
|
39
44
|
});
|
|
40
45
|
// Start interval timer
|
|
41
46
|
this.intervalTimer = setInterval(() => {
|
|
@@ -67,9 +72,12 @@ export class HeartbeatManager {
|
|
|
67
72
|
}
|
|
68
73
|
try {
|
|
69
74
|
// Send application-level heartbeat message
|
|
75
|
+
console.log(`[WS-${this.serverName}-SEND] Sending heartbeat frame:`, this.config.message);
|
|
70
76
|
this.ws.send(this.config.message);
|
|
77
|
+
console.log(`[WS-${this.serverName}-SEND] Heartbeat message sent, size: ${this.config.message.length} bytes`);
|
|
71
78
|
// Send protocol-level ping
|
|
72
79
|
this.ws.ping();
|
|
80
|
+
console.log(`[WS-${this.serverName}-SEND] Protocol-level ping sent`);
|
|
73
81
|
// Setup timeout timer
|
|
74
82
|
this.timeoutTimer = setTimeout(() => {
|
|
75
83
|
this.error(`Heartbeat timeout for ${this.serverName}`);
|