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.
- package/CHANGELOG.md +34 -0
- package/dist/agent-template/runtime.js +5 -2
- package/dist/agents/codex-runner.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +643 -273
- package/dist/cli/directory.js +6 -1
- package/dist/cli/index.js +7 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +11 -1
- package/dist/config/providers-config.js +8 -4
- package/dist/config/providers-management.js +11 -3
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-catalog.js +9 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-handler.js +6 -1
- package/dist/core/command/menu-protocol.js +24 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/daemon-control.js +57 -1
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +6 -2
- package/dist/core/ipc-registration.js +1 -0
- package/dist/core/message/aun-ipc-sender.js +118 -56
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +92 -39
- package/dist/core/message/message-log.js +24 -0
- package/dist/core/message/message-queue.js +97 -15
- package/dist/core/message/response-engine.js +151 -18
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/runtime/supervisor.js +36 -8
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +4 -0
- package/dist/ipc.js +25 -1
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/services/index.js +29 -5
- package/dist/services/ipc-operation.js +84 -0
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/service-payload.js +13 -7
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/script-sandbox.js +12 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/npm-ops.js +43 -8
- package/dist/workbench/service.js +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -0
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +4 -1
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/provider.md +1 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-provider/SKILL.md +57 -8
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/commands.md +1 -0
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/thread.md +1 -0
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +2 -2
- package/scripts/agent-template/inspect.mjs +46 -10
- package/scripts/agent-template/shared/common.mjs +9 -3
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +60 -10
- package/scripts/agent-template/shared/template-package.mjs +182 -21
- package/scripts/agent-template/shared/template-runtime.mjs +35 -2
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +46 -11
package/dist/channels/aun.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { contactInboundKey, createContactInboundDelivery, trustedContactInboundDelivery, readPendingContactInbound, listPendingContactInbound, savePendingContactInbound, updatePendingContactInbound, finishPendingContactInbound, } from '../core/message/contact-pending-inbound.js';
|
|
2
|
+
import { buildContactApprovalCard, findContactThreadDelegation, isContactApprovalCard, ensureContactApprovalThreadContext, readContactApprovalCard, registerContactApprovalCard, } from '../core/message/contact-thread-approval.js';
|
|
1
3
|
import { E2EEError, validateAIDFormat } from '@agentunion/fastaun';
|
|
2
|
-
import { sanitizeMenuLogValue } from '../core/command/menu-protocol.js';
|
|
3
|
-
import { buildContactRequest, contactIntroductionText, consumeContactIntroductionBudget, currentContactBinding, verifiedContactBinding, evaluateAppContactAdmission, executeContactGrant, isContactControlPayload, reconcileTemporaryContactGrants, sameContactBinding, isolatedContactSource, saveIsolatedContactSource, contactSourceDigest, CONTACT_EVENT_TTL_MS, FRIEND_INVITE_TYPE, FRIEND_INVITE_RESULT_TYPE, isFriendInvitePayload, parseFriendInvite, recordedFriendInviteDecision, decideFriendInvite, markFriendInviteWelcomed, buildFriendInviteResult, friendPayloadRouteValid, friendInviteWelcomeText } from '../core/message/contact-admission.js';
|
|
4
|
+
import { sanitizeMenuLogValue, traceMenuStage } from '../core/command/menu-protocol.js';
|
|
5
|
+
import { buildContactRequest, contactIntroductionText, consumeContactIntroductionBudget, currentContactBinding, verifiedContactBinding, evaluateAppContactAdmission, executeContactGrant, isContactControlPayload, reconcileTemporaryContactGrants, sameContactBinding, isolatedContactSource, saveIsolatedContactSource, contactSourceDigest, CONTACT_EVENT_TTL_MS, FRIEND_INVITE_TYPE, FRIEND_INVITE_RESULT_TYPE, FRIEND_INVITE_PROOF_TYPE, isFriendInvitePayload, isFriendInviteProofPayload, parseFriendInvite, parseFriendInviteProof, recordedFriendInviteDecision, serializeFriendInvite, friendInviteDigest, decideFriendInvite, markFriendInviteWelcomed, buildFriendInviteResult, friendPayloadRouteValid, friendInviteWelcomeText } from '../core/message/contact-admission.js';
|
|
4
6
|
import crypto from 'crypto';
|
|
5
7
|
import { performance } from 'node:perf_hooks';
|
|
6
8
|
import fs from 'fs';
|
|
@@ -32,7 +34,7 @@ import { readTopicStatus } from '../core/session/session-mapper.js';
|
|
|
32
34
|
import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
|
|
33
35
|
import { appendAidLifecycle } from '../aun/aid/identity.js';
|
|
34
36
|
import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
|
|
35
|
-
import { classifyServicePayloadType, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
37
|
+
import { classifyServicePayloadType, isProjectionServiceResult, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
36
38
|
import { agentServicesDir } from '../paths.js';
|
|
37
39
|
import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
|
|
38
40
|
import { loadAgent } from '../config-store.js';
|
|
@@ -60,7 +62,7 @@ import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOu
|
|
|
60
62
|
import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
|
|
61
63
|
import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
|
|
62
64
|
import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
|
|
63
|
-
import { isTopicThreadId, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
65
|
+
import { isTopicThreadId, normalizeThreadIdForPeer, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
64
66
|
import { ThreadService } from '../core/thread/thread-service.js';
|
|
65
67
|
import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js';
|
|
66
68
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
@@ -77,28 +79,69 @@ const OBSERVER_GROUP_MEMBERS_TTL_MS = 60_000;
|
|
|
77
79
|
const GROUP_MEMBER_ROLES_TTL_MS = 120 * 60_000;
|
|
78
80
|
/** 群成员角色拉取失败后的退避时间,避免持续失败时每条消息都重试 RPC。 */
|
|
79
81
|
const GROUP_MEMBER_ROLES_FAILURE_TTL_MS = 60_000;
|
|
80
|
-
/**
|
|
81
|
-
|
|
82
|
+
/**
|
|
83
|
+
* `sender_ctx` 是**发件人客户端**填的自由文本,会被原样拼进系统提示里的 `ctx:` 行。
|
|
84
|
+
* 因此在入口处做两件事:折叠所有控制字符与换行(否则可伪造出新的信封行),并按字符数截断。
|
|
85
|
+
* 截断按码位计,不切断代理对。
|
|
86
|
+
*/
|
|
87
|
+
const SENDER_CTX_SCENE_MAX = 40;
|
|
88
|
+
const SENDER_CTX_ACTIVITY_MAX = 80;
|
|
89
|
+
const SENDER_CTX_ADDRESS_MAX = 120;
|
|
90
|
+
function clipSenderCtxText(value, max) {
|
|
91
|
+
if (typeof value !== 'string')
|
|
92
|
+
return undefined;
|
|
93
|
+
const flat = value
|
|
94
|
+
.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ')
|
|
95
|
+
.replace(/\s+/g, ' ')
|
|
96
|
+
.trim();
|
|
97
|
+
if (!flat)
|
|
98
|
+
return undefined;
|
|
99
|
+
const chars = Array.from(flat);
|
|
100
|
+
return chars.length > max ? `${chars.slice(0, max).join('')}…` : flat;
|
|
101
|
+
}
|
|
102
|
+
/** 时区必须能被 Intl 接受;非法值会在渲染阶段抛 RangeError,故在入口丢弃而不是靠下游兜底。 */
|
|
103
|
+
function readSenderTimezone(rawTz) {
|
|
104
|
+
if (typeof rawTz !== 'string')
|
|
105
|
+
return undefined;
|
|
106
|
+
const tz = rawTz.trim();
|
|
107
|
+
if (!tz)
|
|
108
|
+
return undefined;
|
|
109
|
+
try {
|
|
110
|
+
new Intl.DateTimeFormat('en-US', { timeZone: tz }).format(0);
|
|
111
|
+
return tz;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
logger.debug(`[AUN] sender_ctx.timezone ignored (invalid IANA name): ${logPreview(tz)}`);
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** 解析 AUN payload 的 `sender_ctx`;结构非法或全空返回 undefined。导出以便单测覆盖入口清洗。 */
|
|
119
|
+
export function readSenderCtx(payload) {
|
|
82
120
|
const raw = (payload && typeof payload === 'object')
|
|
83
121
|
? (payload.sender_ctx ?? payload.senderCtx)
|
|
84
122
|
: undefined;
|
|
85
123
|
if (!raw || typeof raw !== 'object')
|
|
86
124
|
return undefined;
|
|
87
|
-
const scene =
|
|
88
|
-
const activity =
|
|
125
|
+
const scene = clipSenderCtxText(raw.scene, SENDER_CTX_SCENE_MAX);
|
|
126
|
+
const activity = clipSenderCtxText(raw.activity, SENDER_CTX_ACTIVITY_MAX);
|
|
89
127
|
// 协议字段名尚未在真实 payload 上核对;同时接受 timezone / tz 两种写法。
|
|
90
|
-
const
|
|
91
|
-
const timezone = rawTz.trim() || undefined;
|
|
128
|
+
const timezone = readSenderTimezone(raw.timezone ?? raw.tz);
|
|
92
129
|
let location;
|
|
93
130
|
const loc = raw.location;
|
|
94
131
|
if (loc && typeof loc === 'object') {
|
|
95
132
|
const lat = Number(loc.latitude_e6);
|
|
96
133
|
const lon = Number(loc.longitude_e6);
|
|
97
134
|
if (Number.isFinite(lat) && Number.isFinite(lon)) {
|
|
135
|
+
// 精度与采集时刻缺省时保持缺省(不补 0、不回落成消息时间):缺省含义是「未上报」。
|
|
136
|
+
const accuracy = Number(loc.accuracy_m);
|
|
137
|
+
const capturedAt = Number(loc.timestamp_ms);
|
|
138
|
+
const address = clipSenderCtxText(loc.address, SENDER_CTX_ADDRESS_MAX);
|
|
98
139
|
location = {
|
|
99
140
|
latitude_e6: lat,
|
|
100
141
|
longitude_e6: lon,
|
|
101
|
-
...(
|
|
142
|
+
...(address ? { address } : {}),
|
|
143
|
+
...(Number.isFinite(accuracy) && accuracy > 0 ? { accuracy_m: accuracy } : {}),
|
|
144
|
+
...(Number.isFinite(capturedAt) && capturedAt > 0 ? { timestamp_ms: capturedAt } : {}),
|
|
102
145
|
};
|
|
103
146
|
}
|
|
104
147
|
}
|
|
@@ -805,6 +848,7 @@ export function aunOptsToInbound(opts, channel, channelType) {
|
|
|
805
848
|
return {
|
|
806
849
|
channel,
|
|
807
850
|
channelType,
|
|
851
|
+
contactDelivery: trustedContactInboundDelivery(opts.contactDelivery),
|
|
808
852
|
channelId: opts.channelId,
|
|
809
853
|
selfAID: opts.selfAID,
|
|
810
854
|
groupId: opts.groupId,
|
|
@@ -1044,45 +1088,37 @@ export class AUNChannel {
|
|
|
1044
1088
|
callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
|
|
1045
1089
|
params = menuTransportParams(method, params);
|
|
1046
1090
|
const client = this.client;
|
|
1047
|
-
const
|
|
1048
|
-
|
|
1049
|
-
const binding =
|
|
1091
|
+
const friendPayload = (typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.'))
|
|
1092
|
+
|| isContactApprovalCard(params.payload);
|
|
1093
|
+
const binding = friendPayload ? currentContactBinding(this.config.aid) : undefined;
|
|
1050
1094
|
onPrepared?.(params);
|
|
1051
1095
|
return this.withOutboundSendGate(method, async () => {
|
|
1052
1096
|
if (client !== this.client || !client)
|
|
1053
1097
|
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1054
|
-
if (!this.config.pureIdentity &&
|
|
1098
|
+
if (!this.config.pureIdentity && friendPayload
|
|
1055
1099
|
&& (method === 'message.send' || method === 'message.thought.put')) {
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
}
|
|
1066
|
-
if (client !== this.client)
|
|
1067
|
-
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1100
|
+
const routePayload = isContactApprovalCard(params.payload) ? params.payload.friend_request ?? {} : params.payload;
|
|
1101
|
+
const refreshed = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'contact.transport' });
|
|
1102
|
+
const verified = verifiedContactBinding(this.config.aid, refreshed);
|
|
1103
|
+
if (!verified) {
|
|
1104
|
+
throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
|
|
1105
|
+
}
|
|
1106
|
+
if (!friendPayloadRouteValid(routePayload, params.to, params.encrypt, verified)
|
|
1107
|
+
|| !sameContactBinding(verified, currentContactBinding(this.config.aid))) {
|
|
1108
|
+
throw Object.assign(new Error('contact Owner relation changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1068
1109
|
}
|
|
1110
|
+
if (client !== this.client)
|
|
1111
|
+
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1069
1112
|
const current = currentContactBinding(this.config.aid);
|
|
1070
1113
|
if (!current)
|
|
1071
1114
|
throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
|
|
1072
1115
|
if (!binding || !sameContactBinding(binding, current))
|
|
1073
1116
|
throw Object.assign(new Error('Owner relation changed while queued'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1074
|
-
|
|
1075
|
-
if (typeof payload?.type === 'string' && payload.type.startsWith('friend.')
|
|
1076
|
-
&& !friendPayloadRouteValid(payload, params.to, params.encrypt, current)) {
|
|
1117
|
+
if (!friendPayloadRouteValid(routePayload, params.to, params.encrypt, current)) {
|
|
1077
1118
|
throw Object.assign(new Error('contact event relation or encryption changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1078
1119
|
}
|
|
1079
|
-
if (
|
|
1080
|
-
|
|
1081
|
-
if (blocked) {
|
|
1082
|
-
throw Object.assign(new Error(blocked.error), {
|
|
1083
|
-
code: blocked.code, retryable: blocked.status === 'retry',
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1120
|
+
if (isContactApprovalCard(params.payload) && routePayload.received_at_ms + CONTACT_EVENT_TTL_MS <= Date.now()) {
|
|
1121
|
+
throw Object.assign(new Error('contact approval card has expired'), { code: 'CONTACT_APPROVAL_EXPIRED' });
|
|
1086
1122
|
}
|
|
1087
1123
|
}
|
|
1088
1124
|
beforeSend?.();
|
|
@@ -1483,8 +1519,8 @@ export class AUNChannel {
|
|
|
1483
1519
|
.finally(() => this.forgetInteractionCard(cardMsgId, cardInfo.requestId));
|
|
1484
1520
|
}
|
|
1485
1521
|
else {
|
|
1486
|
-
// Gateway-driven
|
|
1487
|
-
//
|
|
1522
|
+
// Gateway-driven invalidation has already disabled the card
|
|
1523
|
+
// before the callback returned. Keep the original message.
|
|
1488
1524
|
this.forgetInteractionCard(cardMsgId, cardInfo.requestId);
|
|
1489
1525
|
}
|
|
1490
1526
|
this.notifyCardActionFailure(channelId, '⚠️ 卡片已失效,请重新发起', cardClickerAid, threadId, cardDelivery);
|
|
@@ -1836,7 +1872,192 @@ export class AUNChannel {
|
|
|
1836
1872
|
void this.finishEcdiag(mid, 'shutdown').catch(() => { });
|
|
1837
1873
|
}
|
|
1838
1874
|
}
|
|
1875
|
+
contactReplayTimer;
|
|
1876
|
+
contactReplayRunning = false;
|
|
1877
|
+
contactReplayFlight;
|
|
1878
|
+
contactReplayDirty = false;
|
|
1879
|
+
contactReplayReconcileAt = 0;
|
|
1880
|
+
contactReplayReceiptResolver;
|
|
1881
|
+
contactReplayFinishHandler;
|
|
1882
|
+
setContactReplayReceiptResolver(resolver, finish) {
|
|
1883
|
+
this.contactReplayReceiptResolver = resolver;
|
|
1884
|
+
this.contactReplayFinishHandler = finish;
|
|
1885
|
+
}
|
|
1886
|
+
scheduleContactReplay() {
|
|
1887
|
+
if (this.config.pureIdentity || this.intentionalDisconnect || !this.connected || !this.messageHandler)
|
|
1888
|
+
return;
|
|
1889
|
+
this.contactReplayDirty = true;
|
|
1890
|
+
if (this.contactReplayRunning)
|
|
1891
|
+
return;
|
|
1892
|
+
if (this.contactReplayTimer)
|
|
1893
|
+
clearTimeout(this.contactReplayTimer);
|
|
1894
|
+
this.contactReplayTimer = setTimeout(() => {
|
|
1895
|
+
this.contactReplayTimer = undefined;
|
|
1896
|
+
void this.runContactReplay();
|
|
1897
|
+
}, 0);
|
|
1898
|
+
this.contactReplayTimer.unref?.();
|
|
1899
|
+
}
|
|
1900
|
+
validateContactReplay(record) {
|
|
1901
|
+
isolatedContactSource(this.config.aid, record.fromAid, record.messageId);
|
|
1902
|
+
const current = readPendingContactInbound(this.config.aid, record.key);
|
|
1903
|
+
if (!current?.message || !['waiting', 'transferring'].includes(current.state))
|
|
1904
|
+
throw new Error('contact replay is no longer pending');
|
|
1905
|
+
if (!this.connected || !sameContactBinding(record.binding, currentContactBinding(this.config.aid))
|
|
1906
|
+
|| record.expiresAt <= Date.now())
|
|
1907
|
+
throw new Error('contact replay binding or lifetime changed');
|
|
1908
|
+
const decision = evaluateAppContactAdmission(this.config.aid, record.fromAid);
|
|
1909
|
+
if (!decision.allow || !['contact', 'temporary', 'owner'].includes(decision.reason)) {
|
|
1910
|
+
throw new Error('contact replay is not admitted');
|
|
1911
|
+
}
|
|
1912
|
+
if (this.ownerDirectoryCache?.cache.readPendingUpdate())
|
|
1913
|
+
throw new Error('contact directory update is pending');
|
|
1914
|
+
}
|
|
1915
|
+
async runContactReplay() {
|
|
1916
|
+
if (this.contactReplayFlight)
|
|
1917
|
+
return this.contactReplayFlight;
|
|
1918
|
+
const flight = this.drainContactReplay();
|
|
1919
|
+
this.contactReplayFlight = flight;
|
|
1920
|
+
try {
|
|
1921
|
+
await flight;
|
|
1922
|
+
}
|
|
1923
|
+
finally {
|
|
1924
|
+
if (this.contactReplayFlight === flight)
|
|
1925
|
+
this.contactReplayFlight = undefined;
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
async drainContactReplay() {
|
|
1929
|
+
if (this.contactReplayRunning || !this.connected || !this.messageHandler)
|
|
1930
|
+
return;
|
|
1931
|
+
this.contactReplayRunning = true;
|
|
1932
|
+
try {
|
|
1933
|
+
do {
|
|
1934
|
+
this.contactReplayDirty = false;
|
|
1935
|
+
if (!listPendingContactInbound(this.config.aid).length)
|
|
1936
|
+
break;
|
|
1937
|
+
await ownerResolver.refresh(this.config.aid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.replay' });
|
|
1938
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1939
|
+
if (runtime && Date.now() >= this.contactReplayReconcileAt) {
|
|
1940
|
+
this.contactReplayReconcileAt = Date.now() + 60_000;
|
|
1941
|
+
await runtime.cache.reconcilePendingContacts();
|
|
1942
|
+
}
|
|
1943
|
+
await this.settleOwnerDirectoryBeforeTurn();
|
|
1944
|
+
// Application callbacks above are already reflected in this scan. Reading
|
|
1945
|
+
// again also includes messages saved while synchronization was in flight.
|
|
1946
|
+
this.contactReplayDirty = false;
|
|
1947
|
+
const records = listPendingContactInbound(this.config.aid);
|
|
1948
|
+
const blockedRoutes = new Set();
|
|
1949
|
+
for (let record of records) {
|
|
1950
|
+
if (!this.connected || !this.messageHandler)
|
|
1951
|
+
break;
|
|
1952
|
+
if (this.contactReplayReceiptResolver?.(record.key)) {
|
|
1953
|
+
finishPendingContactInbound(record, 'accepted');
|
|
1954
|
+
continue;
|
|
1955
|
+
}
|
|
1956
|
+
const binding = currentContactBinding(this.config.aid);
|
|
1957
|
+
if (record.expiresAt <= Date.now()) {
|
|
1958
|
+
finishPendingContactInbound(record, 'expired');
|
|
1959
|
+
continue;
|
|
1960
|
+
}
|
|
1961
|
+
if (binding && !sameContactBinding(record.binding, binding)) {
|
|
1962
|
+
finishPendingContactInbound(record, 'binding_changed');
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
if (!binding)
|
|
1966
|
+
continue;
|
|
1967
|
+
const decision = evaluateAppContactAdmission(this.config.aid, record.fromAid);
|
|
1968
|
+
if (decision.reason === 'blocked') {
|
|
1969
|
+
finishPendingContactInbound(record, 'blocked');
|
|
1970
|
+
continue;
|
|
1971
|
+
}
|
|
1972
|
+
if (!decision.allow && record.message) {
|
|
1973
|
+
const source = isolatedContactSource(this.config.aid, record.fromAid, record.messageId);
|
|
1974
|
+
if (source && !source.notified) {
|
|
1975
|
+
try {
|
|
1976
|
+
await this.notifyContactIntroduction(record.fromAid, record.message.payload, record.messageId, source, record.binding);
|
|
1977
|
+
}
|
|
1978
|
+
catch (error) {
|
|
1979
|
+
logger.warn(`${this.logPrefix()} Contact approval notification deferred: mid=${record.messageId} reason=${error instanceof Error ? error.message : String(error)}`);
|
|
1980
|
+
}
|
|
1981
|
+
record = readPendingContactInbound(this.config.aid, record.key);
|
|
1982
|
+
if (!record?.message || !['waiting', 'transferring'].includes(record.state))
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
const route = JSON.stringify([record.fromAid, record.message?.payload?.thread_id ?? '']);
|
|
1987
|
+
if (blockedRoutes.has(route))
|
|
1988
|
+
continue;
|
|
1989
|
+
if (!decision.allow || !['contact', 'temporary', 'owner'].includes(decision.reason)) {
|
|
1990
|
+
blockedRoutes.add(route);
|
|
1991
|
+
continue;
|
|
1992
|
+
}
|
|
1993
|
+
const delivery = createContactInboundDelivery({
|
|
1994
|
+
key: record.key, receivedAt: record.receivedAt, sessionId: record.sessionId,
|
|
1995
|
+
validate: () => this.validateContactReplay(record),
|
|
1996
|
+
bindSession: sessionId => {
|
|
1997
|
+
if (record.sessionId && record.sessionId !== sessionId)
|
|
1998
|
+
throw new Error('contact replay session changed');
|
|
1999
|
+
delivery.validate();
|
|
2000
|
+
ensureContactApprovalThreadContext(this.config.aid, record, sessionId);
|
|
2001
|
+
record.sessionId = sessionId;
|
|
2002
|
+
delivery.sessionId = sessionId;
|
|
2003
|
+
record.state = 'transferring';
|
|
2004
|
+
updatePendingContactInbound(record);
|
|
2005
|
+
},
|
|
2006
|
+
startCommand: () => {
|
|
2007
|
+
if (record.commandStartedAt)
|
|
2008
|
+
throw new Error('contact command outcome requires reconciliation');
|
|
2009
|
+
delivery.validate();
|
|
2010
|
+
record.commandStartedAt = Date.now();
|
|
2011
|
+
updatePendingContactInbound(record);
|
|
2012
|
+
},
|
|
2013
|
+
cancelCommand: () => {
|
|
2014
|
+
delete record.commandStartedAt;
|
|
2015
|
+
updatePendingContactInbound(record);
|
|
2016
|
+
},
|
|
2017
|
+
});
|
|
2018
|
+
try {
|
|
2019
|
+
await this.handleIncomingPrivateMessage(record.message, delivery);
|
|
2020
|
+
if (delivery.receipt) {
|
|
2021
|
+
// Observer telemetry is best effort, emitted only after durable acceptance.
|
|
2022
|
+
void this.forwardInbound(record.message);
|
|
2023
|
+
finishPendingContactInbound(record, 'accepted');
|
|
2024
|
+
logger.info(`${this.logPrefix()} Contact replay accepted: mid=${record.messageId} outcome=${delivery.receipt.outcome}`);
|
|
2025
|
+
}
|
|
2026
|
+
else
|
|
2027
|
+
blockedRoutes.add(route);
|
|
2028
|
+
}
|
|
2029
|
+
catch (error) {
|
|
2030
|
+
blockedRoutes.add(route);
|
|
2031
|
+
logger.warn(`${this.logPrefix()} Contact replay deferred: mid=${record.messageId} reason=${error instanceof Error ? error.message : String(error)}`);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
} while (this.contactReplayDirty && this.connected);
|
|
2035
|
+
}
|
|
2036
|
+
catch (error) {
|
|
2037
|
+
logger.warn(`${this.logPrefix()} Contact replay pending: ${error instanceof Error ? error.message : String(error)}`);
|
|
2038
|
+
}
|
|
2039
|
+
finally {
|
|
2040
|
+
this.contactReplayRunning = false;
|
|
2041
|
+
if (this.connected && !this.intentionalDisconnect && !this.contactReplayTimer) {
|
|
2042
|
+
let pending = true;
|
|
2043
|
+
try {
|
|
2044
|
+
pending = listPendingContactInbound(this.config.aid).length > 0;
|
|
2045
|
+
}
|
|
2046
|
+
catch { /* retry store recovery */ }
|
|
2047
|
+
if (pending) {
|
|
2048
|
+
this.contactReplayTimer = setTimeout(() => {
|
|
2049
|
+
this.contactReplayTimer = undefined;
|
|
2050
|
+
this.scheduleContactReplay();
|
|
2051
|
+
}, 15_000);
|
|
2052
|
+
this.contactReplayTimer.unref?.();
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
1839
2057
|
stopOwnerDirectoryRefresh() {
|
|
2058
|
+
if (this.contactReplayTimer)
|
|
2059
|
+
clearTimeout(this.contactReplayTimer);
|
|
2060
|
+
this.contactReplayTimer = undefined;
|
|
1840
2061
|
this.ownerDirectoryWatch?.stop();
|
|
1841
2062
|
this.ownerDirectoryWatch = undefined;
|
|
1842
2063
|
if (this.ownerDirectoryRetryTimer)
|
|
@@ -1866,6 +2087,7 @@ export class AUNChannel {
|
|
|
1866
2087
|
}),
|
|
1867
2088
|
};
|
|
1868
2089
|
this.queueOwnerDirectoryRefresh();
|
|
2090
|
+
this.scheduleContactReplay();
|
|
1869
2091
|
}
|
|
1870
2092
|
ownerDirectoryViewSignature(view) {
|
|
1871
2093
|
return JSON.stringify([
|
|
@@ -1982,6 +2204,8 @@ export class AUNChannel {
|
|
|
1982
2204
|
// the new cache implementation own storage and event synchronization.
|
|
1983
2205
|
const directory = path.join(this.agentDir, 'directory');
|
|
1984
2206
|
const cache = new OwnerDirectoryCache({
|
|
2207
|
+
onSnapshotApplied: () => { if (isCurrent())
|
|
2208
|
+
this.scheduleContactReplay(); },
|
|
1985
2209
|
onSnapshotApplying: snapshot => { if (isCurrent())
|
|
1986
2210
|
reconcileTemporaryContactGrants(selfAid, snapshot); },
|
|
1987
2211
|
relationVersion,
|
|
@@ -2382,9 +2606,9 @@ export class AUNChannel {
|
|
|
2382
2606
|
/** 本 agent 曾发出过的卡片 msgId(只增不删,用于区分"过期失效"vs"他人发的卡") */
|
|
2383
2607
|
ownedCardMsgIds = new Set();
|
|
2384
2608
|
ownedCardTopics = new Map();
|
|
2385
|
-
/** requestId → 已投递的卡片 message_id
|
|
2609
|
+
/** requestId → 已投递的卡片 message_id 集合(失效时清理交互映射,保留原消息) */
|
|
2386
2610
|
interactionCardMessageIds = new Map();
|
|
2387
|
-
/**
|
|
2611
|
+
/** 失效可能先于 outbox 卡片投递完成;迟到卡片不得重新启用交互。 */
|
|
2388
2612
|
invalidatedInteractions = new Map();
|
|
2389
2613
|
mentionModeResolver;
|
|
2390
2614
|
/** Agent-level policy controlling whether group slash commands require structured mentions. */
|
|
@@ -2511,13 +2735,11 @@ export class AUNChannel {
|
|
|
2511
2735
|
getGroupInviteDeliveryState(outboxId) {
|
|
2512
2736
|
return outbox.deliveryState(this.config.aid, outboxId);
|
|
2513
2737
|
}
|
|
2514
|
-
async invalidateGroupInviteCard(interactionId,
|
|
2515
|
-
const known = new Set(this.interactionCardMessageIds.get(interactionId) ?? []);
|
|
2738
|
+
async invalidateGroupInviteCard(interactionId, _ownerAid, messageIds) {
|
|
2516
2739
|
await this.invalidateInteraction(interactionId, 'group_invite_review');
|
|
2517
2740
|
// After a daemon restart only the review store knows the delivered cards.
|
|
2518
2741
|
for (const id of messageIds) {
|
|
2519
|
-
|
|
2520
|
-
await this.recallInteractionCard(id, ownerAid, { chatType: 'private' });
|
|
2742
|
+
this.forgetInteractionCard(id, interactionId);
|
|
2521
2743
|
}
|
|
2522
2744
|
}
|
|
2523
2745
|
refreshGroupInviteMembership(groupId) {
|
|
@@ -2696,6 +2918,31 @@ export class AUNChannel {
|
|
|
2696
2918
|
// instance must not mutate the new instance's health or message state.
|
|
2697
2919
|
const isCurrentClient = () => this.client === client
|
|
2698
2920
|
&& generation === this.reconnectGeneration && !this.intentionalDisconnect;
|
|
2921
|
+
const completeControlAgentMd = () => {
|
|
2922
|
+
if (!this.config.pureIdentity || !this.connected || !isCurrentClient())
|
|
2923
|
+
return;
|
|
2924
|
+
void ensureControlAgentMd(aidName, {
|
|
2925
|
+
store,
|
|
2926
|
+
aunPath,
|
|
2927
|
+
cacheRoot: resolveRoot(),
|
|
2928
|
+
ownerAid: this.config.controlOwnerAid,
|
|
2929
|
+
}).then(result => {
|
|
2930
|
+
if (!isCurrentClient())
|
|
2931
|
+
return;
|
|
2932
|
+
this._selfName = result.name;
|
|
2933
|
+
this.aidStatsCollector?.setSelfName(this.config.aid, result.name);
|
|
2934
|
+
if (result.published)
|
|
2935
|
+
logger.info(`${this.logPrefix()} 控制 AID agent.md 已发布: ${result.name}`);
|
|
2936
|
+
}).catch(error => {
|
|
2937
|
+
if (!isCurrentClient())
|
|
2938
|
+
return;
|
|
2939
|
+
if (error?.code === 'CONTROL_OWNER_REQUIRED') {
|
|
2940
|
+
logger.info(`${this.logPrefix()} 控制 AID agent.md 暂缓补全:等待归属名片就绪(名片更新或重连后重试)`);
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
logger.warn(`${this.logPrefix()} 控制 AID agent.md 补全失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
2944
|
+
});
|
|
2945
|
+
};
|
|
2699
2946
|
// Register event handlers before connecting
|
|
2700
2947
|
client.on('agentmd.changed', (data) => {
|
|
2701
2948
|
if (!isCurrentClient() || this.intentionalDisconnect || typeof data !== 'string')
|
|
@@ -2724,11 +2971,14 @@ export class AUNChannel {
|
|
|
2724
2971
|
this.serviceRouter.ensureStarted(identity);
|
|
2725
2972
|
this.serviceRouter.reload();
|
|
2726
2973
|
}
|
|
2727
|
-
void refreshAgentDisplayName(aid).then(name => {
|
|
2728
|
-
if (!
|
|
2974
|
+
void refreshAgentDisplayName(aid, { store, aunPath }).then(name => {
|
|
2975
|
+
if (!isCurrentClient())
|
|
2729
2976
|
return;
|
|
2730
|
-
|
|
2731
|
-
|
|
2977
|
+
if (name) {
|
|
2978
|
+
this._selfName = name;
|
|
2979
|
+
this.aidStatsCollector?.setSelfName(this.config.aid, name);
|
|
2980
|
+
}
|
|
2981
|
+
completeControlAgentMd();
|
|
2732
2982
|
});
|
|
2733
2983
|
}
|
|
2734
2984
|
});
|
|
@@ -2929,19 +3179,6 @@ export class AUNChannel {
|
|
|
2929
3179
|
// Service/Gateway 故障不能把控制通道判定为连接失败。
|
|
2930
3180
|
if (this.config.pureIdentity) {
|
|
2931
3181
|
this._selfName = buildControlAgentName(aidName);
|
|
2932
|
-
void ensureControlAgentMd(aidName, {
|
|
2933
|
-
store: this.store ?? undefined,
|
|
2934
|
-
aunPath,
|
|
2935
|
-
cacheRoot: resolveRoot(),
|
|
2936
|
-
})
|
|
2937
|
-
.then(result => {
|
|
2938
|
-
this._selfName = result.name;
|
|
2939
|
-
if (this.aidStatsCollector)
|
|
2940
|
-
this.aidStatsCollector.setSelfName(this.config.aid, result.name);
|
|
2941
|
-
if (result.published)
|
|
2942
|
-
logger.info(`${this.logPrefix()} 控制 AID agent.md 已发布: ${result.name}`);
|
|
2943
|
-
})
|
|
2944
|
-
.catch(error => logger.warn(`${this.logPrefix()} 控制 AID agent.md 补全失败(后台重试): ${error instanceof Error ? error.message : String(error)}`));
|
|
2945
3182
|
}
|
|
2946
3183
|
else {
|
|
2947
3184
|
this._selfName = this.loadSelfName(aidName, aunPath);
|
|
@@ -2951,10 +3188,19 @@ export class AUNChannel {
|
|
|
2951
3188
|
this.connected = true;
|
|
2952
3189
|
this.connectedAt = Date.now();
|
|
2953
3190
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
3191
|
+
completeControlAgentMd();
|
|
2954
3192
|
this.reconcileConfiguredOwnerBinding();
|
|
2955
3193
|
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
2956
3194
|
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
2957
3195
|
if (!this.config.pureIdentity) {
|
|
3196
|
+
// Move local pack/index initialization off the first Owner projection
|
|
3197
|
+
// request. The cached router is reused across reconnects.
|
|
3198
|
+
try {
|
|
3199
|
+
this.ensureServiceRouter();
|
|
3200
|
+
}
|
|
3201
|
+
catch (error) {
|
|
3202
|
+
logger.warn(`${this.logPrefix()} Service warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3203
|
+
}
|
|
2958
3204
|
void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
|
|
2959
3205
|
logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2960
3206
|
});
|
|
@@ -3360,11 +3606,101 @@ export class AUNChannel {
|
|
|
3360
3606
|
}
|
|
3361
3607
|
}
|
|
3362
3608
|
ownerDirectoryRelationVersion;
|
|
3609
|
+
/** One notification for one isolated source: a contextual card replaces the generic request. */
|
|
3610
|
+
async notifyContactIntroduction(fromAid, payload, messageId, source, binding) {
|
|
3611
|
+
const selfAid = this.config.aid;
|
|
3612
|
+
const introduction = contactIntroductionText(payload);
|
|
3613
|
+
const reason = source.reason;
|
|
3614
|
+
if (source.notified || introduction === undefined || !['not_in_contacts', 'scope_extension'].includes(reason ?? '')
|
|
3615
|
+
|| !sameContactBinding(source.binding ?? {}, binding))
|
|
3616
|
+
return;
|
|
3617
|
+
if (!source.notificationReady) {
|
|
3618
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid))
|
|
3619
|
+
return;
|
|
3620
|
+
source = saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notificationReady: true });
|
|
3621
|
+
}
|
|
3622
|
+
const pending = readPendingContactInbound(selfAid, contactInboundKey(selfAid, fromAid, messageId));
|
|
3623
|
+
if (pending && (!pending.message || !['waiting', 'transferring'].includes(pending.state)))
|
|
3624
|
+
return;
|
|
3625
|
+
const match = pending?.approval ? { defer: false, origin: pending.approval }
|
|
3626
|
+
: findContactThreadDelegation(selfAid, binding, fromAid, payload, source.at);
|
|
3627
|
+
if (match.defer)
|
|
3628
|
+
return;
|
|
3629
|
+
const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, reason);
|
|
3630
|
+
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
3631
|
+
if (remainingTtl <= 0)
|
|
3632
|
+
return;
|
|
3633
|
+
if (pending && match.origin && !pending.approval) {
|
|
3634
|
+
pending.approval = { ...match.origin, eventId: request.event_id };
|
|
3635
|
+
updatePendingContactInbound(pending);
|
|
3636
|
+
}
|
|
3637
|
+
const approval = pending?.approval;
|
|
3638
|
+
const sent = await this.sendContentPayload(binding.owner_aid, approval ? buildContactApprovalCard(request, approval) : request, {
|
|
3639
|
+
contentKind: approval ? 'card' : 'custom', dedupeKey: request.event_id,
|
|
3640
|
+
logText: approval ? '[friend.request.v1 action_card]' : '[friend.request.v1]',
|
|
3641
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true },
|
|
3642
|
+
...(approval ? { sessionId: approval.originSessionId, localTopicId: approval.originThreadId,
|
|
3643
|
+
...(isTopicThreadId(approval.originThreadId) ? { threadId: approval.originThreadId } : {}) } : {}) },
|
|
3644
|
+
...(approval && pending ? { postSend: { type: 'register_contact_approval_card',
|
|
3645
|
+
pendingKey: pending.key, eventId: request.event_id } } : {}),
|
|
3646
|
+
ttl: remainingTtl,
|
|
3647
|
+
});
|
|
3648
|
+
if (sent.messageId || sent.queued)
|
|
3649
|
+
saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
|
|
3650
|
+
logger.info(`${this.logPrefix()} Contact introduction isolated: event=${request.event_id} card=${!!approval} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3651
|
+
}
|
|
3652
|
+
/** Consume only daemon-owned, durable card bindings. This never invokes the interaction/model runner. */
|
|
3653
|
+
async handleContactApprovalReply(fromAid, payload, encrypted) {
|
|
3654
|
+
const cardId = payload.card_message_id ?? payload.ref_message_id;
|
|
3655
|
+
if (typeof cardId !== 'string' || !cardId)
|
|
3656
|
+
return false;
|
|
3657
|
+
const selfAid = this.config.aid;
|
|
3658
|
+
const card = readContactApprovalCard(selfAid, cardId);
|
|
3659
|
+
if (!card)
|
|
3660
|
+
return false;
|
|
3661
|
+
if (!encrypted || card.expiresAt <= Date.now())
|
|
3662
|
+
return true;
|
|
3663
|
+
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.card.reply' });
|
|
3664
|
+
const binding = verifiedContactBinding(selfAid, view);
|
|
3665
|
+
const pending = readPendingContactInbound(selfAid, card.pendingKey);
|
|
3666
|
+
if (!binding || fromAid !== binding.owner_aid || !pending?.message || !pending.approval
|
|
3667
|
+
|| !sameContactBinding(pending.binding, binding) || pending.approval.eventId !== card.eventId
|
|
3668
|
+
|| pending.expiresAt <= Date.now() || !['waiting', 'transferring'].includes(pending.state)
|
|
3669
|
+
|| this.contactReplayReceiptResolver?.(pending.key))
|
|
3670
|
+
return true;
|
|
3671
|
+
if (payload.thread_id !== undefined
|
|
3672
|
+
&& normalizeThreadIdForPeer(payload.thread_id, selfAid, fromAid) !== pending.approval.originThreadId)
|
|
3673
|
+
return true;
|
|
3674
|
+
if (payload.behavior !== undefined && payload.behavior !== 'reply')
|
|
3675
|
+
return true;
|
|
3676
|
+
const action = payload.action_value ?? payload.value ?? payload.text;
|
|
3677
|
+
if (action !== 'approve' && action !== 'reject')
|
|
3678
|
+
return true;
|
|
3679
|
+
if (pending.approval.response)
|
|
3680
|
+
return true;
|
|
3681
|
+
pending.approval.response = action;
|
|
3682
|
+
if (action === 'reject')
|
|
3683
|
+
finishPendingContactInbound(pending, 'rejected');
|
|
3684
|
+
else {
|
|
3685
|
+
updatePendingContactInbound(pending);
|
|
3686
|
+
// The click is a refresh hint. Only the independently verified contact snapshot grants admission.
|
|
3687
|
+
this.contactReplayReconcileAt = 0;
|
|
3688
|
+
this.scheduleContactReplay();
|
|
3689
|
+
}
|
|
3690
|
+
logger.info(`${this.logPrefix()} Contact approval card receipt: event=${card.eventId} action=${action}`);
|
|
3691
|
+
return true;
|
|
3692
|
+
}
|
|
3363
3693
|
/** Returns before any ordinary history, observer, attachment or model side effect. */
|
|
3364
|
-
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted) {
|
|
3694
|
+
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted, message) {
|
|
3365
3695
|
const selfAid = this.config.aid;
|
|
3366
3696
|
const value = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : undefined;
|
|
3367
3697
|
const type = typeof value?.type === 'string' ? value.type : '';
|
|
3698
|
+
const pending = readPendingContactInbound(selfAid, contactInboundKey(selfAid, fromAid, messageId));
|
|
3699
|
+
if (pending) {
|
|
3700
|
+
this.scheduleContactReplay();
|
|
3701
|
+
if (!pending.message || pending.digest !== contactSourceDigest(payload))
|
|
3702
|
+
return true;
|
|
3703
|
+
}
|
|
3368
3704
|
const previous = isolatedContactSource(selfAid, fromAid, messageId);
|
|
3369
3705
|
const digest = contactSourceDigest(payload);
|
|
3370
3706
|
if (previous && (previous.notified || !previous.reason || contactIntroductionText(payload) === undefined
|
|
@@ -3372,14 +3708,14 @@ export class AUNChannel {
|
|
|
3372
3708
|
return true;
|
|
3373
3709
|
if (previous && !sameContactBinding(previous.binding, currentContactBinding(selfAid)))
|
|
3374
3710
|
return true;
|
|
3375
|
-
if (previous && !consumeContactIntroductionBudget(selfAid, fromAid))
|
|
3376
|
-
return true;
|
|
3377
3711
|
if (type.startsWith('friend.')) {
|
|
3378
3712
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.grant' });
|
|
3379
3713
|
const binding = verifiedContactBinding(selfAid, view);
|
|
3380
3714
|
if (!binding)
|
|
3381
3715
|
return true;
|
|
3382
3716
|
const result = executeContactGrant(selfAid, fromAid, payload, encrypted, Date.now(), binding);
|
|
3717
|
+
if (result?.status === 'applied')
|
|
3718
|
+
this.scheduleContactReplay();
|
|
3383
3719
|
if (result)
|
|
3384
3720
|
await this.sendContentPayload(fromAid, result, {
|
|
3385
3721
|
contentKind: 'custom', dedupeKey: `friend-result:${result.owner_aid}:${result.relation_version}:${result.type}:${result.grant_id}:${result.status}:${result.error_code ?? ''}`,
|
|
@@ -3395,14 +3731,25 @@ export class AUNChannel {
|
|
|
3395
3731
|
return true; // Retired App protocol; never create legacy pending.
|
|
3396
3732
|
if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
|
|
3397
3733
|
return false;
|
|
3398
|
-
//
|
|
3734
|
+
// A redelivered isolated source can only reenter through the durable replay worker.
|
|
3399
3735
|
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.inbound' });
|
|
3400
3736
|
await this.getOwnerDirectoryRuntime();
|
|
3401
3737
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3402
3738
|
const decision = evaluateAppContactAdmission(selfAid, fromAid);
|
|
3403
3739
|
logger.debug(`${this.logPrefix()} Contact admission: mid=${messageId} from=${fromAid} allow=${decision.allow} reason=${decision.reason} elapsedMs=${Math.max(0, Date.now() - receivedAt)}`);
|
|
3404
|
-
if (decision.allow && !previous)
|
|
3405
|
-
|
|
3740
|
+
if (decision.allow && !previous) {
|
|
3741
|
+
const backlog = message && contactIntroductionText(payload) !== undefined
|
|
3742
|
+
&& listPendingContactInbound(selfAid).some(record => record.fromAid === fromAid
|
|
3743
|
+
&& (record.message?.payload?.thread_id ?? '') === (value?.thread_id ?? ''));
|
|
3744
|
+
if (!backlog || !message)
|
|
3745
|
+
return false;
|
|
3746
|
+
const binding = currentContactBinding(selfAid);
|
|
3747
|
+
if (!binding)
|
|
3748
|
+
return true;
|
|
3749
|
+
savePendingContactInbound({ selfAid, fromAid, messageId, receivedAt, binding, message });
|
|
3750
|
+
this.scheduleContactReplay();
|
|
3751
|
+
return true;
|
|
3752
|
+
}
|
|
3406
3753
|
const introduction = contactIntroductionText(payload);
|
|
3407
3754
|
const binding = currentContactBinding(selfAid);
|
|
3408
3755
|
const reason = previous?.reason ?? decision.reason;
|
|
@@ -3410,32 +3757,46 @@ export class AUNChannel {
|
|
|
3410
3757
|
return true;
|
|
3411
3758
|
let source = previous ?? { at: receivedAt, digest, binding,
|
|
3412
3759
|
...(reason === 'not_in_contacts' || reason === 'scope_extension' ? { reason } : {}) };
|
|
3760
|
+
if (!previous && binding && message && introduction !== undefined
|
|
3761
|
+
&& (reason === 'not_in_contacts' || reason === 'scope_extension')) {
|
|
3762
|
+
savePendingContactInbound({ selfAid, fromAid, messageId, receivedAt, binding, message });
|
|
3763
|
+
this.scheduleContactReplay();
|
|
3764
|
+
}
|
|
3413
3765
|
// Write the tombstone before budgets, receipt capacity checks or any delivery.
|
|
3414
3766
|
if (!previous)
|
|
3415
3767
|
source = saveIsolatedContactSource(selfAid, fromAid, messageId, source);
|
|
3416
3768
|
if (source.notified || source.digest !== digest || !sameContactBinding(source.binding ?? {}, binding))
|
|
3417
3769
|
return true;
|
|
3418
3770
|
const eventReason = source.reason;
|
|
3419
|
-
if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')
|
|
3420
|
-
|
|
3421
|
-
const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, eventReason);
|
|
3422
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
3423
|
-
if (remainingTtl <= 0)
|
|
3424
|
-
return true;
|
|
3425
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3426
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1]',
|
|
3427
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
3428
|
-
ttl: remainingTtl,
|
|
3429
|
-
});
|
|
3430
|
-
if (sent.messageId || sent.queued)
|
|
3431
|
-
saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
|
|
3432
|
-
logger.info(`${this.logPrefix()} Contact introduction isolated: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3771
|
+
if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')) {
|
|
3772
|
+
await this.notifyContactIntroduction(fromAid, payload, messageId, source, binding);
|
|
3433
3773
|
}
|
|
3434
3774
|
else {
|
|
3435
3775
|
logger.info(`${this.logPrefix()} Contact message isolated: mid=${messageId} reason=${decision.reason}`);
|
|
3436
3776
|
}
|
|
3437
3777
|
return true;
|
|
3438
3778
|
}
|
|
3779
|
+
/** Forward an invite to the Owner using a fresh target-Agent binding. */
|
|
3780
|
+
async forwardFriendInviteRequest(binding, invite, sourceMessageId, receivedAt, reason, proof, rawInvite) {
|
|
3781
|
+
const eventKey = proof
|
|
3782
|
+
? `proof:${proof.proof_id}:${friendInviteDigest(proof.invite)}:${proof.qr_proof.version}:${proof.qr_proof.token}`
|
|
3783
|
+
: invite.qr_proof ? `invite:${invite.invite_id}:${friendInviteDigest(invite)}` : `invite:${invite.invite_id}`;
|
|
3784
|
+
const request = {
|
|
3785
|
+
...buildContactRequest(binding, invite.applicant_aid, sourceMessageId, receivedAt, invite.introduction, reason, eventKey),
|
|
3786
|
+
// Keep the complete wire invite received from the App. In particular a
|
|
3787
|
+
// proof retry must retain the old nested qr_proof unchanged while the
|
|
3788
|
+
// wrapper's top-level qr_proof carries the fresh credential.
|
|
3789
|
+
invite: rawInvite ?? serializeFriendInvite(invite),
|
|
3790
|
+
...(proof ? { proof_id: proof.proof_id, qr_proof: proof.qr_proof } : {}),
|
|
3791
|
+
};
|
|
3792
|
+
const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, Math.max(1, invite.expires_at_ms - Date.now()));
|
|
3793
|
+
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3794
|
+
contentKind: 'custom', dedupeKey: request.event_id,
|
|
3795
|
+
logText: proof ? '[friend.request.v1 invite.proof]' : '[friend.request.v1 invite]',
|
|
3796
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
|
|
3797
|
+
});
|
|
3798
|
+
logger.info(`${this.logPrefix()} Friend invite forwarded to Owner: event=${request.event_id} proof=${proof?.proof_id ?? 'none'} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3799
|
+
}
|
|
3439
3800
|
/** friend.invite.v1 never reaches the model, ordinary history, attachments or observers. */
|
|
3440
3801
|
async handleFriendInvite(fromAid, payload, messageId, receivedAt, encrypted, seq) {
|
|
3441
3802
|
const selfAid = this.config.aid;
|
|
@@ -3467,6 +3828,17 @@ export class AUNChannel {
|
|
|
3467
3828
|
await this.sendFriendInviteResult(invite, decideFriendInvite(selfAid, binding, invite, 'expired'), messageId);
|
|
3468
3829
|
return;
|
|
3469
3830
|
}
|
|
3831
|
+
// A QR-backed invite is an Owner decision request. Core only authenticates
|
|
3832
|
+
// the sender/target and carries the proof through; it never verifies the
|
|
3833
|
+
// token or accepts the invite locally.
|
|
3834
|
+
if (invite.qr_proof) {
|
|
3835
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
|
|
3836
|
+
logger.info(`${this.logPrefix()} QR friend invite dropped: code=INTRODUCTION_BUDGET invite=${invite.invite_id} from=${fromAid}`);
|
|
3837
|
+
return;
|
|
3838
|
+
}
|
|
3839
|
+
await this.forwardFriendInviteRequest(binding, invite, messageId, receivedAt, 'not_in_contacts', undefined, isFriendInvitePayload(payload) ? payload : undefined);
|
|
3840
|
+
return;
|
|
3841
|
+
}
|
|
3470
3842
|
await this.getOwnerDirectoryRuntime();
|
|
3471
3843
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3472
3844
|
const verdict = await this.judgeFriendInvite(selfAid, fromAid);
|
|
@@ -3487,21 +3859,50 @@ export class AUNChannel {
|
|
|
3487
3859
|
return;
|
|
3488
3860
|
}
|
|
3489
3861
|
const reason = verdict.reason === 'scope_extension' ? 'scope_extension' : 'not_in_contacts';
|
|
3490
|
-
|
|
3491
|
-
...buildContactRequest(binding, fromAid, messageId, receivedAt, invite.introduction, reason, `invite:${invite.invite_id}`),
|
|
3492
|
-
invite: { type: FRIEND_INVITE_TYPE, schema_version: 1, ...invite },
|
|
3493
|
-
};
|
|
3494
|
-
const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, invite.expires_at_ms - Date.now());
|
|
3495
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3496
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 invite]',
|
|
3497
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
|
|
3498
|
-
});
|
|
3499
|
-
logger.info(`${this.logPrefix()} Friend invite forwarded to Owner: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3862
|
+
await this.forwardFriendInviteRequest(binding, invite, messageId, receivedAt, reason, undefined, isFriendInvitePayload(payload) ? payload : undefined);
|
|
3500
3863
|
}
|
|
3501
3864
|
catch (error) {
|
|
3502
3865
|
logger.warn(`${this.logPrefix()} Friend invite isolated: code=CONTACT_STATE_UNAVAILABLE invite=${invite.invite_id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3503
3866
|
}
|
|
3504
3867
|
}
|
|
3868
|
+
/**
|
|
3869
|
+
* A queued invite can be retried with a durable QR proof package. It follows
|
|
3870
|
+
* the same authenticated Owner route as a live QR invite, but never enters
|
|
3871
|
+
* local admission/decision code or the model.
|
|
3872
|
+
*/
|
|
3873
|
+
async handleFriendInviteProof(fromAid, payload, messageId, receivedAt, encrypted, seq) {
|
|
3874
|
+
const selfAid = this.config.aid;
|
|
3875
|
+
this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, encrypted, false, classifyAunPayloadForLog(payload), undefined, receivedAt, seq);
|
|
3876
|
+
const proof = parseFriendInviteProof(payload, fromAid, selfAid);
|
|
3877
|
+
if (!proof || !encrypted) {
|
|
3878
|
+
logger.info(`${this.logPrefix()} Friend invite proof ignored: code=INVALID_FRIEND_INVITE_PROOF from=${fromAid} mid=${messageId} encrypted=${encrypted}`);
|
|
3879
|
+
return;
|
|
3880
|
+
}
|
|
3881
|
+
if (proof.invite.expires_at_ms <= Date.now()) {
|
|
3882
|
+
logger.info(`${this.logPrefix()} Friend invite proof ignored: code=FRIEND_INVITE_EXPIRED proof=${proof.proof_id} from=${fromAid}`);
|
|
3883
|
+
return;
|
|
3884
|
+
}
|
|
3885
|
+
try {
|
|
3886
|
+
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.invite.proof' });
|
|
3887
|
+
const binding = verifiedContactBinding(selfAid, view);
|
|
3888
|
+
if (!binding) {
|
|
3889
|
+
logger.info(`${this.logPrefix()} Friend invite proof deferred: code=CONTACT_OWNERSHIP_UNAVAILABLE proof=${proof.proof_id} from=${fromAid}`);
|
|
3890
|
+
return;
|
|
3891
|
+
}
|
|
3892
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
|
|
3893
|
+
logger.info(`${this.logPrefix()} Friend invite proof dropped: code=INTRODUCTION_BUDGET proof=${proof.proof_id} from=${fromAid}`);
|
|
3894
|
+
return;
|
|
3895
|
+
}
|
|
3896
|
+
const rawProofPayload = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
3897
|
+
? payload : undefined;
|
|
3898
|
+
const rawInvite = rawProofPayload?.invite && typeof rawProofPayload.invite === 'object' && !Array.isArray(rawProofPayload.invite)
|
|
3899
|
+
? rawProofPayload.invite : undefined;
|
|
3900
|
+
await this.forwardFriendInviteRequest(binding, proof.invite, messageId, receivedAt, 'not_in_contacts', proof, rawInvite);
|
|
3901
|
+
}
|
|
3902
|
+
catch (error) {
|
|
3903
|
+
logger.warn(`${this.logPrefix()} Friend invite proof isolated: code=CONTACT_STATE_UNAVAILABLE proof=${proof.proof_id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3904
|
+
}
|
|
3905
|
+
}
|
|
3505
3906
|
/**
|
|
3506
3907
|
* Friend invites use the same app-v1 decision as ordinary private messages.
|
|
3507
3908
|
*/
|
|
@@ -3531,11 +3932,13 @@ export class AUNChannel {
|
|
|
3531
3932
|
if (sent.messageId || sent.queued)
|
|
3532
3933
|
markFriendInviteWelcomed(this.config.aid, binding, invite.invite_id);
|
|
3533
3934
|
}
|
|
3534
|
-
async handleIncomingPrivateMessage(data) {
|
|
3935
|
+
async handleIncomingPrivateMessage(data, contactDelivery) {
|
|
3535
3936
|
if (!data || typeof data !== 'object')
|
|
3536
3937
|
return;
|
|
3537
3938
|
const msg = data;
|
|
3538
|
-
|
|
3939
|
+
if (contactDelivery)
|
|
3940
|
+
contactDelivery.validate();
|
|
3941
|
+
const receivedAt = contactDelivery?.receivedAt ?? Date.now();
|
|
3539
3942
|
const receivedAtMono = performance.now();
|
|
3540
3943
|
// Validate the authenticated envelope before any payload extraction or
|
|
3541
3944
|
// command parsing. Retransmits may carry a new seq, but the application
|
|
@@ -3605,9 +4008,25 @@ export class AUNChannel {
|
|
|
3605
4008
|
return;
|
|
3606
4009
|
const protectedHeaders = verifiedProtectedHeaders(msg, env);
|
|
3607
4010
|
const payload = msg.payload ?? '';
|
|
4011
|
+
const menuRequest = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
4012
|
+
&& ['menu.list', 'menu.query', 'menu.options', 'menu.update', 'menu.action', 'menu.token.request'].includes(payload.type)
|
|
4013
|
+
? payload : undefined;
|
|
4014
|
+
const menuContext = {
|
|
4015
|
+
source: appOwned ? 'agent-aun' : 'control-aun',
|
|
4016
|
+
selfAid: this.config.aid, requesterAid: fromAid, messageId,
|
|
4017
|
+
};
|
|
4018
|
+
const menuTiming = { receivedAt, receivedAtMono };
|
|
3608
4019
|
// Credential answers must be consumed before contact/request persistence,
|
|
3609
4020
|
// observer forwarding or generic message logging. Card binding is server-owned.
|
|
3610
4021
|
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
4022
|
+
try {
|
|
4023
|
+
if (await this.handleContactApprovalReply(fromAid, payload, !!env.encrypted))
|
|
4024
|
+
return;
|
|
4025
|
+
}
|
|
4026
|
+
catch {
|
|
4027
|
+
logger.warn(`${this.logPrefix()} Contact card receipt isolated: code=CONTACT_STATE_UNAVAILABLE`);
|
|
4028
|
+
return;
|
|
4029
|
+
}
|
|
3611
4030
|
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
3612
4031
|
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
3613
4032
|
if (!card || card.sensitive) {
|
|
@@ -3625,11 +4044,17 @@ export class AUNChannel {
|
|
|
3625
4044
|
await this.handleFriendInvite(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
|
|
3626
4045
|
return;
|
|
3627
4046
|
}
|
|
4047
|
+
if (!this.config.pureIdentity && isFriendInviteProofPayload(payload)) {
|
|
4048
|
+
if (appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
4049
|
+
return;
|
|
4050
|
+
await this.handleFriendInviteProof(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
|
|
4051
|
+
return;
|
|
4052
|
+
}
|
|
3628
4053
|
const contactControl = appOwned && isContactControlPayload(payload);
|
|
3629
4054
|
if (appOwned) {
|
|
3630
4055
|
let handled;
|
|
3631
4056
|
try {
|
|
3632
|
-
handled = await this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted);
|
|
4057
|
+
handled = await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.contact-admission', () => contactDelivery ? Promise.resolve(false) : this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted, msg));
|
|
3633
4058
|
}
|
|
3634
4059
|
catch {
|
|
3635
4060
|
// Storage/lock/capacity/conflict failures remain isolated; log metadata only.
|
|
@@ -3646,7 +4071,7 @@ export class AUNChannel {
|
|
|
3646
4071
|
}
|
|
3647
4072
|
if (handled)
|
|
3648
4073
|
return;
|
|
3649
|
-
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4074
|
+
if (!contactDelivery && !this.claimInboundMessage('private', messageId, seq))
|
|
3650
4075
|
return;
|
|
3651
4076
|
if (contactControl)
|
|
3652
4077
|
this.rememberContactControlRequest(fromAid, payload, messageId, menuSenderDeviceId(msg.sender_device_id));
|
|
@@ -3719,7 +4144,7 @@ export class AUNChannel {
|
|
|
3719
4144
|
// forwardInbound 内部排除 self-echo 与 from-owner。
|
|
3720
4145
|
// 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
|
|
3721
4146
|
// (即便日后 from-owner 排除规则调整,也不会泄漏)。
|
|
3722
|
-
if (!contactControl && inboundType !== 'action_card_reply'
|
|
4147
|
+
if (!contactDelivery && !contactControl && inboundType !== 'action_card_reply'
|
|
3723
4148
|
&& (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
|
|
3724
4149
|
void this.forwardInbound(msg);
|
|
3725
4150
|
}
|
|
@@ -3748,14 +4173,14 @@ export class AUNChannel {
|
|
|
3748
4173
|
mentions.push({ aid: this._aid });
|
|
3749
4174
|
}
|
|
3750
4175
|
// Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
|
|
3751
|
-
const { finalText, images: inboundImages } = contactControl ? { finalText: text, images: [] } : await this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' });
|
|
4176
|
+
const { finalText, images: inboundImages } = contactControl ? { finalText: text, images: [] } : await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.attachments', () => this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' }));
|
|
3752
4177
|
// 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
|
|
3753
4178
|
// device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
|
|
3754
4179
|
const chatId = fromAid;
|
|
3755
4180
|
// 解析对端身份(30天缓存)
|
|
3756
4181
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
3757
|
-
const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
3758
|
-
await prepareSameOwnerProof(this.config.aid, fromAid);
|
|
4182
|
+
const peerIdentity = await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.peer-identity', () => PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot()));
|
|
4183
|
+
await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.same-owner-proof', () => prepareSameOwnerProof(this.config.aid, fromAid));
|
|
3759
4184
|
const shortAid = this.getShortAid(fromAid);
|
|
3760
4185
|
const displayName = this.inboundDisplayName(fromAid, peerIdentity.name, shortAid);
|
|
3761
4186
|
// 详细 dispatch 决策日志:记录消息为何被路由到 agent
|
|
@@ -3863,11 +4288,17 @@ export class AUNChannel {
|
|
|
3863
4288
|
const isSystemP2P = p2pPayloadType === 'event';
|
|
3864
4289
|
this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
|
|
3865
4290
|
const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicStatus(payload));
|
|
3866
|
-
this.dispatchMessage({
|
|
4291
|
+
const dispatched = this.dispatchMessage({
|
|
4292
|
+
contactDelivery,
|
|
3867
4293
|
channelId: chatId,
|
|
3868
4294
|
userId: fromAid,
|
|
3869
|
-
text
|
|
4295
|
+
// Control text commands must use the original payload, never quote/attachment rendering.
|
|
4296
|
+
text: this.config.pureIdentity && p2pPayloadType === 'text'
|
|
4297
|
+
? (typeof payload.text === 'string' ? payload.text : '') : finalText,
|
|
3870
4298
|
chatType: 'private',
|
|
4299
|
+
...(this.config.pureIdentity && p2pPayloadType === 'text' ? {
|
|
4300
|
+
peerDeviceId: menuSenderDeviceId(msg.sender_device_id),
|
|
4301
|
+
} : {}),
|
|
3871
4302
|
messageId,
|
|
3872
4303
|
receivedAt,
|
|
3873
4304
|
createdAt: typeof msg.created_at === 'number' ? msg.created_at : undefined,
|
|
@@ -3891,6 +4322,8 @@ export class AUNChannel {
|
|
|
3891
4322
|
payloadSummary: logDescriptor.payloadSummary,
|
|
3892
4323
|
messageLogContent: logDescriptor.msgType === 'text' ? finalText : logDescriptor.content,
|
|
3893
4324
|
});
|
|
4325
|
+
if (contactDelivery)
|
|
4326
|
+
await dispatched;
|
|
3894
4327
|
}
|
|
3895
4328
|
async handleIncomingGroupMessage(data) {
|
|
3896
4329
|
if (!data || typeof data !== 'object')
|
|
@@ -3994,7 +4427,7 @@ export class AUNChannel {
|
|
|
3994
4427
|
const createdAt = data.created_at;
|
|
3995
4428
|
if (!peerInfo)
|
|
3996
4429
|
this.prefetchPeerInfo(senderAid);
|
|
3997
|
-
this.handleEcho({
|
|
4430
|
+
void this.handleEcho({
|
|
3998
4431
|
channelId: groupId,
|
|
3999
4432
|
userId: senderAid,
|
|
4000
4433
|
text,
|
|
@@ -4005,7 +4438,7 @@ export class AUNChannel {
|
|
|
4005
4438
|
seq,
|
|
4006
4439
|
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId, readTopicStatus(payload)),
|
|
4007
4440
|
createdAt,
|
|
4008
|
-
});
|
|
4441
|
+
}).catch(() => { });
|
|
4009
4442
|
return;
|
|
4010
4443
|
}
|
|
4011
4444
|
}
|
|
@@ -4244,12 +4677,24 @@ export class AUNChannel {
|
|
|
4244
4677
|
const hasEvolCoreTracePrivate = /\[EvolCore\.(receive|reply|agent)\]/.test(event.text);
|
|
4245
4678
|
// echo:不进大模型,直接回包
|
|
4246
4679
|
if (echoKindPrivate === 'echo' && !hasEvolCoreTracePrivate) {
|
|
4247
|
-
|
|
4680
|
+
if (event.contactDelivery) {
|
|
4681
|
+
return this.handleEcho(event).then(() => {
|
|
4682
|
+
if (!this.contactReplayFinishHandler)
|
|
4683
|
+
throw new Error('contact terminal persistence unavailable');
|
|
4684
|
+
this.contactReplayFinishHandler(event.contactDelivery);
|
|
4685
|
+
});
|
|
4686
|
+
}
|
|
4687
|
+
void this.handleEcho(event).catch(() => { });
|
|
4248
4688
|
return;
|
|
4249
4689
|
}
|
|
4250
4690
|
// 回声炸弹:已被任何 EvolCore 节点 trace 过的探针,直接丢弃
|
|
4251
4691
|
if (echoKindPrivate !== null && hasEvolCoreTracePrivate) {
|
|
4252
4692
|
logger.info(`${this.logPrefix()} Dropped: echo bomb (already-traced mid=${event.messageId} chat=${event.chatType})`);
|
|
4693
|
+
if (event.contactDelivery) {
|
|
4694
|
+
if (!this.contactReplayFinishHandler)
|
|
4695
|
+
throw new Error('contact terminal persistence unavailable');
|
|
4696
|
+
this.contactReplayFinishHandler(event.contactDelivery);
|
|
4697
|
+
}
|
|
4253
4698
|
return;
|
|
4254
4699
|
}
|
|
4255
4700
|
// echo.ask / echo.ecdiag:追加 trace 后继续交给 agent 处理
|
|
@@ -4284,10 +4729,11 @@ export class AUNChannel {
|
|
|
4284
4729
|
};
|
|
4285
4730
|
const handler = this.messageHandler;
|
|
4286
4731
|
const inbound = {
|
|
4732
|
+
contactDelivery: trustedContactInboundDelivery(event.contactDelivery),
|
|
4287
4733
|
channelId: event.channelId || '',
|
|
4288
4734
|
channelType: 'aun',
|
|
4289
4735
|
content: event.text || '',
|
|
4290
|
-
selfAID: this._aid,
|
|
4736
|
+
selfAID: this._aid || this.config.aid,
|
|
4291
4737
|
groupId: event.groupId,
|
|
4292
4738
|
chatType: event.chatType,
|
|
4293
4739
|
peerId: event.userId || event.channelId || '',
|
|
@@ -4327,11 +4773,15 @@ export class AUNChannel {
|
|
|
4327
4773
|
// 落地先于这一轮处理:ECK 的 hasOwnerDirectory 是同步 stat,名录没落盘时
|
|
4328
4774
|
// 本轮上下文就会丢掉整段名录。这段最多等 OWNER_DIRECTORY_APPLY_WAIT_MS,
|
|
4329
4775
|
// 且只等本地 I/O;网络拉取仍在 processPendingDirectoryUpdate 里后台跑。
|
|
4330
|
-
|
|
4776
|
+
const dispatched = this.settleOwnerDirectoryBeforeTurn()
|
|
4331
4777
|
.then(() => handler(inbound))
|
|
4332
4778
|
.catch(err => {
|
|
4333
4779
|
logger.error(`${this.logPrefix()} Message handler error:`, err);
|
|
4780
|
+
if (event.contactDelivery)
|
|
4781
|
+
throw err;
|
|
4334
4782
|
});
|
|
4783
|
+
if (event.contactDelivery)
|
|
4784
|
+
return dispatched;
|
|
4335
4785
|
}
|
|
4336
4786
|
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery) {
|
|
4337
4787
|
try {
|
|
@@ -4864,18 +5314,21 @@ export class AUNChannel {
|
|
|
4864
5314
|
: { chatType: 'private' };
|
|
4865
5315
|
const context = {
|
|
4866
5316
|
threadId: event.threadId ?? event.replyContext?.threadId,
|
|
4867
|
-
metadata: event.
|
|
5317
|
+
metadata: event.contactDelivery
|
|
5318
|
+
? { ...event.replyContext?.metadata, operationId: `contact-echo-${event.contactDelivery.key}` }
|
|
5319
|
+
: event.replyContext?.metadata,
|
|
4868
5320
|
delivery: authenticatedDelivery,
|
|
4869
5321
|
};
|
|
4870
5322
|
const sendStart = Date.now();
|
|
4871
5323
|
this.isEchoSending = true;
|
|
4872
|
-
this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
5324
|
+
return this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
4873
5325
|
this.isEchoSending = false;
|
|
4874
5326
|
const elapsed = Date.now() - sendStart;
|
|
4875
5327
|
logger.info(`${this.logPrefix()} Echo reply sent to ${replyTarget} (${elapsed}ms)`);
|
|
4876
5328
|
}).catch(e => {
|
|
4877
5329
|
this.isEchoSending = false;
|
|
4878
5330
|
logger.error(`${this.logPrefix()} Echo reply failed: ${e}`);
|
|
5331
|
+
throw e;
|
|
4879
5332
|
});
|
|
4880
5333
|
}
|
|
4881
5334
|
/**
|
|
@@ -5413,6 +5866,7 @@ export class AUNChannel {
|
|
|
5413
5866
|
* 应答支不经过这里——那由 AunRequestRegistry 在消息层更早匹配。
|
|
5414
5867
|
*/
|
|
5415
5868
|
async handleServiceMessage(input) {
|
|
5869
|
+
const startedAt = Date.now();
|
|
5416
5870
|
const router = this.ensureServiceRouter();
|
|
5417
5871
|
const payload = input.payload;
|
|
5418
5872
|
const rawType = typeof payload.type === 'string' ? payload.type : '';
|
|
@@ -5439,7 +5893,11 @@ export class AUNChannel {
|
|
|
5439
5893
|
const reply = await router.handleRequest(message, { admission });
|
|
5440
5894
|
if (!reply.shouldSend)
|
|
5441
5895
|
return;
|
|
5896
|
+
const handledAt = Date.now();
|
|
5442
5897
|
await this.sendServiceReply(input.fromAid, input.messageId, input.encrypted, reply);
|
|
5898
|
+
if (isProjectionServiceResult(reply.type)) {
|
|
5899
|
+
logger.info(`${this.logPrefix()} ServiceProjection id=${requestId} type=${rawType} queueMs=${Math.max(0, startedAt - input.receivedAt)} handleMs=${handledAt - startedAt} sendMs=${Date.now() - handledAt}`);
|
|
5900
|
+
}
|
|
5443
5901
|
}
|
|
5444
5902
|
/** 回复:点对点、带 service 标记位,不带 threadId/topicName/chatmode。 */
|
|
5445
5903
|
async sendServiceReply(toAid, replyToMessageId, encrypted, reply) {
|
|
@@ -5457,6 +5915,7 @@ export class AUNChannel {
|
|
|
5457
5915
|
}
|
|
5458
5916
|
onMessage(handler) {
|
|
5459
5917
|
this.messageHandler = handler;
|
|
5918
|
+
this.scheduleContactReplay();
|
|
5460
5919
|
}
|
|
5461
5920
|
setMentionModeResolver(resolver) {
|
|
5462
5921
|
this.mentionModeResolver = resolver;
|
|
@@ -5738,44 +6197,21 @@ export class AUNChannel {
|
|
|
5738
6197
|
const timer = setTimeout(() => this.invalidatedInteractions.delete(interactionId), 24 * 60 * 60 * 1000);
|
|
5739
6198
|
timer.unref?.();
|
|
5740
6199
|
}
|
|
5741
|
-
async recallInteractionCard(messageId, channelId, delivery) {
|
|
5742
|
-
if (!this.client || !this.connected)
|
|
5743
|
-
return false;
|
|
5744
|
-
try {
|
|
5745
|
-
if (!channelId || !delivery) {
|
|
5746
|
-
logger.warn(`${this.logPrefix()} Cannot recall interaction card without trusted delivery route: mid=${messageId}`);
|
|
5747
|
-
return false;
|
|
5748
|
-
}
|
|
5749
|
-
const isGroup = delivery.chatType === 'group';
|
|
5750
|
-
const method = isGroup ? 'group.recall' : 'message.recall';
|
|
5751
|
-
const params = isGroup
|
|
5752
|
-
? { group_id: delivery.groupId, message_ids: [messageId] }
|
|
5753
|
-
: { message_ids: [messageId] };
|
|
5754
|
-
await this.callAndTrace(method, params, { silentError: true });
|
|
5755
|
-
return true;
|
|
5756
|
-
}
|
|
5757
|
-
catch (error) {
|
|
5758
|
-
logger.debug(`${this.logPrefix()} Failed to recall invalidated interaction card mid=${messageId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
5759
|
-
return false;
|
|
5760
|
-
}
|
|
5761
|
-
}
|
|
5762
6200
|
/**
|
|
5763
|
-
*
|
|
5764
|
-
*
|
|
5765
|
-
* rejects any concurrent/late callback independently.
|
|
6201
|
+
* Disable AUN card interactions while preserving the original chat message.
|
|
6202
|
+
* Drop undelivered cards and actionable mappings; the response router still
|
|
6203
|
+
* rejects any concurrent/late callback independently. Never recall a card
|
|
6204
|
+
* merely because its interaction has ended.
|
|
5766
6205
|
*/
|
|
5767
6206
|
async invalidateInteraction(interactionId, reason = 'cancelled') {
|
|
5768
6207
|
this.rememberInvalidatedInteraction(interactionId, reason);
|
|
5769
6208
|
const removedQueued = outbox.removeInteractionCards(this.config.aid, interactionId);
|
|
5770
6209
|
if (removedQueued > 0) {
|
|
5771
|
-
logger.info(`${this.logPrefix()} Removed ${removedQueued}
|
|
6210
|
+
logger.info(`${this.logPrefix()} Removed ${removedQueued} invalidated interaction card(s) from durable outbox: request=${interactionId}`);
|
|
5772
6211
|
}
|
|
5773
6212
|
const messageIds = [...(this.interactionCardMessageIds.get(interactionId) ?? [])];
|
|
5774
6213
|
for (const messageId of messageIds) {
|
|
5775
|
-
const card = this.cardMessageIdMap.get(messageId);
|
|
5776
|
-
const channelId = card?.channelId;
|
|
5777
6214
|
this.forgetInteractionCard(messageId, interactionId);
|
|
5778
|
-
await this.recallInteractionCard(messageId, channelId, card?.delivery);
|
|
5779
6215
|
}
|
|
5780
6216
|
}
|
|
5781
6217
|
restoreInteraction(envelope, interaction, receipt) {
|
|
@@ -5907,13 +6343,16 @@ export class AUNChannel {
|
|
|
5907
6343
|
ownedTimer.unref?.();
|
|
5908
6344
|
const invalidationReason = this.invalidatedInteractions.get(action.requestId);
|
|
5909
6345
|
if (invalidationReason) {
|
|
5910
|
-
this.
|
|
5911
|
-
void this.recallInteractionCard(messageId, channelId, delivery ?? action.delivery);
|
|
6346
|
+
this.forgetInteractionCard(messageId, action.requestId);
|
|
5912
6347
|
}
|
|
5913
6348
|
}
|
|
5914
6349
|
runPostSend(entry, messageId) {
|
|
5915
6350
|
if (!entry.postSend)
|
|
5916
6351
|
return;
|
|
6352
|
+
if (entry.postSend.type === 'register_contact_approval_card') {
|
|
6353
|
+
registerContactApprovalCard(this.config.aid, entry.postSend.pendingKey, entry.postSend.eventId, messageId);
|
|
6354
|
+
return;
|
|
6355
|
+
}
|
|
5917
6356
|
if (entry.postSend.type === 'register_interaction_card') {
|
|
5918
6357
|
this.registerCardPostSend(messageId, entry.postSend, entry.channelId, entry.delivery, entry.context);
|
|
5919
6358
|
if (entry.postSend.requestId.startsWith('gir-'))
|
|
@@ -5934,66 +6373,8 @@ export class AUNChannel {
|
|
|
5934
6373
|
const target = normalize(channelId);
|
|
5935
6374
|
return !!self && !!target && self === target;
|
|
5936
6375
|
}
|
|
5937
|
-
appContactOutboundBlock(channelId, delivery, payload, params) {
|
|
5938
|
-
// 服务回复是对一次已到达请求的应答,不是主动联系;且拒绝信息本身必须能送达,
|
|
5939
|
-
// 否则调用方只会看到超时。
|
|
5940
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5941
|
-
return undefined;
|
|
5942
|
-
// 跨话题自派:收件人是本端,不是跨主体通讯,不适用联系人准入(同 aun-ipc-sender)。
|
|
5943
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5944
|
-
return undefined;
|
|
5945
|
-
if (delivery.chatType === 'group' || this.config.pureIdentity
|
|
5946
|
-
|| this.hasContactControlPermit(channelId, payload, params))
|
|
5947
|
-
return undefined;
|
|
5948
|
-
const decision = evaluateAppContactAdmission(this.config.aid, channelId);
|
|
5949
|
-
if (params?.encrypt === true && params?.rawPayload === true && parseFriendInvite(payload, this.config.aid, channelId)
|
|
5950
|
-
&& decision.reason === 'not_in_contacts')
|
|
5951
|
-
return undefined;
|
|
5952
|
-
if (decision.allow)
|
|
5953
|
-
return undefined;
|
|
5954
|
-
return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
|
|
5955
|
-
code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE' : 'CONTACT_DENIED',
|
|
5956
|
-
error: `联系人准入未通过:${decision.reason}` };
|
|
5957
|
-
}
|
|
5958
|
-
async prepareAppContactOutbound(channelId, delivery, payload, params) {
|
|
5959
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5960
|
-
return undefined;
|
|
5961
|
-
// 跨话题自派:收件人是本端,连通告归属刷新这一跳都不需要。
|
|
5962
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5963
|
-
return undefined;
|
|
5964
|
-
if (delivery.chatType === 'private' && !this.config.pureIdentity
|
|
5965
|
-
&& !this.hasContactControlPermit(channelId, payload, params)
|
|
5966
|
-
&& !this.acceptsVerifiedOwnership(channelId, payload, params)) {
|
|
5967
|
-
await ownerResolver.refresh(this.config.aid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
5968
|
-
}
|
|
5969
|
-
return this.appContactOutboundBlock(channelId, delivery, payload, params);
|
|
5970
|
-
}
|
|
5971
|
-
/**
|
|
5972
|
-
* A caller that already holds the consensus may skip the refresh round-trip.
|
|
5973
|
-
*
|
|
5974
|
-
* Only lifecycle notices qualify, and only toward their own Owner. Shutdown is
|
|
5975
|
-
* the reason this exists: the offline notice runs while the daemon is tearing
|
|
5976
|
-
* down, so a network refresh would outlive the AUN connection it needs.
|
|
5977
|
-
* Admission itself is unchanged — the block below still demands a live
|
|
5978
|
-
* consensus in the resolver cache, so this skips the check of the cache's
|
|
5979
|
-
* freshness, never the requirement that a consensus exists.
|
|
5980
|
-
*/
|
|
5981
|
-
acceptsVerifiedOwnership(channelId, payload, params) {
|
|
5982
|
-
if (params?.ownershipVerified !== true)
|
|
5983
|
-
return false;
|
|
5984
|
-
const notice = payload;
|
|
5985
|
-
if (!notice || notice.type !== 'notice'
|
|
5986
|
-
|| (notice.subtype !== 'agent.online' && notice.subtype !== 'agent.offline'))
|
|
5987
|
-
return false;
|
|
5988
|
-
// Even if the flag ever leaked, it cannot widen admission: the target must be
|
|
5989
|
-
// the Owner the live consensus names, which admission allows unconditionally.
|
|
5990
|
-
return currentContactBinding(this.config.aid)?.owner_aid === channelId;
|
|
5991
|
-
}
|
|
5992
6376
|
async sendAunPayload(channelId, payload, context, label) {
|
|
5993
6377
|
const delivery = this.requireDelivery(channelId, context);
|
|
5994
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, payload);
|
|
5995
|
-
if (blocked)
|
|
5996
|
-
return { ok: false, ...blocked };
|
|
5997
6378
|
let normalizedPayload;
|
|
5998
6379
|
try {
|
|
5999
6380
|
normalizedPayload = this.normalizeAunPayloadMentions(payload);
|
|
@@ -6027,7 +6408,7 @@ export class AUNChannel {
|
|
|
6027
6408
|
if (payloadWithCausationRef.thread_id === '')
|
|
6028
6409
|
delete payloadWithCausationRef.thread_id;
|
|
6029
6410
|
// Truncate payload if too large (AUN SDK limit: 1MB)
|
|
6030
|
-
const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
|
|
6411
|
+
const friendPayload = (typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload);
|
|
6031
6412
|
const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
6032
6413
|
if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
|
|
6033
6414
|
|| (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
|
|
@@ -6123,7 +6504,7 @@ export class AUNChannel {
|
|
|
6123
6504
|
};
|
|
6124
6505
|
}
|
|
6125
6506
|
recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
|
|
6126
|
-
if (typeof payload.type === 'string' && payload.type.startsWith('friend.')) {
|
|
6507
|
+
if ((typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload)) {
|
|
6127
6508
|
logger.info(`${this.logPrefix()} Contact control transport accepted: type=${payload.type} mid=${messageId}`);
|
|
6128
6509
|
return;
|
|
6129
6510
|
}
|
|
@@ -6513,49 +6894,6 @@ export class AUNChannel {
|
|
|
6513
6894
|
this.sentCount.set(turnKey, seqInTurn);
|
|
6514
6895
|
return seqInTurn;
|
|
6515
6896
|
}
|
|
6516
|
-
/** An unadmitted outbound text becomes an Owner request, never a send to the peer. */
|
|
6517
|
-
async requestOutboundContact(args) {
|
|
6518
|
-
const selfAid = this.config.aid;
|
|
6519
|
-
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
6520
|
-
const binding = currentContactBinding(selfAid);
|
|
6521
|
-
if (!binding) {
|
|
6522
|
-
return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
|
|
6523
|
-
}
|
|
6524
|
-
const decision = evaluateAppContactAdmission(selfAid, args.to);
|
|
6525
|
-
if (decision.allow || (decision.reason !== 'not_in_contacts' && decision.reason !== 'scope_extension')) {
|
|
6526
|
-
return { ok: false, code: 'CONTACT_DENIED', error: `联系人状态不允许提交申请:${decision.reason};原消息未发送` };
|
|
6527
|
-
}
|
|
6528
|
-
const text = contactIntroductionText(args.payload);
|
|
6529
|
-
if (text === undefined) {
|
|
6530
|
-
return { ok: false, code: 'CONTACT_DENIED', error: '只有纯文本可以向本端 Owner 提交联系申请;原消息未发送' };
|
|
6531
|
-
}
|
|
6532
|
-
if (!consumeContactIntroductionBudget(selfAid, `outbound:${args.to}`)) {
|
|
6533
|
-
return { ok: false, code: 'CONTACT_INTRODUCTION_RATE_LIMIT', error: '联系申请过于频繁,请稍后重试;原消息未发送' };
|
|
6534
|
-
}
|
|
6535
|
-
const request = {
|
|
6536
|
-
...buildContactRequest(binding, args.to, args.sourceMessageId, Date.now(), `申请联系 ${args.to}。以下为本端拟发送的内容,尚未发给对方:\n${text}`, decision.reason),
|
|
6537
|
-
direction: 'outbound',
|
|
6538
|
-
};
|
|
6539
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
6540
|
-
if (remainingTtl <= 0) {
|
|
6541
|
-
return { ok: false, code: 'CONTACT_REQUEST_EXPIRED', error: '联系申请已过期,未重新提交;原消息未发送' };
|
|
6542
|
-
}
|
|
6543
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
6544
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 outbound]',
|
|
6545
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
6546
|
-
ttl: remainingTtl,
|
|
6547
|
-
});
|
|
6548
|
-
if (!sent.messageId && !sent.queued) {
|
|
6549
|
-
return { ok: false, code: sent.code ?? 'CONTACT_OWNER_REQUEST_FAILED',
|
|
6550
|
-
error: `向本端 Owner 提交联系申请失败:${sent.error ?? '未获得发送或排队回执'};原消息未发送` };
|
|
6551
|
-
}
|
|
6552
|
-
return { ok: true, receipt: {
|
|
6553
|
-
event_id: request.event_id, owner_aid: binding.owner_aid, target_aid: args.to,
|
|
6554
|
-
status: sent.messageId ? 'sent' : 'queued',
|
|
6555
|
-
...(sent.messageId ? { message_id: sent.messageId } : {}),
|
|
6556
|
-
...(sent.outboxId ? { outbox_id: sent.outboxId } : {}),
|
|
6557
|
-
} };
|
|
6558
|
-
}
|
|
6559
6897
|
async sendDaemonMsg(args) {
|
|
6560
6898
|
try {
|
|
6561
6899
|
resolveAunSendDevice(args.deviceId, 'msg', args.payload);
|
|
@@ -6589,6 +6927,38 @@ export class AUNChannel {
|
|
|
6589
6927
|
code: e?.code,
|
|
6590
6928
|
};
|
|
6591
6929
|
}
|
|
6930
|
+
// Friend invitations are durable control messages. Keep the validated
|
|
6931
|
+
// application payload intact, require E2EE, and use the business ID as the
|
|
6932
|
+
// retry key so reconnects cannot create a second logical invitation.
|
|
6933
|
+
const durableInvite = finalPayload.type === FRIEND_INVITE_TYPE || finalPayload.type === FRIEND_INVITE_PROOF_TYPE;
|
|
6934
|
+
if (durableInvite) {
|
|
6935
|
+
if (args.encrypt !== true || args.ttl !== undefined || args.rawPayload !== true) {
|
|
6936
|
+
return { ok: false, error: 'friend invite controls require encrypted persistent raw delivery', code: 'FRIEND_CONTROL_REQUIREMENTS' };
|
|
6937
|
+
}
|
|
6938
|
+
const parsedInvite = finalPayload.type === FRIEND_INVITE_TYPE
|
|
6939
|
+
? parseFriendInvite(finalPayload, this.config.aid, args.to)
|
|
6940
|
+
: parseFriendInviteProof(finalPayload, this.config.aid, args.to)?.invite;
|
|
6941
|
+
if (!parsedInvite)
|
|
6942
|
+
return { ok: false, error: 'invalid friend invite control payload', code: 'INVALID_FRIEND_INVITE' };
|
|
6943
|
+
const businessId = finalPayload.type === FRIEND_INVITE_TYPE
|
|
6944
|
+
? finalPayload.invite_id
|
|
6945
|
+
: finalPayload.proof_id;
|
|
6946
|
+
const expiresAt = parsedInvite.expires_at_ms;
|
|
6947
|
+
if (expiresAt <= Date.now()) {
|
|
6948
|
+
return { ok: false, status: 'failed', encrypt: true, error: 'friend invite has expired', code: 'FRIEND_INVITE_EXPIRED' };
|
|
6949
|
+
}
|
|
6950
|
+
const sent = await this.sendContentPayload(args.to, finalPayload, {
|
|
6951
|
+
contentKind: 'custom', dedupeKey: `${finalPayload.type}:${businessId}`,
|
|
6952
|
+
logText: `[${finalPayload.type}]`,
|
|
6953
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true, source: 'daemon' } },
|
|
6954
|
+
ttl: Math.max(1, expiresAt - Date.now()),
|
|
6955
|
+
});
|
|
6956
|
+
if (sent.messageId)
|
|
6957
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', encrypt: true };
|
|
6958
|
+
if (sent.queued)
|
|
6959
|
+
return { ok: true, status: 'queued', encrypt: true, outbox_id: sent.outboxId, error: sent.error, code: sent.code };
|
|
6960
|
+
return { ok: false, status: 'failed', encrypt: true, outbox_id: sent.outboxId, error: sent.error ?? 'friend invite control send failed', code: sent.code };
|
|
6961
|
+
}
|
|
6592
6962
|
if (!this.connected || !this.client) {
|
|
6593
6963
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6594
6964
|
}
|
|
@@ -6599,9 +6969,6 @@ export class AUNChannel {
|
|
|
6599
6969
|
code: 'INVALID_REQUEST_TTL',
|
|
6600
6970
|
};
|
|
6601
6971
|
}
|
|
6602
|
-
const contactBlock = await this.prepareAppContactOutbound(args.to, args.service ? { chatType: 'private', service: args.service } : { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
|
|
6603
|
-
if (contactBlock)
|
|
6604
|
-
return { ok: false, code: contactBlock.code, error: contactBlock.error };
|
|
6605
6972
|
if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
|
|
6606
6973
|
return {
|
|
6607
6974
|
ok: false,
|
|
@@ -7081,11 +7448,6 @@ export class AUNChannel {
|
|
|
7081
7448
|
const finalText = entry.text;
|
|
7082
7449
|
const delivery = this.requirePersistedDelivery(channelId, entry.delivery);
|
|
7083
7450
|
const context = this.withDelivery(entry.context, delivery);
|
|
7084
|
-
if (!entry.deliveryReceipt) {
|
|
7085
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, { type: 'text', text: entry.text });
|
|
7086
|
-
if (blocked)
|
|
7087
|
-
return blocked;
|
|
7088
|
-
}
|
|
7089
7451
|
const operationId = entry.dedupeKey
|
|
7090
7452
|
|| (typeof context?.metadata?.operationId === 'string' ? context.metadata.operationId : undefined);
|
|
7091
7453
|
if (operationId) {
|
|
@@ -7355,18 +7717,34 @@ export class AUNChannel {
|
|
|
7355
7717
|
}
|
|
7356
7718
|
}
|
|
7357
7719
|
async deliverPayloadEntry(entry) {
|
|
7358
|
-
if (
|
|
7720
|
+
if (entry.payload?.type === 'friend.request.v1' && entry.payload.direction === 'outbound') {
|
|
7721
|
+
return { ok: false, status: 'permanent', code: 'OUTBOUND_APPROVAL_RETIRED', error: 'outbound contact approval is no longer required' };
|
|
7722
|
+
}
|
|
7723
|
+
if (!entry.deliveryReceipt && ((typeof entry.payload?.type === 'string' && entry.payload.type.startsWith('friend.'))
|
|
7724
|
+
|| isContactApprovalCard(entry.payload))) {
|
|
7359
7725
|
const selfAid = this.config.aid;
|
|
7360
7726
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.outbox' });
|
|
7361
7727
|
const binding = verifiedContactBinding(selfAid, view);
|
|
7362
7728
|
if (!binding)
|
|
7363
7729
|
return { ok: false, status: 'retry', code: 'CONTACT_OWNERSHIP_UNAVAILABLE', error: 'current Owner relation could not be verified' };
|
|
7364
|
-
|
|
7730
|
+
const routePayload = isContactApprovalCard(entry.payload) ? entry.payload?.friend_request ?? {} : entry.payload;
|
|
7731
|
+
if (!friendPayloadRouteValid(routePayload, entry.channelId, true, binding)) {
|
|
7365
7732
|
return { ok: false, status: 'permanent', code: 'CONTACT_OWNERSHIP_CHANGED', error: 'contact event no longer belongs to the current Owner relation' };
|
|
7366
7733
|
}
|
|
7367
7734
|
// E2EE is mandatory even for a recovered queue entry.
|
|
7368
7735
|
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
7369
7736
|
}
|
|
7737
|
+
if (!entry.deliveryReceipt && isContactApprovalCard(entry.payload)) {
|
|
7738
|
+
const action = entry.postSend;
|
|
7739
|
+
const pending = action?.type === 'register_contact_approval_card'
|
|
7740
|
+
? readPendingContactInbound(this.config.aid, action.pendingKey) : undefined;
|
|
7741
|
+
if (!pending?.message || !pending.approval || !['waiting', 'transferring'].includes(pending.state)
|
|
7742
|
+
|| pending.approval.eventId !== entry.payload?.friend_request?.event_id
|
|
7743
|
+
|| pending.expiresAt <= Date.now()
|
|
7744
|
+
|| normalizeThreadIdForPeer(entry.payload?.thread_id, this.config.aid, entry.channelId) !== pending.approval.originThreadId) {
|
|
7745
|
+
return { ok: false, status: 'permanent', code: 'CONTACT_APPROVAL_STALE', error: 'contact approval card is no longer pending' };
|
|
7746
|
+
}
|
|
7747
|
+
}
|
|
7370
7748
|
const interactionId = entry.postSend?.type === 'register_interaction_card'
|
|
7371
7749
|
? entry.postSend.requestId
|
|
7372
7750
|
: undefined;
|
|
@@ -7412,15 +7790,16 @@ export class AUNChannel {
|
|
|
7412
7790
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7413
7791
|
if (entry.deliveryReceipt) {
|
|
7414
7792
|
try {
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
|
|
7422
|
-
|
|
7423
|
-
|
|
7793
|
+
if (!isContactApprovalCard(payload))
|
|
7794
|
+
this.appendOutboundJsonl(channelId, {
|
|
7795
|
+
...classifyAunPayloadForLog(payload),
|
|
7796
|
+
msgId: entry.deliveryReceipt.messageId,
|
|
7797
|
+
encrypt: entry.deliveryReceipt.encrypt,
|
|
7798
|
+
context,
|
|
7799
|
+
isGroup,
|
|
7800
|
+
source,
|
|
7801
|
+
transport: entry.deliveryReceipt.transport,
|
|
7802
|
+
});
|
|
7424
7803
|
this.runPostSend(entry, entry.deliveryReceipt.messageId);
|
|
7425
7804
|
return {
|
|
7426
7805
|
ok: true,
|
|
@@ -7654,7 +8033,7 @@ export class AUNChannel {
|
|
|
7654
8033
|
}
|
|
7655
8034
|
const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
|
|
7656
8035
|
const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
|
|
7657
|
-
&&
|
|
8036
|
+
&& isProjectionServiceResult(finalPayload.type);
|
|
7658
8037
|
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
7659
8038
|
const params = { payload: finalPayload, encrypt };
|
|
7660
8039
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
@@ -7875,11 +8254,6 @@ export class AUNChannel {
|
|
|
7875
8254
|
return imagePayload;
|
|
7876
8255
|
}
|
|
7877
8256
|
async deliverImageEntry(entry) {
|
|
7878
|
-
if (!entry.deliveryReceipt) {
|
|
7879
|
-
const blocked = await this.prepareAppContactOutbound(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'image' });
|
|
7880
|
-
if (blocked)
|
|
7881
|
-
return blocked;
|
|
7882
|
-
}
|
|
7883
8257
|
const image = entry.image;
|
|
7884
8258
|
if (!image || typeof image.dataBase64 !== 'string') {
|
|
7885
8259
|
logger.warn(`${this.logPrefix()} deliverImageEntry: missing image data (outbox id=${entry.id})`);
|
|
@@ -7926,11 +8300,6 @@ export class AUNChannel {
|
|
|
7926
8300
|
}
|
|
7927
8301
|
}
|
|
7928
8302
|
async deliverFileEntry(entry) {
|
|
7929
|
-
if (!entry.deliveryReceipt) {
|
|
7930
|
-
const blocked = await this.prepareAppContactOutbound(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'file' });
|
|
7931
|
-
if (blocked)
|
|
7932
|
-
return blocked;
|
|
7933
|
-
}
|
|
7934
8303
|
const channelId = entry.channelId;
|
|
7935
8304
|
if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
|
|
7936
8305
|
logger.warn(`${this.logPrefix()} deliverFileEntry: missing file path (outbox id=${entry.id})`);
|
|
@@ -9140,8 +9509,9 @@ export class AUNChannelPlugin {
|
|
|
9140
9509
|
disconnect: (clientCloseBudgetMs) => channel.disconnect(clientCloseBudgetMs),
|
|
9141
9510
|
onProjectPathRequest: () => Promise.resolve(ctx.defaultProjectPath),
|
|
9142
9511
|
registerBridge(bridge, channelType) {
|
|
9512
|
+
channel.setContactReplayReceiptResolver(key => bridge.contactDeliveryReceipt(key), delivery => bridge.finishContactDelivery(delivery));
|
|
9143
9513
|
bridge.register(adapter.channelName, (handler) => channel.onMessage(async (opts) => {
|
|
9144
|
-
handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9514
|
+
await handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9145
9515
|
}), async (channelId, text, replyContext) => { await channel.sendMessage(channelId, text, replyContext); }, adapter, channelType);
|
|
9146
9516
|
bridge.registerGroupInviteReviewChannel({
|
|
9147
9517
|
selfAid: aid,
|