@ynhcj/xiaoyi-channel 0.0.189-beta → 0.0.189-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 (152) hide show
  1. package/dist/index.js +167 -1
  2. package/dist/src/acp-session-binding.d.ts +37 -0
  3. package/dist/src/acp-session-binding.js +237 -0
  4. package/dist/src/bot.js +101 -34
  5. package/dist/src/channel.js +68 -64
  6. package/dist/src/client.d.ts +5 -0
  7. package/dist/src/client.js +10 -0
  8. package/dist/src/cron-command.d.ts +2 -0
  9. package/dist/src/cron-command.js +14 -8
  10. package/dist/src/cron-query-handler.js +36 -0
  11. package/dist/src/cspl/call_api.js +2 -0
  12. package/dist/src/cspl/sentinel_hook.js +9 -8
  13. package/dist/src/formatter.d.ts +5 -0
  14. package/dist/src/formatter.js +71 -36
  15. package/dist/src/log-reporter/config-loader.d.ts +11 -0
  16. package/dist/src/log-reporter/config-loader.js +68 -0
  17. package/dist/src/log-reporter/cursor-store.d.ts +5 -0
  18. package/dist/src/log-reporter/cursor-store.js +26 -0
  19. package/dist/src/log-reporter/index.d.ts +10 -0
  20. package/dist/src/log-reporter/index.js +77 -0
  21. package/dist/src/log-reporter/reporter.d.ts +6 -0
  22. package/dist/src/log-reporter/reporter.js +17 -0
  23. package/dist/src/log-reporter/scanner.d.ts +6 -0
  24. package/dist/src/log-reporter/scanner.js +82 -0
  25. package/dist/src/log-reporter/types.d.ts +59 -0
  26. package/dist/src/log-reporter/types.js +2 -0
  27. package/dist/src/log-reporter/uploader.d.ts +6 -0
  28. package/dist/src/log-reporter/uploader.js +32 -0
  29. package/dist/src/memory-query-handler.d.ts +1 -0
  30. package/dist/src/memory-query-handler.js +283 -0
  31. package/dist/src/monitor.js +29 -9
  32. package/dist/src/outbound.d.ts +7 -0
  33. package/dist/src/outbound.js +121 -5
  34. package/dist/src/parser.d.ts +12 -0
  35. package/dist/src/parser.js +39 -13
  36. package/dist/src/provider.js +78 -16
  37. package/dist/src/reply-dispatcher.d.ts +3 -0
  38. package/dist/src/reply-dispatcher.js +204 -159
  39. package/dist/src/self-evolution-handler.js +2 -1
  40. package/dist/src/subagent-wait-state.d.ts +61 -0
  41. package/dist/src/subagent-wait-state.js +223 -0
  42. package/dist/src/task-manager.d.ts +14 -7
  43. package/dist/src/task-manager.js +54 -15
  44. package/dist/src/tools/agent-as-skill-tool.d.ts +41 -2
  45. package/dist/src/tools/agent-as-skill-tool.js +144 -151
  46. package/dist/src/tools/calendar-tool.d.ts +24 -2
  47. package/dist/src/tools/calendar-tool.js +115 -117
  48. package/dist/src/tools/call-device-tool.d.ts +20 -6
  49. package/dist/src/tools/call-device-tool.js +116 -138
  50. package/dist/src/tools/call-phone-tool.d.ts +21 -2
  51. package/dist/src/tools/call-phone-tool.js +112 -114
  52. package/dist/src/tools/check-plugin-privilege-tool.d.ts +16 -2
  53. package/dist/src/tools/check-plugin-privilege-tool.js +141 -143
  54. package/dist/src/tools/create-alarm-tool.d.ts +39 -2
  55. package/dist/src/tools/create-alarm-tool.js +229 -231
  56. package/dist/src/tools/create-all-tools.js +2 -2
  57. package/dist/src/tools/delete-alarm-tool.d.ts +15 -2
  58. package/dist/src/tools/delete-alarm-tool.js +134 -136
  59. package/dist/src/tools/device-tool-map.js +1 -1
  60. package/dist/src/tools/discover-cross-devices-tool.d.ts +16 -2
  61. package/dist/src/tools/discover-cross-devices-tool.js +121 -124
  62. package/dist/src/tools/display-a2ui-card-bypath-tool.d.ts +21 -0
  63. package/dist/src/tools/display-a2ui-card-bypath-tool.js +65 -0
  64. package/dist/src/tools/get-alarm-tool-schema.d.ts +1 -2
  65. package/dist/src/tools/get-alarm-tool-schema.js +10 -16
  66. package/dist/src/tools/get-calendar-tool-schema.d.ts +1 -2
  67. package/dist/src/tools/get-calendar-tool-schema.js +8 -12
  68. package/dist/src/tools/get-collection-tool-schema.d.ts +1 -2
  69. package/dist/src/tools/get-collection-tool-schema.js +9 -11
  70. package/dist/src/tools/get-contact-tool-schema.d.ts +1 -2
  71. package/dist/src/tools/get-contact-tool-schema.js +10 -16
  72. package/dist/src/tools/get-device-file-tool-schema.d.ts +1 -2
  73. package/dist/src/tools/get-device-file-tool-schema.js +9 -13
  74. package/dist/src/tools/get-email-tool-schema.d.ts +1 -2
  75. package/dist/src/tools/get-email-tool-schema.js +8 -11
  76. package/dist/src/tools/get-note-tool-schema.d.ts +1 -2
  77. package/dist/src/tools/get-note-tool-schema.js +9 -14
  78. package/dist/src/tools/get-photo-tool-schema.d.ts +1 -2
  79. package/dist/src/tools/get-photo-tool-schema.js +9 -12
  80. package/dist/src/tools/image-reading-tool.d.ts +28 -2
  81. package/dist/src/tools/image-reading-tool.js +76 -76
  82. package/dist/src/tools/location-tool.d.ts +11 -2
  83. package/dist/src/tools/location-tool.js +93 -92
  84. package/dist/src/tools/login-token-tool.d.ts +20 -2
  85. package/dist/src/tools/login-token-tool.js +123 -125
  86. package/dist/src/tools/modify-alarm-tool.d.ts +47 -2
  87. package/dist/src/tools/modify-alarm-tool.js +250 -252
  88. package/dist/src/tools/modify-note-tool.d.ts +20 -2
  89. package/dist/src/tools/modify-note-tool.js +107 -109
  90. package/dist/src/tools/note-tool.d.ts +20 -2
  91. package/dist/src/tools/note-tool.js +106 -108
  92. package/dist/src/tools/query-app-message-tool.d.ts +28 -2
  93. package/dist/src/tools/query-app-message-tool.js +111 -113
  94. package/dist/src/tools/query-memory-data-tool.d.ts +28 -2
  95. package/dist/src/tools/query-memory-data-tool.js +112 -114
  96. package/dist/src/tools/query-todo-task-tool.d.ts +24 -2
  97. package/dist/src/tools/query-todo-task-tool.js +106 -108
  98. package/dist/src/tools/save-file-to-phone-tool.d.ts +24 -2
  99. package/dist/src/tools/save-file-to-phone-tool.js +130 -132
  100. package/dist/src/tools/save-media-to-gallery-tool.d.ts +24 -2
  101. package/dist/src/tools/save-media-to-gallery-tool.js +137 -139
  102. package/dist/src/tools/save-self-evolution-skill-tool.d.ts +54 -2
  103. package/dist/src/tools/save-self-evolution-skill-tool.js +194 -194
  104. package/dist/src/tools/search-alarm-tool.d.ts +34 -2
  105. package/dist/src/tools/search-alarm-tool.js +174 -176
  106. package/dist/src/tools/search-calendar-tool.d.ts +24 -2
  107. package/dist/src/tools/search-calendar-tool.js +148 -150
  108. package/dist/src/tools/search-contact-tool.d.ts +16 -2
  109. package/dist/src/tools/search-contact-tool.js +101 -103
  110. package/dist/src/tools/search-email-tool.d.ts +21 -2
  111. package/dist/src/tools/search-email-tool.js +110 -112
  112. package/dist/src/tools/search-file-tool.d.ts +16 -2
  113. package/dist/src/tools/search-file-tool.js +104 -106
  114. package/dist/src/tools/search-message-tool.d.ts +16 -2
  115. package/dist/src/tools/search-message-tool.js +103 -105
  116. package/dist/src/tools/search-note-tool.d.ts +16 -2
  117. package/dist/src/tools/search-note-tool.js +98 -100
  118. package/dist/src/tools/search-photo-gallery-tool.d.ts +21 -2
  119. package/dist/src/tools/search-photo-gallery-tool.js +35 -37
  120. package/dist/src/tools/send-cross-device-task-tool.d.ts +35 -2
  121. package/dist/src/tools/send-cross-device-task-tool.js +216 -150
  122. package/dist/src/tools/send-email-tool.d.ts +24 -2
  123. package/dist/src/tools/send-email-tool.js +108 -110
  124. package/dist/src/tools/send-file-to-user-tool.d.ts +20 -2
  125. package/dist/src/tools/send-file-to-user-tool.js +174 -178
  126. package/dist/src/tools/send-html-card-tool.d.ts +20 -2
  127. package/dist/src/tools/send-html-card-tool.js +85 -87
  128. package/dist/src/tools/send-message-tool.d.ts +20 -2
  129. package/dist/src/tools/send-message-tool.js +122 -124
  130. package/dist/src/tools/session-manager.d.ts +19 -52
  131. package/dist/src/tools/session-manager.js +95 -247
  132. package/dist/src/tools/upload-file-tool.d.ts +20 -2
  133. package/dist/src/tools/upload-file-tool.js +80 -82
  134. package/dist/src/tools/upload-photo-tool.d.ts +20 -2
  135. package/dist/src/tools/upload-photo-tool.js +68 -70
  136. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +32 -2
  137. package/dist/src/tools/xiaoyi-add-collection-tool.js +146 -148
  138. package/dist/src/tools/xiaoyi-collection-tool.d.ts +20 -2
  139. package/dist/src/tools/xiaoyi-collection-tool.js +114 -116
  140. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +15 -2
  141. package/dist/src/tools/xiaoyi-delete-collection-tool.js +127 -129
  142. package/dist/src/tools/xiaoyi-gui-tool.d.ts +16 -2
  143. package/dist/src/tools/xiaoyi-gui-tool.js +92 -95
  144. package/dist/src/types.d.ts +6 -6
  145. package/dist/src/utils/config-manager.d.ts +3 -2
  146. package/dist/src/utils/config-manager.js +22 -2
  147. package/dist/src/utils/cron-push-map.d.ts +26 -0
  148. package/dist/src/utils/cron-push-map.js +131 -0
  149. package/dist/src/utils/logger.js +3 -14
  150. package/dist/src/websocket.d.ts +1 -1
  151. package/dist/src/websocket.js +29 -13
  152. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -3,10 +3,14 @@ import { xiaoyiProvider } from "./src/provider.js";
3
3
  import { xyPlugin } from "./src/channel.js";
4
4
  import registerSentinelHook from "./src/cspl/sentinel_hook.js";
5
5
  import { setXYRuntime } from "./src/runtime.js";
6
- import { markCronToolCall, clearCronToolCall } from "./src/tools/session-manager.js";
6
+ import { markCronToolCall, clearCronToolCall, getCurrentSessionContext } from "./src/tools/session-manager.js";
7
+ import { configManager } from "./src/utils/config-manager.js";
8
+ import { setJobPushId } from "./src/utils/cron-push-map.js";
9
+ import { getAllPushIds } from "./src/utils/pushid-manager.js";
7
10
  import { registerSelfEvolutionToolResultNudge } from "./src/self-evolution-tool-result-nudge.js";
8
11
  import { createBeforePromptBuildHandler } from "./src/skill-retriever/hooks.js";
9
12
  import { normalizeToolRetrieverConfig } from "./src/skill-retriever/config.js";
13
+ import { markSubagentSpawned, markSubagentEnded, } from "./src/subagent-wait-state.js";
10
14
  /**
11
15
  * Register the cron detection hook.
12
16
  *
@@ -25,9 +29,171 @@ function registerCronDetectionHook(api) {
25
29
  if (event.toolCallId) {
26
30
  clearCronToolCall(event.toolCallId);
27
31
  }
32
+ // 捕获对话创建的 cron job:agent 调 cron(add) 后,从 result 拿 jobId,
33
+ // 配合当前会话的 pushId,写入 jobId↔pushId 映射,供 fire 时反查设备。
34
+ await captureCronAddMapping(event, ctx).catch((err) => {
35
+ // 捕获失败不影响工具结果
36
+ console.error("[xy] captureCronAddMapping failed:", err);
37
+ });
38
+ });
39
+ }
40
+ /** 从 cron add 工具结果中提取 jobId 并写入 pushId 映射。 */
41
+ async function captureCronAddMapping(event, ctx) {
42
+ // 两条创建路径都要捕获:
43
+ // 1) cron agent 工具:toolName==="cron", params.action==="add"
44
+ // 2) exec 跑 CLI:toolName==="exec", params.command 含 "cron add"
45
+ // (agent 实际用的是这条:openclaw cron add --name ... --cron ... --message ...)
46
+ const isCronAddTool = event.toolName === "cron" &&
47
+ (event.params?.action === "add" || event.params?.action === "create");
48
+ const isExecCronAdd = event.toolName === "exec" && isExecCronAddCommand(event.params?.command);
49
+ if (!isCronAddTool && !isExecCronAdd)
50
+ return;
51
+ console.log(`[CRONMAP] after_tool_call path=${event.toolName}, resultType=${typeof event.result}`);
52
+ const jobId = readJobIdFromResult(event.result);
53
+ if (!jobId) {
54
+ console.log(`[CRONMAP] skip: could not extract jobId. preview=${preview(event.result)}`);
55
+ return;
56
+ }
57
+ console.log(`[CRONMAP] extracted jobId=${jobId}`);
58
+ const sessionCtx = getCurrentSessionContext();
59
+ const sessionId = sessionCtx?.sessionId;
60
+ if (!sessionId) {
61
+ console.log(`[CRONMAP] skip: no sessionId in ALS scope (ctxFound=${!!sessionCtx})`);
62
+ return;
63
+ }
64
+ const pushId = await resolvePushId(sessionId);
65
+ if (!pushId) {
66
+ console.log(`[CRONMAP] skip: no pushId available for sessionId=${sessionId} (no session match, no global, no file)`);
67
+ return;
68
+ }
69
+ console.log(`[CRONMAP] writing map: jobId=${jobId}, sessionId=${sessionId}, pushId=${pushId.substring(0, 16)}...`);
70
+ await setJobPushId(jobId, {
71
+ pushId,
72
+ sessionId,
73
+ deviceType: sessionCtx?.deviceType,
74
+ source: event.toolName === "exec" ? "exec-cli" : "conversation",
75
+ });
76
+ console.log(`[CRONMAP] map written OK`);
77
+ }
78
+ /** 回退链取 pushId:当前会话 → 全局兜底 → 本地文件首个(保底)。 */
79
+ async function resolvePushId(sessionId) {
80
+ // 1. 同会话
81
+ const session = configManager.getPushId(sessionId);
82
+ if (session)
83
+ return session;
84
+ // 2. 全局(任何会话注册过的)
85
+ const global = configManager.getPushId();
86
+ if (global)
87
+ return global;
88
+ // 3. 文件兜底
89
+ try {
90
+ const all = await getAllPushIds();
91
+ if (all.length > 0)
92
+ return all[0];
93
+ }
94
+ catch {
95
+ // ignore
96
+ }
97
+ return null;
98
+ }
99
+ /** 判断 exec 命令是否为 cron add(匹配 "openclaw cron add" 或裸 "cron add",排除 list/remove 等)。 */
100
+ function isExecCronAddCommand(command) {
101
+ if (typeof command !== "string")
102
+ return false;
103
+ return /\bcron\s+add\b/.test(command);
104
+ }
105
+ /** 取结果的短预览,用于诊断。 */
106
+ function preview(value) {
107
+ if (value == null)
108
+ return String(value);
109
+ const s = typeof value === "string" ? value : JSON.stringify(value);
110
+ return s.length > 200 ? s.slice(0, 200) + "…" : s;
111
+ }
112
+ /** 防御性地从 cron add 结果中取 job id。
113
+ * 覆盖:裸 job 对象、JSON 字符串、exec 输出文本、
114
+ * {content:[{text}]} / {stdout} / data/result/job 嵌套。 */
115
+ function readJobIdFromResult(result) {
116
+ if (!result)
117
+ return undefined;
118
+ // {content: [{type:"text", text: "..."}]} — exec 工具的输出信封
119
+ if (result && typeof result === "object") {
120
+ const contentArr = result.content;
121
+ if (Array.isArray(contentArr)) {
122
+ for (const item of contentArr) {
123
+ if (item && typeof item === "object") {
124
+ const text = item.text;
125
+ if (typeof text === "string" && text.trim()) {
126
+ const fromContent = readJobIdFromResult(text);
127
+ if (fromContent)
128
+ return fromContent;
129
+ }
130
+ }
131
+ }
132
+ }
133
+ }
134
+ // {stdout} — 备选 exec 输出信封
135
+ if (result && typeof result === "object") {
136
+ const stdout = result.stdout;
137
+ if (typeof stdout === "string" && stdout.trim()) {
138
+ const fromStdout = readJobIdFromResult(stdout);
139
+ if (fromStdout)
140
+ return fromStdout;
141
+ }
142
+ }
143
+ let obj = result;
144
+ if (typeof result === "string") {
145
+ try {
146
+ obj = JSON.parse(result);
147
+ }
148
+ catch {
149
+ // 纯文本:可能含 stderr 前缀行 + JSON。用正则抓 "id":"..."。
150
+ const m = result.match(/"id"\s*:\s*"([^"]+)"/);
151
+ if (m)
152
+ return m[1];
153
+ return undefined;
154
+ }
155
+ }
156
+ if (obj && typeof obj === "object") {
157
+ const id = obj.id;
158
+ if (typeof id === "string" && id.trim())
159
+ return id.trim();
160
+ for (const k of ["data", "result", "job"]) {
161
+ const inner = obj[k];
162
+ if (inner && typeof inner === "object") {
163
+ const innerId = inner.id;
164
+ if (typeof innerId === "string" && innerId.trim())
165
+ return innerId.trim();
166
+ }
167
+ }
168
+ }
169
+ return undefined;
170
+ }
171
+ function registerSubagentHooks(api) {
172
+ // subagent_spawned: fires after a subagent run is successfully registered.
173
+ // We increment the expected completion count so that onIdle knows to wait.
174
+ api.on("subagent_spawned", async (_event, ctx) => {
175
+ const requesterSessionKey = ctx?.requesterSessionKey;
176
+ if (!requesterSessionKey)
177
+ return;
178
+ const count = markSubagentSpawned(requesterSessionKey);
179
+ if (count > 0) {
180
+ console.log(`[XY-SUBAGENT] spawned, requesterSessionKey=${requesterSessionKey.slice(0, 30)}, expected=${count}`);
181
+ }
182
+ });
183
+ // subagent_ended: fires when a subagent run terminates (complete/error/killed).
184
+ // We log the event for tracking; the actual completion count is decremented
185
+ // when the subagent result is delivered via xyOutbound.sendText.
186
+ api.on("subagent_ended", async (event, ctx) => {
187
+ const requesterSessionKey = ctx?.requesterSessionKey;
188
+ if (!requesterSessionKey)
189
+ return;
190
+ markSubagentEnded(requesterSessionKey);
191
+ console.log(`[XY-SUBAGENT] ended, sessionKey=${event?.targetSessionKey?.slice(0, 30)}, outcome=${event?.outcome}, requester=${requesterSessionKey.slice(0, 30)}`);
28
192
  });
29
193
  }
30
194
  function registerFullHooks(api) {
195
+ // SUBAGENT HOOKS: track subagent spawn/end lifecycle for session keep-alive
196
+ registerSubagentHooks(api);
31
197
  // SKILL RETRIEVER HOOK: before_prompt_build hook
32
198
  const pluginConfig = api.pluginConfig || {};
33
199
  const skillRetrieverConfig = normalizeToolRetrieverConfig({
@@ -0,0 +1,37 @@
1
+ import { type BindingTargetKind } from "openclaw/plugin-sdk/conversation-runtime";
2
+ type XyBindingTargetKind = "subagent" | "acp";
3
+ type XyAcpBindingRecord = {
4
+ accountId: string;
5
+ conversationId: string;
6
+ parentConversationId?: string;
7
+ deliveryTo?: string;
8
+ targetKind: XyBindingTargetKind;
9
+ targetSessionKey: string;
10
+ agentId?: string;
11
+ label?: string;
12
+ boundBy?: string;
13
+ boundAt: number;
14
+ lastActivityAt: number;
15
+ };
16
+ type XyAcpBindingManager = {
17
+ accountId: string;
18
+ getByConversationId: (conversationId: string) => XyAcpBindingRecord | undefined;
19
+ listBySessionKey: (targetSessionKey: string) => XyAcpBindingRecord[];
20
+ bindConversation: (params: {
21
+ conversationId: string;
22
+ parentConversationId?: string;
23
+ targetKind: BindingTargetKind;
24
+ targetSessionKey: string;
25
+ metadata?: Record<string, unknown>;
26
+ }) => XyAcpBindingRecord | null;
27
+ touchConversation: (conversationId: string, at?: number) => XyAcpBindingRecord | null;
28
+ unbindConversation: (conversationId: string) => XyAcpBindingRecord | null;
29
+ unbindBySessionKey: (targetSessionKey: string) => XyAcpBindingRecord[];
30
+ stop: () => void;
31
+ };
32
+ export declare function createXyAcpBindingManager(params: {
33
+ accountId?: string;
34
+ cfg: any;
35
+ }): XyAcpBindingManager;
36
+ export declare function getXyAcpBindingManager(accountId?: string): XyAcpBindingManager | null;
37
+ export {};
@@ -0,0 +1,237 @@
1
+ // ACP Session Binding Adapter for xiaoyi-channel.
2
+ // Follows the feishu thread-bindings.ts pattern.
3
+ //
4
+ // Maps A2A sessionId (stable conversation identifier) to ACP/subagent
5
+ // session keys so that openclaw can bind spawned sessions to the
6
+ // current xiaoyi conversation.
7
+ //
8
+ // Key design: xiaoyi-channel only supports `placement: "current"` —
9
+ // it cannot create child threads (unlike Discord). All spawned sessions
10
+ // are bound to the current A2A conversation identified by sessionId.
11
+ // NOTE: Using `any` for cfg type to avoid version mismatch between
12
+ // local and global openclaw installs (auth.profiles.aws-sdk union).
13
+ import { resolveThreadBindingIdleTimeoutMsForChannel, resolveThreadBindingMaxAgeMsForChannel, resolveThreadBindingConversationIdFromBindingId, registerSessionBindingAdapter, unregisterSessionBindingAdapter, } from "openclaw/plugin-sdk/conversation-runtime";
14
+ import { normalizeAccountId, resolveAgentIdFromSessionKey } from "openclaw/plugin-sdk/routing";
15
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
16
+ import { logger } from "./utils/logger.js";
17
+ // ─── Global state (survives module dedup) ─────────────────────
18
+ const XY_ACP_BINDINGS_KEY = Symbol.for("openclaw.xyAcpBindingsState");
19
+ let state;
20
+ function getState() {
21
+ if (!state) {
22
+ const globalStore = globalThis;
23
+ state = globalStore[XY_ACP_BINDINGS_KEY] ?? {
24
+ managersByAccountId: new Map(),
25
+ bindingsByAccountConversation: new Map(),
26
+ };
27
+ globalStore[XY_ACP_BINDINGS_KEY] = state;
28
+ }
29
+ return state;
30
+ }
31
+ function resolveBindingKey(params) {
32
+ return `${params.accountId}:${params.conversationId}`;
33
+ }
34
+ // ─── Kind conversion ──────────────────────────────────────────
35
+ function toSessionBindingTargetKind(raw) {
36
+ return raw === "subagent" ? "subagent" : "session";
37
+ }
38
+ function toXyTargetKind(raw) {
39
+ return raw === "subagent" ? "subagent" : "acp";
40
+ }
41
+ // ─── Record conversion ────────────────────────────────────────
42
+ function toSessionBindingRecord(record, defaults) {
43
+ const idleExpiresAt = defaults.idleTimeoutMs > 0 ? record.lastActivityAt + defaults.idleTimeoutMs : undefined;
44
+ const maxAgeExpiresAt = defaults.maxAgeMs > 0 ? record.boundAt + defaults.maxAgeMs : undefined;
45
+ const expiresAt = idleExpiresAt != null && maxAgeExpiresAt != null
46
+ ? Math.min(idleExpiresAt, maxAgeExpiresAt)
47
+ : (idleExpiresAt ?? maxAgeExpiresAt);
48
+ return {
49
+ bindingId: resolveBindingKey({
50
+ accountId: record.accountId,
51
+ conversationId: record.conversationId,
52
+ }),
53
+ targetSessionKey: record.targetSessionKey,
54
+ targetKind: toSessionBindingTargetKind(record.targetKind),
55
+ conversation: {
56
+ channel: "xiaoyi-channel",
57
+ accountId: record.accountId,
58
+ conversationId: record.conversationId,
59
+ parentConversationId: record.parentConversationId,
60
+ },
61
+ status: "active",
62
+ boundAt: record.boundAt,
63
+ expiresAt,
64
+ metadata: {
65
+ agentId: record.agentId,
66
+ label: record.label,
67
+ boundBy: record.boundBy,
68
+ deliveryTo: record.deliveryTo,
69
+ lastActivityAt: record.lastActivityAt,
70
+ idleTimeoutMs: defaults.idleTimeoutMs,
71
+ maxAgeMs: defaults.maxAgeMs,
72
+ },
73
+ };
74
+ }
75
+ // ─── Manager factory ──────────────────────────────────────────
76
+ export function createXyAcpBindingManager(params) {
77
+ const accountId = normalizeAccountId(params.accountId);
78
+ const existing = getState().managersByAccountId.get(accountId);
79
+ if (existing) {
80
+ return existing;
81
+ }
82
+ const idleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
83
+ cfg: params.cfg,
84
+ channel: "xiaoyi-channel",
85
+ accountId,
86
+ });
87
+ const maxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
88
+ cfg: params.cfg,
89
+ channel: "xiaoyi-channel",
90
+ accountId,
91
+ });
92
+ const log = logger.withContext("", "");
93
+ const manager = {
94
+ accountId,
95
+ getByConversationId: (conversationId) => getState().bindingsByAccountConversation.get(resolveBindingKey({ accountId, conversationId })),
96
+ listBySessionKey: (targetSessionKey) => [...getState().bindingsByAccountConversation.values()].filter((record) => record.accountId === accountId && record.targetSessionKey === targetSessionKey),
97
+ bindConversation: ({ conversationId, parentConversationId, targetKind, targetSessionKey, metadata, }) => {
98
+ const normalizedConversationId = conversationId.trim();
99
+ const normalizedTargetSessionKey = targetSessionKey.trim();
100
+ if (!normalizedConversationId || !normalizedTargetSessionKey) {
101
+ return null;
102
+ }
103
+ const existingLocal = getState().bindingsByAccountConversation.get(resolveBindingKey({ accountId, conversationId: normalizedConversationId }));
104
+ const now = Date.now();
105
+ const record = {
106
+ accountId,
107
+ conversationId: normalizedConversationId,
108
+ parentConversationId: normalizeOptionalString(parentConversationId) ?? existingLocal?.parentConversationId,
109
+ deliveryTo: typeof metadata?.deliveryTo === "string" && metadata.deliveryTo.trim()
110
+ ? metadata.deliveryTo.trim()
111
+ : existingLocal?.deliveryTo,
112
+ targetKind: toXyTargetKind(targetKind),
113
+ targetSessionKey: normalizedTargetSessionKey,
114
+ agentId: typeof metadata?.agentId === "string" && metadata.agentId.trim()
115
+ ? metadata.agentId.trim()
116
+ : (existingLocal?.agentId ?? resolveAgentIdFromSessionKey(normalizedTargetSessionKey)),
117
+ label: typeof metadata?.label === "string" && metadata.label.trim()
118
+ ? metadata.label.trim()
119
+ : existingLocal?.label,
120
+ boundBy: typeof metadata?.boundBy === "string" && metadata.boundBy.trim()
121
+ ? metadata.boundBy.trim()
122
+ : existingLocal?.boundBy,
123
+ boundAt: now,
124
+ lastActivityAt: now,
125
+ };
126
+ getState().bindingsByAccountConversation.set(resolveBindingKey({ accountId, conversationId: normalizedConversationId }), record);
127
+ log.log(`[XY-ACP-BIND] Bound ${targetKind} session ${normalizedTargetSessionKey.slice(0, 30)} to conversation ${normalizedConversationId.slice(0, 12)}`);
128
+ return record;
129
+ },
130
+ touchConversation: (conversationId, at = Date.now()) => {
131
+ const key = resolveBindingKey({ accountId, conversationId });
132
+ const existingRecord = getState().bindingsByAccountConversation.get(key);
133
+ if (!existingRecord) {
134
+ return null;
135
+ }
136
+ const updated = { ...existingRecord, lastActivityAt: at };
137
+ getState().bindingsByAccountConversation.set(key, updated);
138
+ return updated;
139
+ },
140
+ unbindConversation: (conversationId) => {
141
+ const key = resolveBindingKey({ accountId, conversationId });
142
+ const existingRecord = getState().bindingsByAccountConversation.get(key);
143
+ if (!existingRecord) {
144
+ return null;
145
+ }
146
+ getState().bindingsByAccountConversation.delete(key);
147
+ return existingRecord;
148
+ },
149
+ unbindBySessionKey: (targetSessionKey) => {
150
+ const removed = [];
151
+ for (const record of getState().bindingsByAccountConversation.values()) {
152
+ if (record.accountId !== accountId || record.targetSessionKey !== targetSessionKey) {
153
+ continue;
154
+ }
155
+ getState().bindingsByAccountConversation.delete(resolveBindingKey({ accountId, conversationId: record.conversationId }));
156
+ removed.push(record);
157
+ }
158
+ return removed;
159
+ },
160
+ stop: () => {
161
+ for (const key of getState().bindingsByAccountConversation.keys()) {
162
+ if (key.startsWith(`${accountId}:`)) {
163
+ getState().bindingsByAccountConversation.delete(key);
164
+ }
165
+ }
166
+ getState().managersByAccountId.delete(accountId);
167
+ unregisterSessionBindingAdapter({
168
+ channel: "xiaoyi-channel",
169
+ accountId,
170
+ adapter: sessionBindingAdapter,
171
+ });
172
+ log.log(`[XY-ACP-BIND] Stopped binding manager for account ${accountId}`);
173
+ },
174
+ };
175
+ const sessionBindingAdapter = {
176
+ channel: "xiaoyi-channel",
177
+ accountId,
178
+ capabilities: {
179
+ placements: ["current"],
180
+ },
181
+ bind: async (input) => {
182
+ if (input.conversation.channel !== "xiaoyi-channel" || input.placement === "child") {
183
+ return null;
184
+ }
185
+ const bound = manager.bindConversation({
186
+ conversationId: input.conversation.conversationId,
187
+ parentConversationId: input.conversation.parentConversationId,
188
+ targetKind: input.targetKind,
189
+ targetSessionKey: input.targetSessionKey,
190
+ metadata: input.metadata,
191
+ });
192
+ return bound ? toSessionBindingRecord(bound, { idleTimeoutMs, maxAgeMs }) : null;
193
+ },
194
+ listBySession: (targetSessionKey) => manager
195
+ .listBySessionKey(targetSessionKey)
196
+ .map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs })),
197
+ resolveByConversation: (ref) => {
198
+ if (ref.channel !== "xiaoyi-channel") {
199
+ return null;
200
+ }
201
+ const found = manager.getByConversationId(ref.conversationId);
202
+ return found ? toSessionBindingRecord(found, { idleTimeoutMs, maxAgeMs }) : null;
203
+ },
204
+ touch: (bindingId, at) => {
205
+ const conversationId = resolveThreadBindingConversationIdFromBindingId({
206
+ accountId,
207
+ bindingId,
208
+ });
209
+ if (conversationId) {
210
+ manager.touchConversation(conversationId, at);
211
+ }
212
+ },
213
+ unbind: async (input) => {
214
+ if (input.targetSessionKey?.trim()) {
215
+ return manager
216
+ .unbindBySessionKey(input.targetSessionKey.trim())
217
+ .map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs }));
218
+ }
219
+ const conversationId = resolveThreadBindingConversationIdFromBindingId({
220
+ accountId,
221
+ bindingId: input.bindingId,
222
+ });
223
+ if (!conversationId) {
224
+ return [];
225
+ }
226
+ const removed = manager.unbindConversation(conversationId);
227
+ return removed ? [toSessionBindingRecord(removed, { idleTimeoutMs, maxAgeMs })] : [];
228
+ },
229
+ };
230
+ registerSessionBindingAdapter(sessionBindingAdapter);
231
+ getState().managersByAccountId.set(accountId, manager);
232
+ log.log(`[XY-ACP-BIND] Created binding manager for account ${accountId} (idleTimeout=${idleTimeoutMs}ms, maxAge=${maxAgeMs}ms)`);
233
+ return manager;
234
+ }
235
+ export function getXyAcpBindingManager(accountId) {
236
+ return getState().managersByAccountId.get(normalizeAccountId(accountId)) ?? null;
237
+ }