@ynhcj/xiaoyi-channel 0.0.115-beta → 0.0.115-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 (132) hide show
  1. package/dist/index.d.ts +4 -5
  2. package/dist/index.js +72 -82
  3. package/dist/provider-discovery.d.ts +2 -0
  4. package/dist/provider-discovery.js +4 -0
  5. package/dist/src/bot.d.ts +2 -0
  6. package/dist/src/bot.js +80 -72
  7. package/dist/src/channel.js +2 -17
  8. package/dist/src/client.d.ts +1 -5
  9. package/dist/src/client.js +32 -37
  10. package/dist/src/cspl/call-api.js +6 -5
  11. package/dist/src/file-download.js +4 -3
  12. package/dist/src/file-upload.js +19 -18
  13. package/dist/src/formatter.js +32 -44
  14. package/dist/src/heartbeat.js +4 -3
  15. package/dist/src/login-token-handler.js +7 -8
  16. package/dist/src/message-queue.js +2 -1
  17. package/dist/src/monitor.js +62 -41
  18. package/dist/src/outbound.js +22 -18
  19. package/dist/src/provider.d.ts +1 -1
  20. package/dist/src/provider.js +124 -34
  21. package/dist/src/push.js +16 -15
  22. package/dist/src/reply-dispatcher.js +47 -48
  23. package/dist/src/runtime.d.ts +3 -11
  24. package/dist/src/runtime.js +6 -18
  25. package/dist/src/self-evolution-handler.js +11 -14
  26. package/dist/src/self-evolution-tool-result-nudge.d.ts +3 -0
  27. package/dist/src/self-evolution-tool-result-nudge.js +96 -0
  28. package/dist/src/skill-retriever/hooks.js +7 -15
  29. package/dist/src/skill-retriever/tool-search.js +13 -9
  30. package/dist/src/steer-injector.js +1 -1
  31. package/dist/src/task-manager.js +6 -1
  32. package/dist/src/tools/calendar-tool.d.ts +2 -1
  33. package/dist/src/tools/calendar-tool.js +112 -116
  34. package/dist/src/tools/call-device-tool.d.ts +2 -1
  35. package/dist/src/tools/call-device-tool.js +126 -103
  36. package/dist/src/tools/call-phone-tool.d.ts +2 -1
  37. package/dist/src/tools/call-phone-tool.js +109 -113
  38. package/dist/src/tools/create-alarm-tool.d.ts +2 -1
  39. package/dist/src/tools/create-alarm-tool.js +227 -231
  40. package/dist/src/tools/create-all-tools.d.ts +16 -0
  41. package/dist/src/tools/create-all-tools.js +50 -0
  42. package/dist/src/tools/delete-alarm-tool.d.ts +2 -1
  43. package/dist/src/tools/delete-alarm-tool.js +131 -135
  44. package/dist/src/tools/get-alarm-tool-schema.d.ts +2 -1
  45. package/dist/src/tools/get-alarm-tool-schema.js +16 -10
  46. package/dist/src/tools/get-calendar-tool-schema.d.ts +2 -1
  47. package/dist/src/tools/get-calendar-tool-schema.js +12 -8
  48. package/dist/src/tools/get-collection-tool-schema.d.ts +2 -1
  49. package/dist/src/tools/get-collection-tool-schema.js +11 -9
  50. package/dist/src/tools/get-contact-tool-schema.d.ts +2 -1
  51. package/dist/src/tools/get-contact-tool-schema.js +16 -10
  52. package/dist/src/tools/get-device-file-tool-schema.d.ts +2 -1
  53. package/dist/src/tools/get-device-file-tool-schema.js +13 -9
  54. package/dist/src/tools/get-email-tool-schema.d.ts +2 -1
  55. package/dist/src/tools/get-email-tool-schema.js +11 -8
  56. package/dist/src/tools/get-note-tool-schema.d.ts +2 -1
  57. package/dist/src/tools/get-note-tool-schema.js +14 -9
  58. package/dist/src/tools/get-photo-tool-schema.d.ts +2 -1
  59. package/dist/src/tools/get-photo-tool-schema.js +12 -9
  60. package/dist/src/tools/image-reading-tool.d.ts +3 -2
  61. package/dist/src/tools/image-reading-tool.js +82 -162
  62. package/dist/src/tools/location-tool.d.ts +2 -1
  63. package/dist/src/tools/location-tool.js +87 -91
  64. package/dist/src/tools/login-token-tool.d.ts +2 -1
  65. package/dist/src/tools/login-token-tool.js +113 -116
  66. package/dist/src/tools/modify-alarm-tool.d.ts +2 -1
  67. package/dist/src/tools/modify-alarm-tool.js +232 -236
  68. package/dist/src/tools/modify-note-tool.d.ts +2 -1
  69. package/dist/src/tools/modify-note-tool.js +104 -108
  70. package/dist/src/tools/note-tool.d.ts +2 -1
  71. package/dist/src/tools/note-tool.js +103 -107
  72. package/dist/src/tools/query-app-message-tool.d.ts +2 -1
  73. package/dist/src/tools/query-app-message-tool.js +108 -111
  74. package/dist/src/tools/query-memory-data-tool.d.ts +2 -1
  75. package/dist/src/tools/query-memory-data-tool.js +109 -112
  76. package/dist/src/tools/query-todo-task-tool.d.ts +2 -1
  77. package/dist/src/tools/query-todo-task-tool.js +103 -106
  78. package/dist/src/tools/save-file-to-phone-tool.d.ts +2 -1
  79. package/dist/src/tools/save-file-to-phone-tool.js +127 -131
  80. package/dist/src/tools/save-media-to-gallery-tool.d.ts +2 -1
  81. package/dist/src/tools/save-media-to-gallery-tool.js +134 -138
  82. package/dist/src/tools/save-self-evolution-skill-tool.d.ts +2 -1
  83. package/dist/src/tools/save-self-evolution-skill-tool.js +194 -196
  84. package/dist/src/tools/search-alarm-tool.d.ts +2 -1
  85. package/dist/src/tools/search-alarm-tool.js +171 -175
  86. package/dist/src/tools/search-calendar-tool.d.ts +2 -1
  87. package/dist/src/tools/search-calendar-tool.js +145 -149
  88. package/dist/src/tools/search-contact-tool.d.ts +2 -1
  89. package/dist/src/tools/search-contact-tool.js +98 -102
  90. package/dist/src/tools/search-email-tool.d.ts +2 -1
  91. package/dist/src/tools/search-email-tool.js +107 -111
  92. package/dist/src/tools/search-file-tool.d.ts +2 -1
  93. package/dist/src/tools/search-file-tool.js +99 -103
  94. package/dist/src/tools/search-message-tool.d.ts +2 -1
  95. package/dist/src/tools/search-message-tool.js +100 -104
  96. package/dist/src/tools/search-note-tool.d.ts +2 -1
  97. package/dist/src/tools/search-note-tool.js +95 -99
  98. package/dist/src/tools/search-photo-gallery-tool.d.ts +2 -1
  99. package/dist/src/tools/search-photo-gallery-tool.js +34 -38
  100. package/dist/src/tools/send-email-tool.d.ts +2 -1
  101. package/dist/src/tools/send-email-tool.js +105 -108
  102. package/dist/src/tools/send-file-to-user-tool.d.ts +2 -1
  103. package/dist/src/tools/send-file-to-user-tool.js +157 -155
  104. package/dist/src/tools/send-message-tool.d.ts +2 -1
  105. package/dist/src/tools/send-message-tool.js +119 -123
  106. package/dist/src/tools/session-helper.d.ts +24 -0
  107. package/dist/src/tools/session-helper.js +45 -0
  108. package/dist/src/tools/session-manager.d.ts +29 -6
  109. package/dist/src/tools/session-manager.js +134 -19
  110. package/dist/src/tools/upload-file-tool.d.ts +2 -1
  111. package/dist/src/tools/upload-file-tool.js +78 -82
  112. package/dist/src/tools/upload-photo-tool.d.ts +2 -1
  113. package/dist/src/tools/upload-photo-tool.js +69 -73
  114. package/dist/src/tools/xiaoyi-add-collection-tool.d.ts +2 -1
  115. package/dist/src/tools/xiaoyi-add-collection-tool.js +143 -147
  116. package/dist/src/tools/xiaoyi-collection-tool.d.ts +2 -1
  117. package/dist/src/tools/xiaoyi-collection-tool.js +111 -115
  118. package/dist/src/tools/xiaoyi-delete-collection-tool.d.ts +2 -1
  119. package/dist/src/tools/xiaoyi-delete-collection-tool.js +124 -128
  120. package/dist/src/tools/xiaoyi-gui-tool.d.ts +2 -1
  121. package/dist/src/tools/xiaoyi-gui-tool.js +87 -88
  122. package/dist/src/trigger-handler.js +8 -9
  123. package/dist/src/utils/logger.js +105 -19
  124. package/dist/src/utils/self-evolution-manager.d.ts +5 -0
  125. package/dist/src/utils/self-evolution-manager.js +45 -23
  126. package/dist/src/utils/throw.d.ts +5 -0
  127. package/dist/src/utils/throw.js +10 -0
  128. package/dist/src/websocket.js +35 -31
  129. package/dist/src/xy-session-store.d.ts +79 -0
  130. package/dist/src/xy-session-store.js +153 -0
  131. package/openclaw.plugin.json +22 -0
  132. package/package.json +7 -6
@@ -8,9 +8,9 @@
8
8
  // models.providers.xiaoyiprovider.api = "openai-completions"
9
9
  // models.providers.xiaoyiprovider.models = [...]
10
10
  import { createHash } from "crypto";
11
+ import { logger } from "./utils/logger.js";
11
12
  import { getCurrentSessionContext } from "./tools/session-manager.js";
12
13
  import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
13
- import { logger } from "./utils/logger.js";
14
14
  // ── Retry config ──────────────────────────────────────────────
15
15
  const RETRY_DELAYS_MS = [10_000, 20_000, 40_000, 60_000, 60_000];
16
16
  const MAX_RETRY_ATTEMPTS = 5;
@@ -127,7 +127,7 @@ function createRetryingStream(createStream, cronJob) {
127
127
  if (!hasContent && !isContent) {
128
128
  // ── Buffer phase (no content yet) ──
129
129
  if (event.type === "done") {
130
- console.log(`[xiaoyiprovider] stream completed (no content), usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
130
+ logger.log(`[xiaoyiprovider] stream completed (no content), usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
131
131
  for (const b of buffer)
132
132
  yield b;
133
133
  resultResolve(event.message);
@@ -142,7 +142,7 @@ function createRetryingStream(createStream, cronJob) {
142
142
  else {
143
143
  // ── Streaming phase ──
144
144
  if (!hasContent) {
145
- console.log("[xiaoyiprovider] first content event received, switching to streaming mode");
145
+ logger.log("[xiaoyiprovider] first content event received, switching to streaming mode");
146
146
  hasContent = true;
147
147
  for (const b of buffer)
148
148
  yield b;
@@ -151,33 +151,32 @@ function createRetryingStream(createStream, cronJob) {
151
151
  // The SDK calls result() when it sees done/error — if we yield first, the generator
152
152
  // suspends and can never reach resolve, causing a permanent deadlock.
153
153
  if (event.type === "done") {
154
- console.log(`[xiaoyiprovider] stream completed, usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
154
+ logger.log(`[xiaoyiprovider] stream completed, usage: input=${event.message?.usage?.input} output=${event.message?.usage?.output}`);
155
155
  resultResolve(event.message);
156
156
  yield event;
157
157
  return;
158
158
  }
159
159
  if (event.type === "error") {
160
- console.log(`[xiaoyiprovider] stream error after content: ${event.error?.errorMessage}`);
161
- resultResolve(event.error);
162
- yield event;
163
- return;
160
+ logger.log(`[xiaoyiprovider] stream error after content: ${event.error?.errorMessage}`);
161
+ errorResult = event.error;
162
+ break; // break inner loop, proceed to retry decision
164
163
  }
165
164
  yield event;
166
165
  }
167
166
  }
168
- // Stream ended during buffer phase — decide whether to retry
167
+ // Stream ended (buffer or streaming phase) — decide whether to retry
169
168
  if (errorResult?.stopReason === "error" && isRetryableProviderError(errorResult.errorMessage)) {
170
169
  if (attempt < MAX_RETRY_ATTEMPTS - 1) {
171
170
  const delayMs = getRetryDelayMs(attempt + 1, cronJob);
172
- console.log(`[xiaoyiprovider] retryable error (attempt ${attempt + 1}/${MAX_RETRY_ATTEMPTS}): ` +
171
+ logger.log(`[xiaoyiprovider] retryable error (attempt ${attempt + 1}/${MAX_RETRY_ATTEMPTS}): ` +
173
172
  `${errorResult.errorMessage} — retrying in ${delayMs}ms`);
174
173
  await sleep(delayMs);
175
174
  continue; // discard buffer, retry with a new stream
176
175
  }
177
- console.log(`[xiaoyiprovider] all ${MAX_RETRY_ATTEMPTS} retries exhausted, surfacing last error`);
176
+ logger.log(`[xiaoyiprovider] all ${MAX_RETRY_ATTEMPTS} retries exhausted, surfacing last error`);
178
177
  }
179
178
  else if (errorResult) {
180
- console.log(`[xiaoyiprovider] non-retryable error: ${errorResult.errorMessage}`);
179
+ logger.log(`[xiaoyiprovider] non-retryable error: ${errorResult.errorMessage}`);
181
180
  }
182
181
  // Non-retryable or retries exhausted — yield buffered events.
183
182
  // Resolve before yielding the terminal event to avoid the same deadlock.
@@ -192,11 +191,12 @@ function createRetryingStream(createStream, cronJob) {
192
191
  }
193
192
  if (errorResult && buffer.every(b => b.type !== "done" && b.type !== "error")) {
194
193
  resultResolve(errorResult);
194
+ yield { type: "error", reason: "error", error: errorResult };
195
195
  }
196
196
  return;
197
197
  }
198
198
  // Safety: final fallback attempt
199
- console.log("[xiaoyiprovider] entering final fallback attempt");
199
+ logger.log("[xiaoyiprovider] entering final fallback attempt");
200
200
  const lastStream = await createStream();
201
201
  for await (const event of lastStream) {
202
202
  if (event.type === "done") {
@@ -230,6 +230,8 @@ const HEADER_SESSION_ID = "x-session-id";
230
230
  const HEADER_INTERACTION_ID = "x-interaction-id";
231
231
  /** Internal key for passing fallback uid prefix from prepareExtraParams to wrapStreamFn. */
232
232
  const FALLBACK_PREFIX_KEY = "_xiaoyi_fallback_prefix";
233
+ /** Internal key for passing deviceType from prepareExtraParams to wrapStreamFn. */
234
+ const DEVICE_TYPE_KEY = "_xiaoyi_device_type";
233
235
  const SELF_EVOLUTION_PROMPT_BEGIN = "<self_evolution_prompt>";
234
236
  const SELF_EVOLUTION_PROMPT_END = "</self_evolution_prompt>";
235
237
  const SELF_EVOLUTION_ENABLED_PROMPT_SECTION = `
@@ -370,6 +372,39 @@ function encodeUid(uid) {
370
372
  function getUidFromConfig(config) {
371
373
  return config?.channels?.["xiaoyi-channel"]?.uid;
372
374
  }
375
+ /**
376
+ * Trim user message metadata:
377
+ * 1. In "Conversation info (untrusted metadata)" JSON, keep only timestamp
378
+ * 2. Remove "Sender (untrusted metadata)" section entirely
379
+ */
380
+ function trimUserMetadata(text) {
381
+ // 1. Conversation info: keep only timestamp
382
+ text = text.replace(/(Conversation info \(untrusted metadata\):\n```json\n)([\s\S]*?)(\n```)/, (_match, prefix, json, suffix) => {
383
+ const tsMatch = json.match(/"timestamp"\s*:\s*"([^"]+)"/);
384
+ return tsMatch
385
+ ? `${prefix}{\n "timestamp": "${tsMatch[1]}"\n}\n${suffix}`
386
+ : _match;
387
+ });
388
+ // 2. Sender: remove entirely
389
+ text = text.replace(/\n*Sender \(untrusted metadata\):\n```json\n[\s\S]*?\n```\n*/, "\n");
390
+ return text.replace(/\n{3,}/g, "\n\n");
391
+ }
392
+ /**
393
+ * Extract A2A taskId and deviceType from Conversation info JSON.
394
+ * bot.ts stores them as MessageSid = "taskId_deviceType".
395
+ */
396
+ function extractA2AFromConversationInfo(text) {
397
+ const match = text.match(/Conversation info \(untrusted metadata\):\n```json\n([\s\S]*?)\n```/);
398
+ if (!match)
399
+ return null;
400
+ const msgIdMatch = match[1].match(/"message_id"\s*:\s*"([^"]+)"/);
401
+ if (!msgIdMatch)
402
+ return null;
403
+ const parts = msgIdMatch[1].split("_");
404
+ if (parts.length < 2)
405
+ return null;
406
+ return { taskId: parts[0], deviceType: parts[1] };
407
+ }
373
408
  export const xiaoyiProvider = {
374
409
  id: "xiaoyiprovider",
375
410
  label: "Xiaoyi Provider",
@@ -396,6 +431,7 @@ export const xiaoyiProvider = {
396
431
  [HEADER_TRACE_ID]: taskId,
397
432
  [HEADER_SESSION_ID]: sessionId,
398
433
  [HEADER_INTERACTION_ID]: interactionId,
434
+ [DEVICE_TYPE_KEY]: sessionCtx.deviceType ?? "",
399
435
  };
400
436
  }
401
437
  // Fallback: store uid prefix for lazy timestamp generation in wrapStreamFn.
@@ -419,12 +455,38 @@ export const xiaoyiProvider = {
419
455
  * since the default agent timeout is 48 hours).
420
456
  */
421
457
  wrapStreamFn: (ctx) => {
458
+ logger.log("[xiaoyiprovider] wrapStreamFn CALLED — provider resolved by openclaw");
422
459
  const underlying = ctx.streamFn;
423
460
  if (!underlying)
424
461
  return underlying;
425
462
  return async (model, context, options) => {
426
- // 每次请求时从 ctx.extraParams 动态读取 header
427
463
  const dynamicHeaders = {};
464
+ // ── Extract A2A taskId/deviceType from Conversation info ──
465
+ // bot.ts stores taskId_deviceType as MessageSid, which the framework
466
+ // renders as message_id in the Conversation info JSON block.
467
+ let extractedTaskId = null;
468
+ let extractedDeviceType = null;
469
+ if (context.messages) {
470
+ for (let i = context.messages.length - 1; i >= 0; i--) {
471
+ const msg = context.messages[i];
472
+ if (msg.role !== "user")
473
+ continue;
474
+ const text = typeof msg.content === "string"
475
+ ? msg.content
476
+ : Array.isArray(msg.content)
477
+ ? msg.content.find((b) => b.type === "text")?.text ?? ""
478
+ : "";
479
+ if (!text)
480
+ continue;
481
+ const extracted = extractA2AFromConversationInfo(text);
482
+ if (extracted) {
483
+ extractedTaskId = extracted.taskId;
484
+ extractedDeviceType = extracted.deviceType;
485
+ break;
486
+ }
487
+ }
488
+ }
489
+ // ── Build dynamic headers ────────────────────────────
428
490
  if (ctx.extraParams) {
429
491
  const fallbackPrefix = ctx.extraParams[FALLBACK_PREFIX_KEY];
430
492
  if (typeof fallbackPrefix === "string") {
@@ -442,22 +504,30 @@ export const xiaoyiProvider = {
442
504
  dynamicHeaders["x-cron-flag"] = "begin";
443
505
  }
444
506
  }
507
+ else if (extractedTaskId) {
508
+ // Session mode: taskId extracted from Conversation info
509
+ const traceId = extractedTaskId;
510
+ const sessionId = traceId.split("&")[0];
511
+ const interactionId = traceId.split("&")[1] ?? "";
512
+ const isCron = isCronTriggered(context.messages);
513
+ dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
514
+ if (isCron) {
515
+ const cronTitle = extractCronTitle(context.messages);
516
+ if (cronTitle)
517
+ dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
518
+ if (context.messages?.length === 1)
519
+ dynamicHeaders["x-cron-flag"] = "begin";
520
+ }
521
+ dynamicHeaders[HEADER_SESSION_ID] = sessionId;
522
+ dynamicHeaders[HEADER_INTERACTION_ID] = interactionId;
523
+ }
445
524
  else {
446
- // Session mode: use pre-resolved session headers + fresh timestamp
525
+ // Fallback: use extraParams cached values
447
526
  const traceId = ctx.extraParams[HEADER_TRACE_ID];
448
527
  const sessionId = ctx.extraParams[HEADER_SESSION_ID];
449
528
  const interactionId = ctx.extraParams[HEADER_INTERACTION_ID];
450
- if (typeof traceId === "string") {
451
- const isCron = isCronTriggered(context.messages);
452
- dynamicHeaders[HEADER_TRACE_ID] = isCron ? `cron_${traceId}_${Date.now()}` : traceId;
453
- if (isCron) {
454
- const cronTitle = extractCronTitle(context.messages);
455
- if (cronTitle)
456
- dynamicHeaders["x-cron-title"] = encodeURIComponent(cronTitle);
457
- if (context.messages?.length === 1)
458
- dynamicHeaders["x-cron-flag"] = "begin";
459
- }
460
- }
529
+ if (typeof traceId === "string")
530
+ dynamicHeaders[HEADER_TRACE_ID] = traceId;
461
531
  if (typeof sessionId === "string")
462
532
  dynamicHeaders[HEADER_SESSION_ID] = sessionId;
463
533
  if (typeof interactionId === "string")
@@ -465,11 +535,15 @@ export const xiaoyiProvider = {
465
535
  }
466
536
  }
467
537
  // 记录输入
468
- console.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
538
+ logger.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
469
539
  if (context.systemPrompt) {
470
- console.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
540
+ logger.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
471
541
  }
472
- const sessionCtx = getCurrentSessionContext();
542
+ // deviceType: prefer value extracted from Conversation info,
543
+ // then extraParams, then ALS fallback.
544
+ const extraParamsDeviceType = ctx.extraParams?.[DEVICE_TYPE_KEY] || undefined;
545
+ const deviceType = (extractedDeviceType || extraParamsDeviceType)
546
+ ?? getCurrentSessionContext()?.deviceType;
473
547
  // 在发送给模型前,优化 systemPrompt 结构
474
548
  if (context.systemPrompt) {
475
549
  let sp = context.systemPrompt;
@@ -496,23 +570,39 @@ export const xiaoyiProvider = {
496
570
  sp = sp.replace('## Runtime', combined + '\n\n## Runtime');
497
571
  }
498
572
  }
499
- console.log(`[xiaoyiprovider] system prompt optimized: ${beforeLen} -> ${sp.length}`);
573
+ logger.log(`[xiaoyiprovider] system prompt optimized: ${beforeLen} -> ${sp.length}`);
500
574
  context.systemPrompt = sp;
501
575
  }
502
576
  const selfEvolutionEnabled = await selfEvolutionManager.isEnabled();
503
577
  logger.log(`[selfEvolution] selfEvolution flag: ${selfEvolutionEnabled}`);
504
578
  context.systemPrompt = applySelfEvolutionPrompt(context.systemPrompt, selfEvolutionEnabled);
505
579
  // Append device context to systemPrompt
506
- if (sessionCtx?.deviceType) {
507
- const rawDevice = sessionCtx.deviceType;
508
- const displayDevice = (rawDevice === "2in1") ? "鸿蒙PC" : rawDevice;
580
+ if (deviceType) {
581
+ const displayDevice = (deviceType === "2in1") ? "鸿蒙PC" : deviceType;
509
582
  const deviceSection = `\n\n## Current User Device Context\nThe current user is using the following device: ${displayDevice}\nYou need to be aware of the user's current device and provide guidance accordingly. If the response involves device-related tools or actions, you must tailor the reply based on the user's current device, using device-specific references such as "saved to the Notes/Calendar on your {deviceType}.\n"`;
510
583
  context.systemPrompt = (context.systemPrompt ?? "") + deviceSection;
511
584
  }
585
+ // ── Trim user message metadata ──────────────────────
586
+ if (context.messages) {
587
+ for (const msg of context.messages) {
588
+ if (msg.role !== "user" || !msg.content)
589
+ continue;
590
+ if (typeof msg.content === "string") {
591
+ msg.content = trimUserMetadata(msg.content);
592
+ }
593
+ else if (Array.isArray(msg.content)) {
594
+ for (const block of msg.content) {
595
+ if (block.type === "text" && typeof block.text === "string") {
596
+ block.text = trimUserMetadata(block.text);
597
+ }
598
+ }
599
+ }
600
+ }
601
+ }
512
602
  // ── Retry-capable streaming ──────────────────────────────
513
603
  const cronJob = isCronTriggered(context.messages);
514
604
  if (cronJob)
515
- console.log("[xiaoyiprovider] detected cron-triggered request, using extended retry delays");
605
+ logger.log("[xiaoyiprovider] detected cron-triggered request, using extended retry delays");
516
606
  const makeStream = () => underlying(model, context, {
517
607
  ...options,
518
608
  headers: {
package/dist/src/push.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Push message service for scheduled tasks
2
2
  import fetch from "node-fetch";
3
3
  import { randomUUID } from "crypto";
4
+ import { logger } from "./utils/logger.js";
4
5
  /**
5
6
  * Service for sending push messages to users.
6
7
  * Used for outbound messages and scheduled tasks.
@@ -33,8 +34,8 @@ export class XYPushService {
33
34
  const traceId = this.generateTraceId();
34
35
  // Use provided pushId or fall back to config pushId
35
36
  const actualPushId = pushId || this.config.pushId;
36
- console.log(`[PUSH] 📤 Preparing to send push message`);
37
- console.log(`[PUSH] - Using pushId: ${actualPushId.substring(0, 20)}...`);
37
+ logger.log(`[PUSH] 📤 Preparing to send push message`);
38
+ logger.log(`[PUSH] - Using pushId: ${actualPushId.substring(0, 20)}...`);
38
39
  try {
39
40
  const requestBody = {
40
41
  jsonrpc: "2.0",
@@ -80,12 +81,12 @@ export class XYPushService {
80
81
  body: JSON.stringify(requestBody),
81
82
  });
82
83
  // Log response status and headers
83
- console.log(`[PUSH] 📥 Response received`);
84
- console.log(`[PUSH] - HTTP Status: ${response.status} ${response.statusText}`);
84
+ logger.log(`[PUSH] 📥 Response received`);
85
+ logger.log(`[PUSH] - HTTP Status: ${response.status} ${response.statusText}`);
85
86
  if (!response.ok) {
86
87
  const errorText = await response.text();
87
- console.log(`[PUSH] ❌ Push request failed`);
88
- console.log(`[PUSH] - HTTP Status: ${response.status}`);
88
+ logger.error(`[PUSH] ❌ Push request failed`);
89
+ logger.error(`[PUSH] - HTTP Status: ${response.status}`);
89
90
  throw new Error(`Push failed: HTTP ${response.status} - ${errorText}`);
90
91
  }
91
92
  // Try to parse JSON response with detailed error handling
@@ -93,7 +94,7 @@ export class XYPushService {
93
94
  try {
94
95
  const responseText = await response.text();
95
96
  if (!responseText || responseText.trim() === '') {
96
- console.log(`[PUSH] ⚠️ Received empty response body`);
97
+ logger.error(`[PUSH] ⚠️ Received empty response body`);
97
98
  result = {};
98
99
  }
99
100
  else {
@@ -101,21 +102,21 @@ export class XYPushService {
101
102
  }
102
103
  }
103
104
  catch (parseError) {
104
- console.log(`[PUSH] ❌ Failed to parse JSON response`);
105
- console.log(`[PUSH] - Parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
105
+ logger.error(`[PUSH] ❌ Failed to parse JSON response`);
106
+ logger.error(`[PUSH] - Parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
106
107
  throw new Error(`Invalid JSON response from push service: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
107
108
  }
108
- console.log(`[PUSH] ✅ Push message sent successfully`);
109
- console.log(`[PUSH] - Trace ID: ${traceId}`);
109
+ logger.log(`[PUSH] ✅ Push message sent successfully`);
110
+ logger.log(`[PUSH] - Trace ID: ${traceId}`);
110
111
  }
111
112
  catch (error) {
112
- console.log(`[PUSH] ❌ Failed to send push message`);
113
+ logger.error(`[PUSH] ❌ Failed to send push message`);
113
114
  if (error instanceof Error) {
114
- console.log(`[PUSH] - Error name: ${error.name}`);
115
- console.log(`[PUSH] - Error message: ${error.message}`);
115
+ logger.error(`[PUSH] - Error name: ${error.name}`);
116
+ logger.error(`[PUSH] - Error message: ${error.message}`);
116
117
  }
117
118
  else {
118
- console.log(`[PUSH] - Error:`, error);
119
+ logger.error(`[PUSH] - Error:`, error);
119
120
  }
120
121
  throw error;
121
122
  }
@@ -4,6 +4,7 @@ import { resolveXYConfig } from "./config.js";
4
4
  import { getCurrentTaskId, getCurrentMessageId } from "./task-manager.js";
5
5
  import fs from "fs/promises";
6
6
  import path from "path";
7
+ import { logger } from "./utils/logger.js";
7
8
  const TEMP_FILE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
8
9
  /**
9
10
  * 清理 /tmp/xy_channel 目录中超过 24 小时的旧文件
@@ -31,11 +32,11 @@ export async function cleanupStaleTempFiles(tempDir = "/tmp/xy_channel") {
31
32
  }
32
33
  }
33
34
  if (cleanedCount > 0) {
34
- console.log(`[CLEANUP] 🧹 Cleaned ${cleanedCount} stale files (>${TEMP_FILE_TTL_MS / 1000 / 3600}h) from ${tempDir}`);
35
+ logger.log(`[CLEANUP] 🧹 Cleaned ${cleanedCount} stale files (>${TEMP_FILE_TTL_MS / 1000 / 3600}h) from ${tempDir}`);
35
36
  }
36
37
  }
37
38
  catch (err) {
38
- console.error(`[CLEANUP] ❌ Failed to cleanup temp dir:`, err);
39
+ logger.error(`[CLEANUP] ❌ Failed to cleanup temp dir:`, err);
39
40
  }
40
41
  }
41
42
  /**
@@ -45,11 +46,9 @@ export async function cleanupStaleTempFiles(tempDir = "/tmp/xy_channel") {
45
46
  */
46
47
  export function createXYReplyDispatcher(params) {
47
48
  const { cfg, runtime, sessionId, taskId, messageId, accountId, isSteerFollower } = params;
48
- const log = runtime?.log ?? console.log;
49
- const error = runtime?.error ?? console.error;
50
- log(`[DISPATCHER-CREATE] ******* Creating dispatcher *******`);
51
- log(`[DISPATCHER-CREATE] - taskId: ${taskId}`);
52
- log(`[DISPATCHER-CREATE] - isSteerFollower: ${isSteerFollower ?? false}`);
49
+ logger.log(`[DISPATCHER-CREATE] ******* Creating dispatcher *******`);
50
+ logger.log(`[DISPATCHER-CREATE] - taskId: ${taskId}`);
51
+ logger.log(`[DISPATCHER-CREATE] - isSteerFollower: ${isSteerFollower ?? false}`);
53
52
  // 初始taskId和messageId(作为fallback)
54
53
  const initialTaskId = taskId;
55
54
  const initialMessageId = messageId;
@@ -79,14 +78,14 @@ export function createXYReplyDispatcher(params) {
79
78
  * Start the status update interval
80
79
  */
81
80
  const startStatusInterval = () => {
82
- log(`[STATUS INTERVAL] Starting interval for session ${sessionId}`);
81
+ logger.log(`[STATUS INTERVAL] Starting interval for session ${sessionId}`);
83
82
  statusUpdateInterval = setInterval(() => {
84
83
  // 🔑 使用动态taskId
85
84
  const currentTaskId = getActiveTaskId();
86
85
  const currentMessageId = getActiveMessageId();
87
- log(`[STATUS INTERVAL] Triggering status update`);
88
- log(`[STATUS INTERVAL] - sessionId: ${sessionId}`);
89
- log(`[STATUS INTERVAL] - currentTaskId: ${currentTaskId}`);
86
+ logger.log(`[STATUS INTERVAL] Triggering status update`);
87
+ logger.log(`[STATUS INTERVAL] - sessionId: ${sessionId}`);
88
+ logger.log(`[STATUS INTERVAL] - currentTaskId: ${currentTaskId}`);
90
89
  void sendStatusUpdate({
91
90
  config,
92
91
  sessionId,
@@ -95,13 +94,13 @@ export function createXYReplyDispatcher(params) {
95
94
  text: "任务正在处理中,请稍候~",
96
95
  state: "working",
97
96
  }).catch((err) => {
98
- error(`Failed to send status update:`, err);
97
+ logger.error(`Failed to send status update:`, err);
99
98
  });
100
99
  }, 30000); // 30 seconds
101
100
  };
102
101
  const stopStatusInterval = () => {
103
102
  if (statusUpdateInterval) {
104
- log(`[STATUS INTERVAL] Stopping interval for session ${sessionId}`);
103
+ logger.log(`[STATUS INTERVAL] Stopping interval for session ${sessionId}`);
105
104
  clearInterval(statusUpdateInterval);
106
105
  statusUpdateInterval = null;
107
106
  }
@@ -112,21 +111,21 @@ export function createXYReplyDispatcher(params) {
112
111
  humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, accountId),
113
112
  onReplyStart: () => {
114
113
  const currentTaskId = getActiveTaskId();
115
- log(`[REPLY START] Reply started for session ${sessionId}, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
114
+ logger.log(`[REPLY START] Reply started for session ${sessionId}, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
116
115
  },
117
116
  deliver: async (payload, info) => {
118
117
  const text = payload.text ?? "";
119
118
  const currentTaskId = getActiveTaskId();
120
119
  const currentMessageId = getActiveMessageId();
121
- log(`[DELIVER] sessionId=${sessionId}, taskId=${currentTaskId}, info.kind=${info?.kind}, text.length=${text.length}`);
120
+ logger.log(`[DELIVER] sessionId=${sessionId}, taskId=${currentTaskId}, info.kind=${info?.kind}, text.length=${text.length}`);
122
121
  try {
123
122
  if (!text.trim()) {
124
- log(`[DELIVER SKIP] Empty text, skipping`);
123
+ logger.log(`[DELIVER SKIP] Empty text, skipping`);
125
124
  return;
126
125
  }
127
126
  accumulatedText += text;
128
127
  hasSentResponse = true;
129
- log(`[DELIVER ACCUMULATE] Accumulated text, current length=${accumulatedText.length}`);
128
+ logger.log(`[DELIVER ACCUMULATE] Accumulated text, current length=${accumulatedText.length}`);
130
129
  // 🔑 使用动态taskId发送reasoningText更新
131
130
  await sendReasoningTextUpdate({
132
131
  config,
@@ -135,10 +134,10 @@ export function createXYReplyDispatcher(params) {
135
134
  messageId: currentMessageId,
136
135
  text,
137
136
  });
138
- log(`[DELIVER] ✅ Sent deliver text as reasoningText update`);
137
+ logger.log(`[DELIVER] ✅ Sent deliver text as reasoningText update`);
139
138
  }
140
139
  catch (deliverError) {
141
- error(`Failed to deliver message:`, deliverError);
140
+ logger.error(`Failed to deliver message:`, deliverError);
142
141
  }
143
142
  },
144
143
  onError: async (err, info) => {
@@ -146,7 +145,7 @@ export function createXYReplyDispatcher(params) {
146
145
  stopStatusInterval();
147
146
  // 🔑 steer follower不发送错误状态(让主dispatcher处理)
148
147
  if (isSteerFollower) {
149
- log(`[ON_ERROR] Steer follower - skipping error response`);
148
+ logger.log(`[ON_ERROR] Steer follower - skipping error response`);
150
149
  return;
151
150
  }
152
151
  if (!hasSentResponse) {
@@ -163,29 +162,29 @@ export function createXYReplyDispatcher(params) {
163
162
  });
164
163
  }
165
164
  catch (statusError) {
166
- error(`Failed to send error status:`, statusError);
165
+ logger.error(`Failed to send error status:`, statusError);
167
166
  }
168
167
  }
169
168
  },
170
169
  onIdle: async () => {
171
170
  const currentTaskId = getActiveTaskId();
172
171
  const currentMessageId = getActiveMessageId();
173
- log(`[ON_IDLE] Reply idle`);
174
- log(`[ON_IDLE] - sessionId: ${sessionId}`);
175
- log(`[ON_IDLE] - taskId: ${currentTaskId}`);
176
- log(`[ON_IDLE] - isSteerFollower: ${isSteerFollower}`);
177
- log(`[ON_IDLE] - hasSentResponse: ${hasSentResponse}`);
178
- log(`[ON_IDLE] - finalSent: ${finalSent}`);
172
+ logger.log(`[ON_IDLE] Reply idle`);
173
+ logger.log(`[ON_IDLE] - sessionId: ${sessionId}`);
174
+ logger.log(`[ON_IDLE] - taskId: ${currentTaskId}`);
175
+ logger.log(`[ON_IDLE] - isSteerFollower: ${isSteerFollower}`);
176
+ logger.log(`[ON_IDLE] - hasSentResponse: ${hasSentResponse}`);
177
+ logger.log(`[ON_IDLE] - finalSent: ${finalSent}`);
179
178
  // 🔑 核心改动:steer follower不发送final响应
180
179
  if (isSteerFollower) {
181
- log(`[ON_IDLE] Steer follower - skipping final response`);
182
- log(`[ON_IDLE] - Message queued successfully, waiting for primary dispatcher`);
180
+ logger.log(`[ON_IDLE] Steer follower - skipping final response`);
181
+ logger.log(`[ON_IDLE] - Message queued successfully, waiting for primary dispatcher`);
183
182
  stopStatusInterval();
184
183
  return; // ← 直接返回,不发送任何东西!
185
184
  }
186
185
  // 正常模式(或steer的第一条消息)
187
186
  if (hasSentResponse && !finalSent) {
188
- log(`[ON_IDLE] Sending accumulated text, length=${accumulatedText.length}`);
187
+ logger.log(`[ON_IDLE] Sending accumulated text, length=${accumulatedText.length}`);
189
188
  try {
190
189
  // 🔑 使用动态taskId发送完成状态
191
190
  await sendStatusUpdate({
@@ -196,7 +195,7 @@ export function createXYReplyDispatcher(params) {
196
195
  text: "任务处理已完成~",
197
196
  state: "completed",
198
197
  });
199
- log(`[ON_IDLE] ✅ Sent completion status update`);
198
+ logger.log(`[ON_IDLE] ✅ Sent completion status update`);
200
199
  // 🔑 使用动态taskId发送最终响应
201
200
  await sendA2AResponse({
202
201
  config,
@@ -208,15 +207,15 @@ export function createXYReplyDispatcher(params) {
208
207
  final: true,
209
208
  });
210
209
  finalSent = true;
211
- log(`[ON_IDLE] ✅ Sent final response with taskId=${currentTaskId}`);
210
+ logger.log(`[ON_IDLE] ✅ Sent final response with taskId=${currentTaskId}`);
212
211
  }
213
212
  catch (err) {
214
- error(`[ON_IDLE] Failed to send final response:`, err);
213
+ logger.error(`[ON_IDLE] Failed to send final response:`, err);
215
214
  }
216
215
  }
217
216
  else {
218
217
  // 正常失败场景(非steer follower)
219
- log(`[ON_IDLE] Skipping final message: hasSentResponse=${hasSentResponse}, finalSent=${finalSent}`);
218
+ logger.log(`[ON_IDLE] Skipping final message: hasSentResponse=${hasSentResponse}, finalSent=${finalSent}`);
220
219
  try {
221
220
  await sendStatusUpdate({
222
221
  config,
@@ -226,7 +225,7 @@ export function createXYReplyDispatcher(params) {
226
225
  text: "任务处理中断了~",
227
226
  state: "failed",
228
227
  });
229
- log(`[ON_IDLE] ✅ Sent failure status update`);
228
+ logger.log(`[ON_IDLE] ✅ Sent failure status update`);
230
229
  await sendA2AResponse({
231
230
  config,
232
231
  sessionId,
@@ -239,17 +238,17 @@ export function createXYReplyDispatcher(params) {
239
238
  errorMessage: "任务执行异常,请重试",
240
239
  });
241
240
  finalSent = true;
242
- log(`[ON_IDLE] ✅ Sent error response with code: 99921111`);
241
+ logger.log(`[ON_IDLE] ✅ Sent error response with code: 99921111`);
243
242
  }
244
243
  catch (err) {
245
- error(`[ON_IDLE] Failed to send error response:`, err);
244
+ logger.error(`[ON_IDLE] Failed to send error response:`, err);
246
245
  }
247
246
  }
248
247
  stopStatusInterval();
249
248
  },
250
249
  onCleanup: () => {
251
250
  const currentTaskId = getActiveTaskId();
252
- log(`[ON_CLEANUP] Reply cleanup, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
251
+ logger.log(`[ON_CLEANUP] Reply cleanup, taskId=${currentTaskId}, isSteerFollower=${isSteerFollower}`);
253
252
  },
254
253
  });
255
254
  return {
@@ -264,13 +263,13 @@ export function createXYReplyDispatcher(params) {
264
263
  }
265
264
  const currentTaskId = getActiveTaskId();
266
265
  const currentMessageId = getActiveMessageId();
267
- log(`[TOOL START] Tool: ${name}, phase: ${phase}, taskId: ${currentTaskId}`);
266
+ logger.log(`[TOOL START] Tool: ${name}, phase: ${phase}, taskId: ${currentTaskId}`);
268
267
  if (phase === "start") {
269
268
  const toolName = name || "unknown";
270
269
  // call_device_tool 由自身 execute() 内部发送具体子工具名的状态更新
271
270
  // get_xxx_tool_schema 是给 LLM 查 schema 用的,无需向用户展示
272
- if (toolName === "call_device_tool" || toolName.endsWith("_tool_schema")) {
273
- log(`[TOOL START] Skipping generic status for ${toolName}`);
271
+ if (toolName === "call_device_tool" || toolName.endsWith("_tool_schema") || toolName === "huawei_id_tool") {
272
+ logger.log(`[TOOL START] Skipping generic status for ${toolName}`);
274
273
  return;
275
274
  }
276
275
  try {
@@ -282,10 +281,10 @@ export function createXYReplyDispatcher(params) {
282
281
  text: `正在使用工具: ${toolName}...`,
283
282
  state: "working",
284
283
  });
285
- log(`[TOOL START] ✅ Sent status update for tool start: ${toolName}`);
284
+ logger.log(`[TOOL START] ✅ Sent status update for tool start: ${toolName}`);
286
285
  }
287
286
  catch (err) {
288
- error(`[TOOL START] ❌ Failed to send tool start status:`, err);
287
+ logger.error(`[TOOL START] ❌ Failed to send tool start status:`, err);
289
288
  }
290
289
  }
291
290
  },
@@ -298,7 +297,7 @@ export function createXYReplyDispatcher(params) {
298
297
  const currentMessageId = getActiveMessageId();
299
298
  const text = payload.text ?? "";
300
299
  const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
301
- log(`[TOOL RESULT] Tool result, taskId: ${currentTaskId}, text.length: ${text.length}`);
300
+ logger.log(`[TOOL RESULT] Tool result, taskId: ${currentTaskId}, text.length: ${text.length}`);
302
301
  try {
303
302
  if (text.length > 0 || hasMedia) {
304
303
  const resultText = text.length > 0 ? text : "工具执行完成";
@@ -310,11 +309,11 @@ export function createXYReplyDispatcher(params) {
310
309
  text: resultText,
311
310
  state: "working",
312
311
  });
313
- log(`[TOOL RESULT] ✅ Sent tool result as status update`);
312
+ logger.log(`[TOOL RESULT] ✅ Sent tool result as status update`);
314
313
  }
315
314
  }
316
315
  catch (err) {
317
- error(`[TOOL RESULT] ❌ Failed to send tool result status:`, err);
316
+ logger.error(`[TOOL RESULT] ❌ Failed to send tool result status:`, err);
318
317
  }
319
318
  },
320
319
  onReasoningStream: async (payload) => {
@@ -323,7 +322,7 @@ export function createXYReplyDispatcher(params) {
323
322
  return;
324
323
  }
325
324
  const text = payload.text ?? "";
326
- log(`[REASONING STREAM] Reasoning chunk received, text.length: ${text.length}`);
325
+ logger.log(`[REASONING STREAM] Reasoning chunk received, text.length: ${text.length}`);
327
326
  // Reasoning stream 目前被注释掉
328
327
  // 如果需要可以启用
329
328
  },
@@ -348,7 +347,7 @@ export function createXYReplyDispatcher(params) {
348
347
  }
349
348
  }
350
349
  catch (err) {
351
- error(`[PARTIAL REPLY] ❌ Failed to send partial reply:`, err);
350
+ logger.error(`[PARTIAL REPLY] ❌ Failed to send partial reply:`, err);
352
351
  }
353
352
  },
354
353
  },