evolcore 0.0.48 → 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 (112) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/agent-template/runtime.js +5 -2
  3. package/dist/agents/codex-runner.js +5 -1
  4. package/dist/aun/msg/p2p.js +2 -1
  5. package/dist/build-identity.json +1 -1
  6. package/dist/channels/aun.js +643 -273
  7. package/dist/cli/directory.js +6 -1
  8. package/dist/cli/index.js +7 -1
  9. package/dist/cli/managed-command-guard.js +2 -0
  10. package/dist/cli/model.js +20 -5
  11. package/dist/cli/quota.js +89 -0
  12. package/dist/cli/role.js +1 -0
  13. package/dist/cli/services-command.js +1 -0
  14. package/dist/cli/team-workspace-command.js +56 -2
  15. package/dist/config/config-field-policy.js +71 -1
  16. package/dist/config/config-manager.js +11 -1
  17. package/dist/config/providers-config.js +8 -4
  18. package/dist/config/providers-management.js +11 -3
  19. package/dist/config/resolved-config-op.js +3 -2
  20. package/dist/core/auth/delegation-authorization.js +33 -26
  21. package/dist/core/auth/operation-catalog.js +9 -0
  22. package/dist/core/command/cli-intent-parser.js +13 -0
  23. package/dist/core/command/command-handler.js +45 -2
  24. package/dist/core/command/menu-handler.js +6 -1
  25. package/dist/core/command/menu-protocol.js +24 -0
  26. package/dist/core/command/remote-shell.js +565 -0
  27. package/dist/core/daemon-control.js +57 -1
  28. package/dist/core/daemon-lifecycle.js +16 -2
  29. package/dist/core/evolagent-registry.js +6 -2
  30. package/dist/core/ipc-registration.js +1 -0
  31. package/dist/core/message/aun-ipc-sender.js +118 -56
  32. package/dist/core/message/contact-admission.js +91 -6
  33. package/dist/core/message/contact-pending-inbound.js +113 -0
  34. package/dist/core/message/contact-thread-approval.js +212 -0
  35. package/dist/core/message/im-renderer.js +40 -1
  36. package/dist/core/message/message-admission.js +5 -39
  37. package/dist/core/message/message-bridge.js +92 -39
  38. package/dist/core/message/message-log.js +24 -0
  39. package/dist/core/message/message-queue.js +97 -15
  40. package/dist/core/message/response-engine.js +151 -18
  41. package/dist/core/model/config-scope.js +6 -14
  42. package/dist/core/model/model-diagnostics.js +19 -0
  43. package/dist/core/model/model-fallback.js +13 -2
  44. package/dist/core/pack-auth.js +3 -0
  45. package/dist/core/pack-install.js +1 -1
  46. package/dist/core/permission/ec-command-parser.js +106 -19
  47. package/dist/core/permission/services-path-acl.js +451 -0
  48. package/dist/core/permission/tool-policy.js +5 -1
  49. package/dist/core/relation/peer-identity.js +13 -0
  50. package/dist/core/task/task-recovery-service.js +1 -0
  51. package/dist/core/thread/topic-id.js +15 -0
  52. package/dist/directory/owner-directory-admission.js +11 -8
  53. package/dist/directory/owner-directory-cache.js +19 -0
  54. package/dist/directory/owner-directory-markdown.js +1 -1
  55. package/dist/directory/owner-directory-policy.js +5 -30
  56. package/dist/directory/owner-directory-request-operation.js +5 -2
  57. package/dist/eck/kit-renderer.js +1 -1
  58. package/dist/eck/message-renderer.js +28 -5
  59. package/dist/ecweb/runtime/supervisor.js +36 -8
  60. package/dist/event-center/center-config.js +9 -5
  61. package/dist/event-center/dispatcher.js +10 -1
  62. package/dist/event-center/ipc-operation.js +19 -0
  63. package/dist/event-center/registry.js +20 -5
  64. package/dist/event-center/runtime.js +10 -7
  65. package/dist/index.js +4 -0
  66. package/dist/ipc.js +25 -1
  67. package/dist/outputs/authorization.js +16 -0
  68. package/dist/outputs/cards.js +336 -0
  69. package/dist/outputs/events.js +3 -2
  70. package/dist/outputs/protocol.js +1 -0
  71. package/dist/outputs/service.js +2 -15
  72. package/dist/services/index.js +29 -5
  73. package/dist/services/ipc-operation.js +84 -0
  74. package/dist/services/pack-manager.js +1 -0
  75. package/dist/services/service-payload.js +13 -7
  76. package/dist/stats/budget.js +1 -1
  77. package/dist/stats/model-resolver.js +2 -2
  78. package/dist/stats/quota-query.js +95 -0
  79. package/dist/trigger/script-sandbox.js +12 -0
  80. package/dist/utils/atomic-write.js +22 -8
  81. package/dist/utils/evolcore-version.js +2 -2
  82. package/dist/utils/host-info.js +100 -1
  83. package/dist/utils/npm-ops.js +43 -8
  84. package/dist/workbench/service.js +1 -1
  85. package/kits/docs/evolcore/INDEX.md +2 -0
  86. package/kits/docs/evolcore/aid.md +25 -0
  87. package/kits/docs/evolcore/config.md +4 -1
  88. package/kits/docs/evolcore/directory.md +8 -9
  89. package/kits/docs/evolcore/msg.md +9 -0
  90. package/kits/docs/evolcore/provider.md +1 -1
  91. package/kits/docs/evolcore/quota.md +54 -0
  92. package/kits/docs/evolcore/role.md +3 -0
  93. package/kits/docs/evolcore/stats.md +2 -0
  94. package/kits/docs/evolcore/trigger.md +2 -0
  95. package/kits/schemas/agent-config.schema.20.json +24 -0
  96. package/kits/skills/.switches.json +4 -0
  97. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  98. package/kits/skills/ec-provider/SKILL.md +57 -8
  99. package/kits/templates/roles/visitor.json +1 -0
  100. package/kits/templates/system-fragments/commands.md +1 -0
  101. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  102. package/kits/templates/system-fragments/thread.md +1 -0
  103. package/kits/templates/system-fragments/venue.md +11 -0
  104. package/package.json +2 -2
  105. package/scripts/agent-template/inspect.mjs +46 -10
  106. package/scripts/agent-template/shared/common.mjs +9 -3
  107. package/scripts/agent-template/shared/team-schema.json +6 -4
  108. package/scripts/agent-template/shared/template-contract.mjs +60 -10
  109. package/scripts/agent-template/shared/template-package.mjs +182 -21
  110. package/scripts/agent-template/shared/template-runtime.mjs +35 -2
  111. package/scripts/agent-template/shared/template.mjs +2 -2
  112. package/scripts/agent-template/team-pack.mjs +46 -11
@@ -0,0 +1,212 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { contactAdmissionDirectory } from '../../directory/contact-admission-paths.js';
5
+ import { atomicWriteJson } from '../../utils/atomic-write.js';
6
+ import { ThreadService } from '../thread/thread-service.js';
7
+ import { ThreadContextStorage } from '../thread/thread-context-storage.js';
8
+ import { isTopicThreadId, normalizeThreadIdForPeer } from '../thread/topic-id.js';
9
+ import { currentContactBinding, sameContactBinding } from './contact-admission.js';
10
+ import { CONTACT_RECEIPT_TTL_MS, readPendingContactInbound } from './contact-pending-inbound.js';
11
+ const PREPARED_TTL_MS = 30_000;
12
+ const MAX_RECORDS = 10_000;
13
+ function file(selfAid, kind, id) {
14
+ if (!/^[a-f0-9]{64}$/.test(id))
15
+ throw new Error('invalid contact thread state key');
16
+ return path.join(contactAdmissionDirectory(selfAid), kind, `${id}.json`);
17
+ }
18
+ function hash(value) { return crypto.createHash('sha256').update(value).digest('hex'); }
19
+ function read(filename) {
20
+ try {
21
+ return JSON.parse(fs.readFileSync(filename, 'utf8'));
22
+ }
23
+ catch (error) {
24
+ if (error.code === 'ENOENT')
25
+ return undefined;
26
+ throw error;
27
+ }
28
+ }
29
+ function records(selfAid, kind, prune = false) {
30
+ const directory = path.join(contactAdmissionDirectory(selfAid), kind);
31
+ let names;
32
+ try {
33
+ names = fs.readdirSync(directory);
34
+ }
35
+ catch (error) {
36
+ if (error.code === 'ENOENT')
37
+ return [];
38
+ throw error;
39
+ }
40
+ const values = [];
41
+ for (const name of names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
42
+ const filename = path.join(directory, name);
43
+ const value = read(filename);
44
+ if (!value || !Number.isSafeInteger(value.expiresAt))
45
+ throw new Error('invalid contact thread state');
46
+ if (prune && value.expiresAt <= Date.now()) {
47
+ fs.rmSync(filename, { force: true });
48
+ fs.rmSync(filename + '_', { force: true });
49
+ }
50
+ else
51
+ values.push(value);
52
+ }
53
+ return values;
54
+ }
55
+ function activeDelegations(selfAid, binding, peer, threadId) {
56
+ const now = Date.now();
57
+ return records(selfAid, 'thread-delegations').filter(record => record.version === 1 && sameContactBinding(record.binding, binding)
58
+ && record.targetAid === peer && record.targetThreadId === threadId && record.expiresAt > now);
59
+ }
60
+ function uniqueDelegationOrigin(candidates) {
61
+ const origins = new Map(candidates.map(record => [JSON.stringify([record.originThreadId, record.originSessionId]), record]));
62
+ return origins.size === 1 ? origins.values().next().value : undefined;
63
+ }
64
+ /** Persist before handing the send to a transport, so an immediate reply cannot outrun its provenance. */
65
+ export function prepareContactThreadDelegation(input) {
66
+ const { selfAid, grant, runtime, target } = input;
67
+ const binding = currentContactBinding(selfAid);
68
+ if (!binding || grant.selfAid !== selfAid || grant.actorId !== binding.owner_aid
69
+ || grant.channelType !== 'aun' || grant.chatType !== 'private' || grant.systemSession
70
+ || runtime?.selfAid !== selfAid || runtime.channel !== 'aun' || runtime.chatType !== 'private'
71
+ || runtime.channelId !== binding.owner_aid || grant.peerKey !== `aun#${binding.owner_aid}`
72
+ || (target.channelType ?? 'aun') !== 'aun' || target.peerKind !== 'private'
73
+ || target.peer === selfAid || target.peer === binding.owner_aid)
74
+ return undefined;
75
+ const originThreadId = normalizeThreadIdForPeer(runtime.threadId, selfAid, binding.owner_aid);
76
+ const targetThreadId = normalizeThreadIdForPeer(input.targetThreadId, selfAid, target.peer);
77
+ if (!originThreadId || !targetThreadId
78
+ || normalizeThreadIdForPeer(input.wireThreadId, selfAid, target.peer) !== targetThreadId)
79
+ return undefined;
80
+ const origin = isTopicThreadId(originThreadId)
81
+ ? ThreadService.findThreadById(selfAid, originThreadId)
82
+ : ThreadService.findMainSessionEntry(selfAid, binding.owner_aid);
83
+ if (!origin || origin.sessionId !== grant.sessionId || origin.peer !== binding.owner_aid
84
+ || origin.peerKind !== 'private' || (origin.channelType ?? 'aun') !== 'aun')
85
+ return undefined;
86
+ if (records(selfAid, 'thread-delegations', true).length >= MAX_RECORDS)
87
+ throw new Error('contact delegation capacity reached');
88
+ const id = hash(crypto.randomUUID());
89
+ const createdAt = Date.now();
90
+ const record = { version: 1, id, binding, originThreadId,
91
+ originSessionId: grant.sessionId, targetAid: target.peer, targetThreadId,
92
+ createdAt, expiresAt: createdAt + CONTACT_RECEIPT_TTL_MS, submitted: false };
93
+ atomicWriteJson(file(selfAid, 'thread-delegations', id), record);
94
+ return id;
95
+ }
96
+ export function finishContactThreadDelegation(selfAid, id, messageId) {
97
+ const filename = file(selfAid, 'thread-delegations', id);
98
+ const record = read(filename);
99
+ if (!record)
100
+ return;
101
+ if (!messageId) {
102
+ fs.rmSync(filename, { force: true });
103
+ fs.rmSync(filename + '_', { force: true });
104
+ return;
105
+ }
106
+ atomicWriteJson(filename, { ...record, submitted: true, messageId });
107
+ }
108
+ export function findContactThreadDelegation(selfAid, binding, fromAid, payload, receivedAt) {
109
+ const threadId = normalizeThreadIdForPeer(payload.thread_id, selfAid, fromAid);
110
+ if (!threadId)
111
+ return { defer: false };
112
+ const matches = activeDelegations(selfAid, binding, fromAid, threadId).filter(record => record.createdAt <= receivedAt);
113
+ const submitted = matches.filter(record => record.submitted);
114
+ const ref = typeof payload.ref_message_id === 'string' ? payload.ref_message_id : undefined;
115
+ const exact = ref ? submitted.filter(record => record.messageId === ref) : [];
116
+ // A supplied, unknown reference cannot be used to choose among several origins.
117
+ const candidates = exact.length ? exact : submitted;
118
+ if (!exact.length && matches.some(record => !record.submitted && record.createdAt + PREPARED_TTL_MS > Date.now())) {
119
+ return { defer: true };
120
+ }
121
+ const origin = uniqueDelegationOrigin(candidates);
122
+ if (!origin)
123
+ return { defer: false };
124
+ return { defer: false, origin: { eventId: '', originThreadId: origin.originThreadId, originSessionId: origin.originSessionId } };
125
+ }
126
+ /** Resolve an implicit report to Owner from durable local provenance, never wire topic_source. */
127
+ export function findContactThreadReturn(input) {
128
+ const { selfAid, grant, runtime } = input;
129
+ const binding = currentContactBinding(selfAid);
130
+ const peer = runtime.channelId;
131
+ if (!binding || !peer || peer === selfAid || peer === binding.owner_aid
132
+ || grant.selfAid !== selfAid || grant.channelType !== 'aun' || grant.chatType !== 'private' || grant.systemSession
133
+ || runtime.selfAid !== selfAid || runtime.sessionId !== grant.sessionId
134
+ || runtime.channel !== 'aun' || runtime.chatType !== 'private'
135
+ || grant.actorId !== peer || grant.peerKey !== `aun#${peer}` || runtime.peerKey !== grant.peerKey)
136
+ return undefined;
137
+ const threadId = normalizeThreadIdForPeer(runtime.threadId, selfAid, peer);
138
+ if (!threadId)
139
+ return undefined;
140
+ const target = isTopicThreadId(threadId)
141
+ ? ThreadService.findThreadById(selfAid, threadId) : ThreadService.findMainSessionEntry(selfAid, peer);
142
+ if (!target || target.sessionId !== grant.sessionId || target.peer !== peer
143
+ || target.peerKind !== 'private' || (target.channelType ?? 'aun') !== 'aun')
144
+ return undefined;
145
+ const record = uniqueDelegationOrigin(activeDelegations(selfAid, binding, peer, threadId).filter(record => record.submitted));
146
+ if (!record)
147
+ return undefined;
148
+ const origin = isTopicThreadId(record.originThreadId)
149
+ ? ThreadService.findThreadById(selfAid, record.originThreadId)
150
+ : ThreadService.findMainSessionEntry(selfAid, binding.owner_aid);
151
+ if (!origin || origin.sessionId !== record.originSessionId || origin.peer !== binding.owner_aid
152
+ || origin.peerKind !== 'private' || (origin.channelType ?? 'aun') !== 'aun'
153
+ || normalizeThreadIdForPeer(origin.threadId, selfAid, binding.owner_aid) !== record.originThreadId)
154
+ return undefined;
155
+ return { eventId: '', originThreadId: record.originThreadId, originSessionId: record.originSessionId };
156
+ }
157
+ export function isContactApprovalCard(payload) {
158
+ return payload?.type === 'action_card' && payload.card_kind === 'friend_request';
159
+ }
160
+ export function buildContactApprovalCard(request, approval) {
161
+ return {
162
+ type: 'action_card', card_kind: 'friend_request', blocking: false,
163
+ ...(isTopicThreadId(approval.originThreadId) ? { thread_id: approval.originThreadId } : {}),
164
+ title: request.reason === 'scope_extension' ? '联系人回复待授权' : '联系人回复待确认',
165
+ text: `您委托联系的 ${request.applicant_aid} 发来消息:\n\n${request.introduction.text}\n\n是否添加好友并允许本 Agent 继续处理?`,
166
+ actions: [
167
+ { label: request.reason === 'scope_extension' ? '允许本 Agent 并继续' : '添加好友并继续', value: 'approve', behavior: 'reply', style: 'primary' },
168
+ { label: '拒绝', value: 'reject', behavior: 'reply' },
169
+ ],
170
+ friend_request: request,
171
+ };
172
+ }
173
+ /** Restore provenance even when a review already consumed the original one-shot thread inbox. */
174
+ export function ensureContactApprovalThreadContext(selfAid, pending, sessionId) {
175
+ const approval = pending.approval;
176
+ if (!approval)
177
+ return;
178
+ const messageId = `contact-approval:${approval.eventId}`;
179
+ const storage = new ThreadContextStorage();
180
+ if (storage.readAll(selfAid, sessionId).some(entry => entry.messageId === messageId))
181
+ return;
182
+ storage.append(selfAid, {
183
+ messageId, content: '联系人准入已生效,请继续处理原委托中对方的回复。',
184
+ timestamp: pending.receivedAt, originThreadId: approval.originThreadId,
185
+ originPeer: pending.binding.owner_aid, originSessionId: approval.originSessionId,
186
+ targetSessionId: sessionId,
187
+ });
188
+ }
189
+ /** Durable binding does not depend on the generic interaction router's in-memory callbacks. */
190
+ export function registerContactApprovalCard(selfAid, pendingKey, eventId, messageId) {
191
+ const pending = readPendingContactInbound(selfAid, pendingKey);
192
+ if (!pending?.approval || pending.approval.eventId !== eventId)
193
+ throw new Error('contact approval event mismatch');
194
+ const filename = file(selfAid, 'approval-cards', hash(messageId));
195
+ const previous = read(filename);
196
+ if (previous) {
197
+ if (previous.messageId !== messageId || previous.pendingKey !== pendingKey || previous.eventId !== eventId) {
198
+ throw new Error('contact approval card identity conflict');
199
+ }
200
+ return;
201
+ }
202
+ if (records(selfAid, 'approval-cards', true).length >= MAX_RECORDS)
203
+ throw new Error('contact approval card capacity reached');
204
+ atomicWriteJson(filename, { version: 1, messageId, pendingKey, eventId,
205
+ expiresAt: pending.receivedAt + CONTACT_RECEIPT_TTL_MS });
206
+ }
207
+ export function readContactApprovalCard(selfAid, messageId) {
208
+ const record = read(file(selfAid, 'approval-cards', hash(messageId)));
209
+ if (record && (record.version !== 1 || record.messageId !== messageId))
210
+ throw new Error('invalid contact approval card');
211
+ return record;
212
+ }
@@ -104,7 +104,34 @@ export class IMRenderer {
104
104
  return;
105
105
  this.recordActivity(item);
106
106
  if (!this.suppressProactiveItem(item)) {
107
- await this.sendPayload({ kind: 'activity.batch', items: [item], isFinal: true });
107
+ logger.info(`[IMRenderer] proactive.final.attempt ${JSON.stringify({
108
+ taskId: this.opts.envelope.taskId,
109
+ sessionId: this.opts.envelope.sessionId ?? 'none',
110
+ textLength: item.text.length,
111
+ })}`);
112
+ try {
113
+ await this.sendPayload({ kind: 'activity.batch', items: [item], isFinal: true });
114
+ logger.info(`[IMRenderer] proactive.final.accepted ${JSON.stringify({
115
+ taskId: this.opts.envelope.taskId,
116
+ sessionId: this.opts.envelope.sessionId ?? 'none',
117
+ })}`);
118
+ }
119
+ catch (error) {
120
+ logger.error(`[IMRenderer] proactive.final.failed ${JSON.stringify({
121
+ taskId: this.opts.envelope.taskId,
122
+ sessionId: this.opts.envelope.sessionId ?? 'none',
123
+ error: error instanceof Error ? error.message : String(error),
124
+ code: error?.code,
125
+ })}`);
126
+ throw error;
127
+ }
128
+ }
129
+ else {
130
+ logger.info(`[IMRenderer] proactive.final.suppressed ${JSON.stringify({
131
+ taskId: this.opts.envelope.taskId,
132
+ sessionId: this.opts.envelope.sessionId ?? 'none',
133
+ reason: 'renderer_policy',
134
+ })}`);
108
135
  }
109
136
  }
110
137
  releaseProactiveFinal() {
@@ -150,6 +177,18 @@ export class IMRenderer {
150
177
  async flush(isFinal, attention) {
151
178
  await this.activityRecordChain;
152
179
  if (this.usesProactiveBehavior()) {
180
+ if (isFinal) {
181
+ logger.info(`[IMRenderer] proactive.flush ${JSON.stringify({
182
+ taskId: this.opts.envelope.taskId,
183
+ sessionId: this.opts.envelope.sessionId ?? 'none',
184
+ activityTransport: this.opts.envelope.activityTransport ?? 'none',
185
+ customFinal: this.usesCustomFinal(),
186
+ deferredTextCount: this.deferredProactiveText.length,
187
+ pendingFinal: !!this.pendingProactiveFinal,
188
+ suppressIntermediateText: this.suppressIntermediateText(),
189
+ suppressActivities: this.suppressActivityItems(),
190
+ })}`);
191
+ }
153
192
  if (isFinal === false && this.usesCustomFinal())
154
193
  this.releaseProactiveFinal();
155
194
  if (isFinal) {
@@ -2,47 +2,13 @@ import { readAccessPolicy, } from '../../config/access-policy.js';
2
2
  import { resolvePeerView, resolvePrincipal, } from '../../config/peer-book.js';
3
3
  import { isValidAid } from '../../aun/aid/validation.js';
4
4
  import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
5
- import { resolveAunPeerKind } from '../relation/peer-identity.js';
6
5
  import { evaluateAppContactAdmission } from './contact-admission.js';
7
- import { ownerResolver, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
8
- /**
9
- * AUN 出站私聊固定使用 app-v1,与入站保持相同的绑定和联系人判定。
10
- * 群聊的准入单位是群,出站到群不做发言人判定。
11
- */
6
+ /** @deprecated Ordinary outbound messages have no contact admission gate. */
12
7
  export async function evaluateOutboundContactAdmission(input) {
13
- const selfAid = String(input.selfAid || '').trim();
14
- const targetAid = String(input.targetAid || '').trim();
15
- if (!isValidAid(selfAid) || !isValidAid(targetAid)) {
16
- return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: 'A valid Agent AID is required for outbound contact admission' };
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' };
23
- let decision;
24
- try {
25
- await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
26
- decision = evaluateAppContactAdmission(selfAid, targetAid);
27
- }
28
- catch (error) {
29
- return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
30
- }
31
- if (decision.allow) {
32
- if (decision.reason === 'owner')
33
- return { allow: true, status: 'owner' };
34
- if (decision.reason === 'temporary')
35
- return { allow: true, status: 'temporary' };
36
- if (decision.reason === 'open') {
37
- const policy = readAccessPolicy(selfAid);
38
- return { allow: true, status: policy.allowedAids?.includes(targetAid) ? 'allowed_aid' : 'all_contacts' };
39
- }
40
- return { allow: true, status: 'contact' };
8
+ if (!isValidAid(input.selfAid) || !isValidAid(input.targetAid)) {
9
+ return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: 'A valid sender and target AID are required' };
41
10
  }
42
- return { allow: false, code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE'
43
- : decision.reason === 'blocked' ? 'CONTACT_BLOCKED' : 'CONTACT_DENIED',
44
- status: decision.reason === 'unavailable' ? 'unavailable' : decision.reason === 'blocked' ? 'blocked' : 'denied',
45
- error: `联系人准入未通过:${decision.reason}` };
11
+ return { allow: true, status: 'unrestricted' };
46
12
  }
47
13
  export function evaluateInboundAdmissionPreflight(input) {
48
14
  const selfAid = String(input.selfAid || '').trim();
@@ -162,7 +128,7 @@ export function evaluateOwnerDirectoryInboundAdmission(context) {
162
128
  }
163
129
  }
164
130
  /**
165
- * 普通消息准入。出站私聊复用同一套判定,保证出入站对称。
131
+ * 普通消息入站准入。出站不执行联系人准入。
166
132
  *
167
133
  * 顺序:可信 handoff → Owner/个人助理 → 群聊(准入单位是整个群)→ 黑名单
168
134
  * → `allowAllContacts` 总开关 → 名录不可用 → 白名单 → 名录三档。
@@ -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,7 +11,7 @@ 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 { appendMessageLog, appendMessageLogStrict, appendInboundMessageLogOnce, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
14
15
  import { buildEnvelope } from './message-utils.js';
15
16
  import { chatDirPath } from '../session/session-fs-store.js';
16
17
  import { readTopicStatus } from '../session/session-mapper.js';
@@ -22,14 +23,14 @@ import { isValidAid } from '../../aun/aid/validation.js';
22
23
  import { prepareOwnerDirectoryAdmission } from '../../directory/owner-directory-admission.js';
23
24
  import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
24
25
  import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
25
- import { isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
26
+ import { isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
26
27
  import { resolveEffective } from '../../config/config-manager.js';
27
28
  import { createDecisionInferenceProvider } from '../inference/text-inference.js';
28
29
  import { AutoMentionGate } from './auto-mention-gate.js';
29
30
  import { syncGroupRulesContext } from '../../eck/group-rules-sync.js';
30
31
  import { readSoulContent } from '../soul.js';
31
32
  import { authorizeAccess, buildAuthSubject } from '../auth/auth-gateway.js';
32
- 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';
33
34
  import { resolveExplicitMenuExecutionContext, validateMenuCatalogArgs, validateMenuValueBatchArgs } from '../command/menu-catalog.js';
34
35
  import { MenuTokenStore } from '../command/menu-token-store.js';
35
36
  import { SessionRenewService } from '../session/session-renew.js';
@@ -45,8 +46,12 @@ const REJECTABLE_PEER_TYPES = new Set(['ai', 'bot', 'agent', 'service']);
45
46
  const REJECTION_MAX = 3;
46
47
  const REJECTION_WINDOW_MS = 60 * 60 * 1000;
47
48
  const rejectionState = new Map();
48
- /** Topic admission runs after session resolution and before task queueing. */
49
- function decideTopicInbound(input) {
49
+ /**
50
+ * Topic admission runs after session resolution and before task queueing.
51
+ *
52
+ * 纯函数,导出以便单测直接覆盖各状态组合(回退 / 丢弃 / 是否回文案)。
53
+ */
54
+ export function decideTopicInbound(input) {
50
55
  if (!input.isTopic)
51
56
  return { action: 'proceed', reopen: false, replyArchived: false };
52
57
  if (input.topicStatus === 'archived') {
@@ -553,6 +558,19 @@ export class MessageBridge {
553
558
  register(channelName, onMessage, sendReply, adapter, channelType) {
554
559
  const effectiveChannelType = channelType || channelName;
555
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
+ }
556
574
  let releaseAdmission;
557
575
  let releaseSessionIngress;
558
576
  const releaseIngress = () => {
@@ -587,6 +605,10 @@ export class MessageBridge {
587
605
  const menuControl = resolvedChannelType === 'aun'
588
606
  ? parseMenuControl(content)
589
607
  : { isMenu: false };
608
+ if (menuControl.isMenu) {
609
+ Object.assign(msg, menuTiming);
610
+ this.logMenuInbound(channelName, msg, menuControl);
611
+ }
590
612
  const isPrivateMenuTokenRequest = menuControl.isMenu
591
613
  && menuControl.type === 'menu.token.request'
592
614
  && chatType === 'private';
@@ -605,10 +627,10 @@ export class MessageBridge {
605
627
  // a sender against an expired or invalidated ownership cache.
606
628
  const ownership = ownerResolver.snapshot(selfAid);
607
629
  if (ownership.connected || ownership.relation) {
608
- await ownerResolver.refresh(selfAid, {
630
+ await traceMenuStage(menuControl.isMenu ? menuControl.request : undefined, this.menuFlowContext(channelName, msg), menuTiming, 'bridge.ownership', () => ownerResolver.refresh(selfAid, {
609
631
  maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
610
632
  allowTransient: true,
611
- });
633
+ }));
612
634
  }
613
635
  }
614
636
  const admissionPreflight = evaluateInboundAdmissionPreflight({
@@ -680,6 +702,8 @@ export class MessageBridge {
680
702
  return;
681
703
  }
682
704
  if (!trustedHandoffEcho && selfAid && actorId && this.groupInviteReviewService) {
705
+ if (contactDelivery && /^\s*\/invites(?:\s|$)/i.test(content))
706
+ contactDelivery.startCommand();
683
707
  const inviteCommand = await this.groupInviteReviewService.handleCommand({
684
708
  selfAid,
685
709
  ownerAid: actorId,
@@ -743,10 +767,6 @@ export class MessageBridge {
743
767
  });
744
768
  return;
745
769
  }
746
- // AUN captures this mark at its adapter boundary. Legacy/test
747
- // adapters fall back to the bridge entry mark captured above.
748
- Object.assign(msg, menuTiming);
749
- this.logMenuInbound(channelName, msg, menuControl);
750
770
  if (!hasValidMenuId(menuControl)) {
751
771
  this.logMenuDiagnostic('missing-id', channelName, msg, menuControl);
752
772
  logMenuRequestCompleted(menuControl.request, undefined, this.menuFlowContext(channelName, msg), {
@@ -1041,7 +1061,7 @@ export class MessageBridge {
1041
1061
  const inboundReplyTo = typeof msg.replyContext?.metadata?.refMessageId === 'string'
1042
1062
  ? msg.replyContext.metadata.refMessageId
1043
1063
  : null;
1044
- appendMessageLog(chatDir, buildInboundEntry({
1064
+ logInbound(chatDir, buildInboundEntry({
1045
1065
  from: msg.peerId || 'unknown',
1046
1066
  to: msg.selfAID || 'self',
1047
1067
  threadId: msg.threadId ?? '',
@@ -1067,6 +1087,8 @@ export class MessageBridge {
1067
1087
  logger.debug(`[MessageBridge] Failed to log inbound command: ${e}`);
1068
1088
  }
1069
1089
  }
1090
+ if (contactDelivery && isCmd)
1091
+ contactDelivery.startCommand();
1070
1092
  if (msg.source !== 'handoff'
1071
1093
  && !executionPermissionOverride
1072
1094
  && await this.handleCommand(cmdContent, channelName, msg.channelId, (text) => {
@@ -1075,6 +1097,10 @@ export class MessageBridge {
1075
1097
  return sendReply(msg.channelId, text, msg.replyContext);
1076
1098
  }, msg.peerId, msg.threadId, msg.chatType, msg.source, msg.replyContext, msg.messageId, msg.selfAID, authSubject))
1077
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?.();
1078
1104
  // 3. session 解析(使用 Channel 层填充的 chatType)
1079
1105
  if (!(await this.canCreateThreadSession(channelName, msg, chatType))) {
1080
1106
  // 静默丢弃:绝不向群里注入回复。
@@ -1185,7 +1211,15 @@ export class MessageBridge {
1185
1211
  if (!releaseAdmission)
1186
1212
  releaseAdmission = await this.acquireAdmission(admissionRoute);
1187
1213
  const hadMainSession = msg.threadId ? true : this.sessionManager.hasMainSession(channelName, msg.channelId, msg.channelType || effectiveChannelType, msg.selfAID || selfAid);
1188
- 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, 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));
1189
1223
  // 归档话题不再入队;closed 收到新消息时回退 active,主话题不受此状态影响。
1190
1224
  const topicGate = decideTopicInbound({
1191
1225
  isTopic: isTopicSession(session),
@@ -1226,7 +1260,7 @@ export class MessageBridge {
1226
1260
  const inboundCausation = restoredCausation
1227
1261
  ? deriveCausation(restoredCausation)
1228
1262
  : createRootCausation();
1229
- const renewResult = session.metadata?.diagnostic ? { session } : await this.sessionRenewService.resolve({
1263
+ const renewResult = session.metadata?.diagnostic || boundContactSession ? { session } : await this.sessionRenewService.resolve({
1230
1264
  session,
1231
1265
  channelName,
1232
1266
  channelType: msg.channelType || effectiveChannelType,
@@ -1243,6 +1277,8 @@ export class MessageBridge {
1243
1277
  causation: inboundCausation,
1244
1278
  });
1245
1279
  session = renewResult.session;
1280
+ if (contactDelivery)
1281
+ contactDelivery.bindSession(session.id);
1246
1282
  if (!executionPermissionOverride && selfAid && owningAgent?.aid === selfAid) {
1247
1283
  executionPermissionOverride = createAgentPolicyAuthorization({
1248
1284
  agentAid: selfAid, actor: roleDetail.actor, chatType,
@@ -1426,7 +1462,7 @@ export class MessageBridge {
1426
1462
  }
1427
1463
  }
1428
1464
  if (!handoffCandidate)
1429
- appendMessageLog(inboundEntry.chatDir, inboundEntry.entry);
1465
+ logInbound(inboundEntry.chatDir, inboundEntry.entry);
1430
1466
  if (autoResult && autoResult.batch.length > 1) {
1431
1467
  for (const item of autoResult.batch.slice(0, -1)) {
1432
1468
  const member = item.value;
@@ -1461,20 +1497,24 @@ export class MessageBridge {
1461
1497
  if (fullMessage.messageId && currentSessionBusy) {
1462
1498
  adapter?.acknowledge?.(fullMessage.messageId).catch(() => { });
1463
1499
  }
1464
- const isInterrupt = chatType !== 'group' && !handoffCandidate;
1465
- const attentionPolicy = fullMessage.attentionPolicy;
1500
+ const isInterrupt = chatType !== 'group' && !handoffCandidate && !contactDelivery;
1501
+ const attentionPolicy = contactDelivery ? 'defer' : fullMessage.attentionPolicy;
1466
1502
  const shouldInterrupt = isInterrupt || attentionPolicy === 'interrupt';
1467
1503
  const enqueueAgentName = owningAgent?.name ?? '<unknown>';
1468
1504
  const selfAID = session.selfAID;
1469
1505
  const doEnqueue = async (m) => {
1470
1506
  // A cancellation can arrive while this message is being debounced.
1471
- 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');
1472
1510
  return;
1473
- 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);
1474
1513
  try {
1475
1514
  return await enqueue(session.id, m, session.projectPath, {
1476
1515
  interruptible: shouldInterrupt,
1477
1516
  attentionPolicy,
1517
+ contactDelivery,
1478
1518
  interruptSamePeer: !shouldInterrupt && !attentionPolicy, // 旧群聊路径保留同人连发打断
1479
1519
  priority: attentionPolicy === 'interrupt',
1480
1520
  agentName: enqueueAgentName,
@@ -1497,7 +1537,7 @@ export class MessageBridge {
1497
1537
  throw error;
1498
1538
  }
1499
1539
  };
1500
- if (handoffCandidate) {
1540
+ if (handoffCandidate || contactDelivery) {
1501
1541
  await doEnqueue(fullMessage);
1502
1542
  }
1503
1543
  else if (isInterrupt) {
@@ -1516,6 +1556,7 @@ export class MessageBridge {
1516
1556
  }
1517
1557
  }
1518
1558
  catch (error) {
1559
+ contactFailed = true;
1519
1560
  if (isRetryableMenuTransportError(error)) {
1520
1561
  logger.warn(`[MessageBridge] Retryable response delivery unavailable for ${channelName}:`, error);
1521
1562
  }
@@ -1525,9 +1566,18 @@ export class MessageBridge {
1525
1566
  finally {
1526
1567
  releaseAdmission?.();
1527
1568
  releaseIngress();
1569
+ if (contactDelivery && !contactFailed && !contactDelivery.receipt) {
1570
+ this.messageQueue.finishContactDelivery(contactDelivery);
1571
+ }
1528
1572
  }
1529
1573
  });
1530
1574
  }
1575
+ contactDeliveryReceipt(key) {
1576
+ return this.messageQueue.contactDeliveryReceipt(key);
1577
+ }
1578
+ finishContactDelivery(delivery) {
1579
+ this.messageQueue.finishContactDelivery(delivery);
1580
+ }
1531
1581
  async acquireAdmission(key) {
1532
1582
  const previous = this.admissionLocks.get(key) ?? Promise.resolve();
1533
1583
  let release;
@@ -1586,23 +1636,26 @@ export class MessageBridge {
1586
1636
  // Menu IDs are the protocol's stable correlation key. Bind it, together
1587
1637
  // with the active EvolCore session, before authorization so every
1588
1638
  // CommandAudit record and denial can be joined to the same request.
1589
- let activeSession;
1590
- if (msg.threadId && typeof this.sessionManager.getThreadSession === 'function') {
1591
- try {
1592
- activeSession = await this.sessionManager.getThreadSession(channel, msg.channelId, msg.threadId);
1593
- }
1594
- catch {
1595
- activeSession = undefined;
1596
- }
1597
- }
1598
- if (!activeSession && typeof this.sessionManager.getActiveSession === 'function') {
1599
- try {
1600
- 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
+ }
1601
1648
  }
1602
- catch {
1603
- 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
+ }
1604
1656
  }
1605
- }
1657
+ return session;
1658
+ });
1606
1659
  const menuAuthSubject = {
1607
1660
  ...authSubject,
1608
1661
  requestId: parsed.id,
@@ -1656,9 +1709,9 @@ export class MessageBridge {
1656
1709
  const dedupKey = [msg.selfAID || channel, channelType, msg.chatType || 'private', scope, msg.peerId,
1657
1710
  msg.peerDeviceId || '', msg.peerSlotId || '', msg.threadId || '', parsed.id].join('\u001f');
1658
1711
  let afterResponse;
1659
- 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
1660
1713
  ? this.issueMenuTokenResponse(header, channel, msg)
1661
- : this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; }));
1714
+ : this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; })));
1662
1715
  if ('conflict' in deduped) {
1663
1716
  this.logMenuDiagnostic('request-conflict', channel, msg, parsed, 'CONFLICT');
1664
1717
  await this.sendMenuResponse(adapter, channel, msg, menuFailure(header, {
@@ -1936,7 +1989,7 @@ export class MessageBridge {
1936
1989
  const deliveryTiming = beginMenuDeliveryTiming(msg);
1937
1990
  let deliveryOutcome;
1938
1991
  try {
1939
- await deliverMenuResponse(async () => {
1992
+ await traceMenuStage(request, flowContext, msg, 'menu.delivery', () => deliverMenuResponse(async () => {
1940
1993
  Object.assign(timedResponse, withMenuProcessingTime(timedResponse, msg));
1941
1994
  await adapter.send(envelope, { kind: 'custom', channelType: channel, payload: timedResponse });
1942
1995
  }, {
@@ -1964,7 +2017,7 @@ export class MessageBridge {
1964
2017
  },
1965
2018
  onRetry: (attempt, error, delay) => logMenuResponseRetry(request, flowContext, attempt, delay, error),
1966
2019
  onComplete: outcome => { deliveryOutcome = outcome; },
1967
- });
2020
+ }));
1968
2021
  logMenuRequestCompleted(request, timedResponse, flowContext, { delivery: 'sent', ...deliveryOutcome, ...deliveryTiming() });
1969
2022
  const upgradeData = 'data' in response ? response.data : undefined;
1970
2023
  if (request.type === 'menu.action' && request.action === 'upgrade' && (request.name === 'system' || request.cmd === '/system') && upgradeData?.jobId) {