@ynhcj/xiaoyi-channel 0.0.30-beta → 0.0.30-next

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/index.d.ts +0 -2
  2. package/dist/index.js +42 -2
  3. package/dist/src/bot.js +55 -25
  4. package/dist/src/channel.js +24 -8
  5. package/dist/src/client.js +11 -27
  6. package/dist/src/config.js +2 -2
  7. package/dist/src/cspl/call-api.d.ts +3 -0
  8. package/dist/src/cspl/call-api.js +107 -0
  9. package/dist/src/cspl/config.d.ts +19 -0
  10. package/dist/src/cspl/config.js +50 -0
  11. package/dist/src/cspl/constants.d.ts +43 -0
  12. package/dist/src/cspl/constants.js +22 -0
  13. package/dist/src/cspl/utils.d.ts +10 -0
  14. package/dist/src/cspl/utils.js +57 -0
  15. package/dist/src/file-upload.d.ts +5 -0
  16. package/dist/src/file-upload.js +92 -0
  17. package/dist/src/formatter.d.ts +14 -0
  18. package/dist/src/formatter.js +49 -25
  19. package/dist/src/heartbeat.js +0 -4
  20. package/dist/src/monitor.js +12 -0
  21. package/dist/src/onboarding.d.ts +3 -4
  22. package/dist/src/onboarding.js +2 -2
  23. package/dist/src/outbound.d.ts +2 -1
  24. package/dist/src/outbound.js +122 -88
  25. package/dist/src/parser.d.ts +7 -0
  26. package/dist/src/parser.js +22 -0
  27. package/dist/src/push.d.ts +8 -1
  28. package/dist/src/push.js +30 -22
  29. package/dist/src/reply-dispatcher.js +39 -5
  30. package/dist/src/steer-injector.d.ts +16 -0
  31. package/dist/src/steer-injector.js +74 -0
  32. package/dist/src/thread-bindings.d.ts +54 -0
  33. package/dist/src/thread-bindings.js +214 -0
  34. package/dist/src/tools/calendar-tool.js +5 -38
  35. package/dist/src/tools/call-phone-tool.js +1 -42
  36. package/dist/src/tools/create-alarm-tool.js +9 -104
  37. package/dist/src/tools/delete-alarm-tool.js +5 -69
  38. package/dist/src/tools/image-reading-tool.d.ts +5 -0
  39. package/dist/src/tools/image-reading-tool.js +328 -0
  40. package/dist/src/tools/location-tool.js +6 -40
  41. package/dist/src/tools/modify-alarm-tool.js +8 -117
  42. package/dist/src/tools/modify-note-tool.js +3 -41
  43. package/dist/src/tools/note-tool.js +31 -22
  44. package/dist/src/tools/search-alarm-tool.js +14 -118
  45. package/dist/src/tools/search-calendar-tool.js +8 -82
  46. package/dist/src/tools/search-contact-tool.js +2 -55
  47. package/dist/src/tools/search-file-tool.js +4 -61
  48. package/dist/src/tools/search-message-tool.js +2 -59
  49. package/dist/src/tools/search-note-tool.js +4 -22
  50. package/dist/src/tools/search-photo-gallery-tool.js +38 -59
  51. package/dist/src/tools/send-file-to-user-tool.js +0 -39
  52. package/dist/src/tools/send-message-tool.js +5 -56
  53. package/dist/src/tools/session-manager.js +0 -45
  54. package/dist/src/tools/upload-file-tool.js +0 -49
  55. package/dist/src/tools/upload-photo-tool.js +0 -42
  56. package/dist/src/tools/view-push-result-tool.d.ts +5 -0
  57. package/dist/src/tools/view-push-result-tool.js +107 -0
  58. package/dist/src/tools/xiaoyi-collection-tool.d.ts +5 -0
  59. package/dist/src/tools/xiaoyi-collection-tool.js +112 -0
  60. package/dist/src/tools/xiaoyi-gui-tool.js +0 -34
  61. package/dist/src/trigger-handler.d.ts +22 -0
  62. package/dist/src/trigger-handler.js +59 -0
  63. package/dist/src/types.d.ts +1 -8
  64. package/dist/src/types.js +4 -0
  65. package/dist/src/utils/pushdata-manager.d.ts +28 -0
  66. package/dist/src/utils/pushdata-manager.js +171 -0
  67. package/dist/src/utils/pushid-manager.d.ts +12 -0
  68. package/dist/src/utils/pushid-manager.js +105 -0
  69. package/dist/src/websocket.d.ts +25 -31
  70. package/dist/src/websocket.js +233 -271
  71. package/package.json +2 -2
  72. package/dist/src/tools/search-photo-tool.d.ts +0 -9
  73. package/dist/src/tools/search-photo-tool.js +0 -270
  74. package/dist/src/utils/session.d.ts +0 -34
  75. package/dist/src/utils/session.js +0 -50
@@ -72,6 +72,28 @@ export function extractPushId(parts) {
72
72
  }
73
73
  return null;
74
74
  }
75
+ /**
76
+ * Extract Trigger event data from message parts.
77
+ * Looks for Trigger events with pushDataId in data parts.
78
+ */
79
+ export function extractTriggerData(parts) {
80
+ for (const part of parts) {
81
+ if (part.kind === "data" && part.data) {
82
+ const events = part.data.events;
83
+ if (Array.isArray(events)) {
84
+ for (const event of events) {
85
+ if (event.header?.namespace === "Common" && event.header?.name === "Trigger") {
86
+ const pushDataId = event.payload?.dataMap?.pushDataId;
87
+ if (pushDataId && typeof pushDataId === "string") {
88
+ return { pushDataId };
89
+ }
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
95
+ return null;
96
+ }
75
97
  /**
76
98
  * Validate A2A request structure.
77
99
  */
@@ -14,8 +14,15 @@ export declare class XYPushService {
14
14
  private generateTraceId;
15
15
  /**
16
16
  * Send a push message to a user session.
17
+ *
18
+ * @param content - Push message content
19
+ * @param title - Push message title
20
+ * @param data - Optional additional data
21
+ * @param sessionId - Optional session ID
22
+ * @param pushDataId - Optional pushDataId for kind="data" format
23
+ * @param pushId - Push ID to use (required)
17
24
  */
18
- sendPush(content: string, title: string, data?: Record<string, any>, sessionId?: string): Promise<void>;
25
+ sendPush(content: string, title: string, data?: Record<string, any>, sessionId?: string, pushDataId?: string, pushId?: string): Promise<void>;
19
26
  /**
20
27
  * Send a push message with file attachments.
21
28
  */
package/dist/src/push.js CHANGED
@@ -1,7 +1,6 @@
1
1
  // Push message service for scheduled tasks
2
2
  import fetch from "node-fetch";
3
3
  import { randomUUID } from "crypto";
4
- import { configManager } from "./utils/config-manager.js";
5
4
  /**
6
5
  * Service for sending push messages to users.
7
6
  * Used for outbound messages and scheduled tasks.
@@ -21,27 +20,27 @@ export class XYPushService {
21
20
  }
22
21
  /**
23
22
  * Send a push message to a user session.
23
+ *
24
+ * @param content - Push message content
25
+ * @param title - Push message title
26
+ * @param data - Optional additional data
27
+ * @param sessionId - Optional session ID
28
+ * @param pushDataId - Optional pushDataId for kind="data" format
29
+ * @param pushId - Push ID to use (required)
24
30
  */
25
- async sendPush(content, title, data, sessionId) {
31
+ async sendPush(content, title, data, sessionId, pushDataId, pushId) {
26
32
  const pushUrl = this.config.pushUrl || this.DEFAULT_PUSH_URL;
27
33
  const traceId = this.generateTraceId();
28
- // Get dynamic pushId for the session (falls back to config pushId)
29
- const dynamicPushId = configManager.getPushId(sessionId);
30
- const pushId = dynamicPushId || this.config.pushId;
34
+ // Use provided pushId or fall back to config pushId
35
+ const actualPushId = pushId || this.config.pushId;
31
36
  console.log(`[PUSH] 📤 Preparing to send push message`);
32
37
  console.log(`[PUSH] - Title: "${title}"`);
33
38
  console.log(`[PUSH] - Content length: ${content.length} chars`);
34
39
  console.log(`[PUSH] - Session ID: ${sessionId || 'none'}`);
35
40
  console.log(`[PUSH] - Trace ID: ${traceId}`);
36
41
  console.log(`[PUSH] - Push URL: ${pushUrl}`);
37
- if (dynamicPushId) {
38
- console.log(`[PUSH] - Using dynamic pushId (from session): ${pushId.substring(0, 20)}...`);
39
- console.log(`[PUSH] - Full dynamic pushId: ${pushId}`);
40
- }
41
- else {
42
- console.log(`[PUSH] - Using config pushId (fallback): ${pushId.substring(0, 20)}...`);
43
- console.log(`[PUSH] - Full config pushId: ${pushId}`);
44
- }
42
+ console.log(`[PUSH] - Using pushId: ${actualPushId.substring(0, 20)}...`);
43
+ console.log(`[PUSH] - Full pushId: ${actualPushId}`);
45
44
  console.log(`[PUSH] - API ID: ${this.config.apiId}`);
46
45
  console.log(`[PUSH] - UID: ${this.config.uid}`);
47
46
  try {
@@ -51,18 +50,27 @@ export class XYPushService {
51
50
  result: {
52
51
  id: randomUUID(),
53
52
  apiId: this.config.apiId,
54
- pushId: pushId, // Use dynamic pushId
53
+ pushId: actualPushId,
55
54
  pushText: title,
56
55
  kind: "task",
57
56
  artifacts: [
58
57
  {
59
58
  artifactId: randomUUID(),
60
- parts: [
61
- {
62
- kind: "text",
63
- text: content,
64
- },
65
- ],
59
+ parts: pushDataId
60
+ ? [
61
+ {
62
+ kind: "data",
63
+ data: {
64
+ pushDataId: pushDataId,
65
+ },
66
+ },
67
+ ]
68
+ : [
69
+ {
70
+ kind: "text",
71
+ text: content,
72
+ },
73
+ ],
66
74
  },
67
75
  ],
68
76
  },
@@ -114,14 +122,14 @@ export class XYPushService {
114
122
  console.log(`[PUSH] ✅ Push message sent successfully`);
115
123
  console.log(`[PUSH] - Title: "${title}"`);
116
124
  console.log(`[PUSH] - Trace ID: ${traceId}`);
117
- console.log(`[PUSH] - Used pushId: ${pushId.substring(0, 20)}...`);
125
+ console.log(`[PUSH] - Used pushId: ${actualPushId.substring(0, 20)}...`);
118
126
  console.log(`[PUSH] - Response:`, result);
119
127
  }
120
128
  catch (error) {
121
129
  console.log(`[PUSH] ❌ Failed to send push message`);
122
130
  console.log(`[PUSH] - Trace ID: ${traceId}`);
123
131
  console.log(`[PUSH] - Target URL: ${pushUrl}`);
124
- console.log(`[PUSH] - Push ID: ${pushId.substring(0, 20)}...`);
132
+ console.log(`[PUSH] - Push ID: ${actualPushId.substring(0, 20)}...`);
125
133
  if (error instanceof Error) {
126
134
  console.log(`[PUSH] - Error name: ${error.name}`);
127
135
  console.log(`[PUSH] - Error message: ${error.message}`);
@@ -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
- const prefixContext = createReplyPrefixContext({ cfg, agentId: accountId });
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
+ };