evolcore 0.0.43-test.8 → 0.0.46

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 (204) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +13 -5
  12. package/dist/agents/codex/app-server-client.js +2 -4
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/menu/client.js +142 -182
  18. package/dist/aun/rpc/client.js +33 -17
  19. package/dist/aun/service-proxy.js +6 -23
  20. package/dist/channels/aun.js +656 -112
  21. package/dist/cli/agent-create.js +37 -10
  22. package/dist/cli/agent-template.js +105 -84
  23. package/dist/cli/agent.js +31 -18
  24. package/dist/cli/daemon-commands.js +15 -17
  25. package/dist/cli/daemon-lifecycle-client.js +40 -18
  26. package/dist/cli/directory.js +12 -4
  27. package/dist/cli/ecmsg-gateway.js +5 -2
  28. package/dist/cli/events-command.js +2 -1
  29. package/dist/cli/init.js +50 -20
  30. package/dist/cli/integrity-command.js +2 -0
  31. package/dist/cli/managed-command-guard.js +20 -1
  32. package/dist/cli/menu-client.js +7 -5
  33. package/dist/cli/restart-monitor.js +33 -20
  34. package/dist/cli/services-command.js +28 -5
  35. package/dist/config/config-field-policy.js +24 -0
  36. package/dist/config/config-manager.js +20 -2
  37. package/dist/config/peer-book-store.js +152 -120
  38. package/dist/config/peer-role-resolver.js +24 -4
  39. package/dist/config/provider-identity-migration.js +1 -1
  40. package/dist/config/provider-identity.js +10 -4
  41. package/dist/config/provider-ipc-service.js +10 -2
  42. package/dist/config/provider-local-sync.js +2 -2
  43. package/dist/config/providers-config.js +95 -10
  44. package/dist/config/providers-import.js +4 -6
  45. package/dist/config/providers.js +14 -3
  46. package/dist/config/role-store.js +1 -1
  47. package/dist/config-store.js +9 -1
  48. package/dist/core/agent-application-service.js +56 -29
  49. package/dist/core/agent-create-status.js +3 -1
  50. package/dist/core/agent-creation-claim.js +1 -0
  51. package/dist/core/agent-ipc-registration.js +2 -2
  52. package/dist/core/agent-reload-coordinator.js +38 -1
  53. package/dist/core/agent-runtime.js +85 -38
  54. package/dist/core/auth/agent-delegation.js +5 -0
  55. package/dist/core/auth/operation-authorizer.js +1 -1
  56. package/dist/core/auth/operation-catalog.js +3 -3
  57. package/dist/core/bootstrap-service.js +3 -0
  58. package/dist/core/capability/capability-manager.js +3 -1
  59. package/dist/core/channel-loader.js +29 -3
  60. package/dist/core/channel-runtime.js +1 -1
  61. package/dist/core/command/agent-control.js +6 -5
  62. package/dist/core/command/agent-template-menu.js +32 -97
  63. package/dist/core/command/eventcenter-menu.js +61 -13
  64. package/dist/core/command/menu-catalog.js +11 -4
  65. package/dist/core/command/menu-handler.js +35 -8
  66. package/dist/core/command/menu-protocol.js +8 -16
  67. package/dist/core/command/skill-slash.js +6 -2
  68. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  69. package/dist/core/command/team-workspace-management-store.js +83 -0
  70. package/dist/core/command/team-workspace-management.js +1 -2
  71. package/dist/core/command/team-workspace-team.js +26 -3
  72. package/dist/core/daemon-control.js +3 -4
  73. package/dist/core/daemon-lifecycle.js +146 -110
  74. package/dist/core/evolagent-registry.js +42 -0
  75. package/dist/core/evolagent.js +2 -1
  76. package/dist/core/file-integrity/read.js +9 -16
  77. package/dist/core/file-integrity/store.js +94 -34
  78. package/dist/core/handoff/dispatcher.js +33 -7
  79. package/dist/core/handoff/runtime.js +8 -0
  80. package/dist/core/inference/text-inference.js +12 -2
  81. package/dist/core/invoke/invoke-service.js +24 -3
  82. package/dist/core/ipc-registration.js +3 -0
  83. package/dist/core/message/aun-ipc-sender.js +109 -7
  84. package/dist/core/message/contact-admission.js +6 -2
  85. package/dist/core/message/message-bridge.js +13 -0
  86. package/dist/core/message/message-queue.js +131 -30
  87. package/dist/core/message/pending-hints.js +8 -0
  88. package/dist/core/message/response-engine.js +48 -2
  89. package/dist/core/message/send-routing.js +3 -12
  90. package/dist/core/model/catalog-service.js +13 -0
  91. package/dist/core/model/model-catalog.js +57 -18
  92. package/dist/core/pack-auth.js +163 -31
  93. package/dist/core/pack-install.js +42 -1
  94. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  95. package/dist/core/permission/ec-command-parser.js +3 -1
  96. package/dist/core/permission/shell-environment.js +23 -0
  97. package/dist/core/rate-window.js +6 -1
  98. package/dist/core/session/session-idle-monitor.js +0 -1
  99. package/dist/core/session/session-manager.js +14 -0
  100. package/dist/core/session/session-title.js +26 -6
  101. package/dist/core/skill/index-generator.js +3 -4
  102. package/dist/core/thread/thread-service.js +0 -1
  103. package/dist/core/thread/topic-id.js +8 -0
  104. package/dist/directory/owner-directory-admission.js +17 -0
  105. package/dist/directory/owner-directory-cache.js +3 -1
  106. package/dist/directory/owner-directory-markdown.js +145 -23
  107. package/dist/directory/owner-directory-policy.js +23 -0
  108. package/dist/directory/owner-directory-query-operation.js +20 -6
  109. package/dist/directory/owner-directory-search.js +47 -0
  110. package/dist/eck/message-renderer.js +171 -32
  111. package/dist/ecweb/basic-settings-service.js +7 -3
  112. package/dist/ecweb/providers-service.js +17 -10
  113. package/dist/ecweb/runtime/lifecycle.js +1 -1
  114. package/dist/ecweb/runtime/supervisor.js +77 -35
  115. package/dist/event-center/admission-materializer.js +1 -1
  116. package/dist/event-center/bus-gate.js +48 -4
  117. package/dist/event-center/bus-host.js +3 -3
  118. package/dist/event-center/center-config.js +57 -28
  119. package/dist/event-center/dispatcher.js +8 -0
  120. package/dist/event-center/event-log.js +69 -27
  121. package/dist/event-center/index-generator.js +6 -1
  122. package/dist/event-center/ipc-operation.js +66 -25
  123. package/dist/event-center/pack-loader.js +12 -55
  124. package/dist/event-center/pack-manager.js +5 -3
  125. package/dist/event-center/registry.js +48 -52
  126. package/dist/event-center/runtime.js +219 -81
  127. package/dist/event-center/script-runner.js +18 -7
  128. package/dist/event-center/types.js +9 -1
  129. package/dist/event-center/validation.js +33 -4
  130. package/dist/index.js +96 -42
  131. package/dist/ipc.js +33 -7
  132. package/dist/product.js +1 -0
  133. package/dist/proxy/manager.js +52 -11
  134. package/dist/proxy/service-supervisor.js +265 -67
  135. package/dist/services/dispatcher.js +26 -3
  136. package/dist/services/idempotency.js +128 -0
  137. package/dist/services/identity.js +3 -27
  138. package/dist/services/index-generator.js +5 -1
  139. package/dist/services/index.js +244 -45
  140. package/dist/services/ipc-operation.js +164 -20
  141. package/dist/services/pack-manager.js +37 -9
  142. package/dist/services/router.js +100 -31
  143. package/dist/services/script-runner.js +15 -4
  144. package/dist/services/service-payload.js +50 -2
  145. package/dist/services/validation.js +107 -3
  146. package/dist/trigger/scheduler.js +14 -4
  147. package/dist/trigger/script-sandbox.js +39 -2
  148. package/dist/utils/cross-platform.js +35 -11
  149. package/dist/utils/error-utils.js +13 -1
  150. package/dist/utils/instance-registry.js +33 -35
  151. package/dist/utils/process-introspect.js +35 -20
  152. package/dist/utils/project-path.js +47 -3
  153. package/dist/utils/windows-shell-trust.js +174 -68
  154. package/kits/docs/context-assembly.md +3 -3
  155. package/kits/docs/evolcore/agent.md +28 -10
  156. package/kits/docs/evolcore/config.md +22 -0
  157. package/kits/docs/evolcore/directory.md +46 -12
  158. package/kits/docs/evolcore/event-center.md +6 -6
  159. package/kits/docs/evolcore/group-collaboration.md +1 -1
  160. package/kits/docs/evolcore/menu-client.md +7 -5
  161. package/kits/docs/evolcore/menu-protocol.md +5 -3
  162. package/kits/docs/evolcore/msg.md +10 -3
  163. package/kits/docs/evolcore/provider.md +7 -3
  164. package/kits/docs/evolcore/services.md +145 -12
  165. package/kits/docs/evolcore/thread-chain.md +17 -9
  166. package/kits/docs/prompt-loading-architecture.md +4 -4
  167. package/kits/eck_message_manifest.json +46 -3
  168. package/kits/rules/04-relation.md +10 -2
  169. package/kits/rules/06-channel.md +2 -1
  170. package/kits/schemas/providers.schema.2.json +1 -0
  171. package/kits/skills/ec-group/SKILL.md +4 -0
  172. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  173. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  174. package/kits/skills/thread-ops/SKILL.md +8 -5
  175. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  176. package/kits/templates/message-fragments/group-batch.md +1 -0
  177. package/kits/templates/message-fragments/item-group.md +4 -0
  178. package/kits/templates/message-fragments/item-private.md +4 -0
  179. package/kits/templates/message-fragments/thread-context.md +1 -1
  180. package/kits/templates/system-fragments/commands.md +5 -5
  181. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  182. package/kits/templates/system-fragments/relation.md +11 -7
  183. package/package.json +3 -2
  184. package/scripts/agent-template/index.mjs +9 -4
  185. package/scripts/agent-template/inspect.mjs +16 -9
  186. package/scripts/agent-template/shared/plan.mjs +3 -33
  187. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  188. package/scripts/agent-template/shared/template-package.mjs +119 -10
  189. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  190. package/scripts/agent-template/shared/template.mjs +5 -5
  191. package/scripts/agent-template/team-pack.mjs +245 -0
  192. package/scripts/agent-template/team-preview.mjs +111 -0
  193. package/scripts/aid-batch/identity-batch.mjs +143 -0
  194. package/dist/ability/versions.js +0 -32
  195. package/dist/aun/model-headers.js +0 -17
  196. package/dist/channels/builtin-plugins.js +0 -19
  197. package/dist/core/command/team-workspace-initializer.js +0 -2
  198. package/dist/core/command/team-workspace-job-store.js +0 -88
  199. package/dist/core/command/team-workspace-management-service.js +0 -2
  200. package/dist/core/contact-bind-registry.js +0 -27
  201. package/dist/event-center/ledger.js +0 -52
  202. package/dist/services/reply.js +0 -55
  203. package/kits/templates/message-fragments/item.md +0 -3
  204. package/scripts/agent-template/pack.mjs +0 -169
@@ -32,19 +32,18 @@ import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.
32
32
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
33
33
  import { appendAidLifecycle } from '../aun/aid/identity.js';
34
34
  import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
35
- import { classifyServicePayloadType, getServiceRouter, readLocalSelfIdentity, } from '../services/index.js';
35
+ import { classifyServicePayloadType, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
36
36
  import { agentServicesDir } from '../paths.js';
37
37
  import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
38
38
  import { loadAgent } from '../config-store.js';
39
39
  import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
40
- import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
40
+ import { resolvePeerRoleDetail, resolveSenderRelationRole } from '../config/peer-role-resolver.js';
41
41
  import { resolveAgentLifecycle } from '../config/lifecycle.js';
42
42
  import { resolveEffective } from '../config/config-manager.js';
43
43
  import { isManagementRole } from '../config/builtin-roles.js';
44
44
  import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
45
45
  import { getProcessStartTime } from '../utils/process-introspect.js';
46
46
  import * as outbox from '../aun/outbox.js';
47
- import { aunProtectedHeaders } from '../aun/model-headers.js';
48
47
  import { formatSize } from '../utils/media-cache.js';
49
48
  import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
50
49
  import { prepareSameOwnerProof, registerSameOwnerClient, unregisterSameOwnerClient } from '../core/relation/same-owner-proof.js';
@@ -71,6 +70,47 @@ const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
71
70
  const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
72
71
  const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
73
72
  const OBSERVER_GROUP_MEMBERS_TTL_MS = 60_000;
73
+ /**
74
+ * 群成员角色表缓存:角色变更极少(管理员操作),120 分钟足够;
75
+ * 入群/退群只影响该成员的 `群角色` 是否可见,不做主动失效。失败不缓存。
76
+ */
77
+ const GROUP_MEMBER_ROLES_TTL_MS = 120 * 60_000;
78
+ /** 群成员角色拉取失败后的退避时间,避免持续失败时每条消息都重试 RPC。 */
79
+ const GROUP_MEMBER_ROLES_FAILURE_TTL_MS = 60_000;
80
+ /** 解析 AUN payload 的 `sender_ctx`;结构非法或全空返回 undefined。 */
81
+ function readSenderCtx(payload) {
82
+ const raw = (payload && typeof payload === 'object')
83
+ ? (payload.sender_ctx ?? payload.senderCtx)
84
+ : undefined;
85
+ if (!raw || typeof raw !== 'object')
86
+ return undefined;
87
+ const scene = typeof raw.scene === 'string' && raw.scene.trim() ? raw.scene.trim() : undefined;
88
+ const activity = typeof raw.activity === 'string' && raw.activity.trim() ? raw.activity.trim() : undefined;
89
+ // 协议字段名尚未在真实 payload 上核对;同时接受 timezone / tz 两种写法。
90
+ const rawTz = typeof raw.timezone === 'string' ? raw.timezone : (typeof raw.tz === 'string' ? raw.tz : '');
91
+ const timezone = rawTz.trim() || undefined;
92
+ let location;
93
+ const loc = raw.location;
94
+ if (loc && typeof loc === 'object') {
95
+ const lat = Number(loc.latitude_e6);
96
+ const lon = Number(loc.longitude_e6);
97
+ if (Number.isFinite(lat) && Number.isFinite(lon)) {
98
+ location = {
99
+ latitude_e6: lat,
100
+ longitude_e6: lon,
101
+ ...(typeof loc.address === 'string' && loc.address.trim() ? { address: loc.address.trim() } : {}),
102
+ };
103
+ }
104
+ }
105
+ if (!scene && !activity && !timezone && !location)
106
+ return undefined;
107
+ return {
108
+ ...(scene ? { scene } : {}),
109
+ ...(activity ? { activity } : {}),
110
+ ...(timezone ? { timezone } : {}),
111
+ ...(location ? { location } : {}),
112
+ };
113
+ }
74
114
  const OBSERVER_GROUP_MEMBERS_PAGE_SIZE = 200;
75
115
  const OBSERVER_GROUP_MEMBERS_MAX_PAGES = 100;
76
116
  const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
@@ -230,6 +270,109 @@ export function echoInboundLegLabel(createdAt, receivedAt) {
230
270
  return '';
231
271
  return ` inbound_est=${Math.round(delta)}ms`;
232
272
  }
273
+ /**
274
+ * 判定探针前缀。最长前缀先判——`/^echo/` 会命中 `echo.ecdiag`,顺序不可颠倒。
275
+ * 只认消息文本第 0 个字符起的前缀,前面打空格或其它字符一律不认。
276
+ */
277
+ export function echoProbeKind(text) {
278
+ const first = text.split('\n', 1)[0] ?? '';
279
+ if (/^echo\.ecdiag(?=$|\s)/i.test(first))
280
+ return 'ecdiag';
281
+ if (/^echo\.ask(?=$|\s)/i.test(first))
282
+ return 'ask';
283
+ if (/^echo(?=$|[\s[])/i.test(first))
284
+ return 'echo';
285
+ return null;
286
+ }
287
+ /** 探针默认跳数预算。省略 `hop=` 时从此值起算。 */
288
+ export const ECHO_DEFAULT_HOP = 100;
289
+ /**
290
+ * echo.ecdiag 的回包等待时长(毫秒)。
291
+ *
292
+ * 到点无条件回包,把当时已经走到的阶段打包发出。等待期间 agent 若回复则提前收口。
293
+ * 这个值决定「观察窗口」有多长:太短看不到 LLM 阶段,太长则测一次要等很久。
294
+ */
295
+ export function ecdiagTimeoutMs(text) {
296
+ const declared = /\btimeout=(\d+)\b/.exec(text.split('\n', 1)[0] ?? '');
297
+ const ms = declared ? Number(declared[1]) : Number.NaN;
298
+ return Number.isFinite(ms) && ms > 0 ? ms : 20_000;
299
+ }
300
+ /** 本腿是去程还是返程:看正文最后一行 trace 的 dir,没有则按去程。 */
301
+ export function echoTraceDirection(text) {
302
+ const lines = text.split('\n');
303
+ for (let i = lines.length - 1; i >= 0; i--) {
304
+ const m = /\bdir=(fwd|ret)\b/.exec(lines[i]);
305
+ if (m)
306
+ return m[1];
307
+ }
308
+ return 'fwd';
309
+ }
310
+ /**
311
+ * 下一跳的值 = 正文最后一行 trace 的 hop − 1。
312
+ * 正文还没有 trace 行时,回落到首行 `hop=<N>` 参数;都没有则用默认值。
313
+ * 去程返程共用这一个计数器,不重置。
314
+ */
315
+ export function echoTraceNextHop(text) {
316
+ const lines = text.split('\n');
317
+ for (let i = lines.length - 1; i >= 0; i--) {
318
+ const m = /\bhop=(\d+)\b/.exec(lines[i]);
319
+ if (m)
320
+ return Math.max(0, Number(m[1]) - 1);
321
+ }
322
+ const declared = /\bhop=(\d+)\b/.exec(lines[0] ?? '');
323
+ if (declared)
324
+ return Math.max(0, Number(declared[1]) - 1);
325
+ return ECHO_DEFAULT_HOP - 1;
326
+ }
327
+ /**
328
+ * 组装一行 trace。
329
+ *
330
+ * 前缀 `HH:MM:SS.mmm` 与既有 `echoTraceClock` 完全一致,字段一律追加在 `epoch=… tz=…`
331
+ * 之后——App 的旧解析器只认前缀那一段,字段插进前缀会让它静默失配。
332
+ */
333
+ export function echoTraceLine(opts) {
334
+ const now = opts.now ?? Date.now();
335
+ const base = `${echoTraceClock(now)} [${opts.node}] dir=${opts.dir} hop=${opts.hop} enc=0 ver=${opts.ver}${echoTraceOriginLabel(now)}`;
336
+ return opts.extra ? `${base} ${opts.extra}` : base;
337
+ }
338
+ /**
339
+ * 从 msg-diag.jsonl 里按 msgId 捞出该消息的全部阶段记录,按时间正序。
340
+ *
341
+ * echo.ecdiag 用它把内部阶段转成 trace 行。每条记录自带 msgId,所以不需要
342
+ * 探针 ID 贯穿、不用改任何打点调用点。文件不存在或读失败时返回空数组。
343
+ */
344
+ export function readDiagStages(msgId) {
345
+ if (!msgId)
346
+ return [];
347
+ try {
348
+ const home = process.env.EVOLCORE_HOME ?? path.join(os.homedir(), '.evolcore');
349
+ const file = path.join(home, 'logs', 'msg-diag.jsonl');
350
+ const raw = fs.readFileSync(file, 'utf-8');
351
+ const out = [];
352
+ for (const line of raw.split('\n')) {
353
+ if (!line.includes(msgId))
354
+ continue;
355
+ try {
356
+ const rec = JSON.parse(line);
357
+ // msgId 用 includes 粗筛,这里精确比对,避免子串误命中
358
+ if (rec.msgId !== msgId || !rec.stage || !rec.ts)
359
+ continue;
360
+ const epoch = Date.parse(rec.ts);
361
+ if (!Number.isFinite(epoch))
362
+ continue;
363
+ out.push({ stage: rec.stage, epoch });
364
+ }
365
+ catch {
366
+ // 单行损坏不影响其余
367
+ }
368
+ }
369
+ out.sort((a, b) => a.epoch - b.epoch);
370
+ return out;
371
+ }
372
+ catch {
373
+ return [];
374
+ }
375
+ }
233
376
  function attachmentDownloadHost(url) {
234
377
  try {
235
378
  return new URL(url).host || '<unknown>';
@@ -781,7 +924,7 @@ export class AUNChannel {
781
924
  if (!this.connected || !this.client)
782
925
  return Promise.reject(new Error('AUN channel is not connected'));
783
926
  return this.callAndTrace('message.send', params, { beforeSend });
784
- });
927
+ }, () => this.getDefaultEncrypt());
785
928
  requestRemoteMenu(options) {
786
929
  if (options.fromAid !== (this._aid || this.config.aid))
787
930
  throw new Error('Menu sender does not match channel identity');
@@ -837,6 +980,14 @@ export class AUNChannel {
837
980
  groupInviteDeliveryGate;
838
981
  groupInviteDelivered;
839
982
  pendingEchoMessages = new Map();
983
+ /**
984
+ * echo.ecdiag 的待回包探针。
985
+ *
986
+ * 与 pendingEchoMessages 分开存:ecdiag 的意义是观察「消息进来之后走到哪一步」,
987
+ * 所以必须在固定时长后无条件回包——不能等 agent 回复,否则 agent 不回复时
988
+ * 探针永远不出结果,而这正是最需要它的时候。agent 若中途回复,提前收口即可。
989
+ */
990
+ pendingEcdiag = new Map();
840
991
  isEchoSending = false;
841
992
  agentDir;
842
993
  trace(dir, event, data) {
@@ -1665,11 +1816,18 @@ export class AUNChannel {
1665
1816
  /** Quiesce callbacks before the shared resolver is detached, while offline sends still work. */
1666
1817
  prepareShutdown() {
1667
1818
  this.intentionalDisconnect = true;
1819
+ this.reconnectGeneration++;
1668
1820
  this.configuredOwnerBindEpoch++;
1669
1821
  this.stopOwnerDirectoryRefresh();
1822
+ this.stopOutboxTimer();
1670
1823
  if (this.reconnectTimer)
1671
1824
  clearTimeout(this.reconnectTimer);
1672
1825
  this.reconnectTimer = null;
1826
+ // 停在观察窗口里的 ecdiag 探针按「当前已走到哪」直接回包,不让重启吞掉结果。
1827
+ // 不 await:关停不能被探针投递拖住,发不出去的会进 outbox。
1828
+ for (const mid of [...this.pendingEcdiag.keys()]) {
1829
+ void this.finishEcdiag(mid, 'shutdown').catch(() => { });
1830
+ }
1673
1831
  }
1674
1832
  stopOwnerDirectoryRefresh() {
1675
1833
  this.ownerDirectoryWatch?.stop();
@@ -2226,12 +2384,13 @@ export class AUNChannel {
2226
2384
  // 2. terminal_failed with kick reason:直接 5min 后重试,不刷屏
2227
2385
  intentionalDisconnect = false;
2228
2386
  reconnectTimer = null;
2229
- reconnectGeneration = 0; // 防止并发 initClient:每次 takeoverReconnect 递增,回调中校验
2387
+ reconnectGeneration = 0; // Shutdown/takeover retires every earlier initialization attempt.
2230
2388
  onChannelDown;
2231
2389
  /** Prevent a legacy state alias from double-counting the same SDK transition. */
2232
2390
  lastConnectionStateSignature = '';
2233
- // initClient concurrency guard: 防止多个 initClient 并发执行
2234
- initInProgress = false;
2391
+ // Concurrent startup/reconnect callers observe the same connection outcome.
2392
+ initInFlight;
2393
+ initInFlightGeneration = 0;
2235
2394
  // Flap detection: 连接寿命 < FLAP_WINDOW_MS 累计 FLAP_THRESHOLD 次,判定为持续被踢
2236
2395
  connectedAt = 0;
2237
2396
  flapCount = 0;
@@ -2372,27 +2531,61 @@ export class AUNChannel {
2372
2531
  }
2373
2532
  async connect() {
2374
2533
  this.intentionalDisconnect = false;
2534
+ const generation = this.reconnectGeneration;
2375
2535
  this.flapCount = 0;
2376
2536
  this.connectedAt = 0;
2377
- this.setAidStatus('reconnecting', { lastAttemptAt: Date.now() });
2378
2537
  await this.initClient();
2379
- this.startOutboxTimer();
2538
+ this.assertInitializationActive(generation);
2539
+ this.assertNoGatewayRejection();
2380
2540
  }
2381
- async initClient() {
2382
- // 防止并发 initClient(sendMessage 触发 + timer 触发同时进入)
2383
- if (this.initInProgress) {
2384
- logger.info(`${this.logPrefix()} initClient already in progress, skipping`);
2385
- return;
2386
- }
2387
- this.initInProgress = true;
2388
- try {
2389
- await this._initClientInner();
2390
- }
2391
- finally {
2392
- this.initInProgress = false;
2541
+ initClient() {
2542
+ if (this.intentionalDisconnect)
2543
+ return Promise.reject(this.initializationCancelled());
2544
+ const generation = this.reconnectGeneration;
2545
+ if (this.initInFlight && this.initInFlightGeneration === generation)
2546
+ return this.initInFlight;
2547
+ // Publish the promise before initialization runs, including synchronous
2548
+ // hooks that could reenter. Cache only the attempt, never its outcome.
2549
+ const pending = Promise.resolve().then(() => this._initClientInner(generation)).then(() => {
2550
+ this.assertInitializationActive(generation);
2551
+ this.assertNoGatewayRejection();
2552
+ // Automatic and manual reconnects share initialization, not connect().
2553
+ this.startOutboxTimer();
2554
+ }).catch(error => {
2555
+ // Store/identity failures precede client.connect(), but need the same
2556
+ // recovery as transport failures. A retired attempt cannot restart us.
2557
+ this.assertInitializationActive(generation);
2558
+ // A gateway no-retry decision outranks the generic failure fallback.
2559
+ if (this.aidState.status === 'kicked_no_retry')
2560
+ throw error;
2561
+ logger.error(`${this.logPrefix()} Initialization failed: ${error}`);
2562
+ this.setAidStatus('failed', { lastError: String(error).slice(0, 80) });
2563
+ this.scheduleReconnect();
2564
+ throw error;
2565
+ }).finally(() => {
2566
+ if (this.initInFlight === pending)
2567
+ this.initInFlight = undefined;
2568
+ });
2569
+ this.initInFlight = pending;
2570
+ this.initInFlightGeneration = generation;
2571
+ return pending;
2572
+ }
2573
+ initializationCancelled() {
2574
+ return Object.assign(new Error('AUN connection initialization cancelled'), { code: 'AUN_CONNECT_CANCELLED' });
2575
+ }
2576
+ assertInitializationActive(generation) {
2577
+ if (this.intentionalDisconnect || generation !== this.reconnectGeneration)
2578
+ throw this.initializationCancelled();
2579
+ }
2580
+ assertNoGatewayRejection() {
2581
+ if (this.aidState.status === 'kicked_no_retry') {
2582
+ throw Object.assign(new Error(this.aidState.lastError ?? 'AUN gateway rejected the connection'), { code: 'AUN_GATEWAY_NO_RETRY' });
2393
2583
  }
2394
2584
  }
2395
- async _initClientInner() {
2585
+ async _initClientInner(generation) {
2586
+ this.assertInitializationActive(generation);
2587
+ // An explicit new attempt retires the previous gateway's terminal decision.
2588
+ this.setAidStatus('reconnecting', { lastAttemptAt: Date.now() });
2396
2589
  this.stopOwnerDirectoryRefresh();
2397
2590
  this.configuredOwnerBindEpoch++;
2398
2591
  this.observerGroupMembers.clear();
@@ -2405,17 +2598,19 @@ export class AUNChannel {
2405
2598
  this.observerGroupMemberFetches.clear();
2406
2599
  // Clean up existing client if any
2407
2600
  if (this.client) {
2408
- unregisterSameOwnerClient(this.config.aid, this.client);
2409
- ownerResolver.detachClient(this.config.aid, this.client);
2601
+ const previousClient = this.client;
2602
+ this.client = null;
2603
+ unregisterSameOwnerClient(this.config.aid, previousClient);
2604
+ ownerResolver.detachClient(this.config.aid, previousClient);
2410
2605
  this.trace('OUT', 'client.close', { reason: 'initClient' });
2411
2606
  try {
2412
- await this.client.close();
2607
+ await previousClient.close();
2413
2608
  this.trace('OUT', 'client.close.ok', { reason: 'initClient' });
2414
2609
  }
2415
2610
  catch (e) {
2416
2611
  this.trace('OUT', 'client.close.error', { reason: 'initClient', error: String(e) });
2417
2612
  }
2418
- this.client = null;
2613
+ this.assertInitializationActive(generation);
2419
2614
  }
2420
2615
  if (this.store) {
2421
2616
  try {
@@ -2441,8 +2636,26 @@ export class AUNChannel {
2441
2636
  aunPath,
2442
2637
  debug: this.config.aunSdkLog ?? false,
2443
2638
  });
2639
+ if (this.intentionalDisconnect || generation !== this.reconnectGeneration) {
2640
+ try {
2641
+ store.close();
2642
+ }
2643
+ catch { /* ignore */ }
2644
+ throw this.initializationCancelled();
2645
+ }
2444
2646
  this.store = store;
2445
2647
  const client = await loadClient(store, aidName);
2648
+ if (this.intentionalDisconnect || generation !== this.reconnectGeneration) {
2649
+ await client.close().catch(() => { });
2650
+ if (this.store === store) {
2651
+ this.store = null;
2652
+ try {
2653
+ store.close();
2654
+ }
2655
+ catch { /* ignore */ }
2656
+ }
2657
+ throw this.initializationCancelled();
2658
+ }
2446
2659
  this.client = client;
2447
2660
  const localConfig = loadAgent(aidName);
2448
2661
  ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
@@ -2452,11 +2665,14 @@ export class AUNChannel {
2452
2665
  await this.config.onClientReady?.(client);
2453
2666
  }
2454
2667
  catch (error) {
2668
+ this.assertInitializationActive(generation);
2455
2669
  logger.warn(`${this.logPrefix()} client-ready hook failed: ${error instanceof Error ? error.message : String(error)}`);
2456
2670
  }
2671
+ this.assertInitializationActive(generation);
2457
2672
  // A reconnect replaces the SDK client. Late events from the retired
2458
2673
  // instance must not mutate the new instance's health or message state.
2459
- const isCurrentClient = () => this.client === client;
2674
+ const isCurrentClient = () => this.client === client
2675
+ && generation === this.reconnectGeneration && !this.intentionalDisconnect;
2460
2676
  // Register event handlers before connecting
2461
2677
  client.on('agentmd.changed', (data) => {
2462
2678
  if (!isCurrentClient() || this.intentionalDisconnect || typeof data !== 'string')
@@ -2476,6 +2692,10 @@ export class AUNChannel {
2476
2692
  // held separately by this channel, so refresh it with the existing API.
2477
2693
  if (aid === (this._aid || this.config.aid)) {
2478
2694
  // 名片 type/exttype 是 requires 判定的依据:变更后重新扫描包。
2695
+ //
2696
+ // 两个调用都要:`ensureStarted` 在已启动时只更新 identity(不重扫),
2697
+ // `reload()` 才带新 identity 重算 `requires`。删掉任何一个都会让名片变更
2698
+ // 不生效——别把它当成重复扫描。
2479
2699
  if (this.serviceRouter) {
2480
2700
  const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
2481
2701
  this.serviceRouter.ensureStarted(identity);
@@ -2593,7 +2813,7 @@ export class AUNChannel {
2593
2813
  });
2594
2814
  }
2595
2815
  const handleSdkState = (source) => (data) => {
2596
- if (!isCurrentClient())
2816
+ if (this.client !== client || (!this.intentionalDisconnect && !isCurrentClient()))
2597
2817
  return;
2598
2818
  // fastaun 0.5.x publishes state_change with nine-state values. Keep the
2599
2819
  // legacy event subscription for older stores/SDKs during rolling upgrades.
@@ -2674,8 +2894,12 @@ export class AUNChannel {
2674
2894
  retry_initial_delay: 1.0,
2675
2895
  retry_max_delay: 300.0,
2676
2896
  });
2897
+ this.assertInitializationActive(generation);
2898
+ if (this.client !== client)
2899
+ throw this.initializationCancelled();
2900
+ this.assertNoGatewayRejection();
2677
2901
  this.trace('OUT', 'client.connect.ok', { aid: client.aid });
2678
- this._aid = this.client.aid ?? undefined;
2902
+ this._aid = client.aid ?? undefined;
2679
2903
  const deviceId = client.currentAid?.deviceId ?? '';
2680
2904
  this._chatId = this._aid ? `${this._aid}:${deviceId}:` : '';
2681
2905
  // 控制 AID 也有标准 host agent.md。发布在后台执行,短暂的 Name
@@ -2718,10 +2942,10 @@ export class AUNChannel {
2718
2942
  appendAidLifecycle({ ts: Date.now(), iso: new Date().toISOString(), event: 'connected', aid: this.config.aid, gateway: this.gatewayUrl });
2719
2943
  }
2720
2944
  catch (e) {
2945
+ this.assertInitializationActive(generation);
2946
+ if (this.client !== client)
2947
+ throw this.initializationCancelled();
2721
2948
  this.trace('OUT', 'client.connect.error', { error: String(e) });
2722
- logger.error(`${this.logPrefix()} Connection failed: ${e}`);
2723
- this.setAidStatus('failed', { lastError: String(e).slice(0, 80) });
2724
- this.scheduleReconnect();
2725
2949
  throw e;
2726
2950
  }
2727
2951
  }
@@ -3618,6 +3842,8 @@ export class AUNChannel {
3618
3842
  mentions,
3619
3843
  peerName: displayName || undefined,
3620
3844
  peerType: peerIdentity.type,
3845
+ peerExttype: peerIdentity.exttype,
3846
+ senderCtx: readSenderCtx(payload),
3621
3847
  sameDevice: msg.same_device === true || undefined,
3622
3848
  sameNetwork: msg.same_network === true || undefined,
3623
3849
  sameEgressIp: msg.same_egress_ip === true || undefined,
@@ -3708,11 +3934,12 @@ export class AUNChannel {
3708
3934
  }
3709
3935
  // Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
3710
3936
  // this.checkOwnerDirectoryAuthorizationOnMessage(senderAid, payload);
3711
- // 短 echo 快速通道:连通性测试要尽量低延迟,命中后绕过所有 await(后续 mention 过滤)
3937
+ // 探针快速通道:连通性测试要尽量低延迟,命中后绕过所有 await(后续 mention 过滤)
3938
+ // 判定看位置锚定的前缀,不看长度;已带本节点 trace 的视为回路,不进这里
3712
3939
  {
3713
- const firstLineFast = text.split('\n')[0] || '';
3940
+ const echoKindFast = echoProbeKind(text);
3714
3941
  const hasEvolCoreTrace = /\[EvolCore\.(receive|reply|agent)\]/.test(text);
3715
- if (/echo/i.test(firstLineFast) && firstLineFast.trim().length <= 10 && !hasEvolCoreTrace) {
3942
+ if (echoKindFast === 'echo' && !hasEvolCoreTrace) {
3716
3943
  const msgEncryptedFast = !!env.encrypted;
3717
3944
  const msgChatmodeFast = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
3718
3945
  const peerInfo = this.peerInfoCached(senderAid);
@@ -3775,11 +4002,10 @@ export class AUNChannel {
3775
4002
  const mentionedSelf = !!this._aid && mentionEntryTargets(payloadMentionEntries).includes(this._aid);
3776
4003
  // @all 仅认结构化 mentions(payload.mentions),不扫描正文,避免引述性 "@all" 误判。
3777
4004
  const mentionedAll = hasMentionAll(payloadMentionEntries);
3778
- // Echo 机制优先于 mention 过滤:消息第一行包含 echo 时触发
3779
- // 包含 [EvolCore.xxx] trace 说明已被本系统处理过,是回声的回声,丢弃防止链式爆炸
3780
- const firstLineGroup = text.split('\n')[0] || '';
4005
+ // 探针优先于 mention 过滤。判定看位置锚定前缀(echo / echo.ask / echo.ecdiag),不看长度。
4006
+ const echoKindGroup = echoProbeKind(text);
3781
4007
  const hasEvolCoreTraceGroup = /\[EvolCore\.(receive|reply|agent)\]/.test(text);
3782
- const isEchoMsg = /echo/i.test(firstLineGroup) && !hasEvolCoreTraceGroup;
4008
+ const isEchoMsg = echoKindGroup !== null && !hasEvolCoreTraceGroup;
3783
4009
  const slashCommandText = this.normalizeSlashCommandText(text);
3784
4010
  // 命令判定:剥离所有 @ 后看是否 / 开头(多 @ 场景如 @a @b /status 也能正确识别)。
3785
4011
  // echo 消息走独立的 trace 流程,不参与命令语义判定。
@@ -3795,22 +4021,25 @@ export class AUNChannel {
3795
4021
  ? await this.groupSlashRequireMentionsResolver().catch(() => undefined) ?? true
3796
4022
  : true;
3797
4023
  if (isEchoMsg) {
3798
- // 短 echo(≤10 字符)已在前面的快速通道命中并 return,这里只处理长 echo
3799
- // >10 字符:追加 trace,存 pending echo,跳过 mention 过滤继续走 Agent 流程
4024
+ // echo.ask / echo.ecdiag:追加 trace 后继续走 Agent 流程(下面会 dispatch)。
4025
+ // echo 本身已在快速通道直接回包,不会走到这里。
3800
4026
  const echoCreatedAt = data.created_at;
3801
4027
  const echoReceiveTs = Date.now();
3802
4028
  let echoText = text;
3803
- echoText += `\n${echoTraceClock(echoReceiveTs)} [EvolCore.receive] from=${senderAid} mid=${messageId} chat=group self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(echoCreatedAt, receivedAt)}${echoTraceOriginLabel(echoReceiveTs)}`;
4029
+ echoText += `\n${echoTraceLine({
4030
+ node: 'EvolCore.receive',
4031
+ dir: echoTraceDirection(text),
4032
+ hop: echoTraceNextHop(text),
4033
+ ver: readInstalledEvolcoreVersion(),
4034
+ now: echoReceiveTs,
4035
+ extra: `from=${senderAid} mid=${messageId} chat=group self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(echoCreatedAt, receivedAt)}`,
4036
+ })}`;
3804
4037
  const msgChatmodeEcho = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
3805
- this.pendingEchoMessages.set(messageId, {
3806
- text: echoText,
3807
- channelId: groupId,
3808
- context: this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId, readTopicLabel(payload), readTopicStatus(payload)),
3809
- receiveTs: Date.now(),
3810
- });
4038
+ const groupProbeContext = this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId, readTopicLabel(payload), readTopicStatus(payload));
4039
+ this.registerProbe(messageId, echoKindGroup ?? 'ask', echoText, groupId, groupProbeContext, echoReceiveTs);
3811
4040
  // 继续走正常 Agent 流程(下面的代码会 dispatch)
3812
4041
  }
3813
- else if (/echo/i.test(firstLineGroup) && hasEvolCoreTraceGroup) {
4042
+ else if (echoKindGroup !== null && hasEvolCoreTraceGroup) {
3814
4043
  // 回声炸弹:已被任何 EvolCore 节点 trace 过的 echo,直接丢弃
3815
4044
  logger.info(`${this.logPrefix()} Group dropped: echo bomb (already-traced group=${groupId} sender=${senderAid} mid=${messageId})`);
3816
4045
  return;
@@ -3891,12 +4120,33 @@ export class AUNChannel {
3891
4120
  ...payloadMentionAids,
3892
4121
  ...this.extractMentionAidsFromText(text),
3893
4122
  ]));
4123
+ // 群角色表:发言人角色用于信封 `群角色:`,本端角色用于系统段「我的群角色」。
4124
+ // 取不到就留空(渲染层省略),绝不回落 member。
4125
+ const memberRoles = await this.resolveGroupMemberRoles(groupId);
4126
+ const senderGroupRole = memberRoles?.get(String(senderAid).toLowerCase());
4127
+ const myGroupRole = memberRoles?.get(String(this._aid || '').toLowerCase());
4128
+ const groupRoles = memberRoles ? Object.fromEntries(memberRoles) : undefined;
4129
+ // 「与发言人」:发言人本人的关系 → 联系人 → visitor。
4130
+ const speakerRelation = resolveSenderRelationRole({
4131
+ selfAid: this.config.aid,
4132
+ channelKey: `aun#${this.config.aid}#main`,
4133
+ channelType: 'aun',
4134
+ chatType: 'group',
4135
+ senderAid,
4136
+ conversationId: groupId,
4137
+ });
3894
4138
  this.dispatchMessage({
3895
4139
  channelId: groupId,
3896
4140
  groupId,
3897
4141
  userId: senderAid,
3898
4142
  peerName: displayName || undefined,
3899
4143
  peerType: peerIdentity.type,
4144
+ peerExttype: peerIdentity.exttype,
4145
+ senderCtx: readSenderCtx(payload),
4146
+ groupRole: senderGroupRole,
4147
+ groupRoles,
4148
+ myGroupRole,
4149
+ speakerRelation,
3900
4150
  sameDevice: msg.same_device === true || undefined,
3901
4151
  sameNetwork: msg.same_network === true || undefined,
3902
4152
  sameEgressIp: msg.same_egress_ip === true || undefined,
@@ -3942,35 +4192,39 @@ export class AUNChannel {
3942
4192
  // Inbound events are claimed in handleIncomingPrivateMessage / GroupMessage
3943
4193
  // before parsing. Keeping dedupe there prevents duplicate slash commands
3944
4194
  // from reaching routing and mention policy code.
3945
- // Echo 机制:消息第一行包含 "echo"(不区分大小写)且原始内容 ≤10 字符时,直接回声
3946
- // 包含 [EvolCore.xxx] trace 说明已被本系统处理过,是回声的回声,丢弃防止链式爆炸
3947
- const firstLine = event.text.split('\n')[0] || '';
4195
+ // 探针机制:位置锚定前缀 echo / echo.ask / echo.ecdiag,不看长度。
4196
+ // 带 [EvolCore.xxx] trace 说明已被本节点处理过,是回声的回声,丢弃防止链式爆炸。
4197
+ const echoKindPrivate = echoProbeKind(event.text);
3948
4198
  const hasEvolCoreTracePrivate = /\[EvolCore\.(receive|reply|agent)\]/.test(event.text);
3949
- if (/echo/i.test(firstLine) && firstLine.trim().length <= 10 && !hasEvolCoreTracePrivate) {
4199
+ // echo:不进大模型,直接回包
4200
+ if (echoKindPrivate === 'echo' && !hasEvolCoreTracePrivate) {
3950
4201
  this.handleEcho(event);
3951
4202
  return;
3952
4203
  }
3953
- // 回声炸弹:已被任何 EvolCore 节点 trace 过的 echo,直接丢弃(防止多 agent 间无限回声)
3954
- if (/echo/i.test(firstLine) && hasEvolCoreTracePrivate) {
4204
+ // 回声炸弹:已被任何 EvolCore 节点 trace 过的探针,直接丢弃
4205
+ if (echoKindPrivate !== null && hasEvolCoreTracePrivate) {
3955
4206
  logger.info(`${this.logPrefix()} Dropped: echo bomb (already-traced mid=${event.messageId} chat=${event.chatType})`);
3956
4207
  return;
3957
4208
  }
3958
- // 长 echo(>10 字符):存 pending,继续交给 agent 处理
3959
- if (/echo/i.test(firstLine) && firstLine.trim().length > 10 && !hasEvolCoreTracePrivate) {
4209
+ // echo.ask / echo.ecdiag:追加 trace 后继续交给 agent 处理
4210
+ if (echoKindPrivate !== null) {
3960
4211
  const echoReceiveTs = Date.now();
3961
4212
  let echoText = event.text;
3962
- echoText += `\n${echoTraceClock(echoReceiveTs)} [EvolCore.receive] from=${event.userId}${event.peerName ? `(${event.peerName})` : ''} mid=${event.messageId} chat=${event.chatType} self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(event.createdAt, event.receivedAt ?? echoReceiveTs)}${echoTraceOriginLabel(echoReceiveTs)}`;
3963
- this.pendingEchoMessages.set(event.messageId, {
3964
- text: echoText,
3965
- channelId: event.channelId,
3966
- context: {
3967
- ...(event.replyContext?.metadata ? { metadata: event.replyContext.metadata } : {}),
3968
- ...(typeof threadId === 'string' ? { threadId } : {}),
3969
- delivery,
3970
- },
3971
- receiveTs: Date.now(),
3972
- });
3973
- logger.info(`${this.logPrefix()} [Echo] long echo stored: mid=${event.messageId} channelId=${event.channelId}`);
4213
+ echoText += `\n${echoTraceLine({
4214
+ node: 'EvolCore.receive',
4215
+ dir: echoTraceDirection(event.text),
4216
+ hop: echoTraceNextHop(event.text),
4217
+ ver: readInstalledEvolcoreVersion(),
4218
+ now: echoReceiveTs,
4219
+ extra: `from=${event.userId}${event.peerName ? `(${event.peerName})` : ''} mid=${event.messageId} chat=${event.chatType} self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(event.createdAt, event.receivedAt ?? echoReceiveTs)}`,
4220
+ })}`;
4221
+ const probeContext = {
4222
+ ...(event.replyContext?.metadata ? { metadata: event.replyContext.metadata } : {}),
4223
+ ...(typeof threadId === 'string' ? { threadId } : {}),
4224
+ delivery,
4225
+ };
4226
+ this.registerProbe(event.messageId, echoKindPrivate, echoText, event.channelId, probeContext, echoReceiveTs);
4227
+ logger.info(`${this.logPrefix()} [Echo] ${echoKindPrivate} probe stored: mid=${event.messageId} channelId=${event.channelId}`);
3974
4228
  }
3975
4229
  if (!this.messageHandler)
3976
4230
  return;
@@ -3993,6 +4247,12 @@ export class AUNChannel {
3993
4247
  peerId: event.userId || event.channelId || '',
3994
4248
  peerName: event.peerName,
3995
4249
  peerType: event.peerType,
4250
+ peerExttype: event.peerExttype,
4251
+ senderCtx: event.senderCtx,
4252
+ groupRole: event.groupRole,
4253
+ groupRoles: event.groupRoles,
4254
+ myGroupRole: event.myGroupRole,
4255
+ speakerRelation: event.speakerRelation,
3996
4256
  peerDeviceId: event.peerDeviceId,
3997
4257
  peerSlotId: event.peerSlotId,
3998
4258
  sameDevice: event.sameDevice,
@@ -4071,6 +4331,74 @@ export class AUNChannel {
4071
4331
  observerGroupMembers = new Map();
4072
4332
  observerGroupMemberFetches = new Map();
4073
4333
  observerGroupMembershipEpoch = new Map();
4334
+ /** 群成员角色缓存(AID → role),供消息信封 `群角色:` / 系统段「我的群角色」使用。 */
4335
+ groupMemberRoles = new Map();
4336
+ groupMemberRoleFetches = new Map();
4337
+ /** 读取整张群成员角色表(分页取全量)。失败返回 undefined,调用方不得回落 member。 */
4338
+ async resolveGroupMemberRoles(groupId) {
4339
+ if (!groupId || !this.client)
4340
+ return undefined;
4341
+ const cached = this.groupMemberRoles.get(groupId);
4342
+ if (cached && cached.expiresAt > Date.now())
4343
+ return cached.roles;
4344
+ const pending = this.groupMemberRoleFetches.get(groupId);
4345
+ if (pending)
4346
+ return pending;
4347
+ let request;
4348
+ request = (async () => {
4349
+ try {
4350
+ const roles = new Map();
4351
+ const size = 100;
4352
+ for (let page = 1; page <= 20; page++) {
4353
+ const result = await this.callAndTrace('group.get_members', { group_id: groupId, page, size });
4354
+ const members = Array.isArray(result?.members)
4355
+ ? result.members
4356
+ : Array.isArray(result?.items) ? result.items : undefined;
4357
+ if (!members)
4358
+ return undefined;
4359
+ for (const member of members) {
4360
+ const aid = typeof member === 'string'
4361
+ ? member.trim()
4362
+ : typeof member?.aid === 'string' ? member.aid.trim()
4363
+ : typeof member?.member_aid === 'string' ? member.member_aid.trim() : '';
4364
+ const role = typeof member?.role === 'string' ? member.role.trim() : '';
4365
+ if (aid && role)
4366
+ roles.set(aid.toLowerCase(), role);
4367
+ }
4368
+ const total = Number(result?.total);
4369
+ const pageSize = Number(result?.size) > 0 ? Number(result.size) : size;
4370
+ if (members.length === 0)
4371
+ break;
4372
+ // total 缺失时按"整页=还有下一页"继续,避免大群只取到第一页。
4373
+ if (Number.isFinite(total)) {
4374
+ if (page * pageSize >= total)
4375
+ break;
4376
+ }
4377
+ else if (members.length < pageSize) {
4378
+ break;
4379
+ }
4380
+ }
4381
+ this.groupMemberRoles.set(groupId, {
4382
+ roles,
4383
+ expiresAt: Date.now() + GROUP_MEMBER_ROLES_TTL_MS,
4384
+ });
4385
+ return roles;
4386
+ }
4387
+ catch {
4388
+ // 失败也做短缓存:group.get_members 持续失败时,不能每条群消息都重试一次 RPC。
4389
+ this.groupMemberRoles.set(groupId, {
4390
+ roles: new Map(),
4391
+ expiresAt: Date.now() + GROUP_MEMBER_ROLES_FAILURE_TTL_MS,
4392
+ });
4393
+ return undefined;
4394
+ }
4395
+ finally {
4396
+ this.groupMemberRoleFetches.delete(groupId);
4397
+ }
4398
+ })();
4399
+ this.groupMemberRoleFetches.set(groupId, request);
4400
+ return request;
4401
+ }
4074
4402
  /** 注入观察者配置读取器(daemon 侧从 EvolAgent merged config 读)。 */
4075
4403
  setObserverConfigResolver(fn) {
4076
4404
  this.observerConfigResolver = fn;
@@ -4459,11 +4787,27 @@ export class AUNChannel {
4459
4787
  }
4460
4788
  handleEcho(event) {
4461
4789
  const receiveTs = Date.now();
4790
+ const ver = readInstalledEvolcoreVersion();
4791
+ const dir = echoTraceDirection(event.text);
4462
4792
  // 在收到的消息文本末尾追加 trace 行(只追加,不修改原文)
4463
4793
  let echoText = event.text;
4464
- echoText += `\n${echoTraceClock(receiveTs)} [EvolCore.receive] from=${event.userId}${event.peerName ? `(${event.peerName})` : ''} mid=${event.messageId} chat=${event.chatType} self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((receiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(event.createdAt, receiveTs)}${echoTraceOriginLabel(receiveTs)}`;
4794
+ echoText += `\n${echoTraceLine({
4795
+ node: 'EvolCore.receive',
4796
+ dir,
4797
+ hop: echoTraceNextHop(event.text),
4798
+ ver,
4799
+ now: receiveTs,
4800
+ extra: `from=${event.userId}${event.peerName ? `(${event.peerName})` : ''} mid=${event.messageId} chat=${event.chatType} self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((receiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(event.createdAt, receiveTs)}`,
4801
+ })}`;
4465
4802
  const replyTs = Date.now();
4466
- echoText += `\n${echoTraceClock(replyTs)} [EvolCore.reply] echo回声发出 conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoTraceOriginLabel(replyTs)}`;
4803
+ echoText += `\n${echoTraceLine({
4804
+ node: 'EvolCore.reply',
4805
+ dir: 'ret',
4806
+ hop: echoTraceNextHop(echoText),
4807
+ ver,
4808
+ now: replyTs,
4809
+ extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
4810
+ })}`;
4467
4811
  if (Buffer.byteLength(echoText, 'utf-8') > 4096) {
4468
4812
  echoText += `\n[TRUNCATED]`;
4469
4813
  }
@@ -4552,11 +4896,17 @@ export class AUNChannel {
4552
4896
  if (signature === this.lastConnectionStateSignature)
4553
4897
  return;
4554
4898
  this.lastConnectionStateSignature = signature;
4555
- if (this.intentionalDisconnect && state === 'disconnected') {
4556
- this.connected = false;
4557
- this.connectedAt = 0;
4899
+ if (this.intentionalDisconnect) {
4900
+ if (state === 'disconnected') {
4901
+ this.connected = false;
4902
+ this.connectedAt = 0;
4903
+ }
4558
4904
  return;
4559
4905
  }
4906
+ // Only a new initialization may leave a gateway no-retry decision.
4907
+ // Queued state aliases or a late ready event still belong to this attempt.
4908
+ if (this.aidState.status === 'kicked_no_retry')
4909
+ return;
4560
4910
  if (state === 'connected') {
4561
4911
  this.connected = true;
4562
4912
  this.connectedAt = Date.now();
@@ -4864,21 +5214,16 @@ export class AUNChannel {
4864
5214
  await this.initClient();
4865
5215
  // initClient 完成后再次校验 generation,防止 initClient 期间被新的 takeover 取代
4866
5216
  if (gen !== this.reconnectGeneration) {
4867
- logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded but generation stale, closing stale client`);
4868
- this.stopOwnerDirectoryRefresh();
4869
- if (this.client) {
4870
- unregisterSameOwnerClient(this.config.aid, this.client);
4871
- ownerResolver.detachClient(this.config.aid, this.client);
4872
- this.client.close().catch(() => { });
4873
- this.client = null;
4874
- }
4875
- this.connected = false;
5217
+ // Initialization owns its resources; this.client may already be a replacement.
5218
+ logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) ignored: generation stale`);
4876
5219
  return;
4877
5220
  }
4878
5221
  this.trace('OUT', 'reconnect.ok', { reason, generation: gen });
4879
5222
  logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded`);
4880
5223
  }
4881
5224
  catch (err) {
5225
+ if (gen !== this.reconnectGeneration || this.intentionalDisconnect)
5226
+ return;
4882
5227
  this.trace('OUT', 'reconnect.error', { reason, error: String(err), generation: gen });
4883
5228
  logger.error(`${this.logPrefix()} TS-layer reconnect (${reason}) failed: ${err}`);
4884
5229
  // initClient 内部已经在失败路径触发 scheduleReconnect 了,这里不重复
@@ -4933,8 +5278,12 @@ export class AUNChannel {
4933
5278
  * identity 用本地名片(不触发网络);requires 判定与 ECK 变量读同一份。
4934
5279
  */
4935
5280
  ensureServiceRouter() {
4936
- if (this.serviceRouter)
5281
+ // 缓存的实例必须仍在单例表里:同一 AID 的另一个 channel 实例 `disconnect()`
5282
+ // 时会把表项摘走并关掉调度器,残留的旧对象再拿去分发只会得到 DISPATCHER_CLOSED。
5283
+ // 不在这里校验的话,本实例要等到自己 `disconnect()` 才会丢掉它。
5284
+ if (this.serviceRouter && peekServiceRouter(this.config.aid) === this.serviceRouter) {
4937
5285
  return this.serviceRouter;
5286
+ }
4938
5287
  const aid = this.config.aid;
4939
5288
  const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
4940
5289
  this.serviceRouter = getServiceRouter(aid, agentServicesDir(aid), {
@@ -4986,14 +5335,21 @@ export class AUNChannel {
4986
5335
  logger.debug(`${this.logPrefix()} Service-mode rejection not delivered: code=${result.code ?? 'UNKNOWN'} to=${toAid}`);
4987
5336
  }
4988
5337
  }
4989
- /** 服务调用的准入判决。blocked 静默;其余未通过回 NOT_AUTHORIZED。 */
5338
+ /**
5339
+ * 服务调用的准入判决。blocked 静默;其余未通过走统一拒绝。
5340
+ *
5341
+ * 不再把 Owner AID 塞进回包(`request_contact`)——那等于对陌生人确认
5342
+ * 「这台机器有 EvolCore、它的 owner 是谁」。要让对端申请联系人,走名录流程。
5343
+ */
4990
5344
  serviceAdmission(fromAid) {
4991
- const decision = evaluateAppContactAdmission(this.config.aid, fromAid);
5345
+ // `includeTemporary: false`:临时授权是分钟级的短时放行,服务调用属长效口径,
5346
+ // 不该随它抖动。需要临时放行用 services-config.json 的 rules.allow。
5347
+ const decision = evaluateAppContactAdmission(this.config.aid, fromAid, Date.now(), { includeTemporary: false });
4992
5348
  if (decision.allow)
4993
- return { admission: 'allow' };
5349
+ return 'allow';
4994
5350
  if (decision.reason === 'blocked')
4995
- return { admission: 'blocked' };
4996
- return { admission: 'not_authorized', requestContact: currentContactBinding(this.config.aid)?.owner_aid };
5351
+ return 'blocked';
5352
+ return 'not_authorized';
4997
5353
  }
4998
5354
  /**
4999
5355
  * 入站服务消息(请求支)。调用方已完成 claim。
@@ -5006,18 +5362,24 @@ export class AUNChannel {
5006
5362
  const requestId = typeof payload.request_id === 'string' && payload.request_id
5007
5363
  ? payload.request_id
5008
5364
  : input.messageId;
5365
+ const requestIdGenerated = requestId === input.messageId;
5366
+ if (requestIdGenerated) {
5367
+ // 对端没带 request_id:用 message_id 顶上,保证每次调用有唯一 id。
5368
+ // 必须留痕——否则"为什么同一个业务请求被跑了两次"查不出是对方没传 id。
5369
+ logger.debug(`${this.logPrefix()} service request without request_id; using message_id ${input.messageId} type=${rawType} from=${input.fromAid}`);
5370
+ }
5009
5371
  const message = {
5010
5372
  type: rawType,
5011
5373
  requestId,
5012
- requestIdGenerated: requestId === input.messageId,
5374
+ requestIdGenerated,
5013
5375
  fromAid: input.fromAid,
5014
5376
  messageId: input.messageId,
5015
5377
  encrypted: input.encrypted,
5016
5378
  payload,
5017
5379
  receivedAt: input.receivedAt,
5018
5380
  };
5019
- const { admission, requestContact } = this.serviceAdmission(input.fromAid);
5020
- const reply = await router.handleRequest(message, { admission, requestContact });
5381
+ const admission = this.serviceAdmission(input.fromAid);
5382
+ const reply = await router.handleRequest(message, { admission });
5021
5383
  if (!reply.shouldSend)
5022
5384
  return;
5023
5385
  await this.sendServiceReply(input.fromAid, input.messageId, input.encrypted, reply);
@@ -5955,9 +6317,10 @@ export class AUNChannel {
5955
6317
  }
5956
6318
  const delivery = this.requireDelivery(channelId, context);
5957
6319
  let routedContext = this.withDelivery(context, delivery);
5958
- // 长 echo: agent 首次回复前先发 echo trace(echo 自身发送时跳过)
6320
+ // echo.ask / echo.ecdiag: agent 首次回复前先发探针回包(探针自身发送时跳过)
6321
+ // 把这次回复的正文一并交给 flushPendingEcho,echo.ask 会把它嵌进 trace 里
5959
6322
  if (!this.isEchoSending) {
5960
- await this.flushPendingEcho(channelId, delivery, context?.threadId);
6323
+ await this.flushPendingEcho(channelId, delivery, context?.threadId, text);
5961
6324
  }
5962
6325
  let finalText = text;
5963
6326
  const turnKey = `${channelId}\0${context?.threadId ?? ''}`;
@@ -6459,20 +6822,155 @@ export class AUNChannel {
6459
6822
  return { ok: false, error: e?.message || String(e), code: e?.code };
6460
6823
  }
6461
6824
  }
6462
- async flushPendingEcho(channelId, delivery, threadId) {
6463
- // 查找该 channelId 是否有 pending echo(长 echo 等待 agent 首次回复)
6825
+ /**
6826
+ * 登记一条待回包的探针。
6827
+ *
6828
+ * `echo.ask`:等 agent 首次回复触发 flushPendingEcho。
6829
+ * `echo.ecdiag`:**立即起计时器**,到点无条件回包——这条路径不能依赖 agent 回复,
6830
+ * 因为探针存在的意义就是诊断「消息之后发生了什么」,agent 不回复恰恰是最需要
6831
+ * 看结果的情形。等待期间 agent 若回复,flushPendingEcho 会提前收口。
6832
+ */
6833
+ registerProbe(messageId, kind, text, channelId, context, receiveTs) {
6834
+ if (kind === 'ecdiag') {
6835
+ const timeoutMs = ecdiagTimeoutMs(text);
6836
+ const timer = setTimeout(() => { void this.finishEcdiag(messageId, 'timeout'); }, timeoutMs);
6837
+ // 不阻止进程退出:探针计时器不该拖住 daemon 关停
6838
+ timer.unref?.();
6839
+ this.pendingEcdiag.set(messageId, { text, channelId, context, receiveTs, timer });
6840
+ logger.info(`${this.logPrefix()} [Echo] ecdiag armed mid=${messageId} timeoutMs=${timeoutMs}`);
6841
+ return;
6842
+ }
6843
+ this.pendingEchoMessages.set(messageId, { text, channelId, context, receiveTs, probeKind: kind });
6844
+ }
6845
+ /**
6846
+ * echo.ecdiag 回包收口。`reason` 只是日志标记:`timeout` 表示等满了观察窗口,
6847
+ * `agent` 表示 agent 提前回复,`shutdown` 表示进程退出时冲刷。
6848
+ *
6849
+ * 无论哪种原因,都按「当时已经走到哪」输出——这正是探针要的语义。
6850
+ */
6851
+ async finishEcdiag(msgId, reason) {
6852
+ const probe = this.pendingEcdiag.get(msgId);
6853
+ if (!probe)
6854
+ return;
6855
+ this.pendingEcdiag.delete(msgId);
6856
+ clearTimeout(probe.timer);
6857
+ const ver = readInstalledEvolcoreVersion();
6858
+ const stages = readDiagStages(msgId);
6859
+ const doneTs = Date.now();
6860
+ const firstTs = stages.length > 0 ? stages[0].epoch : probe.receiveTs;
6861
+ let echoText = probe.text;
6862
+ let hop = echoTraceNextHop(echoText);
6863
+ for (const stage of stages) {
6864
+ echoText += `\n${echoTraceLine({
6865
+ node: `EvolCore.${stage.stage}`,
6866
+ dir: 'fwd',
6867
+ hop: hop--,
6868
+ ver,
6869
+ now: stage.epoch,
6870
+ extra: `stage=${stage.stage}`,
6871
+ })}`;
6872
+ }
6873
+ echoText += `\n${echoTraceLine({
6874
+ node: 'EvolCore.diag_done',
6875
+ dir: 'fwd',
6876
+ hop: Math.max(0, hop),
6877
+ ver,
6878
+ now: doneTs,
6879
+ extra: `stages=${stages.length} total_ms=${doneTs - firstTs} reason=${reason}`,
6880
+ })}`;
6881
+ echoText += `\n${echoTraceLine({
6882
+ node: 'EvolCore.reply',
6883
+ dir: 'ret',
6884
+ hop: Math.max(0, hop - 1),
6885
+ ver,
6886
+ now: doneTs,
6887
+ extra: `conn_uptime=${this.connectedAt ? Math.round((doneTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
6888
+ })}`;
6889
+ logger.info(`${this.logPrefix()} [Echo] ecdiag reply mid=${msgId} reason=${reason} stages=${stages.length} totalMs=${doneTs - firstTs}`);
6890
+ await this.deliverProbeText(probe.channelId, probe.context, echoText);
6891
+ }
6892
+ /** 投递探针回包:不经过 sendMessage,避免 @peer 前缀和递归触发。 */
6893
+ async deliverProbeText(channelId, context, text) {
6894
+ const delivery = context?.delivery ?? { chatType: 'private' };
6895
+ let finalText = text;
6896
+ if (Buffer.byteLength(finalText, 'utf-8') > 4096) {
6897
+ finalText += `\n[TRUNCATED]`;
6898
+ }
6899
+ if (this.connected && this.client) {
6900
+ const probeEntry = {
6901
+ id: `echo-${Date.now()}-${crypto.randomBytes(2).toString('hex')}`,
6902
+ ts: Date.now(),
6903
+ aid: this.config.aid,
6904
+ channelId,
6905
+ delivery,
6906
+ type: 'text',
6907
+ text: finalText,
6908
+ context: this.withDelivery(context, delivery),
6909
+ ttl: 300_000,
6910
+ };
6911
+ const ok = await this.deliverTextEntry(probeEntry);
6912
+ if (ok.status !== 'sent' && ok.status !== 'permanent') {
6913
+ outbox.enqueue(this.config.aid, {
6914
+ channelId,
6915
+ delivery,
6916
+ type: 'text',
6917
+ text: finalText,
6918
+ context: this.withDelivery(context, delivery),
6919
+ });
6920
+ }
6921
+ }
6922
+ else {
6923
+ outbox.enqueue(this.config.aid, {
6924
+ channelId,
6925
+ delivery,
6926
+ type: 'text',
6927
+ text: finalText,
6928
+ context: this.withDelivery(context, delivery),
6929
+ });
6930
+ logger.warn(`${this.logPrefix()} [Echo] not connected, probe reply queued in outbox mid=…`);
6931
+ }
6932
+ }
6933
+ async flushPendingEcho(channelId, delivery, threadId, agentOutput) {
6934
+ // echo.ecdiag:agent 提前回复,立即收口(不等观察窗口走完)
6935
+ for (const [mid, probe] of this.pendingEcdiag) {
6936
+ if (probe.channelId === channelId
6937
+ && (probe.context?.threadId ?? '') === (threadId ?? '')
6938
+ && (probe.context?.delivery?.chatType ?? 'private') === delivery.chatType) {
6939
+ void this.finishEcdiag(mid, 'agent');
6940
+ break;
6941
+ }
6942
+ }
6943
+ // 查找该 channelId 是否有 pending echo(echo.ask 等待 agent 首次回复)
6464
6944
  for (const [key, echo] of this.pendingEchoMessages) {
6465
6945
  if (echo.channelId === channelId
6466
6946
  && (echo.context?.threadId ?? '') === (threadId ?? '')
6467
6947
  && echo.context?.delivery?.chatType === delivery.chatType) {
6468
6948
  this.pendingEchoMessages.delete(key);
6469
- logger.info(`${this.logPrefix()} [Echo] flushPendingEcho triggered: key=${key} channelId=${channelId} pendingCount=${this.pendingEchoMessages.size}`);
6949
+ logger.info(`${this.logPrefix()} [Echo] flushPendingEcho triggered: key=${key} kind=${echo.probeKind} channelId=${channelId} pendingCount=${this.pendingEchoMessages.size}`);
6470
6950
  const agentDoneTs = Date.now();
6471
6951
  const agentDuration = agentDoneTs - echo.receiveTs;
6952
+ const ver = readInstalledEvolcoreVersion();
6472
6953
  let echoText = echo.text;
6473
- echoText += `\n${echoTraceClock(agentDoneTs)} [EvolCore.agent] duration=${agentDuration}ms${echoTraceOriginLabel(agentDoneTs)}`;
6954
+ // echo.ask:agent 行 → 空行 → agent 回复正文 → 空行 → reply 行
6955
+ echoText += `\n${echoTraceLine({
6956
+ node: 'EvolCore.agent',
6957
+ dir: 'fwd',
6958
+ hop: echoTraceNextHop(echoText),
6959
+ ver,
6960
+ now: agentDoneTs,
6961
+ extra: `duration=${agentDuration}ms`,
6962
+ })}`;
6963
+ if (agentOutput)
6964
+ echoText += `\n\n${agentOutput}\n`;
6474
6965
  const replyTs = Date.now();
6475
- echoText += `\n${echoTraceClock(replyTs)} [EvolCore.reply] echo回声发出 conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoTraceOriginLabel(replyTs)}`;
6966
+ echoText += `\n${echoTraceLine({
6967
+ node: 'EvolCore.reply',
6968
+ dir: 'ret',
6969
+ hop: echoTraceNextHop(echoText),
6970
+ ver,
6971
+ now: replyTs,
6972
+ extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
6973
+ })}`;
6476
6974
  if (Buffer.byteLength(echoText, 'utf-8') > 4096) {
6477
6975
  echoText += `\n[TRUNCATED]`;
6478
6976
  }
@@ -7784,9 +8282,18 @@ export class AUNChannel {
7784
8282
  */
7785
8283
  async disconnect(clientCloseBudgetMs) {
7786
8284
  this.prepareShutdown();
7787
- if (this.client) {
7788
- unregisterSameOwnerClient(this.config.aid, this.client);
7789
- ownerResolver.detachClient(this.config.aid, this.client);
8285
+ const generation = this.reconnectGeneration;
8286
+ // Retire the pointers before awaiting close: a later connect owns its own
8287
+ // resources and must not be cleared by this disconnect's continuation.
8288
+ const client = this.client;
8289
+ const store = this.store;
8290
+ this.client = null;
8291
+ this.store = null;
8292
+ this.connected = false;
8293
+ this.clearQueuedObserverSends('intentional disconnect');
8294
+ if (client) {
8295
+ unregisterSameOwnerClient(this.config.aid, client);
8296
+ ownerResolver.detachClient(this.config.aid, client);
7790
8297
  }
7791
8298
  this.managedMenuClient.close();
7792
8299
  this.intentionalDisconnect = true;
@@ -7794,10 +8301,10 @@ export class AUNChannel {
7794
8301
  clearTimeout(this.reconnectTimer);
7795
8302
  this.reconnectTimer = null;
7796
8303
  }
7797
- if (this.client) {
8304
+ if (client) {
7798
8305
  this.trace('OUT', 'client.close', { reason: 'disconnect' });
7799
8306
  // 未等到 close 的 promise 可能稍后 reject(握手被进程退出截断),全程吞掉以免 unhandledRejection。
7800
- const closing = this.client.close().catch(() => { });
8307
+ const closing = client.close().catch(() => { });
7801
8308
  try {
7802
8309
  if (clientCloseBudgetMs === undefined) {
7803
8310
  await closing;
@@ -7820,17 +8327,28 @@ export class AUNChannel {
7820
8327
  catch (e) {
7821
8328
  this.trace('OUT', 'client.close.error', { reason: 'disconnect', error: String(e) });
7822
8329
  }
7823
- this.client = null;
7824
8330
  }
7825
- if (this.store) {
8331
+ if (store) {
7826
8332
  try {
7827
- this.store.close();
8333
+ store.close();
7828
8334
  }
7829
8335
  catch { /* ignore */ }
7830
- this.store = null;
7831
8336
  }
7832
- this.connected = false;
7833
- this.clearQueuedObserverSends('intentional disconnect');
8337
+ if (generation !== this.reconnectGeneration || !this.intentionalDisconnect)
8338
+ return;
8339
+ // 服务路由实例随 channel 一起释放。`routers` 是模块级单例表,不释放的话
8340
+ // `ec agent stop` / `disable` / `delete` 之后实例仍留在里面:同名 agent 重建时
8341
+ // `getServiceRouter` 从表里捞回旧对象,`started` 仍是 true,`ensureStarted` 直接
8342
+ // 短路——新装或改过的包不会被重扫,要等手工 `ec services reload`。更糟的是
8343
+ // deps 里 `getProjectPath` / `resolvePeerRole` 闭包捕获的是旧 channel(旧的工程
8344
+ // 目录、旧的 channelKey),服务脚本会按旧沙箱跑。`peekServiceRouter` 还被
8345
+ // ECK 的 hasServicePacks 读着,僵尸实例会让 prompt 里继续留着 `[services]` 段。
8346
+ //
8347
+ // 重连不走这里(SDK 指数退避 + `takeoverReconnect`,均不调 `disconnect()`),
8348
+ // 所以网络抖动不会误杀 router。进程退出路径(`disconnectAll`)会多跑一次,
8349
+ // 此时 Map 随进程消失,`releaseServiceRouter` 找不到条目直接 return,无副作用。
8350
+ this.serviceRouter = null;
8351
+ releaseServiceRouter(this.config.aid);
7834
8352
  appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'disconnected', aid: this.config.aid, reason: 'intentional' });
7835
8353
  appendAidLifecycle({ ts: Date.now(), iso: new Date().toISOString(), event: 'disconnected', aid: this.config.aid, reason: 'intentional' });
7836
8354
  this.setAidStatus('disabled');
@@ -7844,13 +8362,14 @@ export class AUNChannel {
7844
8362
  // SDK 内部已经跑无限指数退避(max_attempts=0, max_delay=300s),
7845
8363
  // TS 层只负责:(1) initClient 失败时安排兜底重试;(2) flap/kicked 接管路径见 takeoverReconnect。
7846
8364
  scheduleReconnect() {
7847
- // initClient 早期失败(auth / connect 阶段)走这里:用 fallback 延迟兜底
8365
+ // 初始化任一阶段失败都沿用 fallback 延迟兜底,不占用首连队列槽位。
7848
8366
  this.takeoverReconnect(AUNChannel.FALLBACK_DELAY_MS, 'terminal');
7849
8367
  }
7850
8368
  /** Manually trigger reconnect (e.g. from /check reconnect command) */
7851
8369
  async reconnect() {
7852
8370
  if (this.connected)
7853
8371
  return '已连接,无需重连';
8372
+ const generation = this.reconnectGeneration;
7854
8373
  if (this.reconnectTimer) {
7855
8374
  clearTimeout(this.reconnectTimer);
7856
8375
  this.reconnectTimer = null;
@@ -7858,10 +8377,18 @@ export class AUNChannel {
7858
8377
  this.flapCount = 0;
7859
8378
  try {
7860
8379
  await this.initClient();
8380
+ this.assertInitializationActive(generation);
8381
+ this.assertNoGatewayRejection();
7861
8382
  return `重连成功 (${this._aid})`;
7862
8383
  }
7863
8384
  catch (err) {
7864
- this.scheduleReconnect();
8385
+ if (this.intentionalDisconnect || err?.code === 'AUN_CONNECT_CANCELLED') {
8386
+ return '重连已取消:渠道已停止或连接已被替换';
8387
+ }
8388
+ if (this.aidState.status === 'kicked_no_retry')
8389
+ return `重连失败: ${err},已停止自动重试`;
8390
+ if (generation === this.reconnectGeneration)
8391
+ this.scheduleReconnect();
7865
8392
  return `重连失败: ${err},已安排自动重试`;
7866
8393
  }
7867
8394
  }
@@ -8622,3 +9149,20 @@ export class AUNChannelPlugin {
8622
9149
  };
8623
9150
  }
8624
9151
  }
9152
+ /** Per-message authenticated metadata. Never read the Agent's mutable model here:
9153
+ * an in-flight turn must keep its model even after a configuration change. */
9154
+ export function aunProtectedHeaders(context) {
9155
+ const headers = {};
9156
+ const raw = context?.metadata?.protectedHeaders;
9157
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
9158
+ for (const [key, value] of Object.entries(raw)) {
9159
+ const name = key.trim().toLowerCase();
9160
+ if (/^[a-z0-9_-]+$/.test(name) && typeof value === 'string')
9161
+ headers[name] = value;
9162
+ }
9163
+ }
9164
+ const model = context?.model?.trim();
9165
+ if (model)
9166
+ headers.model = model;
9167
+ return Object.keys(headers).length > 0 ? headers : undefined;
9168
+ }