@ynhcj/xiaoyi-channel 0.0.2 → 0.0.3-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 (71) hide show
  1. package/dist/src/bot.js +115 -35
  2. package/dist/src/channel.js +22 -1
  3. package/dist/src/client.d.ts +15 -0
  4. package/dist/src/client.js +97 -2
  5. package/dist/src/file-download.js +10 -1
  6. package/dist/src/file-upload.js +1 -1
  7. package/dist/src/formatter.d.ts +17 -0
  8. package/dist/src/formatter.js +86 -6
  9. package/dist/src/heartbeat.d.ts +2 -1
  10. package/dist/src/heartbeat.js +9 -1
  11. package/dist/src/monitor.d.ts +5 -0
  12. package/dist/src/monitor.js +131 -25
  13. package/dist/src/onboarding.js +7 -7
  14. package/dist/src/outbound.js +150 -71
  15. package/dist/src/parser.d.ts +5 -0
  16. package/dist/src/parser.js +15 -0
  17. package/dist/src/push.d.ts +7 -1
  18. package/dist/src/push.js +110 -19
  19. package/dist/src/reply-dispatcher.d.ts +1 -0
  20. package/dist/src/reply-dispatcher.js +210 -57
  21. package/dist/src/task-manager.d.ts +55 -0
  22. package/dist/src/task-manager.js +136 -0
  23. package/dist/src/tools/calendar-tool.d.ts +6 -0
  24. package/dist/src/tools/calendar-tool.js +167 -0
  25. package/dist/src/tools/call-phone-tool.d.ts +5 -0
  26. package/dist/src/tools/call-phone-tool.js +183 -0
  27. package/dist/src/tools/create-alarm-tool.d.ts +7 -0
  28. package/dist/src/tools/create-alarm-tool.js +444 -0
  29. package/dist/src/tools/delete-alarm-tool.d.ts +11 -0
  30. package/dist/src/tools/delete-alarm-tool.js +238 -0
  31. package/dist/src/tools/location-tool.js +48 -9
  32. package/dist/src/tools/modify-alarm-tool.d.ts +9 -0
  33. package/dist/src/tools/modify-alarm-tool.js +474 -0
  34. package/dist/src/tools/modify-note-tool.d.ts +9 -0
  35. package/dist/src/tools/modify-note-tool.js +163 -0
  36. package/dist/src/tools/note-tool.d.ts +5 -0
  37. package/dist/src/tools/note-tool.js +146 -0
  38. package/dist/src/tools/search-alarm-tool.d.ts +8 -0
  39. package/dist/src/tools/search-alarm-tool.js +389 -0
  40. package/dist/src/tools/search-calendar-tool.d.ts +12 -0
  41. package/dist/src/tools/search-calendar-tool.js +259 -0
  42. package/dist/src/tools/search-contact-tool.d.ts +5 -0
  43. package/dist/src/tools/search-contact-tool.js +168 -0
  44. package/dist/src/tools/search-file-tool.d.ts +5 -0
  45. package/dist/src/tools/search-file-tool.js +185 -0
  46. package/dist/src/tools/search-message-tool.d.ts +5 -0
  47. package/dist/src/tools/search-message-tool.js +173 -0
  48. package/dist/src/tools/search-note-tool.d.ts +5 -0
  49. package/dist/src/tools/search-note-tool.js +130 -0
  50. package/dist/src/tools/search-photo-gallery-tool.d.ts +8 -0
  51. package/dist/src/tools/search-photo-gallery-tool.js +184 -0
  52. package/dist/src/tools/search-photo-tool.d.ts +9 -0
  53. package/dist/src/tools/search-photo-tool.js +270 -0
  54. package/dist/src/tools/send-file-to-user-tool.d.ts +5 -0
  55. package/dist/src/tools/send-file-to-user-tool.js +318 -0
  56. package/dist/src/tools/send-message-tool.d.ts +5 -0
  57. package/dist/src/tools/send-message-tool.js +189 -0
  58. package/dist/src/tools/session-manager.d.ts +15 -0
  59. package/dist/src/tools/session-manager.js +126 -6
  60. package/dist/src/tools/upload-file-tool.d.ts +13 -0
  61. package/dist/src/tools/upload-file-tool.js +265 -0
  62. package/dist/src/tools/upload-photo-tool.d.ts +9 -0
  63. package/dist/src/tools/upload-photo-tool.js +223 -0
  64. package/dist/src/tools/xiaoyi-gui-tool.d.ts +6 -0
  65. package/dist/src/tools/xiaoyi-gui-tool.js +151 -0
  66. package/dist/src/types.d.ts +5 -9
  67. package/dist/src/utils/config-manager.d.ts +26 -0
  68. package/dist/src/utils/config-manager.js +56 -0
  69. package/dist/src/websocket.d.ts +41 -0
  70. package/dist/src/websocket.js +192 -9
  71. package/package.json +1 -2
package/dist/src/push.js CHANGED
@@ -1,46 +1,135 @@
1
1
  // Push message service for scheduled tasks
2
2
  import fetch from "node-fetch";
3
- import { logger } from "./utils/logger.js";
3
+ import { randomUUID } from "crypto";
4
+ import { configManager } from "./utils/config-manager.js";
4
5
  /**
5
6
  * Service for sending push messages to users.
6
7
  * Used for outbound messages and scheduled tasks.
7
8
  */
8
9
  export class XYPushService {
9
10
  config;
11
+ DEFAULT_PUSH_URL = "https://hag.cloud.huawei.com/open-ability-agent/v1/agent-webhook";
12
+ REQUEST_FROM = "openclaw";
10
13
  constructor(config) {
11
14
  this.config = config;
12
15
  }
16
+ /**
17
+ * Generate a random trace ID for request tracking.
18
+ */
19
+ generateTraceId() {
20
+ return `trace-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
21
+ }
13
22
  /**
14
23
  * Send a push message to a user session.
15
24
  */
16
- async sendPush(content, title, sessionId) {
17
- const pushUrl = this.config.pushUrl || `${this.config.fileUploadUrl}/push`;
18
- logger.debug(`Sending push message: title="${title}"`);
25
+ async sendPush(content, title, data, sessionId) {
26
+ const pushUrl = this.config.pushUrl || this.DEFAULT_PUSH_URL;
27
+ const traceId = this.generateTraceId();
28
+ // Get dynamic pushId for the session (falls back to config pushId)
29
+ const dynamicPushId = configManager.getPushId(sessionId);
30
+ const pushId = dynamicPushId || this.config.pushId;
31
+ console.log(`[PUSH] 📤 Preparing to send push message`);
32
+ console.log(`[PUSH] - Title: "${title}"`);
33
+ console.log(`[PUSH] - Content length: ${content.length} chars`);
34
+ console.log(`[PUSH] - Session ID: ${sessionId || 'none'}`);
35
+ console.log(`[PUSH] - Trace ID: ${traceId}`);
36
+ console.log(`[PUSH] - Push URL: ${pushUrl}`);
37
+ if (dynamicPushId) {
38
+ console.log(`[PUSH] - Using dynamic pushId (from session): ${pushId.substring(0, 20)}...`);
39
+ console.log(`[PUSH] - Full dynamic pushId: ${pushId}`);
40
+ }
41
+ else {
42
+ console.log(`[PUSH] - Using config pushId (fallback): ${pushId.substring(0, 20)}...`);
43
+ console.log(`[PUSH] - Full config pushId: ${pushId}`);
44
+ }
45
+ console.log(`[PUSH] - API ID: ${this.config.apiId}`);
46
+ console.log(`[PUSH] - UID: ${this.config.uid}`);
19
47
  try {
20
- const request = {
21
- apiKey: this.config.apiKey,
22
- apiId: this.config.apiId,
23
- pushId: this.config.pushId,
24
- sessionId: sessionId || "default",
25
- title,
26
- content,
48
+ const requestBody = {
49
+ jsonrpc: "2.0",
50
+ id: randomUUID(),
51
+ result: {
52
+ id: randomUUID(),
53
+ apiId: this.config.apiId,
54
+ pushId: pushId, // Use dynamic pushId
55
+ pushText: title,
56
+ kind: "task",
57
+ artifacts: [
58
+ {
59
+ artifactId: randomUUID(),
60
+ parts: [
61
+ {
62
+ kind: "text",
63
+ text: content,
64
+ },
65
+ ],
66
+ },
67
+ ],
68
+ },
27
69
  };
70
+ console.log(`[PUSH] Full request body:`, JSON.stringify(requestBody, null, 2));
28
71
  const response = await fetch(pushUrl, {
29
72
  method: "POST",
30
73
  headers: {
31
74
  "Content-Type": "application/json",
75
+ "Accept": "application/json",
76
+ "x-hag-trace-id": traceId,
77
+ "x-uid": this.config.uid,
32
78
  "x-api-key": this.config.apiKey,
33
- "x-request-from": "openclaw",
79
+ "x-request-from": this.REQUEST_FROM,
34
80
  },
35
- body: JSON.stringify(request),
81
+ body: JSON.stringify(requestBody),
36
82
  });
83
+ // Log response status and headers
84
+ console.log(`[PUSH] 📥 Response received`);
85
+ console.log(`[PUSH] - HTTP Status: ${response.status} ${response.statusText}`);
86
+ console.log(`[PUSH] - Content-Type: ${response.headers.get('content-type')}`);
87
+ console.log(`[PUSH] - Content-Length: ${response.headers.get('content-length')}`);
37
88
  if (!response.ok) {
38
- throw new Error(`Push failed: HTTP ${response.status}`);
89
+ const errorText = await response.text();
90
+ console.log(`[PUSH] ❌ Push request failed`);
91
+ console.log(`[PUSH] - HTTP Status: ${response.status}`);
92
+ console.log(`[PUSH] - Response body: ${errorText}`);
93
+ throw new Error(`Push failed: HTTP ${response.status} - ${errorText}`);
94
+ }
95
+ // Try to parse JSON response with detailed error handling
96
+ let result;
97
+ try {
98
+ const responseText = await response.text();
99
+ console.log(`[PUSH] 📄 Response body length: ${responseText.length} chars`);
100
+ console.log(`[PUSH] 📄 Response body preview: ${responseText.substring(0, 200)}`);
101
+ if (!responseText || responseText.trim() === '') {
102
+ console.log(`[PUSH] ⚠️ Received empty response body`);
103
+ result = {};
104
+ }
105
+ else {
106
+ result = JSON.parse(responseText);
107
+ }
108
+ }
109
+ catch (parseError) {
110
+ console.log(`[PUSH] ❌ Failed to parse JSON response`);
111
+ console.log(`[PUSH] - Parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
112
+ throw new Error(`Invalid JSON response from push service: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
39
113
  }
40
- logger.log(`Push message sent successfully: "${title}"`);
114
+ console.log(`[PUSH] ✅ Push message sent successfully`);
115
+ console.log(`[PUSH] - Title: "${title}"`);
116
+ console.log(`[PUSH] - Trace ID: ${traceId}`);
117
+ console.log(`[PUSH] - Used pushId: ${pushId.substring(0, 20)}...`);
118
+ console.log(`[PUSH] - Response:`, result);
41
119
  }
42
120
  catch (error) {
43
- logger.error("Failed to send push message:", error);
121
+ console.log(`[PUSH] ❌ Failed to send push message`);
122
+ console.log(`[PUSH] - Trace ID: ${traceId}`);
123
+ console.log(`[PUSH] - Target URL: ${pushUrl}`);
124
+ console.log(`[PUSH] - Push ID: ${pushId.substring(0, 20)}...`);
125
+ if (error instanceof Error) {
126
+ console.log(`[PUSH] - Error name: ${error.name}`);
127
+ console.log(`[PUSH] - Error message: ${error.message}`);
128
+ console.log(`[PUSH] - Error stack:`, error.stack);
129
+ }
130
+ else {
131
+ console.log(`[PUSH] - Error:`, error);
132
+ }
44
133
  throw error;
45
134
  }
46
135
  }
@@ -48,8 +137,10 @@ export class XYPushService {
48
137
  * Send a push message with file attachments.
49
138
  */
50
139
  async sendPushWithFiles(content, title, fileIds, sessionId) {
51
- // Build content with file references
52
- const contentWithFiles = `${content}\n\n[文件: ${fileIds.join(", ")}]`;
53
- await this.sendPush(contentWithFiles, title, sessionId);
140
+ const data = {
141
+ content,
142
+ fileIds,
143
+ };
144
+ await this.sendPush(content, title, data, sessionId);
54
145
  }
55
146
  }
@@ -6,6 +6,7 @@ export interface CreateXYReplyDispatcherParams {
6
6
  taskId: string;
7
7
  messageId: string;
8
8
  accountId: string;
9
+ isSteerFollower?: boolean;
9
10
  }
10
11
  /**
11
12
  * Create a reply dispatcher for XY channel messages.
@@ -1,57 +1,71 @@
1
1
  import { createReplyPrefixContext } from "openclaw/plugin-sdk";
2
2
  import { getXYRuntime } from "./runtime.js";
3
- import { sendA2AResponse, sendStatusUpdate } from "./formatter.js";
3
+ import { sendA2AResponse, sendStatusUpdate, sendReasoningTextUpdate } from "./formatter.js";
4
4
  import { resolveXYConfig } from "./config.js";
5
+ import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
5
6
  /**
6
7
  * Create a reply dispatcher for XY channel messages.
7
8
  * Follows feishu pattern with status updates and streaming support.
8
9
  * Runtime is expected to be validated before calling this function.
9
10
  */
10
11
  export function createXYReplyDispatcher(params) {
11
- const { cfg, runtime, sessionId, taskId, messageId, accountId } = params;
12
+ const { cfg, runtime, sessionId, taskId, messageId, accountId, isSteerFollower } = params;
12
13
  const log = runtime?.log ?? console.log;
13
14
  const error = runtime?.error ?? console.error;
14
- // Get runtime (already validated in monitor.ts, but get reference for use)
15
+ log(`[DISPATCHER-CREATE] ******* Creating dispatcher *******`);
16
+ log(`[DISPATCHER-CREATE] - sessionId: ${sessionId}`);
17
+ log(`[DISPATCHER-CREATE] - taskId: ${taskId}`);
18
+ log(`[DISPATCHER-CREATE] - messageId: ${messageId}`);
19
+ log(`[DISPATCHER-CREATE] - isSteerFollower: ${isSteerFollower ?? false}`);
20
+ // 初始taskId和messageId(作为fallback)
21
+ const initialTaskId = taskId;
22
+ const initialMessageId = messageId;
23
+ /**
24
+ * 🔑 核心改造:动态获取当前活跃的taskId和messageId
25
+ * 每次需要taskId时,都从TaskManager获取最新值
26
+ */
27
+ const getActiveTaskId = () => {
28
+ return getCurrentTaskId(sessionId) ?? initialTaskId;
29
+ };
30
+ const getActiveMessageId = () => {
31
+ return getCurrentMessageId(sessionId) ?? initialMessageId;
32
+ };
15
33
  const core = getXYRuntime();
16
- // Resolve configuration
17
34
  const config = resolveXYConfig(cfg);
18
- // Create reply prefix context (for model selection, etc.)
19
35
  const prefixContext = createReplyPrefixContext({ cfg, agentId: accountId });
20
- // Status update interval (every 60 seconds)
21
36
  let statusUpdateInterval = null;
22
- // Track if we've sent any response
23
37
  let hasSentResponse = false;
24
- // Track if we've sent the final empty message
25
38
  let finalSent = false;
39
+ let accumulatedText = "";
26
40
  /**
27
41
  * Start the status update interval
28
- * Call this immediately after creating the dispatcher
29
42
  */
30
43
  const startStatusInterval = () => {
31
- log(`[STATUS INTERVAL] Starting interval for session ${sessionId}, taskId=${taskId}`);
44
+ log(`[STATUS INTERVAL] Starting interval for session ${sessionId}`);
32
45
  statusUpdateInterval = setInterval(() => {
33
- log(`[STATUS INTERVAL] Triggering status update for session ${sessionId}, taskId=${taskId}`);
46
+ // 🔑 使用动态taskId
47
+ const currentTaskId = getActiveTaskId();
48
+ const currentMessageId = getActiveMessageId();
49
+ log(`[STATUS INTERVAL] Triggering status update`);
50
+ log(`[STATUS INTERVAL] - sessionId: ${sessionId}`);
51
+ log(`[STATUS INTERVAL] - currentTaskId: ${currentTaskId}`);
34
52
  void sendStatusUpdate({
35
53
  config,
36
54
  sessionId,
37
- taskId,
38
- messageId,
55
+ taskId: currentTaskId, // 🔑 动态taskId
56
+ messageId: currentMessageId, // 🔑 动态messageId
39
57
  text: "任务正在处理中,请稍后~",
40
58
  state: "working",
41
59
  }).catch((err) => {
42
60
  error(`Failed to send status update:`, err);
43
61
  });
44
- }, 60000); // 60 seconds
62
+ }, 30000); // 30 seconds
45
63
  };
46
- /**
47
- * Stop the status update interval
48
- */
49
64
  const stopStatusInterval = () => {
50
65
  if (statusUpdateInterval) {
51
- log(`[STATUS INTERVAL] Stopping interval for session ${sessionId}, taskId=${taskId}`);
66
+ log(`[STATUS INTERVAL] Stopping interval for session ${sessionId}`);
52
67
  clearInterval(statusUpdateInterval);
53
68
  statusUpdateInterval = null;
54
- log(`[STATUS INTERVAL] Stopped interval for session ${sessionId}, taskId=${taskId}`);
55
69
  }
56
70
  };
57
71
  const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
@@ -59,36 +73,31 @@ export function createXYReplyDispatcher(params) {
59
73
  responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
60
74
  humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, accountId),
61
75
  onReplyStart: () => {
62
- log(`[REPLY START] Reply started for session ${sessionId}, taskId=${taskId}`);
63
- // Status update interval is now managed externally
76
+ const currentTaskId = getActiveTaskId();
77
+ log(`[REPLY START] Reply started for session ${sessionId}, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
64
78
  },
65
79
  deliver: async (payload, info) => {
66
80
  const text = payload.text ?? "";
67
- // 🔍 Debug logging
68
- log(`[DELIVER] sessionId=${sessionId}, info.kind=${info?.kind}, text.length=${text.length}, text="${text.slice(0, 200)}"`);
69
- log(`[DELIVER] payload keys: ${Object.keys(payload).join(", ")}`);
70
- if (payload.mediaUrls) {
71
- log(`[DELIVER] mediaUrls: ${payload.mediaUrls.length} files`);
72
- }
81
+ const currentTaskId = getActiveTaskId();
82
+ const currentMessageId = getActiveMessageId();
83
+ log(`[DELIVER] sessionId=${sessionId}, taskId=${currentTaskId}, info.kind=${info?.kind}, text.length=${text.length}`);
73
84
  try {
74
- // Skip empty messages
75
85
  if (!text.trim()) {
76
86
  log(`[DELIVER SKIP] Empty text, skipping`);
77
87
  return;
78
88
  }
79
- // Send text with append=true (backend will accumulate)
80
- log(`[DELIVER SEND] Sending text, length=${text.length}, kind=${info?.kind || "undefined"}`);
81
- await sendA2AResponse({
89
+ accumulatedText += text;
90
+ hasSentResponse = true;
91
+ log(`[DELIVER ACCUMULATE] Accumulated text, current length=${accumulatedText.length}`);
92
+ // 🔑 使用动态taskId发送reasoningText更新
93
+ await sendReasoningTextUpdate({
82
94
  config,
83
95
  sessionId,
84
- taskId,
85
- messageId,
86
- text: text,
87
- append: true,
88
- final: false,
96
+ taskId: currentTaskId,
97
+ messageId: currentMessageId,
98
+ text,
89
99
  });
90
- hasSentResponse = true;
91
- log(`[DELIVER DONE] Sent text, hasSentResponse=${hasSentResponse}`);
100
+ log(`[DELIVER] Sent deliver text as reasoningText update`);
92
101
  }
93
102
  catch (deliverError) {
94
103
  error(`Failed to deliver message:`, deliverError);
@@ -96,16 +105,21 @@ export function createXYReplyDispatcher(params) {
96
105
  },
97
106
  onError: async (err, info) => {
98
107
  runtime.error?.(`xy: ${info.kind} reply failed: ${String(err)}`);
99
- // Stop status updates
100
108
  stopStatusInterval();
101
- // Send error status if we haven't sent any response yet
109
+ // 🔑 steer follower不发送错误状态(让主dispatcher处理)
110
+ if (isSteerFollower) {
111
+ log(`[ON_ERROR] Steer follower - skipping error response`);
112
+ return;
113
+ }
102
114
  if (!hasSentResponse) {
115
+ const currentTaskId = getActiveTaskId();
116
+ const currentMessageId = getActiveMessageId();
103
117
  try {
104
118
  await sendStatusUpdate({
105
119
  config,
106
120
  sessionId,
107
- taskId,
108
- messageId,
121
+ taskId: currentTaskId,
122
+ messageId: currentMessageId,
109
123
  text: "处理失败,请稍后重试",
110
124
  state: "failed",
111
125
  });
@@ -116,37 +130,86 @@ export function createXYReplyDispatcher(params) {
116
130
  }
117
131
  },
118
132
  onIdle: async () => {
119
- log(`[ON_IDLE] Reply idle for session ${sessionId}, hasSentResponse=${hasSentResponse}, finalSent=${finalSent}`);
120
- // Send final empty message to signal end if we haven't sent it yet
133
+ const currentTaskId = getActiveTaskId();
134
+ const currentMessageId = getActiveMessageId();
135
+ log(`[ON_IDLE] Reply idle`);
136
+ log(`[ON_IDLE] - sessionId: ${sessionId}`);
137
+ log(`[ON_IDLE] - taskId: ${currentTaskId}`);
138
+ log(`[ON_IDLE] - isSteerFollower: ${isSteerFollower}`);
139
+ log(`[ON_IDLE] - hasSentResponse: ${hasSentResponse}`);
140
+ log(`[ON_IDLE] - finalSent: ${finalSent}`);
141
+ // 🔑 核心改动:steer follower不发送final响应
142
+ if (isSteerFollower) {
143
+ log(`[ON_IDLE] Steer follower - skipping final response`);
144
+ log(`[ON_IDLE] - Message queued successfully, waiting for primary dispatcher`);
145
+ stopStatusInterval();
146
+ return; // ← 直接返回,不发送任何东西!
147
+ }
148
+ // 正常模式(或steer的第一条消息)
121
149
  if (hasSentResponse && !finalSent) {
122
- log(`[ON_IDLE] Sending final empty message`);
150
+ log(`[ON_IDLE] Sending accumulated text, length=${accumulatedText.length}`);
123
151
  try {
152
+ // 🔑 使用动态taskId发送完成状态
153
+ await sendStatusUpdate({
154
+ config,
155
+ sessionId,
156
+ taskId: currentTaskId,
157
+ messageId: currentMessageId,
158
+ text: "任务处理已完成~",
159
+ state: "completed",
160
+ });
161
+ log(`[ON_IDLE] ✅ Sent completion status update`);
162
+ // 🔑 使用动态taskId发送最终响应
124
163
  await sendA2AResponse({
125
164
  config,
126
165
  sessionId,
127
- taskId,
128
- messageId,
129
- text: "",
130
- append: true,
166
+ taskId: currentTaskId,
167
+ messageId: currentMessageId,
168
+ text: accumulatedText,
169
+ append: false,
131
170
  final: true,
132
171
  });
133
172
  finalSent = true;
134
- log(`[ON_IDLE] Sent final empty message`);
173
+ log(`[ON_IDLE] Sent final response with taskId=${currentTaskId}`);
135
174
  }
136
175
  catch (err) {
137
- error(`[ON_IDLE] Failed to send final message:`, err);
176
+ error(`[ON_IDLE] Failed to send final response:`, err);
138
177
  }
139
178
  }
140
179
  else {
180
+ // 正常失败场景(非steer follower)
141
181
  log(`[ON_IDLE] Skipping final message: hasSentResponse=${hasSentResponse}, finalSent=${finalSent}`);
182
+ try {
183
+ await sendStatusUpdate({
184
+ config,
185
+ sessionId,
186
+ taskId: currentTaskId,
187
+ messageId: currentMessageId,
188
+ text: "任务处理中断了~",
189
+ state: "failed",
190
+ });
191
+ log(`[ON_IDLE] ✅ Sent failure status update`);
192
+ await sendA2AResponse({
193
+ config,
194
+ sessionId,
195
+ taskId: currentTaskId,
196
+ messageId: currentMessageId,
197
+ text: "任务执行异常,请重试~",
198
+ append: false,
199
+ final: true,
200
+ });
201
+ finalSent = true;
202
+ log(`[ON_IDLE] ✅ Sent error response`);
203
+ }
204
+ catch (err) {
205
+ error(`[ON_IDLE] Failed to send error response:`, err);
206
+ }
142
207
  }
143
- // Stop status updates
144
208
  stopStatusInterval();
145
209
  },
146
210
  onCleanup: () => {
147
- log(`[ON_CLEANUP] Reply cleanup for session ${sessionId}, hasSentResponse=${hasSentResponse}, finalSent=${finalSent}`);
148
- // Stop status updates
149
- stopStatusInterval();
211
+ const currentTaskId = getActiveTaskId();
212
+ log(`[ON_CLEANUP] Reply cleanup, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
150
213
  },
151
214
  });
152
215
  return {
@@ -154,9 +217,99 @@ export function createXYReplyDispatcher(params) {
154
217
  replyOptions: {
155
218
  ...replyOptions,
156
219
  onModelSelected: prefixContext.onModelSelected,
220
+ onToolStart: async ({ name, phase }) => {
221
+ // 🔑 steer follower不发送tool状态(让主dispatcher处理)
222
+ if (isSteerFollower) {
223
+ return;
224
+ }
225
+ const currentTaskId = getActiveTaskId();
226
+ const currentMessageId = getActiveMessageId();
227
+ log(`[TOOL START] Tool: ${name}, phase: ${phase}, taskId: ${currentTaskId}`);
228
+ if (phase === "start") {
229
+ const toolName = name || "unknown";
230
+ try {
231
+ await sendStatusUpdate({
232
+ config,
233
+ sessionId,
234
+ taskId: currentTaskId,
235
+ messageId: currentMessageId,
236
+ text: `正在使用工具: ${toolName}...`,
237
+ state: "working",
238
+ });
239
+ log(`[TOOL START] ✅ Sent status update for tool start: ${toolName}`);
240
+ }
241
+ catch (err) {
242
+ error(`[TOOL START] ❌ Failed to send tool start status:`, err);
243
+ }
244
+ }
245
+ },
246
+ onToolResult: async (payload) => {
247
+ // 🔑 steer follower不发送tool结果(让主dispatcher处理)
248
+ if (isSteerFollower) {
249
+ return;
250
+ }
251
+ const currentTaskId = getActiveTaskId();
252
+ const currentMessageId = getActiveMessageId();
253
+ const text = payload.text ?? "";
254
+ const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
255
+ log(`[TOOL RESULT] Tool result, taskId: ${currentTaskId}, text.length: ${text.length}`);
256
+ try {
257
+ if (text.length > 0 || hasMedia) {
258
+ const resultText = text.length > 0 ? text : "工具执行完成";
259
+ await sendStatusUpdate({
260
+ config,
261
+ sessionId,
262
+ taskId: currentTaskId,
263
+ messageId: currentMessageId,
264
+ text: resultText,
265
+ state: "working",
266
+ });
267
+ log(`[TOOL RESULT] ✅ Sent tool result as status update`);
268
+ }
269
+ }
270
+ catch (err) {
271
+ error(`[TOOL RESULT] ❌ Failed to send tool result status:`, err);
272
+ }
273
+ },
274
+ onReasoningStream: async (payload) => {
275
+ // 🔑 steer follower不发送reasoning stream
276
+ if (isSteerFollower) {
277
+ return;
278
+ }
279
+ const text = payload.text ?? "";
280
+ log(`[REASONING STREAM] Reasoning chunk received, text.length: ${text.length}`);
281
+ // Reasoning stream 目前被注释掉
282
+ // 如果需要可以启用
283
+ },
284
+ onPartialReply: async (payload) => {
285
+ // 🔑 steer follower不发送partial reply(让主dispatcher处理)
286
+ if (isSteerFollower) {
287
+ return;
288
+ }
289
+ const currentTaskId = getActiveTaskId();
290
+ const currentMessageId = getActiveMessageId();
291
+ const text = payload.text ?? "";
292
+ log(`[PARTIAL REPLY] Partial reply chunk received, taskId: ${currentTaskId}`);
293
+ try {
294
+ if (text.length > 0) {
295
+ await sendReasoningTextUpdate({
296
+ config,
297
+ sessionId,
298
+ taskId: currentTaskId,
299
+ messageId: currentMessageId,
300
+ text,
301
+ append: false,
302
+ });
303
+ log(`[PARTIAL REPLY] ✅ Sent partial reply as reasoningText update`);
304
+ }
305
+ }
306
+ catch (err) {
307
+ error(`[PARTIAL REPLY] ❌ Failed to send partial reply:`, err);
308
+ }
309
+ },
157
310
  },
158
311
  markDispatchIdle,
159
- startStatusInterval, // Expose this to be called immediately
160
- stopStatusInterval, // Expose this for manual control if needed
312
+ startStatusInterval,
313
+ stopStatusInterval,
161
314
  };
162
315
  }
@@ -0,0 +1,55 @@
1
+ interface TaskIdBinding {
2
+ sessionId: string;
3
+ currentTaskId: string;
4
+ currentMessageId: string;
5
+ refCount: number;
6
+ updatedAt: number;
7
+ locked: boolean;
8
+ }
9
+ /**
10
+ * 注册或更新session的活跃taskId
11
+ * 返回是否是更新(用于判断是否是第二条消息)
12
+ */
13
+ export declare function registerTaskId(sessionId: string, taskId: string, messageId: string, options?: {
14
+ incrementRef?: boolean;
15
+ }): {
16
+ isUpdate: boolean;
17
+ refCount: number;
18
+ };
19
+ /**
20
+ * 增加引用计数(消息开始处理时调用)
21
+ */
22
+ export declare function incrementTaskIdRef(sessionId: string): void;
23
+ /**
24
+ * 减少引用计数,当refCount=0时才真正清理
25
+ */
26
+ export declare function decrementTaskIdRef(sessionId: string): void;
27
+ /**
28
+ * 锁定taskId,防止被清理(第一个消息使用)
29
+ */
30
+ export declare function lockTaskId(sessionId: string): void;
31
+ /**
32
+ * 解锁taskId(第一个消息完成时使用)
33
+ */
34
+ export declare function unlockTaskId(sessionId: string): void;
35
+ /**
36
+ * 获取session的当前活跃taskId
37
+ */
38
+ export declare function getCurrentTaskId(sessionId: string): string | null;
39
+ /**
40
+ * 获取session的当前活跃messageId
41
+ */
42
+ export declare function getCurrentMessageId(sessionId: string): string | null;
43
+ /**
44
+ * 检查session是否有活跃的taskId
45
+ */
46
+ export declare function hasActiveTask(sessionId: string): boolean;
47
+ /**
48
+ * 获取完整的binding信息(用于调试)
49
+ */
50
+ export declare function getTaskIdBinding(sessionId: string): TaskIdBinding | null;
51
+ /**
52
+ * 强制清理(错误恢复用)
53
+ */
54
+ export declare function forceCleanTaskId(sessionId: string): void;
55
+ export {};