evolcore 0.0.42 → 0.0.43-test.1

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 (189) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bin/ec-safe-output.js +4 -1
  3. package/dist/ability/application-service.js +882 -0
  4. package/dist/ability/authorization.js +70 -0
  5. package/dist/ability/command-contract.js +105 -0
  6. package/dist/ability/daemon.js +137 -0
  7. package/dist/ability/development.js +450 -0
  8. package/dist/ability/environment.js +75 -0
  9. package/dist/ability/interop-v1.js +547 -0
  10. package/dist/ability/management.js +79 -0
  11. package/dist/ability/package.js +264 -0
  12. package/dist/ability/provider.js +73 -0
  13. package/dist/ability/publication.js +107 -0
  14. package/dist/ability/resources.js +106 -0
  15. package/dist/ability/runtime.js +212 -0
  16. package/dist/ability/secrets.js +47 -0
  17. package/dist/ability/store.js +112 -0
  18. package/dist/ability/toolchain.js +69 -0
  19. package/dist/ability/types.js +14 -0
  20. package/dist/ability/versions.js +32 -0
  21. package/dist/agents/baseagent.js +2 -2
  22. package/dist/agents/claude-runner.js +4 -0
  23. package/dist/agents/codex-runner.js +81 -17
  24. package/dist/agents/ecagent-plugin-lazy.js +41 -0
  25. package/dist/agents/ecagent-runner.js +18 -11
  26. package/dist/aun/ability-device-routing.js +12 -1
  27. package/dist/aun/aid/agentmd.js +2 -2
  28. package/dist/aun/aid/client.js +1 -1
  29. package/dist/aun/aid/identity.js +45 -0
  30. package/dist/aun/aid/index.js +1 -0
  31. package/dist/aun/aid/managed-operation.js +73 -2
  32. package/dist/channels/aun.js +64 -18
  33. package/dist/channels/builtin-plugins.js +14 -0
  34. package/dist/channels/dingtalk.js +78 -26
  35. package/dist/channels/feishu.js +89 -14
  36. package/dist/channels/qqbot.js +84 -19
  37. package/dist/channels/wechat.js +77 -19
  38. package/dist/channels/wecom.js +67 -22
  39. package/dist/cli/ability-command.js +92 -0
  40. package/dist/cli/aun-commands.js +124 -85
  41. package/dist/cli/daemon-commands.js +37 -85
  42. package/dist/cli/index.js +14 -0
  43. package/dist/cli/init.js +11 -13
  44. package/dist/cli/managed-command-guard.js +6 -0
  45. package/dist/cli/model.js +101 -104
  46. package/dist/cli/provider-command.js +6 -4
  47. package/dist/cli/restart-monitor.js +52 -11
  48. package/dist/cli/upgrade-command.js +102 -0
  49. package/dist/cli/version.js +1 -1
  50. package/dist/config/access-policy.js +4 -2
  51. package/dist/config/builtin-roles.js +1 -0
  52. package/dist/config/config-field-policy.js +4 -0
  53. package/dist/config/config-manager.js +7 -0
  54. package/dist/config/provider-ipc-service.js +10 -0
  55. package/dist/config/providers-config.js +12 -3
  56. package/dist/config/providers-management.js +45 -9
  57. package/dist/config/schema-migration.js +40 -22
  58. package/dist/contracts/ecweb-service-protocol.js +2 -1
  59. package/dist/core/agent-runtime.js +2 -1
  60. package/dist/core/auth/agent-delegation.js +21 -5
  61. package/dist/core/auth/auth-gateway.js +31 -9
  62. package/dist/core/auth/authorization-audit.js +52 -4
  63. package/dist/core/auth/delegation-authorization.js +140 -4
  64. package/dist/core/auth/operation-authorizer.js +114 -13
  65. package/dist/core/auth/operation-catalog.js +118 -4
  66. package/dist/core/baseagent-loader.js +14 -1
  67. package/dist/core/channel-loader.js +47 -9
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-storage-menu.js +1 -1
  70. package/dist/core/command/cli-intent-parser.js +26 -13
  71. package/dist/core/command/command-handler.js +232 -76
  72. package/dist/core/command/connect-menu.js +10 -4
  73. package/dist/core/command/daemon-diagnostics.js +3 -3
  74. package/dist/core/command/data-root-resolver.js +2 -3
  75. package/dist/core/command/menu-catalog.js +10 -3
  76. package/dist/core/command/menu-handler.js +321 -46
  77. package/dist/core/command/menu-protocol.js +53 -7
  78. package/dist/core/command/pa-workspace-calendar.js +1 -2
  79. package/dist/core/command/pa-workspace-items.js +486 -0
  80. package/dist/core/command/pa-workspace-store.js +10 -1
  81. package/dist/core/command/slash-gate.js +2 -2
  82. package/dist/core/command/slash-handler.js +67 -25
  83. package/dist/core/contact-bind-registry.js +27 -0
  84. package/dist/core/daemon-control.js +3 -3
  85. package/dist/core/daemon-lifecycle.js +2 -1
  86. package/dist/core/event-bus.js +9 -2
  87. package/dist/core/handoff/ipc-registration.js +1 -0
  88. package/dist/core/host-snapshot.js +1 -2
  89. package/dist/core/initialization/service.js +32 -11
  90. package/dist/core/ipc-registration.js +18 -5
  91. package/dist/core/memory/consolidation-context.js +2 -2
  92. package/dist/core/message/aun-request-registry.js +99 -18
  93. package/dist/core/message/im-renderer.js +16 -11
  94. package/dist/core/message/message-admission.js +25 -20
  95. package/dist/core/message/message-bridge.js +21 -47
  96. package/dist/core/message/message-queue.js +3 -0
  97. package/dist/core/message/response-engine.js +7 -5
  98. package/dist/core/model/catalog-service.js +1 -1
  99. package/dist/core/permission/ec-command-parser.js +41 -9
  100. package/dist/core/permission/permission-result.js +1 -0
  101. package/dist/core/permission/protected-paths.js +25 -14
  102. package/dist/core/permission/tool-policy.js +108 -107
  103. package/dist/core/plugin-lifecycle.js +133 -0
  104. package/dist/core/runner-reload-transaction.js +4 -1
  105. package/dist/core/system-session/memory.js +16 -3
  106. package/dist/core/task/task-activity-store.js +50 -0
  107. package/dist/core/task/task-image-resources.js +140 -0
  108. package/dist/core/thread/ipc-operation.js +1 -1
  109. package/dist/core/thread/thread-service.js +0 -1
  110. package/dist/directory/canonical-digest.js +5 -3
  111. package/dist/directory/owner-directory-admission.js +22 -2
  112. package/dist/directory/owner-directory-cache.js +394 -60
  113. package/dist/directory/owner-directory-markdown.js +29 -2
  114. package/dist/directory/owner-directory-scope.js +35 -16
  115. package/dist/ecweb/basic-settings-service.js +4 -1
  116. package/dist/ecweb/pairing.js +41 -0
  117. package/dist/ecweb/providers-service.js +8 -1
  118. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  119. package/dist/ecweb/runtime/lifecycle.js +184 -0
  120. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  121. package/dist/index.js +34 -25
  122. package/dist/ipc.js +124 -7
  123. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  124. package/dist/trigger/authorization.js +2 -2
  125. package/dist/utils/atomic-write.js +24 -0
  126. package/dist/utils/avatar-upload.js +3 -1
  127. package/dist/utils/cross-platform.js +31 -2
  128. package/dist/utils/host-info.js +36 -0
  129. package/dist/utils/instance-registry.js +38 -11
  130. package/dist/utils/logger.js +9 -0
  131. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  132. package/dist/utils/tool-summary.js +9 -1
  133. package/dist/utils/upgrade-jobs.js +96 -15
  134. package/dist/utils/windows-autostart.js +1 -1
  135. package/ecagent/README.md +19 -0
  136. package/ecagent/dist/harness/agent-harness.js +9 -0
  137. package/ecagent/dist/harness/env/nodejs.js +71 -11
  138. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  139. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  140. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  141. package/kits/docs/evolcore/INDEX.md +5 -1
  142. package/kits/docs/evolcore/ability.md +181 -0
  143. package/kits/docs/evolcore/aid.md +20 -0
  144. package/kits/docs/evolcore/config.md +10 -6
  145. package/kits/docs/evolcore/menu-protocol.md +40 -1
  146. package/kits/docs/evolcore/provider.md +2 -2
  147. package/kits/docs/evolcore/tool-authorization.md +270 -0
  148. package/kits/runtime/ability-job.ps1 +41 -0
  149. package/kits/runtime/ability-runner.mjs +67 -0
  150. package/kits/runtime/ability-secret.ps1 +59 -0
  151. package/kits/runtime/ability-templates/go/main.go +59 -0
  152. package/kits/runtime/ability-templates/java/Json.java +67 -0
  153. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  154. package/kits/runtime/ability-templates/python/runner.py +48 -0
  155. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  156. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  157. package/kits/schemas/_meta.json +12 -1
  158. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  159. package/kits/schemas/ability-project.schema.1.json +31 -0
  160. package/kits/schemas/agent-config.schema.16.json +20 -0
  161. package/kits/schemas/agent-config.schema.17.json +20 -0
  162. package/kits/schemas/agent-config.schema.18.json +917 -0
  163. package/kits/skills/.switches.json +4 -0
  164. package/kits/skills/aid-ability/SKILL.md +5 -4
  165. package/kits/skills/ec-ability/SKILL.md +67 -0
  166. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  167. package/kits/skills/ec-ability/references/development.md +104 -0
  168. package/kits/skills/ec-ability/references/management.md +117 -0
  169. package/kits/skills/ec-ability/references/recovery.md +27 -0
  170. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  171. package/kits/skills/ec-ability/references/workflows.md +15 -0
  172. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  173. package/kits/skills/personal-assistant/SKILL.md +240 -6
  174. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  175. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  176. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  177. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  178. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  179. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  180. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  181. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  182. package/kits/templates/memory-consolidation/notes.md +1 -1
  183. package/kits/templates/system-fragments/channel.md +2 -1
  184. package/kits/templates/system-fragments/commands.md +1 -0
  185. package/package.json +5 -3
  186. package/dist/core/command/data-root-error.js +0 -10
  187. package/dist/utils/machine-info.js +0 -46
  188. package/dist/utils/process-tree-worker.js +0 -31
  189. package/dist/utils/windows-output.js +0 -36
@@ -4,7 +4,7 @@ import crypto from 'crypto';
4
4
  import { performance } from 'node:perf_hooks';
5
5
  import fs from 'fs';
6
6
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
7
- import { OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/owner-directory-cache.js';
7
+ import { OWNER_DIRECTORY_APPLY_WAIT_MS, OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/owner-directory-cache.js';
8
8
  import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-admission.js';
9
9
  import { OwnerDirectoryAgentMdSync } from '../directory/owner-directory-agentmd-sync.js';
10
10
  import { parseNotificationSnapshots } from '../directory/owner-directory-store.js';
@@ -18,6 +18,8 @@ import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } f
18
18
  import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
19
19
  import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
20
20
  import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
21
+ import { AbilityError } from '../ability/types.js';
22
+ import { publishAbilityDocuments } from '../ability/publication.js';
21
23
  import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
22
24
  import { saveToUploads, saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch } from '../utils/media-cache.js';
23
25
  import { appendAidEvent } from '../utils/instance-registry.js';
@@ -1725,13 +1727,14 @@ export class AUNChannel {
1725
1727
  PeerIdentityCache.invalidate('aun', aid, path.join(resolvePaths().agentsDir, this.config.aid));
1726
1728
  }
1727
1729
  /**
1728
- * Fire-and-forget:每条进入消息队列的消息都走这里。
1730
+ * 每条进入消息队列的消息都走这里。分两段,代价完全不同:
1729
1731
  *
1730
- * ① 有 pending 就补拉一次共享缓存——立即拉取失败后,这里是唯一的重试机会;
1731
- * ② 无论拉没拉成,都把共享缓存落到本 agent 目录。落地按 content_digest 判重,
1732
- * 没有新内容时几乎零成本,所以不需要任何"有新内容吗"的标记。
1733
- *
1734
- * 两段串行,落地必须等拉取结束,否则可能拿旧数据覆盖刚落的新数据。
1732
+ * ① **落地**(共享缓存 → 本 agent 目录 + directory.md):只读本机文件、写本机
1733
+ * 文件,毫秒级。**必须在本轮上下文渲染之前完成**——ECK 的 `hasOwnerDirectory`
1734
+ * 是同步 stat,落地没做完这条消息就整段丢名录(directory.md 此前不存在时更彻底,
1735
+ * 连段都不会进)。所以这一段有界等待,见 `settleOwnerDirectoryBeforeTurn`。
1736
+ * ② **拉取**(owner 级 → 共享缓存):走网络,可能几秒。不阻塞消息,后台跑,
1737
+ * 跑完再落一次地,让下一条消息看到新内容。它同时是"立即拉取失败"的唯一重试机会。
1735
1738
  */
1736
1739
  processPendingDirectoryUpdate() {
1737
1740
  const runtime = this.ownerDirectoryCache;
@@ -1746,6 +1749,19 @@ export class AUNChannel {
1746
1749
  logger.warn(`${this.logPrefix()} processPendingDirectoryUpdate apply failed: ${error instanceof Error ? error.message : String(error)}`);
1747
1750
  });
1748
1751
  }
1752
+ /**
1753
+ * 渲染本轮上下文之前,把「共享缓存 → 本 agent 目录」这一步做完。
1754
+ *
1755
+ * 只等落地、不等网络:owner 级目录若已更新而本 agent 还没落地,这里几百毫秒内
1756
+ * 就补齐;owner 级共享缓存根本不存在时立即返回,不发请求也不空等。拉取由
1757
+ * `processPendingDirectoryUpdate` 在后台继续,下一条消息自然看到新内容。
1758
+ */
1759
+ async settleOwnerDirectoryBeforeTurn() {
1760
+ const runtime = this.ownerDirectoryCache;
1761
+ if (!runtime)
1762
+ return;
1763
+ await runtime.cache.applyFromSharedCacheWithin(OWNER_DIRECTORY_APPLY_WAIT_MS).catch(() => undefined);
1764
+ }
1749
1765
  async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
1750
1766
  // 只认点名发给的那台设备:广播或其它设备的回复不能改写授权状态。
1751
1767
  // 无 targetDeviceId 的是旧记录,无从校验,放行(调用方已确认 state=completed 且消息匹配)。
@@ -1834,11 +1850,21 @@ export class AUNChannel {
1834
1850
  return;
1835
1851
  runtime.cache.saveAuthorization(parsed);
1836
1852
  logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
1837
- // 授权变更本身不触发拉取:名录变没变由 owner.directory.changed 说了算。
1838
- // 只有本地还没有任何快照时才补一次,否则新授权的 agent 要等到下一条入站消息才有名录。
1839
- if (!runtime.cache.readSnapshot('contacts')) {
1840
- logger.info(`${this.logPrefix()} owner.directory.grant: no local snapshot yet, scheduling first pull`);
1841
- await runtime.cache.handleOwnerChangedEvent(senderAid);
1853
+ // 授权被撤销/拒绝时 saveAuthorization 已经清掉凭证和快照,这里无事可做:
1854
+ // 下一次 owner.directory.changed 会写 pending,准入回落到"名录不可用"。
1855
+ if (runtime.cache.scopeAccess('contacts') !== 'authorized')
1856
+ return;
1857
+ // 授权是 Owner 的主动操作,用户点完就在等结果。写标记 + 立即拉取 + 落地,
1858
+ // 不再等"下一条入站消息"——那条消息可能几小时后才来。
1859
+ await runtime.cache.handleOwnerChangedEvent(senderAid);
1860
+ try {
1861
+ await runtime.cache.processPendingIfNeeded();
1862
+ await runtime.cache.applyFromSharedCache();
1863
+ logger.info(`${this.logPrefix()} owner.directory.grant: pulled and applied after authorization (total=${runtime.cache.readSnapshot('contacts')?.total ?? 'none'})`);
1864
+ }
1865
+ catch (error) {
1866
+ // 拉取失败不影响授权本身:pending 还在,退避重试或下一条消息会补上。
1867
+ logger.warn(`${this.logPrefix()} owner.directory.grant: initial pull failed (pending kept): ${error instanceof Error ? error.message : String(error)}`);
1842
1868
  }
1843
1869
  }
1844
1870
  buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
@@ -2074,9 +2100,9 @@ export class AUNChannel {
2074
2100
  baseName: 'aun',
2075
2101
  logDir: resolvePaths().logs,
2076
2102
  rotation: 'hourly',
2077
- retention: { hours: 24 },
2103
+ retention: { hours: 48 },
2078
2104
  });
2079
- logger.info(`${this.logPrefix()} Trace logging enabled (hourly rotation, 24h retention): ${this.traceWriter.activePath()}`);
2105
+ logger.info(`${this.logPrefix()} Trace logging enabled (hourly rotation, 48h retention): ${this.traceWriter.activePath()}`);
2080
2106
  }
2081
2107
  this.aidState = {
2082
2108
  aid: config.aid,
@@ -2358,6 +2384,10 @@ export class AUNChannel {
2358
2384
  }
2359
2385
  else if (eventName === 'sync.stopped') {
2360
2386
  const record = data && typeof data === 'object' ? data : {};
2387
+ // Empty Pull runs do not represent a delivery change.
2388
+ if ((record.reason === 'pull_drained' || record.reason === 'aborted') && !(record.received_total > 0)) {
2389
+ return;
2390
+ }
2361
2391
  logger.info(`${this.logPrefix()} AUN sync stopped: reason=${record.reason ?? 'unknown'}`);
2362
2392
  }
2363
2393
  });
@@ -2939,6 +2969,8 @@ export class AUNChannel {
2939
2969
  fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
2940
2970
  messageId,
2941
2971
  payload,
2972
+ encrypted: !!env.encrypted,
2973
+ transport: 'p2p',
2942
2974
  });
2943
2975
  if (responseRecord) {
2944
2976
  // An ignored device response or an ACK must not update authorization state.
@@ -3449,8 +3481,8 @@ export class AUNChannel {
3449
3481
  });
3450
3482
  }
3451
3483
  dispatchMessage(event) {
3452
- // 懒触发:收到任意消息时检查 pending,有则先拉取名录再继续处理消息
3453
- void this.processPendingDirectoryUpdate();
3484
+ // 懒触发:收到任意消息时补拉共享缓存(后台,不等),落地交给下面交给上层之前那一步
3485
+ this.processPendingDirectoryUpdate();
3454
3486
  const authenticatedDelivery = event.chatType === 'group'
3455
3487
  ? { chatType: 'group', groupId: event.groupId ?? event.channelId }
3456
3488
  : { chatType: 'private' };
@@ -3508,7 +3540,8 @@ export class AUNChannel {
3508
3540
  delivery,
3509
3541
  ...(typeof threadId === 'string' ? { threadId } : {}),
3510
3542
  };
3511
- this.messageHandler({
3543
+ const handler = this.messageHandler;
3544
+ const inbound = {
3512
3545
  channelId: event.channelId || '',
3513
3546
  channelType: 'aun',
3514
3547
  content: event.text || '',
@@ -3542,7 +3575,13 @@ export class AUNChannel {
3542
3575
  payloadType: event.payloadType,
3543
3576
  payloadSummary: event.payloadSummary,
3544
3577
  messageLogContent: event.messageLogContent,
3545
- }).catch(err => {
3578
+ };
3579
+ // 落地先于这一轮处理:ECK 的 hasOwnerDirectory 是同步 stat,名录没落盘时
3580
+ // 本轮上下文就会丢掉整段名录。这段最多等 OWNER_DIRECTORY_APPLY_WAIT_MS,
3581
+ // 且只等本地 I/O;网络拉取仍在 processPendingDirectoryUpdate 里后台跑。
3582
+ void this.settleOwnerDirectoryBeforeTurn()
3583
+ .then(() => handler(inbound))
3584
+ .catch(err => {
3546
3585
  logger.error(`${this.logPrefix()} Message handler error:`, err);
3547
3586
  });
3548
3587
  }
@@ -5559,6 +5598,13 @@ export class AUNChannel {
5559
5598
  };
5560
5599
  }
5561
5600
  }
5601
+ /** Public contracts use this AID's existing authenticated storage connection. */
5602
+ get abilityPublisherAid() { return this._aid || this.config.aid; }
5603
+ async publishAbilityDocuments(documents, expectedIndexes = []) {
5604
+ if (!this.connected || !this.client)
5605
+ throw new AbilityError('AUN_NOT_CONNECTED', 'AUN channel is not connected', 503);
5606
+ await publishAbilityDocuments(this.client.storage, this.abilityPublisherAid, documents, expectedIndexes);
5607
+ }
5562
5608
  /** Build an attachment payload with the daemon's long-lived AUN connection. */
5563
5609
  async buildDaemonFilePayload(file) {
5564
5610
  if (!this.connected || !this.client) {
@@ -0,0 +1,14 @@
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());
10
+ channelLoader.register(new AUNChannelPlugin());
11
+ channelLoader.register(new DingtalkChannelPlugin());
12
+ channelLoader.register(new QQBotChannelPlugin());
13
+ channelLoader.register(new WecomChannelPlugin());
14
+ }
@@ -156,6 +156,7 @@ const WEBHOOK_RE = /^https:\/\/(api|oapi)\.dingtalk\.com\//;
156
156
  export class DingtalkChannel {
157
157
  agentAid;
158
158
  channelName;
159
+ lifecycle;
159
160
  config;
160
161
  client = null;
161
162
  connected = false;
@@ -184,9 +185,10 @@ export class DingtalkChannel {
184
185
  projectPathProvider = null;
185
186
  // Welcome message manager
186
187
  welcomeManager;
187
- constructor(config, agentAid, channelName) {
188
+ constructor(config, agentAid, channelName, lifecycle) {
188
189
  this.agentAid = agentAid;
189
190
  this.channelName = channelName;
191
+ this.lifecycle = lifecycle;
190
192
  this.config = config;
191
193
  // 初始化 welcomeManager(使用共享帮助函数)
192
194
  if (agentAid && channelName) {
@@ -333,23 +335,81 @@ export class DingtalkChannel {
333
335
  this.loadSeenMessages();
334
336
  this.loadRoutes();
335
337
  const { DWClient, TOPIC_ROBOT, TOPIC_CARD } = await requireOptional('dingtalk-stream');
336
- this.client = new DWClient({ clientId, clientSecret });
337
- this.client.registerCallbackListener(TOPIC_ROBOT, async (msg) => {
338
+ const client = new DWClient({ clientId, clientSecret });
339
+ this.client = client;
340
+ client.registerCallbackListener(TOPIC_ROBOT, async (msg) => {
341
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== "active"))
342
+ return;
338
343
  await this.handleIncoming(msg);
339
344
  });
340
- this.client.registerCallbackListener(TOPIC_CARD || DINGTALK_CARD_CALLBACK_TOPIC, async (msg) => {
345
+ client.registerCallbackListener(TOPIC_CARD || DINGTALK_CARD_CALLBACK_TOPIC, async (msg) => {
346
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== "active"))
347
+ return;
341
348
  await this.handleCardCallbackMessage(msg);
342
349
  });
343
- if (typeof this.client.registerAllEventListener === 'function') {
344
- this.client.registerAllEventListener((event) => {
350
+ if (typeof client.registerAllEventListener === 'function') {
351
+ client.registerAllEventListener((event) => {
352
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== "active"))
353
+ return { status: "SUCCESS" };
345
354
  this.handlePlatformEvent(event);
346
355
  return { status: 'SUCCESS' };
347
356
  });
348
357
  }
349
- await this.client.connect();
358
+ try {
359
+ await client.connect();
360
+ }
361
+ catch (error) {
362
+ if (this.client === client) {
363
+ this.client = null;
364
+ this.connected = false;
365
+ }
366
+ try {
367
+ client.disconnect();
368
+ }
369
+ catch (disconnectError) {
370
+ logger.warn('[DingTalk] Failed to disconnect after connect error:', disconnectError);
371
+ }
372
+ throw error;
373
+ }
374
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== 'active')) {
375
+ try {
376
+ client.disconnect();
377
+ }
378
+ catch (error) {
379
+ logger.warn('[DingTalk] Failed to close superseded client:', error);
380
+ }
381
+ return;
382
+ }
350
383
  this.connected = true;
351
384
  // Hourly cleanup of old dedup entries
352
- this.cleanupInterval = setInterval(() => {
385
+ this.startCleanupTask();
386
+ logger.info('[DingTalk] Connected via Stream Mode');
387
+ }
388
+ async disconnect() {
389
+ this.connected = false;
390
+ if (this.cleanupInterval) {
391
+ if (this.lifecycle)
392
+ await this.lifecycle.clearInterval(this.cleanupInterval);
393
+ else
394
+ clearInterval(this.cleanupInterval);
395
+ this.cleanupInterval = null;
396
+ }
397
+ const client = this.client;
398
+ this.client = null;
399
+ if (client) {
400
+ try {
401
+ client.disconnect();
402
+ }
403
+ catch (error) {
404
+ logger.warn('[DingTalk] Failed to disconnect client:', error);
405
+ }
406
+ }
407
+ logger.info('[DingTalk] Disconnected');
408
+ }
409
+ startCleanupTask() {
410
+ if (this.cleanupInterval)
411
+ return;
412
+ const cleanup = () => {
353
413
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
354
414
  for (const [id, ts] of this.seenMessages) {
355
415
  if (ts < cutoff)
@@ -364,23 +424,10 @@ export class DingtalkChannel {
364
424
  }
365
425
  }
366
426
  this.cleanupCardState();
367
- }, 60 * 60 * 1000);
368
- logger.info('[DingTalk] Connected via Stream Mode');
369
- }
370
- async disconnect() {
371
- this.connected = false;
372
- if (this.cleanupInterval) {
373
- clearInterval(this.cleanupInterval);
374
- this.cleanupInterval = null;
375
- }
376
- if (this.client) {
377
- try {
378
- this.client.disconnect();
379
- }
380
- catch { /* ignore */ }
381
- this.client = null;
382
- }
383
- logger.info('[DingTalk] Disconnected');
427
+ };
428
+ this.cleanupInterval = this.lifecycle
429
+ ? this.lifecycle.setInterval(cleanup, 60 * 60 * 1000)
430
+ : setInterval(cleanup, 60 * 60 * 1000);
384
431
  }
385
432
  getStatus() {
386
433
  return { connected: this.connected };
@@ -1281,6 +1328,11 @@ function isValidCredential(value) {
1281
1328
  }
1282
1329
  export class DingtalkChannelPlugin {
1283
1330
  name = 'dingtalk';
1331
+ contactBind = {
1332
+ displayName: '钉钉',
1333
+ register: registerPendingDingtalkContactBind,
1334
+ handle: handlePendingDingtalkContactBindMessage,
1335
+ };
1284
1336
  async createInstance(inst, ctx) {
1285
1337
  if (inst.enabled === false)
1286
1338
  return null;
@@ -1297,7 +1349,7 @@ export class DingtalkChannelPlugin {
1297
1349
  cardTemplateId: inst.cardTemplateId,
1298
1350
  seenMsgFile: channelStatePath(inst.name, 'dingtalk-seen.jsonl'),
1299
1351
  routeFile: channelStatePath(inst.name, 'routes.json'),
1300
- }, ctx.agentName, inst.name);
1352
+ }, ctx.agentName, inst.name, ctx.lifecycle);
1301
1353
  const mode = resolveShowActivities(inst);
1302
1354
  const adapter = {
1303
1355
  channelName: inst.name,
@@ -30,11 +30,14 @@ export class FeishuChannel {
30
30
  config;
31
31
  agentAid;
32
32
  channelName;
33
+ lifecycle;
33
34
  client = null;
34
35
  wsClient = null;
35
36
  messageHandler;
36
37
  projectPathProvider;
37
38
  cleanupInterval;
39
+ connectionGeneration = 0;
40
+ invalidationTimers = new Map();
38
41
  seenMessages = new Map(); // chatId -> (messageId -> timestamp)
39
42
  seenThreads = new Set(); // 已见的 thread_id,用于判断话题创建消息
40
43
  userNameCache = new Map(); // userId -> userName
@@ -53,10 +56,11 @@ export class FeishuChannel {
53
56
  cardMetaStore = new CardMetaStore();
54
57
  // Welcome message manager(首次交互欢迎消息,与其他 IM 渠道统一)
55
58
  welcomeManager;
56
- constructor(config, agentAid, channelName) {
59
+ constructor(config, agentAid, channelName, lifecycle) {
57
60
  this.config = config;
58
61
  this.agentAid = agentAid;
59
62
  this.channelName = channelName;
63
+ this.lifecycle = lifecycle;
60
64
  // 初始化 welcomeManager(使用共享帮助函数)
61
65
  if (agentAid && channelName) {
62
66
  this.welcomeManager = initWelcomeManager('feishu', agentAid, channelName);
@@ -73,6 +77,9 @@ export class FeishuChannel {
73
77
  }
74
78
  }
75
79
  async connect() {
80
+ const generation = ++this.connectionGeneration;
81
+ const isCurrent = () => this.connectionGeneration === generation
82
+ && (!this.lifecycle || this.lifecycle.state === 'active');
76
83
  // 检查配置有效性
77
84
  if (!this.config.appId || !this.config.appSecret) {
78
85
  throw new Error('Feishu credentials missing (appId or appSecret is empty)');
@@ -84,13 +91,18 @@ export class FeishuChannel {
84
91
  this.loadSeenMessages();
85
92
  const { requireOptional } = await import('../utils/npm-ops.js');
86
93
  const lark = await requireOptional('@larksuiteoapi/node-sdk');
94
+ if (!isCurrent())
95
+ return;
87
96
  try {
88
- this.client = new lark.Client({
97
+ const client = new lark.Client({
89
98
  appId: this.config.appId,
90
99
  appSecret: this.config.appSecret,
91
100
  });
101
+ this.client = client;
92
102
  const eventDispatcher = new lark.EventDispatcher({}).register({
93
103
  'im.message.receive_v1': async (data) => {
104
+ if (!isCurrent() || this.client !== client)
105
+ return;
94
106
  const msg = data.message;
95
107
  logger.debug('[Feishu] Received message, message_id:', msg.message_id, 'type:', msg.message_type);
96
108
  logger.debug('[Feishu] Full data object:', JSON.stringify(data, null, 2));
@@ -345,6 +357,8 @@ export class FeishuChannel {
345
357
  }
346
358
  },
347
359
  'im.message.recalled_v1': async (data) => {
360
+ if (!isCurrent() || this.client !== client)
361
+ return;
348
362
  const messageId = data?.message_id;
349
363
  if (messageId) {
350
364
  logger.info('[Feishu] Message recalled:', messageId);
@@ -353,17 +367,47 @@ export class FeishuChannel {
353
367
  },
354
368
  'im.message.message_read_v1': async () => { },
355
369
  'im.message.reaction.created_v1': async () => { },
356
- 'card.action.trigger': (data) => this.handleCardAction(data),
370
+ 'card.action.trigger': (data) => {
371
+ if (!isCurrent() || this.client !== client)
372
+ return;
373
+ return this.handleCardAction(data);
374
+ },
357
375
  });
358
- this.wsClient = new lark.WSClient({
376
+ const wsClient = new lark.WSClient({
359
377
  appId: this.config.appId,
360
378
  appSecret: this.config.appSecret,
361
379
  });
362
- await this.wsClient.start({ eventDispatcher });
380
+ this.wsClient = wsClient;
381
+ await wsClient.start({ eventDispatcher });
382
+ if (!isCurrent() || this.wsClient !== wsClient) {
383
+ await wsClient.close();
384
+ return;
385
+ }
363
386
  this.connected = true;
364
387
  this.startCleanupTask();
365
388
  }
366
389
  catch (error) {
390
+ if (this.connectionGeneration === generation) {
391
+ this.connected = false;
392
+ const wsClient = this.wsClient;
393
+ this.wsClient = null;
394
+ this.client = null;
395
+ if (wsClient) {
396
+ try {
397
+ await wsClient.close();
398
+ }
399
+ catch (closeError) {
400
+ logger.warn('[Feishu] Failed to close client after connect error:', closeError);
401
+ }
402
+ }
403
+ if (this.cleanupInterval) {
404
+ if (this.lifecycle)
405
+ await this.lifecycle.clearInterval(this.cleanupInterval);
406
+ else
407
+ clearInterval(this.cleanupInterval);
408
+ this.cleanupInterval = undefined;
409
+ }
410
+ }
367
411
  if (error instanceof Error) {
368
412
  throw new Error(`Feishu connection failed: ${error.message}`);
369
413
  }
@@ -832,24 +876,40 @@ export class FeishuChannel {
832
876
  catch { }
833
877
  }
834
878
  startCleanupTask() {
835
- this.cleanupInterval = setInterval(() => {
879
+ const cleanup = () => {
836
880
  this.cleanupSeenMessages();
837
881
  // seenThreads 无时间戳,仅限容量(话题持久存在,不按时间清理)
838
882
  if (this.seenThreads.size > 1000)
839
883
  this.seenThreads.clear();
840
- }, 60 * 60 * 1000);
884
+ };
885
+ this.cleanupInterval = this.lifecycle
886
+ ? this.lifecycle.setInterval(cleanup, 60 * 60 * 1000)
887
+ : setInterval(cleanup, 60 * 60 * 1000);
841
888
  }
842
889
  async disconnect() {
890
+ this.connectionGeneration++;
843
891
  this.connected = false;
844
892
  if (this.cleanupInterval) {
845
- clearInterval(this.cleanupInterval);
893
+ if (this.lifecycle)
894
+ await this.lifecycle.clearInterval(this.cleanupInterval);
895
+ else
896
+ clearInterval(this.cleanupInterval);
846
897
  this.cleanupInterval = undefined;
847
898
  }
848
- if (this.wsClient) {
849
- await this.wsClient.close();
850
- this.wsClient = null;
851
- }
899
+ const wsClient = this.wsClient;
900
+ this.wsClient = null;
852
901
  this.client = null;
902
+ for (const timer of this.invalidationTimers.values()) {
903
+ if (this.lifecycle)
904
+ await this.lifecycle.clearTimeout(timer);
905
+ else
906
+ clearTimeout(timer);
907
+ }
908
+ this.invalidationTimers.clear();
909
+ this.invalidatedInteractions.clear();
910
+ if (wsClient) {
911
+ await wsClient.close();
912
+ }
853
913
  }
854
914
  /** Get current connection status */
855
915
  getStatus() {
@@ -1061,7 +1121,17 @@ export class FeishuChannel {
1061
1121
  }
1062
1122
  rememberInvalidatedInteraction(interactionId, reason) {
1063
1123
  this.invalidatedInteractions.set(interactionId, reason);
1064
- const timer = setTimeout(() => this.invalidatedInteractions.delete(interactionId), 24 * 60 * 60 * 1000);
1124
+ const previousTimer = this.invalidationTimers.get(interactionId);
1125
+ if (previousTimer)
1126
+ clearTimeout(previousTimer);
1127
+ const expire = () => {
1128
+ this.invalidatedInteractions.delete(interactionId);
1129
+ this.invalidationTimers.delete(interactionId);
1130
+ };
1131
+ const timer = this.lifecycle
1132
+ ? this.lifecycle.setTimeout(expire, 24 * 60 * 60 * 1000)
1133
+ : setTimeout(expire, 24 * 60 * 60 * 1000);
1134
+ this.invalidationTimers.set(interactionId, timer);
1065
1135
  timer.unref?.();
1066
1136
  }
1067
1137
  invalidatedCard(reason) {
@@ -1719,13 +1789,18 @@ export function hasMarkdownSyntax(text) {
1719
1789
  import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
1720
1790
  export class FeishuChannelPlugin {
1721
1791
  name = 'feishu';
1792
+ contactBind = {
1793
+ displayName: '飞书',
1794
+ register: registerPendingFeishuContactBind,
1795
+ handle: handlePendingFeishuContactBindMessage,
1796
+ };
1722
1797
  async createInstance(inst, ctx) {
1723
1798
  if (inst.enabled === false || !inst.appId || !inst.appSecret)
1724
1799
  return null;
1725
1800
  const channel = new FeishuChannel({
1726
1801
  appId: inst.appId,
1727
1802
  appSecret: inst.appSecret,
1728
- }, ctx.agentName, inst.name);
1803
+ }, ctx.agentName, inst.name, ctx.lifecycle);
1729
1804
  const mode = resolveShowActivities(inst);
1730
1805
  const adapter = {
1731
1806
  channelName: inst.name,