@ynhcj/xiaoyi-channel 0.0.131-beta → 0.0.133-beta
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/index.js +4 -3
- package/dist/src/bot.d.ts +2 -0
- package/dist/src/bot.js +79 -74
- package/dist/src/client.d.ts +1 -5
- package/dist/src/client.js +25 -39
- package/dist/src/file-download.js +3 -3
- package/dist/src/formatter.d.ts +0 -2
- package/dist/src/formatter.js +12 -14
- package/dist/src/heartbeat.js +3 -2
- package/dist/src/login-token-handler.js +7 -8
- package/dist/src/message-queue.js +2 -1
- package/dist/src/monitor.js +55 -46
- package/dist/src/outbound.js +3 -0
- package/dist/src/provider.js +85 -64
- package/dist/src/push.js +9 -9
- package/dist/src/reply-dispatcher.js +43 -53
- package/dist/src/self-evolution-handler.js +11 -14
- package/dist/src/tools/send-file-to-user-tool.js +0 -1
- package/dist/src/tools/session-helper.d.ts +24 -0
- package/dist/src/tools/session-helper.js +45 -0
- package/dist/src/tools/session-manager.d.ts +8 -0
- package/dist/src/tools/session-manager.js +2 -14
- package/dist/src/trigger-handler.js +8 -9
- package/dist/src/utils/logger.js +106 -22
- package/dist/src/utils/throw.d.ts +5 -0
- package/dist/src/utils/throw.js +10 -0
- package/dist/src/websocket.js +4 -2
- package/dist/src/xy-session-store.d.ts +79 -0
- package/dist/src/xy-session-store.js +153 -0
- package/package.json +6 -5
package/dist/src/heartbeat.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Heartbeat management for WebSocket connections
|
|
2
2
|
import WebSocket from "ws";
|
|
3
|
+
import { logger } from "./utils/logger.js";
|
|
3
4
|
/**
|
|
4
5
|
* Manages heartbeat for a WebSocket connection.
|
|
5
6
|
* Supports both application-level (30s) and protocol-level (20s) heartbeats.
|
|
@@ -23,8 +24,8 @@ export class HeartbeatManager {
|
|
|
23
24
|
this.onTimeout = onTimeout;
|
|
24
25
|
this.serverName = serverName;
|
|
25
26
|
this.onHeartbeatSuccess = onHeartbeatSuccess;
|
|
26
|
-
this.log = logFn ??
|
|
27
|
-
this.error = errorFn ??
|
|
27
|
+
this.log = logFn ?? ((msg, ...args) => logger.log(msg, ...args));
|
|
28
|
+
this.error = errorFn ?? ((msg, ...args) => logger.error(msg, ...args));
|
|
28
29
|
}
|
|
29
30
|
/**
|
|
30
31
|
* Start heartbeat monitoring.
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// 监听 LoginTokenEvent.ClawAutoLogin 事件,将 clientId 写入 .xiaoyitoken.json
|
|
3
3
|
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
|
|
4
4
|
import { dirname } from "path";
|
|
5
|
+
import { logger } from "./utils/logger.js";
|
|
5
6
|
const TOKEN_FILE_PATH = "/home/sandbox/.openclaw/.xiaoyitoken.json";
|
|
6
7
|
/**
|
|
7
8
|
* 处理 LoginTokenEvent.ClawAutoLogin 事件
|
|
@@ -11,15 +12,13 @@ const TOKEN_FILE_PATH = "/home/sandbox/.openclaw/.xiaoyitoken.json";
|
|
|
11
12
|
* @param runtime - 运行时环境
|
|
12
13
|
*/
|
|
13
14
|
export function handleLoginTokenEvent(context, runtime) {
|
|
14
|
-
const log = runtime?.log ?? console.log;
|
|
15
|
-
const error = runtime?.error ?? console.error;
|
|
16
15
|
try {
|
|
17
16
|
const clientId = context.event?.payload?.clientId;
|
|
18
17
|
if (!clientId || typeof clientId !== "string") {
|
|
19
|
-
error("[LOGIN_TOKEN_HANDLER] invalid payload: missing clientId");
|
|
18
|
+
logger.error("[LOGIN_TOKEN_HANDLER] invalid payload: missing clientId");
|
|
20
19
|
return;
|
|
21
20
|
}
|
|
22
|
-
log(`[LOGIN_TOKEN_HANDLER] received login token event, clientId=${clientId}`);
|
|
21
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] received login token event, clientId=${clientId}`);
|
|
23
22
|
// Ensure directory exists
|
|
24
23
|
const dir = dirname(TOKEN_FILE_PATH);
|
|
25
24
|
if (!existsSync(dir)) {
|
|
@@ -44,17 +43,17 @@ export function handleLoginTokenEvent(context, runtime) {
|
|
|
44
43
|
if (existing) {
|
|
45
44
|
// Update timestamp
|
|
46
45
|
existing.timestamp = now;
|
|
47
|
-
log(`[LOGIN_TOKEN_HANDLER] updated timestamp for clientId=${clientId}`);
|
|
46
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] updated timestamp for clientId=${clientId}`);
|
|
48
47
|
}
|
|
49
48
|
else {
|
|
50
49
|
// Insert new entry
|
|
51
50
|
tokens.push({ clientId, timestamp: now });
|
|
52
|
-
log(`[LOGIN_TOKEN_HANDLER] inserted new entry for clientId=${clientId}`);
|
|
51
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] inserted new entry for clientId=${clientId}`);
|
|
53
52
|
}
|
|
54
53
|
writeFileSync(TOKEN_FILE_PATH, JSON.stringify(tokens, null, 2), "utf-8");
|
|
55
|
-
log(`[LOGIN_TOKEN_HANDLER] wrote token file: ${TOKEN_FILE_PATH}`);
|
|
54
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] wrote token file: ${TOKEN_FILE_PATH}`);
|
|
56
55
|
}
|
|
57
56
|
catch (err) {
|
|
58
|
-
error("[LOGIN_TOKEN_HANDLER] failed to handle event:", err);
|
|
57
|
+
logger.error("[LOGIN_TOKEN_HANDLER] failed to handle event:", err);
|
|
59
58
|
}
|
|
60
59
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { logger } from "./utils/logger.js";
|
|
1
2
|
const MAX_QUEUE_SIZE = 1000;
|
|
2
3
|
/**
|
|
3
4
|
* Simple message queue for buffering outbound WebSocket messages
|
|
@@ -7,7 +8,7 @@ export class MessageQueue {
|
|
|
7
8
|
items = [];
|
|
8
9
|
log;
|
|
9
10
|
constructor(log) {
|
|
10
|
-
this.log = log ??
|
|
11
|
+
this.log = log ?? ((msg, ...args) => logger.log(msg, ...args));
|
|
11
12
|
}
|
|
12
13
|
/** Enqueue a message. Drops oldest if over limit. */
|
|
13
14
|
enqueue(message) {
|
package/dist/src/monitor.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolveXYConfig } from "./config.js";
|
|
2
|
-
import { getXYWebSocketManager,
|
|
2
|
+
import { getXYWebSocketManager, diagnoseAllManagers, cleanupOrphanConnections, removeXYWebSocketManager } from "./client.js";
|
|
3
3
|
import { handleXYMessage } from "./bot.js";
|
|
4
4
|
import { parseA2AMessage } from "./parser.js";
|
|
5
5
|
import { hasActiveTask, getAllActiveTaskBindings } from "./task-manager.js";
|
|
@@ -9,6 +9,7 @@ import { handleSelfEvolutionEvent, handleSelfEvolutionStateGetEvent } from "./se
|
|
|
9
9
|
import { handleLoginTokenEvent } from "./login-token-handler.js";
|
|
10
10
|
import { cleanupStaleTempFiles } from "./reply-dispatcher.js";
|
|
11
11
|
import { cleanupStaleSessions, getActiveSessionCount, cleanupAllSessions } from "./tools/session-manager.js";
|
|
12
|
+
import { logger } from "./utils/logger.js";
|
|
12
13
|
/**
|
|
13
14
|
* Per-session serial queue that ensures messages from the same session are processed
|
|
14
15
|
* in arrival order while allowing different sessions to run concurrently.
|
|
@@ -38,8 +39,6 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
38
39
|
throw new Error("Config is required for XY monitor");
|
|
39
40
|
}
|
|
40
41
|
const runtime = opts.runtime;
|
|
41
|
-
const log = runtime?.log ?? console.log;
|
|
42
|
-
const error = runtime?.error ?? console.error;
|
|
43
42
|
const account = resolveXYConfig(cfg);
|
|
44
43
|
if (!account.enabled) {
|
|
45
44
|
throw new Error(`XY account is disabled`);
|
|
@@ -51,13 +50,11 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
51
50
|
opts.setStatus({ lastEventAt: Date.now(), lastInboundAt: Date.now() });
|
|
52
51
|
}
|
|
53
52
|
: undefined;
|
|
54
|
-
// ✅ Set runtime for WebSocket manager logging before creating/getting manager
|
|
55
|
-
setClientRuntime(runtime);
|
|
56
53
|
// 🔍 Diagnose WebSocket managers before gateway start
|
|
57
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
|
|
54
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
|
|
58
55
|
diagnoseAllManagers();
|
|
59
56
|
// Get WebSocket manager (cached)
|
|
60
|
-
const wsManager = getXYWebSocketManager(account);
|
|
57
|
+
const wsManager = getXYWebSocketManager(account, runtime);
|
|
61
58
|
// ✅ Set health event callback for heartbeat reporting
|
|
62
59
|
if (trackEvent) {
|
|
63
60
|
wsManager.setHealthEventCallback(trackEvent);
|
|
@@ -68,21 +65,32 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
68
65
|
const activeMessages = new Set();
|
|
69
66
|
// Create session queue for ordered message processing
|
|
70
67
|
const enqueue = createSessionQueue();
|
|
68
|
+
// Global gate that serializes dispatch initialization across sessions.
|
|
69
|
+
// When a new session starts dispatching, it acquires this gate and holds it
|
|
70
|
+
// until agent setup (agentTools + wrapStreamFn) is complete, then releases it.
|
|
71
|
+
// This prevents lastRegisteredKey races when multiple sessions initialize
|
|
72
|
+
// concurrently.
|
|
73
|
+
let globalDispatchInitGate = Promise.resolve();
|
|
71
74
|
// Health check interval
|
|
72
75
|
let healthCheckInterval = null;
|
|
73
76
|
return new Promise((resolve, reject) => {
|
|
74
77
|
// Event handlers (defined early so they can be referenced in cleanup)
|
|
75
78
|
const messageHandler = (message, sessionId, serverId) => {
|
|
76
79
|
const messageKey = `${sessionId}::${message.id}`;
|
|
77
|
-
log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
|
|
80
|
+
logger.log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
|
|
78
81
|
// ✅ Report health: received a message
|
|
79
82
|
trackEvent?.();
|
|
80
83
|
// Check for duplicate message handling
|
|
81
84
|
if (activeMessages.has(messageKey)) {
|
|
82
|
-
error(`[MONITOR-HANDLER] ⚠️ WARNING: Duplicate message detected! messageKey=${messageKey}, this may cause duplicate dispatchers!`);
|
|
85
|
+
logger.error(`[MONITOR-HANDLER] ⚠️ WARNING: Duplicate message detected! messageKey=${messageKey}, this may cause duplicate dispatchers!`);
|
|
83
86
|
}
|
|
84
87
|
activeMessages.add(messageKey);
|
|
85
88
|
const task = async () => {
|
|
89
|
+
// Wait for the previous session's init to complete (global gate),
|
|
90
|
+
// then acquire the gate for this session's init.
|
|
91
|
+
await globalDispatchInitGate;
|
|
92
|
+
let releaseGate;
|
|
93
|
+
globalDispatchInitGate = new Promise((r) => { releaseGate = r; });
|
|
86
94
|
try {
|
|
87
95
|
await handleXYMessage({
|
|
88
96
|
cfg,
|
|
@@ -90,11 +98,13 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
90
98
|
message,
|
|
91
99
|
accountId, // ✅ Pass accountId ("default")
|
|
92
100
|
webSocketSessionId: sessionId, // ✅ 传递 WebSocket 层级的 sessionId
|
|
101
|
+
onInitComplete: () => releaseGate(),
|
|
93
102
|
});
|
|
94
103
|
}
|
|
95
104
|
catch (err) {
|
|
96
105
|
// ✅ Only log error, don't re-throw to prevent gateway restart
|
|
97
|
-
|
|
106
|
+
releaseGate();
|
|
107
|
+
logger.error(`XY gateway: error handling message from ${serverId}: ${String(err)}`);
|
|
98
108
|
}
|
|
99
109
|
finally {
|
|
100
110
|
// Remove from active messages when done
|
|
@@ -109,33 +119,33 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
109
119
|
const hasActiveRun = hasActiveTask(parsed.sessionId);
|
|
110
120
|
if (steerMode && hasActiveRun) {
|
|
111
121
|
// Steer模式且有活跃任务:不入队列,直接并发执行
|
|
112
|
-
log(`[MONITOR-HANDLER] 🔄 STEER MODE: Executing concurrently for messageKey=${messageKey}`);
|
|
113
|
-
log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
|
|
122
|
+
logger.log(`[MONITOR-HANDLER] 🔄 STEER MODE: Executing concurrently for messageKey=${messageKey}`);
|
|
123
|
+
logger.log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
|
|
114
124
|
void task().catch((err) => {
|
|
115
|
-
error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
|
|
125
|
+
logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
|
|
116
126
|
activeMessages.delete(messageKey);
|
|
117
127
|
});
|
|
118
128
|
}
|
|
119
129
|
else {
|
|
120
130
|
// 正常模式:入队列串行执行
|
|
121
131
|
void enqueue(sessionId, task).catch((err) => {
|
|
122
|
-
error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
132
|
+
logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
123
133
|
activeMessages.delete(messageKey);
|
|
124
134
|
});
|
|
125
135
|
}
|
|
126
136
|
}
|
|
127
137
|
catch (parseErr) {
|
|
128
138
|
// 解析失败,回退到正常队列模式
|
|
129
|
-
error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
|
|
139
|
+
logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
|
|
130
140
|
void enqueue(sessionId, task).catch((err) => {
|
|
131
|
-
error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
141
|
+
logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
132
142
|
activeMessages.delete(messageKey);
|
|
133
143
|
});
|
|
134
144
|
}
|
|
135
145
|
};
|
|
136
146
|
const connectedHandler = (serverId) => {
|
|
137
147
|
if (!loggedServers.has(serverId)) {
|
|
138
|
-
log(`XY gateway: ${serverId} connected`);
|
|
148
|
+
logger.log(`XY gateway: ${serverId} connected`);
|
|
139
149
|
loggedServers.add(serverId);
|
|
140
150
|
}
|
|
141
151
|
// ✅ Report health: connection established
|
|
@@ -143,7 +153,7 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
143
153
|
opts.setStatus?.({ connected: true });
|
|
144
154
|
};
|
|
145
155
|
const disconnectedHandler = (serverId) => {
|
|
146
|
-
log(`XY gateway: ${serverId} disconnected`);
|
|
156
|
+
logger.log(`XY gateway: ${serverId} disconnected`);
|
|
147
157
|
loggedServers.delete(serverId);
|
|
148
158
|
// ✅ Report disconnection status (only if all servers disconnected)
|
|
149
159
|
if (loggedServers.size === 0) {
|
|
@@ -151,41 +161,41 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
151
161
|
}
|
|
152
162
|
};
|
|
153
163
|
const errorHandler = (err, serverId) => {
|
|
154
|
-
error(`XY gateway: ${serverId} error: ${String(err)}`);
|
|
164
|
+
logger.error(`XY gateway: ${serverId} error: ${String(err)}`);
|
|
155
165
|
};
|
|
156
166
|
const triggerEventHandler = (context) => {
|
|
157
|
-
log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
|
|
158
|
-
log(`[MONITOR] - sessionId: ${context.sessionId}`);
|
|
159
|
-
log(`[MONITOR] - taskId: ${context.taskId}`);
|
|
167
|
+
logger.log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
|
|
168
|
+
logger.log(`[MONITOR] - sessionId: ${context.sessionId}`);
|
|
169
|
+
logger.log(`[MONITOR] - taskId: ${context.taskId}`);
|
|
160
170
|
// 异步处理 Trigger 事件,不阻塞主流程
|
|
161
171
|
handleTriggerEvent(context, cfg, runtime, accountId).catch((err) => {
|
|
162
|
-
error(`[MONITOR] Failed to handle trigger-event:`, err);
|
|
172
|
+
logger.error(`[MONITOR] Failed to handle trigger-event:`, err);
|
|
163
173
|
});
|
|
164
174
|
};
|
|
165
175
|
const selfEvolutionHandler = (context) => {
|
|
166
|
-
log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
|
|
176
|
+
logger.log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
|
|
167
177
|
handleSelfEvolutionEvent(context, runtime);
|
|
168
178
|
};
|
|
169
179
|
const selfEvolutionStateGetHandler = (context) => {
|
|
170
|
-
log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
|
|
180
|
+
logger.log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
|
|
171
181
|
handleSelfEvolutionStateGetEvent(context, account, runtime, wsManager).catch((err) => {
|
|
172
|
-
error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
|
|
182
|
+
logger.error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
|
|
173
183
|
});
|
|
174
184
|
};
|
|
175
185
|
const loginTokenEventHandler = (context) => {
|
|
176
|
-
log(`[MONITOR] Received login-token-event, dispatching to handler...`);
|
|
186
|
+
logger.log(`[MONITOR] Received login-token-event, dispatching to handler...`);
|
|
177
187
|
handleLoginTokenEvent(context, runtime);
|
|
178
188
|
};
|
|
179
189
|
const cleanup = () => {
|
|
180
|
-
log("XY gateway: cleaning up...");
|
|
190
|
+
logger.log("XY gateway: cleaning up...");
|
|
181
191
|
// 🔍 Diagnose before cleanup
|
|
182
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
|
|
192
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
|
|
183
193
|
diagnoseAllManagers();
|
|
184
194
|
// Stop health check interval
|
|
185
195
|
if (healthCheckInterval) {
|
|
186
196
|
clearInterval(healthCheckInterval);
|
|
187
197
|
healthCheckInterval = null;
|
|
188
|
-
log("⏸️ Stopped periodic health check");
|
|
198
|
+
logger.log("⏸️ Stopped periodic health check");
|
|
189
199
|
}
|
|
190
200
|
// Remove event handlers to prevent duplicate calls on gateway restart
|
|
191
201
|
wsManager.off("message", messageHandler);
|
|
@@ -205,20 +215,20 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
205
215
|
cleanupAllSessions();
|
|
206
216
|
loggedServers.clear();
|
|
207
217
|
activeMessages.clear();
|
|
208
|
-
log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
|
|
218
|
+
logger.log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
|
|
209
219
|
// 🔍 Diagnose after cleanup
|
|
210
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
|
|
220
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
|
|
211
221
|
diagnoseAllManagers();
|
|
212
222
|
};
|
|
213
223
|
const handleAbort = async () => {
|
|
214
|
-
log("XY gateway: abort signal received, sending notifications before stopping");
|
|
224
|
+
logger.log("XY gateway: abort signal received, sending notifications before stopping");
|
|
215
225
|
// 📤 Send restart notification to all active sessions before disconnecting
|
|
216
226
|
try {
|
|
217
227
|
const activeBindings = getAllActiveTaskBindings();
|
|
218
228
|
if (activeBindings.length > 0) {
|
|
219
229
|
const config = resolveXYConfig(cfg);
|
|
220
230
|
const notificationText = "Gateway即将重启,重启期间可能短暂出现\u201c环境异常\u201d提示,请稍候并耐心重试~";
|
|
221
|
-
log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
|
|
231
|
+
logger.log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
|
|
222
232
|
const sendPromises = activeBindings.map(binding => sendA2AResponse({
|
|
223
233
|
config,
|
|
224
234
|
sessionId: binding.sessionId,
|
|
@@ -227,22 +237,21 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
227
237
|
text: notificationText,
|
|
228
238
|
append: false,
|
|
229
239
|
final: true,
|
|
230
|
-
runtime,
|
|
231
240
|
}).catch(err => {
|
|
232
|
-
error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
|
|
241
|
+
logger.error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
|
|
233
242
|
}));
|
|
234
243
|
await Promise.all(sendPromises);
|
|
235
|
-
log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
|
|
244
|
+
logger.log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
|
|
236
245
|
}
|
|
237
246
|
else {
|
|
238
|
-
log(`[MONITOR] No active sessions, skipping restart notifications`);
|
|
247
|
+
logger.log(`[MONITOR] No active sessions, skipping restart notifications`);
|
|
239
248
|
}
|
|
240
249
|
}
|
|
241
250
|
catch (err) {
|
|
242
|
-
error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
|
|
251
|
+
logger.error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
|
|
243
252
|
}
|
|
244
253
|
cleanup();
|
|
245
|
-
log("XY gateway stopped");
|
|
254
|
+
logger.log("XY gateway stopped");
|
|
246
255
|
resolve();
|
|
247
256
|
};
|
|
248
257
|
if (opts.abortSignal?.aborted) {
|
|
@@ -261,20 +270,20 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
261
270
|
wsManager.on("self-evolution-state-get-event", selfEvolutionStateGetHandler);
|
|
262
271
|
wsManager.on("login-token-event", loginTokenEventHandler);
|
|
263
272
|
// Start periodic health check (every 6 hours)
|
|
264
|
-
log("🏥 Starting periodic health check (every 6 hours)...");
|
|
273
|
+
logger.log("🏥 Starting periodic health check (every 6 hours)...");
|
|
265
274
|
healthCheckInterval = setInterval(() => {
|
|
266
|
-
log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
|
|
275
|
+
logger.log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
|
|
267
276
|
diagnoseAllManagers();
|
|
268
277
|
// Auto-cleanup orphan connections
|
|
269
278
|
const cleaned = cleanupOrphanConnections();
|
|
270
279
|
if (cleaned > 0) {
|
|
271
|
-
log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
|
|
280
|
+
logger.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
|
|
272
281
|
}
|
|
273
282
|
// Cleanup stale sessions (older than 10min TTL)
|
|
274
283
|
const cleanedSessions = cleanupStaleSessions();
|
|
275
284
|
const remainingSessions = getActiveSessionCount();
|
|
276
285
|
if (cleanedSessions > 0 || remainingSessions > 0) {
|
|
277
|
-
log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
|
|
286
|
+
logger.log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
|
|
278
287
|
}
|
|
279
288
|
// Cleanup stale temp files (older than 24 hours)
|
|
280
289
|
void cleanupStaleTempFiles();
|
|
@@ -282,11 +291,11 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
282
291
|
// Connect to WebSocket servers
|
|
283
292
|
wsManager.connect()
|
|
284
293
|
.then(() => {
|
|
285
|
-
log("XY gateway: started successfully");
|
|
294
|
+
logger.log("XY gateway: started successfully");
|
|
286
295
|
})
|
|
287
296
|
.catch((err) => {
|
|
288
297
|
// Connection failed but don't reject - continue monitoring for reconnection
|
|
289
|
-
error(`XY gateway: initial connection failed: ${String(err)}`);
|
|
298
|
+
logger.error(`XY gateway: initial connection failed: ${String(err)}`);
|
|
290
299
|
// Still resolve successfully so plugin starts
|
|
291
300
|
resolve();
|
|
292
301
|
});
|
package/dist/src/outbound.js
CHANGED
|
@@ -162,6 +162,7 @@ export const xyOutbound = {
|
|
|
162
162
|
// Parse to: "sessionId::taskId"
|
|
163
163
|
const parts = to.split("::");
|
|
164
164
|
if (parts.length !== 2) {
|
|
165
|
+
logger.error(`Invalid to format: "${to}". Expected "sessionId::taskId"`);
|
|
165
166
|
throw new Error(`Invalid to format: "${to}". Expected "sessionId::taskId"`);
|
|
166
167
|
}
|
|
167
168
|
const [sessionId, taskId] = parts;
|
|
@@ -171,12 +172,14 @@ export const xyOutbound = {
|
|
|
171
172
|
const uploadService = new XYFileUploadService(config.fileUploadUrl, config.apiKey, config.uid);
|
|
172
173
|
// Validate mediaUrl
|
|
173
174
|
if (!mediaUrl) {
|
|
175
|
+
logger.error("mediaUrl is required for sendMedia");
|
|
174
176
|
throw new Error("mediaUrl is required for sendMedia");
|
|
175
177
|
}
|
|
176
178
|
// Upload file
|
|
177
179
|
const fileId = await uploadService.uploadFile(mediaUrl);
|
|
178
180
|
// Check if fileId is empty (should not happen if uploadFile throws on failure)
|
|
179
181
|
if (!fileId) {
|
|
182
|
+
logger.error(`File upload returned empty fileId for: ${mediaUrl}`);
|
|
180
183
|
throw new Error(`File upload returned empty fileId for: ${mediaUrl}`);
|
|
181
184
|
}
|
|
182
185
|
logger.log(`[xyOutbound.sendMedia] File uploaded:`, {
|
package/dist/src/provider.js
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
// models.providers.xiaoyiprovider.api = "openai-completions"
|
|
9
9
|
// models.providers.xiaoyiprovider.models = [...]
|
|
10
10
|
import { createHash } from "crypto";
|
|
11
|
+
import { logger } from "./utils/logger.js";
|
|
11
12
|
import { getCurrentSessionContext } from "./tools/session-manager.js";
|
|
12
|
-
import { getCurrentTaskId } from "./task-manager.js";
|
|
13
13
|
import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
|
|
14
14
|
// ── Retry config ──────────────────────────────────────────────
|
|
15
15
|
const RETRY_DELAYS_MS = [10_000, 20_000, 40_000, 60_000, 60_000];
|
|
@@ -127,7 +127,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
127
127
|
if (!hasContent && !isContent) {
|
|
128
128
|
// ── Buffer phase (no content yet) ──
|
|
129
129
|
if (event.type === "done") {
|
|
130
|
-
|
|
130
|
+
logger.log(`[xiaoyiprovider] stream completed (no content), usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
|
|
131
131
|
for (const b of buffer)
|
|
132
132
|
yield b;
|
|
133
133
|
resultResolve(event.message);
|
|
@@ -142,7 +142,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
142
142
|
else {
|
|
143
143
|
// ── Streaming phase ──
|
|
144
144
|
if (!hasContent) {
|
|
145
|
-
|
|
145
|
+
logger.log("[xiaoyiprovider] first content event received, switching to streaming mode");
|
|
146
146
|
hasContent = true;
|
|
147
147
|
for (const b of buffer)
|
|
148
148
|
yield b;
|
|
@@ -151,13 +151,13 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
151
151
|
// The SDK calls result() when it sees done/error — if we yield first, the generator
|
|
152
152
|
// suspends and can never reach resolve, causing a permanent deadlock.
|
|
153
153
|
if (event.type === "done") {
|
|
154
|
-
|
|
154
|
+
logger.log(`[xiaoyiprovider] stream completed, usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
|
|
155
155
|
resultResolve(event.message);
|
|
156
156
|
yield event;
|
|
157
157
|
return;
|
|
158
158
|
}
|
|
159
159
|
if (event.type === "error") {
|
|
160
|
-
|
|
160
|
+
logger.log(`[xiaoyiprovider] stream error after content: ${event.error?.errorMessage}`);
|
|
161
161
|
errorResult = event.error;
|
|
162
162
|
break; // break inner loop, proceed to retry decision
|
|
163
163
|
}
|
|
@@ -168,15 +168,15 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
168
168
|
if (errorResult?.stopReason === "error" && isRetryableProviderError(errorResult.errorMessage)) {
|
|
169
169
|
if (attempt < MAX_RETRY_ATTEMPTS - 1) {
|
|
170
170
|
const delayMs = getRetryDelayMs(attempt + 1, cronJob);
|
|
171
|
-
|
|
171
|
+
logger.log(`[xiaoyiprovider] retryable error (attempt ${attempt + 1}/${MAX_RETRY_ATTEMPTS}): ` +
|
|
172
172
|
`${errorResult.errorMessage} — retrying in ${delayMs}ms`);
|
|
173
173
|
await sleep(delayMs);
|
|
174
174
|
continue; // discard buffer, retry with a new stream
|
|
175
175
|
}
|
|
176
|
-
|
|
176
|
+
logger.log(`[xiaoyiprovider] all ${MAX_RETRY_ATTEMPTS} retries exhausted, surfacing last error`);
|
|
177
177
|
}
|
|
178
178
|
else if (errorResult) {
|
|
179
|
-
|
|
179
|
+
logger.log(`[xiaoyiprovider] non-retryable error: ${errorResult.errorMessage}`);
|
|
180
180
|
}
|
|
181
181
|
// Non-retryable or retries exhausted — yield buffered events.
|
|
182
182
|
// Resolve before yielding the terminal event to avoid the same deadlock.
|
|
@@ -196,7 +196,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
196
196
|
return;
|
|
197
197
|
}
|
|
198
198
|
// Safety: final fallback attempt
|
|
199
|
-
|
|
199
|
+
logger.log("[xiaoyiprovider] entering final fallback attempt");
|
|
200
200
|
const lastStream = await createStream();
|
|
201
201
|
for await (const event of lastStream) {
|
|
202
202
|
if (event.type === "done") {
|
|
@@ -389,6 +389,22 @@ function trimUserMetadata(text) {
|
|
|
389
389
|
text = text.replace(/\n*Sender \(untrusted metadata\):\n```json\n[\s\S]*?\n```\n*/, "\n");
|
|
390
390
|
return text.replace(/\n{3,}/g, "\n\n");
|
|
391
391
|
}
|
|
392
|
+
/**
|
|
393
|
+
* Extract A2A taskId and deviceType from Conversation info JSON.
|
|
394
|
+
* bot.ts stores them as MessageSid = "taskId_deviceType".
|
|
395
|
+
*/
|
|
396
|
+
function extractA2AFromConversationInfo(text) {
|
|
397
|
+
const match = text.match(/Conversation info \(untrusted metadata\):\n```json\n([\s\S]*?)\n```/);
|
|
398
|
+
if (!match)
|
|
399
|
+
return null;
|
|
400
|
+
const msgIdMatch = match[1].match(/"message_id"\s*:\s*"([^"]+)"/);
|
|
401
|
+
if (!msgIdMatch)
|
|
402
|
+
return null;
|
|
403
|
+
const parts = msgIdMatch[1].split("_");
|
|
404
|
+
if (parts.length < 2)
|
|
405
|
+
return null;
|
|
406
|
+
return { taskId: parts[0], deviceType: parts[1] };
|
|
407
|
+
}
|
|
392
408
|
export const xiaoyiProvider = {
|
|
393
409
|
id: "xiaoyiprovider",
|
|
394
410
|
label: "Xiaoyi Provider",
|
|
@@ -439,21 +455,38 @@ export const xiaoyiProvider = {
|
|
|
439
455
|
* since the default agent timeout is 48 hours).
|
|
440
456
|
*/
|
|
441
457
|
wrapStreamFn: (ctx) => {
|
|
442
|
-
|
|
458
|
+
logger.log("[xiaoyiprovider] wrapStreamFn CALLED — provider resolved by openclaw");
|
|
443
459
|
const underlying = ctx.streamFn;
|
|
444
460
|
if (!underlying)
|
|
445
461
|
return underlying;
|
|
446
|
-
// Capture A2A sessionId at agent setup time for multi-session isolation.
|
|
447
|
-
// openclaw calls wrapStreamFn per-agent (per session), so this runs inside
|
|
448
|
-
// the correct runWithSessionContext() ALS scope. When multiple sessions are
|
|
449
|
-
// active concurrently, getCurrentSessionContext() may later return the WRONG
|
|
450
|
-
// session (lastRegisteredKey fallback). The captured sessionId lets us
|
|
451
|
-
// bypass that fallback and look up the correct taskId directly from
|
|
452
|
-
// task-manager.
|
|
453
|
-
const capturedA2ASessionId = getCurrentSessionContext()?.sessionId ?? null;
|
|
454
462
|
return async (model, context, options) => {
|
|
455
|
-
// 每次请求时从 ctx.extraParams 动态读取 header
|
|
456
463
|
const dynamicHeaders = {};
|
|
464
|
+
// ── Extract A2A taskId/deviceType from Conversation info ──
|
|
465
|
+
// bot.ts stores taskId_deviceType as MessageSid, which the framework
|
|
466
|
+
// renders as message_id in the Conversation info JSON block.
|
|
467
|
+
let extractedTaskId = null;
|
|
468
|
+
let extractedDeviceType = null;
|
|
469
|
+
if (context.messages) {
|
|
470
|
+
for (let i = context.messages.length - 1; i >= 0; i--) {
|
|
471
|
+
const msg = context.messages[i];
|
|
472
|
+
if (msg.role !== "user")
|
|
473
|
+
continue;
|
|
474
|
+
const text = typeof msg.content === "string"
|
|
475
|
+
? msg.content
|
|
476
|
+
: Array.isArray(msg.content)
|
|
477
|
+
? msg.content.find((b) => b.type === "text")?.text ?? ""
|
|
478
|
+
: "";
|
|
479
|
+
if (!text)
|
|
480
|
+
continue;
|
|
481
|
+
const extracted = extractA2AFromConversationInfo(text);
|
|
482
|
+
if (extracted) {
|
|
483
|
+
extractedTaskId = extracted.taskId;
|
|
484
|
+
extractedDeviceType = extracted.deviceType;
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
// ── Build dynamic headers ────────────────────────────
|
|
457
490
|
if (ctx.extraParams) {
|
|
458
491
|
const fallbackPrefix = ctx.extraParams[FALLBACK_PREFIX_KEY];
|
|
459
492
|
if (typeof fallbackPrefix === "string") {
|
|
@@ -471,40 +504,30 @@ export const xiaoyiProvider = {
|
|
|
471
504
|
dynamicHeaders["x-cron-flag"] = "begin";
|
|
472
505
|
}
|
|
473
506
|
}
|
|
474
|
-
else {
|
|
475
|
-
// Session mode:
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
}
|
|
488
|
-
if (!resolvedTaskId) {
|
|
489
|
-
resolvedTaskId = getCurrentSessionContext()?.taskId ?? null;
|
|
490
|
-
}
|
|
491
|
-
const traceId = resolvedTaskId ?? ctx.extraParams[HEADER_TRACE_ID];
|
|
492
|
-
const sessionId = resolvedTaskId?.split("&")[0]
|
|
493
|
-
?? ctx.extraParams[HEADER_SESSION_ID];
|
|
494
|
-
const interactionId = resolvedTaskId?.split("&")[1]
|
|
495
|
-
?? ctx.extraParams[HEADER_INTERACTION_ID]
|
|
496
|
-
?? "";
|
|
497
|
-
if (typeof traceId === "string") {
|
|
498
|
-
const isCron = isCronTriggered(context.messages);
|
|
499
|
-
dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
|
|
500
|
-
if (isCron) {
|
|
501
|
-
const cronTitle = extractCronTitle(context.messages);
|
|
502
|
-
if (cronTitle)
|
|
503
|
-
dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
|
|
504
|
-
if (context.messages?.length === 1)
|
|
505
|
-
dynamicHeaders["x-cron-flag"] = "begin";
|
|
506
|
-
}
|
|
507
|
+
else if (extractedTaskId) {
|
|
508
|
+
// Session mode: taskId extracted from Conversation info
|
|
509
|
+
const traceId = extractedTaskId;
|
|
510
|
+
const sessionId = traceId.split("&")[0];
|
|
511
|
+
const interactionId = traceId.split("&")[1] ?? "";
|
|
512
|
+
const isCron = isCronTriggered(context.messages);
|
|
513
|
+
dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
|
|
514
|
+
if (isCron) {
|
|
515
|
+
const cronTitle = extractCronTitle(context.messages);
|
|
516
|
+
if (cronTitle)
|
|
517
|
+
dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
|
|
518
|
+
if (context.messages?.length === 1)
|
|
519
|
+
dynamicHeaders["x-cron-flag"] = "begin";
|
|
507
520
|
}
|
|
521
|
+
dynamicHeaders[HEADER_SESSION_ID] = sessionId;
|
|
522
|
+
dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
// Fallback: use extraParams cached values
|
|
526
|
+
const traceId = ctx.extraParams[HEADER_TRACE_ID];
|
|
527
|
+
const sessionId = ctx.extraParams[HEADER_SESSION_ID];
|
|
528
|
+
const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
|
|
529
|
+
if (typeof traceId === "string")
|
|
530
|
+
dynamicHeaders[HEADER_TRACE_ID] = traceId;
|
|
508
531
|
if (typeof sessionId === "string")
|
|
509
532
|
dynamicHeaders[HEADER_SESSION_ID] = sessionId;
|
|
510
533
|
if (typeof interactionId === "string")
|
|
@@ -512,17 +535,15 @@ export const xiaoyiProvider = {
|
|
|
512
535
|
}
|
|
513
536
|
}
|
|
514
537
|
// 记录输入
|
|
515
|
-
|
|
538
|
+
logger.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
|
|
516
539
|
if (context.systemPrompt) {
|
|
517
|
-
|
|
540
|
+
logger.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
|
|
518
541
|
}
|
|
519
|
-
//
|
|
520
|
-
//
|
|
521
|
-
// resolvePreparedExtraParams by provider/modelId – the cache key does
|
|
522
|
-
// not include session-specific data, so deviceType may be missing
|
|
523
|
-
// from the cached extraParams even when a session is active.
|
|
542
|
+
// deviceType: prefer value extracted from Conversation info,
|
|
543
|
+
// then extraParams, then ALS fallback.
|
|
524
544
|
const extraParamsDeviceType = ctx.extraParams?.[DEVICE_TYPE_KEY] || undefined;
|
|
525
|
-
const deviceType =
|
|
545
|
+
const deviceType = (extractedDeviceType || extraParamsDeviceType)
|
|
546
|
+
?? getCurrentSessionContext()?.deviceType;
|
|
526
547
|
// 在发送给模型前,优化 systemPrompt 结构
|
|
527
548
|
if (context.systemPrompt) {
|
|
528
549
|
let sp = context.systemPrompt;
|
|
@@ -549,13 +570,13 @@ export const xiaoyiProvider = {
|
|
|
549
570
|
sp = sp.replace('## Runtime', combined + '\n\n## Runtime');
|
|
550
571
|
}
|
|
551
572
|
}
|
|
552
|
-
|
|
573
|
+
logger.log(`[xiaoyiprovider] system prompt optimized: ${beforeLen} -> ${sp.length}`);
|
|
553
574
|
context.systemPrompt = sp;
|
|
554
575
|
}
|
|
555
576
|
const selfEvolutionEnabled = await selfEvolutionManager.isEnabled();
|
|
556
|
-
|
|
577
|
+
logger.log(`[selfEvolution] selfEvolution flag: ${selfEvolutionEnabled}`);
|
|
557
578
|
context.systemPrompt = applySelfEvolutionPrompt(context.systemPrompt, selfEvolutionEnabled);
|
|
558
|
-
// Append device context to systemPrompt
|
|
579
|
+
// Append device context to systemPrompt
|
|
559
580
|
if (deviceType) {
|
|
560
581
|
const displayDevice = (deviceType === "2in1") ? "鸿蒙PC" : deviceType;
|
|
561
582
|
const deviceSection = `\n\n## Current User Device Context\nThe current user is using the following device: ${displayDevice}\nYou need to be aware of the user's current device and provide guidance accordingly. If the response involves device-related tools or actions, you must tailor the reply based on the user's current device, using device-specific references such as "saved to the Notes/Calendar on your {deviceType}.\n"`;
|
|
@@ -581,7 +602,7 @@ export const xiaoyiProvider = {
|
|
|
581
602
|
// ── Retry-capable streaming ──────────────────────────────
|
|
582
603
|
const cronJob = isCronTriggered(context.messages);
|
|
583
604
|
if (cronJob)
|
|
584
|
-
|
|
605
|
+
logger.log("[xiaoyiprovider] detected cron-triggered request, using extended retry delays");
|
|
585
606
|
const makeStream = () => underlying(model, context, {
|
|
586
607
|
...options,
|
|
587
608
|
headers: {
|