evolcore 0.0.47 → 0.0.49

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 (266) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +143 -40
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +36 -17
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/msg/p2p.js +2 -1
  14. package/dist/aun/service-proxy.js +4 -2
  15. package/dist/build-identity.json +1 -0
  16. package/dist/channels/aun.js +722 -295
  17. package/dist/channels/daemon.js +9 -25
  18. package/dist/cli/aun-commands.js +86 -51
  19. package/dist/cli/code-stats.js +19 -8
  20. package/dist/cli/command-log.js +1 -1
  21. package/dist/cli/daemon-commands.js +44 -43
  22. package/dist/cli/directory.js +13 -2
  23. package/dist/cli/ecmsg-gateway.js +5 -2
  24. package/dist/cli/index.js +9 -9
  25. package/dist/cli/init-channel.js +4 -6
  26. package/dist/cli/init.js +72 -50
  27. package/dist/cli/invoke-command.js +1 -1
  28. package/dist/cli/managed-command-guard.js +2 -0
  29. package/dist/cli/model.js +20 -5
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/quota.js +89 -0
  32. package/dist/cli/role.js +62 -17
  33. package/dist/cli/services-command.js +1 -0
  34. package/dist/cli/stats.js +3 -3
  35. package/dist/cli/team-workspace-command.js +56 -2
  36. package/dist/cli/thread-command.js +16 -51
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-field-policy.js +71 -1
  40. package/dist/config/config-manager.js +13 -7
  41. package/dist/config/daemon-services.js +30 -3
  42. package/dist/config/gateway-config.js +2 -2
  43. package/dist/config/invoke-ipc-service.js +6 -4
  44. package/dist/config/peer-bind-code.js +3 -4
  45. package/dist/config/peer-book-store.js +62 -229
  46. package/dist/config/peer-book.js +26 -27
  47. package/dist/config/peer-role-resolver.js +16 -1
  48. package/dist/config/provider-identity-migration.js +4 -1
  49. package/dist/config/provider-ipc-service.js +56 -11
  50. package/dist/config/provider-menu-request.js +24 -5
  51. package/dist/config/provider-templates.js +127 -0
  52. package/dist/config/providers-config.js +67 -12
  53. package/dist/config/providers-management.js +477 -51
  54. package/dist/config/resolved-config-op.js +3 -2
  55. package/dist/config/role-command-service.js +248 -1
  56. package/dist/config/schema-migration.js +105 -4
  57. package/dist/core/agent-application-service.js +6 -1
  58. package/dist/core/agent-runtime.js +4 -0
  59. package/dist/core/auth/agent-delegation.js +2 -1
  60. package/dist/core/auth/auth-gateway.js +2 -1
  61. package/dist/core/auth/delegation-authorization.js +36 -26
  62. package/dist/core/auth/operation-authorizer.js +25 -0
  63. package/dist/core/auth/operation-catalog.js +37 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/cli-intent-parser.js +13 -0
  68. package/dist/core/command/command-handler.js +126 -87
  69. package/dist/core/command/menu-catalog.js +1 -0
  70. package/dist/core/command/menu-handler.js +67 -150
  71. package/dist/core/command/menu-protocol.js +31 -1
  72. package/dist/core/command/provider-menu.js +13 -3
  73. package/dist/core/command/remote-shell.js +565 -0
  74. package/dist/core/command/role-menu.js +47 -23
  75. package/dist/core/command/slash-handler.js +26 -43
  76. package/dist/core/command/team-workspace-items.js +81 -12
  77. package/dist/core/command/team-workspace-team.js +9 -71
  78. package/dist/core/command/topic-slash.js +9 -30
  79. package/dist/core/daemon-bootstrap.js +8 -1
  80. package/dist/core/daemon-control.js +64 -8
  81. package/dist/core/daemon-lifecycle.js +16 -2
  82. package/dist/core/evolagent-registry.js +20 -3
  83. package/dist/core/file-integrity/store.js +2 -0
  84. package/dist/core/handoff/runtime.js +37 -1
  85. package/dist/core/inference/text-inference.js +3 -1
  86. package/dist/core/initialization/service.js +11 -6
  87. package/dist/core/interaction-router.js +3 -0
  88. package/dist/core/invoke/executors/text.js +72 -19
  89. package/dist/core/ipc-registration.js +3 -1
  90. package/dist/core/message/aun-ipc-sender.js +279 -107
  91. package/dist/core/message/contact-admission.js +91 -6
  92. package/dist/core/message/contact-pending-inbound.js +113 -0
  93. package/dist/core/message/contact-thread-approval.js +212 -0
  94. package/dist/core/message/im-renderer.js +41 -2
  95. package/dist/core/message/message-admission.js +5 -39
  96. package/dist/core/message/message-bridge.js +140 -370
  97. package/dist/core/message/message-log.js +29 -0
  98. package/dist/core/message/message-queue.js +119 -15
  99. package/dist/core/message/message-utils.js +8 -0
  100. package/dist/core/message/response-engine.js +580 -134
  101. package/dist/core/message/send-routing.js +5 -1
  102. package/dist/core/model/catalog-service.js +31 -11
  103. package/dist/core/model/config-scope.js +6 -14
  104. package/dist/core/model/model-capabilities.js +22 -4
  105. package/dist/core/model/model-catalog.js +1 -0
  106. package/dist/core/model/model-diagnostics.js +19 -0
  107. package/dist/core/model/model-fallback.js +13 -2
  108. package/dist/core/ownership/owner-resolver.js +328 -50
  109. package/dist/core/pack-auth.js +3 -0
  110. package/dist/core/pack-install.js +1 -1
  111. package/dist/core/permission/ec-command-parser.js +106 -19
  112. package/dist/core/permission/protected-paths.js +6 -6
  113. package/dist/core/permission/services-path-acl.js +451 -0
  114. package/dist/core/permission/tool-policy.js +5 -1
  115. package/dist/core/relation/peer-identity.js +36 -1
  116. package/dist/core/relation/same-owner-proof.js +81 -112
  117. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  118. package/dist/core/session/session-file-health.js +13 -7
  119. package/dist/core/session/session-fs-store.js +91 -35
  120. package/dist/core/session/session-manager.js +68 -24
  121. package/dist/core/session/session-mapper.js +14 -34
  122. package/dist/core/session/session-transcript.js +5 -1
  123. package/dist/core/task/task-activity-store.js +84 -0
  124. package/dist/core/task/task-recovery-service.js +13 -0
  125. package/dist/core/thread/command-parser.js +7 -12
  126. package/dist/core/thread/thread-context-storage.js +3 -2
  127. package/dist/core/thread/thread-operation.js +2 -13
  128. package/dist/core/thread/thread-service.js +15 -46
  129. package/dist/core/thread/topic-id.js +15 -0
  130. package/dist/directory/owner-directory-admission.js +12 -9
  131. package/dist/directory/owner-directory-cache.js +64 -28
  132. package/dist/directory/owner-directory-markdown.js +14 -2
  133. package/dist/directory/owner-directory-policy.js +5 -30
  134. package/dist/directory/owner-directory-query-operation.js +29 -3
  135. package/dist/directory/owner-directory-remarks.js +11 -3
  136. package/dist/directory/owner-directory-request-operation.js +5 -2
  137. package/dist/eck/kit-renderer.js +1 -1
  138. package/dist/eck/message-renderer.js +112 -29
  139. package/dist/ecweb/basic-settings-service.js +3 -1
  140. package/dist/ecweb/message-context-service.js +1 -1
  141. package/dist/ecweb/pairing.js +4 -3
  142. package/dist/ecweb/providers-service.js +26 -1
  143. package/dist/ecweb/runtime/lifecycle.js +18 -8
  144. package/dist/ecweb/runtime/proxy-access.js +74 -0
  145. package/dist/ecweb/runtime/supervisor.js +36 -6
  146. package/dist/event-center/center-config.js +9 -5
  147. package/dist/event-center/dispatcher.js +10 -1
  148. package/dist/event-center/ipc-operation.js +19 -0
  149. package/dist/event-center/registry.js +29 -3
  150. package/dist/event-center/runtime.js +106 -11
  151. package/dist/event-center/script-runner.js +5 -5
  152. package/dist/index.js +96 -59
  153. package/dist/ipc.js +38 -3
  154. package/dist/outputs/authorization.js +16 -0
  155. package/dist/outputs/cards.js +336 -0
  156. package/dist/outputs/events.js +63 -0
  157. package/dist/outputs/protocol.js +103 -0
  158. package/dist/outputs/service.js +266 -0
  159. package/dist/paths.js +3 -0
  160. package/dist/proxy/manager.js +43 -13
  161. package/dist/services/index.js +114 -5
  162. package/dist/services/ipc-operation.js +88 -15
  163. package/dist/services/pack-manager.js +13 -1
  164. package/dist/services/router.js +21 -6
  165. package/dist/services/script-runner.js +5 -4
  166. package/dist/services/service-payload.js +13 -7
  167. package/dist/services/validation.js +1 -1
  168. package/dist/stats/budget.js +2 -2
  169. package/dist/stats/db.js +19 -0
  170. package/dist/stats/index.js +1 -1
  171. package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
  172. package/dist/stats/normalizer.js +2 -0
  173. package/dist/stats/query.js +35 -27
  174. package/dist/stats/quota-query.js +95 -0
  175. package/dist/stats/role-budget.js +5 -2
  176. package/dist/stats/writer.js +10 -6
  177. package/dist/trigger/audit.js +7 -0
  178. package/dist/trigger/authorization.js +105 -11
  179. package/dist/trigger/feedback.js +10 -0
  180. package/dist/trigger/history.js +37 -11
  181. package/dist/trigger/ipc-service.js +12 -1
  182. package/dist/trigger/manager.js +1 -0
  183. package/dist/trigger/scheduler.js +7 -5
  184. package/dist/trigger/script-executor.js +2 -1
  185. package/dist/trigger/script-sandbox.js +21 -3
  186. package/dist/trigger/validation.js +22 -0
  187. package/dist/utils/atomic-write.js +22 -8
  188. package/dist/utils/cross-platform.js +73 -26
  189. package/dist/utils/error-dict.json +94 -4
  190. package/dist/utils/error-utils.js +27 -4
  191. package/dist/utils/evolcore-version.js +36 -65
  192. package/dist/utils/host-info.js +100 -1
  193. package/dist/utils/msg-diag.js +1 -0
  194. package/dist/utils/npm-ops.js +43 -8
  195. package/dist/utils/process-introspect.js +12 -7
  196. package/dist/utils/process-tree.js +50 -2
  197. package/dist/utils/windows-shell-trust.js +2 -0
  198. package/dist/workbench/protocol.js +80 -0
  199. package/dist/workbench/service.js +359 -0
  200. package/ecagent/dist/types.d.ts +6 -2
  201. package/kits/docs/context-assembly.md +1 -1
  202. package/kits/docs/evolcore/INDEX.md +4 -2
  203. package/kits/docs/evolcore/aid.md +25 -0
  204. package/kits/docs/evolcore/config.md +16 -1
  205. package/kits/docs/evolcore/directory.md +30 -12
  206. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  207. package/kits/docs/evolcore/model.md +10 -0
  208. package/kits/docs/evolcore/msg.md +9 -0
  209. package/kits/docs/evolcore/peer.md +19 -65
  210. package/kits/docs/evolcore/provider.md +124 -4
  211. package/kits/docs/evolcore/quota.md +54 -0
  212. package/kits/docs/evolcore/role.md +83 -0
  213. package/kits/docs/evolcore/services.md +6 -6
  214. package/kits/docs/evolcore/stats.md +2 -0
  215. package/kits/docs/evolcore/team-workspace.md +1 -1
  216. package/kits/docs/evolcore/thread-chain.md +14 -15
  217. package/kits/docs/evolcore/tool-authorization.md +5 -0
  218. package/kits/docs/evolcore/trigger.md +12 -0
  219. package/kits/eck_message_manifest.json +12 -0
  220. package/kits/provider-templates.json +1213 -0
  221. package/kits/rules/04-relation.md +3 -3
  222. package/kits/schemas/_meta.json +14 -2
  223. package/kits/schemas/agent-config.schema.20.json +24 -0
  224. package/kits/schemas/contact-book.schema.4.json +52 -0
  225. package/kits/schemas/providers.schema.3.json +200 -0
  226. package/kits/skills/.switches.json +8 -0
  227. package/kits/skills/ability/references/calling.md +1 -1
  228. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  229. package/kits/skills/ec-group/SKILL.md +2 -2
  230. package/kits/skills/ec-identity/SKILL.md +19 -72
  231. package/kits/skills/ec-provider/SKILL.md +270 -0
  232. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  233. package/kits/skills/ec-trigger/SKILL.md +1 -1
  234. package/kits/skills/thread-ops/SKILL.md +34 -21
  235. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  236. package/kits/templates/message-fragments/group-batch.md +1 -1
  237. package/kits/templates/message-fragments/inject-default.md +1 -1
  238. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  239. package/kits/templates/message-fragments/item-group.md +1 -1
  240. package/kits/templates/message-fragments/item-private.md +1 -1
  241. package/kits/templates/message-fragments/thread-context.md +1 -1
  242. package/kits/templates/message-fragments/trigger-session.md +1 -1
  243. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  244. package/kits/templates/roles/admin.json +2 -19
  245. package/kits/templates/roles/member.json +0 -3
  246. package/kits/templates/roles/visitor.json +1 -0
  247. package/kits/templates/system-fragments/baseagent.md +6 -0
  248. package/kits/templates/system-fragments/commands.md +4 -3
  249. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  250. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  251. package/kits/templates/system-fragments/relation.md +1 -1
  252. package/kits/templates/system-fragments/thread.md +7 -5
  253. package/kits/templates/system-fragments/venue.md +11 -0
  254. package/package.json +6 -4
  255. package/scripts/agent-template/inspect.mjs +50 -11
  256. package/scripts/agent-template/shared/common.mjs +11 -6
  257. package/scripts/agent-template/shared/team-schema.json +6 -4
  258. package/scripts/agent-template/shared/template-contract.mjs +62 -11
  259. package/scripts/agent-template/shared/template-package.mjs +189 -21
  260. package/scripts/agent-template/shared/template-runtime.mjs +54 -6
  261. package/scripts/agent-template/shared/template.mjs +2 -2
  262. package/scripts/agent-template/team-pack.mjs +52 -14
  263. package/dist/cli/peer.js +0 -127
  264. package/dist/config/peer-operation-service.js +0 -132
  265. package/dist/config/peer-request-service.js +0 -532
  266. package/dist/core/command/connect-menu.js +0 -624
@@ -1,3 +1,4 @@
1
+ import { trustedContactInboundDelivery } from './contact-pending-inbound.js';
1
2
  import { loadAgent } from '../../config-store.js';
2
3
  import { subscribeUpgradeJob } from '../../utils/upgrade-jobs.js';
3
4
  import { initializationBlocksTasks } from '../../cli/agent-create.js';
@@ -10,34 +11,31 @@ import { containsAgentMdMenuRequest } from '../command/agentmd-menu-request.js';
10
11
  import { currentContactBinding, sameContactBinding } from './contact-admission.js';
11
12
  import { logger, logPreview } from '../../utils/logger.js';
12
13
  import { StreamDebouncer } from './stream-debouncer.js';
13
- import { appendMessageLog, appendMessageLogStrict, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
14
- import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from './message-utils.js';
14
+ import { appendMessageLog, appendMessageLogStrict, appendInboundMessageLogOnce, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
15
+ import { buildEnvelope } from './message-utils.js';
15
16
  import { chatDirPath } from '../session/session-fs-store.js';
16
- import { readTopicLabel, readTopicStatus } from '../session/session-mapper.js';
17
+ import { readTopicStatus } from '../session/session-mapper.js';
17
18
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
18
19
  import { agentDir, resolvePaths } from '../../paths.js';
19
- import { listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
20
+ import { resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
20
21
  import { resolvePeerView, resolvePeerDisplayLabel, resolvePrincipal } from '../../config/peer-book.js';
21
- import { findPeerRequestNote, expirePendingPeerRequests, reviewPeerRequest, submitPeerRequest, peerRequestSubmissionProtocolResult, queryOwnPeerRequestStatus, } from '../../config/peer-request-service.js';
22
22
  import { isValidAid } from '../../aun/aid/validation.js';
23
23
  import { prepareOwnerDirectoryAdmission } from '../../directory/owner-directory-admission.js';
24
24
  import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
25
25
  import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
26
- import { isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
26
+ import { isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
27
27
  import { resolveEffective } from '../../config/config-manager.js';
28
28
  import { createDecisionInferenceProvider } from '../inference/text-inference.js';
29
29
  import { AutoMentionGate } from './auto-mention-gate.js';
30
30
  import { syncGroupRulesContext } from '../../eck/group-rules-sync.js';
31
31
  import { readSoulContent } from '../soul.js';
32
32
  import { authorizeAccess, buildAuthSubject } from '../auth/auth-gateway.js';
33
- import { MenuDiagnosticLimiter, deliverMenuResponse, isRetryableMenuTransportError, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, beginMenuDeliveryTiming, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, } from '../command/menu-protocol.js';
33
+ import { MenuDiagnosticLimiter, deliverMenuResponse, isRetryableMenuTransportError, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, beginMenuDeliveryTiming, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, traceMenuStage, } from '../command/menu-protocol.js';
34
34
  import { resolveExplicitMenuExecutionContext, validateMenuCatalogArgs, validateMenuValueBatchArgs } from '../command/menu-catalog.js';
35
35
  import { MenuTokenStore } from '../command/menu-token-store.js';
36
36
  import { SessionRenewService } from '../session/session-renew.js';
37
37
  import { createRootCausation, deriveCausation, normalizeCausation } from '../causation/context.js';
38
38
  import { recordCausationSpan } from '../causation/audit.js';
39
- import { renderActionAsText } from '../interaction-router.js';
40
- import { planApprovalRoute } from '../permission/approval-gateway.js';
41
39
  import { guardGroupSlashCommand, parseFullAccessCommand } from '../command/slash-gate.js';
42
40
  import { createAgentPolicyAuthorization, createSessionFullAccessAuthorization } from '../role/runtime-policy.js';
43
41
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
@@ -48,6 +46,22 @@ const REJECTABLE_PEER_TYPES = new Set(['ai', 'bot', 'agent', 'service']);
48
46
  const REJECTION_MAX = 3;
49
47
  const REJECTION_WINDOW_MS = 60 * 60 * 1000;
50
48
  const rejectionState = new Map();
49
+ /**
50
+ * Topic admission runs after session resolution and before task queueing.
51
+ *
52
+ * 纯函数,导出以便单测直接覆盖各状态组合(回退 / 丢弃 / 是否回文案)。
53
+ */
54
+ export function decideTopicInbound(input) {
55
+ if (!input.isTopic)
56
+ return { action: 'proceed', reopen: false, replyArchived: false };
57
+ if (input.topicStatus === 'archived') {
58
+ return { action: 'drop-archived', reopen: false, replyArchived: input.chatType !== 'group' };
59
+ }
60
+ if (input.topicStatus === 'closed') {
61
+ return { action: 'proceed', reopen: true, replyArchived: false };
62
+ }
63
+ return { action: 'proceed', reopen: false, replyArchived: false };
64
+ }
51
65
  export function shouldBlockInboundContact(input) {
52
66
  if (!input.selfAid) {
53
67
  return { blocked: false, status: 'unsupported-channel' };
@@ -467,175 +481,6 @@ export class MessageBridge {
467
481
  }
468
482
  return false;
469
483
  }
470
- async handleContactRequestProtocol(input) {
471
- const { context, msg, content, owningAgent, adapter, sendReply } = input;
472
- const requestMatch = /^\s*\/request(?:\s+([\s\S]*?))?\s*$/i.exec(content);
473
- let protocolType;
474
- let protocolPayload;
475
- try {
476
- const parsed = JSON.parse(content);
477
- protocolPayload = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
478
- ? parsed
479
- : undefined;
480
- protocolType = protocolPayload?.type === 'contact.request.query'
481
- ? 'query'
482
- : protocolPayload?.type === 'contact.request.submit' ? 'submit' : undefined;
483
- }
484
- catch { /* slash command */ }
485
- if (!requestMatch && !protocolType)
486
- return false;
487
- if (context.channelType === 'aun') {
488
- // The App owns requests; retired commands cannot create a second approval state.
489
- return true;
490
- }
491
- // Slash commands keep their human-facing response semantics. Structured
492
- // App requests use contact.request.response and never fall through to the
493
- // normal command/session pipeline.
494
- if (requestMatch) {
495
- // Blacklist remains the first gate even though slash controls are
496
- // recognized before ordinary admission. Let the normal blocked path
497
- // decide whether an agent/bot/service gets a limited rejection.
498
- if (context.contactStatus === 'blocked')
499
- return false;
500
- if (context.channelType !== 'aun') {
501
- await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
502
- return true;
503
- }
504
- if (context.chatType !== 'private') {
505
- await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
506
- return true;
507
- }
508
- if (!context.primaryId || context.principal?.principalStatus !== 'native_aid') {
509
- await this.sendAdmissionControlReply(context, msg, sendReply, '无法验证当前 AUN 身份,未提交联系人申请。');
510
- return true;
511
- }
512
- try {
513
- const submission = await submitPeerRequest({
514
- selfAid: context.selfAid,
515
- applicantAid: context.primaryId,
516
- note: requestMatch[1],
517
- sourceChannelKey: context.channelKey,
518
- routeKind: 'private',
519
- });
520
- if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
521
- void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
522
- .catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
523
- }
524
- await this.sendAdmissionControlReply(context, msg, sendReply, this.contactRequestReply(submission));
525
- }
526
- catch (error) {
527
- logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
528
- await this.sendAdmissionControlReply(context, msg, sendReply, '当前无法受理联系人申请,请稍后再试。');
529
- }
530
- return true;
531
- }
532
- // The structured protocol is AUN-only. For a blocked external alias,
533
- // return false so the existing blacklist response/silence policy applies;
534
- // never emit a custom payload through a non-AUN adapter.
535
- if (context.contactStatus === 'blocked' && context.channelType !== 'aun')
536
- return false;
537
- if (context.channelType !== 'aun')
538
- return true;
539
- if (context.chatType !== 'private')
540
- return true;
541
- if (context.principal?.principalStatus !== 'native_aid' || !context.primaryId) {
542
- await this.sendContactRequestProtocolResponse(adapter, msg, {
543
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
544
- }, owningAgent?.name);
545
- return true;
546
- }
547
- if (context.contactStatus === 'blocked') {
548
- await this.sendContactRequestProtocolResponse(adapter, msg, {
549
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
550
- }, owningAgent?.name);
551
- return true;
552
- }
553
- let result;
554
- if (protocolType === 'query') {
555
- try {
556
- result = await queryOwnPeerRequestStatus({
557
- selfAid: context.selfAid,
558
- applicantAid: context.primaryId,
559
- requestId: protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'request_id')
560
- ? protocolPayload.request_id
561
- : undefined,
562
- });
563
- }
564
- catch (error) {
565
- logger.warn(`[MessageBridge] Contact request query failed: ${error instanceof Error ? error.message : String(error)}`);
566
- result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
567
- }
568
- }
569
- else {
570
- try {
571
- if (protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'note')
572
- && typeof protocolPayload?.note !== 'string') {
573
- await this.sendContactRequestProtocolResponse(adapter, msg, {
574
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
575
- }, owningAgent?.name);
576
- return true;
577
- }
578
- const submission = await submitPeerRequest({
579
- selfAid: context.selfAid,
580
- applicantAid: context.primaryId,
581
- note: typeof protocolPayload?.note === 'string' ? protocolPayload.note : undefined,
582
- sourceChannelKey: context.channelKey,
583
- routeKind: 'private',
584
- });
585
- result = peerRequestSubmissionProtocolResult(submission);
586
- if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
587
- void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
588
- .catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
589
- }
590
- }
591
- catch (error) {
592
- logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
593
- result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
594
- }
595
- }
596
- await this.sendContactRequestProtocolResponse(adapter, msg, result, owningAgent?.name);
597
- return true;
598
- }
599
- contactRequestReply(result) {
600
- switch (result.code) {
601
- case 'submitted': return '联系人申请已提交,等待管理员审核。';
602
- case 'resubmitted': return '联系人申请已更新,等待管理员审核。';
603
- case 'already-contact': return '你已经是联系人。';
604
- case 'owner': return '你已经是 Owner。';
605
- case 'blocked': return CONTACT_REJECTION_NOTICE;
606
- case 'rate-limited': return '联系人申请过于频繁,请稍后再试。';
607
- case 'capacity': return '当前申请较多,请稍后再试。';
608
- case 'no-owner': return '当前无法受理联系人申请。';
609
- case 'invalid-applicant': return '无法验证当前 AUN 身份,未提交联系人申请。';
610
- case 'invalid-note': return '申请说明不能超过 500 个字符。';
611
- }
612
- }
613
- async sendContactRequestProtocolResponse(adapter, msg, result, agentName) {
614
- if (!adapter?.send)
615
- return;
616
- await adapter.send(buildEnvelope({
617
- taskId: `contact-request-${randomBytes(4).toString('hex')}`,
618
- channel: adapter.channelName,
619
- channelId: msg.channelId,
620
- agentName: agentName ?? '<unknown>',
621
- replyContext: {
622
- ...(msg.replyContext ?? {}),
623
- metadata: {
624
- ...(msg.replyContext?.metadata ?? {}),
625
- ...evolMenuResponseTransportMetadata(msg.protectedHeaders?.sdk_version),
626
- },
627
- },
628
- }), {
629
- kind: 'custom',
630
- channelType: 'aun',
631
- payload: {
632
- type: 'contact.request.response',
633
- status: result.status,
634
- request_id: result.requestId,
635
- expires_at: result.expiresAt,
636
- },
637
- });
638
- }
639
484
  async sendAdmissionControlReply(context, msg, sendReply, text) {
640
485
  if (!text || !consumeAdmissionReplyBudget(context))
641
486
  return false;
@@ -685,155 +530,6 @@ export class MessageBridge {
685
530
  }
686
531
  return '当前不接受非联系人消息。联系人申请仅支持 AUN 私聊。';
687
532
  }
688
- async deliverContactReviewCard(selfAid, applicantAid, submission, owningAgent) {
689
- if (!this.interactionRouter || !submission.requestId || !submission.expiresAt || !submission.submittedAt) {
690
- return false;
691
- }
692
- const ownerAdapterKey = formatChannelKey({ type: 'aun', selfAID: selfAid, name: 'main' });
693
- const ownerAdapter = this.processor.getChannelInfo?.(ownerAdapterKey)?.adapter;
694
- const resolveApproverCandidates = () => ({
695
- owners: listStaticAgentOwners(selfAid, { fresh: true }),
696
- admins: listStaticAgentAdmins(selfAid, { fresh: true }),
697
- });
698
- const { owners, admins } = resolveApproverCandidates();
699
- const route = planApprovalRoute({
700
- id: submission.requestId,
701
- sessionId: `contact-request:${selfAid}:${submission.requestId}`,
702
- toolName: 'contact.request.review',
703
- toolInput: { applicantAid, requestId: submission.requestId },
704
- summary: `Review contact request from ${applicantAid}`,
705
- grantable: true,
706
- // Contact membership is an Agent-owner decision. Do not use the broader
707
- // agent_manager policy here: that policy intentionally prefers an Admin,
708
- // which made request cards invisible to the configured Owner.
709
- approverPolicy: 'agent_owner',
710
- createdAt: Date.parse(submission.submittedAt),
711
- }, {
712
- userId: applicantAid,
713
- chatType: 'private',
714
- selfAid,
715
- approvalRouting: {
716
- approverPolicy: 'agent_owner',
717
- owners,
718
- admins,
719
- resolveApproverCandidates,
720
- ownerAdapter,
721
- forceHandoff: true,
722
- selfAid,
723
- originSessionId: `contact-request:${selfAid}:${submission.requestId}`,
724
- originChannel: 'aun',
725
- originChannelId: applicantAid,
726
- originPeerId: applicantAid,
727
- originPrincipalId: applicantAid,
728
- },
729
- });
730
- if (route.kind !== 'handoff') {
731
- logger.warn(`[MessageBridge] Contact review route unavailable: self=${selfAid} request=${submission.requestId} reason=${route.kind === 'unavailable' ? route.reason : 'local-route-not-allowed'}`);
732
- return false;
733
- }
734
- let note = '申请说明不可用';
735
- try {
736
- note = findPeerRequestNote(selfAid, submission.requestId) || '(未填写)';
737
- }
738
- catch { }
739
- const expiresAtMs = Date.parse(submission.expiresAt);
740
- const sessionId = `contact-request:${selfAid}:${submission.requestId}`;
741
- const interaction = {
742
- type: 'interaction',
743
- id: submission.requestId,
744
- channelId: route.approverOperatorId,
745
- sessionId,
746
- initiatorId: route.approverOperatorId,
747
- expiresAt: expiresAtMs,
748
- kind: {
749
- kind: 'action',
750
- title: '联系人申请审核',
751
- bodyFormat: 'plain',
752
- body: `申请人:${applicantAid}\n申请说明:${note}\n提交时间:${submission.submittedAt}\n截止时间:${submission.expiresAt}\n\n此卡片只处理当前这一次联系人申请。申请人重新提交、已被他人处理或审批超时,均不会修改当前联系人状态。卡片因重启或投递失效时,可在联系人列表处理仍未到期的 pending;已过期申请需由申请人重新发送 /request。`,
753
- buttons: [
754
- { key: 'approve', label: '通过', style: 'primary' },
755
- { key: 'reject', label: '拒绝', style: 'default' },
756
- { key: 'block', label: '拉黑', style: 'danger', confirm: { title: '拉黑申请人', body: `确定拉黑 ${applicantAid}?` } },
757
- ],
758
- },
759
- };
760
- this.interactionRouter.register(submission.requestId, sessionId, async (action, _values, operatorId) => {
761
- if (action !== 'approve' && action !== 'reject' && action !== 'block')
762
- return false;
763
- const reviewed = await reviewPeerRequest({
764
- selfAid,
765
- primaryId: applicantAid,
766
- requestId: submission.requestId,
767
- expectedContactRevision: submission.peerRevision,
768
- approverId: route.approverOperatorId,
769
- actorId: String(operatorId || ''),
770
- decision: action,
771
- });
772
- try {
773
- await this.sendContactReviewOutcome(route.adapter, route.approverOperatorId, applicantAid, reviewed.code, owningAgent?.name);
774
- }
775
- catch (error) {
776
- logger.warn(`[MessageBridge] Contact review outcome notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
777
- }
778
- if (reviewed.code === 'approved' || reviewed.code === 'rejected' || reviewed.code === 'blocked') {
779
- try {
780
- await this.notifyContactApplicant(route.adapter, applicantAid, reviewed.code, submission.requestId, submission.expiresAt, owningAgent?.name);
781
- }
782
- catch (error) {
783
- logger.warn(`[MessageBridge] Contact applicant notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
784
- }
785
- return true;
786
- }
787
- return false;
788
- }, {
789
- timeoutMs: Math.max(1, expiresAtMs - Date.now()),
790
- initiatorId: route.approverOperatorId,
791
- initiatorChannelKey: route.approverChannelKey,
792
- onTimeout: () => { void expirePendingPeerRequests(selfAid); },
793
- onCancel: reason => route.adapter.invalidateInteraction?.(submission.requestId, reason),
794
- });
795
- const envelope = buildEnvelope({
796
- taskId: `contact-request-${submission.requestId}`,
797
- sessionId,
798
- channel: route.adapter.channelName,
799
- channelId: route.approverOperatorId,
800
- agentName: owningAgent?.name ?? selfAid,
801
- chatmode: 'interactive',
802
- replyContext: { delivery: { chatType: 'private' }, metadata: { source: 'handoff', chatmode: 'interactive' } },
803
- });
804
- const receipt = await sendInteractionPayload(route.adapter, envelope, interaction, renderActionAsText(interaction), envelope.replyContext);
805
- const accepted = isInteractionSendAccepted(receipt);
806
- if (!accepted)
807
- await this.interactionRouter.cancel(submission.requestId, 'delivery_failed');
808
- return accepted;
809
- }
810
- async sendContactReviewOutcome(adapter, ownerAid, applicantAid, code, agentName) {
811
- const text = code === 'approved' ? `已通过 ${applicantAid} 的联系人申请。`
812
- : code === 'rejected' ? `已拒绝 ${applicantAid} 的联系人申请。`
813
- : code === 'blocked' ? `已拉黑 ${applicantAid}。`
814
- : code === 'request-expired' ? '审核已过期。'
815
- : code === 'request-stale' ? '申请已更新或已被处理。'
816
- : code === 'revision-conflict' ? '联系人列表已变化,请从联系人列表重新审核。'
817
- : '当前无审核权限。';
818
- await adapter.send(buildEnvelope({ channel: adapter.channelName, channelId: ownerAid, agentName: agentName ?? '<unknown>', delivery: { chatType: 'private' } }), { kind: 'system.notice', text, subtype: 'contact-review' });
819
- }
820
- async notifyContactApplicant(adapter, applicantAid, code, requestId, expiresAt, agentName) {
821
- await adapter.send(buildEnvelope({
822
- channel: adapter.channelName,
823
- channelId: applicantAid,
824
- agentName: agentName ?? '<unknown>',
825
- replyContext: { delivery: { chatType: 'private' }, metadata: evolMenuResponseTransportMetadata() },
826
- }), {
827
- kind: 'custom',
828
- channelType: 'aun',
829
- payload: {
830
- type: 'contact.request.response',
831
- status: code === 'approved' ? 'APPROVED' : code === 'rejected' ? 'REJECTED' : 'NOT_ALLOWED',
832
- request_id: requestId,
833
- expires_at: expiresAt,
834
- },
835
- });
836
- }
837
533
  getDebouncer(channelName, channelType) {
838
534
  let d = this.debouncers.get(channelName);
839
535
  if (!d) {
@@ -862,6 +558,19 @@ export class MessageBridge {
862
558
  register(channelName, onMessage, sendReply, adapter, channelType) {
863
559
  const effectiveChannelType = channelType || channelName;
864
560
  onMessage(async (msg) => {
561
+ const contactDelivery = trustedContactInboundDelivery(msg.contactDelivery);
562
+ const logInbound = contactDelivery
563
+ ? (dir, entry) => appendInboundMessageLogOnce(dir, entry, `contact-inbound-${contactDelivery.key}`)
564
+ : appendMessageLog;
565
+ let contactFailed = false;
566
+ if (contactDelivery) {
567
+ const receipt = this.messageQueue.contactDeliveryReceipt(contactDelivery.key);
568
+ if (receipt) {
569
+ contactDelivery.receipt = receipt;
570
+ return;
571
+ }
572
+ contactDelivery.validate();
573
+ }
865
574
  let releaseAdmission;
866
575
  let releaseSessionIngress;
867
576
  const releaseIngress = () => {
@@ -896,6 +605,10 @@ export class MessageBridge {
896
605
  const menuControl = resolvedChannelType === 'aun'
897
606
  ? parseMenuControl(content)
898
607
  : { isMenu: false };
608
+ if (menuControl.isMenu) {
609
+ Object.assign(msg, menuTiming);
610
+ this.logMenuInbound(channelName, msg, menuControl);
611
+ }
899
612
  const isPrivateMenuTokenRequest = menuControl.isMenu
900
613
  && menuControl.type === 'menu.token.request'
901
614
  && chatType === 'private';
@@ -914,10 +627,10 @@ export class MessageBridge {
914
627
  // a sender against an expired or invalidated ownership cache.
915
628
  const ownership = ownerResolver.snapshot(selfAid);
916
629
  if (ownership.connected || ownership.relation) {
917
- await ownerResolver.refresh(selfAid, {
630
+ await traceMenuStage(menuControl.isMenu ? menuControl.request : undefined, this.menuFlowContext(channelName, msg), menuTiming, 'bridge.ownership', () => ownerResolver.refresh(selfAid, {
918
631
  maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
919
632
  allowTransient: true,
920
- });
633
+ }));
921
634
  }
922
635
  }
923
636
  const admissionPreflight = evaluateInboundAdmissionPreflight({
@@ -939,16 +652,15 @@ export class MessageBridge {
939
652
  return;
940
653
  }
941
654
  }
942
- if (!trustedHandoffEcho && await this.handleContactRequestProtocol({
943
- context: admissionPreflight.context,
944
- msg,
945
- content,
946
- owningAgent,
947
- adapter,
948
- sendReply,
949
- })) {
655
+ // Retired controls must not enter the command/session/LLM pipeline.
656
+ if (/^\s*\/request(?:\s|$)/i.test(content))
950
657
  return;
658
+ try {
659
+ const legacyControl = JSON.parse(content);
660
+ if (typeof legacyControl?.type === 'string' && legacyControl.type.startsWith('contact.request.'))
661
+ return;
951
662
  }
663
+ catch { /* ordinary text */ }
952
664
  const ownershipFailure = selfAid ? ownerResolver.snapshot(selfAid) : undefined;
953
665
  if (!trustedHandoffEcho && !admissionPreflight.context.isOwner
954
666
  && admissionPreflight.allow
@@ -990,6 +702,8 @@ export class MessageBridge {
990
702
  return;
991
703
  }
992
704
  if (!trustedHandoffEcho && selfAid && actorId && this.groupInviteReviewService) {
705
+ if (contactDelivery && /^\s*\/invites(?:\s|$)/i.test(content))
706
+ contactDelivery.startCommand();
993
707
  const inviteCommand = await this.groupInviteReviewService.handleCommand({
994
708
  selfAid,
995
709
  ownerAid: actorId,
@@ -1053,10 +767,6 @@ export class MessageBridge {
1053
767
  });
1054
768
  return;
1055
769
  }
1056
- // AUN captures this mark at its adapter boundary. Legacy/test
1057
- // adapters fall back to the bridge entry mark captured above.
1058
- Object.assign(msg, menuTiming);
1059
- this.logMenuInbound(channelName, msg, menuControl);
1060
770
  if (!hasValidMenuId(menuControl)) {
1061
771
  this.logMenuDiagnostic('missing-id', channelName, msg, menuControl);
1062
772
  logMenuRequestCompleted(menuControl.request, undefined, this.menuFlowContext(channelName, msg), {
@@ -1351,7 +1061,7 @@ export class MessageBridge {
1351
1061
  const inboundReplyTo = typeof msg.replyContext?.metadata?.refMessageId === 'string'
1352
1062
  ? msg.replyContext.metadata.refMessageId
1353
1063
  : null;
1354
- appendMessageLog(chatDir, buildInboundEntry({
1064
+ logInbound(chatDir, buildInboundEntry({
1355
1065
  from: msg.peerId || 'unknown',
1356
1066
  to: msg.selfAID || 'self',
1357
1067
  threadId: msg.threadId ?? '',
@@ -1377,6 +1087,8 @@ export class MessageBridge {
1377
1087
  logger.debug(`[MessageBridge] Failed to log inbound command: ${e}`);
1378
1088
  }
1379
1089
  }
1090
+ if (contactDelivery && isCmd)
1091
+ contactDelivery.startCommand();
1380
1092
  if (msg.source !== 'handoff'
1381
1093
  && !executionPermissionOverride
1382
1094
  && await this.handleCommand(cmdContent, channelName, msg.channelId, (text) => {
@@ -1385,6 +1097,10 @@ export class MessageBridge {
1385
1097
  return sendReply(msg.channelId, text, msg.replyContext);
1386
1098
  }, msg.peerId, msg.threadId, msg.chatType, msg.source, msg.replyContext, msg.messageId, msg.selfAID, authSubject))
1387
1099
  return;
1100
+ // A quick-command prefix may be unknown to the handler and fall through
1101
+ // to model input. No command ran, so a failed queue commit may retry it.
1102
+ if (contactDelivery && isCmd)
1103
+ contactDelivery.cancelCommand?.();
1388
1104
  // 3. session 解析(使用 Channel 层填充的 chatType)
1389
1105
  if (!(await this.canCreateThreadSession(channelName, msg, chatType))) {
1390
1106
  // 静默丢弃:绝不向群里注入回复。
@@ -1495,7 +1211,43 @@ export class MessageBridge {
1495
1211
  if (!releaseAdmission)
1496
1212
  releaseAdmission = await this.acquireAdmission(admissionRoute);
1497
1213
  const hadMainSession = msg.threadId ? true : this.sessionManager.hasMainSession(channelName, msg.channelId, msg.channelType || effectiveChannelType, msg.selfAID || selfAid);
1498
- let session = diagnosticSession ?? await this.sessionManager.getOrCreateSession(channelName, msg.channelId, effectiveProjectPath, msg.threadId, Object.keys(metadata).length ? metadata : undefined, this.extractTopicName(msg), msg.peerId, chatType, owningAgent?.baseagent, msg.selfAID, msg.channelType || effectiveChannelType, msg.peerType, identity, readTopicLabel(msg) ?? readTopicLabel(msg.replyContext?.metadata), readTopicStatus(msg) ?? readTopicStatus(msg.replyContext?.metadata));
1214
+ const boundContactSession = contactDelivery?.sessionId
1215
+ ? await this.sessionManager.getSessionById(contactDelivery.sessionId) : undefined;
1216
+ if (contactDelivery?.sessionId && (!boundContactSession || boundContactSession.selfAID !== selfAid
1217
+ || boundContactSession.channelId !== msg.channelId
1218
+ || (sessionTopicThreadId(boundContactSession) ?? '') !== (isTopicThreadId(msg.threadId) ? msg.threadId : '')))
1219
+ throw new Error('contact replay bound session is unavailable');
1220
+ if (boundContactSession)
1221
+ boundContactSession.identity = identity;
1222
+ let session = boundContactSession ?? diagnosticSession ?? await this.sessionManager.getOrCreateSession(channelName, msg.channelId, effectiveProjectPath, msg.threadId, Object.keys(metadata).length ? metadata : undefined, this.extractTopicName(msg), msg.peerId, chatType, owningAgent?.baseagent, msg.selfAID, msg.channelType || effectiveChannelType, msg.peerType, identity, readTopicStatus(msg) ?? readTopicStatus(msg.replyContext?.metadata));
1223
+ // 归档话题不再入队;closed 收到新消息时回退 active,主话题不受此状态影响。
1224
+ const topicGate = decideTopicInbound({
1225
+ isTopic: isTopicSession(session),
1226
+ topicStatus: session.topicStatus,
1227
+ chatType,
1228
+ });
1229
+ if (topicGate.action === 'drop-archived') {
1230
+ logger.info(`[MessageBridge] 话题已归档,丢弃入站消息 session=${session.id} from=${msg.peerId} chatType=${chatType}`);
1231
+ if (topicGate.replyArchived && adapter?.send) {
1232
+ await adapter.send(buildEnvelope({
1233
+ taskId: `archived-${randomBytes(5).toString('hex')}`,
1234
+ channel: channelName,
1235
+ channelId: msg.channelId,
1236
+ chatmode: 'interactive',
1237
+ replyContext: {
1238
+ ...msg.replyContext,
1239
+ ...(msg.threadId ? { threadId: msg.threadId } : {}),
1240
+ },
1241
+ }), { kind: 'result.text', text: '话题已归档', isFinal: true }).catch((error) => {
1242
+ logger.warn(`[MessageBridge] 归档提示发送失败 session=${session.id}: ${error}`);
1243
+ });
1244
+ }
1245
+ return;
1246
+ }
1247
+ if (topicGate.reopen) {
1248
+ await this.sessionManager.setTopicStatus(session.id, 'active');
1249
+ session.topicStatus = 'active';
1250
+ }
1499
1251
  if (isTopicSession(session) && typeof this.messageQueue.reserveSessionIngress === 'function') {
1500
1252
  releaseSessionIngress = this.messageQueue.reserveSessionIngress(session.id);
1501
1253
  }
@@ -1508,7 +1260,7 @@ export class MessageBridge {
1508
1260
  const inboundCausation = restoredCausation
1509
1261
  ? deriveCausation(restoredCausation)
1510
1262
  : createRootCausation();
1511
- const renewResult = session.metadata?.diagnostic ? { session } : await this.sessionRenewService.resolve({
1263
+ const renewResult = session.metadata?.diagnostic || boundContactSession ? { session } : await this.sessionRenewService.resolve({
1512
1264
  session,
1513
1265
  channelName,
1514
1266
  channelType: msg.channelType || effectiveChannelType,
@@ -1525,6 +1277,8 @@ export class MessageBridge {
1525
1277
  causation: inboundCausation,
1526
1278
  });
1527
1279
  session = renewResult.session;
1280
+ if (contactDelivery)
1281
+ contactDelivery.bindSession(session.id);
1528
1282
  if (!executionPermissionOverride && selfAid && owningAgent?.aid === selfAid) {
1529
1283
  executionPermissionOverride = createAgentPolicyAuthorization({
1530
1284
  agentAid: selfAid, actor: roleDetail.actor, chatType,
@@ -1594,7 +1348,6 @@ export class MessageBridge {
1594
1348
  mentions: msg.mentions, mentionAids: msg.mentionAids, threadId: msg.threadId,
1595
1349
  isMentioned: msg.isMentioned,
1596
1350
  topicName: this.extractTopicName(msg),
1597
- label: session.label,
1598
1351
  topicStatus: session.topicStatus,
1599
1352
  replyContext: msg.replyContext,
1600
1353
  source: msg.source,
@@ -1709,7 +1462,7 @@ export class MessageBridge {
1709
1462
  }
1710
1463
  }
1711
1464
  if (!handoffCandidate)
1712
- appendMessageLog(inboundEntry.chatDir, inboundEntry.entry);
1465
+ logInbound(inboundEntry.chatDir, inboundEntry.entry);
1713
1466
  if (autoResult && autoResult.batch.length > 1) {
1714
1467
  for (const item of autoResult.batch.slice(0, -1)) {
1715
1468
  const member = item.value;
@@ -1744,20 +1497,24 @@ export class MessageBridge {
1744
1497
  if (fullMessage.messageId && currentSessionBusy) {
1745
1498
  adapter?.acknowledge?.(fullMessage.messageId).catch(() => { });
1746
1499
  }
1747
- const isInterrupt = chatType !== 'group' && !handoffCandidate;
1748
- const attentionPolicy = fullMessage.attentionPolicy;
1500
+ const isInterrupt = chatType !== 'group' && !handoffCandidate && !contactDelivery;
1501
+ const attentionPolicy = contactDelivery ? 'defer' : fullMessage.attentionPolicy;
1749
1502
  const shouldInterrupt = isInterrupt || attentionPolicy === 'interrupt';
1750
1503
  const enqueueAgentName = owningAgent?.name ?? '<unknown>';
1751
1504
  const selfAID = session.selfAID;
1752
1505
  const doEnqueue = async (m) => {
1753
1506
  // A cancellation can arrive while this message is being debounced.
1754
- if (!isDiagnosticSessionActive(session, this.sessionManager.getChatDir(session)))
1507
+ if (!isDiagnosticSessionActive(session, this.sessionManager.getChatDir(session))) {
1508
+ if (contactDelivery)
1509
+ throw new Error('contact replay session is no longer active');
1755
1510
  return;
1756
- const enqueue = handoffCandidate ? this.messageQueue.enqueuePersisted.bind(this.messageQueue) : this.messageQueue.enqueue.bind(this.messageQueue);
1511
+ }
1512
+ const enqueue = handoffCandidate || contactDelivery ? this.messageQueue.enqueuePersisted.bind(this.messageQueue) : this.messageQueue.enqueue.bind(this.messageQueue);
1757
1513
  try {
1758
1514
  return await enqueue(session.id, m, session.projectPath, {
1759
1515
  interruptible: shouldInterrupt,
1760
1516
  attentionPolicy,
1517
+ contactDelivery,
1761
1518
  interruptSamePeer: !shouldInterrupt && !attentionPolicy, // 旧群聊路径保留同人连发打断
1762
1519
  priority: attentionPolicy === 'interrupt',
1763
1520
  agentName: enqueueAgentName,
@@ -1780,7 +1537,7 @@ export class MessageBridge {
1780
1537
  throw error;
1781
1538
  }
1782
1539
  };
1783
- if (handoffCandidate) {
1540
+ if (handoffCandidate || contactDelivery) {
1784
1541
  await doEnqueue(fullMessage);
1785
1542
  }
1786
1543
  else if (isInterrupt) {
@@ -1799,6 +1556,7 @@ export class MessageBridge {
1799
1556
  }
1800
1557
  }
1801
1558
  catch (error) {
1559
+ contactFailed = true;
1802
1560
  if (isRetryableMenuTransportError(error)) {
1803
1561
  logger.warn(`[MessageBridge] Retryable response delivery unavailable for ${channelName}:`, error);
1804
1562
  }
@@ -1808,9 +1566,18 @@ export class MessageBridge {
1808
1566
  finally {
1809
1567
  releaseAdmission?.();
1810
1568
  releaseIngress();
1569
+ if (contactDelivery && !contactFailed && !contactDelivery.receipt) {
1570
+ this.messageQueue.finishContactDelivery(contactDelivery);
1571
+ }
1811
1572
  }
1812
1573
  });
1813
1574
  }
1575
+ contactDeliveryReceipt(key) {
1576
+ return this.messageQueue.contactDeliveryReceipt(key);
1577
+ }
1578
+ finishContactDelivery(delivery) {
1579
+ this.messageQueue.finishContactDelivery(delivery);
1580
+ }
1814
1581
  async acquireAdmission(key) {
1815
1582
  const previous = this.admissionLocks.get(key) ?? Promise.resolve();
1816
1583
  let release;
@@ -1869,23 +1636,26 @@ export class MessageBridge {
1869
1636
  // Menu IDs are the protocol's stable correlation key. Bind it, together
1870
1637
  // with the active EvolCore session, before authorization so every
1871
1638
  // CommandAudit record and denial can be joined to the same request.
1872
- let activeSession;
1873
- if (msg.threadId && typeof this.sessionManager.getThreadSession === 'function') {
1874
- try {
1875
- activeSession = await this.sessionManager.getThreadSession(channel, msg.channelId, msg.threadId);
1876
- }
1877
- catch {
1878
- activeSession = undefined;
1879
- }
1880
- }
1881
- if (!activeSession && typeof this.sessionManager.getActiveSession === 'function') {
1882
- try {
1883
- activeSession = await this.sessionManager.getActiveSession(channel, msg.channelId);
1639
+ const activeSession = await traceMenuStage(parsed.request, this.menuFlowContext(channel, msg), msg, 'menu.context', async () => {
1640
+ let session;
1641
+ if (msg.threadId && typeof this.sessionManager.getThreadSession === 'function') {
1642
+ try {
1643
+ session = await this.sessionManager.getThreadSession(channel, msg.channelId, msg.threadId);
1644
+ }
1645
+ catch {
1646
+ session = undefined;
1647
+ }
1884
1648
  }
1885
- catch {
1886
- activeSession = undefined;
1649
+ if (!session && typeof this.sessionManager.getActiveSession === 'function') {
1650
+ try {
1651
+ session = await this.sessionManager.getActiveSession(channel, msg.channelId);
1652
+ }
1653
+ catch {
1654
+ session = undefined;
1655
+ }
1887
1656
  }
1888
- }
1657
+ return session;
1658
+ });
1889
1659
  const menuAuthSubject = {
1890
1660
  ...authSubject,
1891
1661
  requestId: parsed.id,
@@ -1939,9 +1709,9 @@ export class MessageBridge {
1939
1709
  const dedupKey = [msg.selfAID || channel, channelType, msg.chatType || 'private', scope, msg.peerId,
1940
1710
  msg.peerDeviceId || '', msg.peerSlotId || '', msg.threadId || '', parsed.id].join('\u001f');
1941
1711
  let afterResponse;
1942
- const deduped = await this.menuDeduper.execute(dedupKey, menuPayloadFingerprint(parsed.raw), () => isTokenRequest
1712
+ const deduped = await traceMenuStage(parsed.request, this.menuFlowContext(channel, msg), msg, 'menu.execute', () => this.menuDeduper.execute(dedupKey, menuPayloadFingerprint(parsed.raw), () => isTokenRequest
1943
1713
  ? this.issueMenuTokenResponse(header, channel, msg)
1944
- : this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; }));
1714
+ : this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; })));
1945
1715
  if ('conflict' in deduped) {
1946
1716
  this.logMenuDiagnostic('request-conflict', channel, msg, parsed, 'CONFLICT');
1947
1717
  await this.sendMenuResponse(adapter, channel, msg, menuFailure(header, {
@@ -2219,7 +1989,7 @@ export class MessageBridge {
2219
1989
  const deliveryTiming = beginMenuDeliveryTiming(msg);
2220
1990
  let deliveryOutcome;
2221
1991
  try {
2222
- await deliverMenuResponse(async () => {
1992
+ await traceMenuStage(request, flowContext, msg, 'menu.delivery', () => deliverMenuResponse(async () => {
2223
1993
  Object.assign(timedResponse, withMenuProcessingTime(timedResponse, msg));
2224
1994
  await adapter.send(envelope, { kind: 'custom', channelType: channel, payload: timedResponse });
2225
1995
  }, {
@@ -2247,7 +2017,7 @@ export class MessageBridge {
2247
2017
  },
2248
2018
  onRetry: (attempt, error, delay) => logMenuResponseRetry(request, flowContext, attempt, delay, error),
2249
2019
  onComplete: outcome => { deliveryOutcome = outcome; },
2250
- });
2020
+ }));
2251
2021
  logMenuRequestCompleted(request, timedResponse, flowContext, { delivery: 'sent', ...deliveryOutcome, ...deliveryTiming() });
2252
2022
  const upgradeData = 'data' in response ? response.data : undefined;
2253
2023
  if (request.type === 'menu.action' && request.action === 'upgrade' && (request.name === 'system' || request.cmd === '/system') && upgradeData?.jobId) {