evolcore 0.0.43-test.1 → 0.0.43-test.3

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 (200) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -1,14 +1,19 @@
1
1
  import { AUNChannelPlugin } from './aun.js';
2
- import { DingtalkChannelPlugin } from './dingtalk.js';
3
- import { FeishuChannelPlugin } from './feishu.js';
4
- import { QQBotChannelPlugin } from './qqbot.js';
5
- import { WechatChannelPlugin } from './wechat.js';
6
- import { WecomChannelPlugin } from './wecom.js';
7
- export function registerBuiltinChannelPlugins(channelLoader) {
8
- channelLoader.register(new FeishuChannelPlugin());
9
- channelLoader.register(new WechatChannelPlugin());
2
+ export async function registerBuiltinChannelPlugins(channelLoader) {
10
3
  channelLoader.register(new AUNChannelPlugin());
11
- channelLoader.register(new DingtalkChannelPlugin());
12
- channelLoader.register(new QQBotChannelPlugin());
13
- channelLoader.register(new WecomChannelPlugin());
4
+ const providers = [
5
+ ['feishu', async () => new (await import('./feishu.js')).FeishuChannelPlugin()],
6
+ ['wechat', async () => new (await import('./wechat.js')).WechatChannelPlugin()],
7
+ ['dingtalk', async () => new (await import('./dingtalk.js')).DingtalkChannelPlugin()],
8
+ ['qqbot', async () => new (await import('./qqbot.js')).QQBotChannelPlugin()],
9
+ ['wecom', async () => new (await import('./wecom.js')).WecomChannelPlugin()],
10
+ ];
11
+ for (const [channelType, load] of providers) {
12
+ try {
13
+ channelLoader.register(await load());
14
+ }
15
+ catch (error) {
16
+ channelLoader.recordProviderFailure(channelType, error);
17
+ }
18
+ }
14
19
  }
@@ -3,6 +3,7 @@ import { ExecutionTimeoutError } from '../utils/error-utils.js';
3
3
  import { logger } from '../utils/logger.js';
4
4
  import { normalizeExecutionMode } from '../trigger/validation.js';
5
5
  import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
6
+ import { preparePaTeamQualification } from '../core/relation/pa-team.js';
6
7
  import { assertSystemSessionLaunchable } from '../core/system-session/registry.js';
7
8
  import { sessionTopicThreadId } from '../core/thread/topic-id.js';
8
9
  const DEFAULT_WATCHDOG_MS = 11 * 60 * 1000;
@@ -146,6 +147,9 @@ export class DaemonChannel {
146
147
  }
147
148
  if (ctx.signal?.aborted)
148
149
  onAbort();
150
+ if (message.triggerMeta?.originChannelType === 'aun' && message.triggerMeta.originChatType !== 'group') {
151
+ await preparePaTeamQualification(ctx.trigger.agentAid, message.triggerMeta.originPeerId);
152
+ }
149
153
  if (!slot?.terminalClaim) {
150
154
  void this.messageQueue.enqueue(ctx.session.id, message, ctx.projectPath, {
151
155
  interruptible: false,
@@ -160,6 +160,7 @@ export class DingtalkChannel {
160
160
  config;
161
161
  client = null;
162
162
  connected = false;
163
+ connectionGeneration = 0;
163
164
  messageHandler = null;
164
165
  recallHandler;
165
166
  webhookCache = new Map();
@@ -182,6 +183,7 @@ export class DingtalkChannel {
182
183
  cardActionsInFlight = new Set();
183
184
  interactionSendTails = new Map();
184
185
  cleanupInterval = null;
186
+ cardCallbackCancellations = new Set();
185
187
  projectPathProvider = null;
186
188
  // Welcome message manager
187
189
  welcomeManager;
@@ -328,13 +330,18 @@ export class DingtalkChannel {
328
330
  }
329
331
  // ── Lifecycle ──────────────────────────────────────────────────────────────
330
332
  async connect() {
333
+ this.lifecycle?.assertActive();
334
+ const generation = ++this.connectionGeneration;
331
335
  const { clientId, clientSecret } = this.config;
332
336
  if (!clientId || !clientSecret || clientId.includes('your-') || clientSecret.includes('your-')) {
333
337
  throw new Error('DingTalk clientId/clientSecret not configured');
334
338
  }
335
339
  this.loadSeenMessages();
336
340
  this.loadRoutes();
337
- const { DWClient, TOPIC_ROBOT, TOPIC_CARD } = await requireOptional('dingtalk-stream');
341
+ const { DWClient, TOPIC_ROBOT, TOPIC_CARD } = await requireOptional('dingtalk-stream', false);
342
+ if (generation !== this.connectionGeneration)
343
+ throw new Error('dingtalk connection cancelled');
344
+ this.lifecycle?.assertActive();
338
345
  const client = new DWClient({ clientId, clientSecret });
339
346
  this.client = client;
340
347
  client.registerCallbackListener(TOPIC_ROBOT, async (msg) => {
@@ -386,6 +393,10 @@ export class DingtalkChannel {
386
393
  logger.info('[DingTalk] Connected via Stream Mode');
387
394
  }
388
395
  async disconnect() {
396
+ this.connectionGeneration++;
397
+ for (const cancel of this.cardCallbackCancellations)
398
+ cancel();
399
+ this.cardCallbackCancellations.clear();
389
400
  this.connected = false;
390
401
  if (this.cleanupInterval) {
391
402
  if (this.lifecycle)
@@ -444,7 +455,11 @@ export class DingtalkChannel {
444
455
  }
445
456
  }
446
457
  onMessage(handler) {
447
- this.messageHandler = handler;
458
+ this.messageHandler = async (event) => {
459
+ if (this.lifecycle && this.lifecycle.state !== 'active')
460
+ return;
461
+ await handler(event);
462
+ };
448
463
  }
449
464
  onRecall(handler) {
450
465
  this.recallHandler = handler;
@@ -470,6 +485,13 @@ export class DingtalkChannel {
470
485
  }
471
486
  // ── Inbound message handling ───────────────────────────────────────────────
472
487
  async handleIncoming(msg) {
488
+ const generation = this.connectionGeneration;
489
+ const isCurrent = () => generation === this.connectionGeneration
490
+ && (!this.lifecycle || this.lifecycle.state === 'active');
491
+ const dispatchMessage = async (event) => {
492
+ if (isCurrent())
493
+ await this.messageHandler?.(event);
494
+ };
473
495
  // Stream callbacks must be acknowledged even when the payload is a
474
496
  // duplicate, stale, malformed, or intentionally ignored by mention policy.
475
497
  this.acknowledgeStreamMessage(msg);
@@ -540,29 +562,32 @@ export class DingtalkChannel {
540
562
  if (!this.messageHandler)
541
563
  return;
542
564
  // 首次交互欢迎消息(使用共享帮助函数)
543
- await sendWelcomeIfNeeded(this.welcomeManager, senderId, chatId, async (id, text) => { await this.sendMessage(id, text); }, 'DingTalk');
565
+ await sendWelcomeIfNeeded(this.welcomeManager, senderId, chatId, async (id, text) => { if (isCurrent())
566
+ await this.sendMessage(id, text); }, 'DingTalk');
567
+ if (!isCurrent())
568
+ return;
544
569
  if (msgtype === 'text' || !msgtype) {
545
570
  const text = this.extractText(data);
546
571
  if (!text)
547
572
  return;
548
- await this.messageHandler({
573
+ await dispatchMessage({
549
574
  channelId: chatId, content: text, chatType,
550
575
  peerId: senderId || '', peerName: senderNick, messageId: msgId,
551
576
  ...eventMetadata,
552
577
  });
553
578
  }
554
579
  else if (msgtype === 'picture' || msgtype === 'image') {
555
- await this.handleImageMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata);
580
+ await this.handleImageMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata, dispatchMessage);
556
581
  }
557
582
  else if (msgtype === 'file') {
558
- await this.handleFileMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata);
583
+ await this.handleFileMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata, dispatchMessage);
559
584
  }
560
585
  else if (msgtype === 'richText') {
561
- await this.handleRichTextMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata);
586
+ await this.handleRichTextMessage(data, chatId, chatType, senderId, senderNick, msgId, eventMetadata, dispatchMessage);
562
587
  }
563
588
  else if (msgtype === 'audio') {
564
589
  const recognition = data.recognition || data.content?.recognition;
565
- await this.messageHandler({
590
+ await dispatchMessage({
566
591
  channelId: chatId,
567
592
  content: recognition ? `用户发送了语音:${recognition}` : '[语音消息:未提供语音识别文本]',
568
593
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
@@ -574,10 +599,10 @@ export class DingtalkChannel {
574
599
  await this.handleFileMessage({
575
600
  ...data,
576
601
  content: { ...videoContent, fileName: videoContent.fileName || data.fileName || 'video.mp4' },
577
- }, chatId, chatType, senderId, senderNick, msgId, eventMetadata);
602
+ }, chatId, chatType, senderId, senderNick, msgId, eventMetadata, dispatchMessage);
578
603
  }
579
604
  else {
580
- await this.messageHandler({
605
+ await dispatchMessage({
581
606
  channelId: chatId,
582
607
  content: `[不支持的消息类型: ${msgtype}]`,
583
608
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
@@ -627,12 +652,12 @@ export class DingtalkChannel {
627
652
  rejectRedirects: true,
628
653
  });
629
654
  }
630
- async handleImageMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}) {
655
+ async handleImageMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}, dispatchMessage = this.messageHandler) {
631
656
  const content = typeof data.content === 'string' ? JSON.parse(data.content) : (data.content || {});
632
657
  const downloadRef = content.downloadUrl || content.downloadCode || data.downloadUrl || data.downloadCode;
633
658
  if (!downloadRef) {
634
659
  logger.warn('[DingTalk] Image message without downloadUrl');
635
- await this.messageHandler({
660
+ await dispatchMessage({
636
661
  channelId: chatId, content: '[图片下载失败:缺少下载链接]',
637
662
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
638
663
  ...metadata,
@@ -644,7 +669,7 @@ export class DingtalkChannel {
644
669
  const buffer = await this.downloadMessageMedia(downloadRef);
645
670
  const result = await validateImage(buffer);
646
671
  if (result.mime) {
647
- await this.messageHandler({
672
+ await dispatchMessage({
648
673
  channelId: chatId,
649
674
  content: '用户发送了一张图片,请分析这张图片的内容。',
650
675
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
@@ -654,7 +679,7 @@ export class DingtalkChannel {
654
679
  }
655
680
  else {
656
681
  logger.warn(`[DingTalk] Image validation failed: ${!result.mime && 'reason' in result ? result.reason : 'unknown'}`);
657
- await this.messageHandler({
682
+ await dispatchMessage({
658
683
  channelId: chatId, content: '[图片验证失败]',
659
684
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
660
685
  ...metadata,
@@ -663,20 +688,20 @@ export class DingtalkChannel {
663
688
  }
664
689
  catch (error) {
665
690
  logger.error('[DingTalk] Failed to download image:', error);
666
- await this.messageHandler({
691
+ await dispatchMessage({
667
692
  channelId: chatId, content: '[图片下载失败]',
668
693
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
669
694
  ...metadata,
670
695
  });
671
696
  }
672
697
  }
673
- async handleFileMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}) {
698
+ async handleFileMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}, dispatchMessage = this.messageHandler) {
674
699
  const content = typeof data.content === 'string' ? JSON.parse(data.content) : (data.content || {});
675
700
  const downloadRef = content.downloadUrl || content.downloadCode || data.downloadUrl || data.downloadCode;
676
701
  const fileName = content.fileName || data.fileName || 'unknown';
677
702
  if (!downloadRef) {
678
703
  logger.warn('[DingTalk] File message without downloadUrl');
679
- await this.messageHandler({
704
+ await dispatchMessage({
680
705
  channelId: chatId, content: `[文件下载失败:缺少下载链接] ${fileName}`,
681
706
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
682
707
  ...metadata,
@@ -690,7 +715,7 @@ export class DingtalkChannel {
690
715
  : process.cwd();
691
716
  const buffer = await this.downloadMessageMedia(downloadRef);
692
717
  const { filePath } = saveToUploads(buffer, sanitizeFileName(fileName), projectPath);
693
- await this.messageHandler({
718
+ await dispatchMessage({
694
719
  channelId: chatId,
695
720
  content: `用户发送了文件:${fileName}\n文件已保存到:${filePath}\n请使用 Read 工具读取并分析文件内容。`,
696
721
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
@@ -699,18 +724,18 @@ export class DingtalkChannel {
699
724
  }
700
725
  catch (error) {
701
726
  logger.error('[DingTalk] Failed to download file:', error);
702
- await this.messageHandler({
727
+ await dispatchMessage({
703
728
  channelId: chatId, content: `[文件下载失败] ${fileName}`,
704
729
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
705
730
  ...metadata,
706
731
  });
707
732
  }
708
733
  }
709
- async handleRichTextMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}) {
734
+ async handleRichTextMessage(data, chatId, chatType, senderId, senderNick, msgId, metadata = {}, dispatchMessage = this.messageHandler) {
710
735
  const content = typeof data.content === 'string' ? JSON.parse(data.content) : (data.content || {});
711
736
  const richText = content.richText;
712
737
  if (!Array.isArray(richText)) {
713
- await this.messageHandler({
738
+ await dispatchMessage({
714
739
  channelId: chatId, content: '[不支持的富文本格式]',
715
740
  chatType, peerId: senderId || '', peerName: senderNick, messageId: msgId,
716
741
  ...metadata,
@@ -738,7 +763,7 @@ export class DingtalkChannel {
738
763
  }
739
764
  }
740
765
  const prompt = text.trim() || (images.length > 0 ? '用户发送了一张图片,请分析这张图片的内容。' : '[空消息]');
741
- await this.messageHandler({
766
+ await dispatchMessage({
742
767
  channelId: chatId, content: prompt, chatType,
743
768
  peerId: senderId || '', peerName: senderNick, messageId: msgId,
744
769
  images: images.length > 0 ? images : undefined,
@@ -894,7 +919,7 @@ export class DingtalkChannel {
894
919
  }
895
920
  const extension = imageInfo.mime === 'image/jpeg' ? 'jpg' : imageInfo.mime.slice('image/'.length);
896
921
  // Step 1: Upload media
897
- const FormData = (await requireOptional('form-data')).default;
922
+ const FormData = (await requireOptional('form-data', false)).default;
898
923
  const form = new FormData();
899
924
  form.append('type', 'image');
900
925
  form.append('media', image, { filename: `image.${extension}`, contentType: imageInfo.mime });
@@ -929,7 +954,7 @@ export class DingtalkChannel {
929
954
  if (!token)
930
955
  throw new Error('DingTalk access token unavailable for sendFile');
931
956
  // Step 1: Upload media
932
- const FormData = (await requireOptional('form-data')).default;
957
+ const FormData = (await requireOptional('form-data', false)).default;
933
958
  const form = new FormData();
934
959
  form.append('type', 'file');
935
960
  form.append('media', fs.createReadStream(filePath), { filename: path.basename(filePath) });
@@ -1285,25 +1310,42 @@ export class DingtalkChannel {
1285
1310
  }
1286
1311
  }
1287
1312
  async handleCardCallbackMessage(msg) {
1288
- const data = typeof msg.data === 'string' ? parseJsonRecord(msg.data) : parseJsonRecord(msg.data);
1313
+ const generation = this.connectionGeneration;
1314
+ const client = this.client;
1315
+ const isCurrent = () => generation === this.connectionGeneration && this.client === client
1316
+ && (!this.lifecycle || this.lifecycle.state === 'active');
1317
+ if (!isCurrent())
1318
+ return;
1319
+ const data = parseJsonRecord(msg.data);
1289
1320
  const callback = parseDingtalkCardCallback(data);
1290
1321
  const streamMessageId = msg?.headers?.messageId || `unknown-${Date.now()}`;
1291
1322
  const work = this.processCardCallback(callback, streamMessageId);
1292
1323
  let timedOut = false;
1293
1324
  let timeoutId;
1325
+ let cancelWait;
1294
1326
  const timeout = new Promise(resolve => {
1295
- timeoutId = setTimeout(() => {
1327
+ cancelWait = () => resolve(undefined);
1328
+ const onTimeout = () => {
1296
1329
  timedOut = true;
1297
1330
  resolve(this.privateCardFeedback('操作已提交,正在处理'));
1298
- }, 1_500);
1331
+ };
1332
+ timeoutId = this.lifecycle
1333
+ ? this.lifecycle.setTimeout(onTimeout, 1_500)
1334
+ : setTimeout(onTimeout, 1_500);
1299
1335
  });
1336
+ this.cardCallbackCancellations.add(cancelWait);
1337
+ this.lifecycle?.signal.addEventListener('abort', cancelWait, { once: true });
1338
+ if (this.lifecycle?.signal.aborted)
1339
+ cancelWait();
1300
1340
  try {
1301
1341
  const response = await Promise.race([work, timeout]);
1302
- if (!timedOut && timeoutId)
1303
- clearTimeout(timeoutId);
1342
+ if (!isCurrent() || !response)
1343
+ return;
1304
1344
  this.acknowledgeStreamMessage(msg, response);
1305
1345
  if (timedOut) {
1306
1346
  void work.then(async (finalResponse) => {
1347
+ if (!isCurrent())
1348
+ return;
1307
1349
  const entry = callback.outTrackId ? this.cardsByTrackId.get(callback.outTrackId) : undefined;
1308
1350
  const cardData = finalResponse?.cardData;
1309
1351
  if (entry && cardData) {
@@ -1315,11 +1357,21 @@ export class DingtalkChannel {
1315
1357
  }
1316
1358
  }
1317
1359
  catch (error) {
1318
- if (timeoutId)
1319
- clearTimeout(timeoutId);
1360
+ if (!isCurrent())
1361
+ return;
1320
1362
  logger.error('[DingTalk] Card callback failed:', error);
1321
1363
  this.acknowledgeStreamMessage(msg, this.privateCardFeedback('操作失败,请重试'));
1322
1364
  }
1365
+ finally {
1366
+ this.cardCallbackCancellations.delete(cancelWait);
1367
+ this.lifecycle?.signal.removeEventListener('abort', cancelWait);
1368
+ if (timeoutId) {
1369
+ if (this.lifecycle)
1370
+ await this.lifecycle.clearTimeout(timeoutId);
1371
+ else
1372
+ clearTimeout(timeoutId);
1373
+ }
1374
+ }
1323
1375
  }
1324
1376
  }
1325
1377
  // ── Plugin ─────────────────────────────────────────────────────────────────────
@@ -90,7 +90,7 @@ export class FeishuChannel {
90
90
  // 加载持久化的已处理消息 ID,防止重启后 Feishu 重推同一条消息
91
91
  this.loadSeenMessages();
92
92
  const { requireOptional } = await import('../utils/npm-ops.js');
93
- const lark = await requireOptional('@larksuiteoapi/node-sdk');
93
+ const lark = await requireOptional('@larksuiteoapi/node-sdk', false);
94
94
  if (!isCurrent())
95
95
  return;
96
96
  try {
@@ -125,6 +125,11 @@ export class FeishuChannel {
125
125
  }
126
126
  if (!this.messageHandler)
127
127
  return;
128
+ const dispatchMessage = async (options) => {
129
+ if (!isCurrent() || this.client !== client)
130
+ return;
131
+ await this.messageHandler?.(options);
132
+ };
128
133
  // 提取 chatType(从 SDK 事件直接获取)
129
134
  const chatType = msg.chat_type === 'group' ? 'group' : 'private';
130
135
  // 话题消息检测日志
@@ -154,11 +159,18 @@ export class FeishuChannel {
154
159
  logger.debug('[Feishu] getUserName error:', err);
155
160
  }
156
161
  }
162
+ if (!isCurrent() || this.client !== client)
163
+ return;
157
164
  try {
158
165
  // 首次交互欢迎消息(使用共享帮助函数)
159
166
  if (peerId) {
160
- await sendWelcomeIfNeeded(this.welcomeManager, peerId, msg.chat_id, async (id, text) => { await this.sendMessage(id, text); }, 'Feishu');
167
+ await sendWelcomeIfNeeded(this.welcomeManager, peerId, msg.chat_id, async (id, text) => {
168
+ if (isCurrent() && this.client === client)
169
+ await this.sendMessage(id, text);
170
+ }, 'Feishu');
161
171
  }
172
+ if (!isCurrent() || this.client !== client)
173
+ return;
162
174
  // 提取话题信息
163
175
  const threadId = msg.thread_id || undefined;
164
176
  const rootId = msg.root_id || undefined;
@@ -259,7 +271,7 @@ export class FeishuChannel {
259
271
  // 清理残留的 mention 占位符(@_user_N 代表机器人)
260
272
  content = content.replace(/@_user_\d+/g, '').trim();
261
273
  const finalContent = quotedText + content;
262
- await this.messageHandler({ channelId: msg.chat_id, content: finalContent, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, mentions: mentions.length > 0 ? mentions : undefined, mentionAids: mentions.length > 0 ? mentions.map((m) => m.userId) : undefined, threadId, rootId, chatType });
274
+ await dispatchMessage({ channelId: msg.chat_id, content: finalContent, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, mentions: mentions.length > 0 ? mentions : undefined, mentionAids: mentions.length > 0 ? mentions.map((m) => m.userId) : undefined, threadId, rootId, chatType });
263
275
  }
264
276
  // 处理图片消息
265
277
  else if (msg.message_type === 'image') {
@@ -273,11 +285,11 @@ export class FeishuChannel {
273
285
  if (imageData) {
274
286
  const allImages = [...quotedImages, imageData];
275
287
  const prompt = quotedText + '用户发送了一张图片,请结合上下文理解用户意图并回应。';
276
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: allImages, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
288
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: allImages, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
277
289
  }
278
290
  else {
279
291
  const prompt = quotedText + '[图片下载失败] 应用可能缺少 im:message 或 im:message:readonly 权限';
280
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
292
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
281
293
  }
282
294
  }
283
295
  // 处理文件消息
@@ -292,11 +304,11 @@ export class FeishuChannel {
292
304
  const filePath = await this.downloadFile(fileKey, fileName, msg.message_id, projectPath);
293
305
  if (filePath) {
294
306
  const prompt = quotedText + `用户发送了文件:${fileName}\n文件已保存到:${filePath}\n请使用 Read 工具读取并分析文件内容。`;
295
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
307
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
296
308
  }
297
309
  else {
298
310
  const prompt = quotedText + '[文件下载失败] 应用可能缺少 im:resource 权限';
299
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
311
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
300
312
  }
301
313
  }
302
314
  // 处理富文本消息
@@ -329,7 +341,7 @@ export class FeishuChannel {
329
341
  finalContent = `${title}\n${finalContent}`;
330
342
  finalContent = quotedText + finalContent;
331
343
  const allImages = [...quotedImages, ...postImages];
332
- await this.messageHandler({ channelId: msg.chat_id, content: finalContent, images: allImages.length > 0 ? allImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
344
+ await dispatchMessage({ channelId: msg.chat_id, content: finalContent, images: allImages.length > 0 ? allImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
333
345
  }
334
346
  // 处理合并转发消息
335
347
  else if (msg.message_type === 'merge_forward') {
@@ -338,18 +350,18 @@ export class FeishuChannel {
338
350
  // 直接发送合并转发时,parent_id 指向自己,引用解析会把相同内容填入 quotedText 导致重复,丢弃
339
351
  const finalContent = mergedText;
340
352
  const allImages = [...quotedImages, ...mergedImages];
341
- await this.messageHandler({ channelId: msg.chat_id, content: finalContent, images: allImages.length > 0 ? allImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
353
+ await dispatchMessage({ channelId: msg.chat_id, content: finalContent, images: allImages.length > 0 ? allImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
342
354
  }
343
355
  else {
344
356
  const prompt = quotedText + '[合并转发消息解析失败]';
345
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
357
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
346
358
  }
347
359
  }
348
360
  // 处理其他类型消息
349
361
  else {
350
362
  logger.debug('[Feishu] Unsupported message type:', msg.message_type);
351
363
  const prompt = quotedText + `[不支持的消息类型: ${msg.message_type}]`;
352
- await this.messageHandler({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
364
+ await dispatchMessage({ channelId: msg.chat_id, content: prompt, images: quotedImages.length > 0 ? quotedImages : undefined, peerId, peerName, messageId: msg.message_id, threadId, rootId, chatType });
353
365
  }
354
366
  }
355
367
  catch (error) {
@@ -1122,8 +1134,12 @@ export class FeishuChannel {
1122
1134
  rememberInvalidatedInteraction(interactionId, reason) {
1123
1135
  this.invalidatedInteractions.set(interactionId, reason);
1124
1136
  const previousTimer = this.invalidationTimers.get(interactionId);
1125
- if (previousTimer)
1126
- clearTimeout(previousTimer);
1137
+ if (previousTimer) {
1138
+ if (this.lifecycle)
1139
+ void this.lifecycle.clearTimeout(previousTimer);
1140
+ else
1141
+ clearTimeout(previousTimer);
1142
+ }
1127
1143
  const expire = () => {
1128
1144
  this.invalidatedInteractions.delete(interactionId);
1129
1145
  this.invalidationTimers.delete(interactionId);
@@ -31,6 +31,7 @@ export class QQBotChannel {
31
31
  config;
32
32
  client = null;
33
33
  connected = false;
34
+ connectionGeneration = 0;
34
35
  messageHandler = null;
35
36
  recallHandler;
36
37
  seenMessages = new Map();
@@ -67,11 +68,16 @@ export class QQBotChannel {
67
68
  }
68
69
  // ── Lifecycle ──────────────────────────────────────────────────────────────
69
70
  async connect() {
71
+ this.lifecycle?.assertActive();
72
+ const generation = ++this.connectionGeneration;
70
73
  const { appId, clientSecret } = this.config;
71
74
  if (!appId || !clientSecret || appId.includes('your-') || clientSecret.includes('your-')) {
72
75
  throw new Error('QQBot appId/clientSecret not configured');
73
76
  }
74
- const { QQBotClient } = await requireOptional('pure-qqbot');
77
+ const { QQBotClient } = await requireOptional('pure-qqbot', false);
78
+ if (generation !== this.connectionGeneration)
79
+ throw new Error('qqbot connection cancelled');
80
+ this.lifecycle?.assertActive();
75
81
  const client = new QQBotClient({
76
82
  appId,
77
83
  clientSecret,
@@ -132,6 +138,7 @@ export class QQBotChannel {
132
138
  logger.info('[QQBot] Connected via WebSocket Gateway v2');
133
139
  }
134
140
  async disconnect() {
141
+ this.connectionGeneration++;
135
142
  this.connected = false;
136
143
  if (this.cleanupInterval) {
137
144
  if (this.lifecycle)
@@ -176,13 +183,24 @@ export class QQBotChannel {
176
183
  return { connected: this.connected };
177
184
  }
178
185
  onMessage(handler) {
179
- this.messageHandler = handler;
186
+ this.messageHandler = async (event) => {
187
+ if (this.lifecycle && this.lifecycle.state !== 'active')
188
+ return;
189
+ await handler(event);
190
+ };
180
191
  }
181
192
  onRecall(handler) {
182
193
  this.recallHandler = handler;
183
194
  }
184
195
  // ── Inbound message handling ───────────────────────────────────────────────
185
196
  async handleIncoming(event) {
197
+ const generation = this.connectionGeneration;
198
+ const isCurrent = () => generation === this.connectionGeneration
199
+ && (!this.lifecycle || this.lifecycle.state === 'active');
200
+ const dispatchMessage = async (event) => {
201
+ if (isCurrent())
202
+ await this.messageHandler?.(event);
203
+ };
186
204
  try {
187
205
  // Filter: only c2c and group
188
206
  if (!this.shouldProcess(event.type))
@@ -202,23 +220,26 @@ export class QQBotChannel {
202
220
  if (!this.messageHandler)
203
221
  return;
204
222
  // 首次交互欢迎消息(使用共享帮助函数)
205
- await sendWelcomeIfNeeded(this.welcomeManager, event.senderId, chatId, (id, text) => this.sendMessage(id, text), 'QQBot');
223
+ await sendWelcomeIfNeeded(this.welcomeManager, event.senderId, chatId, async (id, text) => { if (isCurrent())
224
+ await this.sendMessage(id, text); }, 'QQBot');
225
+ if (!isCurrent())
226
+ return;
206
227
  // Check for attachments (images/files)
207
228
  const attachments = event.attachments || [];
208
229
  const imageAttachments = attachments.filter(a => a.content_type?.startsWith('image/'));
209
230
  const fileAttachments = attachments.filter(a => !a.content_type?.startsWith('image/'));
210
231
  if (imageAttachments.length > 0) {
211
- await this.handleImageAttachments(imageAttachments, event, chatId, chatType);
232
+ await this.handleImageAttachments(imageAttachments, event, chatId, chatType, dispatchMessage);
212
233
  }
213
234
  else if (fileAttachments.length > 0) {
214
- await this.handleFileAttachments(fileAttachments, event, chatId, chatType);
235
+ await this.handleFileAttachments(fileAttachments, event, chatId, chatType, dispatchMessage);
215
236
  }
216
237
  else {
217
238
  // Pure text
218
239
  const text = (event.content || '').trim();
219
240
  if (!text)
220
241
  return;
221
- await this.messageHandler({
242
+ await dispatchMessage({
222
243
  channelId: chatId, content: text, chatType,
223
244
  peerId: event.senderId || '', peerName: event.senderName,
224
245
  messageId: event.messageId,
@@ -230,7 +251,7 @@ export class QQBotChannel {
230
251
  }
231
252
  }
232
253
  // ── Inbound media handling ─────────────────────────────────────────────────
233
- async handleImageAttachments(attachments, event, chatId, chatType) {
254
+ async handleImageAttachments(attachments, event, chatId, chatType, dispatchMessage = this.messageHandler) {
234
255
  const images = [];
235
256
  for (const att of attachments) {
236
257
  if (!att.url)
@@ -252,14 +273,14 @@ export class QQBotChannel {
252
273
  }
253
274
  const text = (event.content || '').trim();
254
275
  const prompt = text || (images.length > 0 ? '用户发送了一张图片,请分析这张图片的内容。' : '[空消息]');
255
- await this.messageHandler({
276
+ await dispatchMessage({
256
277
  channelId: chatId, content: prompt, chatType,
257
278
  peerId: event.senderId || '', peerName: event.senderName,
258
279
  messageId: event.messageId,
259
280
  images: images.length > 0 ? images : undefined,
260
281
  });
261
282
  }
262
- async handleFileAttachments(attachments, event, chatId, chatType) {
283
+ async handleFileAttachments(attachments, event, chatId, chatType, dispatchMessage = this.messageHandler) {
263
284
  for (const att of attachments) {
264
285
  if (!att.url)
265
286
  continue;
@@ -271,7 +292,7 @@ export class QQBotChannel {
271
292
  : process.cwd();
272
293
  const buffer = await safeFetch(att.url, { skipSsrfCheck: true });
273
294
  const { filePath } = saveToUploads(buffer, sanitizeFileName(fileName), projectPath);
274
- await this.messageHandler({
295
+ await dispatchMessage({
275
296
  channelId: chatId,
276
297
  content: `用户发送了文件:${fileName}\n文件已保存到:${filePath}\n请使用 Read 工具读取并分析文件内容。`,
277
298
  chatType, peerId: event.senderId || '', peerName: event.senderName,
@@ -280,7 +301,7 @@ export class QQBotChannel {
280
301
  }
281
302
  catch (error) {
282
303
  logger.error('[QQBot] Failed to download file:', error);
283
- await this.messageHandler({
304
+ await dispatchMessage({
284
305
  channelId: chatId, content: `[文件下载失败] ${fileName}`,
285
306
  chatType, peerId: event.senderId || '', peerName: event.senderName,
286
307
  messageId: event.messageId,