@ynhcj/xiaoyi-channel 0.0.161-beta → 0.0.161-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 (64) hide show
  1. package/dist/src/bot.js +59 -5
  2. package/dist/src/cron-query-handler.d.ts +1 -11
  3. package/dist/src/cron-query-handler.js +88 -1
  4. package/dist/src/cspl/call_api.d.ts +1 -1
  5. package/dist/src/cspl/call_api.js +2 -2
  6. package/dist/src/cspl/config.js +30 -10
  7. package/dist/src/cspl/constants.d.ts +2 -0
  8. package/dist/src/cspl/constants.js +3 -0
  9. package/dist/src/cspl/sentinel_hook.js +11 -6
  10. package/dist/src/cspl/utils.d.ts +9 -3
  11. package/dist/src/cspl/utils.js +17 -11
  12. package/dist/src/file-upload.d.ts +5 -0
  13. package/dist/src/file-upload.js +102 -0
  14. package/dist/src/formatter.d.ts +30 -0
  15. package/dist/src/formatter.js +65 -10
  16. package/dist/src/monitor.js +35 -23
  17. package/dist/src/parser.d.ts +6 -0
  18. package/dist/src/parser.js +16 -0
  19. package/dist/src/provider.js +32 -0
  20. package/dist/src/reply-dispatcher.js +47 -17
  21. package/dist/src/self-evolution-handler.d.ts +1 -1
  22. package/dist/src/self-evolution-handler.js +12 -1
  23. package/dist/src/tools/calendar-tool.js +1 -1
  24. package/dist/src/tools/call-device-tool.js +0 -3
  25. package/dist/src/tools/call-phone-tool.js +1 -1
  26. package/dist/src/tools/check-plugin-privilege-tool.d.ts +6 -0
  27. package/dist/src/tools/check-plugin-privilege-tool.js +182 -0
  28. package/dist/src/tools/create-alarm-tool.js +1 -1
  29. package/dist/src/tools/create-all-tools.js +8 -8
  30. package/dist/src/tools/delete-alarm-tool.js +1 -1
  31. package/dist/src/tools/device-tool-map.js +1 -0
  32. package/dist/src/tools/display-a2ui-card-tool.d.ts +2 -0
  33. package/dist/src/tools/display-a2ui-card-tool.js +85 -0
  34. package/dist/src/tools/get-device-file-tool-schema.js +2 -3
  35. package/dist/src/tools/location-tool.js +1 -1
  36. package/dist/src/tools/modify-alarm-tool.js +1 -1
  37. package/dist/src/tools/modify-note-tool.js +1 -1
  38. package/dist/src/tools/note-tool.js +1 -1
  39. package/dist/src/tools/query-app-message-tool.js +1 -1
  40. package/dist/src/tools/query-memory-data-tool.js +1 -1
  41. package/dist/src/tools/query-todo-task-tool.js +1 -1
  42. package/dist/src/tools/save-file-to-phone-tool.js +1 -1
  43. package/dist/src/tools/save-media-to-gallery-tool.js +1 -1
  44. package/dist/src/tools/schema-tool-factory.js +1 -1
  45. package/dist/src/tools/search-alarm-tool.js +1 -1
  46. package/dist/src/tools/search-calendar-tool.js +1 -1
  47. package/dist/src/tools/search-contact-tool.js +1 -1
  48. package/dist/src/tools/search-email-tool.js +1 -1
  49. package/dist/src/tools/search-file-tool.js +5 -10
  50. package/dist/src/tools/search-note-tool.js +1 -1
  51. package/dist/src/tools/search-photo-gallery-tool.js +1 -1
  52. package/dist/src/tools/send-email-tool.js +1 -1
  53. package/dist/src/tools/send-html-card-tool.d.ts +7 -0
  54. package/dist/src/tools/send-html-card-tool.js +113 -0
  55. package/dist/src/tools/session-manager.d.ts +4 -0
  56. package/dist/src/tools/session-manager.js +13 -0
  57. package/dist/src/tools/upload-file-tool.js +3 -12
  58. package/dist/src/tools/upload-photo-tool.js +1 -1
  59. package/dist/src/tools/xiaoyi-add-collection-tool.js +1 -1
  60. package/dist/src/tools/xiaoyi-collection-tool.js +1 -1
  61. package/dist/src/tools/xiaoyi-delete-collection-tool.js +1 -1
  62. package/dist/src/tools/xiaoyi-gui-tool.js +6 -1
  63. package/dist/src/types.d.ts +3 -1
  64. package/package.json +1 -1
@@ -17,6 +17,7 @@ export interface SendA2AResponseParams {
17
17
  }>;
18
18
  errorCode?: number | string;
19
19
  errorMessage?: string;
20
+ log?: boolean;
20
21
  }
21
22
  /**
22
23
  * Send an A2A artifact update response.
@@ -81,6 +82,35 @@ export interface SendCommandParams {
81
82
  * listening in the calling tool works unchanged.
82
83
  */
83
84
  export declare function sendCommand(params: SendCommandParams): Promise<void>;
85
+ /**
86
+ * Parameters for sending a card (e.g., HTML H5 card).
87
+ */
88
+ export interface SendCardParams {
89
+ config: XYChannelConfig;
90
+ sessionId: string;
91
+ taskId: string;
92
+ messageId: string;
93
+ /** toolCallId from the tool's execute() — used for cron detection via hook-set Map. */
94
+ toolCallId?: string;
95
+ /** When true, the artifact-update is sent with final=true. Default: false. */
96
+ final?: boolean;
97
+ /** Array of card data objects to send. */
98
+ cardsInfo: CardDataObject[];
99
+ }
100
+ /**
101
+ * Card data object for sending display cards.
102
+ */
103
+ export interface CardDataObject {
104
+ cardName: string;
105
+ cardData: Record<string, any>;
106
+ displayType: string;
107
+ }
108
+ /**
109
+ * Send a card (e.g., HTML H5 card) as an artifact update (final=false).
110
+ *
111
+ * Cron-aware: same routing logic as sendCommand.
112
+ */
113
+ export declare function sendCard(params: SendCardParams): Promise<void>;
84
114
  /**
85
115
  * Parameters for sending a clearContext response.
86
116
  */
@@ -42,7 +42,7 @@ function buildTextPreview(text) {
42
42
  * Send an A2A artifact update response.
43
43
  */
44
44
  export async function sendA2AResponse(params) {
45
- const { config, sessionId, taskId, messageId, text, append, final, files, errorCode, errorMessage } = params;
45
+ const { config, sessionId, taskId, messageId, text, append, final, files, errorCode, errorMessage, log: shouldLog = true } = params;
46
46
  const log = logger.withContext(sessionId, taskId);
47
47
  // 审批桥接:将 OpenClaw 的审批提示翻译成用户友好的确认文案
48
48
  const bridgedText = text === undefined ? text : rewriteOutboundApprovalText(sessionId, text);
@@ -97,11 +97,14 @@ export async function sendA2AResponse(params) {
97
97
  taskId,
98
98
  msgDetail: JSON.stringify(jsonRpcResponse),
99
99
  };
100
- // Log complete response body
101
- const redactedText = redactSensitiveText(bridgedText ?? "");
102
- log.log(`[A2A_RESPONSE] Sending artifact-update, append=${append}, final=${final}, text=${buildTextPreview(redactedText)}, files=${files?.length ?? 0}, sensitive=${containsSensitiveInfo(bridgedText ?? "")}`);
100
+ if (shouldLog) {
101
+ const redactedText = redactSensitiveText(bridgedText ?? "");
102
+ log.log(`[A2A_RESPONSE] Sending artifact-update, append=${append}, final=${final}, text=${buildTextPreview(redactedText)}, files=${files?.length ?? 0}, sensitive=${containsSensitiveInfo(bridgedText ?? "")}`);
103
+ }
103
104
  await wsManager.sendMessage(sessionId, outboundMessage);
104
- log.log(`[A2A_RESPONSE] Message sent successfully`);
105
+ if (shouldLog) {
106
+ log.log(`[A2A_RESPONSE] Message sent successfully`);
107
+ }
105
108
  }
106
109
  /**
107
110
  * Send an A2A artifact-update with reasoningText part.
@@ -214,12 +217,11 @@ export async function sendCommand(params) {
214
217
  if (commands.length === 0) {
215
218
  throw new Error("sendCommand requires command or commands.");
216
219
  }
217
- // ── Cron mode: route through push channel ──────────────────────
218
- // Detected via: (a) sessionId "cron-" prefix from synthetic session, OR
219
- // (b) toolCallId marked by before_tool_call hook from openclaw's sessionKey.
220
+ // ── Cron mode: disabled ────────────────────────────────────────
221
+ // sendCommandViaPush is disabled in this version. Cron-triggered
222
+ // tool calls that try to send commands will be rejected.
220
223
  if (sessionId.startsWith("cron-") || isCronToolCall(toolCallId)) {
221
- const { sendCommandViaPush } = await import("./cron-command.js");
222
- return sendCommandViaPush({ config, command: commands[0] });
224
+ throw new Error("sendCommandViaPush is disabled in this version");
223
225
  }
224
226
  // ── Normal mode: WebSocket ─────────────────────────────────────
225
227
  // Dynamic lookup: use latest taskId/messageId from task-manager (handles steer/interrupt),
@@ -269,6 +271,59 @@ export async function sendCommand(params) {
269
271
  await wsManager.sendMessage(sessionId, outboundMessage);
270
272
  log.log(`[A2A_COMMAND] Command sent successfully`);
271
273
  }
274
+ /**
275
+ * Send a card (e.g., HTML H5 card) as an artifact update (final=false).
276
+ *
277
+ * Cron-aware: same routing logic as sendCommand.
278
+ */
279
+ export async function sendCard(params) {
280
+ const { config, sessionId, taskId, messageId, toolCallId } = params;
281
+ // ── Cron mode: route through push channel ──────────────────────
282
+ if (sessionId.startsWith("cron-") || isCronToolCall(toolCallId)) {
283
+ throw new Error("sendCard does not support cron mode");
284
+ }
285
+ // ── Normal mode: WebSocket ─────────────────────────────────────
286
+ const currentTaskId = getCurrentTaskId(sessionId) ?? taskId;
287
+ const currentMessageId = getCurrentMessageId(sessionId) ?? messageId;
288
+ const log = logger.withContext(sessionId, currentTaskId);
289
+ // Build artifact update with cardsInfo as data
290
+ const artifact = {
291
+ taskId: currentTaskId,
292
+ kind: "artifact-update",
293
+ append: false,
294
+ lastChunk: true,
295
+ final: params.final ?? false,
296
+ artifact: {
297
+ artifactId: uuidv4(),
298
+ parts: [
299
+ {
300
+ kind: "data",
301
+ data: {
302
+ cardsInfo: params.cardsInfo,
303
+ },
304
+ },
305
+ ],
306
+ },
307
+ };
308
+ // Build JSON-RPC response
309
+ const jsonRpcResponse = {
310
+ jsonrpc: "2.0",
311
+ id: currentMessageId,
312
+ result: artifact,
313
+ };
314
+ // Send via WebSocket
315
+ const wsManager = getXYWebSocketManager(config);
316
+ const outboundMessage = {
317
+ msgType: "agent_response",
318
+ agentId: config.agentId,
319
+ sessionId,
320
+ taskId: currentTaskId,
321
+ msgDetail: JSON.stringify(jsonRpcResponse),
322
+ };
323
+ log.log(`[A2A_CARD] Sending card`);
324
+ await wsManager.sendMessage(sessionId, outboundMessage);
325
+ log.log(`[A2A_CARD] Card sent successfully`);
326
+ }
272
327
  /**
273
328
  * Send a clearContext response.
274
329
  */
@@ -116,35 +116,45 @@ export async function monitorXYProvider(opts = {}) {
116
116
  }
117
117
  };
118
118
  // 🔑 核心改造:检测steer模式
119
- // 需要提前解析消息以获取sessionId
120
- try {
121
- const parsed = parseA2AMessage(message);
122
- const steerMode = cfg.messages?.queue?.mode === "steer";
123
- const hasActiveRun = hasActiveTask(parsed.sessionId);
124
- if (steerMode && hasActiveRun) {
125
- // Steer模式且有活跃任务:不入队列,直接并发执行
126
- logger.log(`[MONITOR-HANDLER] STEER MODE: Executing concurrently for messageKey=${messageKey}`);
127
- void task().catch((err) => {
128
- logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
129
- activeMessages.delete(messageKey);
130
- });
119
+ // clearContext / tasks/cancel 没有 params,跳过 parseA2AMessage 直接入队
120
+ const messageMethod = message.method;
121
+ if (messageMethod === "clearContext" || messageMethod === "clear_context"
122
+ || messageMethod === "tasks/cancel" || messageMethod === "tasks_cancel") {
123
+ void enqueue(sessionId, task).catch((err) => {
124
+ logger.error(`XY gateway: queue processing failed: ${String(err)}`);
125
+ activeMessages.delete(messageKey);
126
+ });
127
+ }
128
+ else {
129
+ try {
130
+ const parsed = parseA2AMessage(message);
131
+ const steerMode = cfg.messages?.queue?.mode === "steer";
132
+ const hasActiveRun = hasActiveTask(parsed.sessionId);
133
+ if (steerMode && hasActiveRun) {
134
+ // Steer模式且有活跃任务:不入队列,直接并发执行
135
+ logger.log(`[MONITOR-HANDLER] STEER MODE: Executing concurrently for messageKey=${messageKey}`);
136
+ void task().catch((err) => {
137
+ logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
138
+ activeMessages.delete(messageKey);
139
+ });
140
+ }
141
+ else {
142
+ // 正常模式:入队列串行执行
143
+ void enqueue(sessionId, task).catch((err) => {
144
+ logger.error(`XY gateway: queue processing failed: ${String(err)}`);
145
+ activeMessages.delete(messageKey);
146
+ });
147
+ }
131
148
  }
132
- else {
133
- // 正常模式:入队列串行执行
149
+ catch (parseErr) {
150
+ // 解析失败,回退到正常队列模式
151
+ logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
134
152
  void enqueue(sessionId, task).catch((err) => {
135
153
  logger.error(`XY gateway: queue processing failed: ${String(err)}`);
136
154
  activeMessages.delete(messageKey);
137
155
  });
138
156
  }
139
157
  }
140
- catch (parseErr) {
141
- // 解析失败,回退到正常队列模式
142
- logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
143
- void enqueue(sessionId, task).catch((err) => {
144
- logger.error(`XY gateway: queue processing failed: ${String(err)}`);
145
- activeMessages.delete(messageKey);
146
- });
147
- }
148
158
  };
149
159
  const connectedHandler = (serverId) => {
150
160
  if (!loggedServers.has(serverId)) {
@@ -175,7 +185,9 @@ export async function monitorXYProvider(opts = {}) {
175
185
  };
176
186
  const selfEvolutionHandler = (context) => {
177
187
  logger.log(`[MONITOR] Received self-evolution-event, dispatching to handler...`);
178
- handleSelfEvolutionEvent(context, runtime);
188
+ handleSelfEvolutionEvent(context, cfg).catch((err) => {
189
+ logger.error(`[MONITOR] Failed to handle self-evolution-event:`, err);
190
+ });
179
191
  };
180
192
  const selfEvolutionStateGetHandler = (context) => {
181
193
  logger.log(`[MONITOR] Received self-evolution-state-get-event, dispatching to handler...`);
@@ -50,6 +50,12 @@ export declare function extractPushId(parts: A2AMessagePart[]): string | null;
50
50
  * (same level as push_id).
51
51
  */
52
52
  export declare function extractDeviceType(parts: A2AMessagePart[]): string | null;
53
+ /**
54
+ * Extract modelName from message parts.
55
+ * Looks for modelName in data parts under variables.clientVariables.modelName
56
+ * (same level as systemVariables).
57
+ */
58
+ export declare function extractModelName(parts: A2AMessagePart[]): string | null;
53
59
  /**
54
60
  * Extract Trigger event data from message parts.
55
61
  * Looks for Trigger events with pushDataId in data parts.
@@ -143,6 +143,22 @@ export function extractDeviceType(parts) {
143
143
  }
144
144
  return null;
145
145
  }
146
+ /**
147
+ * Extract modelName from message parts.
148
+ * Looks for modelName in data parts under variables.clientVariables.modelName
149
+ * (same level as systemVariables).
150
+ */
151
+ export function extractModelName(parts) {
152
+ for (const part of parts) {
153
+ if (part.kind === "data" && part.data) {
154
+ const modelName = part.data.variables?.clientVariables?.modelName;
155
+ if (modelName && typeof modelName === "string" && modelName.trim() !== "" && modelName.toLowerCase() !== "none") {
156
+ return modelName;
157
+ }
158
+ }
159
+ }
160
+ return null;
161
+ }
146
162
  /**
147
163
  * Extract Trigger event data from message parts.
148
164
  * Looks for Trigger events with pushDataId in data parts.
@@ -417,6 +417,32 @@ export const xiaoyiProvider = {
417
417
  docsPath: "/providers/models",
418
418
  auth: [],
419
419
  isCacheTtlEligible: () => true,
420
+ /**
421
+ * Dynamic model resolution for A2A-specified model names.
422
+ * A2A messages carry a dynamic modelName that isn't in any static catalog.
423
+ * This hook lets OpenClaw's resolveModelAsync accept any model ID under
424
+ * xiaoyiprovider as long as the provider has a configured baseUrl.
425
+ */
426
+ resolveDynamicModel: (ctx) => {
427
+ const baseUrl = ctx.providerConfig?.baseUrl;
428
+ if (!baseUrl || typeof baseUrl !== "string")
429
+ return null;
430
+ return {
431
+ id: ctx.modelId,
432
+ name: ctx.modelId,
433
+ api: ctx.providerConfig?.api ?? "openai-completions",
434
+ provider: "xiaoyiprovider",
435
+ baseUrl,
436
+ reasoning: false,
437
+ input: ["text"],
438
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
439
+ contextWindow: 128_000,
440
+ maxTokens: 8192,
441
+ ...(ctx.providerConfig?.headers && typeof ctx.providerConfig.headers === "object"
442
+ ? { headers: ctx.providerConfig.headers }
443
+ : {}),
444
+ };
445
+ },
420
446
  /**
421
447
  * Store uid-based fallback prefix for lazy timestamp generation in wrapStreamFn.
422
448
  * Session-level headers (traceId / sessionId / interactionId) are resolved
@@ -587,6 +613,12 @@ export const xiaoyiProvider = {
587
613
  }
588
614
  }
589
615
  }
616
+ // ── Override model.id if A2A message specified modelName ──
617
+ const modelNameOverride = getCurrentSessionContext()?.modelName;
618
+ if (modelNameOverride && modelNameOverride.trim() !== "" && modelNameOverride.toLowerCase() !== "none") {
619
+ logger.log(`[xiaoyiprovider] overriding model.id: ${model.id} → ${modelNameOverride}`);
620
+ model = { ...model, id: modelNameOverride };
621
+ }
590
622
  // ── Retry-capable streaming ──────────────────────────────
591
623
  const cronJob = isCronTriggered(context.messages);
592
624
  if (cronJob)
@@ -2,7 +2,7 @@ import { getXYRuntime } from "./runtime.js";
2
2
  import { sendA2AResponse, sendStatusUpdate, sendReasoningTextUpdate, sendCommand } from "./formatter.js";
3
3
  import { resolveXYConfig } from "./config.js";
4
4
  import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
5
- import { getCurrentSessionContext } from "./tools/session-manager.js";
5
+ import { clearRunCrossTaskSentFiles, getCurrentSessionContext } from "./tools/session-manager.js";
6
6
  import fs from "fs/promises";
7
7
  import path from "path";
8
8
  import { logger } from "./utils/logger.js";
@@ -48,7 +48,8 @@ async function sendRunCrossTaskResult(params) {
48
48
  messageId,
49
49
  commands: [statusCommand, resultCommand],
50
50
  });
51
- logger.log(`${RUN_CROSS_TASK_LOG_TAG} sent cross-task result, sessionId=${sessionId}, taskId=${taskId}, code=${resultCode}, sentFileCount=${sentFiles.length}, messageLength=${resultMessage.length}`);
51
+ clearRunCrossTaskSentFiles(context);
52
+ logger.log(`${RUN_CROSS_TASK_LOG_TAG} sent cross-task result, sessionId=${sessionId}, taskId=${taskId}, code=${resultCode}, sentFileCount=${sentFiles.length}, clearedSentFileCount=${sentFiles.length}, messageLength=${resultMessage.length}`);
52
53
  }
53
54
  /**
54
55
  * 清理 /tmp/xy_channel 目录中超过 24 小时的旧文件
@@ -171,18 +172,23 @@ export function createXYReplyDispatcher(params) {
171
172
  scopedLog().log(`[DELIVER SKIP] Empty text, skipping`);
172
173
  return;
173
174
  }
175
+ // 🔑 如果 onPartialReply 已经流式发送过文本,deliver 不再重复发送
176
+ if (hasSentResponse) {
177
+ scopedLog().log(`[DELIVER SKIP] Already sent via onPartialReply`);
178
+ return;
179
+ }
174
180
  accumulatedText += text;
175
181
  hasSentResponse = true;
176
- scopedLog().log(`[DELIVER] Accumulated text, length=${accumulatedText.length}`);
177
- // 🔑 使用动态taskId发送reasoningText更新
178
- await sendReasoningTextUpdate({
182
+ // 🔑 使用动态taskId发送A2A响应(流式append)
183
+ await sendA2AResponse({
179
184
  config,
180
185
  sessionId,
181
186
  taskId: currentTaskId,
182
187
  messageId: currentMessageId,
183
188
  text,
189
+ append: true,
190
+ final: false,
184
191
  });
185
- scopedLog().log(`[DELIVER] Sent deliver text as reasoningText update`);
186
192
  }
187
193
  catch (deliverError) {
188
194
  scopedLog().error(`Failed to deliver message:`, deliverError);
@@ -250,18 +256,18 @@ export function createXYReplyDispatcher(params) {
250
256
  state: "completed",
251
257
  });
252
258
  scopedLog().log(`[ON-IDLE] Sent completion status update`);
253
- // 🔑 使用动态taskId发送最终响应
259
+ // 🔑 使用动态taskId发送最终响应(空字符串表示流结束)
254
260
  await sendA2AResponse({
255
261
  config,
256
262
  sessionId,
257
263
  taskId: currentTaskId,
258
264
  messageId: currentMessageId,
259
- text: accumulatedText,
260
- append: false,
265
+ text: "",
266
+ append: true,
261
267
  final: true,
262
268
  });
263
269
  finalSent = true;
264
- scopedLog().log(`[ON-IDLE] Sent final response`);
270
+ scopedLog().log(`[ON-IDLE] Sent final response (empty, stream end)`);
265
271
  }
266
272
  catch (err) {
267
273
  scopedLog().error(`[ON-IDLE] Failed to send final response:`, err);
@@ -298,7 +304,7 @@ export function createXYReplyDispatcher(params) {
298
304
  taskId: currentTaskId,
299
305
  messageId: currentMessageId,
300
306
  text: "任务执行异常,请重试~",
301
- append: false,
307
+ append: true,
302
308
  final: true,
303
309
  errorCode: 99921111,
304
310
  errorMessage: "任务执行异常,请重试",
@@ -388,10 +394,30 @@ export function createXYReplyDispatcher(params) {
388
394
  if (steerState.steered) {
389
395
  return;
390
396
  }
391
- const text = payload.text ?? "";
392
- scopedLog().log(`[REASONING-STREAM] Reasoning chunk received, text.length: ${text.length}`);
393
- // Reasoning stream 目前被注释掉
394
- // 如果需要可以启用
397
+ const currentTaskId = getActiveTaskId();
398
+ const currentMessageId = getActiveMessageId();
399
+ let text = payload.text ?? "";
400
+ // Strip "Reasoning:" prefix that some reasoning models add to their thinking output
401
+ const lines = text.split(/\r?\n/);
402
+ if (lines[0]?.trim() === "Reasoning:") {
403
+ text = lines.slice(1).join("\n").trim();
404
+ }
405
+ scopedLog().log(`[REASONING-STREAM] ${text.substring(0, 100)}`);
406
+ try {
407
+ if (text.length > 0) {
408
+ await sendReasoningTextUpdate({
409
+ config,
410
+ sessionId,
411
+ taskId: currentTaskId,
412
+ messageId: currentMessageId,
413
+ text,
414
+ append: false,
415
+ });
416
+ }
417
+ }
418
+ catch (err) {
419
+ scopedLog().error(`[REASONING-STREAM] Failed to send reasoning text:`, err);
420
+ }
395
421
  },
396
422
  onPartialReply: async (payload) => {
397
423
  // 🔑 steered dispatch不发送partial reply(让主dispatcher处理)
@@ -403,18 +429,22 @@ export function createXYReplyDispatcher(params) {
403
429
  const text = payload.text ?? "";
404
430
  try {
405
431
  if (text.length > 0) {
406
- await sendReasoningTextUpdate({
432
+ accumulatedText += text;
433
+ hasSentResponse = true;
434
+ await sendA2AResponse({
407
435
  config,
408
436
  sessionId,
409
437
  taskId: currentTaskId,
410
438
  messageId: currentMessageId,
411
439
  text,
412
440
  append: false,
441
+ final: false,
442
+ log: false,
413
443
  });
414
444
  }
415
445
  }
416
446
  catch (err) {
417
- scopedLog().error(`[PARTIAL REPLY] Failed to send partial reply:`, err);
447
+ scopedLog().error(`[PARTIAL-REPLY] Failed to send partial reply:`, err);
418
448
  }
419
449
  },
420
450
  },
@@ -1,5 +1,5 @@
1
1
  import type { XYWebSocketManager } from "./websocket.js";
2
- export declare function handleSelfEvolutionEvent(context: any, runtime: any): void;
2
+ export declare function handleSelfEvolutionEvent(context: any, cfg: any): Promise<void>;
3
3
  /**
4
4
  * 读取 .xiaoyiruntime 中的 selfEvolutionState 并直接通过 wsManager 下发指令回复设备
5
5
  * 参考trigger实现:直接使用当前已连接的 wsManager 发送消息,避免 getXYWebSocketManager 返回未连接实例
@@ -1,14 +1,20 @@
1
1
  import { readFileSync, writeFileSync } from "fs";
2
2
  import { v4 as uuidv4 } from "uuid";
3
+ import { resolveXYConfig } from "./config.js";
4
+ import { sendA2AResponse } from "./formatter.js";
3
5
  import { logger } from "./utils/logger.js";
4
6
  const XIAOYIRUNTIME_PATH = "/home/sandbox/.openclaw/.xiaoyiruntime";
5
- export function handleSelfEvolutionEvent(context, runtime) {
7
+ export async function handleSelfEvolutionEvent(context, cfg) {
6
8
  try {
7
9
  const state = context.event?.payload?.selfEvolutionState;
8
10
  if (typeof state !== "string") {
9
11
  logger.error("[SELF_EVOLUTION] invalid payload: missing selfEvolutionState");
10
12
  return;
11
13
  }
14
+ const sessionId = context.sessionId ?? "";
15
+ const taskId = context.taskId ?? sessionId;
16
+ const messageId = context.messageId ?? uuidv4();
17
+ const config = resolveXYConfig(cfg);
12
18
  logger.log(`[SELF_EVOLUTION] received state: ${state}`);
13
19
  let content;
14
20
  try {
@@ -19,6 +25,8 @@ export function handleSelfEvolutionEvent(context, runtime) {
19
25
  logger.log(`[SELF_EVOLUTION] ${XIAOYIRUNTIME_PATH} not found, creating new file`);
20
26
  writeFileSync(XIAOYIRUNTIME_PATH, `selfEvolutionState=${state}\n`, "utf-8");
21
27
  logger.log(`[SELF_EVOLUTION] wrote selfEvolutionState=${state}`);
28
+ await sendA2AResponse({ config, sessionId, taskId, messageId, text: "", append: false, final: true });
29
+ logger.log(`[SELF_EVOLUTION] Sent final response (empty, stream end)`);
22
30
  return;
23
31
  }
24
32
  const lines = content.split("\n");
@@ -40,6 +48,9 @@ export function handleSelfEvolutionEvent(context, runtime) {
40
48
  writeFileSync(XIAOYIRUNTIME_PATH, updated.join("\n"), "utf-8");
41
49
  }
42
50
  logger.log(`[SELF_EVOLUTION] updated selfEvolutionState=${state} in ${XIAOYIRUNTIME_PATH}`);
51
+ // Reply with final empty response to acknowledge the state update
52
+ await sendA2AResponse({ config, sessionId, taskId, messageId, text: "", append: false, final: true });
53
+ logger.log(`[SELF_EVOLUTION] Sent final response (empty, stream end)`);
43
54
  }
44
55
  catch (err) {
45
56
  logger.error("[SELF_EVOLUTION] failed to handle event:", err);
@@ -106,7 +106,7 @@ export function createCalendarTool(ctx) {
106
106
  });
107
107
  }
108
108
  else {
109
- reject(new Error(`创建日程失败: ${event.status}`));
109
+ reject(new Error(`创建日程失败: ${JSON.stringify(event.outputs)}`));
110
110
  }
111
111
  }
112
112
  };
@@ -22,7 +22,6 @@ import { createUploadFileTool } from "./upload-file-tool.js";
22
22
  import { createSaveFileToPhoneTool } from "./save-file-to-phone-tool.js";
23
23
  import { createSendEmailTool } from "./send-email-tool.js";
24
24
  import { createSearchEmailTool } from "./search-email-tool.js";
25
- import { createFindPcDevicesTool } from "./find-pc-devices-tool.js";
26
25
  import { sendStatusUpdate } from "../formatter.js";
27
26
  import { getCurrentTaskId, getCurrentMessageId } from "../task-manager.js";
28
27
  /**
@@ -55,7 +54,6 @@ export function createCallDeviceTool(ctx) {
55
54
  const searchFileTool = createSearchFileTool(ctx);
56
55
  const saveFileToPhoneTool = createSaveFileToPhoneTool(ctx);
57
56
  const searchEmailTool = createSearchEmailTool(ctx);
58
- const findPcDevicesTool = createFindPcDevicesTool(ctx);
59
57
  /**
60
58
  * 端工具注册表 —— 按 name 索引所有可通过 call_device_tool 调度的工具。
61
59
  */
@@ -84,7 +82,6 @@ export function createCallDeviceTool(ctx) {
84
82
  [saveFileToPhoneTool.name, saveFileToPhoneTool],
85
83
  [sendEmailTool.name, sendEmailTool],
86
84
  [searchEmailTool.name, searchEmailTool],
87
- [findPcDevicesTool.name, findPcDevicesTool],
88
85
  ]);
89
86
  return {
90
87
  name: "call_device_tool",
@@ -98,7 +98,7 @@ export function createCallPhoneTool(ctx) {
98
98
  });
99
99
  }
100
100
  else {
101
- reject(new Error(`拨打电话失败: ${event.status}`));
101
+ reject(new Error(`拨打电话失败: ${JSON.stringify(event.outputs)}`));
102
102
  }
103
103
  }
104
104
  };
@@ -0,0 +1,6 @@
1
+ import type { SessionContext } from "./session-manager.js";
2
+ /**
3
+ * XY check plugin privilege tool - checks user authorization for device-side tools
4
+ * used in scheduled tasks.
5
+ */
6
+ export declare function createCheckPluginPrivilegeTool(ctx: SessionContext): any;