@ynhcj/xiaoyi-channel 0.0.26-beta → 0.0.26-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.d.ts +0 -2
- package/dist/index.js +48 -2
- package/dist/src/bot.js +81 -28
- package/dist/src/channel.js +33 -7
- package/dist/src/client.js +11 -27
- package/dist/src/config.js +2 -2
- package/dist/src/cspl/call-api.d.ts +3 -0
- package/dist/src/cspl/call-api.js +107 -0
- package/dist/src/cspl/config.d.ts +19 -0
- package/dist/src/cspl/config.js +50 -0
- package/dist/src/cspl/constants.d.ts +43 -0
- package/dist/src/cspl/constants.js +22 -0
- package/dist/src/cspl/utils.d.ts +10 -0
- package/dist/src/cspl/utils.js +57 -0
- package/dist/src/file-upload.d.ts +5 -0
- package/dist/src/file-upload.js +92 -0
- package/dist/src/formatter.d.ts +14 -0
- package/dist/src/formatter.js +49 -25
- package/dist/src/heartbeat.js +0 -4
- package/dist/src/monitor.js +12 -0
- package/dist/src/onboarding.d.ts +3 -4
- package/dist/src/onboarding.js +2 -2
- package/dist/src/outbound.d.ts +2 -1
- package/dist/src/outbound.js +52 -6
- package/dist/src/parser.d.ts +7 -0
- package/dist/src/parser.js +22 -0
- package/dist/src/push.d.ts +8 -1
- package/dist/src/push.js +30 -22
- package/dist/src/reply-dispatcher.js +39 -5
- package/dist/src/steer-injector.d.ts +16 -0
- package/dist/src/steer-injector.js +74 -0
- package/dist/src/thread-bindings.d.ts +54 -0
- package/dist/src/thread-bindings.js +214 -0
- package/dist/src/tools/calendar-tool.js +7 -40
- package/dist/src/tools/call-phone-tool.d.ts +5 -0
- package/dist/src/tools/call-phone-tool.js +142 -0
- package/dist/src/tools/create-alarm-tool.d.ts +7 -0
- package/dist/src/tools/create-alarm-tool.js +349 -0
- package/dist/src/tools/delete-alarm-tool.d.ts +11 -0
- package/dist/src/tools/delete-alarm-tool.js +174 -0
- package/dist/src/tools/image-reading-tool.d.ts +5 -0
- package/dist/src/tools/image-reading-tool.js +328 -0
- package/dist/src/tools/location-tool.js +8 -42
- package/dist/src/tools/modify-alarm-tool.d.ts +9 -0
- package/dist/src/tools/modify-alarm-tool.js +365 -0
- package/dist/src/tools/modify-note-tool.js +5 -43
- package/dist/src/tools/note-tool.js +33 -24
- package/dist/src/tools/search-alarm-tool.d.ts +8 -0
- package/dist/src/tools/search-alarm-tool.js +285 -0
- package/dist/src/tools/search-calendar-tool.js +10 -84
- package/dist/src/tools/search-contact-tool.js +4 -57
- package/dist/src/tools/search-file-tool.d.ts +5 -0
- package/dist/src/tools/search-file-tool.js +128 -0
- package/dist/src/tools/search-message-tool.d.ts +5 -0
- package/dist/src/tools/search-message-tool.js +116 -0
- package/dist/src/tools/search-note-tool.js +6 -24
- package/dist/src/tools/search-photo-gallery-tool.js +40 -61
- package/dist/src/tools/send-file-to-user-tool.d.ts +5 -0
- package/dist/src/tools/send-file-to-user-tool.js +279 -0
- package/dist/src/tools/send-message-tool.d.ts +5 -0
- package/dist/src/tools/send-message-tool.js +138 -0
- package/dist/src/tools/session-manager.d.ts +15 -0
- package/dist/src/tools/session-manager.js +43 -31
- package/dist/src/tools/upload-file-tool.d.ts +13 -0
- package/dist/src/tools/upload-file-tool.js +216 -0
- package/dist/src/tools/upload-photo-tool.js +2 -44
- package/dist/src/tools/view-push-result-tool.d.ts +5 -0
- package/dist/src/tools/view-push-result-tool.js +107 -0
- package/dist/src/tools/xiaoyi-collection-tool.d.ts +5 -0
- package/dist/src/tools/xiaoyi-collection-tool.js +112 -0
- package/dist/src/tools/xiaoyi-gui-tool.js +2 -36
- package/dist/src/trigger-handler.d.ts +22 -0
- package/dist/src/trigger-handler.js +59 -0
- package/dist/src/types.d.ts +1 -8
- package/dist/src/types.js +4 -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 +25 -31
- package/dist/src/websocket.js +233 -271
- package/package.json +2 -2
- package/dist/src/tools/search-photo-tool.d.ts +0 -9
- package/dist/src/tools/search-photo-tool.js +0 -270
- package/dist/src/utils/session.d.ts +0 -34
- package/dist/src/utils/session.js +0 -50
|
@@ -1,8 +1,38 @@
|
|
|
1
|
-
import { createReplyPrefixContext } from "openclaw/plugin-sdk";
|
|
2
1
|
import { getXYRuntime } from "./runtime.js";
|
|
3
2
|
import { sendA2AResponse, sendStatusUpdate, sendReasoningTextUpdate } from "./formatter.js";
|
|
4
3
|
import { resolveXYConfig } from "./config.js";
|
|
5
4
|
import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
|
|
5
|
+
import fs from "fs/promises";
|
|
6
|
+
import path from "path";
|
|
7
|
+
/**
|
|
8
|
+
* 清理 /tmp/xy_channel 目录中的所有文件
|
|
9
|
+
*/
|
|
10
|
+
async function cleanupTempDir(tempDir = "/tmp/xy_channel") {
|
|
11
|
+
try {
|
|
12
|
+
const stats = await fs.stat(tempDir).catch(() => null);
|
|
13
|
+
if (!stats?.isDirectory()) {
|
|
14
|
+
return; // 目录不存在,直接返回
|
|
15
|
+
}
|
|
16
|
+
const files = await fs.readdir(tempDir);
|
|
17
|
+
let cleanedCount = 0;
|
|
18
|
+
for (const file of files) {
|
|
19
|
+
const filePath = path.join(tempDir, file);
|
|
20
|
+
try {
|
|
21
|
+
await fs.unlink(filePath);
|
|
22
|
+
cleanedCount++;
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
// 忽略单个文件删除失败,继续处理其他文件
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (cleanedCount > 0) {
|
|
29
|
+
console.log(`[CLEANUP] 🧹 Cleaned ${cleanedCount} files from ${tempDir}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
console.error(`[CLEANUP] ❌ Failed to cleanup temp dir:`, err);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
6
36
|
/**
|
|
7
37
|
* Create a reply dispatcher for XY channel messages.
|
|
8
38
|
* Follows feishu pattern with status updates and streaming support.
|
|
@@ -32,7 +62,12 @@ export function createXYReplyDispatcher(params) {
|
|
|
32
62
|
};
|
|
33
63
|
const core = getXYRuntime();
|
|
34
64
|
const config = resolveXYConfig(cfg);
|
|
35
|
-
|
|
65
|
+
// Simplified prefix context for single-account Xiaoyi channel
|
|
66
|
+
const prefixContext = {
|
|
67
|
+
responsePrefix: undefined,
|
|
68
|
+
responsePrefixContextProvider: undefined,
|
|
69
|
+
onModelSelected: undefined,
|
|
70
|
+
};
|
|
36
71
|
let statusUpdateInterval = null;
|
|
37
72
|
let hasSentResponse = false;
|
|
38
73
|
let finalSent = false;
|
|
@@ -54,7 +89,7 @@ export function createXYReplyDispatcher(params) {
|
|
|
54
89
|
sessionId,
|
|
55
90
|
taskId: currentTaskId, // 🔑 动态taskId
|
|
56
91
|
messageId: currentMessageId, // 🔑 动态messageId
|
|
57
|
-
text: "
|
|
92
|
+
text: "任务正在处理中,请稍候~",
|
|
58
93
|
state: "working",
|
|
59
94
|
}).catch((err) => {
|
|
60
95
|
error(`Failed to send status update:`, err);
|
|
@@ -206,6 +241,7 @@ export function createXYReplyDispatcher(params) {
|
|
|
206
241
|
}
|
|
207
242
|
}
|
|
208
243
|
stopStatusInterval();
|
|
244
|
+
void cleanupTempDir();
|
|
209
245
|
},
|
|
210
246
|
onCleanup: () => {
|
|
211
247
|
const currentTaskId = getActiveTaskId();
|
|
@@ -289,7 +325,6 @@ export function createXYReplyDispatcher(params) {
|
|
|
289
325
|
const currentTaskId = getActiveTaskId();
|
|
290
326
|
const currentMessageId = getActiveMessageId();
|
|
291
327
|
const text = payload.text ?? "";
|
|
292
|
-
log(`[PARTIAL REPLY] Partial reply chunk received, taskId: ${currentTaskId}`);
|
|
293
328
|
try {
|
|
294
329
|
if (text.length > 0) {
|
|
295
330
|
await sendReasoningTextUpdate({
|
|
@@ -300,7 +335,6 @@ export function createXYReplyDispatcher(params) {
|
|
|
300
335
|
text,
|
|
301
336
|
append: false,
|
|
302
337
|
});
|
|
303
|
-
log(`[PARTIAL REPLY] ✅ Sent partial reply as reasoningText update`);
|
|
304
338
|
}
|
|
305
339
|
}
|
|
306
340
|
catch (err) {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ClawdbotConfig, RuntimeEnv } from "openclaw/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* 在 handleXYMessage 入口处调用,缓存 cfg/runtime 供 steer 注入使用。
|
|
4
|
+
*/
|
|
5
|
+
export declare function setCachedContext(cfg: ClawdbotConfig, runtime: RuntimeEnv, accountId: string): void;
|
|
6
|
+
/**
|
|
7
|
+
* 尝试向当前活跃会话注入 steer 消息。
|
|
8
|
+
* 两层保险:
|
|
9
|
+
* 1. getSessionContext(sessionKey) 确认是当前 XY 活跃 session
|
|
10
|
+
* 2. hasActiveTask(sessionId) 确认任务仍在运行
|
|
11
|
+
*
|
|
12
|
+
* @param sessionKey 来自 after_tool_call ctx.sessionKey(per-peer 下精确对应一个 XY session)
|
|
13
|
+
* @param message 要注入的用户消息文本
|
|
14
|
+
* @returns true=已注入,false=跳过
|
|
15
|
+
*/
|
|
16
|
+
export declare function tryInjectSteer(sessionKey: string | undefined, message: string): Promise<boolean>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Steer message injector for CSPL hook integration
|
|
2
|
+
import { getSessionContext } from "./tools/session-manager.js";
|
|
3
|
+
import { hasActiveTask, getCurrentTaskId } from "./task-manager.js";
|
|
4
|
+
import { handleXYMessage } from "./bot.js";
|
|
5
|
+
import { logger } from "./utils/logger.js";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
let cachedCfg = null;
|
|
8
|
+
let cachedRuntime = null;
|
|
9
|
+
let cachedAccountId = "default";
|
|
10
|
+
/**
|
|
11
|
+
* 在 handleXYMessage 入口处调用,缓存 cfg/runtime 供 steer 注入使用。
|
|
12
|
+
*/
|
|
13
|
+
export function setCachedContext(cfg, runtime, accountId) {
|
|
14
|
+
cachedCfg = cfg;
|
|
15
|
+
cachedRuntime = runtime;
|
|
16
|
+
cachedAccountId = accountId;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 尝试向当前活跃会话注入 steer 消息。
|
|
20
|
+
* 两层保险:
|
|
21
|
+
* 1. getSessionContext(sessionKey) 确认是当前 XY 活跃 session
|
|
22
|
+
* 2. hasActiveTask(sessionId) 确认任务仍在运行
|
|
23
|
+
*
|
|
24
|
+
* @param sessionKey 来自 after_tool_call ctx.sessionKey(per-peer 下精确对应一个 XY session)
|
|
25
|
+
* @param message 要注入的用户消息文本
|
|
26
|
+
* @returns true=已注入,false=跳过
|
|
27
|
+
*/
|
|
28
|
+
export async function tryInjectSteer(sessionKey, message) {
|
|
29
|
+
if (!sessionKey) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
const sessionCtx = getSessionContext(sessionKey);
|
|
33
|
+
if (!sessionCtx) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
const { sessionId } = sessionCtx;
|
|
37
|
+
const activeTaskId = getCurrentTaskId(sessionId);
|
|
38
|
+
if (!hasActiveTask(sessionId)) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
if (!cachedCfg || !cachedRuntime) {
|
|
42
|
+
logger.error("[STEER] No cached cfg/runtime available, cannot inject");
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
// 3. 构造合成 A2A 消息(伪装成用户在当前会话中发送的新消息)
|
|
46
|
+
const syntheticMessage = {
|
|
47
|
+
jsonrpc: "2.0",
|
|
48
|
+
method: "tasks/send",
|
|
49
|
+
id: `steer-msg-${randomUUID()}`,
|
|
50
|
+
params: {
|
|
51
|
+
sessionId,
|
|
52
|
+
id: activeTaskId ?? `steer-task-${randomUUID()}`,
|
|
53
|
+
agentLoginSessionId: "",
|
|
54
|
+
message: {
|
|
55
|
+
role: "user",
|
|
56
|
+
parts: [{ kind: "text", text: message }],
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
console.log(`[STEER] Injecting steer for sessionId=${sessionId}, taskId=${syntheticMessage.params.id}`);
|
|
61
|
+
try {
|
|
62
|
+
await handleXYMessage({
|
|
63
|
+
cfg: cachedCfg,
|
|
64
|
+
runtime: cachedRuntime,
|
|
65
|
+
message: syntheticMessage,
|
|
66
|
+
accountId: cachedAccountId,
|
|
67
|
+
});
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
logger.error(`[STEER] ❌ Failed to inject steer: ${err}`);
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-runtime";
|
|
2
|
+
import { type BindingTargetKind } from "openclaw/plugin-sdk/conversation-runtime";
|
|
3
|
+
type XYBindingTargetKind = "subagent" | "session";
|
|
4
|
+
/**
|
|
5
|
+
* Xiaoyi thread binding record.
|
|
6
|
+
* Simplified from feishu - uses sessionId as conversationId, no parentConversationId.
|
|
7
|
+
*/
|
|
8
|
+
type XYThreadBindingRecord = {
|
|
9
|
+
accountId: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
targetKind: XYBindingTargetKind;
|
|
12
|
+
targetSessionKey: string;
|
|
13
|
+
agentId?: string;
|
|
14
|
+
boundAt: number;
|
|
15
|
+
lastActivityAt: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Thread binding manager for Xiaoyi channel.
|
|
19
|
+
* Manages session bindings for single-account mode.
|
|
20
|
+
*/
|
|
21
|
+
type XYThreadBindingManager = {
|
|
22
|
+
accountId: string;
|
|
23
|
+
getBySessionId: (sessionId: string) => XYThreadBindingRecord | undefined;
|
|
24
|
+
listBySessionKey: (targetSessionKey: string) => XYThreadBindingRecord[];
|
|
25
|
+
bindSession: (params: {
|
|
26
|
+
sessionId: string;
|
|
27
|
+
targetKind: BindingTargetKind;
|
|
28
|
+
targetSessionKey: string;
|
|
29
|
+
metadata?: Record<string, unknown>;
|
|
30
|
+
}) => XYThreadBindingRecord | null;
|
|
31
|
+
touchSession: (sessionId: string, at?: number) => XYThreadBindingRecord | null;
|
|
32
|
+
unbindSession: (sessionId: string) => XYThreadBindingRecord | null;
|
|
33
|
+
unbindBySessionKey: (targetSessionKey: string) => XYThreadBindingRecord[];
|
|
34
|
+
stop: () => void;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Creates a thread binding manager for Xiaoyi channel.
|
|
38
|
+
* Based on feishu implementation but simplified for single-account mode.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createXYThreadBindingManager(params: {
|
|
41
|
+
accountId?: string;
|
|
42
|
+
cfg: OpenClawConfig;
|
|
43
|
+
}): XYThreadBindingManager;
|
|
44
|
+
/**
|
|
45
|
+
* Gets the thread binding manager for a given account ID.
|
|
46
|
+
*/
|
|
47
|
+
export declare function getXYThreadBindingManager(accountId?: string): XYThreadBindingManager | null;
|
|
48
|
+
/**
|
|
49
|
+
* Testing utilities for thread bindings.
|
|
50
|
+
*/
|
|
51
|
+
export declare const __testing: {
|
|
52
|
+
resetXYThreadBindingsForTests(): void;
|
|
53
|
+
};
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { resolveThreadBindingIdleTimeoutMsForChannel, resolveThreadBindingMaxAgeMsForChannel, registerSessionBindingAdapter, resolveThreadBindingConversationIdFromBindingId, unregisterSessionBindingAdapter, } from "openclaw/plugin-sdk/conversation-runtime";
|
|
2
|
+
import { normalizeAccountId, resolveAgentIdFromSessionKey } from "openclaw/plugin-sdk/routing";
|
|
3
|
+
import { resolveGlobalSingleton } from "openclaw/plugin-sdk/text-runtime";
|
|
4
|
+
const XY_THREAD_BINDINGS_STATE_KEY = Symbol.for("openclaw.xyThreadBindingsState");
|
|
5
|
+
const state = resolveGlobalSingleton(XY_THREAD_BINDINGS_STATE_KEY, () => ({
|
|
6
|
+
managersByAccountId: new Map(),
|
|
7
|
+
bindingsByAccountSession: new Map(),
|
|
8
|
+
}));
|
|
9
|
+
function getState() {
|
|
10
|
+
return state;
|
|
11
|
+
}
|
|
12
|
+
function resolveBindingKey(params) {
|
|
13
|
+
return `${params.accountId}:${params.sessionId}`;
|
|
14
|
+
}
|
|
15
|
+
function toSessionBindingTargetKind(raw) {
|
|
16
|
+
return raw === "subagent" ? "subagent" : "session";
|
|
17
|
+
}
|
|
18
|
+
function toXYTargetKind(raw) {
|
|
19
|
+
return raw === "subagent" ? "subagent" : "session";
|
|
20
|
+
}
|
|
21
|
+
function toSessionBindingRecord(record, defaults) {
|
|
22
|
+
const idleExpiresAt = defaults.idleTimeoutMs > 0 ? record.lastActivityAt + defaults.idleTimeoutMs : undefined;
|
|
23
|
+
const maxAgeExpiresAt = defaults.maxAgeMs > 0 ? record.boundAt + defaults.maxAgeMs : undefined;
|
|
24
|
+
const expiresAt = idleExpiresAt != null && maxAgeExpiresAt != null
|
|
25
|
+
? Math.min(idleExpiresAt, maxAgeExpiresAt)
|
|
26
|
+
: (idleExpiresAt ?? maxAgeExpiresAt);
|
|
27
|
+
return {
|
|
28
|
+
bindingId: resolveBindingKey({
|
|
29
|
+
accountId: record.accountId,
|
|
30
|
+
sessionId: record.sessionId,
|
|
31
|
+
}),
|
|
32
|
+
targetSessionKey: record.targetSessionKey,
|
|
33
|
+
targetKind: toSessionBindingTargetKind(record.targetKind),
|
|
34
|
+
conversation: {
|
|
35
|
+
channel: "xiaoyi-channel",
|
|
36
|
+
accountId: record.accountId,
|
|
37
|
+
conversationId: record.sessionId, // sessionId is the conversationId for Xiaoyi
|
|
38
|
+
parentConversationId: undefined, // Xiaoyi doesn't have parent conversations
|
|
39
|
+
},
|
|
40
|
+
status: "active",
|
|
41
|
+
boundAt: record.boundAt,
|
|
42
|
+
expiresAt,
|
|
43
|
+
metadata: {
|
|
44
|
+
agentId: record.agentId,
|
|
45
|
+
lastActivityAt: record.lastActivityAt,
|
|
46
|
+
idleTimeoutMs: defaults.idleTimeoutMs,
|
|
47
|
+
maxAgeMs: defaults.maxAgeMs,
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates a thread binding manager for Xiaoyi channel.
|
|
53
|
+
* Based on feishu implementation but simplified for single-account mode.
|
|
54
|
+
*/
|
|
55
|
+
export function createXYThreadBindingManager(params) {
|
|
56
|
+
const accountId = normalizeAccountId(params.accountId);
|
|
57
|
+
const existing = getState().managersByAccountId.get(accountId);
|
|
58
|
+
if (existing) {
|
|
59
|
+
return existing;
|
|
60
|
+
}
|
|
61
|
+
const idleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
|
|
62
|
+
cfg: params.cfg,
|
|
63
|
+
channel: "xiaoyi-channel",
|
|
64
|
+
accountId,
|
|
65
|
+
});
|
|
66
|
+
const maxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
|
|
67
|
+
cfg: params.cfg,
|
|
68
|
+
channel: "xiaoyi-channel",
|
|
69
|
+
accountId,
|
|
70
|
+
});
|
|
71
|
+
const manager = {
|
|
72
|
+
accountId,
|
|
73
|
+
getBySessionId: (sessionId) => getState().bindingsByAccountSession.get(resolveBindingKey({ accountId, sessionId })),
|
|
74
|
+
listBySessionKey: (targetSessionKey) => [...getState().bindingsByAccountSession.values()].filter((record) => record.accountId === accountId && record.targetSessionKey === targetSessionKey),
|
|
75
|
+
bindSession: ({ sessionId, targetKind, targetSessionKey, metadata, }) => {
|
|
76
|
+
const normalizedSessionId = sessionId.trim();
|
|
77
|
+
if (!normalizedSessionId || !targetSessionKey.trim()) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
const record = {
|
|
82
|
+
accountId,
|
|
83
|
+
sessionId: normalizedSessionId,
|
|
84
|
+
targetKind: toXYTargetKind(targetKind),
|
|
85
|
+
targetSessionKey: targetSessionKey.trim(),
|
|
86
|
+
agentId: typeof metadata?.agentId === "string" && metadata.agentId.trim()
|
|
87
|
+
? metadata.agentId.trim()
|
|
88
|
+
: resolveAgentIdFromSessionKey(targetSessionKey),
|
|
89
|
+
boundAt: now,
|
|
90
|
+
lastActivityAt: now,
|
|
91
|
+
};
|
|
92
|
+
getState().bindingsByAccountSession.set(resolveBindingKey({ accountId, sessionId: normalizedSessionId }), record);
|
|
93
|
+
return record;
|
|
94
|
+
},
|
|
95
|
+
touchSession: (sessionId, at = Date.now()) => {
|
|
96
|
+
const key = resolveBindingKey({ accountId, sessionId });
|
|
97
|
+
const existingRecord = getState().bindingsByAccountSession.get(key);
|
|
98
|
+
if (!existingRecord) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
const updated = { ...existingRecord, lastActivityAt: at };
|
|
102
|
+
getState().bindingsByAccountSession.set(key, updated);
|
|
103
|
+
return updated;
|
|
104
|
+
},
|
|
105
|
+
unbindSession: (sessionId) => {
|
|
106
|
+
const key = resolveBindingKey({ accountId, sessionId });
|
|
107
|
+
const existingRecord = getState().bindingsByAccountSession.get(key);
|
|
108
|
+
if (!existingRecord) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
getState().bindingsByAccountSession.delete(key);
|
|
112
|
+
return existingRecord;
|
|
113
|
+
},
|
|
114
|
+
unbindBySessionKey: (targetSessionKey) => {
|
|
115
|
+
const removed = [];
|
|
116
|
+
for (const record of [...getState().bindingsByAccountSession.values()]) {
|
|
117
|
+
if (record.accountId !== accountId || record.targetSessionKey !== targetSessionKey) {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
getState().bindingsByAccountSession.delete(resolveBindingKey({ accountId, sessionId: record.sessionId }));
|
|
121
|
+
removed.push(record);
|
|
122
|
+
}
|
|
123
|
+
return removed;
|
|
124
|
+
},
|
|
125
|
+
stop: () => {
|
|
126
|
+
for (const key of [...getState().bindingsByAccountSession.keys()]) {
|
|
127
|
+
if (key.startsWith(`${accountId}:`)) {
|
|
128
|
+
getState().bindingsByAccountSession.delete(key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
getState().managersByAccountId.delete(accountId);
|
|
132
|
+
unregisterSessionBindingAdapter({
|
|
133
|
+
channel: "xiaoyi-channel",
|
|
134
|
+
accountId,
|
|
135
|
+
adapter: sessionBindingAdapter,
|
|
136
|
+
});
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
const sessionBindingAdapter = {
|
|
140
|
+
channel: "xiaoyi-channel",
|
|
141
|
+
accountId,
|
|
142
|
+
capabilities: {
|
|
143
|
+
placements: ["current"],
|
|
144
|
+
},
|
|
145
|
+
bind: async (input) => {
|
|
146
|
+
if (input.conversation.channel !== "xiaoyi-channel" || input.placement === "child") {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
const bound = manager.bindSession({
|
|
150
|
+
sessionId: input.conversation.conversationId,
|
|
151
|
+
targetKind: input.targetKind,
|
|
152
|
+
targetSessionKey: input.targetSessionKey,
|
|
153
|
+
metadata: input.metadata,
|
|
154
|
+
});
|
|
155
|
+
return bound ? toSessionBindingRecord(bound, { idleTimeoutMs, maxAgeMs }) : null;
|
|
156
|
+
},
|
|
157
|
+
listBySession: (targetSessionKey) => manager
|
|
158
|
+
.listBySessionKey(targetSessionKey)
|
|
159
|
+
.map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs })),
|
|
160
|
+
resolveByConversation: (ref) => {
|
|
161
|
+
if (ref.channel !== "xiaoyi-channel") {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
const found = manager.getBySessionId(ref.conversationId);
|
|
165
|
+
return found ? toSessionBindingRecord(found, { idleTimeoutMs, maxAgeMs }) : null;
|
|
166
|
+
},
|
|
167
|
+
touch: (bindingId, at) => {
|
|
168
|
+
const sessionId = resolveThreadBindingConversationIdFromBindingId({
|
|
169
|
+
accountId,
|
|
170
|
+
bindingId,
|
|
171
|
+
});
|
|
172
|
+
if (sessionId) {
|
|
173
|
+
manager.touchSession(sessionId, at);
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
unbind: async (input) => {
|
|
177
|
+
if (input.targetSessionKey?.trim()) {
|
|
178
|
+
return manager
|
|
179
|
+
.unbindBySessionKey(input.targetSessionKey.trim())
|
|
180
|
+
.map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs }));
|
|
181
|
+
}
|
|
182
|
+
const sessionId = resolveThreadBindingConversationIdFromBindingId({
|
|
183
|
+
accountId,
|
|
184
|
+
bindingId: input.bindingId,
|
|
185
|
+
});
|
|
186
|
+
if (!sessionId) {
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
const removed = manager.unbindSession(sessionId);
|
|
190
|
+
return removed ? [toSessionBindingRecord(removed, { idleTimeoutMs, maxAgeMs })] : [];
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
registerSessionBindingAdapter(sessionBindingAdapter);
|
|
194
|
+
getState().managersByAccountId.set(accountId, manager);
|
|
195
|
+
return manager;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Gets the thread binding manager for a given account ID.
|
|
199
|
+
*/
|
|
200
|
+
export function getXYThreadBindingManager(accountId) {
|
|
201
|
+
return getState().managersByAccountId.get(normalizeAccountId(accountId)) ?? null;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Testing utilities for thread bindings.
|
|
205
|
+
*/
|
|
206
|
+
export const __testing = {
|
|
207
|
+
resetXYThreadBindingsForTests() {
|
|
208
|
+
for (const manager of getState().managersByAccountId.values()) {
|
|
209
|
+
manager.stop();
|
|
210
|
+
}
|
|
211
|
+
getState().managersByAccountId.clear();
|
|
212
|
+
getState().bindingsByAccountSession.clear();
|
|
213
|
+
},
|
|
214
|
+
};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { getXYWebSocketManager } from "../client.js";
|
|
2
2
|
import { sendCommand } from "../formatter.js";
|
|
3
|
-
import {
|
|
4
|
-
import { logger } from "../utils/logger.js";
|
|
3
|
+
import { getCurrentSessionContext } from "./session-manager.js";
|
|
5
4
|
/**
|
|
6
5
|
* XY calendar event tool - creates a calendar event on user's device.
|
|
7
6
|
* Requires title, dtStart (start time), and dtEnd (end time) parameters.
|
|
@@ -10,7 +9,11 @@ import { logger } from "../utils/logger.js";
|
|
|
10
9
|
export const calendarTool = {
|
|
11
10
|
name: "create_calendar_event",
|
|
12
11
|
label: "Create Calendar Event",
|
|
13
|
-
description:
|
|
12
|
+
description: `在用户设备上创建日程。需要提供日程标题、开始时间和结束时间。时间格式必须为:yyyy-mm-dd hh:mm:ss(例如:2024-01-15 14:30:00)。注意:该工具执行时间较长(最多60秒),请勿重复调用,超时或失败时最多重试一次。
|
|
13
|
+
注意事项:使用该工具之前需获取当前真实时间
|
|
14
|
+
|
|
15
|
+
回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。
|
|
16
|
+
`,
|
|
14
17
|
parameters: {
|
|
15
18
|
type: "object",
|
|
16
19
|
properties: {
|
|
@@ -30,47 +33,25 @@ export const calendarTool = {
|
|
|
30
33
|
required: ["title", "dtStart", "dtEnd"],
|
|
31
34
|
},
|
|
32
35
|
async execute(toolCallId, params) {
|
|
33
|
-
logger.log(`[CALENDAR_TOOL] 🚀 Starting execution`);
|
|
34
|
-
logger.log(`[CALENDAR_TOOL] - toolCallId: ${toolCallId}`);
|
|
35
|
-
logger.log(`[CALENDAR_TOOL] - params:`, JSON.stringify(params));
|
|
36
|
-
logger.log(`[CALENDAR_TOOL] - timestamp: ${new Date().toISOString()}`);
|
|
37
36
|
// Validate parameters
|
|
38
37
|
if (!params.title || !params.dtStart || !params.dtEnd) {
|
|
39
|
-
logger.error(`[CALENDAR_TOOL] ❌ Missing required parameters`);
|
|
40
38
|
throw new Error("Missing required parameters: title, dtStart, and dtEnd are required");
|
|
41
39
|
}
|
|
42
40
|
// Convert time strings to millisecond timestamps
|
|
43
|
-
logger.log(`[CALENDAR_TOOL] 🕒 Converting time strings to timestamps...`);
|
|
44
|
-
logger.log(`[CALENDAR_TOOL] - dtStart input: ${params.dtStart}`);
|
|
45
|
-
logger.log(`[CALENDAR_TOOL] - dtEnd input: ${params.dtEnd}`);
|
|
46
41
|
const dtStartMs = new Date(params.dtStart).getTime();
|
|
47
42
|
const dtEndMs = new Date(params.dtEnd).getTime();
|
|
48
43
|
if (isNaN(dtStartMs) || isNaN(dtEndMs)) {
|
|
49
|
-
logger.error(`[CALENDAR_TOOL] ❌ Invalid time format`);
|
|
50
44
|
throw new Error("Invalid time format. Required format: yyyy-mm-dd hh:mm:ss (e.g., 2024-01-15 14:30:00)");
|
|
51
45
|
}
|
|
52
|
-
logger.log(`[CALENDAR_TOOL] ✅ Time conversion successful`);
|
|
53
|
-
logger.log(`[CALENDAR_TOOL] - dtStart timestamp: ${dtStartMs}`);
|
|
54
|
-
logger.log(`[CALENDAR_TOOL] - dtEnd timestamp: ${dtEndMs}`);
|
|
55
46
|
// Get session context
|
|
56
|
-
|
|
57
|
-
const sessionContext = getLatestSessionContext();
|
|
47
|
+
const sessionContext = getCurrentSessionContext();
|
|
58
48
|
if (!sessionContext) {
|
|
59
|
-
logger.error(`[CALENDAR_TOOL] ❌ FAILED: No active session found!`);
|
|
60
|
-
logger.error(`[CALENDAR_TOOL] - toolCallId: ${toolCallId}`);
|
|
61
49
|
throw new Error("No active XY session found. Calendar tool can only be used during an active conversation.");
|
|
62
50
|
}
|
|
63
|
-
logger.log(`[CALENDAR_TOOL] ✅ Session context found`);
|
|
64
|
-
logger.log(`[CALENDAR_TOOL] - sessionId: ${sessionContext.sessionId}`);
|
|
65
|
-
logger.log(`[CALENDAR_TOOL] - taskId: ${sessionContext.taskId}`);
|
|
66
|
-
logger.log(`[CALENDAR_TOOL] - messageId: ${sessionContext.messageId}`);
|
|
67
51
|
const { config, sessionId, taskId, messageId } = sessionContext;
|
|
68
52
|
// Get WebSocket manager
|
|
69
|
-
logger.log(`[CALENDAR_TOOL] 🔌 Getting WebSocket manager...`);
|
|
70
53
|
const wsManager = getXYWebSocketManager(config);
|
|
71
|
-
logger.log(`[CALENDAR_TOOL] ✅ WebSocket manager obtained`);
|
|
72
54
|
// Build CreateCalendarEvent command
|
|
73
|
-
logger.log(`[CALENDAR_TOOL] 📦 Building CreateCalendarEvent command...`);
|
|
74
55
|
const command = {
|
|
75
56
|
header: {
|
|
76
57
|
namespace: "Common",
|
|
@@ -106,25 +87,17 @@ export const calendarTool = {
|
|
|
106
87
|
},
|
|
107
88
|
};
|
|
108
89
|
// Send command and wait for response (60 second timeout)
|
|
109
|
-
logger.log(`[CALENDAR_TOOL] ⏳ Setting up promise to wait for calendar event response...`);
|
|
110
|
-
logger.log(`[CALENDAR_TOOL] - Timeout: 60 seconds`);
|
|
111
90
|
return new Promise((resolve, reject) => {
|
|
112
91
|
const timeout = setTimeout(() => {
|
|
113
|
-
logger.error(`[CALENDAR_TOOL] ⏰ Timeout: No response received within 60 seconds`);
|
|
114
92
|
wsManager.off("data-event", handler);
|
|
115
93
|
reject(new Error("创建日程超时(60秒)"));
|
|
116
94
|
}, 60000);
|
|
117
95
|
// Listen for data events from WebSocket
|
|
118
96
|
const handler = (event) => {
|
|
119
|
-
logger.log(`[CALENDAR_TOOL] 📨 Received data event:`, JSON.stringify(event));
|
|
120
97
|
if (event.intentName === "CreateCalendarEvent") {
|
|
121
|
-
logger.log(`[CALENDAR_TOOL] 🎯 CreateCalendarEvent event received`);
|
|
122
|
-
logger.log(`[CALENDAR_TOOL] - status: ${event.status}`);
|
|
123
98
|
clearTimeout(timeout);
|
|
124
99
|
wsManager.off("data-event", handler);
|
|
125
100
|
if (event.status === "success" && event.outputs) {
|
|
126
|
-
logger.log(`[CALENDAR_TOOL] ✅ Calendar event created successfully`);
|
|
127
|
-
logger.log(`[CALENDAR_TOOL] - outputs:`, JSON.stringify(event.outputs));
|
|
128
101
|
resolve({
|
|
129
102
|
content: [
|
|
130
103
|
{
|
|
@@ -135,17 +108,13 @@ export const calendarTool = {
|
|
|
135
108
|
});
|
|
136
109
|
}
|
|
137
110
|
else {
|
|
138
|
-
logger.error(`[CALENDAR_TOOL] ❌ Calendar event creation failed`);
|
|
139
|
-
logger.error(`[CALENDAR_TOOL] - status: ${event.status}`);
|
|
140
111
|
reject(new Error(`创建日程失败: ${event.status}`));
|
|
141
112
|
}
|
|
142
113
|
}
|
|
143
114
|
};
|
|
144
115
|
// Register event handler
|
|
145
|
-
logger.log(`[CALENDAR_TOOL] 📡 Registering data-event handler on WebSocket manager`);
|
|
146
116
|
wsManager.on("data-event", handler);
|
|
147
117
|
// Send the command
|
|
148
|
-
logger.log(`[CALENDAR_TOOL] 📤 Sending CreateCalendarEvent command...`);
|
|
149
118
|
sendCommand({
|
|
150
119
|
config,
|
|
151
120
|
sessionId,
|
|
@@ -154,10 +123,8 @@ export const calendarTool = {
|
|
|
154
123
|
command,
|
|
155
124
|
})
|
|
156
125
|
.then(() => {
|
|
157
|
-
logger.log(`[CALENDAR_TOOL] ✅ Command sent successfully, waiting for response...`);
|
|
158
126
|
})
|
|
159
127
|
.catch((error) => {
|
|
160
|
-
logger.error(`[CALENDAR_TOOL] ❌ Failed to send command:`, error);
|
|
161
128
|
clearTimeout(timeout);
|
|
162
129
|
wsManager.off("data-event", handler);
|
|
163
130
|
reject(error);
|