@ynhcj/xiaoyi-channel 0.0.20-beta → 0.0.20-release20260606
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 +2 -15
- package/dist/index.js +323 -10
- package/dist/provider-discovery.d.ts +2 -0
- package/dist/provider-discovery.js +4 -0
- package/dist/src/acp-session-binding.d.ts +37 -0
- package/dist/src/acp-session-binding.js +237 -0
- package/dist/src/approval-bridge.d.ts +48 -0
- package/dist/src/approval-bridge.js +382 -0
- package/dist/src/bot.d.ts +9 -0
- package/dist/src/bot.js +392 -130
- package/dist/src/channel.js +110 -17
- package/dist/src/client.d.ts +4 -3
- package/dist/src/client.js +34 -61
- package/dist/src/compaction-provider.d.ts +50 -0
- package/dist/src/compaction-provider.js +185 -0
- package/dist/src/config.js +2 -2
- package/dist/src/conversation/conversation-manager.d.ts +87 -0
- package/dist/src/conversation/conversation-manager.js +391 -0
- package/dist/src/conversation/conversation-session.d.ts +44 -0
- package/dist/src/conversation/conversation-session.js +17 -0
- package/dist/src/conversation/cron-buffer.d.ts +25 -0
- package/dist/src/conversation/cron-buffer.js +168 -0
- package/dist/src/conversation/outbound-gateway.d.ts +39 -0
- package/dist/src/conversation/outbound-gateway.js +81 -0
- package/dist/src/conversation/steer-service.d.ts +29 -0
- package/dist/src/conversation/steer-service.js +52 -0
- package/dist/src/cron-command.d.ts +17 -0
- package/dist/src/cron-command.js +55 -0
- package/dist/src/cron-query-handler.d.ts +27 -0
- package/dist/src/cron-query-handler.js +615 -0
- package/dist/src/cron-recovery.d.ts +25 -0
- package/dist/src/cron-recovery.js +587 -0
- package/dist/src/cspl/call_api.d.ts +2 -0
- package/dist/src/cspl/call_api.js +112 -0
- package/dist/src/cspl/config.d.ts +16 -0
- package/dist/src/cspl/config.js +113 -0
- package/dist/src/cspl/configs.json +10 -0
- package/dist/src/cspl/constants.d.ts +70 -0
- package/dist/src/cspl/constants.js +64 -0
- package/dist/src/cspl/sentinel_hook.d.ts +2 -0
- package/dist/src/cspl/sentinel_hook.js +103 -0
- package/dist/src/cspl/skill_scope_hook.d.ts +17 -0
- package/dist/src/cspl/skill_scope_hook.js +125 -0
- package/dist/src/cspl/steer-context.d.ts +21 -0
- package/dist/src/cspl/steer-context.js +78 -0
- package/dist/src/cspl/upload_file.d.ts +1 -0
- package/dist/src/cspl/upload_file.js +216 -0
- package/dist/src/cspl/utils.d.ts +25 -0
- package/dist/src/cspl/utils.js +315 -0
- package/dist/src/dispatch/bot.d.ts +20 -0
- package/dist/src/dispatch/bot.js +510 -0
- package/dist/src/dispatch/monitor.d.ts +17 -0
- package/dist/src/dispatch/monitor.js +333 -0
- package/dist/src/dispatch/outbound.d.ts +7 -0
- package/dist/src/dispatch/outbound.js +272 -0
- package/dist/src/dispatch/reply-dispatcher.d.ts +22 -0
- package/dist/src/dispatch/reply-dispatcher.js +505 -0
- package/dist/src/file-download.js +2 -4
- package/dist/src/file-upload.d.ts +10 -0
- package/dist/src/file-upload.js +249 -17
- package/dist/src/formatter.d.ts +95 -1
- package/dist/src/formatter.js +340 -82
- package/dist/src/heartbeat.js +4 -7
- package/dist/src/log-reporter/cursor-store.d.ts +5 -0
- package/dist/src/log-reporter/cursor-store.js +26 -0
- package/dist/src/log-reporter/index.d.ts +10 -0
- package/dist/src/log-reporter/index.js +210 -0
- package/dist/src/log-reporter/openclaw-parser.d.ts +18 -0
- package/dist/src/log-reporter/openclaw-parser.js +94 -0
- package/dist/src/log-reporter/path-resolver.d.ts +5 -0
- package/dist/src/log-reporter/path-resolver.js +50 -0
- package/dist/src/log-reporter/reporter.d.ts +6 -0
- package/dist/src/log-reporter/reporter.js +56 -0
- package/dist/src/log-reporter/scanner.d.ts +10 -0
- package/dist/src/log-reporter/scanner.js +78 -0
- package/dist/src/log-reporter/types.d.ts +58 -0
- package/dist/src/log-reporter/types.js +2 -0
- package/dist/src/log-reporter/uploader.d.ts +7 -0
- package/dist/src/log-reporter/uploader.js +55 -0
- package/dist/src/login-token-handler.d.ts +8 -0
- package/dist/src/login-token-handler.js +63 -0
- package/dist/src/memory-query-handler.d.ts +1 -0
- package/dist/src/memory-query-handler.js +283 -0
- package/dist/src/message-queue.d.ts +17 -0
- package/dist/src/message-queue.js +52 -0
- package/dist/src/monitor.js +193 -34
- 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 +69 -38
- package/dist/src/parser.d.ts +33 -1
- package/dist/src/parser.js +135 -0
- package/dist/src/provider.d.ts +3 -0
- package/dist/src/provider.js +777 -0
- package/dist/src/push.d.ts +19 -2
- package/dist/src/push.js +128 -56
- package/dist/src/reply-dispatcher.d.ts +10 -0
- package/dist/src/reply-dispatcher.js +333 -162
- package/dist/src/runtime.d.ts +3 -11
- package/dist/src/runtime.js +6 -18
- package/dist/src/self-evolution-handler.d.ts +7 -0
- package/dist/src/self-evolution-handler.js +149 -0
- package/dist/src/self-evolution-keyword.d.ts +9 -0
- package/dist/src/self-evolution-keyword.js +147 -0
- package/dist/src/self-evolution-tool-result-nudge.d.ts +3 -0
- package/dist/src/self-evolution-tool-result-nudge.js +96 -0
- package/dist/src/sensitive-redactor.d.ts +4 -0
- package/dist/src/sensitive-redactor.js +364 -0
- package/dist/src/skill-retriever/config.d.ts +4 -0
- package/dist/src/skill-retriever/config.js +25 -0
- package/dist/src/skill-retriever/hooks.d.ts +22 -0
- package/dist/src/skill-retriever/hooks.js +92 -0
- package/dist/src/skill-retriever/tool-search.d.ts +19 -0
- package/dist/src/skill-retriever/tool-search.js +186 -0
- package/dist/src/skill-retriever/types.d.ts +37 -0
- package/dist/src/skill-retriever/types.js +1 -0
- package/dist/src/subagent-wait-state.d.ts +73 -0
- package/dist/src/subagent-wait-state.js +240 -0
- package/dist/src/task-manager.d.ts +42 -0
- package/dist/src/task-manager.js +101 -0
- package/dist/src/tools/agent-as-skill-tool.d.ts +46 -0
- package/dist/src/tools/agent-as-skill-tool.js +183 -0
- package/dist/src/tools/calendar-tool.d.ts +24 -1
- package/dist/src/tools/calendar-tool.js +13 -47
- package/dist/src/tools/call-device-tool.d.ts +20 -0
- package/dist/src/tools/call-device-tool.js +131 -0
- package/dist/src/tools/call-phone-tool.d.ts +24 -0
- package/dist/src/tools/call-phone-tool.js +122 -0
- package/dist/src/tools/check-plugin-privilege-tool.d.ts +20 -0
- package/dist/src/tools/check-plugin-privilege-tool.js +180 -0
- package/dist/src/tools/create-alarm-tool.d.ts +45 -0
- package/dist/src/tools/create-alarm-tool.js +333 -0
- package/dist/src/tools/delete-alarm-tool.d.ts +25 -0
- package/dist/src/tools/delete-alarm-tool.js +170 -0
- package/dist/src/tools/device-tool-map.d.ts +4 -0
- package/dist/src/tools/device-tool-map.js +45 -0
- package/dist/src/tools/discover-cross-devices-tool.d.ts +16 -0
- package/dist/src/tools/discover-cross-devices-tool.js +232 -0
- package/dist/src/tools/display-a2ui-card-bypath-tool.d.ts +21 -0
- package/dist/src/tools/display-a2ui-card-bypath-tool.js +65 -0
- package/dist/src/tools/get-alarm-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-alarm-tool-schema.js +11 -0
- package/dist/src/tools/get-calendar-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-calendar-tool-schema.js +9 -0
- package/dist/src/tools/get-collection-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-collection-tool-schema.js +10 -0
- package/dist/src/tools/get-contact-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-contact-tool-schema.js +11 -0
- package/dist/src/tools/get-device-file-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-device-file-tool-schema.js +10 -0
- package/dist/src/tools/get-email-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-email-tool-schema.js +9 -0
- package/dist/src/tools/get-note-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-note-tool-schema.js +10 -0
- package/dist/src/tools/get-photo-tool-schema.d.ts +16 -0
- package/dist/src/tools/get-photo-tool-schema.js +10 -0
- package/dist/src/tools/hmos-cli.d.ts +109 -0
- package/dist/src/tools/hmos-cli.js +504 -0
- package/dist/src/tools/image-reading-tool.d.ts +32 -0
- package/dist/src/tools/image-reading-tool.js +246 -0
- package/dist/src/tools/invoke.d.ts +88 -0
- package/dist/src/tools/invoke.js +1209 -0
- package/dist/src/tools/location-tool.d.ts +11 -1
- package/dist/src/tools/location-tool.js +17 -49
- package/dist/src/tools/login-token-tool.d.ts +24 -0
- package/dist/src/tools/login-token-tool.js +142 -0
- package/dist/src/tools/modify-alarm-tool.d.ts +55 -0
- package/dist/src/tools/modify-alarm-tool.js +364 -0
- package/dist/src/tools/modify-note-tool.d.ts +20 -1
- package/dist/src/tools/modify-note-tool.js +11 -50
- package/dist/src/tools/note-tool.d.ts +20 -1
- package/dist/src/tools/note-tool.js +38 -30
- package/dist/src/tools/query-app-message-tool.d.ts +31 -0
- package/dist/src/tools/query-app-message-tool.js +138 -0
- package/dist/src/tools/query-memory-data-tool.d.ts +31 -0
- package/dist/src/tools/query-memory-data-tool.js +154 -0
- package/dist/src/tools/query-todo-task-tool.d.ts +27 -0
- package/dist/src/tools/query-todo-task-tool.js +133 -0
- package/dist/src/tools/save-file-to-phone-tool.d.ts +28 -0
- package/dist/src/tools/save-file-to-phone-tool.js +165 -0
- package/dist/src/tools/save-media-to-gallery-tool.d.ts +28 -0
- package/dist/src/tools/save-media-to-gallery-tool.js +173 -0
- package/dist/src/tools/save-self-evolution-skill-tool.d.ts +54 -0
- package/dist/src/tools/save-self-evolution-skill-tool.js +410 -0
- package/dist/src/tools/schema-tool-factory.d.ts +27 -0
- package/dist/src/tools/schema-tool-factory.js +32 -0
- package/dist/src/tools/search-alarm-tool.d.ts +41 -0
- package/dist/src/tools/search-alarm-tool.js +277 -0
- package/dist/src/tools/search-calendar-tool.d.ts +24 -1
- package/dist/src/tools/search-calendar-tool.js +18 -91
- package/dist/src/tools/search-contact-tool.d.ts +16 -1
- package/dist/src/tools/search-contact-tool.js +10 -64
- package/dist/src/tools/search-email-tool.d.ts +25 -0
- package/dist/src/tools/search-email-tool.js +136 -0
- package/dist/src/tools/search-file-tool.d.ts +20 -0
- package/dist/src/tools/search-file-tool.js +125 -0
- package/dist/src/tools/search-message-tool.d.ts +20 -0
- package/dist/src/tools/search-message-tool.js +116 -0
- package/dist/src/tools/search-note-tool.d.ts +16 -1
- package/dist/src/tools/search-note-tool.js +12 -31
- package/dist/src/tools/search-photo-gallery-tool.d.ts +21 -1
- package/dist/src/tools/search-photo-gallery-tool.js +57 -70
- package/dist/src/tools/send-cross-device-task-tool.d.ts +35 -0
- package/dist/src/tools/send-cross-device-task-tool.js +365 -0
- package/dist/src/tools/send-email-tool.d.ts +27 -0
- package/dist/src/tools/send-email-tool.js +134 -0
- package/dist/src/tools/send-file-to-user-tool.d.ts +24 -0
- package/dist/src/tools/send-file-to-user-tool.js +305 -0
- package/dist/src/tools/send-html-card-tool.d.ts +25 -0
- package/dist/src/tools/send-html-card-tool.js +111 -0
- package/dist/src/tools/send-message-tool.d.ts +24 -0
- package/dist/src/tools/send-message-tool.js +139 -0
- package/dist/src/tools/session-manager.d.ts +40 -18
- package/dist/src/tools/session-manager.js +149 -62
- package/dist/src/tools/timestamp-to-utc8-tool.d.ts +12 -0
- package/dist/src/tools/timestamp-to-utc8-tool.js +104 -0
- package/dist/src/tools/upload-file-tool.d.ts +32 -0
- package/dist/src/tools/upload-file-tool.js +216 -0
- package/dist/src/tools/upload-photo-tool.d.ts +20 -1
- package/dist/src/tools/upload-photo-tool.js +22 -55
- 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-add-collection-tool.d.ts +35 -0
- package/dist/src/tools/xiaoyi-add-collection-tool.js +192 -0
- package/dist/src/tools/xiaoyi-append-reference.d.ts +47 -0
- package/dist/src/tools/xiaoyi-append-reference.js +107 -0
- package/dist/src/tools/xiaoyi-collection-tool.d.ts +24 -0
- package/dist/src/tools/xiaoyi-collection-tool.js +147 -0
- package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +18 -0
- package/dist/src/tools/xiaoyi-delete-collection-tool.js +162 -0
- package/dist/src/tools/xiaoyi-gui-tool.d.ts +21 -0
- package/dist/src/tools/xiaoyi-gui-tool.js +130 -0
- package/dist/src/transport/client.d.ts +36 -0
- package/dist/src/transport/client.js +120 -0
- package/dist/src/transport/heartbeat.d.ts +39 -0
- package/dist/src/transport/heartbeat.js +99 -0
- package/dist/src/transport/message-queue.d.ts +17 -0
- package/dist/src/transport/message-queue.js +52 -0
- package/dist/src/transport/push.d.ts +40 -0
- package/dist/src/transport/push.js +218 -0
- package/dist/src/transport/websocket.d.ts +124 -0
- package/dist/src/transport/websocket.js +839 -0
- package/dist/src/trigger-handler.d.ts +22 -0
- package/dist/src/trigger-handler.js +55 -0
- package/dist/src/types.d.ts +26 -9
- package/dist/src/types.js +4 -0
- package/dist/src/utils/config-manager.d.ts +3 -2
- package/dist/src/utils/config-manager.js +25 -8
- package/dist/src/utils/cron-push-map.d.ts +26 -0
- package/dist/src/utils/cron-push-map.js +131 -0
- package/dist/src/utils/logger.d.ts +8 -0
- package/dist/src/utils/logger.js +128 -18
- package/dist/src/utils/pushdata-manager.d.ts +28 -0
- package/dist/src/utils/pushdata-manager.js +167 -0
- package/dist/src/utils/pushid-manager.d.ts +12 -0
- package/dist/src/utils/pushid-manager.js +104 -0
- package/dist/src/utils/runtime-manager.d.ts +7 -0
- package/dist/src/utils/runtime-manager.js +61 -0
- package/dist/src/utils/self-evolution-manager.d.ts +10 -0
- package/dist/src/utils/self-evolution-manager.js +69 -0
- package/dist/src/utils/skills-logger.d.ts +5 -0
- package/dist/src/utils/skills-logger.js +76 -0
- package/dist/src/utils/throw.d.ts +5 -0
- package/dist/src/utils/throw.js +10 -0
- package/dist/src/utils/tool-call-nudge-manager.d.ts +16 -0
- package/dist/src/utils/tool-call-nudge-manager.js +47 -0
- package/dist/src/websocket.d.ts +33 -32
- package/dist/src/websocket.js +574 -282
- package/openclaw.plugin.json +26 -0
- package/package.json +9 -8
- 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
package/dist/index.d.ts
CHANGED
|
@@ -1,16 +1,3 @@
|
|
|
1
|
-
import type
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Xiaoyi Channel Plugin Entry Point.
|
|
5
|
-
* Exports the plugin for OpenClaw to load.
|
|
6
|
-
* Located at root level following feishu pattern for proper plugin registration.
|
|
7
|
-
*/
|
|
8
|
-
declare const plugin: {
|
|
9
|
-
id: string;
|
|
10
|
-
name: string;
|
|
11
|
-
description: string;
|
|
12
|
-
configSchema: import("openclaw/plugin-sdk").OpenClawPluginConfigSchema;
|
|
13
|
-
register(api: OpenClawPluginApi): void;
|
|
14
|
-
};
|
|
1
|
+
import { type OpenClawPluginDefinition } from "openclaw/plugin-sdk/core";
|
|
2
|
+
declare const plugin: OpenClawPluginDefinition;
|
|
15
3
|
export default plugin;
|
|
16
|
-
export { xyPlugin };
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,334 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { definePluginEntry } from "openclaw/plugin-sdk/core";
|
|
2
|
+
import { xiaoyiProvider } from "./src/provider.js";
|
|
3
|
+
import { xiaoyiCompactionProvider } from "./src/compaction-provider.js";
|
|
2
4
|
import { xyPlugin } from "./src/channel.js";
|
|
5
|
+
import registerSentinelHook from "./src/cspl/sentinel_hook.js";
|
|
3
6
|
import { setXYRuntime } from "./src/runtime.js";
|
|
7
|
+
import { markCronToolCall, clearCronToolCall, getCurrentSessionContext } from "./src/tools/session-manager.js";
|
|
8
|
+
import { configManager } from "./src/utils/config-manager.js";
|
|
9
|
+
import { setJobPushId } from "./src/utils/cron-push-map.js";
|
|
10
|
+
import { getAllPushIds } from "./src/utils/pushid-manager.js";
|
|
11
|
+
import { registerSelfEvolutionToolResultNudge } from "./src/self-evolution-tool-result-nudge.js";
|
|
12
|
+
import { createBeforePromptBuildHandler } from "./src/skill-retriever/hooks.js";
|
|
13
|
+
import { normalizeToolRetrieverConfig } from "./src/skill-retriever/config.js";
|
|
14
|
+
import { registerCLIHook } from "./src/tools/hmos-cli.js";
|
|
15
|
+
import { recoverCronState } from "./src/cron-recovery.js";
|
|
16
|
+
import { writeSkillUsage } from "./src/utils/skills-logger.js";
|
|
17
|
+
import { logger } from "./src/utils/logger.js";
|
|
4
18
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
19
|
+
* Parse a file path string to detect if it refers to a SKILL.md file within
|
|
20
|
+
* a skills directory. Returns the skill name (parent directory) if so.
|
|
21
|
+
*
|
|
22
|
+
* Matches paths like:
|
|
23
|
+
* ~/.openclaw/workspace/skills/my-skill/SKILL.md
|
|
24
|
+
* /home/user/core_skills/my-skill/SKILL.md
|
|
25
|
+
* skills/my-skill/SKILL.md
|
|
8
26
|
*/
|
|
9
|
-
|
|
27
|
+
function extractSkillNameFromPath(filePath) {
|
|
28
|
+
if (typeof filePath !== "string" || !filePath)
|
|
29
|
+
return null;
|
|
30
|
+
// Normalize common path prefixes
|
|
31
|
+
const normalized = filePath.replace(/^~\//, "/home/").replace(/\\/g, "/");
|
|
32
|
+
// Match: .../skills/<skillName>/SKILL.md or .../skills/<skillName>/...
|
|
33
|
+
// Also match: .../core_skills/<skillName>/SKILL.md
|
|
34
|
+
const match = normalized.match(/\/(?:core_)?skills\/([^/]+)\/SKILL\.md$/i);
|
|
35
|
+
return match ? match[1] : null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Register the skills diagnostic event listener via after_tool_call hook.
|
|
39
|
+
*
|
|
40
|
+
* When openclaw fires a `skill.used` diagnostic event, the skill's SKILL.md
|
|
41
|
+
* is typically read by the model first. We detect SKILL.md reads through
|
|
42
|
+
* the `after_tool_call` hook and write the skill name to the skills log.
|
|
43
|
+
*/
|
|
44
|
+
function registerSkillsDiagnosticHook(api) {
|
|
45
|
+
api.on("after_tool_call", async (event, _ctx) => {
|
|
46
|
+
if (event.toolName !== "read")
|
|
47
|
+
return;
|
|
48
|
+
const skillName = extractSkillNameFromPath(event.params?.path);
|
|
49
|
+
if (skillName) {
|
|
50
|
+
writeSkillUsage(skillName);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Register the cron detection hook.
|
|
56
|
+
*
|
|
57
|
+
* When openclaw's cron runner triggers a tool call, the sessionKey has the
|
|
58
|
+
* format "cron:<jobId>". We use this to mark the toolCallId in a global Map
|
|
59
|
+
* so that sendCommand() can route the command through the push channel
|
|
60
|
+
* instead of the (non-existent) WebSocket session.
|
|
61
|
+
*/
|
|
62
|
+
function registerCronDetectionHook(api) {
|
|
63
|
+
api.on("before_tool_call", async (event, ctx) => {
|
|
64
|
+
if (ctx.sessionKey?.startsWith("cron:") && event.toolCallId) {
|
|
65
|
+
markCronToolCall(event.toolCallId);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
api.on("after_tool_call", async (event, ctx) => {
|
|
69
|
+
if (event.toolCallId) {
|
|
70
|
+
clearCronToolCall(event.toolCallId);
|
|
71
|
+
}
|
|
72
|
+
// 捕获对话创建的 cron job:agent 调 cron(add) 后,从 result 拿 jobId,
|
|
73
|
+
// 配合当前会话的 pushId,写入 jobId↔pushId 映射,供 fire 时反查设备。
|
|
74
|
+
await captureCronAddMapping(event, ctx).catch((err) => {
|
|
75
|
+
// 捕获失败不影响工具结果
|
|
76
|
+
console.error("[xy] captureCronAddMapping failed:", err);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** 从 cron add 工具结果中提取 jobId 并写入 pushId 映射。 */
|
|
81
|
+
async function captureCronAddMapping(event, ctx) {
|
|
82
|
+
// 两条创建路径都要捕获:
|
|
83
|
+
// 1) cron agent 工具:toolName==="cron", params.action==="add"
|
|
84
|
+
// 2) exec 跑 CLI:toolName==="exec", params.command 含 "cron add"
|
|
85
|
+
// (agent 实际用的是这条:openclaw cron add --name ... --cron ... --message ...)
|
|
86
|
+
const isCronAddTool = event.toolName === "cron" &&
|
|
87
|
+
(event.params?.action === "add" || event.params?.action === "create");
|
|
88
|
+
const isExecCronAdd = event.toolName === "exec" && isExecCronAddCommand(event.params?.command);
|
|
89
|
+
if (!isCronAddTool && !isExecCronAdd)
|
|
90
|
+
return;
|
|
91
|
+
console.log(`[CRONMAP] after_tool_call path=${event.toolName}, resultType=${typeof event.result}`);
|
|
92
|
+
const jobId = readJobIdFromResult(event.result);
|
|
93
|
+
if (!jobId) {
|
|
94
|
+
console.log(`[CRONMAP] skip: could not extract jobId. preview=${preview(event.result)}`);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
console.log(`[CRONMAP] extracted jobId=${jobId}`);
|
|
98
|
+
const sessionCtx = getCurrentSessionContext();
|
|
99
|
+
const sessionId = sessionCtx?.sessionId;
|
|
100
|
+
if (!sessionId) {
|
|
101
|
+
console.log(`[CRONMAP] skip: no sessionId in ALS scope (ctxFound=${!!sessionCtx})`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const pushId = await resolvePushId(sessionId);
|
|
105
|
+
if (!pushId) {
|
|
106
|
+
console.log(`[CRONMAP] skip: no pushId available for sessionId=${sessionId} (no session match, no global, no file)`);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
console.log(`[CRONMAP] writing map: jobId=${jobId}, sessionId=${sessionId}, pushId=${pushId.substring(0, 16)}...`);
|
|
110
|
+
await setJobPushId(jobId, {
|
|
111
|
+
pushId,
|
|
112
|
+
sessionId,
|
|
113
|
+
deviceType: sessionCtx?.deviceType,
|
|
114
|
+
source: event.toolName === "exec" ? "exec-cli" : "conversation",
|
|
115
|
+
});
|
|
116
|
+
console.log(`[CRONMAP] map written OK`);
|
|
117
|
+
}
|
|
118
|
+
/** 回退链取 pushId:当前会话 → 全局兜底 → 本地文件首个(保底)。 */
|
|
119
|
+
async function resolvePushId(sessionId) {
|
|
120
|
+
// 1. 同会话
|
|
121
|
+
const session = configManager.getPushId(sessionId);
|
|
122
|
+
if (session)
|
|
123
|
+
return session;
|
|
124
|
+
// 2. 全局(任何会话注册过的)
|
|
125
|
+
const global = configManager.getPushId();
|
|
126
|
+
if (global)
|
|
127
|
+
return global;
|
|
128
|
+
// 3. 文件兜底
|
|
129
|
+
try {
|
|
130
|
+
const all = await getAllPushIds();
|
|
131
|
+
if (all.length > 0)
|
|
132
|
+
return all[0];
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// ignore
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
/** 判断 exec 命令是否为 cron add(匹配 "openclaw cron add" 或裸 "cron add",排除 list/remove 等)。 */
|
|
140
|
+
function isExecCronAddCommand(command) {
|
|
141
|
+
if (typeof command !== "string")
|
|
142
|
+
return false;
|
|
143
|
+
return /\bcron\s+add\b/.test(command);
|
|
144
|
+
}
|
|
145
|
+
/** 取结果的短预览,用于诊断。 */
|
|
146
|
+
function preview(value) {
|
|
147
|
+
if (value == null)
|
|
148
|
+
return String(value);
|
|
149
|
+
const s = typeof value === "string" ? value : JSON.stringify(value);
|
|
150
|
+
return s.length > 200 ? s.slice(0, 200) + "…" : s;
|
|
151
|
+
}
|
|
152
|
+
/** 防御性地从 cron add 结果中取 job id。
|
|
153
|
+
* 覆盖:裸 job 对象、JSON 字符串、exec 输出文本、
|
|
154
|
+
* {content:[{text}]} / {stdout} / data/result/job 嵌套。 */
|
|
155
|
+
function readJobIdFromResult(result) {
|
|
156
|
+
if (!result)
|
|
157
|
+
return undefined;
|
|
158
|
+
// {content: [{type:"text", text: "..."}]} — exec 工具的输出信封
|
|
159
|
+
if (result && typeof result === "object") {
|
|
160
|
+
const contentArr = result.content;
|
|
161
|
+
if (Array.isArray(contentArr)) {
|
|
162
|
+
for (const item of contentArr) {
|
|
163
|
+
if (item && typeof item === "object") {
|
|
164
|
+
const text = item.text;
|
|
165
|
+
if (typeof text === "string" && text.trim()) {
|
|
166
|
+
const fromContent = readJobIdFromResult(text);
|
|
167
|
+
if (fromContent)
|
|
168
|
+
return fromContent;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// {stdout} — 备选 exec 输出信封
|
|
175
|
+
if (result && typeof result === "object") {
|
|
176
|
+
const stdout = result.stdout;
|
|
177
|
+
if (typeof stdout === "string" && stdout.trim()) {
|
|
178
|
+
const fromStdout = readJobIdFromResult(stdout);
|
|
179
|
+
if (fromStdout)
|
|
180
|
+
return fromStdout;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
let obj = result;
|
|
184
|
+
if (typeof result === "string") {
|
|
185
|
+
try {
|
|
186
|
+
obj = JSON.parse(result);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// 纯文本:可能含 stderr 前缀行 + JSON。用正则抓 "id":"..."。
|
|
190
|
+
const m = result.match(/"id"\s*:\s*"([^"]+)"/);
|
|
191
|
+
if (m)
|
|
192
|
+
return m[1];
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (obj && typeof obj === "object") {
|
|
197
|
+
const id = obj.id;
|
|
198
|
+
if (typeof id === "string" && id.trim())
|
|
199
|
+
return id.trim();
|
|
200
|
+
for (const k of ["data", "result", "job"]) {
|
|
201
|
+
const inner = obj[k];
|
|
202
|
+
if (inner && typeof inner === "object") {
|
|
203
|
+
const innerId = inner.id;
|
|
204
|
+
if (typeof innerId === "string" && innerId.trim())
|
|
205
|
+
return innerId.trim();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
// ── Gateway startup: cron state recovery ────────────────────────────────────
|
|
212
|
+
/**
|
|
213
|
+
* Register the gateway_start hook for cron state recovery.
|
|
214
|
+
*
|
|
215
|
+
* On gateway startup, checks .openclaw/cron/ for legacy JSON/JSONL files
|
|
216
|
+
* and migrates them into the SQLite state database:
|
|
217
|
+
* - Reads legacy jobs.json + jobs-state.json → imports into cron_jobs table
|
|
218
|
+
* - Reads legacy runs/*.jsonl → imports into cron_run_logs table
|
|
219
|
+
* - Archives migrated files with .migrated suffix
|
|
220
|
+
*
|
|
221
|
+
* Pattern follows legacy-store-migration.ts and legacy-run-log-migration.ts:
|
|
222
|
+
* check → load → import into SQLite → archive old files.
|
|
223
|
+
*/
|
|
224
|
+
function registerCronRecoveryHook(api) {
|
|
225
|
+
api.on("gateway_start", async (_event, _ctx) => {
|
|
226
|
+
const logTag = "[CRON-RECOVERY-HOOK]";
|
|
227
|
+
const startTime = Date.now();
|
|
228
|
+
logger.log(`${logTag} ═══════════════════════════════════════════`);
|
|
229
|
+
logger.log(`${logTag} gateway_start fired — checking for legacy cron files`);
|
|
230
|
+
logger.log(`${logTag} Timestamp: ${new Date().toISOString()}`);
|
|
231
|
+
logger.log(`${logTag} Plugin registration mode: ${api.registrationMode ?? "unknown"}`);
|
|
232
|
+
let result;
|
|
233
|
+
try {
|
|
234
|
+
result = await recoverCronState();
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
238
|
+
const errStack = err instanceof Error ? err.stack : undefined;
|
|
239
|
+
logger.error(`${logTag} cron state recovery threw: ${errMsg}`);
|
|
240
|
+
if (errStack)
|
|
241
|
+
logger.error(`${logTag} Stack: ${errStack}`);
|
|
242
|
+
// Don't let a recovery failure block gateway startup.
|
|
243
|
+
logger.log(`${logTag} Recovery failed after ${Date.now() - startTime}ms — gateway startup continues`);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const elapsed = Date.now() - startTime;
|
|
247
|
+
if (result.recovered) {
|
|
248
|
+
logger.log(`${logTag} ✅ Migration performed successfully in ${elapsed}ms:` +
|
|
249
|
+
` storeMigrated=${result.storeMigrated}, ` +
|
|
250
|
+
` runLogFilesImported=${result.runLogFilesImported}`);
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
logger.log(`${logTag} ℹ️ No legacy cron files migrated in ${elapsed}ms ` +
|
|
254
|
+
`(nothing to migrate or database unavailable)`);
|
|
255
|
+
}
|
|
256
|
+
// Log diagnostics summary
|
|
257
|
+
const warnings = result.diagnostics.filter((d) => d.includes("skipping") || d.includes("locked") || d.includes("unavailable"));
|
|
258
|
+
const errors = result.diagnostics.filter((d) => d.includes("error") || d.includes("failed") || d.includes("Failed"));
|
|
259
|
+
if (warnings.length > 0) {
|
|
260
|
+
logger.warn(`${logTag} ${warnings.length} warning(s) from migration:`);
|
|
261
|
+
for (const w of warnings) {
|
|
262
|
+
logger.warn(`${logTag} ⚠ ${w}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (errors.length > 0) {
|
|
266
|
+
logger.error(`${logTag} ${errors.length} error(s) from migration:`);
|
|
267
|
+
for (const e of errors) {
|
|
268
|
+
logger.error(`${logTag} ✗ ${e}`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (warnings.length === 0 && errors.length === 0) {
|
|
272
|
+
logger.log(`${logTag} All diagnostics clean, no warnings or errors`);
|
|
273
|
+
}
|
|
274
|
+
logger.log(`${logTag} ═══════════════════════════════════════════`);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function registerFullHooks(api) {
|
|
278
|
+
// SKILL RETRIEVER HOOK: before_prompt_build hook
|
|
279
|
+
const pluginConfig = api.pluginConfig || {};
|
|
280
|
+
const skillRetrieverConfig = normalizeToolRetrieverConfig({
|
|
281
|
+
enabled: pluginConfig.skillRetrieverEnabled ?? true,
|
|
282
|
+
maxTools: pluginConfig.skillRetrieverMaxTools ?? 2,
|
|
283
|
+
includeUninstalledOnly: true,
|
|
284
|
+
envFilePath: "~/.openclaw/.xiaoyienv",
|
|
285
|
+
timeoutMs: pluginConfig.skillRetrieverTimeoutMs ?? 1000,
|
|
286
|
+
});
|
|
287
|
+
const beforePromptBuildHandler = createBeforePromptBuildHandler(skillRetrieverConfig);
|
|
288
|
+
api.on("before_prompt_build", async (event, ctx) => {
|
|
289
|
+
logger.log(`[BEFORE_PROMPT_BUILD] hook fired, sessionKey=${ctx.sessionKey || "undefined"}, sessionId=${ctx.sessionId || "undefined"}`);
|
|
290
|
+
return beforePromptBuildHandler(event, ctx);
|
|
291
|
+
});
|
|
292
|
+
registerSelfEvolutionToolResultNudge(api);
|
|
293
|
+
}
|
|
294
|
+
const plugin = definePluginEntry({
|
|
10
295
|
id: "xiaoyi-channel",
|
|
11
296
|
name: "Xiaoyi Channel",
|
|
12
297
|
description: "Xiaoyi channel plugin - Xiaoyi A2A protocol integration",
|
|
13
|
-
configSchema: emptyPluginConfigSchema(),
|
|
14
298
|
register(api) {
|
|
15
|
-
|
|
299
|
+
// Always register the provider so wrapStreamFn/prepareExtraParams work
|
|
300
|
+
// in ALL registration modes (not just "full").
|
|
301
|
+
api.registerProvider(xiaoyiProvider);
|
|
302
|
+
// Register the compaction provider so openclaw's safeguard hook uses
|
|
303
|
+
// our summarization path (which injects x-hag-trace-id) instead of the
|
|
304
|
+
// built-in LLM path that bypasses wrapStreamFn.
|
|
305
|
+
api.registerCompactionProvider(xiaoyiCompactionProvider);
|
|
306
|
+
if (api.registrationMode === "cli-metadata") {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (api.registrationMode === "tool-discovery") {
|
|
310
|
+
registerFullHooks(api);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
// Register channel plugin and set runtime
|
|
16
314
|
api.registerChannel({ plugin: xyPlugin });
|
|
315
|
+
setXYRuntime(api.runtime);
|
|
316
|
+
if (api.registrationMode === "discovery") {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (api.registrationMode === "full") {
|
|
320
|
+
registerFullHooks(api);
|
|
321
|
+
// CSPL sentinel hook: before_tool_call + after_tool_call security scanning
|
|
322
|
+
registerSentinelHook(api);
|
|
323
|
+
// Cron detection hook: marks toolCallIds from cron sessions
|
|
324
|
+
registerCronDetectionHook(api);
|
|
325
|
+
// CLI exec hook: intercepts built-in exec for HarmonyOS CLI skill tools
|
|
326
|
+
registerCLIHook(api);
|
|
327
|
+
// Cron recovery hook: prunes stale cron-push-map and pushData on gateway startup
|
|
328
|
+
registerCronRecoveryHook(api);
|
|
329
|
+
// Skills diagnostic hook: log skill usage (detected via SKILL.md reads)
|
|
330
|
+
registerSkillsDiagnosticHook(api);
|
|
331
|
+
}
|
|
17
332
|
},
|
|
18
|
-
};
|
|
333
|
+
});
|
|
19
334
|
export default plugin;
|
|
20
|
-
// Also export the plugin directly for testing
|
|
21
|
-
export { xyPlugin };
|
|
@@ -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
|
+
}
|