@ynhcj/xiaoyi-channel 0.0.129-beta → 0.0.129-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/index.js +36 -7
- package/dist/src/bot.d.ts +8 -0
- package/dist/src/bot.js +151 -139
- package/dist/src/client.d.ts +1 -5
- package/dist/src/client.js +25 -39
- package/dist/src/cspl/call-api.d.ts +6 -0
- package/dist/src/cspl/call-api.js +33 -13
- package/dist/src/cspl/config.d.ts +11 -1
- package/dist/src/cspl/config.js +30 -0
- package/dist/src/cspl/middleware.d.ts +8 -0
- package/dist/src/cspl/middleware.js +90 -0
- package/dist/src/cspl/steer-context.d.ts +21 -0
- package/dist/src/cspl/steer-context.js +78 -0
- 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 +13 -10
- package/dist/src/message-queue.js +2 -1
- package/dist/src/monitor.js +82 -48
- package/dist/src/outbound.js +3 -0
- package/dist/src/provider.js +82 -34
- package/dist/src/push.js +9 -9
- package/dist/src/reply-dispatcher.d.ts +3 -1
- package/dist/src/reply-dispatcher.js +61 -68
- package/dist/src/self-evolution-handler.js +11 -14
- package/dist/src/skill-retriever/hooks.js +0 -1
- package/dist/src/skill-retriever/tool-search.js +7 -12
- package/dist/src/task-manager.d.ts +4 -27
- package/dist/src/task-manager.js +13 -78
- package/dist/src/tools/calendar-tool.js +5 -1
- package/dist/src/tools/call-phone-tool.js +5 -1
- package/dist/src/tools/create-alarm-tool.js +5 -1
- package/dist/src/tools/delete-alarm-tool.js +5 -1
- package/dist/src/tools/image-reading-tool.d.ts +1 -1
- package/dist/src/tools/image-reading-tool.js +38 -114
- package/dist/src/tools/location-tool.js +5 -1
- package/dist/src/tools/login-token-tool.js +13 -2
- package/dist/src/tools/modify-alarm-tool.js +5 -1
- package/dist/src/tools/modify-note-tool.js +5 -1
- package/dist/src/tools/note-tool.js +5 -1
- package/dist/src/tools/query-app-message-tool.js +5 -1
- package/dist/src/tools/query-memory-data-tool.js +5 -1
- package/dist/src/tools/query-todo-task-tool.js +5 -1
- package/dist/src/tools/save-file-to-phone-tool.js +5 -1
- package/dist/src/tools/save-media-to-gallery-tool.js +5 -1
- package/dist/src/tools/search-alarm-tool.js +5 -1
- package/dist/src/tools/search-calendar-tool.js +5 -1
- package/dist/src/tools/search-contact-tool.js +5 -1
- package/dist/src/tools/search-email-tool.js +5 -1
- package/dist/src/tools/search-file-tool.js +5 -1
- package/dist/src/tools/search-message-tool.js +5 -1
- package/dist/src/tools/search-note-tool.js +5 -1
- package/dist/src/tools/search-photo-gallery-tool.js +5 -1
- package/dist/src/tools/send-email-tool.js +5 -1
- package/dist/src/tools/send-file-to-user-tool.js +0 -1
- package/dist/src/tools/send-message-tool.js +5 -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 +3 -15
- package/dist/src/tools/upload-file-tool.js +5 -1
- package/dist/src/tools/upload-photo-tool.js +5 -1
- package/dist/src/tools/xiaoyi-add-collection-tool.js +5 -1
- package/dist/src/tools/xiaoyi-collection-tool.js +5 -1
- package/dist/src/tools/xiaoyi-delete-collection-tool.js +5 -1
- package/dist/src/tools/xiaoyi-gui-tool.js +3 -1
- 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/openclaw.plugin.json +3 -0
- package/package.json +6 -5
|
@@ -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,15 @@ 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;
|
|
17
|
+
const message = context.event?.payload?.message ?? "";
|
|
18
|
+
const code = context.event?.payload?.code ?? "";
|
|
18
19
|
if (!clientId || typeof clientId !== "string") {
|
|
19
|
-
error("[LOGIN_TOKEN_HANDLER] invalid payload: missing clientId");
|
|
20
|
+
logger.error("[LOGIN_TOKEN_HANDLER] invalid payload: missing clientId");
|
|
20
21
|
return;
|
|
21
22
|
}
|
|
22
|
-
log(`[LOGIN_TOKEN_HANDLER] received login token event, clientId=${clientId}`);
|
|
23
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] received login token event, clientId=${clientId}, code=${code}`);
|
|
23
24
|
// Ensure directory exists
|
|
24
25
|
const dir = dirname(TOKEN_FILE_PATH);
|
|
25
26
|
if (!existsSync(dir)) {
|
|
@@ -42,19 +43,21 @@ export function handleLoginTokenEvent(context, runtime) {
|
|
|
42
43
|
const now = String(Date.now());
|
|
43
44
|
const existing = tokens.find((t) => t.clientId === clientId);
|
|
44
45
|
if (existing) {
|
|
45
|
-
// Update timestamp
|
|
46
|
+
// Update timestamp, message, code
|
|
46
47
|
existing.timestamp = now;
|
|
47
|
-
|
|
48
|
+
existing.message = message;
|
|
49
|
+
existing.code = code;
|
|
50
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] updated entry for clientId=${clientId}`);
|
|
48
51
|
}
|
|
49
52
|
else {
|
|
50
53
|
// Insert new entry
|
|
51
|
-
tokens.push({ clientId, timestamp: now });
|
|
52
|
-
log(`[LOGIN_TOKEN_HANDLER] inserted new entry for clientId=${clientId}`);
|
|
54
|
+
tokens.push({ clientId, timestamp: now, message, code });
|
|
55
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] inserted new entry for clientId=${clientId}`);
|
|
53
56
|
}
|
|
54
57
|
writeFileSync(TOKEN_FILE_PATH, JSON.stringify(tokens, null, 2), "utf-8");
|
|
55
|
-
log(`[LOGIN_TOKEN_HANDLER] wrote token file: ${TOKEN_FILE_PATH}`);
|
|
58
|
+
logger.log(`[LOGIN_TOKEN_HANDLER] wrote token file: ${TOKEN_FILE_PATH}`);
|
|
56
59
|
}
|
|
57
60
|
catch (err) {
|
|
58
|
-
error("[LOGIN_TOKEN_HANDLER] failed to handle event:", err);
|
|
61
|
+
logger.error("[LOGIN_TOKEN_HANDLER] failed to handle event:", err);
|
|
59
62
|
}
|
|
60
63
|
}
|
|
@@ -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.
|
|
@@ -28,6 +29,27 @@ function createSessionQueue() {
|
|
|
28
29
|
return next;
|
|
29
30
|
};
|
|
30
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Per-session serial queue for steer messages only.
|
|
34
|
+
* Steer messages must run concurrently with the main query (which may block for
|
|
35
|
+
* minutes inside the Pi agent loop), but must be serialized among themselves to
|
|
36
|
+
* prevent concurrent dispatchReplyFromConfig calls that can drop mid-stream
|
|
37
|
+
* steer messages under race conditions.
|
|
38
|
+
*/
|
|
39
|
+
function createSteerQueue() {
|
|
40
|
+
const queues = new Map();
|
|
41
|
+
return (sessionId, task) => {
|
|
42
|
+
const prev = queues.get(sessionId) ?? Promise.resolve();
|
|
43
|
+
const next = prev.then(task, task);
|
|
44
|
+
queues.set(sessionId, next);
|
|
45
|
+
void next.finally(() => {
|
|
46
|
+
if (queues.get(sessionId) === next) {
|
|
47
|
+
queues.delete(sessionId);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
return next;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
31
53
|
/**
|
|
32
54
|
* Monitor XY channel WebSocket connections.
|
|
33
55
|
* Keeps the connection alive until abortSignal is triggered.
|
|
@@ -38,8 +60,6 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
38
60
|
throw new Error("Config is required for XY monitor");
|
|
39
61
|
}
|
|
40
62
|
const runtime = opts.runtime;
|
|
41
|
-
const log = runtime?.log ?? console.log;
|
|
42
|
-
const error = runtime?.error ?? console.error;
|
|
43
63
|
const account = resolveXYConfig(cfg);
|
|
44
64
|
if (!account.enabled) {
|
|
45
65
|
throw new Error(`XY account is disabled`);
|
|
@@ -51,13 +71,11 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
51
71
|
opts.setStatus({ lastEventAt: Date.now(), lastInboundAt: Date.now() });
|
|
52
72
|
}
|
|
53
73
|
: undefined;
|
|
54
|
-
// ✅ Set runtime for WebSocket manager logging before creating/getting manager
|
|
55
|
-
setClientRuntime(runtime);
|
|
56
74
|
// 🔍 Diagnose WebSocket managers before gateway start
|
|
57
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
|
|
75
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before gateway start...");
|
|
58
76
|
diagnoseAllManagers();
|
|
59
77
|
// Get WebSocket manager (cached)
|
|
60
|
-
const wsManager = getXYWebSocketManager(account);
|
|
78
|
+
const wsManager = getXYWebSocketManager(account, runtime);
|
|
61
79
|
// ✅ Set health event callback for heartbeat reporting
|
|
62
80
|
if (trackEvent) {
|
|
63
81
|
wsManager.setHealthEventCallback(trackEvent);
|
|
@@ -68,21 +86,35 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
68
86
|
const activeMessages = new Set();
|
|
69
87
|
// Create session queue for ordered message processing
|
|
70
88
|
const enqueue = createSessionQueue();
|
|
89
|
+
// Steer-only serial queue: keeps steer messages concurrent with the main
|
|
90
|
+
// query but serialized among themselves to avoid race conditions.
|
|
91
|
+
const enqueueSteer = createSteerQueue();
|
|
92
|
+
// Global gate that serializes dispatch initialization across sessions.
|
|
93
|
+
// When a new session starts dispatching, it acquires this gate and holds it
|
|
94
|
+
// until agent setup (agentTools + wrapStreamFn) is complete, then releases it.
|
|
95
|
+
// This prevents lastRegisteredKey races when multiple sessions initialize
|
|
96
|
+
// concurrently.
|
|
97
|
+
let globalDispatchInitGate = Promise.resolve();
|
|
71
98
|
// Health check interval
|
|
72
99
|
let healthCheckInterval = null;
|
|
73
100
|
return new Promise((resolve, reject) => {
|
|
74
101
|
// Event handlers (defined early so they can be referenced in cleanup)
|
|
75
102
|
const messageHandler = (message, sessionId, serverId) => {
|
|
76
103
|
const messageKey = `${sessionId}::${message.id}`;
|
|
77
|
-
log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
|
|
104
|
+
logger.log(`[MONITOR-HANDLER] ####### messageHandler triggered: sessionId=${sessionId}, messageId=${message.id} #######`);
|
|
78
105
|
// ✅ Report health: received a message
|
|
79
106
|
trackEvent?.();
|
|
80
107
|
// Check for duplicate message handling
|
|
81
108
|
if (activeMessages.has(messageKey)) {
|
|
82
|
-
error(`[MONITOR-HANDLER] ⚠️ WARNING: Duplicate message detected! messageKey=${messageKey}, this may cause duplicate dispatchers!`);
|
|
109
|
+
logger.error(`[MONITOR-HANDLER] ⚠️ WARNING: Duplicate message detected! messageKey=${messageKey}, this may cause duplicate dispatchers!`);
|
|
83
110
|
}
|
|
84
111
|
activeMessages.add(messageKey);
|
|
85
112
|
const task = async () => {
|
|
113
|
+
// Wait for the previous session's init to complete (global gate),
|
|
114
|
+
// then acquire the gate for this session's init.
|
|
115
|
+
await globalDispatchInitGate;
|
|
116
|
+
let releaseGate;
|
|
117
|
+
globalDispatchInitGate = new Promise((r) => { releaseGate = r; });
|
|
86
118
|
try {
|
|
87
119
|
await handleXYMessage({
|
|
88
120
|
cfg,
|
|
@@ -90,11 +122,13 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
90
122
|
message,
|
|
91
123
|
accountId, // ✅ Pass accountId ("default")
|
|
92
124
|
webSocketSessionId: sessionId, // ✅ 传递 WebSocket 层级的 sessionId
|
|
125
|
+
onInitComplete: () => releaseGate(),
|
|
93
126
|
});
|
|
94
127
|
}
|
|
95
128
|
catch (err) {
|
|
96
129
|
// ✅ Only log error, don't re-throw to prevent gateway restart
|
|
97
|
-
|
|
130
|
+
releaseGate();
|
|
131
|
+
logger.error(`XY gateway: error handling message from ${serverId}: ${String(err)}`);
|
|
98
132
|
}
|
|
99
133
|
finally {
|
|
100
134
|
// Remove from active messages when done
|
|
@@ -108,34 +142,35 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
108
142
|
const steerMode = cfg.messages?.queue?.mode === "steer";
|
|
109
143
|
const hasActiveRun = hasActiveTask(parsed.sessionId);
|
|
110
144
|
if (steerMode && hasActiveRun) {
|
|
111
|
-
// Steer
|
|
112
|
-
|
|
113
|
-
log(`[MONITOR-HANDLER]
|
|
114
|
-
|
|
115
|
-
|
|
145
|
+
// Steer模式且有活跃任务:通过 steer 专用队列串行执行,与主消息并发但
|
|
146
|
+
// 避免多个 steer 同时进入 dispatchReplyFromConfig 导致中间消息丢失
|
|
147
|
+
logger.log(`[MONITOR-HANDLER] 🔄 STEER MODE: Enqueuing steer for messageKey=${messageKey}`);
|
|
148
|
+
logger.log(`[MONITOR-HANDLER] - sessionId: ${parsed.sessionId}`);
|
|
149
|
+
void enqueueSteer(parsed.sessionId, task).catch((err) => {
|
|
150
|
+
logger.error(`XY gateway: steer queue processing failed for ${messageKey}: ${String(err)}`);
|
|
116
151
|
activeMessages.delete(messageKey);
|
|
117
152
|
});
|
|
118
153
|
}
|
|
119
154
|
else {
|
|
120
155
|
// 正常模式:入队列串行执行
|
|
121
156
|
void enqueue(sessionId, task).catch((err) => {
|
|
122
|
-
error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
157
|
+
logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
123
158
|
activeMessages.delete(messageKey);
|
|
124
159
|
});
|
|
125
160
|
}
|
|
126
161
|
}
|
|
127
162
|
catch (parseErr) {
|
|
128
163
|
// 解析失败,回退到正常队列模式
|
|
129
|
-
error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
|
|
164
|
+
logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
|
|
130
165
|
void enqueue(sessionId, task).catch((err) => {
|
|
131
|
-
error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
166
|
+
logger.error(`XY gateway: queue processing failed for session ${sessionId}: ${String(err)}`);
|
|
132
167
|
activeMessages.delete(messageKey);
|
|
133
168
|
});
|
|
134
169
|
}
|
|
135
170
|
};
|
|
136
171
|
const connectedHandler = (serverId) => {
|
|
137
172
|
if (!loggedServers.has(serverId)) {
|
|
138
|
-
log(`XY gateway: ${serverId} connected`);
|
|
173
|
+
logger.log(`XY gateway: ${serverId} connected`);
|
|
139
174
|
loggedServers.add(serverId);
|
|
140
175
|
}
|
|
141
176
|
// ✅ Report health: connection established
|
|
@@ -143,7 +178,7 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
143
178
|
opts.setStatus?.({ connected: true });
|
|
144
179
|
};
|
|
145
180
|
const disconnectedHandler = (serverId) => {
|
|
146
|
-
log(`XY gateway: ${serverId} disconnected`);
|
|
181
|
+
logger.log(`XY gateway: ${serverId} disconnected`);
|
|
147
182
|
loggedServers.delete(serverId);
|
|
148
183
|
// ✅ Report disconnection status (only if all servers disconnected)
|
|
149
184
|
if (loggedServers.size === 0) {
|
|
@@ -151,41 +186,41 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
151
186
|
}
|
|
152
187
|
};
|
|
153
188
|
const errorHandler = (err, serverId) => {
|
|
154
|
-
error(`XY gateway: ${serverId} error: ${String(err)}`);
|
|
189
|
+
logger.error(`XY gateway: ${serverId} error: ${String(err)}`);
|
|
155
190
|
};
|
|
156
191
|
const triggerEventHandler = (context) => {
|
|
157
|
-
log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
|
|
158
|
-
log(`[MONITOR] - sessionId: ${context.sessionId}`);
|
|
159
|
-
log(`[MONITOR] - taskId: ${context.taskId}`);
|
|
192
|
+
logger.log(`[MONITOR] 📌 Received trigger-event, dispatching to handler...`);
|
|
193
|
+
logger.log(`[MONITOR] - sessionId: ${context.sessionId}`);
|
|
194
|
+
logger.log(`[MONITOR] - taskId: ${context.taskId}`);
|
|
160
195
|
// 异步处理 Trigger 事件,不阻塞主流程
|
|
161
196
|
handleTriggerEvent(context, cfg, runtime, accountId).catch((err) => {
|
|
162
|
-
error(`[MONITOR] Failed to handle trigger-event:`, err);
|
|
197
|
+
logger.error(`[MONITOR] Failed to handle trigger-event:`, err);
|
|
163
198
|
});
|
|
164
199
|
};
|
|
165
200
|
const selfEvolutionHandler = (context) => {
|
|
166
|
-
log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
|
|
201
|
+
logger.log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
|
|
167
202
|
handleSelfEvolutionEvent(context, runtime);
|
|
168
203
|
};
|
|
169
204
|
const selfEvolutionStateGetHandler = (context) => {
|
|
170
|
-
log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
|
|
205
|
+
logger.log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
|
|
171
206
|
handleSelfEvolutionStateGetEvent(context, account, runtime, wsManager).catch((err) => {
|
|
172
|
-
error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
|
|
207
|
+
logger.error(`[MONITOR] Failed to handle self-evolution-state-get-event:`, err);
|
|
173
208
|
});
|
|
174
209
|
};
|
|
175
210
|
const loginTokenEventHandler = (context) => {
|
|
176
|
-
log(`[MONITOR] Received login-token-event, dispatching to handler...`);
|
|
211
|
+
logger.log(`[MONITOR] Received login-token-event, dispatching to handler...`);
|
|
177
212
|
handleLoginTokenEvent(context, runtime);
|
|
178
213
|
};
|
|
179
214
|
const cleanup = () => {
|
|
180
|
-
log("XY gateway: cleaning up...");
|
|
215
|
+
logger.log("XY gateway: cleaning up...");
|
|
181
216
|
// 🔍 Diagnose before cleanup
|
|
182
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
|
|
217
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers before cleanup...");
|
|
183
218
|
diagnoseAllManagers();
|
|
184
219
|
// Stop health check interval
|
|
185
220
|
if (healthCheckInterval) {
|
|
186
221
|
clearInterval(healthCheckInterval);
|
|
187
222
|
healthCheckInterval = null;
|
|
188
|
-
log("⏸️ Stopped periodic health check");
|
|
223
|
+
logger.log("⏸️ Stopped periodic health check");
|
|
189
224
|
}
|
|
190
225
|
// Remove event handlers to prevent duplicate calls on gateway restart
|
|
191
226
|
wsManager.off("message", messageHandler);
|
|
@@ -205,20 +240,20 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
205
240
|
cleanupAllSessions();
|
|
206
241
|
loggedServers.clear();
|
|
207
242
|
activeMessages.clear();
|
|
208
|
-
log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
|
|
243
|
+
logger.log(`[MONITOR-HANDLER] 🧹 Cleanup complete, cleared active messages and sessions`);
|
|
209
244
|
// 🔍 Diagnose after cleanup
|
|
210
|
-
log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
|
|
245
|
+
logger.log("🔍 [DIAGNOSTICS] Checking WebSocket managers after cleanup...");
|
|
211
246
|
diagnoseAllManagers();
|
|
212
247
|
};
|
|
213
248
|
const handleAbort = async () => {
|
|
214
|
-
log("XY gateway: abort signal received, sending notifications before stopping");
|
|
249
|
+
logger.log("XY gateway: abort signal received, sending notifications before stopping");
|
|
215
250
|
// 📤 Send restart notification to all active sessions before disconnecting
|
|
216
251
|
try {
|
|
217
252
|
const activeBindings = getAllActiveTaskBindings();
|
|
218
253
|
if (activeBindings.length > 0) {
|
|
219
254
|
const config = resolveXYConfig(cfg);
|
|
220
255
|
const notificationText = "Gateway即将重启,重启期间可能短暂出现\u201c环境异常\u201d提示,请稍候并耐心重试~";
|
|
221
|
-
log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
|
|
256
|
+
logger.log(`[MONITOR] 📤 Sending restart notifications to ${activeBindings.length} active session(s)`);
|
|
222
257
|
const sendPromises = activeBindings.map(binding => sendA2AResponse({
|
|
223
258
|
config,
|
|
224
259
|
sessionId: binding.sessionId,
|
|
@@ -227,22 +262,21 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
227
262
|
text: notificationText,
|
|
228
263
|
append: false,
|
|
229
264
|
final: true,
|
|
230
|
-
runtime,
|
|
231
265
|
}).catch(err => {
|
|
232
|
-
error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
|
|
266
|
+
logger.error(`[MONITOR] Failed to send restart notification to session ${binding.sessionId}: ${String(err)}`);
|
|
233
267
|
}));
|
|
234
268
|
await Promise.all(sendPromises);
|
|
235
|
-
log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
|
|
269
|
+
logger.log(`[MONITOR] ✅ Restart notifications sent to ${activeBindings.length} session(s)`);
|
|
236
270
|
}
|
|
237
271
|
else {
|
|
238
|
-
log(`[MONITOR] No active sessions, skipping restart notifications`);
|
|
272
|
+
logger.log(`[MONITOR] No active sessions, skipping restart notifications`);
|
|
239
273
|
}
|
|
240
274
|
}
|
|
241
275
|
catch (err) {
|
|
242
|
-
error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
|
|
276
|
+
logger.error(`[MONITOR] Error sending restart notifications: ${String(err)}`);
|
|
243
277
|
}
|
|
244
278
|
cleanup();
|
|
245
|
-
log("XY gateway stopped");
|
|
279
|
+
logger.log("XY gateway stopped");
|
|
246
280
|
resolve();
|
|
247
281
|
};
|
|
248
282
|
if (opts.abortSignal?.aborted) {
|
|
@@ -261,20 +295,20 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
261
295
|
wsManager.on("self-evolution-state-get-event", selfEvolutionStateGetHandler);
|
|
262
296
|
wsManager.on("login-token-event", loginTokenEventHandler);
|
|
263
297
|
// Start periodic health check (every 6 hours)
|
|
264
|
-
log("🏥 Starting periodic health check (every 6 hours)...");
|
|
298
|
+
logger.log("🏥 Starting periodic health check (every 6 hours)...");
|
|
265
299
|
healthCheckInterval = setInterval(() => {
|
|
266
|
-
log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
|
|
300
|
+
logger.log("🏥 [HEALTH CHECK] Periodic WebSocket diagnostics...");
|
|
267
301
|
diagnoseAllManagers();
|
|
268
302
|
// Auto-cleanup orphan connections
|
|
269
303
|
const cleaned = cleanupOrphanConnections();
|
|
270
304
|
if (cleaned > 0) {
|
|
271
|
-
log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
|
|
305
|
+
logger.log(`🧹 [HEALTH CHECK] Auto-cleaned ${cleaned} manager(s) with orphan connections`);
|
|
272
306
|
}
|
|
273
307
|
// Cleanup stale sessions (older than 10min TTL)
|
|
274
308
|
const cleanedSessions = cleanupStaleSessions();
|
|
275
309
|
const remainingSessions = getActiveSessionCount();
|
|
276
310
|
if (cleanedSessions > 0 || remainingSessions > 0) {
|
|
277
|
-
log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
|
|
311
|
+
logger.log(`🧹 [HEALTH CHECK] Sessions: cleaned=${cleanedSessions}, active=${remainingSessions}`);
|
|
278
312
|
}
|
|
279
313
|
// Cleanup stale temp files (older than 24 hours)
|
|
280
314
|
void cleanupStaleTempFiles();
|
|
@@ -282,11 +316,11 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
282
316
|
// Connect to WebSocket servers
|
|
283
317
|
wsManager.connect()
|
|
284
318
|
.then(() => {
|
|
285
|
-
log("XY gateway: started successfully");
|
|
319
|
+
logger.log("XY gateway: started successfully");
|
|
286
320
|
})
|
|
287
321
|
.catch((err) => {
|
|
288
322
|
// Connection failed but don't reject - continue monitoring for reconnection
|
|
289
|
-
error(`XY gateway: initial connection failed: ${String(err)}`);
|
|
323
|
+
logger.error(`XY gateway: initial connection failed: ${String(err)}`);
|
|
290
324
|
// Still resolve successfully so plugin starts
|
|
291
325
|
resolve();
|
|
292
326
|
});
|
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,6 +8,7 @@
|
|
|
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
13
|
import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
|
|
13
14
|
// ── Retry config ──────────────────────────────────────────────
|
|
@@ -126,7 +127,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
126
127
|
if (!hasContent && !isContent) {
|
|
127
128
|
// ── Buffer phase (no content yet) ──
|
|
128
129
|
if (event.type === "done") {
|
|
129
|
-
|
|
130
|
+
logger.log(`[xiaoyiprovider] stream completed (no content), usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
|
|
130
131
|
for (const b of buffer)
|
|
131
132
|
yield b;
|
|
132
133
|
resultResolve(event.message);
|
|
@@ -141,7 +142,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
141
142
|
else {
|
|
142
143
|
// ── Streaming phase ──
|
|
143
144
|
if (!hasContent) {
|
|
144
|
-
|
|
145
|
+
logger.log("[xiaoyiprovider] first content event received, switching to streaming mode");
|
|
145
146
|
hasContent = true;
|
|
146
147
|
for (const b of buffer)
|
|
147
148
|
yield b;
|
|
@@ -150,13 +151,13 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
150
151
|
// The SDK calls result() when it sees done/error — if we yield first, the generator
|
|
151
152
|
// suspends and can never reach resolve, causing a permanent deadlock.
|
|
152
153
|
if (event.type === "done") {
|
|
153
|
-
|
|
154
|
+
logger.log(`[xiaoyiprovider] stream completed, usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
|
|
154
155
|
resultResolve(event.message);
|
|
155
156
|
yield event;
|
|
156
157
|
return;
|
|
157
158
|
}
|
|
158
159
|
if (event.type === "error") {
|
|
159
|
-
|
|
160
|
+
logger.log(`[xiaoyiprovider] stream error after content: ${event.error?.errorMessage}`);
|
|
160
161
|
errorResult = event.error;
|
|
161
162
|
break; // break inner loop, proceed to retry decision
|
|
162
163
|
}
|
|
@@ -167,15 +168,15 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
167
168
|
if (errorResult?.stopReason === "error" && isRetryableProviderError(errorResult.errorMessage)) {
|
|
168
169
|
if (attempt < MAX_RETRY_ATTEMPTS - 1) {
|
|
169
170
|
const delayMs = getRetryDelayMs(attempt + 1, cronJob);
|
|
170
|
-
|
|
171
|
+
logger.log(`[xiaoyiprovider] retryable error (attempt ${attempt + 1}/${MAX_RETRY_ATTEMPTS}): ` +
|
|
171
172
|
`${errorResult.errorMessage} — retrying in ${delayMs}ms`);
|
|
172
173
|
await sleep(delayMs);
|
|
173
174
|
continue; // discard buffer, retry with a new stream
|
|
174
175
|
}
|
|
175
|
-
|
|
176
|
+
logger.log(`[xiaoyiprovider] all ${MAX_RETRY_ATTEMPTS} retries exhausted, surfacing last error`);
|
|
176
177
|
}
|
|
177
178
|
else if (errorResult) {
|
|
178
|
-
|
|
179
|
+
logger.log(`[xiaoyiprovider] non-retryable error: ${errorResult.errorMessage}`);
|
|
179
180
|
}
|
|
180
181
|
// Non-retryable or retries exhausted — yield buffered events.
|
|
181
182
|
// Resolve before yielding the terminal event to avoid the same deadlock.
|
|
@@ -195,7 +196,7 @@ function createRetryingStream(createStream, cronJob) {
|
|
|
195
196
|
return;
|
|
196
197
|
}
|
|
197
198
|
// Safety: final fallback attempt
|
|
198
|
-
|
|
199
|
+
logger.log("[xiaoyiprovider] entering final fallback attempt");
|
|
199
200
|
const lastStream = await createStream();
|
|
200
201
|
for await (const event of lastStream) {
|
|
201
202
|
if (event.type === "done") {
|
|
@@ -388,6 +389,22 @@ function trimUserMetadata(text) {
|
|
|
388
389
|
text = text.replace(/\n*Sender \(untrusted metadata\):\n```json\n[\s\S]*?\n```\n*/, "\n");
|
|
389
390
|
return text.replace(/\n{3,}/g, "\n\n");
|
|
390
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
|
+
}
|
|
391
408
|
export const xiaoyiProvider = {
|
|
392
409
|
id: "xiaoyiprovider",
|
|
393
410
|
label: "Xiaoyi Provider",
|
|
@@ -438,13 +455,38 @@ export const xiaoyiProvider = {
|
|
|
438
455
|
* since the default agent timeout is 48 hours).
|
|
439
456
|
*/
|
|
440
457
|
wrapStreamFn: (ctx) => {
|
|
441
|
-
|
|
458
|
+
logger.log("[xiaoyiprovider] wrapStreamFn CALLED — provider resolved by openclaw");
|
|
442
459
|
const underlying = ctx.streamFn;
|
|
443
460
|
if (!underlying)
|
|
444
461
|
return underlying;
|
|
445
462
|
return async (model, context, options) => {
|
|
446
|
-
// 每次请求时从 ctx.extraParams 动态读取 header
|
|
447
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 ────────────────────────────
|
|
448
490
|
if (ctx.extraParams) {
|
|
449
491
|
const fallbackPrefix = ctx.extraParams[FALLBACK_PREFIX_KEY];
|
|
450
492
|
if (typeof fallbackPrefix === "string") {
|
|
@@ -462,22 +504,30 @@ export const xiaoyiProvider = {
|
|
|
462
504
|
dynamicHeaders["x-cron-flag"] = "begin";
|
|
463
505
|
}
|
|
464
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";
|
|
520
|
+
}
|
|
521
|
+
dynamicHeaders[HEADER_SESSION_ID] = sessionId;
|
|
522
|
+
dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
|
|
523
|
+
}
|
|
465
524
|
else {
|
|
466
|
-
//
|
|
525
|
+
// Fallback: use extraParams cached values
|
|
467
526
|
const traceId = ctx.extraParams[HEADER_TRACE_ID];
|
|
468
527
|
const sessionId = ctx.extraParams[HEADER_SESSION_ID];
|
|
469
528
|
const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
|
|
470
|
-
if (typeof traceId === "string")
|
|
471
|
-
|
|
472
|
-
dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
|
|
473
|
-
if (isCron) {
|
|
474
|
-
const cronTitle = extractCronTitle(context.messages);
|
|
475
|
-
if (cronTitle)
|
|
476
|
-
dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
|
|
477
|
-
if (context.messages?.length === 1)
|
|
478
|
-
dynamicHeaders["x-cron-flag"] = "begin";
|
|
479
|
-
}
|
|
480
|
-
}
|
|
529
|
+
if (typeof traceId === "string")
|
|
530
|
+
dynamicHeaders[HEADER_TRACE_ID] = traceId;
|
|
481
531
|
if (typeof sessionId === "string")
|
|
482
532
|
dynamicHeaders[HEADER_SESSION_ID] = sessionId;
|
|
483
533
|
if (typeof interactionId === "string")
|
|
@@ -485,17 +535,15 @@ export const xiaoyiProvider = {
|
|
|
485
535
|
}
|
|
486
536
|
}
|
|
487
537
|
// 记录输入
|
|
488
|
-
|
|
538
|
+
logger.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
|
|
489
539
|
if (context.systemPrompt) {
|
|
490
|
-
|
|
540
|
+
logger.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
|
|
491
541
|
}
|
|
492
|
-
//
|
|
493
|
-
//
|
|
494
|
-
// resolvePreparedExtraParams by provider/modelId – the cache key does
|
|
495
|
-
// not include session-specific data, so deviceType may be missing
|
|
496
|
-
// from the cached extraParams even when a session is active.
|
|
542
|
+
// deviceType: prefer value extracted from Conversation info,
|
|
543
|
+
// then extraParams, then ALS fallback.
|
|
497
544
|
const extraParamsDeviceType = ctx.extraParams?.[DEVICE_TYPE_KEY] || undefined;
|
|
498
|
-
const deviceType =
|
|
545
|
+
const deviceType = (extractedDeviceType || extraParamsDeviceType)
|
|
546
|
+
?? getCurrentSessionContext()?.deviceType;
|
|
499
547
|
// 在发送给模型前,优化 systemPrompt 结构
|
|
500
548
|
if (context.systemPrompt) {
|
|
501
549
|
let sp = context.systemPrompt;
|
|
@@ -522,13 +570,13 @@ export const xiaoyiProvider = {
|
|
|
522
570
|
sp = sp.replace('## Runtime', combined + '\n\n## Runtime');
|
|
523
571
|
}
|
|
524
572
|
}
|
|
525
|
-
|
|
573
|
+
logger.log(`[xiaoyiprovider] system prompt optimized: ${beforeLen} -> ${sp.length}`);
|
|
526
574
|
context.systemPrompt = sp;
|
|
527
575
|
}
|
|
528
576
|
const selfEvolutionEnabled = await selfEvolutionManager.isEnabled();
|
|
529
|
-
|
|
577
|
+
logger.log(`[selfEvolution] selfEvolution flag: ${selfEvolutionEnabled}`);
|
|
530
578
|
context.systemPrompt = applySelfEvolutionPrompt(context.systemPrompt, selfEvolutionEnabled);
|
|
531
|
-
// Append device context to systemPrompt
|
|
579
|
+
// Append device context to systemPrompt
|
|
532
580
|
if (deviceType) {
|
|
533
581
|
const displayDevice = (deviceType === "2in1") ? "鸿蒙PC" : deviceType;
|
|
534
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"`;
|
|
@@ -554,7 +602,7 @@ export const xiaoyiProvider = {
|
|
|
554
602
|
// ── Retry-capable streaming ──────────────────────────────
|
|
555
603
|
const cronJob = isCronTriggered(context.messages);
|
|
556
604
|
if (cronJob)
|
|
557
|
-
|
|
605
|
+
logger.log("[xiaoyiprovider] detected cron-triggered request, using extended retry delays");
|
|
558
606
|
const makeStream = () => underlying(model, context, {
|
|
559
607
|
...options,
|
|
560
608
|
headers: {
|