evolcore 0.0.41 → 0.0.42-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -1,16 +1,25 @@
1
- import { AccessPolicyError, readAccessPolicy, } from '../../config/access-policy.js';
2
- import { getContactSnapshot, isAcceptedContact, resolveContactView, resolvePrincipal, } from '../../config/contact-book.js';
1
+ import { readAccessPolicy, } from '../../config/access-policy.js';
2
+ import { resolvePeerView, resolvePrincipal, } from '../../config/peer-book.js';
3
3
  import { isValidAid } from '../../aun/aid/validation.js';
4
- import { addContact, expirePendingContactRequests } from '../../config/contact-request-service.js';
5
4
  import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
6
- import { readAunPeerKind, resolveAunPeerKind } from '../relation/peer-identity.js';
7
- /** Validate managed private AUN sends against the sender's local contact policy. */
5
+ import { resolveAunPeerKind } from '../relation/peer-identity.js';
6
+ /**
7
+ * 出站私聊准入:与入站使用同一套三档判定,保证双向对称。
8
+ *
9
+ * 顺序与入站一致:本地拉黑 → Owner/个人助理 → 黑名单 → 白名单 → 名录三档。
10
+ * 群聊的准入单位是群,出站到群不做发言人判定。
11
+ */
8
12
  export async function evaluateOutboundContactAdmission(input) {
9
13
  const selfAid = String(input.selfAid || '').trim();
10
14
  const targetAid = String(input.targetAid || '').trim();
11
15
  if (!isValidAid(selfAid) || !isValidAid(targetAid)) {
12
16
  return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: 'A valid Agent AID is required for outbound contact admission' };
13
17
  }
18
+ // 群目标按群放行。类型无法确认(本地无证据且远端不可达)时不额外阻拦:
19
+ // 这条路径由 IPC 的 callers 选定 msg scope,准入只负责名录三档判定。
20
+ const target = await resolveAunPeerKind(selfAid, targetAid);
21
+ if (target.kind === 'group')
22
+ return { allow: true, status: 'group' };
14
23
  let policy;
15
24
  try {
16
25
  policy = readAccessPolicy(selfAid);
@@ -18,94 +27,48 @@ export async function evaluateOutboundContactAdmission(input) {
18
27
  catch (error) {
19
28
  return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
20
29
  }
21
- if (policy.policyMode !== 'contacts') {
22
- try {
23
- if (getContactSnapshot(selfAid).contacts.get(targetAid)?.status === 'blocked') {
24
- return { allow: false, code: 'CONTACT_BLOCKED', status: 'blocked', error: `目标联系人 ${targetAid} 已被拉黑。请先解除拉黑:ec contact unblock ${targetAid} --self ${selfAid}` };
25
- }
26
- }
27
- catch (error) {
28
- return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
29
- }
30
- return { allow: true, status: policy.policyMode };
31
- }
30
+ let view;
32
31
  try {
33
- await expirePendingContactRequests(selfAid);
34
- const snapshot = getContactSnapshot(selfAid);
35
- const entry = snapshot.contacts.get(targetAid);
36
- const view = resolveContactView(selfAid, targetAid);
37
- if (view.isOwner)
38
- return { allow: true, status: 'owner' };
39
- if (entry && (entry.status === undefined || entry.status === 'active')) {
40
- const kind = readAunPeerKind(selfAid, targetAid);
41
- return kind.kind === 'private' ? { allow: true, status: 'active' }
42
- : { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent',
43
- error: `Cannot establish private contact type (${kind.reason}): ${targetAid}` };
44
- }
45
- const status = entry?.status ?? 'absent';
46
- if (status === 'blocked')
47
- return { allow: false, code: 'CONTACT_BLOCKED', status, error: `目标联系人 ${targetAid} 已被拉黑。请先解除拉黑:ec contact unblock ${targetAid} --self ${selfAid}` };
48
- const addCommand = `ec contact add ${targetAid} --self ${selfAid}`;
49
- if (status === 'pending')
50
- return { allow: false, code: 'CONTACT_PENDING', status, error: `目标联系人 ${targetAid} 的联系人申请正在审核中,请等待 Owner 通过;如需重新提交,执行:${addCommand}` };
51
- if (status === 'declined')
52
- return { allow: false, code: 'CONTACT_DECLINED', status, error: `目标联系人 ${targetAid} 的联系人申请已拒绝或过期,请重新申请:${addCommand}` };
53
- return { allow: false, code: 'CONTACT_NOT_ACTIVE', status: 'absent', error: `目标 ${targetAid} 不是联系人,请先申请添加:${addCommand}` };
32
+ view = resolvePeerView(selfAid, targetAid);
54
33
  }
55
34
  catch (error) {
56
35
  return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
57
36
  }
58
- }
59
- /** An explicit managed private send establishes the target as an active contact. */
60
- export async function ensureOutboundContactForSend(input) {
61
- const selfAid = String(input.selfAid || '').trim();
62
- const targetAid = String(input.targetAid || '').trim();
63
- if (!isValidAid(selfAid) || !isValidAid(targetAid))
64
- return evaluateOutboundContactAdmission(input);
65
- input = { ...input, selfAid, targetAid };
66
- const target = await resolveAunPeerKind(selfAid, targetAid);
67
- if (target.kind !== 'private') {
68
- return {
69
- allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent',
70
- error: target.kind === 'group' ? `Target ${targetAid} is a group AID; use group send`
71
- : `Cannot establish private target type (${target.reason}): ${targetAid}`,
72
- };
37
+ if (view.blocked) {
38
+ return { allow: false, code: 'CONTACT_BLOCKED', status: 'blocked', error: `目标 ${targetAid} 已被本端拉黑。请先解除拉黑:ec peer unblock ${targetAid} --self ${selfAid}` };
73
39
  }
74
- const admission = await evaluateOutboundContactAdmission(input);
75
- if (!admission.allow && (admission.code === 'CONTACT_BLOCKED' || admission.code === 'CONTACT_POLICY_INVALID')) {
76
- return admission;
40
+ if (view.isOwner)
41
+ return { allow: true, status: 'owner' };
42
+ if (policy.deniedAids?.includes(targetAid)) {
43
+ return { allow: false, code: 'CONTACT_DENIED', status: 'denied', error: `目标 ${targetAid} 在 Owner 配置的黑名单 deniedAids 中,当前无法联系` };
77
44
  }
78
- try {
79
- const view = resolveContactView(input.selfAid, input.targetAid);
80
- if (view.isOwner || (view.source === 'contact' && view.status === 'active'))
81
- return admission;
82
- await addContact({
83
- selfAid: input.selfAid,
84
- primaryId: input.targetAid,
85
- actorId: input.actorId,
86
- });
87
- return evaluateOutboundContactAdmission(input);
88
- }
89
- catch (error) {
90
- const current = await evaluateOutboundContactAdmission(input);
91
- if (!current.allow && current.code === 'CONTACT_BLOCKED')
92
- return current;
93
- if (current.allow) {
94
- try {
95
- const view = resolveContactView(input.selfAid, input.targetAid);
96
- if (view.isOwner || (view.source === 'contact' && view.status === 'active'))
97
- return current;
98
- }
99
- catch {
100
- // Return the original mutation error below.
45
+ if (policy.allowedAids?.includes(targetAid))
46
+ return { allow: true, status: 'allowed_aid' };
47
+ const membership = readOwnerDirectoryMembership(selfAid, targetAid);
48
+ switch (membership?.category) {
49
+ case 'unavailable':
50
+ return { allow: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', status: 'unavailable', error: 'Owner 名录当前不可用,无法确认目标身份,已拒绝发送' };
51
+ case 'owner':
52
+ return { allow: true, status: 'owner' };
53
+ case 'assistant':
54
+ return { allow: true, status: 'internal' };
55
+ case 'agent':
56
+ case 'human':
57
+ case 'other': {
58
+ if (membership.internal) {
59
+ return policy.allowInternalContacts !== false
60
+ ? { allow: true, status: 'internal' }
61
+ : { allow: false, code: 'CONTACT_INTERNAL_DISABLED', status: 'disabled', error: '当前 Agent 不接受内部联系,Owner 未开启 allowInternalContacts' };
101
62
  }
63
+ return policy.allowExternalContacts === true
64
+ ? { allow: true, status: 'external' }
65
+ : { allow: false, code: 'CONTACT_EXTERNAL_DISABLED', status: 'disabled', error: '当前 Agent 不接受外部联系,Owner 未开启 allowExternalContacts' };
102
66
  }
103
- return {
104
- allow: false,
105
- code: 'CONTACT_POLICY_INVALID',
106
- status: 'absent',
107
- error: error instanceof Error ? error.message : String(error),
108
- };
67
+ case 'not_found':
68
+ default:
69
+ if (policy.allowStrangerContacts === true)
70
+ return { allow: true, status: 'stranger' };
71
+ return { allow: false, code: 'CONTACT_STRANGER_DISABLED', status: 'disabled', error: `目标 ${targetAid} 不在当前 Agent 的 Owner 名录中,Owner 未开启 allowStrangerContacts` };
109
72
  }
110
73
  }
111
74
  export function evaluateInboundAdmissionPreflight(input) {
@@ -140,9 +103,9 @@ export function evaluateInboundAdmissionPreflight(input) {
140
103
  }
141
104
  if (principal.principalId) {
142
105
  try {
143
- const contact = resolveContactView(selfAid, principal.principalId);
106
+ const contact = resolvePeerView(selfAid, principal.principalId);
144
107
  context.contactStatus = contact.status;
145
- context.contactSource = contact.source;
108
+ context.peerSource = contact.source;
146
109
  context.isOwner = contact.isOwner;
147
110
  if (contact.blocked)
148
111
  return { allow: false, reason: 'blocked', context };
@@ -161,7 +124,7 @@ export function evaluateInboundAdmissionPreflight(input) {
161
124
  const principal = resolvePrincipal(selfAid, channelType, actorId, input.channelKey);
162
125
  if (principal.principalId) {
163
126
  context.primaryId = principal.principalId;
164
- context.isOwner = resolveContactView(selfAid, principal.principalId).isOwner;
127
+ context.isOwner = resolvePeerView(selfAid, principal.principalId).isOwner;
165
128
  }
166
129
  }
167
130
  catch {
@@ -172,69 +135,103 @@ export function evaluateInboundAdmissionPreflight(input) {
172
135
  try {
173
136
  context.policy = readAccessPolicy(selfAid);
174
137
  }
175
- catch (error) {
176
- if (error instanceof AccessPolicyError && error.code === 'restricted_mode_without_owner') {
177
- return { allow: false, reason: 'restricted_mode_without_owner', context };
178
- }
138
+ catch {
179
139
  return { allow: false, reason: 'invalid_access_policy', context };
180
140
  }
181
141
  return { allow: true, context };
182
142
  }
183
- /** Directory rules also guard control routes; a denied directory sender receives no automatic reply. */
143
+ /**
144
+ * 名录判定:把发送者按在 Owner 名录中的归属分成内部 / 外部 / 陌生人三档。
145
+ *
146
+ * - `owner` / `assistant`:恒放行,不受任何开关与名单影响。
147
+ * - 命中条目且属于本 Owner → `allowInternalContacts`。
148
+ * - 命中条目但归属其他 Owner(或缺失归属)→ `allowExternalContacts`。
149
+ * - 未命中 → 返回 undefined,由调用方按 `allowStrangerContacts` 决定。
150
+ * - 名录不可用 → 拒绝,不回退放行。
151
+ *
152
+ * 拒绝发生在业务路由之前,被拒的名录发送者不会收到自动回复。
153
+ */
184
154
  export function evaluateOwnerDirectoryInboundAdmission(context) {
185
155
  if (context.trustedHandoffEcho || context.isOwner || !context.primaryId || !context.policy)
186
156
  return undefined;
187
157
  const membership = readOwnerDirectoryMembership(context.selfAid, context.primaryId);
188
158
  if (!membership)
189
159
  return undefined;
190
- if (membership.agents === 'found') {
191
- return context.policy.allowOwnerAgentDirectory !== false
192
- ? { allow: true, reason: 'owner_directory_agent', context }
193
- : { allow: false, reason: 'owner_agent_directory_disabled', context };
194
- }
195
- // Resolve the higher-priority Agent category before admitting a contact.
196
- if (membership.agents === 'unavailable')
197
- return { allow: false, reason: 'owner_directory_unavailable', context };
198
- if (membership.contacts === 'found') {
199
- return context.policy.allowOwnerDirectoryContacts !== false
200
- ? { allow: true, reason: 'owner_directory_contact', context }
201
- : { allow: false, reason: 'owner_directory_contacts_disabled', context };
160
+ const policy = context.policy;
161
+ switch (membership.category) {
162
+ case 'unavailable':
163
+ return { allow: false, reason: 'owner_directory_unavailable', context };
164
+ case 'owner':
165
+ return { allow: true, reason: 'owner_directory_owner', context };
166
+ case 'assistant':
167
+ return { allow: true, reason: 'owner_directory_assistant', context };
168
+ case 'agent':
169
+ case 'human':
170
+ case 'other': {
171
+ if (membership.internal) {
172
+ return policy.allowInternalContacts !== false
173
+ ? { allow: true, reason: membership.category === 'agent' ? 'internal_agent' : 'internal_contact', context }
174
+ : { allow: false, reason: 'internal_contacts_disabled', context };
175
+ }
176
+ return policy.allowExternalContacts === true
177
+ ? { allow: true, reason: membership.category === 'agent' ? 'external_agent' : 'external_contact', context }
178
+ : { allow: false, reason: 'external_contacts_disabled', context };
179
+ }
180
+ case 'not_found':
181
+ default:
182
+ return undefined;
202
183
  }
203
- if (membership.contacts === 'unavailable')
204
- return { allow: false, reason: 'owner_directory_unavailable', context };
205
- return undefined;
206
184
  }
185
+ /**
186
+ * 普通消息准入。出站私聊复用同一套判定,保证出入站对称。
187
+ *
188
+ * 顺序:可信 handoff → Owner/个人助理 → 群聊(准入单位是整个群)→ 黑名单 → 白名单
189
+ * → 名录三档。群聊不按发言人判定,因此群内发言人即使落在被关闭的档也放行。
190
+ */
207
191
  export function evaluateOrdinaryInboundAdmission(context) {
192
+ const decision = evaluateOrdinaryAdmission(context);
193
+ if (!decision.allow)
194
+ context.denyReason = decision.reason;
195
+ return decision;
196
+ }
197
+ function evaluateOrdinaryAdmission(context) {
208
198
  if (context.trustedHandoffEcho)
209
199
  return { allow: true, reason: 'trusted_handoff', context };
210
200
  const policy = context.policy;
211
201
  if (!policy)
212
202
  return { allow: false, reason: 'invalid_access_policy', context };
203
+ // 群聊的准入单位是群本身:成员身份已在入群时由 Owner 确立,这里不再按发言人分档。
204
+ if (context.chatType === 'group') {
205
+ if (context.isOwner)
206
+ return { allow: true, reason: 'owner', context };
207
+ return { allow: true, reason: 'group_channel_allowed', context };
208
+ }
209
+ // Owner 恒放行,不查名录也不看三个开关。
213
210
  if (context.isOwner)
214
211
  return { allow: true, reason: 'owner', context };
215
212
  const directoryDecision = evaluateOwnerDirectoryInboundAdmission(context);
216
- if (directoryDecision)
213
+ // Owner 与个人助理恒放行,不受黑名单影响。
214
+ if (directoryDecision?.allow
215
+ && (directoryDecision.reason === 'owner_directory_owner' || directoryDecision.reason === 'owner_directory_assistant')) {
217
216
  return directoryDecision;
218
- if (context.primaryId && policy.allowedAids?.includes(context.primaryId)) {
219
- return { allow: true, reason: 'allowed_aid', context };
220
217
  }
221
- if (policy.allowExternalContacts === false) {
222
- return { allow: false, reason: 'external_contacts_disabled', context };
218
+ // 名录不可用是 fail closed,白名单与陌生人开关都不能把它翻成放行。
219
+ if (directoryDecision && !directoryDecision.allow && directoryDecision.reason === 'owner_directory_unavailable') {
220
+ return directoryDecision;
223
221
  }
224
- if (context.chatType === 'group') {
225
- if (policy.policyMode === 'open' || policy.policyMode === 'contacts') {
226
- return { allow: true, reason: 'group_channel_allowed', context };
227
- }
228
- return { allow: false, reason: 'owners', context };
222
+ const aid = context.primaryId;
223
+ if (aid && policy.deniedAids?.includes(aid)) {
224
+ return { allow: false, reason: 'denied_aid', context };
229
225
  }
230
- if (policy.policyMode === 'open')
231
- return { allow: true, reason: 'open', context };
232
- if (policy.policyMode === 'owners')
233
- return { allow: false, reason: 'owners', context };
234
- if (context.primaryId && isAcceptedContact(context.selfAid, context.primaryId, context.channelType === 'aun' && context.chatType === 'private' ? 'private' : undefined)) {
235
- return { allow: true, reason: 'contact', context };
226
+ if (aid && policy.allowedAids?.includes(aid)) {
227
+ return { allow: true, reason: 'allowed_aid', context };
228
+ }
229
+ if (directoryDecision)
230
+ return directoryDecision;
231
+ if (policy.allowStrangerContacts === true) {
232
+ return { allow: true, reason: 'stranger_contacts_allowed', context };
236
233
  }
237
- return { allow: false, reason: 'contact_required', context };
234
+ return { allow: false, reason: 'stranger_contacts_disabled', context };
238
235
  }
239
236
  const principalReplyBuckets = new Map();
240
237
  const channelReplyBuckets = new Map();
@@ -5,7 +5,7 @@ import { createHash, randomBytes } from 'crypto';
5
5
  import fs from 'fs';
6
6
  import path from 'path';
7
7
  import { agentStorageMenuService, isAgentStorageMenuRequest } from '../command/agent-storage-menu.js';
8
- import { logger } from '../../utils/logger.js';
8
+ import { logger, logPreview } from '../../utils/logger.js';
9
9
  import { StreamDebouncer } from './stream-debouncer.js';
10
10
  import { appendMessageLog, appendMessageLogStrict, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
11
11
  import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from './message-utils.js';
@@ -14,11 +14,11 @@ import { readTopicLabel, readTopicStatus } from '../session/session-mapper.js';
14
14
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
15
15
  import { agentDir, resolvePaths } from '../../paths.js';
16
16
  import { listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
17
- import { resolveContactView, resolvePeerDisplayLabel, resolvePrincipal } from '../../config/contact-book.js';
18
- import { findContactRequestNote, expirePendingContactRequests, reviewContactRequest, submitContactRequest, contactRequestSubmissionProtocolResult, queryOwnContactRequestStatus, } from '../../config/contact-request-service.js';
17
+ import { resolvePeerView, resolvePeerDisplayLabel, resolvePrincipal } from '../../config/peer-book.js';
18
+ import { findPeerRequestNote, expirePendingPeerRequests, reviewPeerRequest, submitPeerRequest, peerRequestSubmissionProtocolResult, queryOwnPeerRequestStatus, } from '../../config/peer-request-service.js';
19
19
  import { isValidAid } from '../../aun/aid/validation.js';
20
20
  import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
21
- import { ownerResolver, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
21
+ import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
22
22
  import { isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
23
23
  import { resolveEffective } from '../../config/config-manager.js';
24
24
  import { createDecisionInferenceProvider } from '../inference/text-inference.js';
@@ -72,11 +72,11 @@ export function shouldBlockInboundContact(input) {
72
72
  const primaryId = resolution.principalId;
73
73
  if (!primaryId)
74
74
  return { blocked: false, status: 'invalid-aid' };
75
- if (resolveContactView(input.selfAid, primaryId).isOwner) {
75
+ if (resolvePeerView(input.selfAid, primaryId).isOwner) {
76
76
  return { blocked: false, status: 'owner-exempt', primaryId };
77
77
  }
78
78
  return {
79
- blocked: resolveContactView(input.selfAid, primaryId).blocked,
79
+ blocked: resolvePeerView(input.selfAid, primaryId).blocked,
80
80
  status: 'resolved',
81
81
  primaryId,
82
82
  };
@@ -528,7 +528,7 @@ export class MessageBridge {
528
528
  return true;
529
529
  }
530
530
  try {
531
- const submission = await submitContactRequest({
531
+ const submission = await submitPeerRequest({
532
532
  selfAid: context.selfAid,
533
533
  applicantAid: context.primaryId,
534
534
  note: requestMatch[1],
@@ -571,7 +571,7 @@ export class MessageBridge {
571
571
  let result;
572
572
  if (protocolType === 'query') {
573
573
  try {
574
- result = await queryOwnContactRequestStatus({
574
+ result = await queryOwnPeerRequestStatus({
575
575
  selfAid: context.selfAid,
576
576
  applicantAid: context.primaryId,
577
577
  requestId: protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'request_id')
@@ -593,14 +593,14 @@ export class MessageBridge {
593
593
  }, owningAgent?.name);
594
594
  return true;
595
595
  }
596
- const submission = await submitContactRequest({
596
+ const submission = await submitPeerRequest({
597
597
  selfAid: context.selfAid,
598
598
  applicantAid: context.primaryId,
599
599
  note: typeof protocolPayload?.note === 'string' ? protocolPayload.note : undefined,
600
600
  sourceChannelKey: context.channelKey,
601
601
  routeKind: 'private',
602
602
  });
603
- result = contactRequestSubmissionProtocolResult(submission);
603
+ result = peerRequestSubmissionProtocolResult(submission);
604
604
  if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
605
605
  void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
606
606
  .catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
@@ -614,27 +614,6 @@ export class MessageBridge {
614
614
  await this.sendContactRequestProtocolResponse(adapter, msg, result, owningAgent?.name);
615
615
  return true;
616
616
  }
617
- /**
618
- * Agent self-service contact add: create/update a pending request and send
619
- * the same Owner action card used by inbound `/request`.
620
- */
621
- async submitAgentContactRequest(input) {
622
- const owningAgent = this.agentRegistry?.get(input.selfAid) ?? null;
623
- const submission = await submitContactRequest({
624
- selfAid: input.selfAid,
625
- applicantAid: input.applicantAid,
626
- sourceChannelKey: input.sourceChannelKey,
627
- note: '通过 ec contact add 发起的联系人申请',
628
- });
629
- if ((submission.code !== 'submitted' && submission.code !== 'resubmitted') || !submission.requestId) {
630
- return { ...submission, reviewCardSent: false };
631
- }
632
- const reviewCardSent = await this.deliverContactReviewCard(input.selfAid, input.applicantAid, submission, owningAgent);
633
- if (!reviewCardSent) {
634
- logger.warn(`[MessageBridge] Agent contact add request persisted without review card: self=${input.selfAid} applicant=${input.applicantAid} request=${submission.requestId}`);
635
- }
636
- return { ...submission, reviewCardSent };
637
- }
638
617
  contactRequestReply(result) {
639
618
  switch (result.code) {
640
619
  case 'submitted': return '联系人申请已提交,等待管理员审核。';
@@ -710,15 +689,15 @@ export class MessageBridge {
710
689
  await sendReply(msg.channelId, payload.text, msg.replyContext);
711
690
  }
712
691
  admissionDeniedNotice(context, channelType) {
713
- if (context.policy?.allowExternalContacts === false) {
714
- return '当前 Agent 不接受外部联系消息,请由 Owner 将你的 AID 加入允许名单。';
715
- }
716
- if (context.contactStatus === 'pending') {
717
- return '联系人申请审核中;可再次发送 /request 更新说明。';
692
+ const reason = context.denyReason;
693
+ if (reason === 'denied_aid') {
694
+ return '当前 Agent 不接受你发送的消息:你已被其 Owner 列入黑名单。';
718
695
  }
719
- if (context.contactSource === 'contact' && context.contactStatus === 'active') {
720
- return '当前不接受任何消息。';
696
+ if (reason === 'internal_contacts_disabled' || reason === 'external_contacts_disabled') {
697
+ return '当前 Agent 不接受这一范围的访问,请联系其 Owner 调整授权范围。';
721
698
  }
699
+ if (reason === 'owner_directory_unavailable')
700
+ return undefined;
722
701
  if (channelType === 'aun') {
723
702
  return '当前不接受陌生人消息。可发送 /request <申请说明> 申请成为联系人。';
724
703
  }
@@ -772,7 +751,7 @@ export class MessageBridge {
772
751
  }
773
752
  let note = '申请说明不可用';
774
753
  try {
775
- note = findContactRequestNote(selfAid, submission.requestId) || '(未填写)';
754
+ note = findPeerRequestNote(selfAid, submission.requestId) || '(未填写)';
776
755
  }
777
756
  catch { }
778
757
  const expiresAtMs = Date.parse(submission.expiresAt);
@@ -799,11 +778,11 @@ export class MessageBridge {
799
778
  this.interactionRouter.register(submission.requestId, sessionId, async (action, _values, operatorId) => {
800
779
  if (action !== 'approve' && action !== 'reject' && action !== 'block')
801
780
  return false;
802
- const reviewed = await reviewContactRequest({
781
+ const reviewed = await reviewPeerRequest({
803
782
  selfAid,
804
783
  primaryId: applicantAid,
805
784
  requestId: submission.requestId,
806
- expectedContactRevision: submission.contactRevision,
785
+ expectedContactRevision: submission.peerRevision,
807
786
  approverId: route.approverOperatorId,
808
787
  actorId: String(operatorId || ''),
809
788
  decision: action,
@@ -828,7 +807,7 @@ export class MessageBridge {
828
807
  timeoutMs: Math.max(1, expiresAtMs - Date.now()),
829
808
  initiatorId: route.approverOperatorId,
830
809
  initiatorChannelKey: route.approverChannelKey,
831
- onTimeout: () => { void expirePendingContactRequests(selfAid); },
810
+ onTimeout: () => { void expirePendingPeerRequests(selfAid); },
832
811
  onCancel: reason => route.adapter.invalidateInteraction?.(submission.requestId, reason),
833
812
  });
834
813
  const envelope = buildEnvelope({
@@ -989,7 +968,7 @@ export class MessageBridge {
989
968
  }
990
969
  const ownershipFailure = selfAid ? ownerResolver.snapshot(selfAid) : undefined;
991
970
  if (!trustedHandoffEcho && !admissionPreflight.context.isOwner
992
- && (admissionPreflight.allow || admissionPreflight.reason === 'restricted_mode_without_owner')
971
+ && admissionPreflight.allow
993
972
  && admissionPreflight.context.primaryId
994
973
  && !/^\s*\/(?:bind|request)(?:\s|$)/i.test(content)
995
974
  && ownershipFailure?.refreshFailure
@@ -1009,7 +988,6 @@ export class MessageBridge {
1009
988
  return;
1010
989
  }
1011
990
  if (!admissionPreflight.allow) {
1012
- const requestCommand = /^\s*\/request(?:\s|$)/i.test(content);
1013
991
  if (admissionPreflight.reason === 'blocked' && admissionPreflight.context.primaryId) {
1014
992
  const primaryId = admissionPreflight.context.primaryId;
1015
993
  let peerType = msg.peerType;
@@ -1023,9 +1001,6 @@ export class MessageBridge {
1023
1001
  }
1024
1002
  logger.info(`[MessageBridge] Blocked canonical inbound before business routing: self=${selfAid} peer=${primaryId} type=${peerType ?? 'unknown'} channel=${channelKey}`);
1025
1003
  }
1026
- else if (admissionPreflight.reason === 'restricted_mode_without_owner' && requestCommand) {
1027
- await this.sendAdmissionControlReply(admissionPreflight.context, msg, sendReply, '当前无法受理联系人申请。');
1028
- }
1029
1004
  else {
1030
1005
  logger.warn(`[MessageBridge] Admission preflight denied: self=${selfAid ?? '<none>'} actor=${actorId ?? '<none>'} channel=${channelKey} reason=${admissionPreflight.reason}`);
1031
1006
  }
@@ -1055,9 +1030,8 @@ export class MessageBridge {
1055
1030
  return;
1056
1031
  }
1057
1032
  const admissionDecision = evaluateOrdinaryInboundAdmission(admissionPreflight.context);
1058
- const directoryDenied = !admissionDecision.allow && (admissionDecision.reason === 'owner_directory_contacts_disabled'
1059
- || admissionDecision.reason === 'owner_agent_directory_disabled'
1060
- || admissionDecision.reason === 'owner_directory_unavailable');
1033
+ // 名录不可用等硬性拒绝不回自动提示,静默丢弃;其余拒绝才发控制面提示。
1034
+ const directoryDenied = !admissionDecision.allow && (admissionDecision.reason === 'owner_directory_unavailable');
1061
1035
  if (!admissionDecision.allow && (!isPrivateMenuTokenRequest || directoryDenied)) {
1062
1036
  if (chatType === 'private' && !directoryDenied) {
1063
1037
  if (menuControl.isMenu) {
@@ -1157,6 +1131,10 @@ export class MessageBridge {
1157
1131
  return;
1158
1132
  }
1159
1133
  }
1134
+ const fullAccessCommand = parseFullAccessCommand(content);
1135
+ if (fullAccessCommand.matched) {
1136
+ await refreshOwnershipForAuthorization(selfAid, { includeDaemon: true, allowTransient: true });
1137
+ }
1160
1138
  const roleDetail = trustedHandoffEcho
1161
1139
  ? {
1162
1140
  effectiveRole: 'owner',
@@ -1199,8 +1177,14 @@ export class MessageBridge {
1199
1177
  await this.handleMenuControl(menuControl, channelName, resolvedChannelType, msg, adapter, authSubject, menuResponseWarning);
1200
1178
  return;
1201
1179
  }
1202
- // 普通消息保留原始日志;控制 payload 使用脱敏元数据日志。
1203
- logger.channelIn({ channel: channelName, channelId: msg.channelId, selfAid: msg.selfAID, peerId: msg.peerId, peerName: msg.peerName, chatType: msg.chatType, msgId: msg.messageId, correlationId: msg.messageId, threadId: msg.threadId, content, images: msg.images?.length ?? 0, mentions: msg.mentions, replyContext: msg.replyContext });
1180
+ // 可选渠道审计只保留预览与元数据;控制 payload 使用脱敏元数据。
1181
+ logger.channelIn({
1182
+ channel: channelName, channelId: msg.channelId, selfAid: msg.selfAID, peerId: msg.peerId,
1183
+ peerName: msg.peerName, chatType: msg.chatType, msgId: msg.messageId,
1184
+ correlationId: msg.messageId, threadId: msg.threadId,
1185
+ content: logPreview(content), textPreview: logPreview(content), textBytes: Buffer.byteLength(content, 'utf8'),
1186
+ images: msg.images?.length ?? 0, mentions: msg.mentions,
1187
+ });
1204
1188
  const accessDecision = authorizeAccess(authSubject);
1205
1189
  if (!accessDecision.allow) {
1206
1190
  logger.warn(`[MessageBridge] Access denied before command routing: channel=${channelName} channelId=${msg.channelId} actor=${actorId ?? '<none>'} role=${identity.role} reason=${accessDecision.reason}`);
@@ -1241,7 +1225,6 @@ export class MessageBridge {
1241
1225
  // /fa on/off controls the current session; other non-empty arguments
1242
1226
  // request one fullaccess run. Only this trusted inbound path can create
1243
1227
  // the per-call authorization carried into ResponseEngine.
1244
- const fullAccessCommand = parseFullAccessCommand(content);
1245
1228
  if (fullAccessCommand.matched) {
1246
1229
  const groupGuard = guardGroupSlashCommand(content, chatType);
1247
1230
  if (groupGuard?.kind === 'command.error') {
@@ -1414,7 +1397,7 @@ export class MessageBridge {
1414
1397
  && !executionPermissionOverride
1415
1398
  && await this.handleCommand(cmdContent, channelName, msg.channelId, (text) => {
1416
1399
  const taskId = `cmd-${msg.messageId || Date.now()}`;
1417
- logger.channelOut({ channel: channelName, channelId: msg.channelId, taskId, correlationId: taskId, sessionId: msg.replyContext?.sessionId, agentAid: msg.selfAID, payload: { kind: 'command.result', text } });
1400
+ logger.channelOut({ channel: channelName, channelId: msg.channelId, taskId, correlationId: taskId, sessionId: msg.replyContext?.sessionId, agentAid: msg.selfAID, payload: { kind: 'command.result', textPreview: logPreview(text), textBytes: Buffer.byteLength(text, 'utf8') } });
1418
1401
  return sendReply(msg.channelId, text, msg.replyContext);
1419
1402
  }, msg.peerId, msg.threadId, msg.chatType, msg.source, msg.replyContext, msg.messageId, msg.selfAID, authSubject))
1420
1403
  return;
@@ -2408,6 +2391,7 @@ export class MessageBridge {
2408
2391
  source: 'agent-aun',
2409
2392
  selfAid: msg.selfAID ?? this.agentRegistry?.resolveByChannel(channel)?.aid,
2410
2393
  messageId: msg.messageId,
2394
+ requesterAid: msg.peerId,
2411
2395
  };
2412
2396
  }
2413
2397
  cancel(messageId, selfAID) {
@@ -1647,6 +1647,13 @@ export class MessageQueue {
1647
1647
  enqueuedAt: earliestEnqueuedAt,
1648
1648
  };
1649
1649
  }
1650
+ /** 所有 session 队列里尚未开始处理的条目总数(启动恢复日志用)。 */
1651
+ getTotalQueueLength() {
1652
+ let total = 0;
1653
+ for (const queue of this.queues.values())
1654
+ total += queue.length;
1655
+ return total;
1656
+ }
1650
1657
  getQueueLength(sessionKey) {
1651
1658
  // 计算该 sessionKey 下所有项目队列的总长度
1652
1659
  let total = 0;