evolcore 0.0.47 → 0.0.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- 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 +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- 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/protected-paths.js +6 -6
- 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 +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- 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 +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
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';
|
|
@@ -28,11 +30,11 @@ import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
|
|
|
28
30
|
import { chatDirPath } from '../core/session/session-fs-store.js';
|
|
29
31
|
import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
|
|
30
32
|
import { resolveRuntimePermissionMode, sessionFullAccessStatus } from '../core/role/runtime-policy.js';
|
|
31
|
-
import {
|
|
33
|
+
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,
|
|
@@ -955,7 +999,7 @@ export class AUNChannel {
|
|
|
955
999
|
ownerDirectoryRetryAttempts = 0;
|
|
956
1000
|
ownerDirectoryResolvedSignature;
|
|
957
1001
|
store = null;
|
|
958
|
-
/**
|
|
1002
|
+
/** 服务路由实例(懒建;缺少 services-config.json 时默认开启,内置查询无需装包)。 */
|
|
959
1003
|
serviceRouter = null;
|
|
960
1004
|
/**
|
|
961
1005
|
* 本 agent 的工程目录,由插件从 `ChannelBuildContext.defaultProjectPath` 注入。
|
|
@@ -998,7 +1042,8 @@ export class AUNChannel {
|
|
|
998
1042
|
// 自动从 data 推断顶层字段(self_aid / peer_aid / group_id / task_id / chatmode),
|
|
999
1043
|
// 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
|
|
1000
1044
|
const inbound = data && typeof data === 'object' ? data : {};
|
|
1001
|
-
const isolateTrace = dir === 'IN' && event === 'message.received'
|
|
1045
|
+
const isolateTrace = dir === 'IN' && event === 'message.received'
|
|
1046
|
+
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply');
|
|
1002
1047
|
const safeData = isolateTrace ? {
|
|
1003
1048
|
message_id: inbound.message_id, seq: inbound.seq,
|
|
1004
1049
|
envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
|
|
@@ -1043,45 +1088,37 @@ export class AUNChannel {
|
|
|
1043
1088
|
callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
|
|
1044
1089
|
params = menuTransportParams(method, params);
|
|
1045
1090
|
const client = this.client;
|
|
1046
|
-
const
|
|
1047
|
-
|
|
1048
|
-
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;
|
|
1049
1094
|
onPrepared?.(params);
|
|
1050
1095
|
return this.withOutboundSendGate(method, async () => {
|
|
1051
1096
|
if (client !== this.client || !client)
|
|
1052
1097
|
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1053
|
-
if (!this.config.pureIdentity &&
|
|
1098
|
+
if (!this.config.pureIdentity && friendPayload
|
|
1054
1099
|
&& (method === 'message.send' || method === 'message.thought.put')) {
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
}
|
|
1061
|
-
if (!friendPayloadRouteValid(params.payload, params.to, params.encrypt, verified)
|
|
1062
|
-
|| !sameContactBinding(verified, currentContactBinding(this.config.aid))) {
|
|
1063
|
-
throw Object.assign(new Error('contact Owner relation changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1064
|
-
}
|
|
1065
|
-
if (client !== this.client)
|
|
1066
|
-
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' });
|
|
1067
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' });
|
|
1109
|
+
}
|
|
1110
|
+
if (client !== this.client)
|
|
1111
|
+
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1068
1112
|
const current = currentContactBinding(this.config.aid);
|
|
1069
1113
|
if (!current)
|
|
1070
1114
|
throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
|
|
1071
1115
|
if (!binding || !sameContactBinding(binding, current))
|
|
1072
1116
|
throw Object.assign(new Error('Owner relation changed while queued'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1073
|
-
|
|
1074
|
-
if (typeof payload?.type === 'string' && payload.type.startsWith('friend.')
|
|
1075
|
-
&& !friendPayloadRouteValid(payload, params.to, params.encrypt, current)) {
|
|
1117
|
+
if (!friendPayloadRouteValid(routePayload, params.to, params.encrypt, current)) {
|
|
1076
1118
|
throw Object.assign(new Error('contact event relation or encryption changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1077
1119
|
}
|
|
1078
|
-
if (
|
|
1079
|
-
|
|
1080
|
-
if (blocked) {
|
|
1081
|
-
throw Object.assign(new Error(blocked.error), {
|
|
1082
|
-
code: blocked.code, retryable: blocked.status === 'retry',
|
|
1083
|
-
});
|
|
1084
|
-
}
|
|
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' });
|
|
1085
1122
|
}
|
|
1086
1123
|
}
|
|
1087
1124
|
beforeSend?.();
|
|
@@ -1320,7 +1357,7 @@ export class AUNChannel {
|
|
|
1320
1357
|
logger.info(`${this.logPrefix()} ActionInteraction audit: behavior=${behavior ?? 'reply'} `
|
|
1321
1358
|
+ `cardId=${cardMessageId} interactionId=${interactionId} result=${result} textLength=${textLength}`);
|
|
1322
1359
|
}
|
|
1323
|
-
extractTextPayload(payload, channelId, senderAid, delivery) {
|
|
1360
|
+
extractTextPayload(payload, channelId, senderAid, delivery, encrypted) {
|
|
1324
1361
|
if (typeof payload === 'string')
|
|
1325
1362
|
return payload;
|
|
1326
1363
|
if (payload && typeof payload === 'object') {
|
|
@@ -1331,6 +1368,11 @@ export class AUNChannel {
|
|
|
1331
1368
|
const cardMsgId = typeof obj.ref_message_id === 'string' ? obj.ref_message_id
|
|
1332
1369
|
: typeof obj.card_message_id === 'string' ? obj.card_message_id : '';
|
|
1333
1370
|
const cardInfo = cardMsgId ? this.cardMessageIdMap.get(cardMsgId) : undefined;
|
|
1371
|
+
if (cardInfo?.sensitive && (encrypted !== true || delivery?.chatType !== 'private'
|
|
1372
|
+
|| !senderAid || senderAid !== cardInfo.initiatorAid || channelId !== cardInfo.channelId)) {
|
|
1373
|
+
this.notifyCardActionFailure(channelId, '凭据仅接受卡片发起者通过加密私聊提交', senderAid, channelId === cardInfo.channelId ? cardInfo.replyContext?.threadId : undefined, delivery);
|
|
1374
|
+
return '';
|
|
1375
|
+
}
|
|
1334
1376
|
const cardDelivery = cardInfo?.delivery ?? delivery;
|
|
1335
1377
|
const savedTopic = this.ownedCardTopics.get(cardMsgId);
|
|
1336
1378
|
// Keep the topic after the actionable mapping expires, including for
|
|
@@ -1463,6 +1505,7 @@ export class AUNChannel {
|
|
|
1463
1505
|
...(isComposeReply ? { custom_text: text } : {}),
|
|
1464
1506
|
},
|
|
1465
1507
|
operatorId: cardClickerAid || undefined,
|
|
1508
|
+
...(cardInfo.sensitive ? { encrypted: encrypted === true } : {}),
|
|
1466
1509
|
};
|
|
1467
1510
|
const settle = (accepted) => {
|
|
1468
1511
|
this.interactionActionsInFlight.delete(cardMsgId);
|
|
@@ -1476,8 +1519,8 @@ export class AUNChannel {
|
|
|
1476
1519
|
.finally(() => this.forgetInteractionCard(cardMsgId, cardInfo.requestId));
|
|
1477
1520
|
}
|
|
1478
1521
|
else {
|
|
1479
|
-
// Gateway-driven
|
|
1480
|
-
//
|
|
1522
|
+
// Gateway-driven invalidation has already disabled the card
|
|
1523
|
+
// before the callback returned. Keep the original message.
|
|
1481
1524
|
this.forgetInteractionCard(cardMsgId, cardInfo.requestId);
|
|
1482
1525
|
}
|
|
1483
1526
|
this.notifyCardActionFailure(channelId, '⚠️ 卡片已失效,请重新发起', cardClickerAid, threadId, cardDelivery);
|
|
@@ -1829,7 +1872,192 @@ export class AUNChannel {
|
|
|
1829
1872
|
void this.finishEcdiag(mid, 'shutdown').catch(() => { });
|
|
1830
1873
|
}
|
|
1831
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
|
+
}
|
|
1832
2057
|
stopOwnerDirectoryRefresh() {
|
|
2058
|
+
if (this.contactReplayTimer)
|
|
2059
|
+
clearTimeout(this.contactReplayTimer);
|
|
2060
|
+
this.contactReplayTimer = undefined;
|
|
1833
2061
|
this.ownerDirectoryWatch?.stop();
|
|
1834
2062
|
this.ownerDirectoryWatch = undefined;
|
|
1835
2063
|
if (this.ownerDirectoryRetryTimer)
|
|
@@ -1859,6 +2087,7 @@ export class AUNChannel {
|
|
|
1859
2087
|
}),
|
|
1860
2088
|
};
|
|
1861
2089
|
this.queueOwnerDirectoryRefresh();
|
|
2090
|
+
this.scheduleContactReplay();
|
|
1862
2091
|
}
|
|
1863
2092
|
ownerDirectoryViewSignature(view) {
|
|
1864
2093
|
return JSON.stringify([
|
|
@@ -1975,6 +2204,8 @@ export class AUNChannel {
|
|
|
1975
2204
|
// the new cache implementation own storage and event synchronization.
|
|
1976
2205
|
const directory = path.join(this.agentDir, 'directory');
|
|
1977
2206
|
const cache = new OwnerDirectoryCache({
|
|
2207
|
+
onSnapshotApplied: () => { if (isCurrent())
|
|
2208
|
+
this.scheduleContactReplay(); },
|
|
1978
2209
|
onSnapshotApplying: snapshot => { if (isCurrent())
|
|
1979
2210
|
reconcileTemporaryContactGrants(selfAid, snapshot); },
|
|
1980
2211
|
relationVersion,
|
|
@@ -2036,6 +2267,26 @@ export class AUNChannel {
|
|
|
2036
2267
|
invalidateAgentDisplayName(aid);
|
|
2037
2268
|
PeerIdentityCache.invalidate('aun', aid, path.join(resolvePaths().agentsDir, this.config.aid));
|
|
2038
2269
|
}
|
|
2270
|
+
/**
|
|
2271
|
+
* 入站发件人展示名:Owner 备注名 > 名片名 > AID 短名。
|
|
2272
|
+
*
|
|
2273
|
+
* 备注名来自 Owner 名录快照(App 里给联系人改的备注),比名片更贴近 Owner
|
|
2274
|
+
* 平时的称呼;名录取不到该条目时才回落到名片名。名录读取是本地快照、
|
|
2275
|
+
* 有文件戳缓存,不产生网络请求。
|
|
2276
|
+
*/
|
|
2277
|
+
inboundDisplayName(fromAid, cardName, shortAid) {
|
|
2278
|
+
let directoryName;
|
|
2279
|
+
try {
|
|
2280
|
+
const entry = this.ownerDirectoryCache?.cache.readSnapshot('contacts')?.entries
|
|
2281
|
+
.find(item => item.aid === fromAid);
|
|
2282
|
+
const remark = entry?.remark?.trim();
|
|
2283
|
+
if (remark)
|
|
2284
|
+
return remark;
|
|
2285
|
+
directoryName = entry?.name?.trim() || undefined;
|
|
2286
|
+
}
|
|
2287
|
+
catch { /* 名录不可用不影响消息处理 */ }
|
|
2288
|
+
return cardName?.trim() || directoryName || shortAid || fromAid;
|
|
2289
|
+
}
|
|
2039
2290
|
/**
|
|
2040
2291
|
* 每条进入消息队列的消息都走这里。分两段,代价完全不同:
|
|
2041
2292
|
*
|
|
@@ -2199,7 +2450,7 @@ export class AUNChannel {
|
|
|
2199
2450
|
logger.warn(`${this.logPrefix()} owner.directory.grant: initial pull failed (pending kept): ${error instanceof Error ? error.message : String(error)}`);
|
|
2200
2451
|
}
|
|
2201
2452
|
}
|
|
2202
|
-
buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId,
|
|
2453
|
+
buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, topicStatus) {
|
|
2203
2454
|
if (!groupId)
|
|
2204
2455
|
throw new Error('buildGroupReplyContext requires groupId');
|
|
2205
2456
|
const replyContext = {
|
|
@@ -2217,13 +2468,11 @@ export class AUNChannel {
|
|
|
2217
2468
|
replyContext.metadata = {};
|
|
2218
2469
|
replyContext.metadata.topicName = topicName;
|
|
2219
2470
|
}
|
|
2220
|
-
if (label && threadId)
|
|
2221
|
-
replyContext.metadata.label = label;
|
|
2222
2471
|
if (topicStatus && threadId)
|
|
2223
2472
|
replyContext.metadata.topicStatus = topicStatus;
|
|
2224
2473
|
return replyContext;
|
|
2225
2474
|
}
|
|
2226
|
-
buildPrivateReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, refMessageId,
|
|
2475
|
+
buildPrivateReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, refMessageId, topicStatus) {
|
|
2227
2476
|
const replyContext = {
|
|
2228
2477
|
metadata: { encrypted, chatmode, refMessageId },
|
|
2229
2478
|
delivery: { chatType: 'private' },
|
|
@@ -2235,8 +2484,6 @@ export class AUNChannel {
|
|
|
2235
2484
|
replyContext.replyToMessageId = messageId;
|
|
2236
2485
|
if (topicName && threadId)
|
|
2237
2486
|
replyContext.metadata.topicName = topicName;
|
|
2238
|
-
if (label && threadId)
|
|
2239
|
-
replyContext.metadata.label = label;
|
|
2240
2487
|
if (topicStatus && threadId)
|
|
2241
2488
|
replyContext.metadata.topicStatus = topicStatus;
|
|
2242
2489
|
return replyContext;
|
|
@@ -2359,9 +2606,9 @@ export class AUNChannel {
|
|
|
2359
2606
|
/** 本 agent 曾发出过的卡片 msgId(只增不删,用于区分"过期失效"vs"他人发的卡") */
|
|
2360
2607
|
ownedCardMsgIds = new Set();
|
|
2361
2608
|
ownedCardTopics = new Map();
|
|
2362
|
-
/** requestId → 已投递的卡片 message_id
|
|
2609
|
+
/** requestId → 已投递的卡片 message_id 集合(失效时清理交互映射,保留原消息) */
|
|
2363
2610
|
interactionCardMessageIds = new Map();
|
|
2364
|
-
/**
|
|
2611
|
+
/** 失效可能先于 outbox 卡片投递完成;迟到卡片不得重新启用交互。 */
|
|
2365
2612
|
invalidatedInteractions = new Map();
|
|
2366
2613
|
mentionModeResolver;
|
|
2367
2614
|
/** Agent-level policy controlling whether group slash commands require structured mentions. */
|
|
@@ -2488,13 +2735,11 @@ export class AUNChannel {
|
|
|
2488
2735
|
getGroupInviteDeliveryState(outboxId) {
|
|
2489
2736
|
return outbox.deliveryState(this.config.aid, outboxId);
|
|
2490
2737
|
}
|
|
2491
|
-
async invalidateGroupInviteCard(interactionId,
|
|
2492
|
-
const known = new Set(this.interactionCardMessageIds.get(interactionId) ?? []);
|
|
2738
|
+
async invalidateGroupInviteCard(interactionId, _ownerAid, messageIds) {
|
|
2493
2739
|
await this.invalidateInteraction(interactionId, 'group_invite_review');
|
|
2494
2740
|
// After a daemon restart only the review store knows the delivered cards.
|
|
2495
2741
|
for (const id of messageIds) {
|
|
2496
|
-
|
|
2497
|
-
await this.recallInteractionCard(id, ownerAid, { chatType: 'private' });
|
|
2742
|
+
this.forgetInteractionCard(id, interactionId);
|
|
2498
2743
|
}
|
|
2499
2744
|
}
|
|
2500
2745
|
refreshGroupInviteMembership(groupId) {
|
|
@@ -2673,6 +2918,31 @@ export class AUNChannel {
|
|
|
2673
2918
|
// instance must not mutate the new instance's health or message state.
|
|
2674
2919
|
const isCurrentClient = () => this.client === client
|
|
2675
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
|
+
};
|
|
2676
2946
|
// Register event handlers before connecting
|
|
2677
2947
|
client.on('agentmd.changed', (data) => {
|
|
2678
2948
|
if (!isCurrentClient() || this.intentionalDisconnect || typeof data !== 'string')
|
|
@@ -2701,11 +2971,14 @@ export class AUNChannel {
|
|
|
2701
2971
|
this.serviceRouter.ensureStarted(identity);
|
|
2702
2972
|
this.serviceRouter.reload();
|
|
2703
2973
|
}
|
|
2704
|
-
void refreshAgentDisplayName(aid).then(name => {
|
|
2705
|
-
if (!
|
|
2974
|
+
void refreshAgentDisplayName(aid, { store, aunPath }).then(name => {
|
|
2975
|
+
if (!isCurrentClient())
|
|
2706
2976
|
return;
|
|
2707
|
-
|
|
2708
|
-
|
|
2977
|
+
if (name) {
|
|
2978
|
+
this._selfName = name;
|
|
2979
|
+
this.aidStatsCollector?.setSelfName(this.config.aid, name);
|
|
2980
|
+
}
|
|
2981
|
+
completeControlAgentMd();
|
|
2709
2982
|
});
|
|
2710
2983
|
}
|
|
2711
2984
|
});
|
|
@@ -2906,19 +3179,6 @@ export class AUNChannel {
|
|
|
2906
3179
|
// Service/Gateway 故障不能把控制通道判定为连接失败。
|
|
2907
3180
|
if (this.config.pureIdentity) {
|
|
2908
3181
|
this._selfName = buildControlAgentName(aidName);
|
|
2909
|
-
void ensureControlAgentMd(aidName, {
|
|
2910
|
-
store: this.store ?? undefined,
|
|
2911
|
-
aunPath,
|
|
2912
|
-
cacheRoot: resolveRoot(),
|
|
2913
|
-
})
|
|
2914
|
-
.then(result => {
|
|
2915
|
-
this._selfName = result.name;
|
|
2916
|
-
if (this.aidStatsCollector)
|
|
2917
|
-
this.aidStatsCollector.setSelfName(this.config.aid, result.name);
|
|
2918
|
-
if (result.published)
|
|
2919
|
-
logger.info(`${this.logPrefix()} 控制 AID agent.md 已发布: ${result.name}`);
|
|
2920
|
-
})
|
|
2921
|
-
.catch(error => logger.warn(`${this.logPrefix()} 控制 AID agent.md 补全失败(后台重试): ${error instanceof Error ? error.message : String(error)}`));
|
|
2922
3182
|
}
|
|
2923
3183
|
else {
|
|
2924
3184
|
this._selfName = this.loadSelfName(aidName, aunPath);
|
|
@@ -2928,10 +3188,19 @@ export class AUNChannel {
|
|
|
2928
3188
|
this.connected = true;
|
|
2929
3189
|
this.connectedAt = Date.now();
|
|
2930
3190
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
3191
|
+
completeControlAgentMd();
|
|
2931
3192
|
this.reconcileConfiguredOwnerBinding();
|
|
2932
3193
|
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
2933
3194
|
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
2934
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
|
+
}
|
|
2935
3204
|
void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
|
|
2936
3205
|
logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2937
3206
|
});
|
|
@@ -3337,11 +3606,101 @@ export class AUNChannel {
|
|
|
3337
3606
|
}
|
|
3338
3607
|
}
|
|
3339
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
|
+
}
|
|
3340
3693
|
/** Returns before any ordinary history, observer, attachment or model side effect. */
|
|
3341
|
-
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted) {
|
|
3694
|
+
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted, message) {
|
|
3342
3695
|
const selfAid = this.config.aid;
|
|
3343
3696
|
const value = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : undefined;
|
|
3344
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
|
+
}
|
|
3345
3704
|
const previous = isolatedContactSource(selfAid, fromAid, messageId);
|
|
3346
3705
|
const digest = contactSourceDigest(payload);
|
|
3347
3706
|
if (previous && (previous.notified || !previous.reason || contactIntroductionText(payload) === undefined
|
|
@@ -3349,14 +3708,14 @@ export class AUNChannel {
|
|
|
3349
3708
|
return true;
|
|
3350
3709
|
if (previous && !sameContactBinding(previous.binding, currentContactBinding(selfAid)))
|
|
3351
3710
|
return true;
|
|
3352
|
-
if (previous && !consumeContactIntroductionBudget(selfAid, fromAid))
|
|
3353
|
-
return true;
|
|
3354
3711
|
if (type.startsWith('friend.')) {
|
|
3355
3712
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.grant' });
|
|
3356
3713
|
const binding = verifiedContactBinding(selfAid, view);
|
|
3357
3714
|
if (!binding)
|
|
3358
3715
|
return true;
|
|
3359
3716
|
const result = executeContactGrant(selfAid, fromAid, payload, encrypted, Date.now(), binding);
|
|
3717
|
+
if (result?.status === 'applied')
|
|
3718
|
+
this.scheduleContactReplay();
|
|
3360
3719
|
if (result)
|
|
3361
3720
|
await this.sendContentPayload(fromAid, result, {
|
|
3362
3721
|
contentKind: 'custom', dedupeKey: `friend-result:${result.owner_aid}:${result.relation_version}:${result.type}:${result.grant_id}:${result.status}:${result.error_code ?? ''}`,
|
|
@@ -3372,14 +3731,25 @@ export class AUNChannel {
|
|
|
3372
3731
|
return true; // Retired App protocol; never create legacy pending.
|
|
3373
3732
|
if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
|
|
3374
3733
|
return false;
|
|
3375
|
-
//
|
|
3376
|
-
await ownerResolver.refresh(selfAid, { maxAgeMs:
|
|
3734
|
+
// A redelivered isolated source can only reenter through the durable replay worker.
|
|
3735
|
+
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.inbound' });
|
|
3377
3736
|
await this.getOwnerDirectoryRuntime();
|
|
3378
3737
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3379
3738
|
const decision = evaluateAppContactAdmission(selfAid, fromAid);
|
|
3380
3739
|
logger.debug(`${this.logPrefix()} Contact admission: mid=${messageId} from=${fromAid} allow=${decision.allow} reason=${decision.reason} elapsedMs=${Math.max(0, Date.now() - receivedAt)}`);
|
|
3381
|
-
if (decision.allow && !previous)
|
|
3382
|
-
|
|
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
|
+
}
|
|
3383
3753
|
const introduction = contactIntroductionText(payload);
|
|
3384
3754
|
const binding = currentContactBinding(selfAid);
|
|
3385
3755
|
const reason = previous?.reason ?? decision.reason;
|
|
@@ -3387,32 +3757,46 @@ export class AUNChannel {
|
|
|
3387
3757
|
return true;
|
|
3388
3758
|
let source = previous ?? { at: receivedAt, digest, binding,
|
|
3389
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
|
+
}
|
|
3390
3765
|
// Write the tombstone before budgets, receipt capacity checks or any delivery.
|
|
3391
3766
|
if (!previous)
|
|
3392
3767
|
source = saveIsolatedContactSource(selfAid, fromAid, messageId, source);
|
|
3393
3768
|
if (source.notified || source.digest !== digest || !sameContactBinding(source.binding ?? {}, binding))
|
|
3394
3769
|
return true;
|
|
3395
3770
|
const eventReason = source.reason;
|
|
3396
|
-
if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')
|
|
3397
|
-
|
|
3398
|
-
const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, eventReason);
|
|
3399
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
3400
|
-
if (remainingTtl <= 0)
|
|
3401
|
-
return true;
|
|
3402
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3403
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1]',
|
|
3404
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
3405
|
-
ttl: remainingTtl,
|
|
3406
|
-
});
|
|
3407
|
-
if (sent.messageId || sent.queued)
|
|
3408
|
-
saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
|
|
3409
|
-
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);
|
|
3410
3773
|
}
|
|
3411
3774
|
else {
|
|
3412
3775
|
logger.info(`${this.logPrefix()} Contact message isolated: mid=${messageId} reason=${decision.reason}`);
|
|
3413
3776
|
}
|
|
3414
3777
|
return true;
|
|
3415
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
|
+
}
|
|
3416
3800
|
/** friend.invite.v1 never reaches the model, ordinary history, attachments or observers. */
|
|
3417
3801
|
async handleFriendInvite(fromAid, payload, messageId, receivedAt, encrypted, seq) {
|
|
3418
3802
|
const selfAid = this.config.aid;
|
|
@@ -3444,6 +3828,17 @@ export class AUNChannel {
|
|
|
3444
3828
|
await this.sendFriendInviteResult(invite, decideFriendInvite(selfAid, binding, invite, 'expired'), messageId);
|
|
3445
3829
|
return;
|
|
3446
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
|
+
}
|
|
3447
3842
|
await this.getOwnerDirectoryRuntime();
|
|
3448
3843
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3449
3844
|
const verdict = await this.judgeFriendInvite(selfAid, fromAid);
|
|
@@ -3464,21 +3859,50 @@ export class AUNChannel {
|
|
|
3464
3859
|
return;
|
|
3465
3860
|
}
|
|
3466
3861
|
const reason = verdict.reason === 'scope_extension' ? 'scope_extension' : 'not_in_contacts';
|
|
3467
|
-
|
|
3468
|
-
...buildContactRequest(binding, fromAid, messageId, receivedAt, invite.introduction, reason, `invite:${invite.invite_id}`),
|
|
3469
|
-
invite: { type: FRIEND_INVITE_TYPE, schema_version: 1, ...invite },
|
|
3470
|
-
};
|
|
3471
|
-
const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, invite.expires_at_ms - Date.now());
|
|
3472
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3473
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 invite]',
|
|
3474
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
|
|
3475
|
-
});
|
|
3476
|
-
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);
|
|
3477
3863
|
}
|
|
3478
3864
|
catch (error) {
|
|
3479
3865
|
logger.warn(`${this.logPrefix()} Friend invite isolated: code=CONTACT_STATE_UNAVAILABLE invite=${invite.invite_id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3480
3866
|
}
|
|
3481
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
|
+
}
|
|
3482
3906
|
/**
|
|
3483
3907
|
* Friend invites use the same app-v1 decision as ordinary private messages.
|
|
3484
3908
|
*/
|
|
@@ -3508,11 +3932,13 @@ export class AUNChannel {
|
|
|
3508
3932
|
if (sent.messageId || sent.queued)
|
|
3509
3933
|
markFriendInviteWelcomed(this.config.aid, binding, invite.invite_id);
|
|
3510
3934
|
}
|
|
3511
|
-
async handleIncomingPrivateMessage(data) {
|
|
3935
|
+
async handleIncomingPrivateMessage(data, contactDelivery) {
|
|
3512
3936
|
if (!data || typeof data !== 'object')
|
|
3513
3937
|
return;
|
|
3514
3938
|
const msg = data;
|
|
3515
|
-
|
|
3939
|
+
if (contactDelivery)
|
|
3940
|
+
contactDelivery.validate();
|
|
3941
|
+
const receivedAt = contactDelivery?.receivedAt ?? Date.now();
|
|
3516
3942
|
const receivedAtMono = performance.now();
|
|
3517
3943
|
// Validate the authenticated envelope before any payload extraction or
|
|
3518
3944
|
// command parsing. Retransmits may carry a new seq, but the application
|
|
@@ -3582,6 +4008,34 @@ export class AUNChannel {
|
|
|
3582
4008
|
return;
|
|
3583
4009
|
const protectedHeaders = verifiedProtectedHeaders(msg, env);
|
|
3584
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 };
|
|
4019
|
+
// Credential answers must be consumed before contact/request persistence,
|
|
4020
|
+
// observer forwarding or generic message logging. Card binding is server-owned.
|
|
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
|
+
}
|
|
4030
|
+
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
4031
|
+
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
4032
|
+
if (!card || card.sensitive) {
|
|
4033
|
+
if (appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
4034
|
+
return;
|
|
4035
|
+
this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' }, !!env.encrypted);
|
|
4036
|
+
return;
|
|
4037
|
+
}
|
|
4038
|
+
}
|
|
3585
4039
|
// friend.invite.v1(App 主动加好友)不依赖 app-v1 灰度:按 Owner 准入策略已放行的申请人
|
|
3586
4040
|
// 由本 Agent 直接回 accepted 并发欢迎语;其余转交 Owner。不进 Agent、不转 observer。
|
|
3587
4041
|
if (!this.config.pureIdentity && isFriendInvitePayload(payload)) {
|
|
@@ -3590,11 +4044,17 @@ export class AUNChannel {
|
|
|
3590
4044
|
await this.handleFriendInvite(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
|
|
3591
4045
|
return;
|
|
3592
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
|
+
}
|
|
3593
4053
|
const contactControl = appOwned && isContactControlPayload(payload);
|
|
3594
4054
|
if (appOwned) {
|
|
3595
4055
|
let handled;
|
|
3596
4056
|
try {
|
|
3597
|
-
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));
|
|
3598
4058
|
}
|
|
3599
4059
|
catch {
|
|
3600
4060
|
// Storage/lock/capacity/conflict failures remain isolated; log metadata only.
|
|
@@ -3611,7 +4071,7 @@ export class AUNChannel {
|
|
|
3611
4071
|
}
|
|
3612
4072
|
if (handled)
|
|
3613
4073
|
return;
|
|
3614
|
-
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4074
|
+
if (!contactDelivery && !this.claimInboundMessage('private', messageId, seq))
|
|
3615
4075
|
return;
|
|
3616
4076
|
if (contactControl)
|
|
3617
4077
|
this.rememberContactControlRequest(fromAid, payload, messageId, menuSenderDeviceId(msg.sender_device_id));
|
|
@@ -3651,7 +4111,7 @@ export class AUNChannel {
|
|
|
3651
4111
|
? payload._evolcore_causation_ref
|
|
3652
4112
|
: undefined;
|
|
3653
4113
|
const logDescriptor = classifyAunPayloadForLog(payload);
|
|
3654
|
-
const text = this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' });
|
|
4114
|
+
const text = this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' }, !!env.encrypted);
|
|
3655
4115
|
const threadId = typeof payload === 'object' && payload !== null ? payload.thread_id : undefined;
|
|
3656
4116
|
const refMessageId = typeof payload === 'object' && payload !== null && typeof payload.ref_message_id === 'string'
|
|
3657
4117
|
? payload.ref_message_id
|
|
@@ -3684,7 +4144,8 @@ export class AUNChannel {
|
|
|
3684
4144
|
// forwardInbound 内部排除 self-echo 与 from-owner。
|
|
3685
4145
|
// 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
|
|
3686
4146
|
// (即便日后 from-owner 排除规则调整,也不会泄漏)。
|
|
3687
|
-
if (!contactControl &&
|
|
4147
|
+
if (!contactDelivery && !contactControl && inboundType !== 'action_card_reply'
|
|
4148
|
+
&& (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
|
|
3688
4149
|
void this.forwardInbound(msg);
|
|
3689
4150
|
}
|
|
3690
4151
|
if (inboundType === 'observer.inject.status' || inboundType === 'observer.inject.ack') {
|
|
@@ -3712,16 +4173,16 @@ export class AUNChannel {
|
|
|
3712
4173
|
mentions.push({ aid: this._aid });
|
|
3713
4174
|
}
|
|
3714
4175
|
// Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
|
|
3715
|
-
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' }));
|
|
3716
4177
|
// 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
|
|
3717
4178
|
// device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
|
|
3718
4179
|
const chatId = fromAid;
|
|
3719
4180
|
// 解析对端身份(30天缓存)
|
|
3720
4181
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
3721
|
-
const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
3722
|
-
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));
|
|
3723
4184
|
const shortAid = this.getShortAid(fromAid);
|
|
3724
|
-
const displayName = peerIdentity.name
|
|
4185
|
+
const displayName = this.inboundDisplayName(fromAid, peerIdentity.name, shortAid);
|
|
3725
4186
|
// 详细 dispatch 决策日志:记录消息为何被路由到 agent
|
|
3726
4187
|
const p2pPayloadType = (payload && typeof payload === 'object' && typeof payload.type === 'string')
|
|
3727
4188
|
? payload.type
|
|
@@ -3826,12 +4287,18 @@ export class AUNChannel {
|
|
|
3826
4287
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
|
|
3827
4288
|
const isSystemP2P = p2pPayloadType === 'event';
|
|
3828
4289
|
this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
|
|
3829
|
-
const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId,
|
|
3830
|
-
this.dispatchMessage({
|
|
4290
|
+
const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicStatus(payload));
|
|
4291
|
+
const dispatched = this.dispatchMessage({
|
|
4292
|
+
contactDelivery,
|
|
3831
4293
|
channelId: chatId,
|
|
3832
4294
|
userId: fromAid,
|
|
3833
|
-
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,
|
|
3834
4298
|
chatType: 'private',
|
|
4299
|
+
...(this.config.pureIdentity && p2pPayloadType === 'text' ? {
|
|
4300
|
+
peerDeviceId: menuSenderDeviceId(msg.sender_device_id),
|
|
4301
|
+
} : {}),
|
|
3835
4302
|
messageId,
|
|
3836
4303
|
receivedAt,
|
|
3837
4304
|
createdAt: typeof msg.created_at === 'number' ? msg.created_at : undefined,
|
|
@@ -3855,6 +4322,8 @@ export class AUNChannel {
|
|
|
3855
4322
|
payloadSummary: logDescriptor.payloadSummary,
|
|
3856
4323
|
messageLogContent: logDescriptor.msgType === 'text' ? finalText : logDescriptor.content,
|
|
3857
4324
|
});
|
|
4325
|
+
if (contactDelivery)
|
|
4326
|
+
await dispatched;
|
|
3858
4327
|
}
|
|
3859
4328
|
async handleIncomingGroupMessage(data) {
|
|
3860
4329
|
if (!data || typeof data !== 'object')
|
|
@@ -3874,6 +4343,14 @@ export class AUNChannel {
|
|
|
3874
4343
|
const groupId = env.group_id ?? '';
|
|
3875
4344
|
const senderAid = env.from ?? '';
|
|
3876
4345
|
const payload = msg.payload ?? '';
|
|
4346
|
+
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
4347
|
+
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
4348
|
+
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
4349
|
+
if (!card || card.sensitive) {
|
|
4350
|
+
this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId }, !!env.encrypted);
|
|
4351
|
+
return;
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
3877
4354
|
const responseRecord = getAunRequestRegistry().resolveIncoming({
|
|
3878
4355
|
selfAid: this._aid || this.config.aid,
|
|
3879
4356
|
fromAid: senderAid,
|
|
@@ -3903,7 +4380,7 @@ export class AUNChannel {
|
|
|
3903
4380
|
return;
|
|
3904
4381
|
const payloadMentionAids = mentionEntryAids(payloadMentionEntries);
|
|
3905
4382
|
const logDescriptor = classifyAunPayloadForLog(payload);
|
|
3906
|
-
const text = this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId });
|
|
4383
|
+
const text = this.extractTextPayload(payload, groupId, senderAid, { chatType: 'group', groupId }, !!env.encrypted);
|
|
3907
4384
|
const threadId = typeof payload === 'object' && payload !== null ? payload.thread_id : undefined;
|
|
3908
4385
|
const topicName = (typeof payload === 'object' && payload !== null)
|
|
3909
4386
|
? this.sanitizeTopicName(payload.topicName)
|
|
@@ -3915,8 +4392,10 @@ export class AUNChannel {
|
|
|
3915
4392
|
}
|
|
3916
4393
|
// Observer forward (inbound):群聊消息在所有过滤之前转发原始明文 payload。
|
|
3917
4394
|
// forwardInbound 内部排除 self-echo 与 from-owner。
|
|
3918
|
-
|
|
3919
|
-
|
|
4395
|
+
if (inboundType !== 'action_card_reply') {
|
|
4396
|
+
void this.forwardInbound(msg);
|
|
4397
|
+
logger.debug(`${this.logPrefix()}[DIAG-GRP] full_msg=${JSON.stringify(msg).substring(0, 500)}`);
|
|
4398
|
+
}
|
|
3920
4399
|
if (!groupId || !senderAid) {
|
|
3921
4400
|
logger.debug(`${this.logPrefix()} Group dropped: missing groupId or senderAid (mid=${messageId})`);
|
|
3922
4401
|
return;
|
|
@@ -3944,11 +4423,11 @@ export class AUNChannel {
|
|
|
3944
4423
|
const msgChatmodeFast = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
3945
4424
|
const peerInfo = this.peerInfoCached(senderAid);
|
|
3946
4425
|
const shortAid = this.getShortAid(senderAid);
|
|
3947
|
-
const displayName = peerInfo?.name
|
|
4426
|
+
const displayName = this.inboundDisplayName(senderAid, peerInfo?.name, shortAid);
|
|
3948
4427
|
const createdAt = data.created_at;
|
|
3949
4428
|
if (!peerInfo)
|
|
3950
4429
|
this.prefetchPeerInfo(senderAid);
|
|
3951
|
-
this.handleEcho({
|
|
4430
|
+
void this.handleEcho({
|
|
3952
4431
|
channelId: groupId,
|
|
3953
4432
|
userId: senderAid,
|
|
3954
4433
|
text,
|
|
@@ -3957,9 +4436,9 @@ export class AUNChannel {
|
|
|
3957
4436
|
peerName: displayName,
|
|
3958
4437
|
peerType: peerInfo?.type || 'unknown',
|
|
3959
4438
|
seq,
|
|
3960
|
-
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId,
|
|
4439
|
+
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId, readTopicStatus(payload)),
|
|
3961
4440
|
createdAt,
|
|
3962
|
-
});
|
|
4441
|
+
}).catch(() => { });
|
|
3963
4442
|
return;
|
|
3964
4443
|
}
|
|
3965
4444
|
}
|
|
@@ -4035,7 +4514,7 @@ export class AUNChannel {
|
|
|
4035
4514
|
extra: `from=${senderAid} mid=${messageId} chat=group self=${this._aid || 'unknown'} conn_uptime=${this.connectedAt ? Math.round((echoReceiveTs - this.connectedAt) / 1000) + 's' : 'unknown'}${echoInboundLegLabel(echoCreatedAt, receivedAt)}`,
|
|
4036
4515
|
})}`;
|
|
4037
4516
|
const msgChatmodeEcho = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
4038
|
-
const groupProbeContext = this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId,
|
|
4517
|
+
const groupProbeContext = this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmodeEcho, topicName, groupId, readTopicStatus(payload));
|
|
4039
4518
|
this.registerProbe(messageId, echoKindGroup ?? 'ask', echoText, groupId, groupProbeContext, echoReceiveTs);
|
|
4040
4519
|
// 继续走正常 Agent 流程(下面的代码会 dispatch)
|
|
4041
4520
|
}
|
|
@@ -4092,7 +4571,7 @@ export class AUNChannel {
|
|
|
4092
4571
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
4093
4572
|
const peerIdentity = await PeerIdentityCache.resolve('aun', senderAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
4094
4573
|
const shortAid = this.getShortAid(senderAid);
|
|
4095
|
-
const displayName = peerIdentity.name
|
|
4574
|
+
const displayName = this.inboundDisplayName(senderAid, peerIdentity.name, shortAid);
|
|
4096
4575
|
// 详细 dispatch 决策日志:记录消息为何被路由到 agent
|
|
4097
4576
|
const payloadType = (payload && typeof payload === 'object') ? payload.type ?? '' : '';
|
|
4098
4577
|
const textMentionSelf = this._aid ? this.hasExplicitMention(text, this._aid) : false;
|
|
@@ -4126,7 +4605,7 @@ export class AUNChannel {
|
|
|
4126
4605
|
const senderGroupRole = memberRoles?.get(String(senderAid).toLowerCase());
|
|
4127
4606
|
const myGroupRole = memberRoles?.get(String(this._aid || '').toLowerCase());
|
|
4128
4607
|
const groupRoles = memberRoles ? Object.fromEntries(memberRoles) : undefined;
|
|
4129
|
-
//
|
|
4608
|
+
// 「关系角色」:发言人本人的关系 → 联系人 → visitor。
|
|
4130
4609
|
const speakerRelation = resolveSenderRelationRole({
|
|
4131
4610
|
selfAid: this.config.aid,
|
|
4132
4611
|
channelKey: `aun#${this.config.aid}#main`,
|
|
@@ -4163,7 +4642,7 @@ export class AUNChannel {
|
|
|
4163
4642
|
isMentioned: isOwnHandoff || mentionedSelf || mentionedAll,
|
|
4164
4643
|
source: isOwnHandoff ? 'handoff' : undefined,
|
|
4165
4644
|
encrypted: msgEncrypted,
|
|
4166
|
-
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmode, topicName, groupId,
|
|
4645
|
+
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncrypted, messageId, msgChatmode, topicName, groupId, readTopicStatus(payload)),
|
|
4167
4646
|
mentionMode: serverMentionMode,
|
|
4168
4647
|
images: inboundImages.length > 0 ? inboundImages : undefined,
|
|
4169
4648
|
msgType: logDescriptor.msgType,
|
|
@@ -4198,12 +4677,24 @@ export class AUNChannel {
|
|
|
4198
4677
|
const hasEvolCoreTracePrivate = /\[EvolCore\.(receive|reply|agent)\]/.test(event.text);
|
|
4199
4678
|
// echo:不进大模型,直接回包
|
|
4200
4679
|
if (echoKindPrivate === 'echo' && !hasEvolCoreTracePrivate) {
|
|
4201
|
-
|
|
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(() => { });
|
|
4202
4688
|
return;
|
|
4203
4689
|
}
|
|
4204
4690
|
// 回声炸弹:已被任何 EvolCore 节点 trace 过的探针,直接丢弃
|
|
4205
4691
|
if (echoKindPrivate !== null && hasEvolCoreTracePrivate) {
|
|
4206
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
|
+
}
|
|
4207
4698
|
return;
|
|
4208
4699
|
}
|
|
4209
4700
|
// echo.ask / echo.ecdiag:追加 trace 后继续交给 agent 处理
|
|
@@ -4238,10 +4729,11 @@ export class AUNChannel {
|
|
|
4238
4729
|
};
|
|
4239
4730
|
const handler = this.messageHandler;
|
|
4240
4731
|
const inbound = {
|
|
4732
|
+
contactDelivery: trustedContactInboundDelivery(event.contactDelivery),
|
|
4241
4733
|
channelId: event.channelId || '',
|
|
4242
4734
|
channelType: 'aun',
|
|
4243
4735
|
content: event.text || '',
|
|
4244
|
-
selfAID: this._aid,
|
|
4736
|
+
selfAID: this._aid || this.config.aid,
|
|
4245
4737
|
groupId: event.groupId,
|
|
4246
4738
|
chatType: event.chatType,
|
|
4247
4739
|
peerId: event.userId || event.channelId || '',
|
|
@@ -4281,11 +4773,15 @@ export class AUNChannel {
|
|
|
4281
4773
|
// 落地先于这一轮处理:ECK 的 hasOwnerDirectory 是同步 stat,名录没落盘时
|
|
4282
4774
|
// 本轮上下文就会丢掉整段名录。这段最多等 OWNER_DIRECTORY_APPLY_WAIT_MS,
|
|
4283
4775
|
// 且只等本地 I/O;网络拉取仍在 processPendingDirectoryUpdate 里后台跑。
|
|
4284
|
-
|
|
4776
|
+
const dispatched = this.settleOwnerDirectoryBeforeTurn()
|
|
4285
4777
|
.then(() => handler(inbound))
|
|
4286
4778
|
.catch(err => {
|
|
4287
4779
|
logger.error(`${this.logPrefix()} Message handler error:`, err);
|
|
4780
|
+
if (event.contactDelivery)
|
|
4781
|
+
throw err;
|
|
4288
4782
|
});
|
|
4783
|
+
if (event.contactDelivery)
|
|
4784
|
+
return dispatched;
|
|
4289
4785
|
}
|
|
4290
4786
|
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery) {
|
|
4291
4787
|
try {
|
|
@@ -4818,18 +5314,21 @@ export class AUNChannel {
|
|
|
4818
5314
|
: { chatType: 'private' };
|
|
4819
5315
|
const context = {
|
|
4820
5316
|
threadId: event.threadId ?? event.replyContext?.threadId,
|
|
4821
|
-
metadata: event.
|
|
5317
|
+
metadata: event.contactDelivery
|
|
5318
|
+
? { ...event.replyContext?.metadata, operationId: `contact-echo-${event.contactDelivery.key}` }
|
|
5319
|
+
: event.replyContext?.metadata,
|
|
4822
5320
|
delivery: authenticatedDelivery,
|
|
4823
5321
|
};
|
|
4824
5322
|
const sendStart = Date.now();
|
|
4825
5323
|
this.isEchoSending = true;
|
|
4826
|
-
this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
5324
|
+
return this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
4827
5325
|
this.isEchoSending = false;
|
|
4828
5326
|
const elapsed = Date.now() - sendStart;
|
|
4829
5327
|
logger.info(`${this.logPrefix()} Echo reply sent to ${replyTarget} (${elapsed}ms)`);
|
|
4830
5328
|
}).catch(e => {
|
|
4831
5329
|
this.isEchoSending = false;
|
|
4832
5330
|
logger.error(`${this.logPrefix()} Echo reply failed: ${e}`);
|
|
5331
|
+
throw e;
|
|
4833
5332
|
});
|
|
4834
5333
|
}
|
|
4835
5334
|
/**
|
|
@@ -5367,6 +5866,7 @@ export class AUNChannel {
|
|
|
5367
5866
|
* 应答支不经过这里——那由 AunRequestRegistry 在消息层更早匹配。
|
|
5368
5867
|
*/
|
|
5369
5868
|
async handleServiceMessage(input) {
|
|
5869
|
+
const startedAt = Date.now();
|
|
5370
5870
|
const router = this.ensureServiceRouter();
|
|
5371
5871
|
const payload = input.payload;
|
|
5372
5872
|
const rawType = typeof payload.type === 'string' ? payload.type : '';
|
|
@@ -5393,7 +5893,11 @@ export class AUNChannel {
|
|
|
5393
5893
|
const reply = await router.handleRequest(message, { admission });
|
|
5394
5894
|
if (!reply.shouldSend)
|
|
5395
5895
|
return;
|
|
5896
|
+
const handledAt = Date.now();
|
|
5396
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
|
+
}
|
|
5397
5901
|
}
|
|
5398
5902
|
/** 回复:点对点、带 service 标记位,不带 threadId/topicName/chatmode。 */
|
|
5399
5903
|
async sendServiceReply(toAid, replyToMessageId, encrypted, reply) {
|
|
@@ -5411,6 +5915,7 @@ export class AUNChannel {
|
|
|
5411
5915
|
}
|
|
5412
5916
|
onMessage(handler) {
|
|
5413
5917
|
this.messageHandler = handler;
|
|
5918
|
+
this.scheduleContactReplay();
|
|
5414
5919
|
}
|
|
5415
5920
|
setMentionModeResolver(resolver) {
|
|
5416
5921
|
this.mentionModeResolver = resolver;
|
|
@@ -5692,44 +6197,21 @@ export class AUNChannel {
|
|
|
5692
6197
|
const timer = setTimeout(() => this.invalidatedInteractions.delete(interactionId), 24 * 60 * 60 * 1000);
|
|
5693
6198
|
timer.unref?.();
|
|
5694
6199
|
}
|
|
5695
|
-
async recallInteractionCard(messageId, channelId, delivery) {
|
|
5696
|
-
if (!this.client || !this.connected)
|
|
5697
|
-
return false;
|
|
5698
|
-
try {
|
|
5699
|
-
if (!channelId || !delivery) {
|
|
5700
|
-
logger.warn(`${this.logPrefix()} Cannot recall interaction card without trusted delivery route: mid=${messageId}`);
|
|
5701
|
-
return false;
|
|
5702
|
-
}
|
|
5703
|
-
const isGroup = delivery.chatType === 'group';
|
|
5704
|
-
const method = isGroup ? 'group.recall' : 'message.recall';
|
|
5705
|
-
const params = isGroup
|
|
5706
|
-
? { group_id: delivery.groupId, message_ids: [messageId] }
|
|
5707
|
-
: { message_ids: [messageId] };
|
|
5708
|
-
await this.callAndTrace(method, params, { silentError: true });
|
|
5709
|
-
return true;
|
|
5710
|
-
}
|
|
5711
|
-
catch (error) {
|
|
5712
|
-
logger.debug(`${this.logPrefix()} Failed to recall invalidated interaction card mid=${messageId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
5713
|
-
return false;
|
|
5714
|
-
}
|
|
5715
|
-
}
|
|
5716
6200
|
/**
|
|
5717
|
-
*
|
|
5718
|
-
*
|
|
5719
|
-
* 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.
|
|
5720
6205
|
*/
|
|
5721
6206
|
async invalidateInteraction(interactionId, reason = 'cancelled') {
|
|
5722
6207
|
this.rememberInvalidatedInteraction(interactionId, reason);
|
|
5723
6208
|
const removedQueued = outbox.removeInteractionCards(this.config.aid, interactionId);
|
|
5724
6209
|
if (removedQueued > 0) {
|
|
5725
|
-
logger.info(`${this.logPrefix()} Removed ${removedQueued}
|
|
6210
|
+
logger.info(`${this.logPrefix()} Removed ${removedQueued} invalidated interaction card(s) from durable outbox: request=${interactionId}`);
|
|
5726
6211
|
}
|
|
5727
6212
|
const messageIds = [...(this.interactionCardMessageIds.get(interactionId) ?? [])];
|
|
5728
6213
|
for (const messageId of messageIds) {
|
|
5729
|
-
const card = this.cardMessageIdMap.get(messageId);
|
|
5730
|
-
const channelId = card?.channelId;
|
|
5731
6214
|
this.forgetInteractionCard(messageId, interactionId);
|
|
5732
|
-
await this.recallInteractionCard(messageId, channelId, card?.delivery);
|
|
5733
6215
|
}
|
|
5734
6216
|
}
|
|
5735
6217
|
restoreInteraction(envelope, interaction, receipt) {
|
|
@@ -5764,6 +6246,7 @@ export class AUNChannel {
|
|
|
5764
6246
|
this.registerCardPostSend(messageId, {
|
|
5765
6247
|
type: 'register_interaction_card', requestId: interaction.id,
|
|
5766
6248
|
isCommandCard: false, initiatorAid: interaction.initiatorId,
|
|
6249
|
+
sensitive: interaction.sensitive,
|
|
5767
6250
|
expiresAt: interaction.expiresAt, delivery,
|
|
5768
6251
|
}, channelId, delivery, envelope.replyContext);
|
|
5769
6252
|
}
|
|
@@ -5827,6 +6310,7 @@ export class AUNChannel {
|
|
|
5827
6310
|
channelId,
|
|
5828
6311
|
delivery: delivery ?? action.delivery,
|
|
5829
6312
|
replyContext: callbackContext,
|
|
6313
|
+
sensitive: action.sensitive,
|
|
5830
6314
|
});
|
|
5831
6315
|
this.ownedCardMsgIds.add(messageId);
|
|
5832
6316
|
if (typeof replyContext?.threadId === 'string') {
|
|
@@ -5859,13 +6343,16 @@ export class AUNChannel {
|
|
|
5859
6343
|
ownedTimer.unref?.();
|
|
5860
6344
|
const invalidationReason = this.invalidatedInteractions.get(action.requestId);
|
|
5861
6345
|
if (invalidationReason) {
|
|
5862
|
-
this.
|
|
5863
|
-
void this.recallInteractionCard(messageId, channelId, delivery ?? action.delivery);
|
|
6346
|
+
this.forgetInteractionCard(messageId, action.requestId);
|
|
5864
6347
|
}
|
|
5865
6348
|
}
|
|
5866
6349
|
runPostSend(entry, messageId) {
|
|
5867
6350
|
if (!entry.postSend)
|
|
5868
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
|
+
}
|
|
5869
6356
|
if (entry.postSend.type === 'register_interaction_card') {
|
|
5870
6357
|
this.registerCardPostSend(messageId, entry.postSend, entry.channelId, entry.delivery, entry.context);
|
|
5871
6358
|
if (entry.postSend.requestId.startsWith('gir-'))
|
|
@@ -5886,66 +6373,8 @@ export class AUNChannel {
|
|
|
5886
6373
|
const target = normalize(channelId);
|
|
5887
6374
|
return !!self && !!target && self === target;
|
|
5888
6375
|
}
|
|
5889
|
-
appContactOutboundBlock(channelId, delivery, payload, params) {
|
|
5890
|
-
// 服务回复是对一次已到达请求的应答,不是主动联系;且拒绝信息本身必须能送达,
|
|
5891
|
-
// 否则调用方只会看到超时。
|
|
5892
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5893
|
-
return undefined;
|
|
5894
|
-
// 跨话题自派:收件人是本端,不是跨主体通讯,不适用联系人准入(同 aun-ipc-sender)。
|
|
5895
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5896
|
-
return undefined;
|
|
5897
|
-
if (delivery.chatType === 'group' || this.config.pureIdentity
|
|
5898
|
-
|| this.hasContactControlPermit(channelId, payload, params))
|
|
5899
|
-
return undefined;
|
|
5900
|
-
const decision = evaluateAppContactAdmission(this.config.aid, channelId);
|
|
5901
|
-
if (params?.encrypt === true && params?.rawPayload === true && parseFriendInvite(payload, this.config.aid, channelId)
|
|
5902
|
-
&& decision.reason === 'not_in_contacts')
|
|
5903
|
-
return undefined;
|
|
5904
|
-
if (decision.allow)
|
|
5905
|
-
return undefined;
|
|
5906
|
-
return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
|
|
5907
|
-
code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE' : 'CONTACT_DENIED',
|
|
5908
|
-
error: `联系人准入未通过:${decision.reason}` };
|
|
5909
|
-
}
|
|
5910
|
-
async prepareAppContactOutbound(channelId, delivery, payload, params) {
|
|
5911
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5912
|
-
return undefined;
|
|
5913
|
-
// 跨话题自派:收件人是本端,连通告归属刷新这一跳都不需要。
|
|
5914
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5915
|
-
return undefined;
|
|
5916
|
-
if (delivery.chatType === 'private' && !this.config.pureIdentity
|
|
5917
|
-
&& !this.hasContactControlPermit(channelId, payload, params)
|
|
5918
|
-
&& !this.acceptsVerifiedOwnership(channelId, payload, params)) {
|
|
5919
|
-
await ownerResolver.refresh(this.config.aid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
5920
|
-
}
|
|
5921
|
-
return this.appContactOutboundBlock(channelId, delivery, payload, params);
|
|
5922
|
-
}
|
|
5923
|
-
/**
|
|
5924
|
-
* A caller that already holds the consensus may skip the refresh round-trip.
|
|
5925
|
-
*
|
|
5926
|
-
* Only lifecycle notices qualify, and only toward their own Owner. Shutdown is
|
|
5927
|
-
* the reason this exists: the offline notice runs while the daemon is tearing
|
|
5928
|
-
* down, so a network refresh would outlive the AUN connection it needs.
|
|
5929
|
-
* Admission itself is unchanged — the block below still demands a live
|
|
5930
|
-
* consensus in the resolver cache, so this skips the check of the cache's
|
|
5931
|
-
* freshness, never the requirement that a consensus exists.
|
|
5932
|
-
*/
|
|
5933
|
-
acceptsVerifiedOwnership(channelId, payload, params) {
|
|
5934
|
-
if (params?.ownershipVerified !== true)
|
|
5935
|
-
return false;
|
|
5936
|
-
const notice = payload;
|
|
5937
|
-
if (!notice || notice.type !== 'notice'
|
|
5938
|
-
|| (notice.subtype !== 'agent.online' && notice.subtype !== 'agent.offline'))
|
|
5939
|
-
return false;
|
|
5940
|
-
// Even if the flag ever leaked, it cannot widen admission: the target must be
|
|
5941
|
-
// the Owner the live consensus names, which admission allows unconditionally.
|
|
5942
|
-
return currentContactBinding(this.config.aid)?.owner_aid === channelId;
|
|
5943
|
-
}
|
|
5944
6376
|
async sendAunPayload(channelId, payload, context, label) {
|
|
5945
6377
|
const delivery = this.requireDelivery(channelId, context);
|
|
5946
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, payload);
|
|
5947
|
-
if (blocked)
|
|
5948
|
-
return { ok: false, ...blocked };
|
|
5949
6378
|
let normalizedPayload;
|
|
5950
6379
|
try {
|
|
5951
6380
|
normalizedPayload = this.normalizeAunPayloadMentions(payload);
|
|
@@ -5979,7 +6408,7 @@ export class AUNChannel {
|
|
|
5979
6408
|
if (payloadWithCausationRef.thread_id === '')
|
|
5980
6409
|
delete payloadWithCausationRef.thread_id;
|
|
5981
6410
|
// Truncate payload if too large (AUN SDK limit: 1MB)
|
|
5982
|
-
const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
|
|
6411
|
+
const friendPayload = (typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload);
|
|
5983
6412
|
const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
5984
6413
|
if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
|
|
5985
6414
|
|| (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
|
|
@@ -6075,7 +6504,7 @@ export class AUNChannel {
|
|
|
6075
6504
|
};
|
|
6076
6505
|
}
|
|
6077
6506
|
recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
|
|
6078
|
-
if (typeof payload.type === 'string' && payload.type.startsWith('friend.')) {
|
|
6507
|
+
if ((typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload)) {
|
|
6079
6508
|
logger.info(`${this.logPrefix()} Contact control transport accepted: type=${payload.type} mid=${messageId}`);
|
|
6080
6509
|
return;
|
|
6081
6510
|
}
|
|
@@ -6465,49 +6894,6 @@ export class AUNChannel {
|
|
|
6465
6894
|
this.sentCount.set(turnKey, seqInTurn);
|
|
6466
6895
|
return seqInTurn;
|
|
6467
6896
|
}
|
|
6468
|
-
/** An unadmitted outbound text becomes an Owner request, never a send to the peer. */
|
|
6469
|
-
async requestOutboundContact(args) {
|
|
6470
|
-
const selfAid = this.config.aid;
|
|
6471
|
-
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
6472
|
-
const binding = currentContactBinding(selfAid);
|
|
6473
|
-
if (!binding) {
|
|
6474
|
-
return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
|
|
6475
|
-
}
|
|
6476
|
-
const decision = evaluateAppContactAdmission(selfAid, args.to);
|
|
6477
|
-
if (decision.allow || (decision.reason !== 'not_in_contacts' && decision.reason !== 'scope_extension')) {
|
|
6478
|
-
return { ok: false, code: 'CONTACT_DENIED', error: `联系人状态不允许提交申请:${decision.reason};原消息未发送` };
|
|
6479
|
-
}
|
|
6480
|
-
const text = contactIntroductionText(args.payload);
|
|
6481
|
-
if (text === undefined) {
|
|
6482
|
-
return { ok: false, code: 'CONTACT_DENIED', error: '只有纯文本可以向本端 Owner 提交联系申请;原消息未发送' };
|
|
6483
|
-
}
|
|
6484
|
-
if (!consumeContactIntroductionBudget(selfAid, `outbound:${args.to}`)) {
|
|
6485
|
-
return { ok: false, code: 'CONTACT_INTRODUCTION_RATE_LIMIT', error: '联系申请过于频繁,请稍后重试;原消息未发送' };
|
|
6486
|
-
}
|
|
6487
|
-
const request = {
|
|
6488
|
-
...buildContactRequest(binding, args.to, args.sourceMessageId, Date.now(), `申请联系 ${args.to}。以下为本端拟发送的内容,尚未发给对方:\n${text}`, decision.reason),
|
|
6489
|
-
direction: 'outbound',
|
|
6490
|
-
};
|
|
6491
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
6492
|
-
if (remainingTtl <= 0) {
|
|
6493
|
-
return { ok: false, code: 'CONTACT_REQUEST_EXPIRED', error: '联系申请已过期,未重新提交;原消息未发送' };
|
|
6494
|
-
}
|
|
6495
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
6496
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 outbound]',
|
|
6497
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
6498
|
-
ttl: remainingTtl,
|
|
6499
|
-
});
|
|
6500
|
-
if (!sent.messageId && !sent.queued) {
|
|
6501
|
-
return { ok: false, code: sent.code ?? 'CONTACT_OWNER_REQUEST_FAILED',
|
|
6502
|
-
error: `向本端 Owner 提交联系申请失败:${sent.error ?? '未获得发送或排队回执'};原消息未发送` };
|
|
6503
|
-
}
|
|
6504
|
-
return { ok: true, receipt: {
|
|
6505
|
-
event_id: request.event_id, owner_aid: binding.owner_aid, target_aid: args.to,
|
|
6506
|
-
status: sent.messageId ? 'sent' : 'queued',
|
|
6507
|
-
...(sent.messageId ? { message_id: sent.messageId } : {}),
|
|
6508
|
-
...(sent.outboxId ? { outbox_id: sent.outboxId } : {}),
|
|
6509
|
-
} };
|
|
6510
|
-
}
|
|
6511
6897
|
async sendDaemonMsg(args) {
|
|
6512
6898
|
try {
|
|
6513
6899
|
resolveAunSendDevice(args.deviceId, 'msg', args.payload);
|
|
@@ -6541,6 +6927,38 @@ export class AUNChannel {
|
|
|
6541
6927
|
code: e?.code,
|
|
6542
6928
|
};
|
|
6543
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
|
+
}
|
|
6544
6962
|
if (!this.connected || !this.client) {
|
|
6545
6963
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6546
6964
|
}
|
|
@@ -6551,9 +6969,6 @@ export class AUNChannel {
|
|
|
6551
6969
|
code: 'INVALID_REQUEST_TTL',
|
|
6552
6970
|
};
|
|
6553
6971
|
}
|
|
6554
|
-
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 });
|
|
6555
|
-
if (contactBlock)
|
|
6556
|
-
return { ok: false, code: contactBlock.code, error: contactBlock.error };
|
|
6557
6972
|
if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
|
|
6558
6973
|
return {
|
|
6559
6974
|
ok: false,
|
|
@@ -7033,11 +7448,6 @@ export class AUNChannel {
|
|
|
7033
7448
|
const finalText = entry.text;
|
|
7034
7449
|
const delivery = this.requirePersistedDelivery(channelId, entry.delivery);
|
|
7035
7450
|
const context = this.withDelivery(entry.context, delivery);
|
|
7036
|
-
if (!entry.deliveryReceipt) {
|
|
7037
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, { type: 'text', text: entry.text });
|
|
7038
|
-
if (blocked)
|
|
7039
|
-
return blocked;
|
|
7040
|
-
}
|
|
7041
7451
|
const operationId = entry.dedupeKey
|
|
7042
7452
|
|| (typeof context?.metadata?.operationId === 'string' ? context.metadata.operationId : undefined);
|
|
7043
7453
|
if (operationId) {
|
|
@@ -7307,18 +7717,34 @@ export class AUNChannel {
|
|
|
7307
7717
|
}
|
|
7308
7718
|
}
|
|
7309
7719
|
async deliverPayloadEntry(entry) {
|
|
7310
|
-
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))) {
|
|
7311
7725
|
const selfAid = this.config.aid;
|
|
7312
7726
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.outbox' });
|
|
7313
7727
|
const binding = verifiedContactBinding(selfAid, view);
|
|
7314
7728
|
if (!binding)
|
|
7315
7729
|
return { ok: false, status: 'retry', code: 'CONTACT_OWNERSHIP_UNAVAILABLE', error: 'current Owner relation could not be verified' };
|
|
7316
|
-
|
|
7730
|
+
const routePayload = isContactApprovalCard(entry.payload) ? entry.payload?.friend_request ?? {} : entry.payload;
|
|
7731
|
+
if (!friendPayloadRouteValid(routePayload, entry.channelId, true, binding)) {
|
|
7317
7732
|
return { ok: false, status: 'permanent', code: 'CONTACT_OWNERSHIP_CHANGED', error: 'contact event no longer belongs to the current Owner relation' };
|
|
7318
7733
|
}
|
|
7319
7734
|
// E2EE is mandatory even for a recovered queue entry.
|
|
7320
7735
|
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
7321
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
|
+
}
|
|
7322
7748
|
const interactionId = entry.postSend?.type === 'register_interaction_card'
|
|
7323
7749
|
? entry.postSend.requestId
|
|
7324
7750
|
: undefined;
|
|
@@ -7364,15 +7790,16 @@ export class AUNChannel {
|
|
|
7364
7790
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7365
7791
|
if (entry.deliveryReceipt) {
|
|
7366
7792
|
try {
|
|
7367
|
-
|
|
7368
|
-
|
|
7369
|
-
|
|
7370
|
-
|
|
7371
|
-
|
|
7372
|
-
|
|
7373
|
-
|
|
7374
|
-
|
|
7375
|
-
|
|
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
|
+
});
|
|
7376
7803
|
this.runPostSend(entry, entry.deliveryReceipt.messageId);
|
|
7377
7804
|
return {
|
|
7378
7805
|
ok: true,
|
|
@@ -7605,6 +8032,8 @@ export class AUNChannel {
|
|
|
7605
8032
|
Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
|
|
7606
8033
|
}
|
|
7607
8034
|
const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
|
|
8035
|
+
const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
|
|
8036
|
+
&& isProjectionServiceResult(finalPayload.type);
|
|
7608
8037
|
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
7609
8038
|
const params = { payload: finalPayload, encrypt };
|
|
7610
8039
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
@@ -7617,6 +8046,10 @@ export class AUNChannel {
|
|
|
7617
8046
|
}
|
|
7618
8047
|
if (encrypt)
|
|
7619
8048
|
params.protected_headers = aunProtectedHeaders(context);
|
|
8049
|
+
if (isOutputServicePayload) {
|
|
8050
|
+
params.message_class = 'control';
|
|
8051
|
+
params.protected_headers = { ...(params.protected_headers ?? {}), message_class: 'control' };
|
|
8052
|
+
}
|
|
7620
8053
|
try {
|
|
7621
8054
|
if (isGroup) {
|
|
7622
8055
|
params.group_id = delivery.groupId;
|
|
@@ -7821,11 +8254,6 @@ export class AUNChannel {
|
|
|
7821
8254
|
return imagePayload;
|
|
7822
8255
|
}
|
|
7823
8256
|
async deliverImageEntry(entry) {
|
|
7824
|
-
if (!entry.deliveryReceipt) {
|
|
7825
|
-
const blocked = await this.prepareAppContactOutbound(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'image' });
|
|
7826
|
-
if (blocked)
|
|
7827
|
-
return blocked;
|
|
7828
|
-
}
|
|
7829
8257
|
const image = entry.image;
|
|
7830
8258
|
if (!image || typeof image.dataBase64 !== 'string') {
|
|
7831
8259
|
logger.warn(`${this.logPrefix()} deliverImageEntry: missing image data (outbox id=${entry.id})`);
|
|
@@ -7872,11 +8300,6 @@ export class AUNChannel {
|
|
|
7872
8300
|
}
|
|
7873
8301
|
}
|
|
7874
8302
|
async deliverFileEntry(entry) {
|
|
7875
|
-
if (!entry.deliveryReceipt) {
|
|
7876
|
-
const blocked = await this.prepareAppContactOutbound(entry.channelId, this.requirePersistedDelivery(entry.channelId, entry.delivery), { type: 'file' });
|
|
7877
|
-
if (blocked)
|
|
7878
|
-
return blocked;
|
|
7879
|
-
}
|
|
7880
8303
|
const channelId = entry.channelId;
|
|
7881
8304
|
if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
|
|
7882
8305
|
logger.warn(`${this.logPrefix()} deliverFileEntry: missing file path (outbox id=${entry.id})`);
|
|
@@ -8932,6 +9355,7 @@ export class AUNChannelPlugin {
|
|
|
8932
9355
|
const aunCard = withAunAttention({
|
|
8933
9356
|
type: 'action_card',
|
|
8934
9357
|
title: action.title,
|
|
9358
|
+
...(req.sensitive ? { sensitive: true } : {}),
|
|
8935
9359
|
...(req.blocking === true ? { blocking: true } : {}),
|
|
8936
9360
|
...(action.recommendedOption ? { recommended_option: action.recommendedOption } : {}),
|
|
8937
9361
|
actions: action.buttons.map(btn => ({
|
|
@@ -8945,6 +9369,7 @@ export class AUNChannelPlugin {
|
|
|
8945
9369
|
if (action.allowCustomInput) {
|
|
8946
9370
|
aunCard.actions.push({
|
|
8947
9371
|
label: '✏️ 手动输入', style: 'default', behavior: 'compose',
|
|
9372
|
+
...(req.sensitive ? { sensitive: true } : {}),
|
|
8948
9373
|
...(cardExpiresAt !== undefined ? { compose_timeout_ms: Math.max(0, cardExpiresAt - Date.now()) } : {}),
|
|
8949
9374
|
});
|
|
8950
9375
|
}
|
|
@@ -8972,6 +9397,7 @@ export class AUNChannelPlugin {
|
|
|
8972
9397
|
type: 'register_interaction_card',
|
|
8973
9398
|
requestId: req.id,
|
|
8974
9399
|
isCommandCard: false,
|
|
9400
|
+
sensitive: req.sensitive,
|
|
8975
9401
|
initiatorAid: req.initiatorId,
|
|
8976
9402
|
delivery: replyCtx?.delivery,
|
|
8977
9403
|
expiresAt: cardExpiresAt,
|
|
@@ -9083,8 +9509,9 @@ export class AUNChannelPlugin {
|
|
|
9083
9509
|
disconnect: (clientCloseBudgetMs) => channel.disconnect(clientCloseBudgetMs),
|
|
9084
9510
|
onProjectPathRequest: () => Promise.resolve(ctx.defaultProjectPath),
|
|
9085
9511
|
registerBridge(bridge, channelType) {
|
|
9512
|
+
channel.setContactReplayReceiptResolver(key => bridge.contactDeliveryReceipt(key), delivery => bridge.finishContactDelivery(delivery));
|
|
9086
9513
|
bridge.register(adapter.channelName, (handler) => channel.onMessage(async (opts) => {
|
|
9087
|
-
handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9514
|
+
await handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9088
9515
|
}), async (channelId, text, replyContext) => { await channel.sendMessage(channelId, text, replyContext); }, adapter, channelType);
|
|
9089
9516
|
bridge.registerGroupInviteReviewChannel({
|
|
9090
9517
|
selfAid: aid,
|