evolcore 0.0.42-test.0 → 0.0.43-test.0

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 (187) hide show
  1. package/CHANGELOG.md +31 -2
  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/identity.js +45 -0
  29. package/dist/aun/aid/index.js +1 -0
  30. package/dist/aun/aid/managed-operation.js +73 -2
  31. package/dist/channels/aun.js +64 -18
  32. package/dist/channels/builtin-plugins.js +14 -0
  33. package/dist/channels/dingtalk.js +78 -26
  34. package/dist/channels/feishu.js +89 -14
  35. package/dist/channels/qqbot.js +84 -19
  36. package/dist/channels/wechat.js +77 -19
  37. package/dist/channels/wecom.js +67 -22
  38. package/dist/cli/ability-command.js +92 -0
  39. package/dist/cli/aun-commands.js +124 -85
  40. package/dist/cli/daemon-commands.js +37 -85
  41. package/dist/cli/index.js +14 -0
  42. package/dist/cli/init.js +11 -13
  43. package/dist/cli/managed-command-guard.js +6 -0
  44. package/dist/cli/model.js +101 -104
  45. package/dist/cli/provider-command.js +6 -4
  46. package/dist/cli/restart-monitor.js +52 -11
  47. package/dist/cli/upgrade-command.js +102 -0
  48. package/dist/cli/version.js +1 -1
  49. package/dist/config/access-policy.js +4 -2
  50. package/dist/config/builtin-roles.js +1 -0
  51. package/dist/config/config-field-policy.js +4 -0
  52. package/dist/config/config-manager.js +7 -0
  53. package/dist/config/provider-ipc-service.js +10 -0
  54. package/dist/config/providers-config.js +12 -3
  55. package/dist/config/providers-management.js +45 -9
  56. package/dist/config/schema-migration.js +40 -22
  57. package/dist/contracts/ecweb-service-protocol.js +2 -1
  58. package/dist/core/auth/agent-delegation.js +21 -5
  59. package/dist/core/auth/auth-gateway.js +31 -9
  60. package/dist/core/auth/authorization-audit.js +52 -4
  61. package/dist/core/auth/delegation-authorization.js +140 -4
  62. package/dist/core/auth/operation-authorizer.js +114 -13
  63. package/dist/core/auth/operation-catalog.js +118 -4
  64. package/dist/core/baseagent-loader.js +14 -1
  65. package/dist/core/channel-loader.js +47 -9
  66. package/dist/core/channel-runtime.js +1 -1
  67. package/dist/core/command/agent-storage-menu.js +1 -1
  68. package/dist/core/command/cli-intent-parser.js +26 -13
  69. package/dist/core/command/command-handler.js +232 -76
  70. package/dist/core/command/connect-menu.js +10 -4
  71. package/dist/core/command/daemon-diagnostics.js +3 -3
  72. package/dist/core/command/data-root-resolver.js +2 -3
  73. package/dist/core/command/menu-catalog.js +10 -3
  74. package/dist/core/command/menu-handler.js +321 -46
  75. package/dist/core/command/menu-protocol.js +53 -7
  76. package/dist/core/command/pa-workspace-calendar.js +1 -2
  77. package/dist/core/command/pa-workspace-items.js +486 -0
  78. package/dist/core/command/pa-workspace-store.js +10 -1
  79. package/dist/core/command/slash-gate.js +2 -2
  80. package/dist/core/command/slash-handler.js +67 -25
  81. package/dist/core/contact-bind-registry.js +27 -0
  82. package/dist/core/daemon-control.js +3 -3
  83. package/dist/core/daemon-lifecycle.js +2 -1
  84. package/dist/core/event-bus.js +9 -2
  85. package/dist/core/handoff/ipc-registration.js +1 -0
  86. package/dist/core/host-snapshot.js +1 -2
  87. package/dist/core/initialization/service.js +32 -11
  88. package/dist/core/ipc-registration.js +18 -5
  89. package/dist/core/memory/consolidation-context.js +2 -2
  90. package/dist/core/message/aun-request-registry.js +99 -18
  91. package/dist/core/message/im-renderer.js +16 -11
  92. package/dist/core/message/message-admission.js +25 -20
  93. package/dist/core/message/message-bridge.js +21 -47
  94. package/dist/core/message/message-queue.js +3 -0
  95. package/dist/core/message/response-engine.js +7 -5
  96. package/dist/core/model/catalog-service.js +1 -1
  97. package/dist/core/permission/ec-command-parser.js +41 -9
  98. package/dist/core/permission/permission-result.js +1 -0
  99. package/dist/core/permission/protected-paths.js +25 -14
  100. package/dist/core/permission/tool-policy.js +108 -107
  101. package/dist/core/plugin-lifecycle.js +133 -0
  102. package/dist/core/runner-reload-transaction.js +4 -1
  103. package/dist/core/system-session/memory.js +16 -3
  104. package/dist/core/task/task-activity-store.js +50 -0
  105. package/dist/core/task/task-image-resources.js +140 -0
  106. package/dist/core/thread/ipc-operation.js +1 -1
  107. package/dist/core/thread/thread-service.js +0 -1
  108. package/dist/directory/canonical-digest.js +5 -3
  109. package/dist/directory/owner-directory-admission.js +22 -2
  110. package/dist/directory/owner-directory-cache.js +394 -60
  111. package/dist/directory/owner-directory-markdown.js +29 -2
  112. package/dist/directory/owner-directory-scope.js +35 -16
  113. package/dist/ecweb/basic-settings-service.js +4 -1
  114. package/dist/ecweb/pairing.js +41 -0
  115. package/dist/ecweb/providers-service.js +8 -1
  116. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  117. package/dist/ecweb/runtime/lifecycle.js +184 -0
  118. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  119. package/dist/index.js +34 -25
  120. package/dist/ipc.js +124 -7
  121. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  122. package/dist/trigger/authorization.js +2 -2
  123. package/dist/utils/atomic-write.js +24 -0
  124. package/dist/utils/avatar-upload.js +3 -1
  125. package/dist/utils/cross-platform.js +31 -2
  126. package/dist/utils/host-info.js +36 -0
  127. package/dist/utils/instance-registry.js +38 -11
  128. package/dist/utils/logger.js +9 -0
  129. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  130. package/dist/utils/tool-summary.js +9 -1
  131. package/dist/utils/upgrade-jobs.js +96 -15
  132. package/dist/utils/windows-autostart.js +1 -1
  133. package/ecagent/README.md +19 -0
  134. package/ecagent/dist/harness/agent-harness.js +9 -0
  135. package/ecagent/dist/harness/env/nodejs.js +71 -11
  136. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  137. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  138. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  139. package/kits/docs/evolcore/INDEX.md +5 -1
  140. package/kits/docs/evolcore/ability.md +181 -0
  141. package/kits/docs/evolcore/aid.md +20 -0
  142. package/kits/docs/evolcore/config.md +10 -6
  143. package/kits/docs/evolcore/menu-protocol.md +40 -1
  144. package/kits/docs/evolcore/provider.md +2 -2
  145. package/kits/docs/evolcore/tool-authorization.md +270 -0
  146. package/kits/runtime/ability-job.ps1 +41 -0
  147. package/kits/runtime/ability-runner.mjs +67 -0
  148. package/kits/runtime/ability-secret.ps1 +59 -0
  149. package/kits/runtime/ability-templates/go/main.go +59 -0
  150. package/kits/runtime/ability-templates/java/Json.java +67 -0
  151. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  152. package/kits/runtime/ability-templates/python/runner.py +48 -0
  153. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  154. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  155. package/kits/schemas/_meta.json +12 -1
  156. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  157. package/kits/schemas/ability-project.schema.1.json +31 -0
  158. package/kits/schemas/agent-config.schema.16.json +20 -0
  159. package/kits/schemas/agent-config.schema.17.json +20 -0
  160. package/kits/schemas/agent-config.schema.18.json +917 -0
  161. package/kits/skills/.switches.json +4 -0
  162. package/kits/skills/aid-ability/SKILL.md +5 -4
  163. package/kits/skills/ec-ability/SKILL.md +67 -0
  164. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  165. package/kits/skills/ec-ability/references/development.md +104 -0
  166. package/kits/skills/ec-ability/references/management.md +117 -0
  167. package/kits/skills/ec-ability/references/recovery.md +27 -0
  168. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  169. package/kits/skills/ec-ability/references/workflows.md +15 -0
  170. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  171. package/kits/skills/personal-assistant/SKILL.md +240 -6
  172. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  173. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  174. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  175. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  176. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  177. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  178. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  179. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  180. package/kits/templates/memory-consolidation/notes.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +2 -1
  182. package/kits/templates/system-fragments/commands.md +1 -0
  183. package/package.json +4 -2
  184. package/dist/core/command/data-root-error.js +0 -10
  185. package/dist/utils/machine-info.js +0 -46
  186. package/dist/utils/process-tree-worker.js +0 -31
  187. package/dist/utils/windows-output.js +0 -36
@@ -27,6 +27,7 @@ export function clearPendingQQBotContactBinds() {
27
27
  export class QQBotChannel {
28
28
  agentAid;
29
29
  channelName;
30
+ lifecycle;
30
31
  config;
31
32
  client = null;
32
33
  connected = false;
@@ -41,9 +42,10 @@ export class QQBotChannel {
41
42
  projectPathProvider = null;
42
43
  // Welcome message manager
43
44
  welcomeManager;
44
- constructor(config, agentAid, channelName) {
45
+ constructor(config, agentAid, channelName, lifecycle) {
45
46
  this.agentAid = agentAid;
46
47
  this.channelName = channelName;
48
+ this.lifecycle = lifecycle;
47
49
  this.config = config;
48
50
  // 初始化 welcomeManager(使用共享帮助函数)
49
51
  if (agentAid && channelName) {
@@ -70,7 +72,7 @@ export class QQBotChannel {
70
72
  throw new Error('QQBot appId/clientSecret not configured');
71
73
  }
72
74
  const { QQBotClient } = await requireOptional('pure-qqbot');
73
- this.client = new QQBotClient({
75
+ const client = new QQBotClient({
74
76
  appId,
75
77
  clientSecret,
76
78
  typingKeepAlive: true,
@@ -80,38 +82,96 @@ export class QQBotChannel {
80
82
  debug: (msg) => logger.debug(`[QQBot/SDK] ${msg}`),
81
83
  },
82
84
  });
83
- this.client.onMessage(async (event) => {
85
+ this.client = client;
86
+ client.onMessage(async (event) => {
87
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== 'active'))
88
+ return;
84
89
  await this.handleIncoming(event);
85
90
  });
86
- await this.client.start();
87
- this.client.startBackgroundRefresh();
91
+ try {
92
+ await client.start();
93
+ }
94
+ catch (error) {
95
+ if (this.client === client) {
96
+ this.client = null;
97
+ this.connected = false;
98
+ }
99
+ try {
100
+ client.stopBackgroundRefresh();
101
+ }
102
+ catch (stopError) {
103
+ logger.warn('[QQBot] Failed to stop refresh after connect error:', stopError);
104
+ }
105
+ try {
106
+ client.stop();
107
+ }
108
+ catch (stopError) {
109
+ logger.warn('[QQBot] Failed to stop client after connect error:', stopError);
110
+ }
111
+ throw error;
112
+ }
113
+ if (this.client !== client || (this.lifecycle && this.lifecycle.state !== 'active')) {
114
+ try {
115
+ client.stopBackgroundRefresh();
116
+ }
117
+ catch (error) {
118
+ logger.warn('[QQBot] Failed to stop superseded refresh:', error);
119
+ }
120
+ try {
121
+ client.stop();
122
+ }
123
+ catch (error) {
124
+ logger.warn('[QQBot] Failed to stop superseded client:', error);
125
+ }
126
+ return;
127
+ }
128
+ client.startBackgroundRefresh();
88
129
  this.connected = true;
89
130
  // Hourly cleanup of old dedup entries
90
- this.cleanupInterval = setInterval(() => {
91
- const cutoff = Date.now() - 24 * 60 * 60 * 1000;
92
- for (const [id, ts] of this.seenMessages) {
93
- if (ts < cutoff)
94
- this.seenMessages.delete(id);
95
- }
96
- }, 60 * 60 * 1000);
131
+ this.startCleanupTask();
97
132
  logger.info('[QQBot] Connected via WebSocket Gateway v2');
98
133
  }
99
134
  async disconnect() {
100
135
  this.connected = false;
101
136
  if (this.cleanupInterval) {
102
- clearInterval(this.cleanupInterval);
137
+ if (this.lifecycle)
138
+ await this.lifecycle.clearInterval(this.cleanupInterval);
139
+ else
140
+ clearInterval(this.cleanupInterval);
103
141
  this.cleanupInterval = null;
104
142
  }
105
- if (this.client) {
143
+ const client = this.client;
144
+ this.client = null;
145
+ if (client) {
106
146
  try {
107
- this.client.stopBackgroundRefresh();
108
- this.client.stop();
147
+ client.stopBackgroundRefresh();
148
+ }
149
+ catch (error) {
150
+ logger.warn('[QQBot] Failed to stop background refresh:', error);
151
+ }
152
+ try {
153
+ client.stop();
154
+ }
155
+ catch (error) {
156
+ logger.warn('[QQBot] Failed to stop client:', error);
109
157
  }
110
- catch { /* ignore */ }
111
- this.client = null;
112
158
  }
113
159
  logger.info('[QQBot] Disconnected');
114
160
  }
161
+ startCleanupTask() {
162
+ if (this.cleanupInterval)
163
+ return;
164
+ const cleanup = () => {
165
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
166
+ for (const [id, ts] of this.seenMessages) {
167
+ if (ts < cutoff)
168
+ this.seenMessages.delete(id);
169
+ }
170
+ };
171
+ this.cleanupInterval = this.lifecycle
172
+ ? this.lifecycle.setInterval(cleanup, 60 * 60 * 1000)
173
+ : setInterval(cleanup, 60 * 60 * 1000);
174
+ }
115
175
  getStatus() {
116
176
  return { connected: this.connected };
117
177
  }
@@ -344,6 +404,11 @@ function isValidCredential(value) {
344
404
  }
345
405
  export class QQBotChannelPlugin {
346
406
  name = 'qqbot';
407
+ contactBind = {
408
+ displayName: 'QQ',
409
+ register: registerPendingQQBotContactBind,
410
+ handle: handlePendingQQBotContactBindMessage,
411
+ };
347
412
  async createInstance(inst, ctx) {
348
413
  if (inst.enabled === false)
349
414
  return null;
@@ -352,7 +417,7 @@ export class QQBotChannelPlugin {
352
417
  const channel = new QQBotChannel({
353
418
  appId: inst.appId,
354
419
  clientSecret: inst.clientSecret,
355
- }, ctx.agentName, inst.name);
420
+ }, ctx.agentName, inst.name, ctx.lifecycle);
356
421
  const mode = resolveShowActivities(inst);
357
422
  const adapter = {
358
423
  channelName: inst.name,
@@ -203,6 +203,7 @@ function extractTextFromMessage(msg) {
203
203
  export class WechatChannel {
204
204
  agentAid;
205
205
  channelName;
206
+ lifecycle;
206
207
  config;
207
208
  messageHandler;
208
209
  recallHandler;
@@ -212,6 +213,8 @@ export class WechatChannel {
212
213
  lastError;
213
214
  reauthRequiredAt;
214
215
  inflightHandlers = new Set();
216
+ lifecycleAbortHandler;
217
+ connectionGeneration = 0;
215
218
  // 内部状态(不外泄到核心层)
216
219
  contextTokenCache = new Map();
217
220
  rejectedContextTokens = new Map();
@@ -227,9 +230,10 @@ export class WechatChannel {
227
230
  projectPathResolver;
228
231
  // Welcome message manager
229
232
  welcomeManager;
230
- constructor(config, agentAid, channelName) {
233
+ constructor(config, agentAid, channelName, lifecycle) {
231
234
  this.agentAid = agentAid;
232
235
  this.channelName = channelName;
236
+ this.lifecycle = lifecycle;
233
237
  this.config = config;
234
238
  const stateKey = channelName || `wechat#${agentAid || '_unknown'}#main`;
235
239
  this.syncBufPath = channelStatePath(stateKey, 'sync-buffer.txt');
@@ -259,6 +263,9 @@ export class WechatChannel {
259
263
  return this.connectionState === 'reauth_required';
260
264
  }
261
265
  async connect() {
266
+ if (this.connected)
267
+ return;
268
+ const generation = ++this.connectionGeneration;
262
269
  if (!this.config.token) {
263
270
  throw new Error('WeChat token not configured');
264
271
  }
@@ -285,19 +292,44 @@ export class WechatChannel {
285
292
  logger.warn(`[WeChat] Failed to restore sync cursor; starting from an empty cursor: ${err instanceof Error ? err.message : String(err)}`);
286
293
  this.getUpdatesBuf = '';
287
294
  }
295
+ const controller = new AbortController();
296
+ this.abortController = controller;
297
+ const lifecycleAbortHandler = () => {
298
+ this.connectionGeneration++;
299
+ this.connected = false;
300
+ if (this.connectionState !== 'reauth_required')
301
+ this.connectionState = 'disconnected';
302
+ if (this.abortController === controller)
303
+ this.abortController = undefined;
304
+ this.lifecycleAbortHandler = undefined;
305
+ controller.abort();
306
+ };
307
+ this.lifecycleAbortHandler = lifecycleAbortHandler;
308
+ if (this.lifecycle?.signal.aborted)
309
+ controller.abort();
310
+ else
311
+ this.lifecycle?.signal.addEventListener('abort', lifecycleAbortHandler, { once: true });
312
+ if (controller.signal.aborted) {
313
+ this.abortController = undefined;
314
+ this.lifecycleAbortHandler = undefined;
315
+ return;
316
+ }
288
317
  // 通知 ilink 后端:bot 上线
289
318
  try {
290
- await this.notifyLifecycle('notifystart');
319
+ await this.notifyLifecycle('notifystart', controller.signal);
291
320
  }
292
321
  catch (err) {
322
+ if (controller.signal.aborted || generation !== this.connectionGeneration)
323
+ return;
293
324
  if (this.isSessionPaused())
294
325
  throw err;
295
326
  logger.warn('[WeChat] notifyStart failed during startup (ignored):', err);
296
327
  }
297
- this.abortController = new AbortController();
328
+ if (controller.signal.aborted || generation !== this.connectionGeneration)
329
+ return;
298
330
  // 启动长轮询(不 await,后台运行)
299
- this.pollLoop(this.abortController.signal).catch(err => {
300
- if (this.abortController?.signal.aborted)
331
+ this.pollLoop(controller.signal).catch(err => {
332
+ if (controller.signal.aborted || generation !== this.connectionGeneration)
301
333
  return;
302
334
  logger.error('[WeChat] Poll loop fatal error:', err);
303
335
  this.connected = false;
@@ -312,11 +344,16 @@ export class WechatChannel {
312
344
  logger.info('[WeChat] Channel connected');
313
345
  }
314
346
  async disconnect() {
347
+ this.connectionGeneration++;
315
348
  this.connected = false;
316
349
  if (this.abortController) {
317
350
  this.abortController.abort();
318
351
  this.abortController = undefined;
319
352
  }
353
+ if (this.lifecycleAbortHandler) {
354
+ this.lifecycle?.signal.removeEventListener('abort', this.lifecycleAbortHandler);
355
+ this.lifecycleAbortHandler = undefined;
356
+ }
320
357
  const reauthRequired = this.connectionState === 'reauth_required';
321
358
  if (!reauthRequired)
322
359
  this.connectionState = 'disconnected';
@@ -798,9 +835,9 @@ export class WechatChannel {
798
835
  }
799
836
  // ── ilink API Helpers ─────────────────────────────────────────────────
800
837
  /** Notify ilink backend of bot lifecycle events (start/stop). */
801
- async notifyLifecycle(action) {
838
+ async notifyLifecycle(action, signal) {
802
839
  const body = JSON.stringify({ base_info: buildBaseInfo() });
803
- await this.apiRequest(`ilink/bot/msg/${action}`, body, DEFAULT_CONFIG_TIMEOUT_MS);
840
+ await this.apiRequest(`ilink/bot/msg/${action}`, body, DEFAULT_CONFIG_TIMEOUT_MS, signal);
804
841
  logger.info(`[WeChat] ${action} succeeded`);
805
842
  }
806
843
  async apiRequest(endpoint, body, timeoutMs, externalSignal) {
@@ -834,14 +871,10 @@ export class WechatChannel {
834
871
  const headers = this.buildHeaders();
835
872
  const controller = new AbortController();
836
873
  const timer = setTimeout(() => controller.abort(), timeoutMs);
874
+ timer.unref?.();
837
875
  // 外部 signal(来自 disconnect)也要能中断
838
876
  const onExternalAbort = () => controller.abort();
839
- if (externalSignal?.aborted) {
840
- controller.abort();
841
- }
842
- else {
843
- externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
844
- }
877
+ const removeAbortListener = listenForAbort(externalSignal, onExternalAbort);
845
878
  try {
846
879
  const res = await fetch(url, {
847
880
  method: 'POST',
@@ -862,7 +895,7 @@ export class WechatChannel {
862
895
  }
863
896
  finally {
864
897
  clearTimeout(timer);
865
- externalSignal?.removeEventListener('abort', onExternalAbort);
898
+ removeAbortListener();
866
899
  }
867
900
  }
868
901
  buildHeaders() {
@@ -937,24 +970,49 @@ export class WechatChannel {
937
970
  reject(new Error('aborted'));
938
971
  return;
939
972
  }
940
- const t = setTimeout(resolve, ms);
941
- signal.addEventListener('abort', () => {
942
- clearTimeout(t);
973
+ let timer;
974
+ const cleanup = () => signal.removeEventListener('abort', onAbort);
975
+ const onAbort = () => {
976
+ clearTimeout(timer);
977
+ cleanup();
943
978
  reject(new Error('aborted'));
944
- }, { once: true });
979
+ };
980
+ timer = setTimeout(() => {
981
+ cleanup();
982
+ resolve();
983
+ }, ms);
984
+ signal.addEventListener('abort', onAbort, { once: true });
985
+ if (signal.aborted) {
986
+ onAbort();
987
+ }
945
988
  });
946
989
  }
947
990
  }
991
+ function listenForAbort(signal, listener) {
992
+ if (!signal)
993
+ return () => { };
994
+ if (signal.aborted) {
995
+ listener();
996
+ return () => { };
997
+ }
998
+ signal.addEventListener('abort', listener, { once: true });
999
+ return () => signal.removeEventListener('abort', listener);
1000
+ }
948
1001
  import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
949
1002
  export class WechatChannelPlugin {
950
1003
  name = 'wechat';
1004
+ contactBind = {
1005
+ displayName: '微信',
1006
+ register: registerPendingWechatContactBind,
1007
+ handle: handlePendingWechatContactBindMessage,
1008
+ };
951
1009
  async createInstance(inst, ctx) {
952
1010
  if (inst.enabled === false || !inst.token)
953
1011
  return null;
954
1012
  const channel = new WechatChannel({
955
1013
  baseUrl: inst.baseUrl || 'https://ilinkai.weixin.qq.com',
956
1014
  token: inst.token,
957
- }, ctx.agentName, inst.name);
1015
+ }, ctx.agentName, inst.name, ctx.lifecycle);
958
1016
  const mode = resolveShowActivities(inst);
959
1017
  const adapter = {
960
1018
  channelName: inst.name,
@@ -481,6 +481,7 @@ export async function pollWecomQrCredentials(scode, opts) {
481
481
  export class WecomChannel {
482
482
  agentAid;
483
483
  channelName;
484
+ lifecycle;
484
485
  config;
485
486
  client = null;
486
487
  connectionState = 'idle';
@@ -497,12 +498,15 @@ export class WecomChannel {
497
498
  cardCallbacksInFlight = new Set();
498
499
  interactionSendTails = new Map();
499
500
  connectPromise;
501
+ cancelAuthenticationWait;
502
+ clientListeners = new Map();
500
503
  activeStreams = new Map();
501
504
  // Welcome message manager
502
505
  welcomeManager;
503
- constructor(config, agentAid, channelName) {
506
+ constructor(config, agentAid, channelName, lifecycle) {
504
507
  this.agentAid = agentAid;
505
508
  this.channelName = channelName;
509
+ this.lifecycle = lifecycle;
506
510
  this.config = config;
507
511
  this.channelKey = channelName || `wecom#${agentAid || 'standalone'}#main`;
508
512
  this.cardStore = new PersistentWecomCardStore(undefined, this.channelKey);
@@ -570,7 +574,7 @@ export class WecomChannel {
570
574
  });
571
575
  this.client = client;
572
576
  // Message events
573
- client.on('message', (frame) => {
577
+ this.listenClient(client, 'message', (frame) => {
574
578
  if (this.client !== client)
575
579
  return;
576
580
  this.handleIncoming(frame).catch((err) => {
@@ -578,7 +582,7 @@ export class WecomChannel {
578
582
  });
579
583
  });
580
584
  // Event callbacks (enter_chat, etc.)
581
- client.on('event.enter_chat', (frame) => {
585
+ this.listenClient(client, 'event.enter_chat', (frame) => {
582
586
  if (this.client !== client)
583
587
  return;
584
588
  const body = frame?.body;
@@ -587,14 +591,14 @@ export class WecomChannel {
587
591
  }
588
592
  });
589
593
  // Lifecycle events
590
- client.on('authenticated', () => {
594
+ this.listenClient(client, 'authenticated', () => {
591
595
  if (this.client !== client)
592
596
  return;
593
597
  this.connectionState = 'authenticated';
594
598
  this.lastConnectionError = undefined;
595
599
  logger.info('[WeCom] WebSocket authenticated');
596
600
  });
597
- client.on('disconnected', (reason) => {
601
+ this.listenClient(client, 'disconnected', (reason) => {
598
602
  if (this.client !== client)
599
603
  return;
600
604
  logger.warn(`[WeCom] WebSocket disconnected: ${reason}`);
@@ -603,14 +607,14 @@ export class WecomChannel {
603
607
  this.lastConnectionError = reason;
604
608
  this.expireActiveStreams();
605
609
  });
606
- client.on('reconnecting', (attempt) => {
610
+ this.listenClient(client, 'reconnecting', (attempt) => {
607
611
  if (this.client !== client)
608
612
  return;
609
613
  this.connectionState = 'reconnecting';
610
614
  this.expireActiveStreams();
611
615
  logger.info(`[WeCom] Reconnecting (attempt ${attempt})...`);
612
616
  });
613
- client.on('error', (error) => {
617
+ this.listenClient(client, 'error', (error) => {
614
618
  if (this.client !== client)
615
619
  return;
616
620
  this.lastConnectionError = error.message;
@@ -620,14 +624,14 @@ export class WecomChannel {
620
624
  this.connectionState = 'disconnected';
621
625
  logger.error('[WeCom] WebSocket error:', error);
622
626
  });
623
- client.on('event.template_card_event', (frame) => {
627
+ this.listenClient(client, 'event.template_card_event', (frame) => {
624
628
  if (this.client !== client)
625
629
  return;
626
630
  this.handleTemplateCardEvent(frame).catch(error => {
627
631
  logger.error('[WeCom] Failed to process template card event:', error);
628
632
  });
629
633
  });
630
- client.on('event.disconnected_event', () => {
634
+ this.listenClient(client, 'event.disconnected_event', () => {
631
635
  if (this.client !== client)
632
636
  return;
633
637
  this.connectionState = 'kicked';
@@ -635,18 +639,21 @@ export class WecomChannel {
635
639
  this.expireActiveStreams();
636
640
  logger.error(`[WeCom] Connection kicked for channel ${this.channelKey}; another client is using this Bot ID`);
637
641
  });
638
- client.connect();
639
642
  try {
643
+ client.connect();
640
644
  await this.waitForAuthentication(client, 20_000);
641
645
  }
642
646
  catch (error) {
643
647
  const wasCurrentClient = this.client === client;
644
648
  if (wasCurrentClient)
645
649
  this.client = null;
650
+ this.removeClientListeners(client);
646
651
  try {
647
652
  client.disconnect();
648
653
  }
649
- catch { /* ignore */ }
654
+ catch (disconnectError) {
655
+ logger.warn('[WeCom] Failed to disconnect after connection error:', disconnectError);
656
+ }
650
657
  if (wasCurrentClient) {
651
658
  const failedState = this.connectionState;
652
659
  if (failedState !== 'auth_failed')
@@ -656,33 +663,62 @@ export class WecomChannel {
656
663
  throw error;
657
664
  }
658
665
  // Hourly cleanup of old dedup entries
659
- this.cleanupInterval = setInterval(() => {
660
- const cutoff = Date.now() - 24 * 60 * 60 * 1000;
661
- for (const [id, ts] of this.seenMessages) {
662
- if (ts < cutoff)
663
- this.seenMessages.delete(id);
664
- }
665
- this.cleanupStreams();
666
- }, 60 * 60 * 1000);
666
+ this.startCleanupTask();
667
667
  logger.info('[WeCom] Channel connected');
668
668
  }
669
669
  async disconnect() {
670
670
  this.connectionState = 'idle';
671
+ this.cancelAuthenticationWait?.(new Error('WeCom connection cancelled'));
671
672
  if (this.cleanupInterval) {
672
- clearInterval(this.cleanupInterval);
673
+ if (this.lifecycle)
674
+ await this.lifecycle.clearInterval(this.cleanupInterval);
675
+ else
676
+ clearInterval(this.cleanupInterval);
673
677
  this.cleanupInterval = null;
674
678
  }
675
679
  const client = this.client;
676
680
  this.client = null;
677
681
  if (client) {
682
+ this.removeClientListeners(client);
678
683
  try {
679
684
  client.disconnect();
680
685
  }
681
- catch { /* ignore */ }
686
+ catch (error) {
687
+ logger.warn('[WeCom] Failed to disconnect client:', error);
688
+ }
682
689
  }
683
690
  this.activeStreams.clear();
684
691
  logger.info('[WeCom] Channel disconnected');
685
692
  }
693
+ startCleanupTask() {
694
+ if (this.cleanupInterval)
695
+ return;
696
+ const cleanup = () => {
697
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
698
+ for (const [id, ts] of this.seenMessages) {
699
+ if (ts < cutoff)
700
+ this.seenMessages.delete(id);
701
+ }
702
+ this.cleanupStreams();
703
+ };
704
+ this.cleanupInterval = this.lifecycle
705
+ ? this.lifecycle.setInterval(cleanup, 60 * 60 * 1000)
706
+ : setInterval(cleanup, 60 * 60 * 1000);
707
+ }
708
+ listenClient(client, event, listener) {
709
+ client.on(event, listener);
710
+ const listeners = this.clientListeners.get(client) ?? [];
711
+ listeners.push({ event, listener });
712
+ this.clientListeners.set(client, listeners);
713
+ }
714
+ removeClientListeners(client) {
715
+ const listeners = this.clientListeners.get(client);
716
+ if (!listeners)
717
+ return;
718
+ this.clientListeners.delete(client);
719
+ for (const { event, listener } of listeners)
720
+ client.off(event, listener);
721
+ }
686
722
  onMessage(handler) {
687
723
  this.messageHandler = handler;
688
724
  }
@@ -756,11 +792,14 @@ export class WecomChannel {
756
792
  client.off('authenticated', onAuthenticated);
757
793
  client.off('error', onError);
758
794
  client.off('disconnected', onDisconnected);
795
+ if (this.cancelAuthenticationWait === cancel)
796
+ this.cancelAuthenticationWait = undefined;
759
797
  if (error)
760
798
  reject(error);
761
799
  else
762
800
  resolve();
763
801
  };
802
+ const cancel = (error) => finish(error);
764
803
  const onAuthenticated = () => finish();
765
804
  const onError = (error) => {
766
805
  if (isWecomAuthError(error))
@@ -773,6 +812,7 @@ export class WecomChannel {
773
812
  client.on('authenticated', onAuthenticated);
774
813
  client.on('error', onError);
775
814
  client.on('disconnected', onDisconnected);
815
+ this.cancelAuthenticationWait = cancel;
776
816
  if (this.connectionState === 'authenticated')
777
817
  finish();
778
818
  });
@@ -1414,6 +1454,11 @@ function isValidCredential(value) {
1414
1454
  }
1415
1455
  export class WecomChannelPlugin {
1416
1456
  name = 'wecom';
1457
+ contactBind = {
1458
+ displayName: '企微',
1459
+ register: registerPendingWecomContactBind,
1460
+ handle: handlePendingWecomContactBindMessage,
1461
+ };
1417
1462
  async createInstance(inst, ctx) {
1418
1463
  if (inst.enabled === false)
1419
1464
  return null;
@@ -1422,7 +1467,7 @@ export class WecomChannelPlugin {
1422
1467
  const channel = new WecomChannel({
1423
1468
  botId: inst.botId,
1424
1469
  secret: inst.secret,
1425
- }, ctx.agentName, inst.name);
1470
+ }, ctx.agentName, inst.name, ctx.lifecycle);
1426
1471
  const mode = resolveShowActivities(inst);
1427
1472
  const adapter = {
1428
1473
  channelName: inst.name,
@@ -0,0 +1,92 @@
1
+ import { resolvePaths } from '../paths.js';
2
+ import { ipcQuery } from '../ipc.js';
3
+ import { readDelegationCredential, hashCurrentDelegatedCommand } from '../core/auth/agent-delegation.js';
4
+ import { wantsHelp } from './help.js';
5
+ import { ABILITY_COMMANDS, ABILITY_DEV_COMMANDS, parseAbilityOptions, parseAbilityWait, abilityCommandSchema } from '../ability/command-contract.js';
6
+ import { abilityFailure } from '../ability/management.js';
7
+ import { abilityAssert } from '../ability/types.js';
8
+ export async function queryAbilityWithWait(args, query) {
9
+ const descriptor = ABILITY_COMMANDS[args[0]];
10
+ abilityAssert(descriptor, 'ACTION_UNSUPPORTED', 'Unknown ability command');
11
+ const { values } = parseAbilityOptions(args.slice(1), descriptor);
12
+ const wait = values.wait ?? values['wait-publication'];
13
+ const waitMs = wait ? parseAbilityWait(wait) : undefined;
14
+ const started = performance.now();
15
+ let last;
16
+ const deadline = () => ({ response: { ...last, wait: { timedOut: true, waitedMs: Math.round(performance.now() - started) } }, exitCode: 1 });
17
+ for (;;) {
18
+ if (waitMs && last && performance.now() - started >= waitMs)
19
+ return deadline();
20
+ const queried = await query(waitMs ? Math.max(1, Math.ceil(waitMs - (performance.now() - started))) : 120_000);
21
+ if (!queried && waitMs && last && performance.now() - started >= waitMs)
22
+ return deadline();
23
+ const response = queried ?? { ok: false, status: 503, code: 'DAEMON_UNAVAILABLE', error: 'Ability daemon unavailable' };
24
+ if (response.ok === false || !waitMs)
25
+ return { response, exitCode: response.ok === false ? 1 : 0 };
26
+ if (args[0] === 'job' && !response.data)
27
+ return { response: { ok: false, status: 404, code: 'JOB_NOT_FOUND', error: 'No job found for this actor and target' }, exitCode: 1 };
28
+ const finished = args[0] === 'job' ? response.data.state !== 'running' : response.data?.publicationConverged === true;
29
+ const waitedMs = Math.round(performance.now() - started);
30
+ if (finished || waitedMs >= waitMs)
31
+ return { response: { ...response, wait: { timedOut: !finished, waitedMs } },
32
+ exitCode: !finished || args[0] === 'job' && response.data.state !== 'completed' ? 1 : 0 };
33
+ last = response;
34
+ await new Promise(resolve => setTimeout(resolve, Math.min(500, waitMs - waitedMs)));
35
+ }
36
+ }
37
+ export async function cmdAbility(args) {
38
+ if (!args.length || wantsHelp(args)) {
39
+ const dev = args[0] === 'dev';
40
+ console.log(dev ? '用法: ec ability dev <命令> [位置参数] [--project <目录>] [--format json]' : '用法: ec ability <命令> [实例或来源] (--aid <AID> | --self) [--file <JSON>] [--format json]');
41
+ for (const [name, command] of Object.entries(dev ? ABILITY_DEV_COMMANDS : ABILITY_COMMANDS)) {
42
+ if (name === 'secret')
43
+ continue;
44
+ const signature = name + (command.positional === 'required' ? ' <参数>' : command.positional === 'optional' ? ' [参数]' : '');
45
+ console.log(' ' + signature.padEnd(24) + command.description + (command.options?.length ? ' ' + command.options.join(' ') : ''));
46
+ }
47
+ if (!dev)
48
+ console.log('\n dev 本地 init/add-ability/remove-ability/doctor/check/build/pack/version;详见 dev --help\n\n写入需 commandId;实例修改需 expectedRevision。提交成功后查询 job,不代表执行完成。\njob --wait 30s / status --wait-publication 30s:仅轮询查询,最多 60s。\n--self 由 daemon 的可信会话解析,不授予额外权限。\nAgent 修改仍需当前实际 Owner;执行新代码还需宿主批准。\n秘密仅用 secrets <实例> --slot <槽> --revision <N> --command-id <ID> --stdin。');
49
+ return;
50
+ }
51
+ try {
52
+ if (args[0] === 'dev') {
53
+ const { executeAbilityDevelopment } = await import('../ability/development.js');
54
+ const data = executeAbilityDevelopment(args.slice(1));
55
+ console.log(JSON.stringify({ ok: true, data }, null, 2));
56
+ if (args[1] === 'doctor' && data && 'available' in data && data.available === false)
57
+ process.exitCode = 1;
58
+ return;
59
+ }
60
+ if (args[0] === 'schema') {
61
+ const { positional } = parseAbilityOptions(args.slice(1), ABILITY_COMMANDS.schema);
62
+ console.log(JSON.stringify({ ok: true, data: abilityCommandSchema(positional[0]) }, null, 2));
63
+ return;
64
+ }
65
+ abilityAssert(Object.hasOwn(ABILITY_COMMANDS, args[0]), 'ACTION_UNSUPPORTED', 'Unknown ability command');
66
+ parseAbilityOptions(args.slice(1), ABILITY_COMMANDS[args[0]]);
67
+ let stdinSecret;
68
+ if (args.includes('--stdin')) {
69
+ abilityAssert(!process.stdin.isTTY, 'SECRET_STDIN_REQUIRED', 'Secrets require non-interactive standard input');
70
+ const chunks = [];
71
+ let size = 0;
72
+ for await (const chunk of process.stdin) {
73
+ const bytes = Buffer.from(chunk);
74
+ size += bytes.length;
75
+ abilityAssert(size <= 16386, 'SECRET_INVALID', 'Secret exceeds 16 KiB');
76
+ chunks.push(bytes);
77
+ }
78
+ stdinSecret = Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, '');
79
+ }
80
+ const command = { type: 'ability.op', argv: ['ability', ...args], sessionId: process.env.EVOLCORE_SESSION_ID,
81
+ ...(stdinSecret === undefined ? {} : { stdinSecret }),
82
+ delegationToken: readDelegationCredential(), delegationCommandHash: hashCurrentDelegatedCommand() };
83
+ const result = await queryAbilityWithWait(args, timeout => ipcQuery(resolvePaths().socket, command, timeout));
84
+ console.log(JSON.stringify(result.response, null, 2));
85
+ if (result.exitCode)
86
+ process.exitCode = result.exitCode;
87
+ }
88
+ catch (error) {
89
+ console.log(JSON.stringify(abilityFailure(error), null, 2));
90
+ process.exitCode = 1;
91
+ }
92
+ }