@ynhcj/xiaoyi-channel 0.0.99-beta → 0.0.99-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 (133) hide show
  1. package/dist/index.d.ts +4 -10
  2. package/dist/index.js +76 -66
  3. package/dist/provider-discovery.d.ts +2 -0
  4. package/dist/provider-discovery.js +4 -0
  5. package/dist/src/bot.js +29 -4
  6. package/dist/src/channel.js +2 -20
  7. package/dist/src/client.js +31 -22
  8. package/dist/src/cspl/call-api.js +6 -5
  9. package/dist/src/file-download.js +4 -3
  10. package/dist/src/file-upload.js +19 -18
  11. package/dist/src/formatter.d.ts +2 -0
  12. package/dist/src/formatter.js +9 -28
  13. package/dist/src/heartbeat.js +1 -1
  14. package/dist/src/message-queue.d.ts +17 -0
  15. package/dist/src/message-queue.js +51 -0
  16. package/dist/src/monitor.js +63 -14
  17. package/dist/src/outbound.js +19 -18
  18. package/dist/src/provider.d.ts +2 -1
  19. package/dist/src/provider.js +211 -41
  20. package/dist/src/push.js +16 -15
  21. package/dist/src/reply-dispatcher.js +12 -3
  22. package/dist/src/runtime.d.ts +3 -11
  23. package/dist/src/runtime.js +6 -18
  24. package/dist/src/self-evolution-handler.d.ts +6 -0
  25. package/dist/src/self-evolution-handler.js +100 -7
  26. package/dist/src/self-evolution-keyword.d.ts +9 -0
  27. package/dist/src/self-evolution-keyword.js +147 -0
  28. package/dist/src/self-evolution-tool-result-nudge.d.ts +3 -0
  29. package/dist/src/self-evolution-tool-result-nudge.js +96 -0
  30. package/dist/src/skill-retriever/hooks.js +8 -12
  31. package/dist/src/skill-retriever/tool-search.js +22 -8
  32. package/dist/src/skill-retriever/types.d.ts +2 -0
  33. package/dist/src/steer-injector.js +1 -1
  34. package/dist/src/task-manager.d.ts +4 -0
  35. package/dist/src/task-manager.js +12 -1
  36. package/dist/src/tools/calendar-tool.d.ts +2 -1
  37. package/dist/src/tools/calendar-tool.js +112 -116
  38. package/dist/src/tools/call-device-tool.d.ts +2 -1
  39. package/dist/src/tools/call-device-tool.js +126 -103
  40. package/dist/src/tools/call-phone-tool.d.ts +2 -1
  41. package/dist/src/tools/call-phone-tool.js +109 -113
  42. package/dist/src/tools/create-alarm-tool.d.ts +2 -1
  43. package/dist/src/tools/create-alarm-tool.js +227 -231
  44. package/dist/src/tools/create-all-tools.d.ts +16 -0
  45. package/dist/src/tools/create-all-tools.js +50 -0
  46. package/dist/src/tools/delete-alarm-tool.d.ts +2 -1
  47. package/dist/src/tools/delete-alarm-tool.js +131 -135
  48. package/dist/src/tools/get-alarm-tool-schema.d.ts +2 -1
  49. package/dist/src/tools/get-alarm-tool-schema.js +16 -10
  50. package/dist/src/tools/get-calendar-tool-schema.d.ts +2 -1
  51. package/dist/src/tools/get-calendar-tool-schema.js +12 -8
  52. package/dist/src/tools/get-collection-tool-schema.d.ts +2 -1
  53. package/dist/src/tools/get-collection-tool-schema.js +11 -9
  54. package/dist/src/tools/get-contact-tool-schema.d.ts +2 -1
  55. package/dist/src/tools/get-contact-tool-schema.js +16 -10
  56. package/dist/src/tools/get-device-file-tool-schema.d.ts +2 -1
  57. package/dist/src/tools/get-device-file-tool-schema.js +13 -9
  58. package/dist/src/tools/get-email-tool-schema.d.ts +2 -1
  59. package/dist/src/tools/get-email-tool-schema.js +11 -8
  60. package/dist/src/tools/get-note-tool-schema.d.ts +2 -1
  61. package/dist/src/tools/get-note-tool-schema.js +14 -9
  62. package/dist/src/tools/get-photo-tool-schema.d.ts +2 -1
  63. package/dist/src/tools/get-photo-tool-schema.js +12 -9
  64. package/dist/src/tools/image-reading-tool.d.ts +2 -1
  65. package/dist/src/tools/image-reading-tool.js +86 -90
  66. package/dist/src/tools/location-tool.d.ts +2 -1
  67. package/dist/src/tools/location-tool.js +87 -91
  68. package/dist/src/tools/login-token-tool.d.ts +3 -2
  69. package/dist/src/tools/login-token-tool.js +114 -117
  70. package/dist/src/tools/modify-alarm-tool.d.ts +2 -1
  71. package/dist/src/tools/modify-alarm-tool.js +232 -236
  72. package/dist/src/tools/modify-note-tool.d.ts +2 -1
  73. package/dist/src/tools/modify-note-tool.js +104 -108
  74. package/dist/src/tools/note-tool.d.ts +2 -1
  75. package/dist/src/tools/note-tool.js +103 -107
  76. package/dist/src/tools/query-app-message-tool.d.ts +2 -1
  77. package/dist/src/tools/query-app-message-tool.js +108 -111
  78. package/dist/src/tools/query-memory-data-tool.d.ts +2 -1
  79. package/dist/src/tools/query-memory-data-tool.js +109 -112
  80. package/dist/src/tools/query-todo-task-tool.d.ts +2 -1
  81. package/dist/src/tools/query-todo-task-tool.js +103 -106
  82. package/dist/src/tools/save-file-to-phone-tool.d.ts +2 -1
  83. package/dist/src/tools/save-file-to-phone-tool.js +127 -131
  84. package/dist/src/tools/save-media-to-gallery-tool.d.ts +2 -1
  85. package/dist/src/tools/save-media-to-gallery-tool.js +134 -138
  86. package/dist/src/tools/save-self-evolution-skill-tool.d.ts +2 -0
  87. package/dist/src/tools/save-self-evolution-skill-tool.js +410 -0
  88. package/dist/src/tools/search-alarm-tool.d.ts +2 -1
  89. package/dist/src/tools/search-alarm-tool.js +171 -175
  90. package/dist/src/tools/search-calendar-tool.d.ts +2 -1
  91. package/dist/src/tools/search-calendar-tool.js +145 -149
  92. package/dist/src/tools/search-contact-tool.d.ts +2 -1
  93. package/dist/src/tools/search-contact-tool.js +98 -102
  94. package/dist/src/tools/search-email-tool.d.ts +2 -1
  95. package/dist/src/tools/search-email-tool.js +107 -111
  96. package/dist/src/tools/search-file-tool.d.ts +2 -1
  97. package/dist/src/tools/search-file-tool.js +99 -103
  98. package/dist/src/tools/search-message-tool.d.ts +2 -1
  99. package/dist/src/tools/search-message-tool.js +100 -104
  100. package/dist/src/tools/search-note-tool.d.ts +2 -1
  101. package/dist/src/tools/search-note-tool.js +95 -99
  102. package/dist/src/tools/search-photo-gallery-tool.d.ts +2 -1
  103. package/dist/src/tools/search-photo-gallery-tool.js +34 -38
  104. package/dist/src/tools/send-email-tool.d.ts +2 -1
  105. package/dist/src/tools/send-email-tool.js +105 -108
  106. package/dist/src/tools/send-file-to-user-tool.d.ts +2 -1
  107. package/dist/src/tools/send-file-to-user-tool.js +154 -155
  108. package/dist/src/tools/send-message-tool.d.ts +2 -1
  109. package/dist/src/tools/send-message-tool.js +119 -123
  110. package/dist/src/tools/session-manager.d.ts +21 -6
  111. package/dist/src/tools/session-manager.js +147 -18
  112. package/dist/src/tools/upload-file-tool.d.ts +2 -1
  113. package/dist/src/tools/upload-file-tool.js +78 -82
  114. package/dist/src/tools/upload-photo-tool.d.ts +2 -1
  115. package/dist/src/tools/upload-photo-tool.js +69 -73
  116. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +2 -1
  117. package/dist/src/tools/xiaoyi-add-collection-tool.js +143 -147
  118. package/dist/src/tools/xiaoyi-collection-tool.d.ts +2 -1
  119. package/dist/src/tools/xiaoyi-collection-tool.js +111 -115
  120. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +2 -1
  121. package/dist/src/tools/xiaoyi-delete-collection-tool.js +124 -128
  122. package/dist/src/tools/xiaoyi-gui-tool.d.ts +2 -1
  123. package/dist/src/tools/xiaoyi-gui-tool.js +84 -88
  124. package/dist/src/utils/logger.js +20 -18
  125. package/dist/src/utils/runtime-manager.js +24 -2
  126. package/dist/src/utils/self-evolution-manager.d.ts +10 -0
  127. package/dist/src/utils/self-evolution-manager.js +69 -0
  128. package/dist/src/utils/tool-call-nudge-manager.d.ts +16 -0
  129. package/dist/src/utils/tool-call-nudge-manager.js +47 -0
  130. package/dist/src/websocket.d.ts +3 -0
  131. package/dist/src/websocket.js +81 -28
  132. package/openclaw.plugin.json +22 -0
  133. package/package.json +3 -3
@@ -1,138 +1,134 @@
1
1
  import { getXYWebSocketManager } from "../client.js";
2
2
  import { sendCommand } from "../formatter.js";
3
- import { getCurrentSessionContext } from "./session-manager.js";
4
3
  /**
5
4
  * XY send message tool - sends SMS message on user's device.
6
5
  * Requires phoneNumber (with +86 prefix) and content parameters.
7
6
  */
8
- export const sendMessageTool = {
9
- name: "send_message",
10
- label: "Send Message",
11
- description: "通过手机发送短信。需要提供接收方手机号码和短信内容。手机号码会自动添加+86前缀(如果没有的话)。注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。",
12
- parameters: {
13
- type: "object",
14
- properties: {
15
- phoneNumber: {
16
- type: "string",
17
- description: "接收方手机号码(会自动添加+86前缀)",
18
- },
19
- content: {
20
- type: "string",
21
- description: "短信内容",
7
+ export function createSendMessageTool(ctx) {
8
+ const { config, sessionId, taskId, messageId } = ctx;
9
+ return {
10
+ name: "send_message",
11
+ label: "Send Message",
12
+ description: "通过手机发送短信。需要提供接收方手机号码和短信内容。手机号码会自动添加+86前缀(如果没有的话)。注意:操作超时时间为60秒,请勿重复调用此工具,如果超时或失败,最多重试一次。回复约束:如果工具返回没有授权或者其他报错,只需要完整描述没有授权或者其他报错内容即可,不需要主动给用户提供解决方案,例如告诉用户如何授权,如何解决报错等都是不需要的,请严格遵守。",
13
+ parameters: {
14
+ type: "object",
15
+ properties: {
16
+ phoneNumber: {
17
+ type: "string",
18
+ description: "接收方手机号码(会自动添加+86前缀)",
19
+ },
20
+ content: {
21
+ type: "string",
22
+ description: "短信内容",
23
+ },
22
24
  },
25
+ required: ["phoneNumber", "content"],
23
26
  },
24
- required: ["phoneNumber", "content"],
25
- },
26
- async execute(toolCallId, params) {
27
- // Validate phoneNumber parameter
28
- if (!params.phoneNumber || typeof params.phoneNumber !== "string" || params.phoneNumber.trim() === "") {
29
- throw new Error("Missing required parameter: phoneNumber must be a non-empty string");
30
- }
31
- // Validate content parameter
32
- if (!params.content || typeof params.content !== "string" || params.content.trim() === "") {
33
- throw new Error("Missing required parameter: content must be a non-empty string");
34
- }
35
- // Normalize phone number: add +86 prefix if not present
36
- let phoneNumber = params.phoneNumber.trim();
37
- if (!phoneNumber.startsWith("+86")) {
38
- // Remove leading 0 if present (e.g., 086 -> 86)
39
- if (phoneNumber.startsWith("0")) {
40
- phoneNumber = phoneNumber.substring(1);
27
+ async execute(toolCallId, params) {
28
+ // Validate phoneNumber parameter
29
+ if (!params.phoneNumber || typeof params.phoneNumber !== "string" || params.phoneNumber.trim() === "") {
30
+ throw new Error("Missing required parameter: phoneNumber must be a non-empty string");
41
31
  }
42
- // Remove +86 or 86 prefix if already present to avoid duplication
43
- if (phoneNumber.startsWith("86")) {
44
- phoneNumber = phoneNumber.substring(2);
32
+ // Validate content parameter
33
+ if (!params.content || typeof params.content !== "string" || params.content.trim() === "") {
34
+ throw new Error("Missing required parameter: content must be a non-empty string");
45
35
  }
46
- phoneNumber = `+86${phoneNumber}`;
47
- }
48
- // Get session context
49
- const sessionContext = getCurrentSessionContext();
50
- if (!sessionContext) {
51
- throw new Error("No active XY session found. Send message tool can only be used during an active conversation.");
52
- }
53
- const { config, sessionId, taskId, messageId } = sessionContext;
54
- // Get WebSocket manager
55
- const wsManager = getXYWebSocketManager(config);
56
- // Build SendShortMessage command
57
- const command = {
58
- header: {
59
- namespace: "Common",
60
- name: "Action",
61
- },
62
- payload: {
63
- cardParam: {},
64
- executeParam: {
65
- executeMode: "background",
66
- intentName: "SendShortMessage",
67
- bundleName: "com.huawei.hmos.aidispatchservice",
68
- needUnlock: true,
69
- actionResponse: true,
70
- appType: "OHOS_APP",
71
- timeOut: 5,
72
- intentParam: {
73
- phoneNumber: phoneNumber,
74
- content: params.content.trim(),
75
- },
76
- permissionId: [],
77
- achieveType: "INTENT",
36
+ // Normalize phone number: add +86 prefix if not present
37
+ let phoneNumber = params.phoneNumber.trim();
38
+ if (!phoneNumber.startsWith("+86")) {
39
+ // Remove leading 0 if present (e.g., 086 -> 86)
40
+ if (phoneNumber.startsWith("0")) {
41
+ phoneNumber = phoneNumber.substring(1);
42
+ }
43
+ // Remove +86 or 86 prefix if already present to avoid duplication
44
+ if (phoneNumber.startsWith("86")) {
45
+ phoneNumber = phoneNumber.substring(2);
46
+ }
47
+ phoneNumber = `+86${phoneNumber}`;
48
+ }
49
+ // Get WebSocket manager
50
+ const wsManager = getXYWebSocketManager(config);
51
+ // Build SendShortMessage command
52
+ const command = {
53
+ header: {
54
+ namespace: "Common",
55
+ name: "Action",
78
56
  },
79
- responses: [
80
- {
81
- resultCode: "",
82
- displayText: "",
83
- ttsText: "",
57
+ payload: {
58
+ cardParam: {},
59
+ executeParam: {
60
+ executeMode: "background",
61
+ intentName: "SendShortMessage",
62
+ bundleName: "com.huawei.hmos.aidispatchservice",
63
+ needUnlock: true,
64
+ actionResponse: true,
65
+ appType: "OHOS_APP",
66
+ timeOut: 5,
67
+ intentParam: {
68
+ phoneNumber: phoneNumber,
69
+ content: params.content.trim(),
70
+ },
71
+ permissionId: [],
72
+ achieveType: "INTENT",
84
73
  },
85
- ],
86
- needUploadResult: true,
87
- noHalfPage: false,
88
- pageControlRelated: false,
89
- },
90
- };
91
- // Send command and wait for response (60 second timeout)
92
- return new Promise((resolve, reject) => {
93
- const timeout = setTimeout(() => {
94
- wsManager.off("data-event", handler);
95
- reject(new Error("发送短信超时(60秒)"));
96
- }, 60000);
97
- // Listen for data events from WebSocket
98
- const handler = (event) => {
99
- if (event.intentName === "SendShortMessage") {
100
- clearTimeout(timeout);
74
+ responses: [
75
+ {
76
+ resultCode: "",
77
+ displayText: "",
78
+ ttsText: "",
79
+ },
80
+ ],
81
+ needUploadResult: true,
82
+ noHalfPage: false,
83
+ pageControlRelated: false,
84
+ },
85
+ };
86
+ // Send command and wait for response (60 second timeout)
87
+ return new Promise((resolve, reject) => {
88
+ const timeout = setTimeout(() => {
101
89
  wsManager.off("data-event", handler);
102
- if (event.status === "success" && event.outputs) {
103
- // 成功,直接返回完整的 event.outputs JSON 字符串
104
- resolve({
105
- content: [
106
- {
107
- type: "text",
108
- text: JSON.stringify(event.outputs),
109
- }
110
- ]
111
- });
90
+ reject(new Error("发送短信超时(60秒)"));
91
+ }, 60000);
92
+ // Listen for data events from WebSocket
93
+ const handler = (event) => {
94
+ if (event.intentName === "SendShortMessage") {
95
+ clearTimeout(timeout);
96
+ wsManager.off("data-event", handler);
97
+ if (event.status === "success" && event.outputs) {
98
+ // 成功,直接返回完整的 event.outputs JSON 字符串
99
+ resolve({
100
+ content: [
101
+ {
102
+ type: "text",
103
+ text: JSON.stringify(event.outputs),
104
+ }
105
+ ]
106
+ });
107
+ }
108
+ else {
109
+ const errorDetail = event.outputs ? JSON.stringify(event.outputs) : event.status;
110
+ reject(new Error(`发送短信失败: ${errorDetail}`));
111
+ }
112
112
  }
113
- else {
114
- const errorDetail = event.outputs ? JSON.stringify(event.outputs) : event.status;
115
- reject(new Error(`发送短信失败: ${errorDetail}`));
116
- }
117
- }
118
- };
119
- // Register event handler
120
- wsManager.on("data-event", handler);
121
- // Send the command
122
- sendCommand({
123
- config,
124
- sessionId,
125
- taskId,
126
- messageId,
127
- command,
128
- })
129
- .then(() => {
130
- })
131
- .catch((error) => {
132
- clearTimeout(timeout);
133
- wsManager.off("data-event", handler);
134
- reject(error);
113
+ };
114
+ // Register event handler
115
+ wsManager.on("data-event", handler);
116
+ // Send the command
117
+ sendCommand({
118
+ config,
119
+ sessionId,
120
+ taskId,
121
+ messageId,
122
+ command,
123
+ })
124
+ .then(() => {
125
+ })
126
+ .catch((error) => {
127
+ clearTimeout(timeout);
128
+ wsManager.off("data-event", handler);
129
+ reject(error);
130
+ });
135
131
  });
136
- });
137
- },
138
- };
132
+ },
133
+ };
134
+ }
@@ -35,11 +35,26 @@ export declare function getLatestSessionContext(): SessionContext | null;
35
35
  */
36
36
  export declare function runWithSessionContext<T>(context: SessionContext, callback: () => Promise<T>): Promise<T>;
37
37
  /**
38
- * Get the current session context from AsyncLocalStorage.
39
- * This is the recommended way to access session context in tools.
40
- * Returns null if not running within a session context.
38
+ * Get the current session context.
39
+ * Prefers AsyncLocalStorage (correct for concurrent sessions).
40
+ * Falls back to the global activeSessions Map when AsyncLocalStorage
41
+ * context is lost (e.g., pi-agent framework tool execution boundary).
41
42
  *
42
- * Enhanced version: Automatically fetches the latest taskId from task-manager
43
- * to support interruption scenarios where a new message updates the taskId.
43
+ * @param sessionKey - Optional exact sessionKey for precise lookup.
44
+ * When provided and AsyncLocalStorage is unavailable, this avoids
45
+ * ambiguous multi-session matching.
44
46
  */
45
- export declare function getCurrentSessionContext(): SessionContext | null;
47
+ export declare function getCurrentSessionContext(sessionKey?: string): SessionContext | null;
48
+ /**
49
+ * Force-clean all active sessions. Used during gateway shutdown/reload.
50
+ */
51
+ export declare function cleanupAllSessions(): void;
52
+ /**
53
+ * Clean up sessions that have exceeded TTL.
54
+ * Returns the number of cleaned sessions.
55
+ */
56
+ export declare function cleanupStaleSessions(): number;
57
+ /**
58
+ * Get the current number of active sessions (for diagnostics).
59
+ */
60
+ export declare function getActiveSessionCount(): number;
@@ -1,10 +1,31 @@
1
1
  // Session manager for XY tool context
2
2
  // Stores active session contexts that tools can access
3
3
  import { AsyncLocalStorage } from "async_hooks";
4
+ import { logger } from "../utils/logger.js";
4
5
  import { configManager } from "../utils/config-manager.js";
6
+ import { toolCallNudgeManager } from "../utils/tool-call-nudge-manager.js";
5
7
  import { getCurrentTaskId, getCurrentMessageId } from "../task-manager.js";
6
- // Map of sessionKey -> SessionContextWithRef
7
- const activeSessions = new Map();
8
+ /** 最大 session 存活时间(毫秒),超过此时间且无新消息的 session 视为僵尸。
9
+ * 仅用于全局 Map 回退路径的清理,不影响 ALS 路径。
10
+ * 工具已改为闭包捕获 ctx,此 TTL 仅作为防止 session 泄漏的最后防线。
11
+ * 正常对话中 registerSession 会刷新 createdAt,所以长对话不受影响。 */
12
+ const SESSION_TTL_MS = 60 * 60 * 1000; // 1 hour
13
+ // Use globalThis to ensure a single Map instance across all module copies.
14
+ // The xy_channel plugin may be loaded by openclaw from different module resolution
15
+ // paths (plugin entry vs tool registration), causing session-manager.ts to be
16
+ // instantiated multiple times. globalThis guarantees all code shares the same Map.
17
+ const _g = globalThis;
18
+ if (!_g.__xyActiveSessions) {
19
+ _g.__xyActiveSessions = new Map();
20
+ }
21
+ const activeSessions = _g.__xyActiveSessions;
22
+ // Track the most recently registered sessionKey for reliable fallback
23
+ // when AsyncLocalStorage context is lost across openclaw's embedded runner boundary.
24
+ if (!_g.__xyLastRegisteredSessionKey) {
25
+ _g.__xyLastRegisteredSessionKey = "";
26
+ }
27
+ const getLastRegisteredKey = () => _g.__xyLastRegisteredSessionKey;
28
+ const setLastRegisteredKey = (key) => { _g.__xyLastRegisteredSessionKey = key; };
8
29
  // AsyncLocalStorage for thread-safe session context isolation
9
30
  const asyncLocalStorage = new AsyncLocalStorage();
10
31
  /**
@@ -12,18 +33,22 @@ const asyncLocalStorage = new AsyncLocalStorage();
12
33
  * Should be called when starting to process a message.
13
34
  */
14
35
  export function registerSession(sessionKey, context) {
36
+ // Track last registered session for reliable ALS-miss fallback
37
+ setLastRegisteredKey(sessionKey);
15
38
  const existing = activeSessions.get(sessionKey);
16
39
  if (existing) {
17
- // 更新上下文,增加引用计数
40
+ // 更新上下文,增加引用计数,刷新存活时间
18
41
  existing.taskId = context.taskId;
19
42
  existing.messageId = context.messageId;
20
43
  existing.refCount++;
44
+ existing.createdAt = Date.now(); // 刷新存活时间,长对话不受 TTL 影响
21
45
  }
22
46
  else {
23
47
  // 新建
24
48
  activeSessions.set(sessionKey, {
25
49
  ...context,
26
50
  refCount: 1,
51
+ createdAt: Date.now(),
27
52
  });
28
53
  }
29
54
  }
@@ -40,6 +65,7 @@ export function unregisterSession(sessionKey) {
40
65
  if (existing.refCount <= 0) {
41
66
  activeSessions.delete(sessionKey);
42
67
  configManager.clearSession(existing.sessionId);
68
+ toolCallNudgeManager.clearSession(sessionKey);
43
69
  }
44
70
  }
45
71
  /**
@@ -50,7 +76,7 @@ export function getSessionContext(sessionKey) {
50
76
  const contextWithRef = activeSessions.get(sessionKey) ?? null;
51
77
  if (contextWithRef) {
52
78
  // 返回时去掉refCount字段
53
- const { refCount, ...context } = contextWithRef;
79
+ const { refCount, createdAt, ...context } = contextWithRef;
54
80
  return context;
55
81
  }
56
82
  return null;
@@ -69,7 +95,7 @@ export function getLatestSessionContext() {
69
95
  const sessions = Array.from(activeSessions.values());
70
96
  const latestSessionWithRef = sessions[sessions.length - 1];
71
97
  // 返回时去掉refCount字段
72
- const { refCount, ...latestSession } = latestSessionWithRef;
98
+ const { refCount, createdAt, ...latestSession } = latestSessionWithRef;
73
99
  return latestSession;
74
100
  }
75
101
  /**
@@ -77,34 +103,137 @@ export function getLatestSessionContext() {
77
103
  * This ensures thread-safe context isolation for concurrent requests.
78
104
  */
79
105
  export function runWithSessionContext(context, callback) {
106
+ logger.log(`[SESSION-MGR] 🔵 ALS SET: sessionId=${context.sessionId} taskId=${context.taskId}`);
80
107
  return asyncLocalStorage.run(context, callback);
81
108
  }
82
109
  /**
83
- * Get the current session context from AsyncLocalStorage.
84
- * This is the recommended way to access session context in tools.
85
- * Returns null if not running within a session context.
110
+ * Get the current session context.
111
+ * Prefers AsyncLocalStorage (correct for concurrent sessions).
112
+ * Falls back to the global activeSessions Map when AsyncLocalStorage
113
+ * context is lost (e.g., pi-agent framework tool execution boundary).
86
114
  *
87
- * Enhanced version: Automatically fetches the latest taskId from task-manager
88
- * to support interruption scenarios where a new message updates the taskId.
115
+ * @param sessionKey - Optional exact sessionKey for precise lookup.
116
+ * When provided and AsyncLocalStorage is unavailable, this avoids
117
+ * ambiguous multi-session matching.
89
118
  */
90
- export function getCurrentSessionContext() {
91
- // 1. Get base context from AsyncLocalStorage
92
- const context = asyncLocalStorage.getStore() ?? null;
93
- if (!context) {
119
+ export function getCurrentSessionContext(sessionKey) {
120
+ // 1. Try AsyncLocalStorage first (correct for concurrent sessions)
121
+ const alsContext = asyncLocalStorage.getStore() ?? null;
122
+ if (alsContext) {
123
+ return enrichWithLatestTaskInfo(alsContext);
124
+ }
125
+ // ALS not available — logging to understand when/why
126
+ const stack = new Error().stack?.split("\n").slice(2, 5).map(s => s.trim()).join(" | ");
127
+ logger.log(`[SESSION-MGR] ⚠️ ALS miss, falling back to Map (size=${activeSessions.size}), callers: ${stack}`);
128
+ // 2. Fallback: look up from global activeSessions Map
129
+ if (activeSessions.size === 0) {
94
130
  return null;
95
131
  }
96
- // 2. Get latest taskId and messageId from task-manager
132
+ // 2a. Exact sessionKey match (highest confidence fallback)
133
+ if (sessionKey) {
134
+ const exact = activeSessions.get(sessionKey);
135
+ if (exact) {
136
+ const { refCount, createdAt, ...context } = exact;
137
+ return enrichWithLatestTaskInfo(context);
138
+ }
139
+ // sessionKey provided but not found — don't fall back to heuristics
140
+ logger.log(`[SESSION-MGR] sessionKey "${sessionKey}" not found in activeSessions (size=${activeSessions.size})`);
141
+ return null;
142
+ }
143
+ // 2b. Single active session — return it directly (but check TTL)
144
+ if (activeSessions.size === 1) {
145
+ const entry = activeSessions.values().next().value;
146
+ if (entry) {
147
+ // Check if session is stale
148
+ if (Date.now() - entry.createdAt > SESSION_TTL_MS) {
149
+ logger.log(`[SESSION-MGR] single session expired, createdAt=${entry.createdAt}, cleaning up`);
150
+ activeSessions.clear();
151
+ return null;
152
+ }
153
+ const { refCount, createdAt, ...context } = entry;
154
+ return enrichWithLatestTaskInfo(context);
155
+ }
156
+ return null;
157
+ }
158
+ // 2c. Multiple sessions — prefer the last registered session.
159
+ // This is the most reliable heuristic when ALS is lost across openclaw's
160
+ // embedded runner boundary: registerSession() is called just before
161
+ // runWithSessionContext(), and agentTools() is called during tool
162
+ // compilation shortly after. The last registered session is always the
163
+ // one currently being set up.
164
+ const lastKey = getLastRegisteredKey();
165
+ if (lastKey) {
166
+ const lastEntry = activeSessions.get(lastKey);
167
+ if (lastEntry) {
168
+ logger.log(`[SESSION-MGR] 🎯 using lastRegistered session: ${lastKey}`);
169
+ const { refCount, createdAt, ...context } = lastEntry;
170
+ return enrichWithLatestTaskInfo(context);
171
+ }
172
+ }
173
+ // 2d. Fallback: find any non-stale session
174
+ const now = Date.now();
175
+ for (const [key, entry] of activeSessions) {
176
+ if (now - entry.createdAt > SESSION_TTL_MS) {
177
+ configManager.clearSession(entry.sessionId);
178
+ toolCallNudgeManager.clearSession(key);
179
+ activeSessions.delete(key);
180
+ continue;
181
+ }
182
+ const { refCount, createdAt, ...context } = entry;
183
+ return enrichWithLatestTaskInfo(context);
184
+ }
185
+ return null;
186
+ }
187
+ /**
188
+ * Force-clean all active sessions. Used during gateway shutdown/reload.
189
+ */
190
+ export function cleanupAllSessions() {
191
+ for (const [key, entry] of activeSessions) {
192
+ configManager.clearSession(entry.sessionId);
193
+ toolCallNudgeManager.clearSession(key);
194
+ }
195
+ activeSessions.clear();
196
+ logger.log("[SESSION-MGR] all sessions cleaned up");
197
+ }
198
+ /**
199
+ * Clean up sessions that have exceeded TTL.
200
+ * Returns the number of cleaned sessions.
201
+ */
202
+ export function cleanupStaleSessions() {
203
+ const now = Date.now();
204
+ let cleaned = 0;
205
+ for (const [key, entry] of activeSessions) {
206
+ if (now - entry.createdAt > SESSION_TTL_MS) {
207
+ configManager.clearSession(entry.sessionId);
208
+ toolCallNudgeManager.clearSession(key);
209
+ activeSessions.delete(key);
210
+ cleaned++;
211
+ }
212
+ }
213
+ if (cleaned > 0) {
214
+ logger.log(`[SESSION-MGR] cleaned ${cleaned} stale session(s)`);
215
+ }
216
+ return cleaned;
217
+ }
218
+ /**
219
+ * Get the current number of active sessions (for diagnostics).
220
+ */
221
+ export function getActiveSessionCount() {
222
+ return activeSessions.size;
223
+ }
224
+ /**
225
+ * Enrich a base session context with the latest taskId/messageId
226
+ * from task-manager (supports interruption scenarios).
227
+ */
228
+ function enrichWithLatestTaskInfo(context) {
97
229
  const latestTaskId = getCurrentTaskId(context.sessionId);
98
230
  const latestMessageId = getCurrentMessageId(context.sessionId);
99
- // 3. If task-manager has a newer taskId, use the latest value
100
231
  if (latestTaskId && latestTaskId !== context.taskId) {
101
- // Return updated context (create new object, don't modify original)
102
232
  return {
103
233
  ...context,
104
234
  taskId: latestTaskId,
105
235
  messageId: latestMessageId ?? context.messageId,
106
236
  };
107
237
  }
108
- // 4. No update needed, return original context
109
238
  return context;
110
239
  }
@@ -1,3 +1,4 @@
1
+ import type { SessionContext } from "./session-manager.js";
1
2
  /**
2
3
  * XY upload file tool - uploads local files to get publicly accessible URLs.
3
4
  * Requires file URIs from search_file tool as prerequisite.
@@ -10,4 +11,4 @@
10
11
  * - After getting public URLs, if further processing is needed, download the file first
11
12
  * - URLs returned are publicly accessible
12
13
  */
13
- export declare const uploadFileTool: any;
14
+ export declare function createUploadFileTool(ctx: SessionContext): any;