evolcore 0.0.48 → 0.0.50
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 +97 -0
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +285 -8
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +9 -2
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +31 -2
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +1175 -457
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/directory.js +6 -1
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +30 -5
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +20 -5
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/quota.js +89 -0
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +12 -9
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +88 -9
- package/dist/config/config-manager.js +97 -47
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +107 -20
- package/dist/config/providers-management.js +45 -21
- package/dist/config/resolved-config-op.js +4 -44
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +59 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +28 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +97 -73
- package/dist/core/command/menu-protocol.js +29 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +58 -1
- package/dist/core/daemon-lifecycle.js +29 -7
- package/dist/core/evolagent-registry.js +18 -9
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +5 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +213 -74
- package/dist/core/message/aun-request-registry.js +31 -0
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +197 -45
- package/dist/core/message/message-log.js +32 -0
- package/dist/core/message/message-queue.js +102 -18
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +174 -26
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-catalog.js +5 -5
- 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 +12 -86
- package/dist/core/pack-auth.js +7 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +288 -77
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +458 -0
- package/dist/core/permission/tool-policy.js +26 -10
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +67 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/ecweb/runtime/supervisor.js +36 -8
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +120 -41
- package/dist/ipc.js +83 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +204 -22
- package/dist/services/ipc-operation.js +288 -44
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/script-runner.js +515 -83
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +109 -4
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -8
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +173 -1
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/dist/workbench/service.js +1 -1
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +9 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +45 -3
- package/kits/docs/evolcore/config.md +5 -2
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +77 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +22 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +64 -0
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +58 -9
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -128
- package/kits/templates/system-fragments/venue.md +27 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +79 -29
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +24 -6
- package/scripts/agent-template/shared/team-schema.json +23 -5
- package/scripts/agent-template/shared/template-contract.mjs +107 -17
- package/scripts/agent-template/shared/template-package.mjs +254 -29
- package/scripts/agent-template/shared/template-runtime.mjs +145 -2
- package/scripts/agent-template/shared/template.mjs +67 -9
- package/scripts/agent-template/team-pack.mjs +132 -41
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
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';
|
|
@@ -13,15 +15,16 @@ import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
|
|
|
13
15
|
import path from 'path';
|
|
14
16
|
import os from 'os';
|
|
15
17
|
import { logger, localTimestamp, logPreview } from '../utils/logger.js';
|
|
18
|
+
import { ensureSessionRuntimeDir } from '../cli/task-context.js';
|
|
16
19
|
import { LogWriter } from '../utils/log-writer.js';
|
|
17
20
|
import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
|
|
18
21
|
import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
|
|
19
|
-
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
|
|
22
|
+
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath, toAttachmentMarkedPath, } from '../paths.js';
|
|
20
23
|
import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
|
|
21
24
|
import { AbilityError } from '../ability/types.js';
|
|
22
25
|
import { publishAbilityDocuments } from '../ability/publication.js';
|
|
23
26
|
import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
|
|
24
|
-
import {
|
|
27
|
+
import { saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch } from '../utils/media-cache.js';
|
|
25
28
|
import { appendAidEvent } from '../utils/instance-registry.js';
|
|
26
29
|
import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
|
|
27
30
|
import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
|
|
@@ -32,11 +35,11 @@ import { readTopicStatus } from '../core/session/session-mapper.js';
|
|
|
32
35
|
import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
|
|
33
36
|
import { appendAidLifecycle } from '../aun/aid/identity.js';
|
|
34
37
|
import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
|
|
35
|
-
import { classifyServicePayloadType, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
38
|
+
import { classifyServicePayloadType, isProjectionServiceResult, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
36
39
|
import { agentServicesDir } from '../paths.js';
|
|
37
40
|
import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
|
|
41
|
+
import { consumePaymentInbound, paymentStore } from '../pay/runtime.js';
|
|
38
42
|
import { loadAgent } from '../config-store.js';
|
|
39
|
-
import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
|
|
40
43
|
import { resolvePeerRoleDetail, resolveSenderRelationRole } from '../config/peer-role-resolver.js';
|
|
41
44
|
import { resolveAgentLifecycle } from '../config/lifecycle.js';
|
|
42
45
|
import { resolveEffective } from '../config/config-manager.js';
|
|
@@ -44,6 +47,8 @@ import { isManagementRole } from '../config/builtin-roles.js';
|
|
|
44
47
|
import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
|
|
45
48
|
import { getProcessStartTime } from '../utils/process-introspect.js';
|
|
46
49
|
import * as outbox from '../aun/outbox.js';
|
|
50
|
+
import { recordTemplateNoticeReceipt } from '../agent-template/jobs.js';
|
|
51
|
+
import { acceptWidgetCardReply, cancelWidgetCard, readWidgetCard, registerWidgetCard } from '../core/interaction-router.js';
|
|
47
52
|
import { formatSize } from '../utils/media-cache.js';
|
|
48
53
|
import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
|
|
49
54
|
import { prepareSameOwnerProof, registerSameOwnerClient, unregisterSameOwnerClient } from '../core/relation/same-owner-proof.js';
|
|
@@ -60,12 +65,20 @@ import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOu
|
|
|
60
65
|
import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
|
|
61
66
|
import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
|
|
62
67
|
import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
|
|
63
|
-
import { isTopicThreadId, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
68
|
+
import { isTopicThreadId, normalizeThreadIdForPeer, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
64
69
|
import { ThreadService } from '../core/thread/thread-service.js';
|
|
65
70
|
import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js';
|
|
66
71
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
67
72
|
const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
|
|
68
73
|
const AUN_INBOUND_DEDUP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
74
|
+
/**
|
|
75
|
+
* 服务应答的 volatile TTL(秒)。
|
|
76
|
+
*
|
|
77
|
+
* 调用方默认等 12 秒(`SERVICE_CALL_TIMEOUT_MS`),应答发出时它可能只剩几秒
|
|
78
|
+
* 有效期。给 15 秒是留出"脚本在最后一刻跑完、包在路上"的余量:超过这个窗口,
|
|
79
|
+
* 调用方的记录已是终态,投过去也只会被丢弃。
|
|
80
|
+
*/
|
|
81
|
+
const SERVICE_REPLY_TTL_SECONDS = 15;
|
|
69
82
|
const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
|
|
70
83
|
const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
|
|
71
84
|
const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
|
|
@@ -77,28 +90,69 @@ const OBSERVER_GROUP_MEMBERS_TTL_MS = 60_000;
|
|
|
77
90
|
const GROUP_MEMBER_ROLES_TTL_MS = 120 * 60_000;
|
|
78
91
|
/** 群成员角色拉取失败后的退避时间,避免持续失败时每条消息都重试 RPC。 */
|
|
79
92
|
const GROUP_MEMBER_ROLES_FAILURE_TTL_MS = 60_000;
|
|
80
|
-
/**
|
|
81
|
-
|
|
93
|
+
/**
|
|
94
|
+
* `sender_ctx` 是**发件人客户端**填的自由文本,会被原样拼进系统提示里的 `ctx:` 行。
|
|
95
|
+
* 因此在入口处做两件事:折叠所有控制字符与换行(否则可伪造出新的信封行),并按字符数截断。
|
|
96
|
+
* 截断按码位计,不切断代理对。
|
|
97
|
+
*/
|
|
98
|
+
const SENDER_CTX_SCENE_MAX = 40;
|
|
99
|
+
const SENDER_CTX_ACTIVITY_MAX = 80;
|
|
100
|
+
const SENDER_CTX_ADDRESS_MAX = 120;
|
|
101
|
+
function clipSenderCtxText(value, max) {
|
|
102
|
+
if (typeof value !== 'string')
|
|
103
|
+
return undefined;
|
|
104
|
+
const flat = value
|
|
105
|
+
.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ')
|
|
106
|
+
.replace(/\s+/g, ' ')
|
|
107
|
+
.trim();
|
|
108
|
+
if (!flat)
|
|
109
|
+
return undefined;
|
|
110
|
+
const chars = Array.from(flat);
|
|
111
|
+
return chars.length > max ? `${chars.slice(0, max).join('')}…` : flat;
|
|
112
|
+
}
|
|
113
|
+
/** 时区必须能被 Intl 接受;非法值会在渲染阶段抛 RangeError,故在入口丢弃而不是靠下游兜底。 */
|
|
114
|
+
function readSenderTimezone(rawTz) {
|
|
115
|
+
if (typeof rawTz !== 'string')
|
|
116
|
+
return undefined;
|
|
117
|
+
const tz = rawTz.trim();
|
|
118
|
+
if (!tz)
|
|
119
|
+
return undefined;
|
|
120
|
+
try {
|
|
121
|
+
new Intl.DateTimeFormat('en-US', { timeZone: tz }).format(0);
|
|
122
|
+
return tz;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
logger.debug(`[AUN] sender_ctx.timezone ignored (invalid IANA name): ${logPreview(tz)}`);
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** 解析 AUN payload 的 `sender_ctx`;结构非法或全空返回 undefined。导出以便单测覆盖入口清洗。 */
|
|
130
|
+
export function readSenderCtx(payload) {
|
|
82
131
|
const raw = (payload && typeof payload === 'object')
|
|
83
132
|
? (payload.sender_ctx ?? payload.senderCtx)
|
|
84
133
|
: undefined;
|
|
85
134
|
if (!raw || typeof raw !== 'object')
|
|
86
135
|
return undefined;
|
|
87
|
-
const scene =
|
|
88
|
-
const activity =
|
|
136
|
+
const scene = clipSenderCtxText(raw.scene, SENDER_CTX_SCENE_MAX);
|
|
137
|
+
const activity = clipSenderCtxText(raw.activity, SENDER_CTX_ACTIVITY_MAX);
|
|
89
138
|
// 协议字段名尚未在真实 payload 上核对;同时接受 timezone / tz 两种写法。
|
|
90
|
-
const
|
|
91
|
-
const timezone = rawTz.trim() || undefined;
|
|
139
|
+
const timezone = readSenderTimezone(raw.timezone ?? raw.tz);
|
|
92
140
|
let location;
|
|
93
141
|
const loc = raw.location;
|
|
94
142
|
if (loc && typeof loc === 'object') {
|
|
95
143
|
const lat = Number(loc.latitude_e6);
|
|
96
144
|
const lon = Number(loc.longitude_e6);
|
|
97
145
|
if (Number.isFinite(lat) && Number.isFinite(lon)) {
|
|
146
|
+
// 精度与采集时刻缺省时保持缺省(不补 0、不回落成消息时间):缺省含义是「未上报」。
|
|
147
|
+
const accuracy = Number(loc.accuracy_m);
|
|
148
|
+
const capturedAt = Number(loc.timestamp_ms);
|
|
149
|
+
const address = clipSenderCtxText(loc.address, SENDER_CTX_ADDRESS_MAX);
|
|
98
150
|
location = {
|
|
99
151
|
latitude_e6: lat,
|
|
100
152
|
longitude_e6: lon,
|
|
101
|
-
...(
|
|
153
|
+
...(address ? { address } : {}),
|
|
154
|
+
...(Number.isFinite(accuracy) && accuracy > 0 ? { accuracy_m: accuracy } : {}),
|
|
155
|
+
...(Number.isFinite(capturedAt) && capturedAt > 0 ? { timestamp_ms: capturedAt } : {}),
|
|
102
156
|
};
|
|
103
157
|
}
|
|
104
158
|
}
|
|
@@ -125,7 +179,7 @@ const AUN_MIN_FIELD_SIZE = 1024;
|
|
|
125
179
|
const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
|
|
126
180
|
const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
|
|
127
181
|
'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
|
|
128
|
-
'action_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
182
|
+
'action_card', 'widget_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
129
183
|
]);
|
|
130
184
|
/** Automatic PA output shares the activity queue, not the ordinary reply path. */
|
|
131
185
|
function isAgentFinalPayload(payload) {
|
|
@@ -312,18 +366,37 @@ export function echoTraceDirection(text) {
|
|
|
312
366
|
* 正文还没有 trace 行时,回落到首行 `hop=<N>` 参数;都没有则用默认值。
|
|
313
367
|
* 去程返程共用这一个计数器,不重置。
|
|
314
368
|
*/
|
|
315
|
-
export function echoTraceNextHop(text) {
|
|
369
|
+
export function echoTraceNextHop(text, dir = echoTraceDirection(text)) {
|
|
316
370
|
const lines = text.split('\n');
|
|
317
371
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
318
|
-
const m = /\bhop=(
|
|
319
|
-
if (m)
|
|
320
|
-
|
|
372
|
+
const m = /\bhop=([+-]?\d+)(?=\s|$)/.exec(lines[i]);
|
|
373
|
+
if (m) {
|
|
374
|
+
const hop = Number(m[1]);
|
|
375
|
+
const next = dir === 'ret' || hop < 0 ? hop - 1 : Math.max(0, hop - 1);
|
|
376
|
+
if (!Number.isSafeInteger(hop) || !Number.isSafeInteger(next)) {
|
|
377
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
378
|
+
}
|
|
379
|
+
return next;
|
|
380
|
+
}
|
|
321
381
|
}
|
|
322
|
-
const declared = /\bhop=(\d+)\b/.exec(lines[0] ?? '');
|
|
323
|
-
if (declared)
|
|
324
|
-
return Math.max(0, Number(declared[1]) - 1);
|
|
325
382
|
return ECHO_DEFAULT_HOP - 1;
|
|
326
383
|
}
|
|
384
|
+
/** Restore terminal reply controls when a text outbox entry becomes a wire payload. */
|
|
385
|
+
export function echoTextPayload(text) {
|
|
386
|
+
const payload = { type: 'text', text };
|
|
387
|
+
if (echoProbeKind(text) === null)
|
|
388
|
+
return payload;
|
|
389
|
+
// Only Core's terminal reply trace supplies controls; arbitrary prose and
|
|
390
|
+
// first-line parameters must not turn an ordinary text message into a return.
|
|
391
|
+
const reply = text.split('\n').reverse().find(line => /^\d{2}:\d{2}:\d{2}\.\d{3} \[EvolCore\.reply\] dir=ret hop=/.test(line));
|
|
392
|
+
const hopField = reply && /\bhop=([+-]?\d+)(?=\s|$)/.exec(reply);
|
|
393
|
+
if (!hopField)
|
|
394
|
+
return payload;
|
|
395
|
+
const hop = Number(hopField[1]);
|
|
396
|
+
if (!Number.isSafeInteger(hop))
|
|
397
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
398
|
+
return { ...payload, dir: 'ret', hop };
|
|
399
|
+
}
|
|
327
400
|
/**
|
|
328
401
|
* 组装一行 trace。
|
|
329
402
|
*
|
|
@@ -805,6 +878,7 @@ export function aunOptsToInbound(opts, channel, channelType) {
|
|
|
805
878
|
return {
|
|
806
879
|
channel,
|
|
807
880
|
channelType,
|
|
881
|
+
contactDelivery: trustedContactInboundDelivery(opts.contactDelivery),
|
|
808
882
|
channelId: opts.channelId,
|
|
809
883
|
selfAID: opts.selfAID,
|
|
810
884
|
groupId: opts.groupId,
|
|
@@ -918,8 +992,6 @@ export class AUNChannel {
|
|
|
918
992
|
&& (!params || !String(payload.type).startsWith('menu.') || params.encrypt === true)
|
|
919
993
|
&& (!params || !permit.device || (params.to_device_id ?? params.device_id) === permit.device));
|
|
920
994
|
}
|
|
921
|
-
// Keep each target's attempt across channel recreation; reset only on process restart.
|
|
922
|
-
static configuredOwnerBindAttempts = new Set();
|
|
923
995
|
managedMenuClient = new ManagedMenuClient((params, beforeSend) => {
|
|
924
996
|
if (!this.connected || !this.client)
|
|
925
997
|
return Promise.reject(new Error('AUN channel is not connected'));
|
|
@@ -944,9 +1016,6 @@ export class AUNChannel {
|
|
|
944
1016
|
} });
|
|
945
1017
|
}
|
|
946
1018
|
client = null;
|
|
947
|
-
configuredOwnerBind;
|
|
948
|
-
configuredOwnerBindEpoch = 0;
|
|
949
|
-
configuredOwnerBindRecheck = false;
|
|
950
1019
|
ownerDirectoryCache;
|
|
951
1020
|
ownerDirectoryWatch;
|
|
952
1021
|
ownerDirectoryFlight;
|
|
@@ -976,7 +1045,6 @@ export class AUNChannel {
|
|
|
976
1045
|
/** `topic.renamed` 事件消费器,由 runtime 注入(见 setThreadRenameHandler)。 */
|
|
977
1046
|
threadRenameHandler = null;
|
|
978
1047
|
groupInviteHandler;
|
|
979
|
-
groupInviteConnectedHandler;
|
|
980
1048
|
groupInviteDeliveryGate;
|
|
981
1049
|
groupInviteDelivered;
|
|
982
1050
|
pendingEchoMessages = new Map();
|
|
@@ -999,7 +1067,7 @@ export class AUNChannel {
|
|
|
999
1067
|
// 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
|
|
1000
1068
|
const inbound = data && typeof data === 'object' ? data : {};
|
|
1001
1069
|
const isolateTrace = dir === 'IN' && event === 'message.received'
|
|
1002
|
-
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply');
|
|
1070
|
+
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply' || inbound.payload?.type === 'widget_card_reply');
|
|
1003
1071
|
const safeData = isolateTrace ? {
|
|
1004
1072
|
message_id: inbound.message_id, seq: inbound.seq,
|
|
1005
1073
|
envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
|
|
@@ -1044,45 +1112,37 @@ export class AUNChannel {
|
|
|
1044
1112
|
callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
|
|
1045
1113
|
params = menuTransportParams(method, params);
|
|
1046
1114
|
const client = this.client;
|
|
1047
|
-
const
|
|
1048
|
-
|
|
1049
|
-
const binding =
|
|
1115
|
+
const friendPayload = (typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.'))
|
|
1116
|
+
|| isContactApprovalCard(params.payload);
|
|
1117
|
+
const binding = friendPayload ? currentContactBinding(this.config.aid) : undefined;
|
|
1050
1118
|
onPrepared?.(params);
|
|
1051
1119
|
return this.withOutboundSendGate(method, async () => {
|
|
1052
1120
|
if (client !== this.client || !client)
|
|
1053
1121
|
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1054
|
-
if (!this.config.pureIdentity &&
|
|
1122
|
+
if (!this.config.pureIdentity && friendPayload
|
|
1055
1123
|
&& (method === 'message.send' || method === 'message.thought.put')) {
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
}
|
|
1066
|
-
if (client !== this.client)
|
|
1067
|
-
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1124
|
+
const routePayload = isContactApprovalCard(params.payload) ? params.payload.friend_request ?? {} : params.payload;
|
|
1125
|
+
const refreshed = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'contact.transport' });
|
|
1126
|
+
const verified = verifiedContactBinding(this.config.aid, refreshed);
|
|
1127
|
+
if (!verified) {
|
|
1128
|
+
throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
|
|
1129
|
+
}
|
|
1130
|
+
if (!friendPayloadRouteValid(routePayload, params.to, params.encrypt, verified)
|
|
1131
|
+
|| !sameContactBinding(verified, currentContactBinding(this.config.aid))) {
|
|
1132
|
+
throw Object.assign(new Error('contact Owner relation changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1068
1133
|
}
|
|
1134
|
+
if (client !== this.client)
|
|
1135
|
+
throw Object.assign(new Error('AUN connection changed'), { code: 'AUN_NOT_CONNECTED' });
|
|
1069
1136
|
const current = currentContactBinding(this.config.aid);
|
|
1070
1137
|
if (!current)
|
|
1071
1138
|
throw Object.assign(new Error('current Owner relation unavailable'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
|
|
1072
1139
|
if (!binding || !sameContactBinding(binding, current))
|
|
1073
1140
|
throw Object.assign(new Error('Owner relation changed while queued'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1074
|
-
|
|
1075
|
-
if (typeof payload?.type === 'string' && payload.type.startsWith('friend.')
|
|
1076
|
-
&& !friendPayloadRouteValid(payload, params.to, params.encrypt, current)) {
|
|
1141
|
+
if (!friendPayloadRouteValid(routePayload, params.to, params.encrypt, current)) {
|
|
1077
1142
|
throw Object.assign(new Error('contact event relation or encryption changed'), { code: 'CONTACT_OWNERSHIP_CHANGED' });
|
|
1078
1143
|
}
|
|
1079
|
-
if (
|
|
1080
|
-
|
|
1081
|
-
if (blocked) {
|
|
1082
|
-
throw Object.assign(new Error(blocked.error), {
|
|
1083
|
-
code: blocked.code, retryable: blocked.status === 'retry',
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1144
|
+
if (isContactApprovalCard(params.payload) && routePayload.received_at_ms + CONTACT_EVENT_TTL_MS <= Date.now()) {
|
|
1145
|
+
throw Object.assign(new Error('contact approval card has expired'), { code: 'CONTACT_APPROVAL_EXPIRED' });
|
|
1086
1146
|
}
|
|
1087
1147
|
}
|
|
1088
1148
|
beforeSend?.();
|
|
@@ -1321,6 +1381,73 @@ export class AUNChannel {
|
|
|
1321
1381
|
logger.info(`${this.logPrefix()} ActionInteraction audit: behavior=${behavior ?? 'reply'} `
|
|
1322
1382
|
+ `cardId=${cardMessageId} interactionId=${interactionId} result=${result} textLength=${textLength}`);
|
|
1323
1383
|
}
|
|
1384
|
+
async handleWidgetCardReply(payload, channelId, senderAid, delivery, messageId, encrypted) {
|
|
1385
|
+
let replyThreadId;
|
|
1386
|
+
try {
|
|
1387
|
+
const binding = typeof payload.card_message_id === 'string'
|
|
1388
|
+
? readWidgetCard(this.config.aid, payload.card_message_id) : undefined;
|
|
1389
|
+
// Group replies are broadcast to every Agent. Like action_card_reply,
|
|
1390
|
+
// a reply to another sender's card is silently ignored by this Agent.
|
|
1391
|
+
if (!binding)
|
|
1392
|
+
return;
|
|
1393
|
+
if (binding?.channelId === channelId && binding.chatType === delivery.chatType && binding.initiatorAid === senderAid) {
|
|
1394
|
+
replyThreadId = binding.threadId;
|
|
1395
|
+
}
|
|
1396
|
+
const outcome = await acceptWidgetCardReply({
|
|
1397
|
+
selfAid: this.config.aid, channelId, senderAid, chatType: delivery.chatType, payload, encrypted,
|
|
1398
|
+
dispatch: async (binding, action, values) => {
|
|
1399
|
+
if (binding.requestId) {
|
|
1400
|
+
const accepted = await this.interactionCallback?.({
|
|
1401
|
+
type: 'interaction.response', id: binding.requestId, action,
|
|
1402
|
+
values, operatorId: senderAid, encrypted,
|
|
1403
|
+
});
|
|
1404
|
+
if (!this.interactionCallback || accepted === false) {
|
|
1405
|
+
await this.invalidateInteraction(binding.requestId, 'backend_rejected');
|
|
1406
|
+
cancelWidgetCard(this.config.aid, binding.messageId);
|
|
1407
|
+
throw Object.assign(new Error('卡片已失效,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1408
|
+
}
|
|
1409
|
+
this.forgetInteractionCard(binding.messageId, binding.requestId);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (!this.messageHandler)
|
|
1413
|
+
throw new Error('WidgetCard handler is unavailable');
|
|
1414
|
+
if (binding.threadId) {
|
|
1415
|
+
const thread = ThreadService.findThreadById(this.config.aid, binding.threadId);
|
|
1416
|
+
if (!thread || thread.peer !== channelId || thread.topicStatus === 'archived') {
|
|
1417
|
+
throw Object.assign(new Error('原话题已不存在或已归档,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
const groupRoles = delivery.chatType === 'group' ? await this.resolveGroupMemberRoles(channelId) : undefined;
|
|
1421
|
+
const text = `[WidgetCard 用户${action === 'cancel' ? '取消' : '提交'}]\n${JSON.stringify({
|
|
1422
|
+
title: binding.title, card_message_id: binding.messageId,
|
|
1423
|
+
submission_id: payload.submission_id, action, ...(action === 'submit' ? { values } : {}),
|
|
1424
|
+
})}`;
|
|
1425
|
+
await this.dispatchMessage({
|
|
1426
|
+
channelId, userId: senderAid, chatType: delivery.chatType,
|
|
1427
|
+
...(delivery.chatType === 'group' ? { groupId: channelId,
|
|
1428
|
+
groupRole: groupRoles?.get(senderAid.toLowerCase()),
|
|
1429
|
+
myGroupRole: groupRoles?.get(this.config.aid.toLowerCase()),
|
|
1430
|
+
groupRoles: groupRoles ? Object.fromEntries(groupRoles) : undefined,
|
|
1431
|
+
speakerRelation: resolveSenderRelationRole({ selfAid: this.config.aid,
|
|
1432
|
+
channelKey: `aun#${this.config.aid}#main`, channelType: 'aun', chatType: 'group',
|
|
1433
|
+
senderAid, conversationId: channelId }),
|
|
1434
|
+
} : {}),
|
|
1435
|
+
text, messageId, encrypted, threadId: binding.threadId, source: 'card-trigger', isMentioned: true,
|
|
1436
|
+
msgType: 'widget_card_reply', payloadType: 'widget_card_reply',
|
|
1437
|
+
messageLogContent: '[WidgetCard 回复]', receivedAt: Date.now(), awaitHandler: true,
|
|
1438
|
+
replyContext: { delivery, threadId: binding.threadId,
|
|
1439
|
+
metadata: { encrypted }, replyToMessageId: messageId },
|
|
1440
|
+
});
|
|
1441
|
+
},
|
|
1442
|
+
});
|
|
1443
|
+
logger.info(`${this.logPrefix()} WidgetCard reply ${outcome}: mid=${messageId}`);
|
|
1444
|
+
}
|
|
1445
|
+
catch (error) {
|
|
1446
|
+
const code = error.code ?? 'WIDGET_REPLY_FAILED';
|
|
1447
|
+
logger.warn(`${this.logPrefix()} WidgetCard reply rejected: code=${code} mid=${messageId}`);
|
|
1448
|
+
this.notifyCardActionFailure(channelId, error.code ? error.message : '表单处理失败,请核实任务状态后再操作', senderAid, replyThreadId, delivery);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1324
1451
|
extractTextPayload(payload, channelId, senderAid, delivery, encrypted) {
|
|
1325
1452
|
if (typeof payload === 'string')
|
|
1326
1453
|
return payload;
|
|
@@ -1345,6 +1472,10 @@ export class AUNChannel {
|
|
|
1345
1472
|
?? (savedTopic?.channelId === channelId ? savedTopic?.threadId : undefined)
|
|
1346
1473
|
?? (typeof obj.thread_id === 'string' ? obj.thread_id : undefined);
|
|
1347
1474
|
if (cardInfo) {
|
|
1475
|
+
if (cardInfo.widget) {
|
|
1476
|
+
this.notifyCardActionFailure(channelId || '', '该卡片需要通过 widget_card_reply 提交表单', senderAid, threadId, cardDelivery);
|
|
1477
|
+
return '';
|
|
1478
|
+
}
|
|
1348
1479
|
// compose 按钮由新版客户端在卡片内采集输入;旧版客户端可继续从主编辑器
|
|
1349
1480
|
// 采集。两者最终都回传 action_card_reply{behavior:"compose", text}。
|
|
1350
1481
|
// 映射为 _custom_input + values.custom_text,复用 claude-runner 已有的自定义输入分支
|
|
@@ -1483,8 +1614,8 @@ export class AUNChannel {
|
|
|
1483
1614
|
.finally(() => this.forgetInteractionCard(cardMsgId, cardInfo.requestId));
|
|
1484
1615
|
}
|
|
1485
1616
|
else {
|
|
1486
|
-
// Gateway-driven
|
|
1487
|
-
//
|
|
1617
|
+
// Gateway-driven invalidation has already disabled the card
|
|
1618
|
+
// before the callback returned. Keep the original message.
|
|
1488
1619
|
this.forgetInteractionCard(cardMsgId, cardInfo.requestId);
|
|
1489
1620
|
}
|
|
1490
1621
|
this.notifyCardActionFailure(channelId, '⚠️ 卡片已失效,请重新发起', cardClickerAid, threadId, cardDelivery);
|
|
@@ -1824,7 +1955,6 @@ export class AUNChannel {
|
|
|
1824
1955
|
prepareShutdown() {
|
|
1825
1956
|
this.intentionalDisconnect = true;
|
|
1826
1957
|
this.reconnectGeneration++;
|
|
1827
|
-
this.configuredOwnerBindEpoch++;
|
|
1828
1958
|
this.stopOwnerDirectoryRefresh();
|
|
1829
1959
|
this.stopOutboxTimer();
|
|
1830
1960
|
if (this.reconnectTimer)
|
|
@@ -1836,7 +1966,192 @@ export class AUNChannel {
|
|
|
1836
1966
|
void this.finishEcdiag(mid, 'shutdown').catch(() => { });
|
|
1837
1967
|
}
|
|
1838
1968
|
}
|
|
1969
|
+
contactReplayTimer;
|
|
1970
|
+
contactReplayRunning = false;
|
|
1971
|
+
contactReplayFlight;
|
|
1972
|
+
contactReplayDirty = false;
|
|
1973
|
+
contactReplayReconcileAt = 0;
|
|
1974
|
+
contactReplayReceiptResolver;
|
|
1975
|
+
contactReplayFinishHandler;
|
|
1976
|
+
setContactReplayReceiptResolver(resolver, finish) {
|
|
1977
|
+
this.contactReplayReceiptResolver = resolver;
|
|
1978
|
+
this.contactReplayFinishHandler = finish;
|
|
1979
|
+
}
|
|
1980
|
+
scheduleContactReplay() {
|
|
1981
|
+
if (this.config.pureIdentity || this.intentionalDisconnect || !this.connected || !this.messageHandler)
|
|
1982
|
+
return;
|
|
1983
|
+
this.contactReplayDirty = true;
|
|
1984
|
+
if (this.contactReplayRunning)
|
|
1985
|
+
return;
|
|
1986
|
+
if (this.contactReplayTimer)
|
|
1987
|
+
clearTimeout(this.contactReplayTimer);
|
|
1988
|
+
this.contactReplayTimer = setTimeout(() => {
|
|
1989
|
+
this.contactReplayTimer = undefined;
|
|
1990
|
+
void this.runContactReplay();
|
|
1991
|
+
}, 0);
|
|
1992
|
+
this.contactReplayTimer.unref?.();
|
|
1993
|
+
}
|
|
1994
|
+
validateContactReplay(record) {
|
|
1995
|
+
isolatedContactSource(this.config.aid, record.fromAid, record.messageId);
|
|
1996
|
+
const current = readPendingContactInbound(this.config.aid, record.key);
|
|
1997
|
+
if (!current?.message || !['waiting', 'transferring'].includes(current.state))
|
|
1998
|
+
throw new Error('contact replay is no longer pending');
|
|
1999
|
+
if (!this.connected || !sameContactBinding(record.binding, currentContactBinding(this.config.aid))
|
|
2000
|
+
|| record.expiresAt <= Date.now())
|
|
2001
|
+
throw new Error('contact replay binding or lifetime changed');
|
|
2002
|
+
const decision = evaluateAppContactAdmission(this.config.aid, record.fromAid);
|
|
2003
|
+
if (!decision.allow || !['contact', 'temporary', 'owner'].includes(decision.reason)) {
|
|
2004
|
+
throw new Error('contact replay is not admitted');
|
|
2005
|
+
}
|
|
2006
|
+
if (this.ownerDirectoryCache?.cache.readPendingUpdate())
|
|
2007
|
+
throw new Error('contact directory update is pending');
|
|
2008
|
+
}
|
|
2009
|
+
async runContactReplay() {
|
|
2010
|
+
if (this.contactReplayFlight)
|
|
2011
|
+
return this.contactReplayFlight;
|
|
2012
|
+
const flight = this.drainContactReplay();
|
|
2013
|
+
this.contactReplayFlight = flight;
|
|
2014
|
+
try {
|
|
2015
|
+
await flight;
|
|
2016
|
+
}
|
|
2017
|
+
finally {
|
|
2018
|
+
if (this.contactReplayFlight === flight)
|
|
2019
|
+
this.contactReplayFlight = undefined;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
async drainContactReplay() {
|
|
2023
|
+
if (this.contactReplayRunning || !this.connected || !this.messageHandler)
|
|
2024
|
+
return;
|
|
2025
|
+
this.contactReplayRunning = true;
|
|
2026
|
+
try {
|
|
2027
|
+
do {
|
|
2028
|
+
this.contactReplayDirty = false;
|
|
2029
|
+
if (!listPendingContactInbound(this.config.aid).length)
|
|
2030
|
+
break;
|
|
2031
|
+
await ownerResolver.refresh(this.config.aid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.replay' });
|
|
2032
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
2033
|
+
if (runtime && Date.now() >= this.contactReplayReconcileAt) {
|
|
2034
|
+
this.contactReplayReconcileAt = Date.now() + 60_000;
|
|
2035
|
+
await runtime.cache.reconcilePendingContacts();
|
|
2036
|
+
}
|
|
2037
|
+
await this.settleOwnerDirectoryBeforeTurn();
|
|
2038
|
+
// Application callbacks above are already reflected in this scan. Reading
|
|
2039
|
+
// again also includes messages saved while synchronization was in flight.
|
|
2040
|
+
this.contactReplayDirty = false;
|
|
2041
|
+
const records = listPendingContactInbound(this.config.aid);
|
|
2042
|
+
const blockedRoutes = new Set();
|
|
2043
|
+
for (let record of records) {
|
|
2044
|
+
if (!this.connected || !this.messageHandler)
|
|
2045
|
+
break;
|
|
2046
|
+
if (this.contactReplayReceiptResolver?.(record.key)) {
|
|
2047
|
+
finishPendingContactInbound(record, 'accepted');
|
|
2048
|
+
continue;
|
|
2049
|
+
}
|
|
2050
|
+
const binding = currentContactBinding(this.config.aid);
|
|
2051
|
+
if (record.expiresAt <= Date.now()) {
|
|
2052
|
+
finishPendingContactInbound(record, 'expired');
|
|
2053
|
+
continue;
|
|
2054
|
+
}
|
|
2055
|
+
if (binding && !sameContactBinding(record.binding, binding)) {
|
|
2056
|
+
finishPendingContactInbound(record, 'binding_changed');
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
if (!binding)
|
|
2060
|
+
continue;
|
|
2061
|
+
const decision = evaluateAppContactAdmission(this.config.aid, record.fromAid);
|
|
2062
|
+
if (decision.reason === 'blocked') {
|
|
2063
|
+
finishPendingContactInbound(record, 'blocked');
|
|
2064
|
+
continue;
|
|
2065
|
+
}
|
|
2066
|
+
if (!decision.allow && record.message) {
|
|
2067
|
+
const source = isolatedContactSource(this.config.aid, record.fromAid, record.messageId);
|
|
2068
|
+
if (source && !source.notified) {
|
|
2069
|
+
try {
|
|
2070
|
+
await this.notifyContactIntroduction(record.fromAid, record.message.payload, record.messageId, source, record.binding);
|
|
2071
|
+
}
|
|
2072
|
+
catch (error) {
|
|
2073
|
+
logger.warn(`${this.logPrefix()} Contact approval notification deferred: mid=${record.messageId} reason=${error instanceof Error ? error.message : String(error)}`);
|
|
2074
|
+
}
|
|
2075
|
+
record = readPendingContactInbound(this.config.aid, record.key);
|
|
2076
|
+
if (!record?.message || !['waiting', 'transferring'].includes(record.state))
|
|
2077
|
+
continue;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
const route = JSON.stringify([record.fromAid, record.message?.payload?.thread_id ?? '']);
|
|
2081
|
+
if (blockedRoutes.has(route))
|
|
2082
|
+
continue;
|
|
2083
|
+
if (!decision.allow || !['contact', 'temporary', 'owner'].includes(decision.reason)) {
|
|
2084
|
+
blockedRoutes.add(route);
|
|
2085
|
+
continue;
|
|
2086
|
+
}
|
|
2087
|
+
const delivery = createContactInboundDelivery({
|
|
2088
|
+
key: record.key, receivedAt: record.receivedAt, sessionId: record.sessionId,
|
|
2089
|
+
validate: () => this.validateContactReplay(record),
|
|
2090
|
+
bindSession: sessionId => {
|
|
2091
|
+
if (record.sessionId && record.sessionId !== sessionId)
|
|
2092
|
+
throw new Error('contact replay session changed');
|
|
2093
|
+
delivery.validate();
|
|
2094
|
+
ensureContactApprovalThreadContext(this.config.aid, record, sessionId);
|
|
2095
|
+
record.sessionId = sessionId;
|
|
2096
|
+
delivery.sessionId = sessionId;
|
|
2097
|
+
record.state = 'transferring';
|
|
2098
|
+
updatePendingContactInbound(record);
|
|
2099
|
+
},
|
|
2100
|
+
startCommand: () => {
|
|
2101
|
+
if (record.commandStartedAt)
|
|
2102
|
+
throw new Error('contact command outcome requires reconciliation');
|
|
2103
|
+
delivery.validate();
|
|
2104
|
+
record.commandStartedAt = Date.now();
|
|
2105
|
+
updatePendingContactInbound(record);
|
|
2106
|
+
},
|
|
2107
|
+
cancelCommand: () => {
|
|
2108
|
+
delete record.commandStartedAt;
|
|
2109
|
+
updatePendingContactInbound(record);
|
|
2110
|
+
},
|
|
2111
|
+
});
|
|
2112
|
+
try {
|
|
2113
|
+
await this.handleIncomingPrivateMessage(record.message, delivery);
|
|
2114
|
+
if (delivery.receipt) {
|
|
2115
|
+
// Observer telemetry is best effort, emitted only after durable acceptance.
|
|
2116
|
+
void this.forwardInbound(record.message);
|
|
2117
|
+
finishPendingContactInbound(record, 'accepted');
|
|
2118
|
+
logger.info(`${this.logPrefix()} Contact replay accepted: mid=${record.messageId} outcome=${delivery.receipt.outcome}`);
|
|
2119
|
+
}
|
|
2120
|
+
else
|
|
2121
|
+
blockedRoutes.add(route);
|
|
2122
|
+
}
|
|
2123
|
+
catch (error) {
|
|
2124
|
+
blockedRoutes.add(route);
|
|
2125
|
+
logger.warn(`${this.logPrefix()} Contact replay deferred: mid=${record.messageId} reason=${error instanceof Error ? error.message : String(error)}`);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
} while (this.contactReplayDirty && this.connected);
|
|
2129
|
+
}
|
|
2130
|
+
catch (error) {
|
|
2131
|
+
logger.warn(`${this.logPrefix()} Contact replay pending: ${error instanceof Error ? error.message : String(error)}`);
|
|
2132
|
+
}
|
|
2133
|
+
finally {
|
|
2134
|
+
this.contactReplayRunning = false;
|
|
2135
|
+
if (this.connected && !this.intentionalDisconnect && !this.contactReplayTimer) {
|
|
2136
|
+
let pending = true;
|
|
2137
|
+
try {
|
|
2138
|
+
pending = listPendingContactInbound(this.config.aid).length > 0;
|
|
2139
|
+
}
|
|
2140
|
+
catch { /* retry store recovery */ }
|
|
2141
|
+
if (pending) {
|
|
2142
|
+
this.contactReplayTimer = setTimeout(() => {
|
|
2143
|
+
this.contactReplayTimer = undefined;
|
|
2144
|
+
this.scheduleContactReplay();
|
|
2145
|
+
}, 15_000);
|
|
2146
|
+
this.contactReplayTimer.unref?.();
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
1839
2151
|
stopOwnerDirectoryRefresh() {
|
|
2152
|
+
if (this.contactReplayTimer)
|
|
2153
|
+
clearTimeout(this.contactReplayTimer);
|
|
2154
|
+
this.contactReplayTimer = undefined;
|
|
1840
2155
|
this.ownerDirectoryWatch?.stop();
|
|
1841
2156
|
this.ownerDirectoryWatch = undefined;
|
|
1842
2157
|
if (this.ownerDirectoryRetryTimer)
|
|
@@ -1866,6 +2181,7 @@ export class AUNChannel {
|
|
|
1866
2181
|
}),
|
|
1867
2182
|
};
|
|
1868
2183
|
this.queueOwnerDirectoryRefresh();
|
|
2184
|
+
this.scheduleContactReplay();
|
|
1869
2185
|
}
|
|
1870
2186
|
ownerDirectoryViewSignature(view) {
|
|
1871
2187
|
return JSON.stringify([
|
|
@@ -1982,6 +2298,8 @@ export class AUNChannel {
|
|
|
1982
2298
|
// the new cache implementation own storage and event synchronization.
|
|
1983
2299
|
const directory = path.join(this.agentDir, 'directory');
|
|
1984
2300
|
const cache = new OwnerDirectoryCache({
|
|
2301
|
+
onSnapshotApplied: () => { if (isCurrent())
|
|
2302
|
+
this.scheduleContactReplay(); },
|
|
1985
2303
|
onSnapshotApplying: snapshot => { if (isCurrent())
|
|
1986
2304
|
reconcileTemporaryContactGrants(selfAid, snapshot); },
|
|
1987
2305
|
relationVersion,
|
|
@@ -2382,11 +2700,13 @@ export class AUNChannel {
|
|
|
2382
2700
|
/** 本 agent 曾发出过的卡片 msgId(只增不删,用于区分"过期失效"vs"他人发的卡") */
|
|
2383
2701
|
ownedCardMsgIds = new Set();
|
|
2384
2702
|
ownedCardTopics = new Map();
|
|
2385
|
-
/** requestId → 已投递的卡片 message_id
|
|
2703
|
+
/** requestId → 已投递的卡片 message_id 集合(失效时清理交互映射,保留原消息) */
|
|
2386
2704
|
interactionCardMessageIds = new Map();
|
|
2387
|
-
/**
|
|
2705
|
+
/** 失效可能先于 outbox 卡片投递完成;迟到卡片不得重新启用交互。 */
|
|
2388
2706
|
invalidatedInteractions = new Map();
|
|
2389
2707
|
mentionModeResolver;
|
|
2708
|
+
/** Agent-level private-chat @ policy (`privateMentionMode`); unrelated to group mention policy. */
|
|
2709
|
+
privateMentionModeResolver;
|
|
2390
2710
|
/** Agent-level policy controlling whether group slash commands require structured mentions. */
|
|
2391
2711
|
groupSlashRequireMentionsResolver;
|
|
2392
2712
|
static PROACTIVE_ALLOW_TYPES = new Set([
|
|
@@ -2489,7 +2809,6 @@ export class AUNChannel {
|
|
|
2489
2809
|
if (this.config.pureIdentity && handlers)
|
|
2490
2810
|
return;
|
|
2491
2811
|
this.groupInviteHandler = handlers?.onInvite;
|
|
2492
|
-
this.groupInviteConnectedHandler = handlers?.onConnected;
|
|
2493
2812
|
this.groupInviteDeliveryGate = handlers?.canDeliver;
|
|
2494
2813
|
this.groupInviteDelivered = handlers?.onDelivered;
|
|
2495
2814
|
}
|
|
@@ -2511,13 +2830,11 @@ export class AUNChannel {
|
|
|
2511
2830
|
getGroupInviteDeliveryState(outboxId) {
|
|
2512
2831
|
return outbox.deliveryState(this.config.aid, outboxId);
|
|
2513
2832
|
}
|
|
2514
|
-
async invalidateGroupInviteCard(interactionId,
|
|
2515
|
-
const known = new Set(this.interactionCardMessageIds.get(interactionId) ?? []);
|
|
2833
|
+
async invalidateGroupInviteCard(interactionId, _ownerAid, messageIds) {
|
|
2516
2834
|
await this.invalidateInteraction(interactionId, 'group_invite_review');
|
|
2517
2835
|
// After a daemon restart only the review store knows the delivered cards.
|
|
2518
2836
|
for (const id of messageIds) {
|
|
2519
|
-
|
|
2520
|
-
await this.recallInteractionCard(id, ownerAid, { chatType: 'private' });
|
|
2837
|
+
this.forgetInteractionCard(id, interactionId);
|
|
2521
2838
|
}
|
|
2522
2839
|
}
|
|
2523
2840
|
refreshGroupInviteMembership(groupId) {
|
|
@@ -2610,7 +2927,6 @@ export class AUNChannel {
|
|
|
2610
2927
|
// An explicit new attempt retires the previous gateway's terminal decision.
|
|
2611
2928
|
this.setAidStatus('reconnecting', { lastAttemptAt: Date.now() });
|
|
2612
2929
|
this.stopOwnerDirectoryRefresh();
|
|
2613
|
-
this.configuredOwnerBindEpoch++;
|
|
2614
2930
|
this.observerGroupMembers.clear();
|
|
2615
2931
|
for (const groupId of new Set([
|
|
2616
2932
|
...this.observerGroupMembershipEpoch.keys(),
|
|
@@ -2680,8 +2996,6 @@ export class AUNChannel {
|
|
|
2680
2996
|
throw this.initializationCancelled();
|
|
2681
2997
|
}
|
|
2682
2998
|
this.client = client;
|
|
2683
|
-
const localConfig = loadAgent(aidName);
|
|
2684
|
-
ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
|
|
2685
2999
|
ownerResolver.attachClient(aidName, client);
|
|
2686
3000
|
registerSameOwnerClient(aidName, client, store);
|
|
2687
3001
|
try {
|
|
@@ -2696,6 +3010,30 @@ export class AUNChannel {
|
|
|
2696
3010
|
// instance must not mutate the new instance's health or message state.
|
|
2697
3011
|
const isCurrentClient = () => this.client === client
|
|
2698
3012
|
&& generation === this.reconnectGeneration && !this.intentionalDisconnect;
|
|
3013
|
+
const completeControlAgentMd = () => {
|
|
3014
|
+
if (!this.config.pureIdentity || !this.connected || !isCurrentClient())
|
|
3015
|
+
return;
|
|
3016
|
+
void ensureControlAgentMd(aidName, {
|
|
3017
|
+
store,
|
|
3018
|
+
aunPath,
|
|
3019
|
+
cacheRoot: resolveRoot(),
|
|
3020
|
+
}).then(result => {
|
|
3021
|
+
if (!isCurrentClient())
|
|
3022
|
+
return;
|
|
3023
|
+
this._selfName = result.name;
|
|
3024
|
+
this.aidStatsCollector?.setSelfName(this.config.aid, result.name);
|
|
3025
|
+
if (result.published)
|
|
3026
|
+
logger.info(`${this.logPrefix()} 控制 AID agent.md 已发布: ${result.name}`);
|
|
3027
|
+
}).catch(error => {
|
|
3028
|
+
if (!isCurrentClient())
|
|
3029
|
+
return;
|
|
3030
|
+
if (error?.code === 'CONTROL_OWNER_REQUIRED') {
|
|
3031
|
+
logger.info(`${this.logPrefix()} 控制 AID agent.md 暂缓补全:等待归属名片就绪(名片更新或重连后重试)`);
|
|
3032
|
+
return;
|
|
3033
|
+
}
|
|
3034
|
+
logger.warn(`${this.logPrefix()} 控制 AID agent.md 补全失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
3035
|
+
});
|
|
3036
|
+
};
|
|
2699
3037
|
// Register event handlers before connecting
|
|
2700
3038
|
client.on('agentmd.changed', (data) => {
|
|
2701
3039
|
if (!isCurrentClient() || this.intentionalDisconnect || typeof data !== 'string')
|
|
@@ -2724,11 +3062,14 @@ export class AUNChannel {
|
|
|
2724
3062
|
this.serviceRouter.ensureStarted(identity);
|
|
2725
3063
|
this.serviceRouter.reload();
|
|
2726
3064
|
}
|
|
2727
|
-
void refreshAgentDisplayName(aid).then(name => {
|
|
2728
|
-
if (!
|
|
3065
|
+
void refreshAgentDisplayName(aid, { store, aunPath }).then(name => {
|
|
3066
|
+
if (!isCurrentClient())
|
|
2729
3067
|
return;
|
|
2730
|
-
|
|
2731
|
-
|
|
3068
|
+
if (name) {
|
|
3069
|
+
this._selfName = name;
|
|
3070
|
+
this.aidStatsCollector?.setSelfName(this.config.aid, name);
|
|
3071
|
+
}
|
|
3072
|
+
completeControlAgentMd();
|
|
2732
3073
|
});
|
|
2733
3074
|
}
|
|
2734
3075
|
});
|
|
@@ -2929,19 +3270,6 @@ export class AUNChannel {
|
|
|
2929
3270
|
// Service/Gateway 故障不能把控制通道判定为连接失败。
|
|
2930
3271
|
if (this.config.pureIdentity) {
|
|
2931
3272
|
this._selfName = buildControlAgentName(aidName);
|
|
2932
|
-
void ensureControlAgentMd(aidName, {
|
|
2933
|
-
store: this.store ?? undefined,
|
|
2934
|
-
aunPath,
|
|
2935
|
-
cacheRoot: resolveRoot(),
|
|
2936
|
-
})
|
|
2937
|
-
.then(result => {
|
|
2938
|
-
this._selfName = result.name;
|
|
2939
|
-
if (this.aidStatsCollector)
|
|
2940
|
-
this.aidStatsCollector.setSelfName(this.config.aid, result.name);
|
|
2941
|
-
if (result.published)
|
|
2942
|
-
logger.info(`${this.logPrefix()} 控制 AID agent.md 已发布: ${result.name}`);
|
|
2943
|
-
})
|
|
2944
|
-
.catch(error => logger.warn(`${this.logPrefix()} 控制 AID agent.md 补全失败(后台重试): ${error instanceof Error ? error.message : String(error)}`));
|
|
2945
3273
|
}
|
|
2946
3274
|
else {
|
|
2947
3275
|
this._selfName = this.loadSelfName(aidName, aunPath);
|
|
@@ -2951,13 +3279,18 @@ export class AUNChannel {
|
|
|
2951
3279
|
this.connected = true;
|
|
2952
3280
|
this.connectedAt = Date.now();
|
|
2953
3281
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
2954
|
-
|
|
3282
|
+
completeControlAgentMd();
|
|
2955
3283
|
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
2956
3284
|
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
2957
3285
|
if (!this.config.pureIdentity) {
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
3286
|
+
// Move local pack/index initialization off the first Owner projection
|
|
3287
|
+
// request. The cached router is reused across reconnects.
|
|
3288
|
+
try {
|
|
3289
|
+
this.ensureServiceRouter();
|
|
3290
|
+
}
|
|
3291
|
+
catch (error) {
|
|
3292
|
+
logger.warn(`${this.logPrefix()} Service warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3293
|
+
}
|
|
2961
3294
|
}
|
|
2962
3295
|
logger.debug(`${this.logPrefix()} connect() completed as ${this._aid}; awaiting connection.state for lifecycle log`);
|
|
2963
3296
|
this.startOwnerDirectoryRefresh();
|
|
@@ -3126,10 +3459,16 @@ export class AUNChannel {
|
|
|
3126
3459
|
const rawAttachments = preCollected ?? this.collectAllAttachments(payload);
|
|
3127
3460
|
const images = [];
|
|
3128
3461
|
let finalText = baseText;
|
|
3462
|
+
let logText = baseText;
|
|
3129
3463
|
if (rawAttachments.length === 0 || !this.client) {
|
|
3130
|
-
return { finalText, images };
|
|
3464
|
+
return { finalText, logText, images };
|
|
3131
3465
|
}
|
|
3466
|
+
// 两套正文:
|
|
3467
|
+
// - finalText:绝对路径。本轮直接给模型用,Read 工具要能立刻读到。
|
|
3468
|
+
// - logText:`$EVOLCORE_HOME/...` 可迁移路径。写进 messages.jsonl,
|
|
3469
|
+
// 换机器/换盘符后仍能被展开成当时的正确绝对路径。
|
|
3132
3470
|
const fileParts = [];
|
|
3471
|
+
const logFileParts = [];
|
|
3133
3472
|
for (const att of rawAttachments) {
|
|
3134
3473
|
const attachmentBuffer = await this.downloadAttachment(att, channelId, delivery);
|
|
3135
3474
|
if (!attachmentBuffer)
|
|
@@ -3144,41 +3483,49 @@ export class AUNChannel {
|
|
|
3144
3483
|
catch { /* read failed, treat as non-image file */ }
|
|
3145
3484
|
if (img) {
|
|
3146
3485
|
try {
|
|
3147
|
-
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType);
|
|
3486
|
+
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType, { filename: name, direction: 'in' });
|
|
3148
3487
|
img = { ...img, attachmentId: attachment.attachmentId, localPath: attachment.filePath };
|
|
3149
|
-
//
|
|
3488
|
+
// 和非图片文件一样,把落盘路径放进消息正文,模型可直接用这个路径读文件或传给命令
|
|
3150
3489
|
fileParts.push(`[图片: ${name} → ${attachment.filePath}]`);
|
|
3490
|
+
logFileParts.push(`[图片: ${name} → ${toAttachmentMarkedPath(this.config.aid, attachment.filePath)}]`);
|
|
3151
3491
|
}
|
|
3152
3492
|
catch (error) {
|
|
3153
3493
|
logger.warn(`${this.logPrefix()} Failed to persist relation attachment for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3154
3494
|
}
|
|
3155
3495
|
images.push(img);
|
|
3156
|
-
//
|
|
3496
|
+
// 图片已注入视觉通道;落盘路径写进消息正文,模型用该路径读文件或传给命令
|
|
3157
3497
|
}
|
|
3158
3498
|
else {
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
: process.cwd();
|
|
3499
|
+
// 非图片文件同样进关系级附件目录:与图片统一落点,
|
|
3500
|
+
// 换机器时只要搬 $EVOLCORE_HOME,历史里引用的文件都还在。
|
|
3162
3501
|
try {
|
|
3163
|
-
const
|
|
3164
|
-
fileParts.push(`[文件: ${name} → ${
|
|
3502
|
+
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), att.content_type || att.mime_type || 'application/octet-stream', { filename: name, allowAnyExtension: true, direction: 'in' });
|
|
3503
|
+
fileParts.push(`[文件: ${name} → ${attachment.filePath}]`);
|
|
3504
|
+
logFileParts.push(`[文件: ${name} → ${toAttachmentMarkedPath(this.config.aid, attachment.filePath)}]`);
|
|
3165
3505
|
}
|
|
3166
3506
|
catch (error) {
|
|
3167
|
-
logger.warn(`${this.logPrefix()}
|
|
3507
|
+
logger.warn(`${this.logPrefix()} Failed to persist relation file for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3168
3508
|
}
|
|
3169
3509
|
}
|
|
3170
3510
|
}
|
|
3171
3511
|
const parts = [];
|
|
3172
|
-
|
|
3512
|
+
const logParts = [];
|
|
3513
|
+
if (baseText) {
|
|
3173
3514
|
parts.push(baseText);
|
|
3515
|
+
logParts.push(baseText);
|
|
3516
|
+
}
|
|
3174
3517
|
if (fileParts.length > 0) {
|
|
3175
3518
|
parts.push(...fileParts);
|
|
3176
3519
|
parts.push('请使用 Read 工具读取文件内容。');
|
|
3520
|
+
logParts.push(...logFileParts);
|
|
3521
|
+
logParts.push('请使用 Read 工具读取文件内容。');
|
|
3177
3522
|
}
|
|
3178
3523
|
if (parts.length > 0)
|
|
3179
3524
|
finalText = parts.join('\n\n');
|
|
3525
|
+
if (logParts.length > 0)
|
|
3526
|
+
logText = logParts.join('\n\n');
|
|
3180
3527
|
logger.info(`${this.logPrefix()} [attachments] count=${rawAttachments.length} images=${images.length} files=${fileParts.length}`);
|
|
3181
|
-
return { finalText, images };
|
|
3528
|
+
return { finalText, logText, images };
|
|
3182
3529
|
}
|
|
3183
3530
|
async downloadAttachmentWithRetry(url, filename, source, download) {
|
|
3184
3531
|
const host = attachmentDownloadHost(url);
|
|
@@ -3360,11 +3707,101 @@ export class AUNChannel {
|
|
|
3360
3707
|
}
|
|
3361
3708
|
}
|
|
3362
3709
|
ownerDirectoryRelationVersion;
|
|
3710
|
+
/** One notification for one isolated source: a contextual card replaces the generic request. */
|
|
3711
|
+
async notifyContactIntroduction(fromAid, payload, messageId, source, binding) {
|
|
3712
|
+
const selfAid = this.config.aid;
|
|
3713
|
+
const introduction = contactIntroductionText(payload);
|
|
3714
|
+
const reason = source.reason;
|
|
3715
|
+
if (source.notified || introduction === undefined || !['not_in_contacts', 'scope_extension'].includes(reason ?? '')
|
|
3716
|
+
|| !sameContactBinding(source.binding ?? {}, binding))
|
|
3717
|
+
return;
|
|
3718
|
+
if (!source.notificationReady) {
|
|
3719
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid))
|
|
3720
|
+
return;
|
|
3721
|
+
source = saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notificationReady: true });
|
|
3722
|
+
}
|
|
3723
|
+
const pending = readPendingContactInbound(selfAid, contactInboundKey(selfAid, fromAid, messageId));
|
|
3724
|
+
if (pending && (!pending.message || !['waiting', 'transferring'].includes(pending.state)))
|
|
3725
|
+
return;
|
|
3726
|
+
const match = pending?.approval ? { defer: false, origin: pending.approval }
|
|
3727
|
+
: findContactThreadDelegation(selfAid, binding, fromAid, payload, source.at);
|
|
3728
|
+
if (match.defer)
|
|
3729
|
+
return;
|
|
3730
|
+
const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, reason);
|
|
3731
|
+
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
3732
|
+
if (remainingTtl <= 0)
|
|
3733
|
+
return;
|
|
3734
|
+
if (pending && match.origin && !pending.approval) {
|
|
3735
|
+
pending.approval = { ...match.origin, eventId: request.event_id };
|
|
3736
|
+
updatePendingContactInbound(pending);
|
|
3737
|
+
}
|
|
3738
|
+
const approval = pending?.approval;
|
|
3739
|
+
const sent = await this.sendContentPayload(binding.owner_aid, approval ? buildContactApprovalCard(request, approval) : request, {
|
|
3740
|
+
contentKind: approval ? 'card' : 'custom', dedupeKey: request.event_id,
|
|
3741
|
+
logText: approval ? '[friend.request.v1 action_card]' : '[friend.request.v1]',
|
|
3742
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true },
|
|
3743
|
+
...(approval ? { sessionId: approval.originSessionId, localTopicId: approval.originThreadId,
|
|
3744
|
+
...(isTopicThreadId(approval.originThreadId) ? { threadId: approval.originThreadId } : {}) } : {}) },
|
|
3745
|
+
...(approval && pending ? { postSend: { type: 'register_contact_approval_card',
|
|
3746
|
+
pendingKey: pending.key, eventId: request.event_id } } : {}),
|
|
3747
|
+
ttl: remainingTtl,
|
|
3748
|
+
});
|
|
3749
|
+
if (sent.messageId || sent.queued)
|
|
3750
|
+
saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
|
|
3751
|
+
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'}`);
|
|
3752
|
+
}
|
|
3753
|
+
/** Consume only daemon-owned, durable card bindings. This never invokes the interaction/model runner. */
|
|
3754
|
+
async handleContactApprovalReply(fromAid, payload, encrypted) {
|
|
3755
|
+
const cardId = payload.card_message_id ?? payload.ref_message_id;
|
|
3756
|
+
if (typeof cardId !== 'string' || !cardId)
|
|
3757
|
+
return false;
|
|
3758
|
+
const selfAid = this.config.aid;
|
|
3759
|
+
const card = readContactApprovalCard(selfAid, cardId);
|
|
3760
|
+
if (!card)
|
|
3761
|
+
return false;
|
|
3762
|
+
if (!encrypted || card.expiresAt <= Date.now())
|
|
3763
|
+
return true;
|
|
3764
|
+
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.card.reply' });
|
|
3765
|
+
const binding = verifiedContactBinding(selfAid, view);
|
|
3766
|
+
const pending = readPendingContactInbound(selfAid, card.pendingKey);
|
|
3767
|
+
if (!binding || fromAid !== binding.owner_aid || !pending?.message || !pending.approval
|
|
3768
|
+
|| !sameContactBinding(pending.binding, binding) || pending.approval.eventId !== card.eventId
|
|
3769
|
+
|| pending.expiresAt <= Date.now() || !['waiting', 'transferring'].includes(pending.state)
|
|
3770
|
+
|| this.contactReplayReceiptResolver?.(pending.key))
|
|
3771
|
+
return true;
|
|
3772
|
+
if (payload.thread_id !== undefined
|
|
3773
|
+
&& normalizeThreadIdForPeer(payload.thread_id, selfAid, fromAid) !== pending.approval.originThreadId)
|
|
3774
|
+
return true;
|
|
3775
|
+
if (payload.behavior !== undefined && payload.behavior !== 'reply')
|
|
3776
|
+
return true;
|
|
3777
|
+
const action = payload.action_value ?? payload.value ?? payload.text;
|
|
3778
|
+
if (action !== 'approve' && action !== 'reject')
|
|
3779
|
+
return true;
|
|
3780
|
+
if (pending.approval.response)
|
|
3781
|
+
return true;
|
|
3782
|
+
pending.approval.response = action;
|
|
3783
|
+
if (action === 'reject')
|
|
3784
|
+
finishPendingContactInbound(pending, 'rejected');
|
|
3785
|
+
else {
|
|
3786
|
+
updatePendingContactInbound(pending);
|
|
3787
|
+
// The click is a refresh hint. Only the independently verified contact snapshot grants admission.
|
|
3788
|
+
this.contactReplayReconcileAt = 0;
|
|
3789
|
+
this.scheduleContactReplay();
|
|
3790
|
+
}
|
|
3791
|
+
logger.info(`${this.logPrefix()} Contact approval card receipt: event=${card.eventId} action=${action}`);
|
|
3792
|
+
return true;
|
|
3793
|
+
}
|
|
3363
3794
|
/** Returns before any ordinary history, observer, attachment or model side effect. */
|
|
3364
|
-
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted) {
|
|
3795
|
+
async handleAppContactInbound(fromAid, payload, messageId, receivedAt, encrypted, message) {
|
|
3365
3796
|
const selfAid = this.config.aid;
|
|
3366
3797
|
const value = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : undefined;
|
|
3367
3798
|
const type = typeof value?.type === 'string' ? value.type : '';
|
|
3799
|
+
const pending = readPendingContactInbound(selfAid, contactInboundKey(selfAid, fromAid, messageId));
|
|
3800
|
+
if (pending) {
|
|
3801
|
+
this.scheduleContactReplay();
|
|
3802
|
+
if (!pending.message || pending.digest !== contactSourceDigest(payload))
|
|
3803
|
+
return true;
|
|
3804
|
+
}
|
|
3368
3805
|
const previous = isolatedContactSource(selfAid, fromAid, messageId);
|
|
3369
3806
|
const digest = contactSourceDigest(payload);
|
|
3370
3807
|
if (previous && (previous.notified || !previous.reason || contactIntroductionText(payload) === undefined
|
|
@@ -3372,14 +3809,14 @@ export class AUNChannel {
|
|
|
3372
3809
|
return true;
|
|
3373
3810
|
if (previous && !sameContactBinding(previous.binding, currentContactBinding(selfAid)))
|
|
3374
3811
|
return true;
|
|
3375
|
-
if (previous && !consumeContactIntroductionBudget(selfAid, fromAid))
|
|
3376
|
-
return true;
|
|
3377
3812
|
if (type.startsWith('friend.')) {
|
|
3378
3813
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.grant' });
|
|
3379
3814
|
const binding = verifiedContactBinding(selfAid, view);
|
|
3380
3815
|
if (!binding)
|
|
3381
3816
|
return true;
|
|
3382
3817
|
const result = executeContactGrant(selfAid, fromAid, payload, encrypted, Date.now(), binding);
|
|
3818
|
+
if (result?.status === 'applied')
|
|
3819
|
+
this.scheduleContactReplay();
|
|
3383
3820
|
if (result)
|
|
3384
3821
|
await this.sendContentPayload(fromAid, result, {
|
|
3385
3822
|
contentKind: 'custom', dedupeKey: `friend-result:${result.owner_aid}:${result.relation_version}:${result.type}:${result.grant_id}:${result.status}:${result.error_code ?? ''}`,
|
|
@@ -3395,14 +3832,25 @@ export class AUNChannel {
|
|
|
3395
3832
|
return true; // Retired App protocol; never create legacy pending.
|
|
3396
3833
|
if (type === 'text' && typeof value?.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text))
|
|
3397
3834
|
return false;
|
|
3398
|
-
//
|
|
3835
|
+
// A redelivered isolated source can only reenter through the durable replay worker.
|
|
3399
3836
|
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true, source: 'contact.inbound' });
|
|
3400
3837
|
await this.getOwnerDirectoryRuntime();
|
|
3401
3838
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3402
3839
|
const decision = evaluateAppContactAdmission(selfAid, fromAid);
|
|
3403
3840
|
logger.debug(`${this.logPrefix()} Contact admission: mid=${messageId} from=${fromAid} allow=${decision.allow} reason=${decision.reason} elapsedMs=${Math.max(0, Date.now() - receivedAt)}`);
|
|
3404
|
-
if (decision.allow && !previous)
|
|
3405
|
-
|
|
3841
|
+
if (decision.allow && !previous) {
|
|
3842
|
+
const backlog = message && contactIntroductionText(payload) !== undefined
|
|
3843
|
+
&& listPendingContactInbound(selfAid).some(record => record.fromAid === fromAid
|
|
3844
|
+
&& (record.message?.payload?.thread_id ?? '') === (value?.thread_id ?? ''));
|
|
3845
|
+
if (!backlog || !message)
|
|
3846
|
+
return false;
|
|
3847
|
+
const binding = currentContactBinding(selfAid);
|
|
3848
|
+
if (!binding)
|
|
3849
|
+
return true;
|
|
3850
|
+
savePendingContactInbound({ selfAid, fromAid, messageId, receivedAt, binding, message });
|
|
3851
|
+
this.scheduleContactReplay();
|
|
3852
|
+
return true;
|
|
3853
|
+
}
|
|
3406
3854
|
const introduction = contactIntroductionText(payload);
|
|
3407
3855
|
const binding = currentContactBinding(selfAid);
|
|
3408
3856
|
const reason = previous?.reason ?? decision.reason;
|
|
@@ -3410,32 +3858,46 @@ export class AUNChannel {
|
|
|
3410
3858
|
return true;
|
|
3411
3859
|
let source = previous ?? { at: receivedAt, digest, binding,
|
|
3412
3860
|
...(reason === 'not_in_contacts' || reason === 'scope_extension' ? { reason } : {}) };
|
|
3861
|
+
if (!previous && binding && message && introduction !== undefined
|
|
3862
|
+
&& (reason === 'not_in_contacts' || reason === 'scope_extension')) {
|
|
3863
|
+
savePendingContactInbound({ selfAid, fromAid, messageId, receivedAt, binding, message });
|
|
3864
|
+
this.scheduleContactReplay();
|
|
3865
|
+
}
|
|
3413
3866
|
// Write the tombstone before budgets, receipt capacity checks or any delivery.
|
|
3414
3867
|
if (!previous)
|
|
3415
3868
|
source = saveIsolatedContactSource(selfAid, fromAid, messageId, source);
|
|
3416
3869
|
if (source.notified || source.digest !== digest || !sameContactBinding(source.binding ?? {}, binding))
|
|
3417
3870
|
return true;
|
|
3418
3871
|
const eventReason = source.reason;
|
|
3419
|
-
if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')
|
|
3420
|
-
|
|
3421
|
-
const request = buildContactRequest(binding, fromAid, messageId, source.at, introduction, eventReason);
|
|
3422
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
3423
|
-
if (remainingTtl <= 0)
|
|
3424
|
-
return true;
|
|
3425
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3426
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1]',
|
|
3427
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
3428
|
-
ttl: remainingTtl,
|
|
3429
|
-
});
|
|
3430
|
-
if (sent.messageId || sent.queued)
|
|
3431
|
-
saveIsolatedContactSource(selfAid, fromAid, messageId, { ...source, notified: true });
|
|
3432
|
-
logger.info(`${this.logPrefix()} Contact introduction isolated: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3872
|
+
if (binding && introduction !== undefined && (eventReason === 'not_in_contacts' || eventReason === 'scope_extension')) {
|
|
3873
|
+
await this.notifyContactIntroduction(fromAid, payload, messageId, source, binding);
|
|
3433
3874
|
}
|
|
3434
3875
|
else {
|
|
3435
3876
|
logger.info(`${this.logPrefix()} Contact message isolated: mid=${messageId} reason=${decision.reason}`);
|
|
3436
3877
|
}
|
|
3437
3878
|
return true;
|
|
3438
3879
|
}
|
|
3880
|
+
/** Forward an invite to the Owner using a fresh target-Agent binding. */
|
|
3881
|
+
async forwardFriendInviteRequest(binding, invite, sourceMessageId, receivedAt, reason, proof, rawInvite) {
|
|
3882
|
+
const eventKey = proof
|
|
3883
|
+
? `proof:${proof.proof_id}:${friendInviteDigest(proof.invite)}:${proof.qr_proof.version}:${proof.qr_proof.token}`
|
|
3884
|
+
: invite.qr_proof ? `invite:${invite.invite_id}:${friendInviteDigest(invite)}` : `invite:${invite.invite_id}`;
|
|
3885
|
+
const request = {
|
|
3886
|
+
...buildContactRequest(binding, invite.applicant_aid, sourceMessageId, receivedAt, invite.introduction, reason, eventKey),
|
|
3887
|
+
// Keep the complete wire invite received from the App. In particular a
|
|
3888
|
+
// proof retry must retain the old nested qr_proof unchanged while the
|
|
3889
|
+
// wrapper's top-level qr_proof carries the fresh credential.
|
|
3890
|
+
invite: rawInvite ?? serializeFriendInvite(invite),
|
|
3891
|
+
...(proof ? { proof_id: proof.proof_id, qr_proof: proof.qr_proof } : {}),
|
|
3892
|
+
};
|
|
3893
|
+
const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, Math.max(1, invite.expires_at_ms - Date.now()));
|
|
3894
|
+
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3895
|
+
contentKind: 'custom', dedupeKey: request.event_id,
|
|
3896
|
+
logText: proof ? '[friend.request.v1 invite.proof]' : '[friend.request.v1 invite]',
|
|
3897
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
|
|
3898
|
+
});
|
|
3899
|
+
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'}`);
|
|
3900
|
+
}
|
|
3439
3901
|
/** friend.invite.v1 never reaches the model, ordinary history, attachments or observers. */
|
|
3440
3902
|
async handleFriendInvite(fromAid, payload, messageId, receivedAt, encrypted, seq) {
|
|
3441
3903
|
const selfAid = this.config.aid;
|
|
@@ -3467,6 +3929,17 @@ export class AUNChannel {
|
|
|
3467
3929
|
await this.sendFriendInviteResult(invite, decideFriendInvite(selfAid, binding, invite, 'expired'), messageId);
|
|
3468
3930
|
return;
|
|
3469
3931
|
}
|
|
3932
|
+
// A QR-backed invite is an Owner decision request. Core only authenticates
|
|
3933
|
+
// the sender/target and carries the proof through; it never verifies the
|
|
3934
|
+
// token or accepts the invite locally.
|
|
3935
|
+
if (invite.qr_proof) {
|
|
3936
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
|
|
3937
|
+
logger.info(`${this.logPrefix()} QR friend invite dropped: code=INTRODUCTION_BUDGET invite=${invite.invite_id} from=${fromAid}`);
|
|
3938
|
+
return;
|
|
3939
|
+
}
|
|
3940
|
+
await this.forwardFriendInviteRequest(binding, invite, messageId, receivedAt, 'not_in_contacts', undefined, isFriendInvitePayload(payload) ? payload : undefined);
|
|
3941
|
+
return;
|
|
3942
|
+
}
|
|
3470
3943
|
await this.getOwnerDirectoryRuntime();
|
|
3471
3944
|
await this.settleOwnerDirectoryBeforeTurn();
|
|
3472
3945
|
const verdict = await this.judgeFriendInvite(selfAid, fromAid);
|
|
@@ -3487,21 +3960,50 @@ export class AUNChannel {
|
|
|
3487
3960
|
return;
|
|
3488
3961
|
}
|
|
3489
3962
|
const reason = verdict.reason === 'scope_extension' ? 'scope_extension' : 'not_in_contacts';
|
|
3490
|
-
|
|
3491
|
-
...buildContactRequest(binding, fromAid, messageId, receivedAt, invite.introduction, reason, `invite:${invite.invite_id}`),
|
|
3492
|
-
invite: { type: FRIEND_INVITE_TYPE, schema_version: 1, ...invite },
|
|
3493
|
-
};
|
|
3494
|
-
const remainingTtl = Math.min(CONTACT_EVENT_TTL_MS, invite.expires_at_ms - Date.now());
|
|
3495
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
3496
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 invite]',
|
|
3497
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } }, ttl: remainingTtl,
|
|
3498
|
-
});
|
|
3499
|
-
logger.info(`${this.logPrefix()} Friend invite forwarded to Owner: event=${request.event_id} state=${sent.messageId ? 'transport_accepted' : sent.queued ? 'queued' : 'failed'} code=${sent.code ?? 'none'}`);
|
|
3963
|
+
await this.forwardFriendInviteRequest(binding, invite, messageId, receivedAt, reason, undefined, isFriendInvitePayload(payload) ? payload : undefined);
|
|
3500
3964
|
}
|
|
3501
3965
|
catch (error) {
|
|
3502
3966
|
logger.warn(`${this.logPrefix()} Friend invite isolated: code=CONTACT_STATE_UNAVAILABLE invite=${invite.invite_id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3503
3967
|
}
|
|
3504
3968
|
}
|
|
3969
|
+
/**
|
|
3970
|
+
* A queued invite can be retried with a durable QR proof package. It follows
|
|
3971
|
+
* the same authenticated Owner route as a live QR invite, but never enters
|
|
3972
|
+
* local admission/decision code or the model.
|
|
3973
|
+
*/
|
|
3974
|
+
async handleFriendInviteProof(fromAid, payload, messageId, receivedAt, encrypted, seq) {
|
|
3975
|
+
const selfAid = this.config.aid;
|
|
3976
|
+
this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, encrypted, false, classifyAunPayloadForLog(payload), undefined, receivedAt, seq);
|
|
3977
|
+
const proof = parseFriendInviteProof(payload, fromAid, selfAid);
|
|
3978
|
+
if (!proof || !encrypted) {
|
|
3979
|
+
logger.info(`${this.logPrefix()} Friend invite proof ignored: code=INVALID_FRIEND_INVITE_PROOF from=${fromAid} mid=${messageId} encrypted=${encrypted}`);
|
|
3980
|
+
return;
|
|
3981
|
+
}
|
|
3982
|
+
if (proof.invite.expires_at_ms <= Date.now()) {
|
|
3983
|
+
logger.info(`${this.logPrefix()} Friend invite proof ignored: code=FRIEND_INVITE_EXPIRED proof=${proof.proof_id} from=${fromAid}`);
|
|
3984
|
+
return;
|
|
3985
|
+
}
|
|
3986
|
+
try {
|
|
3987
|
+
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.invite.proof' });
|
|
3988
|
+
const binding = verifiedContactBinding(selfAid, view);
|
|
3989
|
+
if (!binding) {
|
|
3990
|
+
logger.info(`${this.logPrefix()} Friend invite proof deferred: code=CONTACT_OWNERSHIP_UNAVAILABLE proof=${proof.proof_id} from=${fromAid}`);
|
|
3991
|
+
return;
|
|
3992
|
+
}
|
|
3993
|
+
if (!consumeContactIntroductionBudget(selfAid, fromAid)) {
|
|
3994
|
+
logger.info(`${this.logPrefix()} Friend invite proof dropped: code=INTRODUCTION_BUDGET proof=${proof.proof_id} from=${fromAid}`);
|
|
3995
|
+
return;
|
|
3996
|
+
}
|
|
3997
|
+
const rawProofPayload = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
3998
|
+
? payload : undefined;
|
|
3999
|
+
const rawInvite = rawProofPayload?.invite && typeof rawProofPayload.invite === 'object' && !Array.isArray(rawProofPayload.invite)
|
|
4000
|
+
? rawProofPayload.invite : undefined;
|
|
4001
|
+
await this.forwardFriendInviteRequest(binding, proof.invite, messageId, receivedAt, 'not_in_contacts', proof, rawInvite);
|
|
4002
|
+
}
|
|
4003
|
+
catch (error) {
|
|
4004
|
+
logger.warn(`${this.logPrefix()} Friend invite proof isolated: code=CONTACT_STATE_UNAVAILABLE proof=${proof.proof_id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
4005
|
+
}
|
|
4006
|
+
}
|
|
3505
4007
|
/**
|
|
3506
4008
|
* Friend invites use the same app-v1 decision as ordinary private messages.
|
|
3507
4009
|
*/
|
|
@@ -3531,11 +4033,13 @@ export class AUNChannel {
|
|
|
3531
4033
|
if (sent.messageId || sent.queued)
|
|
3532
4034
|
markFriendInviteWelcomed(this.config.aid, binding, invite.invite_id);
|
|
3533
4035
|
}
|
|
3534
|
-
async handleIncomingPrivateMessage(data) {
|
|
4036
|
+
async handleIncomingPrivateMessage(data, contactDelivery) {
|
|
3535
4037
|
if (!data || typeof data !== 'object')
|
|
3536
4038
|
return;
|
|
3537
4039
|
const msg = data;
|
|
3538
|
-
|
|
4040
|
+
if (contactDelivery)
|
|
4041
|
+
contactDelivery.validate();
|
|
4042
|
+
const receivedAt = contactDelivery?.receivedAt ?? Date.now();
|
|
3539
4043
|
const receivedAtMono = performance.now();
|
|
3540
4044
|
// Validate the authenticated envelope before any payload extraction or
|
|
3541
4045
|
// command parsing. Retransmits may carry a new seq, but the application
|
|
@@ -3601,13 +4105,60 @@ export class AUNChannel {
|
|
|
3601
4105
|
logger.debug(`${this.logPrefix()} P2P dropped: pubsub control envelope (mid=${messageId})`);
|
|
3602
4106
|
return;
|
|
3603
4107
|
}
|
|
4108
|
+
// Ability replies belong to an authenticated protocol request, not a
|
|
4109
|
+
// conversation contact. Match them before chat admission/observers;
|
|
4110
|
+
// unmatched or spoofed protocol replies never become model input.
|
|
4111
|
+
const abilityReply = msg.payload && typeof msg.payload === 'object' && !Array.isArray(msg.payload)
|
|
4112
|
+
&& msg.payload.type === 'ability' && ['ack', 'result'].includes(String(msg.payload.role));
|
|
4113
|
+
if (abilityReply) {
|
|
4114
|
+
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4115
|
+
return;
|
|
4116
|
+
const matched = getAunRequestRegistry().resolveIncoming({
|
|
4117
|
+
selfAid: this._aid || this.config.aid, fromAid,
|
|
4118
|
+
fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
|
|
4119
|
+
messageId, payload: msg.payload, encrypted: !!env.encrypted, transport: 'p2p',
|
|
4120
|
+
});
|
|
4121
|
+
if (!matched)
|
|
4122
|
+
logger.debug(`${this.logPrefix()} Unmatched Ability reply: mid=${messageId} from=${fromAid}`);
|
|
4123
|
+
return;
|
|
4124
|
+
}
|
|
3604
4125
|
if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
3605
4126
|
return;
|
|
3606
4127
|
const protectedHeaders = verifiedProtectedHeaders(msg, env);
|
|
3607
4128
|
const payload = msg.payload ?? '';
|
|
4129
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4130
|
+
await this.handleWidgetCardReply(payload, fromAid, fromAid, { chatType: 'private' }, messageId, !!env.encrypted);
|
|
4131
|
+
return;
|
|
4132
|
+
}
|
|
4133
|
+
// Payment controls have durable business mappings and must precede the
|
|
4134
|
+
// generic one-shot card consumer, observers, attachments and model input.
|
|
4135
|
+
try {
|
|
4136
|
+
if (!this.config.pureIdentity && await consumePaymentInbound(this.config.aid, fromAid, payload, !!env.encrypted))
|
|
4137
|
+
return;
|
|
4138
|
+
}
|
|
4139
|
+
catch (error) {
|
|
4140
|
+
const code = error?.code ?? 'UNKNOWN';
|
|
4141
|
+
logger.warn(`${this.logPrefix()} Payment inbound isolated: code=${code}; continuing normal message handling`);
|
|
4142
|
+
}
|
|
4143
|
+
const menuRequest = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
4144
|
+
&& ['menu.list', 'menu.query', 'menu.options', 'menu.update', 'menu.action', 'menu.token.request'].includes(payload.type)
|
|
4145
|
+
? payload : undefined;
|
|
4146
|
+
const menuContext = {
|
|
4147
|
+
source: appOwned ? 'agent-aun' : 'control-aun',
|
|
4148
|
+
selfAid: this.config.aid, requesterAid: fromAid, messageId,
|
|
4149
|
+
};
|
|
4150
|
+
const menuTiming = { receivedAt, receivedAtMono };
|
|
3608
4151
|
// Credential answers must be consumed before contact/request persistence,
|
|
3609
4152
|
// observer forwarding or generic message logging. Card binding is server-owned.
|
|
3610
4153
|
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
4154
|
+
try {
|
|
4155
|
+
if (await this.handleContactApprovalReply(fromAid, payload, !!env.encrypted))
|
|
4156
|
+
return;
|
|
4157
|
+
}
|
|
4158
|
+
catch {
|
|
4159
|
+
logger.warn(`${this.logPrefix()} Contact card receipt isolated: code=CONTACT_STATE_UNAVAILABLE`);
|
|
4160
|
+
return;
|
|
4161
|
+
}
|
|
3611
4162
|
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
3612
4163
|
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
3613
4164
|
if (!card || card.sensitive) {
|
|
@@ -3625,11 +4176,17 @@ export class AUNChannel {
|
|
|
3625
4176
|
await this.handleFriendInvite(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
|
|
3626
4177
|
return;
|
|
3627
4178
|
}
|
|
4179
|
+
if (!this.config.pureIdentity && isFriendInviteProofPayload(payload)) {
|
|
4180
|
+
if (appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
4181
|
+
return;
|
|
4182
|
+
await this.handleFriendInviteProof(fromAid, payload, messageId, receivedAt, !!env.encrypted, seq);
|
|
4183
|
+
return;
|
|
4184
|
+
}
|
|
3628
4185
|
const contactControl = appOwned && isContactControlPayload(payload);
|
|
3629
4186
|
if (appOwned) {
|
|
3630
4187
|
let handled;
|
|
3631
4188
|
try {
|
|
3632
|
-
handled = await this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted);
|
|
4189
|
+
handled = await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.contact-admission', () => contactDelivery ? Promise.resolve(false) : this.handleAppContactInbound(fromAid, payload, messageId, receivedAt, !!env.encrypted, msg));
|
|
3633
4190
|
}
|
|
3634
4191
|
catch {
|
|
3635
4192
|
// Storage/lock/capacity/conflict failures remain isolated; log metadata only.
|
|
@@ -3646,7 +4203,7 @@ export class AUNChannel {
|
|
|
3646
4203
|
}
|
|
3647
4204
|
if (handled)
|
|
3648
4205
|
return;
|
|
3649
|
-
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4206
|
+
if (!contactDelivery && !this.claimInboundMessage('private', messageId, seq))
|
|
3650
4207
|
return;
|
|
3651
4208
|
if (contactControl)
|
|
3652
4209
|
this.rememberContactControlRequest(fromAid, payload, messageId, menuSenderDeviceId(msg.sender_device_id));
|
|
@@ -3719,7 +4276,7 @@ export class AUNChannel {
|
|
|
3719
4276
|
// forwardInbound 内部排除 self-echo 与 from-owner。
|
|
3720
4277
|
// 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
|
|
3721
4278
|
// (即便日后 from-owner 排除规则调整,也不会泄漏)。
|
|
3722
|
-
if (!contactControl && inboundType !== 'action_card_reply'
|
|
4279
|
+
if (!contactDelivery && !contactControl && inboundType !== 'action_card_reply'
|
|
3723
4280
|
&& (typeof inboundType !== 'string' || !inboundType.startsWith('observer.inject'))) {
|
|
3724
4281
|
void this.forwardInbound(msg);
|
|
3725
4282
|
}
|
|
@@ -3747,15 +4304,29 @@ export class AUNChannel {
|
|
|
3747
4304
|
// sender omitted payload.mentions; keep that compatibility signal.
|
|
3748
4305
|
mentions.push({ aid: this._aid });
|
|
3749
4306
|
}
|
|
4307
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4308
|
+
// 同 AID 其它设备发来的消息(self-sync)也按已提及处理,与群聊 handoff 的口径一致:
|
|
4309
|
+
// 这类记录不是「别人对我说话」,不该被提及过滤挡掉。
|
|
4310
|
+
const addressedInPrivate = (!!this._aid
|
|
4311
|
+
&& (mentionEntryTargets(mentions).includes(this._aid) || hasMentionAll(mentions)))
|
|
4312
|
+
|| (!!this._aid && fromAid === this._aid);
|
|
3750
4313
|
// Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
|
|
3751
|
-
const { finalText,
|
|
4314
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = contactControl
|
|
4315
|
+
? { finalText: text, logText: text, images: [] }
|
|
4316
|
+
: await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.attachments', () => this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' }));
|
|
4317
|
+
// 历史记录正文用 logText(`$AGENT_DIR/attachments/...` 别名路径),不用 finalText:
|
|
4318
|
+
// finalText 是本回合给模型的绝对路径,写进历史后换机器/换盘符就失效。
|
|
4319
|
+
// 用 logDescriptor.content 又会把路径丢掉,读历史的一方只能看到 `[image] 文件名`。
|
|
4320
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4321
|
+
? attachmentLogText
|
|
4322
|
+
: (inboundImages.length > 0 || attachmentLogText !== text ? attachmentLogText : logDescriptor.content);
|
|
3752
4323
|
// 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
|
|
3753
4324
|
// device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
|
|
3754
4325
|
const chatId = fromAid;
|
|
3755
4326
|
// 解析对端身份(30天缓存)
|
|
3756
4327
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
3757
|
-
const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
3758
|
-
await prepareSameOwnerProof(this.config.aid, fromAid);
|
|
4328
|
+
const peerIdentity = await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.peer-identity', () => PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot()));
|
|
4329
|
+
await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.same-owner-proof', () => prepareSameOwnerProof(this.config.aid, fromAid));
|
|
3759
4330
|
const shortAid = this.getShortAid(fromAid);
|
|
3760
4331
|
const displayName = this.inboundDisplayName(fromAid, peerIdentity.name, shortAid);
|
|
3761
4332
|
// 详细 dispatch 决策日志:记录消息为何被路由到 agent
|
|
@@ -3857,17 +4428,42 @@ export class AUNChannel {
|
|
|
3857
4428
|
logger.info(`${this.logPrefix()} P2P retained in generic inbound event stream (not Agent chat): type=${p2pPayloadType} from=${shortAid}(${displayName}) mid=${messageId}`);
|
|
3858
4429
|
return;
|
|
3859
4430
|
}
|
|
4431
|
+
// ── 私聊提及模式(privateMentionMode,仅 Agent 级、Owner 可改)──
|
|
4432
|
+
// 判定放在所有控制类 payload 的 return 之后、真正 dispatch 之前:
|
|
4433
|
+
// menu.* / bind.request / observer.inject / event / 白名单外类型都已在上方返回,
|
|
4434
|
+
// 走到这里的一定是普通对话消息。
|
|
4435
|
+
// 与群聊 mentionMode 完全独立:只看 Agent 级 privateMentionMode,
|
|
4436
|
+
// 不读服务器 mention_mode,也不读关系级配置。
|
|
4437
|
+
if (await this.resolvePrivateMentionMode() === 'mention-only'
|
|
4438
|
+
// 联系人补投必须处理。
|
|
4439
|
+
&& !contactDelivery
|
|
4440
|
+
// echo 探针走独立 trace 流程,不参与提及过滤。
|
|
4441
|
+
&& echoProbeKind(text) === null
|
|
4442
|
+
// slash 命令不拦,与群聊 mention-only 的语义保持一致。
|
|
4443
|
+
&& !/^\s*\//.test(text)
|
|
4444
|
+
&& !addressedInPrivate) {
|
|
4445
|
+
// 先落盘再丢弃:写失败必须抛出,绝不能静默吞掉消息。
|
|
4446
|
+
this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq, undefined, undefined, 'filtered-mention-only', loggedContent);
|
|
4447
|
+
logger.info(`${this.logPrefix()} P2P dropped: private mention-only (from=${fromAid} mid=${messageId} textPreview=${JSON.stringify(logPreview(text))})`);
|
|
4448
|
+
return;
|
|
4449
|
+
}
|
|
3860
4450
|
const msgChatmode = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
3861
4451
|
logger.info(`${this.logPrefix()} message.route: decision=dispatch chatType=private from=${shortAid}(${displayName}) mid=${messageId} payloadType=${p2pPayloadType || 'text'} encrypt=${msgEncrypted} chatmode=${msgChatmode ?? 'none'} textPreview=${JSON.stringify(logPreview(finalText))}`);
|
|
3862
4452
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
|
|
3863
4453
|
const isSystemP2P = p2pPayloadType === 'event';
|
|
3864
4454
|
this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
|
|
3865
4455
|
const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicStatus(payload));
|
|
3866
|
-
this.dispatchMessage({
|
|
4456
|
+
const dispatched = this.dispatchMessage({
|
|
4457
|
+
contactDelivery,
|
|
3867
4458
|
channelId: chatId,
|
|
3868
4459
|
userId: fromAid,
|
|
3869
|
-
text
|
|
4460
|
+
// Control text commands must use the original payload, never quote/attachment rendering.
|
|
4461
|
+
text: this.config.pureIdentity && p2pPayloadType === 'text'
|
|
4462
|
+
? (typeof payload.text === 'string' ? payload.text : '') : finalText,
|
|
3870
4463
|
chatType: 'private',
|
|
4464
|
+
...(p2pPayloadType === 'text' ? {
|
|
4465
|
+
peerDeviceId: menuSenderDeviceId(msg.sender_device_id),
|
|
4466
|
+
} : {}),
|
|
3871
4467
|
messageId,
|
|
3872
4468
|
receivedAt,
|
|
3873
4469
|
createdAt: typeof msg.created_at === 'number' ? msg.created_at : undefined,
|
|
@@ -3876,6 +4472,8 @@ export class AUNChannel {
|
|
|
3876
4472
|
seq,
|
|
3877
4473
|
threadId,
|
|
3878
4474
|
mentions,
|
|
4475
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4476
|
+
isMentioned: addressedInPrivate,
|
|
3879
4477
|
peerName: displayName || undefined,
|
|
3880
4478
|
peerType: peerIdentity.type,
|
|
3881
4479
|
peerExttype: peerIdentity.exttype,
|
|
@@ -3889,8 +4487,10 @@ export class AUNChannel {
|
|
|
3889
4487
|
msgType: logDescriptor.msgType,
|
|
3890
4488
|
payloadType: logDescriptor.payloadType,
|
|
3891
4489
|
payloadSummary: logDescriptor.payloadSummary,
|
|
3892
|
-
messageLogContent:
|
|
4490
|
+
messageLogContent: loggedContent,
|
|
3893
4491
|
});
|
|
4492
|
+
if (contactDelivery)
|
|
4493
|
+
await dispatched;
|
|
3894
4494
|
}
|
|
3895
4495
|
async handleIncomingGroupMessage(data) {
|
|
3896
4496
|
if (!data || typeof data !== 'object')
|
|
@@ -3910,6 +4510,10 @@ export class AUNChannel {
|
|
|
3910
4510
|
const groupId = env.group_id ?? '';
|
|
3911
4511
|
const senderAid = env.from ?? '';
|
|
3912
4512
|
const payload = msg.payload ?? '';
|
|
4513
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4514
|
+
await this.handleWidgetCardReply(payload, groupId, senderAid, { chatType: 'group', groupId }, messageId, !!env.encrypted);
|
|
4515
|
+
return;
|
|
4516
|
+
}
|
|
3913
4517
|
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
3914
4518
|
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
3915
4519
|
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
@@ -3994,7 +4598,7 @@ export class AUNChannel {
|
|
|
3994
4598
|
const createdAt = data.created_at;
|
|
3995
4599
|
if (!peerInfo)
|
|
3996
4600
|
this.prefetchPeerInfo(senderAid);
|
|
3997
|
-
this.handleEcho({
|
|
4601
|
+
void this.handleEcho({
|
|
3998
4602
|
channelId: groupId,
|
|
3999
4603
|
userId: senderAid,
|
|
4000
4604
|
text,
|
|
@@ -4005,7 +4609,7 @@ export class AUNChannel {
|
|
|
4005
4609
|
seq,
|
|
4006
4610
|
replyContext: this.buildGroupReplyContext(threadId, senderAid, msgEncryptedFast, messageId, msgChatmodeFast, topicName, groupId, readTopicStatus(payload)),
|
|
4007
4611
|
createdAt,
|
|
4008
|
-
});
|
|
4612
|
+
}).catch(() => { });
|
|
4009
4613
|
return;
|
|
4010
4614
|
}
|
|
4011
4615
|
}
|
|
@@ -4066,6 +4670,33 @@ export class AUNChannel {
|
|
|
4066
4670
|
const groupSlashRequireMentions = this.groupSlashRequireMentionsResolver
|
|
4067
4671
|
? await this.groupSlashRequireMentionsResolver().catch(() => undefined) ?? true
|
|
4068
4672
|
: true;
|
|
4673
|
+
// 命令消息:剥离所有 @(多 agent 被 @ 时各自拿到干净的 /status 各自执行);
|
|
4674
|
+
// 普通消息:仅在唯一 @ 是自己时剥离,保留其他 @ 供 agent 感知。
|
|
4675
|
+
const strippedText = isCommandMsg
|
|
4676
|
+
? slashCommandText
|
|
4677
|
+
: this.stripSelfMentionIfOnly(text, this._aid);
|
|
4678
|
+
// Detect attachments before the empty-text guard (顶层 + 嵌套)
|
|
4679
|
+
const rawAttachments = this.collectAllAttachments(payload);
|
|
4680
|
+
const hasAttachments = rawAttachments.length > 0;
|
|
4681
|
+
// Allow through if there's text OR attachments; both-empty messages are silently dropped.
|
|
4682
|
+
// echo 探针即使正文为空也要继续走 trace 流程。
|
|
4683
|
+
if (!strippedText && !hasAttachments && !isEchoMsg) {
|
|
4684
|
+
logger.debug(`${this.logPrefix()} Group dropped: empty text and no attachments (group=${groupId} sender=${senderAid} mid=${messageId})`);
|
|
4685
|
+
return;
|
|
4686
|
+
}
|
|
4687
|
+
// 附件统一「收到就下载」:与私聊同一策略,不等进模型。
|
|
4688
|
+
//
|
|
4689
|
+
// 理由:按需下载听上去省资源,但代价落在使用侧——模型要先跑一次
|
|
4690
|
+
// `ec fs cp` 再读文件,多一轮工具调用和往返延迟;而且跨 AID 读取受
|
|
4691
|
+
// public/ACL 授权约束,取回可能直接失败。下载回来存着,用的时候是
|
|
4692
|
+
// 本地绝对路径,一次 Read 就够。
|
|
4693
|
+
//
|
|
4694
|
+
// 同时保证被提及过滤掉的消息,其历史记录里也带落盘路径(loggedContent)。
|
|
4695
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4696
|
+
// 历史记录用别名路径(logText),不能退回到 `[image] 文件名`,也不能记绝对路径。
|
|
4697
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4698
|
+
? attachmentLogText
|
|
4699
|
+
: (inboundImages.length > 0 || attachmentLogText !== strippedText ? attachmentLogText : logDescriptor.content);
|
|
4069
4700
|
if (isEchoMsg) {
|
|
4070
4701
|
// echo.ask / echo.ecdiag:追加 trace 后继续走 Agent 流程(下面会 dispatch)。
|
|
4071
4702
|
// echo 本身已在快速通道直接回包,不会走到这里。
|
|
@@ -4103,7 +4734,7 @@ export class AUNChannel {
|
|
|
4103
4734
|
if ((commandTargetsAnotherAgent || (enforceMention && !isMentioned)) && !isOwnHandoff) {
|
|
4104
4735
|
try {
|
|
4105
4736
|
if (text.trim() || this.collectAllAttachments(payload).length) {
|
|
4106
|
-
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered');
|
|
4737
|
+
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered', undefined, loggedContent);
|
|
4107
4738
|
}
|
|
4108
4739
|
}
|
|
4109
4740
|
catch (error) {
|
|
@@ -4119,22 +4750,7 @@ export class AUNChannel {
|
|
|
4119
4750
|
return;
|
|
4120
4751
|
}
|
|
4121
4752
|
}
|
|
4122
|
-
// 命令消息:剥离所有 @(多 agent 被 @ 时各自拿到干净的 /status 各自执行);
|
|
4123
|
-
// 普通消息:仅在唯一 @ 是自己时剥离,保留其他 @ 供 agent 感知。
|
|
4124
|
-
const strippedText = isCommandMsg
|
|
4125
|
-
? slashCommandText
|
|
4126
|
-
: this.stripSelfMentionIfOnly(text, this._aid);
|
|
4127
|
-
// Detect attachments before the empty-text guard (顶层 + 嵌套)
|
|
4128
|
-
const rawAttachments = this.collectAllAttachments(payload);
|
|
4129
|
-
const hasAttachments = rawAttachments.length > 0;
|
|
4130
|
-
// Allow through if there's text OR attachments; both-empty messages are silently dropped
|
|
4131
|
-
if (!strippedText && !hasAttachments) {
|
|
4132
|
-
logger.debug(`${this.logPrefix()} Group dropped: empty text and no attachments (group=${groupId} sender=${senderAid} mid=${messageId})`);
|
|
4133
|
-
return;
|
|
4134
|
-
}
|
|
4135
4753
|
const mentions = payloadMentionEntries;
|
|
4136
|
-
// Process attachments
|
|
4137
|
-
const { finalText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4138
4754
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
4139
4755
|
const peerIdentity = await PeerIdentityCache.resolve('aun', senderAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
4140
4756
|
const shortAid = this.getShortAid(senderAid);
|
|
@@ -4215,7 +4831,7 @@ export class AUNChannel {
|
|
|
4215
4831
|
msgType: logDescriptor.msgType,
|
|
4216
4832
|
payloadType: logDescriptor.payloadType,
|
|
4217
4833
|
payloadSummary: logDescriptor.payloadSummary,
|
|
4218
|
-
messageLogContent:
|
|
4834
|
+
messageLogContent: loggedContent,
|
|
4219
4835
|
});
|
|
4220
4836
|
}
|
|
4221
4837
|
dispatchMessage(event) {
|
|
@@ -4244,12 +4860,24 @@ export class AUNChannel {
|
|
|
4244
4860
|
const hasEvolCoreTracePrivate = /\[EvolCore\.(receive|reply|agent)\]/.test(event.text);
|
|
4245
4861
|
// echo:不进大模型,直接回包
|
|
4246
4862
|
if (echoKindPrivate === 'echo' && !hasEvolCoreTracePrivate) {
|
|
4247
|
-
|
|
4863
|
+
if (event.contactDelivery) {
|
|
4864
|
+
return this.handleEcho(event).then(() => {
|
|
4865
|
+
if (!this.contactReplayFinishHandler)
|
|
4866
|
+
throw new Error('contact terminal persistence unavailable');
|
|
4867
|
+
this.contactReplayFinishHandler(event.contactDelivery);
|
|
4868
|
+
});
|
|
4869
|
+
}
|
|
4870
|
+
void this.handleEcho(event).catch(() => { });
|
|
4248
4871
|
return;
|
|
4249
4872
|
}
|
|
4250
4873
|
// 回声炸弹:已被任何 EvolCore 节点 trace 过的探针,直接丢弃
|
|
4251
4874
|
if (echoKindPrivate !== null && hasEvolCoreTracePrivate) {
|
|
4252
4875
|
logger.info(`${this.logPrefix()} Dropped: echo bomb (already-traced mid=${event.messageId} chat=${event.chatType})`);
|
|
4876
|
+
if (event.contactDelivery) {
|
|
4877
|
+
if (!this.contactReplayFinishHandler)
|
|
4878
|
+
throw new Error('contact terminal persistence unavailable');
|
|
4879
|
+
this.contactReplayFinishHandler(event.contactDelivery);
|
|
4880
|
+
}
|
|
4253
4881
|
return;
|
|
4254
4882
|
}
|
|
4255
4883
|
// echo.ask / echo.ecdiag:追加 trace 后继续交给 agent 处理
|
|
@@ -4284,10 +4912,11 @@ export class AUNChannel {
|
|
|
4284
4912
|
};
|
|
4285
4913
|
const handler = this.messageHandler;
|
|
4286
4914
|
const inbound = {
|
|
4915
|
+
contactDelivery: trustedContactInboundDelivery(event.contactDelivery),
|
|
4287
4916
|
channelId: event.channelId || '',
|
|
4288
4917
|
channelType: 'aun',
|
|
4289
4918
|
content: event.text || '',
|
|
4290
|
-
selfAID: this._aid,
|
|
4919
|
+
selfAID: this._aid || this.config.aid,
|
|
4291
4920
|
groupId: event.groupId,
|
|
4292
4921
|
chatType: event.chatType,
|
|
4293
4922
|
peerId: event.userId || event.channelId || '',
|
|
@@ -4327,13 +4956,20 @@ export class AUNChannel {
|
|
|
4327
4956
|
// 落地先于这一轮处理:ECK 的 hasOwnerDirectory 是同步 stat,名录没落盘时
|
|
4328
4957
|
// 本轮上下文就会丢掉整段名录。这段最多等 OWNER_DIRECTORY_APPLY_WAIT_MS,
|
|
4329
4958
|
// 且只等本地 I/O;网络拉取仍在 processPendingDirectoryUpdate 里后台跑。
|
|
4330
|
-
|
|
4959
|
+
const dispatched = this.settleOwnerDirectoryBeforeTurn()
|
|
4331
4960
|
.then(() => handler(inbound))
|
|
4332
4961
|
.catch(err => {
|
|
4333
4962
|
logger.error(`${this.logPrefix()} Message handler error:`, err);
|
|
4963
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4964
|
+
throw err;
|
|
4334
4965
|
});
|
|
4966
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4967
|
+
return dispatched;
|
|
4335
4968
|
}
|
|
4336
|
-
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery) {
|
|
4969
|
+
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery, privateAttention, contentOverride) {
|
|
4970
|
+
// 私聊过滤记录与群聊过滤记录共用「严格落盘」语义,但使用独立字段,
|
|
4971
|
+
// 避免群历史读取器把私聊记录当成群分类依据。
|
|
4972
|
+
const strict = groupDelivery === 'filtered' || privateAttention !== undefined;
|
|
4337
4973
|
try {
|
|
4338
4974
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', channelId, this.config.aid, this.config.channelName);
|
|
4339
4975
|
const entry = buildInboundEntry({
|
|
@@ -4343,7 +4979,7 @@ export class AUNChannel {
|
|
|
4343
4979
|
chatType: isGroup ? 'group' : 'private',
|
|
4344
4980
|
groupId: isGroup ? channelId : null,
|
|
4345
4981
|
msgId,
|
|
4346
|
-
content: descriptor.content,
|
|
4982
|
+
content: contentOverride ?? descriptor.content,
|
|
4347
4983
|
encrypt,
|
|
4348
4984
|
msgType: descriptor.msgType,
|
|
4349
4985
|
payloadType: descriptor.payloadType,
|
|
@@ -4353,15 +4989,16 @@ export class AUNChannel {
|
|
|
4353
4989
|
gatewaySeq,
|
|
4354
4990
|
groupAttention,
|
|
4355
4991
|
groupDelivery,
|
|
4992
|
+
privateAttention,
|
|
4356
4993
|
});
|
|
4357
|
-
if (
|
|
4994
|
+
if (strict)
|
|
4358
4995
|
appendMessageLogStrict(chatDir, entry, true);
|
|
4359
4996
|
else
|
|
4360
4997
|
appendMessageLog(chatDir, entry);
|
|
4361
4998
|
}
|
|
4362
4999
|
catch (e) {
|
|
4363
5000
|
logger.warn(`${this.logPrefix()} appendInboundPayloadJsonl failed: ${e}`);
|
|
4364
|
-
if (
|
|
5001
|
+
if (strict)
|
|
4365
5002
|
throw e;
|
|
4366
5003
|
}
|
|
4367
5004
|
}
|
|
@@ -4849,7 +5486,7 @@ export class AUNChannel {
|
|
|
4849
5486
|
echoText += `\n${echoTraceLine({
|
|
4850
5487
|
node: 'EvolCore.reply',
|
|
4851
5488
|
dir: 'ret',
|
|
4852
|
-
hop: echoTraceNextHop(echoText),
|
|
5489
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
4853
5490
|
ver,
|
|
4854
5491
|
now: replyTs,
|
|
4855
5492
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -4864,18 +5501,21 @@ export class AUNChannel {
|
|
|
4864
5501
|
: { chatType: 'private' };
|
|
4865
5502
|
const context = {
|
|
4866
5503
|
threadId: event.threadId ?? event.replyContext?.threadId,
|
|
4867
|
-
metadata: event.
|
|
5504
|
+
metadata: event.contactDelivery
|
|
5505
|
+
? { ...event.replyContext?.metadata, operationId: `contact-echo-${event.contactDelivery.key}` }
|
|
5506
|
+
: event.replyContext?.metadata,
|
|
4868
5507
|
delivery: authenticatedDelivery,
|
|
4869
5508
|
};
|
|
4870
5509
|
const sendStart = Date.now();
|
|
4871
5510
|
this.isEchoSending = true;
|
|
4872
|
-
this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
5511
|
+
return this.sendMessage(replyTarget, echoText, context).then(() => {
|
|
4873
5512
|
this.isEchoSending = false;
|
|
4874
5513
|
const elapsed = Date.now() - sendStart;
|
|
4875
5514
|
logger.info(`${this.logPrefix()} Echo reply sent to ${replyTarget} (${elapsed}ms)`);
|
|
4876
5515
|
}).catch(e => {
|
|
4877
5516
|
this.isEchoSending = false;
|
|
4878
5517
|
logger.error(`${this.logPrefix()} Echo reply failed: ${e}`);
|
|
5518
|
+
throw e;
|
|
4879
5519
|
});
|
|
4880
5520
|
}
|
|
4881
5521
|
/**
|
|
@@ -4965,7 +5605,6 @@ export class AUNChannel {
|
|
|
4965
5605
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
4966
5606
|
this.trace('IN', source, data);
|
|
4967
5607
|
logger.info(`${this.logPrefix()} connection.state: state=connected gateway=${this.gatewayUrl || 'unknown'}`);
|
|
4968
|
-
this.reconcileConfiguredOwnerBinding();
|
|
4969
5608
|
this.startOwnerDirectoryRefresh();
|
|
4970
5609
|
// 不在这里清 flapCount —— 短命连接一上来就会触发本分支,
|
|
4971
5610
|
// 必须等 disconnected 时根据 lifetime 决定是否清零
|
|
@@ -4975,8 +5614,6 @@ export class AUNChannel {
|
|
|
4975
5614
|
const wasConnected = this.connected;
|
|
4976
5615
|
this.connected = false;
|
|
4977
5616
|
this.stopOwnerDirectoryRefresh();
|
|
4978
|
-
if (wasConnected)
|
|
4979
|
-
this.configuredOwnerBindEpoch++;
|
|
4980
5617
|
this.clearQueuedObserverSends(state);
|
|
4981
5618
|
// The nine-state SDK emits standby -> retry_backoff -> reconnecting for
|
|
4982
5619
|
// one reconnect cycle. Count the connected-to-down edge once instead of
|
|
@@ -5030,7 +5667,6 @@ export class AUNChannel {
|
|
|
5030
5667
|
}
|
|
5031
5668
|
else if (state === 'terminal_failed') {
|
|
5032
5669
|
this.stopOwnerDirectoryRefresh();
|
|
5033
|
-
this.configuredOwnerBindEpoch++;
|
|
5034
5670
|
this.connected = false;
|
|
5035
5671
|
this.connectedAt = 0;
|
|
5036
5672
|
this.trace('IN', source, data);
|
|
@@ -5083,95 +5719,6 @@ export class AUNChannel {
|
|
|
5083
5719
|
}
|
|
5084
5720
|
}
|
|
5085
5721
|
}
|
|
5086
|
-
configuredOwnerAid() {
|
|
5087
|
-
const config = loadAgent(this.config.aid);
|
|
5088
|
-
if (!config)
|
|
5089
|
-
return undefined;
|
|
5090
|
-
const lifecycle = resolveAgentLifecycle(config);
|
|
5091
|
-
// Existing active Agents may still carry an unfulfilled configured binding target.
|
|
5092
|
-
if (lifecycle === null)
|
|
5093
|
-
return undefined;
|
|
5094
|
-
return firstConfiguredOwner(config);
|
|
5095
|
-
}
|
|
5096
|
-
reconcileConfiguredOwnerBinding() {
|
|
5097
|
-
const client = this.client;
|
|
5098
|
-
const subjectAid = this.config.aid;
|
|
5099
|
-
const epoch = this.configuredOwnerBindEpoch;
|
|
5100
|
-
if (!client || !this.connected || this.intentionalDisconnect || this.config.pureIdentity)
|
|
5101
|
-
return;
|
|
5102
|
-
if (this.configuredOwnerBind) {
|
|
5103
|
-
if (this.configuredOwnerBind.client !== client || this.configuredOwnerBind.epoch !== epoch) {
|
|
5104
|
-
this.configuredOwnerBindRecheck = true;
|
|
5105
|
-
}
|
|
5106
|
-
return;
|
|
5107
|
-
}
|
|
5108
|
-
// Queue the work after installing the guard; config failures must not fail the channel connection.
|
|
5109
|
-
const promise = Promise.resolve()
|
|
5110
|
-
.then(() => this.submitConfiguredOwnerBinding(subjectAid, client, epoch))
|
|
5111
|
-
.catch(error => {
|
|
5112
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
5113
|
-
logger.warn(`${this.logPrefix()} Configured Owner binding invitation failed: ${reason}`);
|
|
5114
|
-
});
|
|
5115
|
-
const tracked = promise.finally(() => {
|
|
5116
|
-
if (this.configuredOwnerBind?.promise !== tracked)
|
|
5117
|
-
return;
|
|
5118
|
-
this.configuredOwnerBind = undefined;
|
|
5119
|
-
const recheck = this.configuredOwnerBindRecheck;
|
|
5120
|
-
this.configuredOwnerBindRecheck = false;
|
|
5121
|
-
if (recheck)
|
|
5122
|
-
this.reconcileConfiguredOwnerBinding();
|
|
5123
|
-
});
|
|
5124
|
-
this.configuredOwnerBind = { client, epoch, promise: tracked };
|
|
5125
|
-
}
|
|
5126
|
-
isCurrentConfiguredOwnerBind(client, epoch) {
|
|
5127
|
-
return this.client === client && this.configuredOwnerBindEpoch === epoch
|
|
5128
|
-
&& this.connected && !this.intentionalDisconnect;
|
|
5129
|
-
}
|
|
5130
|
-
async submitConfiguredOwnerBinding(subjectAid, client, epoch) {
|
|
5131
|
-
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
5132
|
-
return;
|
|
5133
|
-
const configuredOwnerAid = this.configuredOwnerAid();
|
|
5134
|
-
if (!configuredOwnerAid
|
|
5135
|
-
|| AUNChannel.configuredOwnerBindAttempts.has(JSON.stringify([subjectAid, configuredOwnerAid]))
|
|
5136
|
-
|| ownerResolver.hasRejectedOwnerBinding(subjectAid, configuredOwnerAid))
|
|
5137
|
-
return;
|
|
5138
|
-
ownerResolver.setConnected(subjectAid, client, true);
|
|
5139
|
-
const current = await ownerResolver.refresh(subjectAid, { force: true, source: 'channel.binding' });
|
|
5140
|
-
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
5141
|
-
return;
|
|
5142
|
-
// The config may change while the fresh consensus query is in flight.
|
|
5143
|
-
const ownerAid = this.configuredOwnerAid();
|
|
5144
|
-
if (!ownerAid || ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid))
|
|
5145
|
-
return;
|
|
5146
|
-
if (current.task?.operation === 'bind' && current.task.owner_aid === ownerAid
|
|
5147
|
-
&& current.task.status === 'rejected') {
|
|
5148
|
-
return;
|
|
5149
|
-
}
|
|
5150
|
-
if (current.consensusStatus === 'consensus')
|
|
5151
|
-
return;
|
|
5152
|
-
if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus))
|
|
5153
|
-
return;
|
|
5154
|
-
const attemptKey = JSON.stringify([subjectAid, ownerAid]);
|
|
5155
|
-
if (AUNChannel.configuredOwnerBindAttempts.has(attemptKey))
|
|
5156
|
-
return;
|
|
5157
|
-
// Reserve across channel recreation while preparation is in flight. Only entering
|
|
5158
|
-
// an SDK mutation consumes the attempt; a lost receipt must never release it.
|
|
5159
|
-
AUNChannel.configuredOwnerBindAttempts.add(attemptKey);
|
|
5160
|
-
let submissionStarted = false;
|
|
5161
|
-
try {
|
|
5162
|
-
await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
|
|
5163
|
-
&& !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid), () => {
|
|
5164
|
-
submissionStarted = true;
|
|
5165
|
-
logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
|
|
5166
|
-
+ `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
|
|
5167
|
-
});
|
|
5168
|
-
}
|
|
5169
|
-
catch (error) {
|
|
5170
|
-
if (!submissionStarted)
|
|
5171
|
-
AUNChannel.configuredOwnerBindAttempts.delete(attemptKey);
|
|
5172
|
-
throw error;
|
|
5173
|
-
}
|
|
5174
|
-
}
|
|
5175
5722
|
/** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
|
|
5176
5723
|
isKickReason(reason) {
|
|
5177
5724
|
if (!reason)
|
|
@@ -5366,6 +5913,18 @@ export class AUNChannel {
|
|
|
5366
5913
|
return undefined;
|
|
5367
5914
|
}
|
|
5368
5915
|
},
|
|
5916
|
+
// 常驻宿主的运行目录:与本进程其它 session runtime 同一套(系统临时目录下、
|
|
5917
|
+
// 已做过 ACL 授予)。宿主程序、包脚本快照、调用临时目录都落在这下面。
|
|
5918
|
+
// 取不到时返回 undefined —— 宿主模式会在启动阶段明确拒绝,不静默降级。
|
|
5919
|
+
getRuntimeRoot: () => {
|
|
5920
|
+
try {
|
|
5921
|
+
return ensureSessionRuntimeDir(`services-host:${aid}`);
|
|
5922
|
+
}
|
|
5923
|
+
catch {
|
|
5924
|
+
return undefined;
|
|
5925
|
+
}
|
|
5926
|
+
},
|
|
5927
|
+
onHostLog: line => logger.debug(`[ServicesHost] aid=${aid} ${line}`),
|
|
5369
5928
|
});
|
|
5370
5929
|
this.serviceRouter.ensureStarted(identity);
|
|
5371
5930
|
return this.serviceRouter;
|
|
@@ -5413,6 +5972,7 @@ export class AUNChannel {
|
|
|
5413
5972
|
* 应答支不经过这里——那由 AunRequestRegistry 在消息层更早匹配。
|
|
5414
5973
|
*/
|
|
5415
5974
|
async handleServiceMessage(input) {
|
|
5975
|
+
const startedAt = Date.now();
|
|
5416
5976
|
const router = this.ensureServiceRouter();
|
|
5417
5977
|
const payload = input.payload;
|
|
5418
5978
|
const rawType = typeof payload.type === 'string' ? payload.type : '';
|
|
@@ -5426,6 +5986,9 @@ export class AUNChannel {
|
|
|
5426
5986
|
logger.debug(`${this.logPrefix()} service request without request_id; using message_id ${input.messageId} type=${rawType} from=${input.fromAid}`);
|
|
5427
5987
|
}
|
|
5428
5988
|
const message = {
|
|
5989
|
+
deadlineAt: Number.isSafeInteger(payload.service_deadline_at_ms)
|
|
5990
|
+
? Math.min(payload.service_deadline_at_ms, input.receivedAt + 300_000)
|
|
5991
|
+
: input.receivedAt + 12_000,
|
|
5429
5992
|
type: rawType,
|
|
5430
5993
|
requestId,
|
|
5431
5994
|
requestIdGenerated,
|
|
@@ -5439,7 +6002,11 @@ export class AUNChannel {
|
|
|
5439
6002
|
const reply = await router.handleRequest(message, { admission });
|
|
5440
6003
|
if (!reply.shouldSend)
|
|
5441
6004
|
return;
|
|
6005
|
+
const handledAt = Date.now();
|
|
5442
6006
|
await this.sendServiceReply(input.fromAid, input.messageId, input.encrypted, reply);
|
|
6007
|
+
if (isProjectionServiceResult(reply.type)) {
|
|
6008
|
+
logger.info(`${this.logPrefix()} ServiceProjection id=${requestId} type=${rawType} queueMs=${Math.max(0, startedAt - input.receivedAt)} handleMs=${handledAt - startedAt} sendMs=${Date.now() - handledAt}`);
|
|
6009
|
+
}
|
|
5443
6010
|
}
|
|
5444
6011
|
/** 回复:点对点、带 service 标记位,不带 threadId/topicName/chatmode。 */
|
|
5445
6012
|
async sendServiceReply(toAid, replyToMessageId, encrypted, reply) {
|
|
@@ -5447,6 +6014,9 @@ export class AUNChannel {
|
|
|
5447
6014
|
delivery: { chatType: 'private', service: { type: reply.type, requestId: reply.requestId } },
|
|
5448
6015
|
metadata: { encrypted, source: 'daemon' },
|
|
5449
6016
|
replyToMessageId,
|
|
6017
|
+
// 应答同样只活一个调用窗口:调用方早已超时退出的情况下,回包被持久补投
|
|
6018
|
+
// 没有任何意义,还会在对端留下一条无人认领的消息。
|
|
6019
|
+
ttl: SERVICE_REPLY_TTL_SECONDS,
|
|
5450
6020
|
});
|
|
5451
6021
|
if (!result.ok) {
|
|
5452
6022
|
logger.warn(`${this.logPrefix()} Service reply send failed: type=${reply.type} code=${result.code ?? 'UNKNOWN'} error=${result.error ?? ''}`);
|
|
@@ -5457,10 +6027,34 @@ export class AUNChannel {
|
|
|
5457
6027
|
}
|
|
5458
6028
|
onMessage(handler) {
|
|
5459
6029
|
this.messageHandler = handler;
|
|
6030
|
+
this.scheduleContactReplay();
|
|
5460
6031
|
}
|
|
5461
6032
|
setMentionModeResolver(resolver) {
|
|
5462
6033
|
this.mentionModeResolver = resolver;
|
|
5463
6034
|
}
|
|
6035
|
+
/**
|
|
6036
|
+
* 私聊 @ 处理策略。与 `mentionModeResolver` 分开:后者是按群的群聊策略,
|
|
6037
|
+
* 本 resolver 只读 Agent 级 `privateMentionMode`,不接收群/对端参数。
|
|
6038
|
+
*/
|
|
6039
|
+
setPrivateMentionModeResolver(resolver) {
|
|
6040
|
+
this.privateMentionModeResolver = resolver;
|
|
6041
|
+
}
|
|
6042
|
+
/**
|
|
6043
|
+
* 读取生效的私聊 @ 处理策略。缺省、解析失败或未装配 resolver 时一律按
|
|
6044
|
+
* `disabled` 处理:任何不确定都退回「处理所有消息」,绝不静默丢消息。
|
|
6045
|
+
*/
|
|
6046
|
+
async resolvePrivateMentionMode() {
|
|
6047
|
+
if (!this.privateMentionModeResolver)
|
|
6048
|
+
return 'disabled';
|
|
6049
|
+
try {
|
|
6050
|
+
const mode = await this.privateMentionModeResolver();
|
|
6051
|
+
return mode === 'mention-only' ? 'mention-only' : 'disabled';
|
|
6052
|
+
}
|
|
6053
|
+
catch (error) {
|
|
6054
|
+
logger.warn(`${this.logPrefix()} privateMentionMode unavailable, treating as disabled: ${error instanceof Error ? error.message : String(error)}`);
|
|
6055
|
+
return 'disabled';
|
|
6056
|
+
}
|
|
6057
|
+
}
|
|
5464
6058
|
setGroupSlashRequireMentionsResolver(resolver) {
|
|
5465
6059
|
this.groupSlashRequireMentionsResolver = resolver;
|
|
5466
6060
|
}
|
|
@@ -5738,44 +6332,23 @@ export class AUNChannel {
|
|
|
5738
6332
|
const timer = setTimeout(() => this.invalidatedInteractions.delete(interactionId), 24 * 60 * 60 * 1000);
|
|
5739
6333
|
timer.unref?.();
|
|
5740
6334
|
}
|
|
5741
|
-
async recallInteractionCard(messageId, channelId, delivery) {
|
|
5742
|
-
if (!this.client || !this.connected)
|
|
5743
|
-
return false;
|
|
5744
|
-
try {
|
|
5745
|
-
if (!channelId || !delivery) {
|
|
5746
|
-
logger.warn(`${this.logPrefix()} Cannot recall interaction card without trusted delivery route: mid=${messageId}`);
|
|
5747
|
-
return false;
|
|
5748
|
-
}
|
|
5749
|
-
const isGroup = delivery.chatType === 'group';
|
|
5750
|
-
const method = isGroup ? 'group.recall' : 'message.recall';
|
|
5751
|
-
const params = isGroup
|
|
5752
|
-
? { group_id: delivery.groupId, message_ids: [messageId] }
|
|
5753
|
-
: { message_ids: [messageId] };
|
|
5754
|
-
await this.callAndTrace(method, params, { silentError: true });
|
|
5755
|
-
return true;
|
|
5756
|
-
}
|
|
5757
|
-
catch (error) {
|
|
5758
|
-
logger.debug(`${this.logPrefix()} Failed to recall invalidated interaction card mid=${messageId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
5759
|
-
return false;
|
|
5760
|
-
}
|
|
5761
|
-
}
|
|
5762
6335
|
/**
|
|
5763
|
-
*
|
|
5764
|
-
*
|
|
5765
|
-
* rejects any concurrent/late callback independently.
|
|
6336
|
+
* Disable AUN card interactions while preserving the original chat message.
|
|
6337
|
+
* Drop undelivered cards and actionable mappings; the response router still
|
|
6338
|
+
* rejects any concurrent/late callback independently. Never recall a card
|
|
6339
|
+
* merely because its interaction has ended.
|
|
5766
6340
|
*/
|
|
5767
6341
|
async invalidateInteraction(interactionId, reason = 'cancelled') {
|
|
5768
6342
|
this.rememberInvalidatedInteraction(interactionId, reason);
|
|
5769
6343
|
const removedQueued = outbox.removeInteractionCards(this.config.aid, interactionId);
|
|
5770
6344
|
if (removedQueued > 0) {
|
|
5771
|
-
logger.info(`${this.logPrefix()} Removed ${removedQueued}
|
|
6345
|
+
logger.info(`${this.logPrefix()} Removed ${removedQueued} invalidated interaction card(s) from durable outbox: request=${interactionId}`);
|
|
5772
6346
|
}
|
|
5773
6347
|
const messageIds = [...(this.interactionCardMessageIds.get(interactionId) ?? [])];
|
|
5774
6348
|
for (const messageId of messageIds) {
|
|
5775
|
-
|
|
5776
|
-
|
|
6349
|
+
if (this.cardMessageIdMap.get(messageId)?.widget)
|
|
6350
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
5777
6351
|
this.forgetInteractionCard(messageId, interactionId);
|
|
5778
|
-
await this.recallInteractionCard(messageId, channelId, card?.delivery);
|
|
5779
6352
|
}
|
|
5780
6353
|
}
|
|
5781
6354
|
restoreInteraction(envelope, interaction, receipt) {
|
|
@@ -5875,7 +6448,20 @@ export class AUNChannel {
|
|
|
5875
6448
|
delivery: delivery ?? action.delivery,
|
|
5876
6449
|
replyContext: callbackContext,
|
|
5877
6450
|
sensitive: action.sensitive,
|
|
6451
|
+
widget: action.widget,
|
|
5878
6452
|
});
|
|
6453
|
+
if (action.widget && channelId && (delivery ?? action.delivery)) {
|
|
6454
|
+
const route = (delivery ?? action.delivery);
|
|
6455
|
+
registerWidgetCard(this.config.aid, {
|
|
6456
|
+
version: 1, messageId, channelId, chatType: route.chatType,
|
|
6457
|
+
initiatorAid: route.chatType === 'private' ? channelId : action.initiatorAid,
|
|
6458
|
+
requestId: action.requestId, title: 'WidgetCard', threadId: replyContext?.threadId,
|
|
6459
|
+
expiresAt: action.expiresAt,
|
|
6460
|
+
encrypted: action.sensitive === true || (typeof replyContext?.metadata?.encrypted === 'boolean'
|
|
6461
|
+
? replyContext.metadata.encrypted : this.shouldEncrypt(channelId)),
|
|
6462
|
+
sensitive: action.sensitive, status: 'pending',
|
|
6463
|
+
});
|
|
6464
|
+
}
|
|
5879
6465
|
this.ownedCardMsgIds.add(messageId);
|
|
5880
6466
|
if (typeof replyContext?.threadId === 'string') {
|
|
5881
6467
|
this.ownedCardTopics.set(messageId, { channelId, threadId: replyContext.threadId });
|
|
@@ -5907,13 +6493,36 @@ export class AUNChannel {
|
|
|
5907
6493
|
ownedTimer.unref?.();
|
|
5908
6494
|
const invalidationReason = this.invalidatedInteractions.get(action.requestId);
|
|
5909
6495
|
if (invalidationReason) {
|
|
5910
|
-
|
|
5911
|
-
|
|
6496
|
+
if (action.widget)
|
|
6497
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
6498
|
+
this.forgetInteractionCard(messageId, action.requestId);
|
|
5912
6499
|
}
|
|
5913
6500
|
}
|
|
5914
6501
|
runPostSend(entry, messageId) {
|
|
6502
|
+
if (entry.dedupeKey?.startsWith('template-update:') && entry.payload?.template_update?.noticeId) {
|
|
6503
|
+
recordTemplateNoticeReceipt(resolvePaths().root, entry.payload.template_update.noticeId, entry.channelId, messageId, entry.id);
|
|
6504
|
+
}
|
|
5915
6505
|
if (!entry.postSend)
|
|
5916
6506
|
return;
|
|
6507
|
+
if (entry.postSend.type === 'register_widget_card') {
|
|
6508
|
+
if (!entry.delivery)
|
|
6509
|
+
throw new Error('WidgetCard delivery route is unavailable');
|
|
6510
|
+
registerWidgetCard(this.config.aid, {
|
|
6511
|
+
version: 1, messageId, channelId: entry.channelId, chatType: entry.delivery.chatType,
|
|
6512
|
+
initiatorAid: entry.postSend.initiatorAid, title: entry.postSend.title,
|
|
6513
|
+
threadId: typeof entry.payload?.thread_id === 'string' ? entry.payload.thread_id : undefined,
|
|
6514
|
+
expiresAt: entry.postSend.expiresAt, encrypted: entry.postSend.encrypted, status: 'pending',
|
|
6515
|
+
});
|
|
6516
|
+
return;
|
|
6517
|
+
}
|
|
6518
|
+
if (entry.postSend.type === 'register_payment_delivery') {
|
|
6519
|
+
paymentStore(this.config.aid).markDelivered(entry.postSend.requestId, entry.postSend.deliveryId, messageId);
|
|
6520
|
+
return;
|
|
6521
|
+
}
|
|
6522
|
+
if (entry.postSend.type === 'register_contact_approval_card') {
|
|
6523
|
+
registerContactApprovalCard(this.config.aid, entry.postSend.pendingKey, entry.postSend.eventId, messageId);
|
|
6524
|
+
return;
|
|
6525
|
+
}
|
|
5917
6526
|
if (entry.postSend.type === 'register_interaction_card') {
|
|
5918
6527
|
this.registerCardPostSend(messageId, entry.postSend, entry.channelId, entry.delivery, entry.context);
|
|
5919
6528
|
if (entry.postSend.requestId.startsWith('gir-'))
|
|
@@ -5934,66 +6543,8 @@ export class AUNChannel {
|
|
|
5934
6543
|
const target = normalize(channelId);
|
|
5935
6544
|
return !!self && !!target && self === target;
|
|
5936
6545
|
}
|
|
5937
|
-
appContactOutboundBlock(channelId, delivery, payload, params) {
|
|
5938
|
-
// 服务回复是对一次已到达请求的应答,不是主动联系;且拒绝信息本身必须能送达,
|
|
5939
|
-
// 否则调用方只会看到超时。
|
|
5940
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5941
|
-
return undefined;
|
|
5942
|
-
// 跨话题自派:收件人是本端,不是跨主体通讯,不适用联系人准入(同 aun-ipc-sender)。
|
|
5943
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5944
|
-
return undefined;
|
|
5945
|
-
if (delivery.chatType === 'group' || this.config.pureIdentity
|
|
5946
|
-
|| this.hasContactControlPermit(channelId, payload, params))
|
|
5947
|
-
return undefined;
|
|
5948
|
-
const decision = evaluateAppContactAdmission(this.config.aid, channelId);
|
|
5949
|
-
if (params?.encrypt === true && params?.rawPayload === true && parseFriendInvite(payload, this.config.aid, channelId)
|
|
5950
|
-
&& decision.reason === 'not_in_contacts')
|
|
5951
|
-
return undefined;
|
|
5952
|
-
if (decision.allow)
|
|
5953
|
-
return undefined;
|
|
5954
|
-
return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
|
|
5955
|
-
code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE' : 'CONTACT_DENIED',
|
|
5956
|
-
error: `联系人准入未通过:${decision.reason}` };
|
|
5957
|
-
}
|
|
5958
|
-
async prepareAppContactOutbound(channelId, delivery, payload, params) {
|
|
5959
|
-
if (delivery.chatType === 'private' && delivery.service)
|
|
5960
|
-
return undefined;
|
|
5961
|
-
// 跨话题自派:收件人是本端,连通告归属刷新这一跳都不需要。
|
|
5962
|
-
if (this.isSelfAddressedTarget(channelId))
|
|
5963
|
-
return undefined;
|
|
5964
|
-
if (delivery.chatType === 'private' && !this.config.pureIdentity
|
|
5965
|
-
&& !this.hasContactControlPermit(channelId, payload, params)
|
|
5966
|
-
&& !this.acceptsVerifiedOwnership(channelId, payload, params)) {
|
|
5967
|
-
await ownerResolver.refresh(this.config.aid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
5968
|
-
}
|
|
5969
|
-
return this.appContactOutboundBlock(channelId, delivery, payload, params);
|
|
5970
|
-
}
|
|
5971
|
-
/**
|
|
5972
|
-
* A caller that already holds the consensus may skip the refresh round-trip.
|
|
5973
|
-
*
|
|
5974
|
-
* Only lifecycle notices qualify, and only toward their own Owner. Shutdown is
|
|
5975
|
-
* the reason this exists: the offline notice runs while the daemon is tearing
|
|
5976
|
-
* down, so a network refresh would outlive the AUN connection it needs.
|
|
5977
|
-
* Admission itself is unchanged — the block below still demands a live
|
|
5978
|
-
* consensus in the resolver cache, so this skips the check of the cache's
|
|
5979
|
-
* freshness, never the requirement that a consensus exists.
|
|
5980
|
-
*/
|
|
5981
|
-
acceptsVerifiedOwnership(channelId, payload, params) {
|
|
5982
|
-
if (params?.ownershipVerified !== true)
|
|
5983
|
-
return false;
|
|
5984
|
-
const notice = payload;
|
|
5985
|
-
if (!notice || notice.type !== 'notice'
|
|
5986
|
-
|| (notice.subtype !== 'agent.online' && notice.subtype !== 'agent.offline'))
|
|
5987
|
-
return false;
|
|
5988
|
-
// Even if the flag ever leaked, it cannot widen admission: the target must be
|
|
5989
|
-
// the Owner the live consensus names, which admission allows unconditionally.
|
|
5990
|
-
return currentContactBinding(this.config.aid)?.owner_aid === channelId;
|
|
5991
|
-
}
|
|
5992
6546
|
async sendAunPayload(channelId, payload, context, label) {
|
|
5993
6547
|
const delivery = this.requireDelivery(channelId, context);
|
|
5994
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, payload);
|
|
5995
|
-
if (blocked)
|
|
5996
|
-
return { ok: false, ...blocked };
|
|
5997
6548
|
let normalizedPayload;
|
|
5998
6549
|
try {
|
|
5999
6550
|
normalizedPayload = this.normalizeAunPayloadMentions(payload);
|
|
@@ -6027,9 +6578,10 @@ export class AUNChannel {
|
|
|
6027
6578
|
if (payloadWithCausationRef.thread_id === '')
|
|
6028
6579
|
delete payloadWithCausationRef.thread_id;
|
|
6029
6580
|
// Truncate payload if too large (AUN SDK limit: 1MB)
|
|
6030
|
-
const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
|
|
6581
|
+
const friendPayload = (typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload);
|
|
6031
6582
|
const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
6032
6583
|
if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
|
|
6584
|
+
|| (payload.type === 'widget_card' && truncatedPayload.type !== 'widget_card')
|
|
6033
6585
|
|| (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
|
|
6034
6586
|
return {
|
|
6035
6587
|
ok: false, status: 'permanent', code: 'PAYLOAD_TOO_LARGE',
|
|
@@ -6123,7 +6675,7 @@ export class AUNChannel {
|
|
|
6123
6675
|
};
|
|
6124
6676
|
}
|
|
6125
6677
|
recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
|
|
6126
|
-
if (typeof payload.type === 'string' && payload.type.startsWith('friend.')) {
|
|
6678
|
+
if ((typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload)) {
|
|
6127
6679
|
logger.info(`${this.logPrefix()} Contact control transport accepted: type=${payload.type} mid=${messageId}`);
|
|
6128
6680
|
return;
|
|
6129
6681
|
}
|
|
@@ -6176,8 +6728,33 @@ export class AUNChannel {
|
|
|
6176
6728
|
// intentionally removes undefined array elements, which would otherwise
|
|
6177
6729
|
// turn malformed `mentions: [undefined]` into an apparently valid `[]`.
|
|
6178
6730
|
const finalPayload = this.normalizeAunPayloadMentions(this.applyReplyContextToPayload(validatedPayload, context));
|
|
6731
|
+
if (finalPayload.type === 'widget_card') {
|
|
6732
|
+
if (finalPayload.thread_id !== undefined && !isTopicThreadId(finalPayload.thread_id)) {
|
|
6733
|
+
throw Object.assign(new Error('WidgetCard thread_id must be an existing topic ID'), { code: 'INVALID_WIDGET_CARD' });
|
|
6734
|
+
}
|
|
6735
|
+
const attachments = finalPayload.attachments;
|
|
6736
|
+
const html = Array.isArray(attachments) && attachments.length === 1 ? attachments[0] : undefined;
|
|
6737
|
+
if (!html || typeof html !== 'object' || typeof html.owner_aid !== 'string' || !html.owner_aid
|
|
6738
|
+
|| typeof html.object_key !== 'string' || !html.object_key || html.object_key.includes(':')
|
|
6739
|
+
|| html.object_key.startsWith('/') || html.object_key.split('/').includes('..')
|
|
6740
|
+
|| typeof html.filename !== 'string' || !/\.html?$/i.test(html.filename)
|
|
6741
|
+
|| typeof html.content_type !== 'string' || !/^text\/html(?:\s*;|$)/i.test(html.content_type)) {
|
|
6742
|
+
throw Object.assign(new Error('WidgetCard requires one uploaded HTML attachment with owner_aid and object_key'), { code: 'INVALID_WIDGET_CARD' });
|
|
6743
|
+
}
|
|
6744
|
+
const initiatorAid = delivery.chatType === 'private' ? channelId : finalPayload.initiator;
|
|
6745
|
+
if (typeof initiatorAid !== 'string' || !initiatorAid.trim()) {
|
|
6746
|
+
throw Object.assign(new Error('Group WidgetCard requires an initiator'), { code: 'INVALID_WIDGET_INITIATOR' });
|
|
6747
|
+
}
|
|
6748
|
+
if (opts.postSend?.type !== 'register_interaction_card')
|
|
6749
|
+
opts = { ...opts, postSend: {
|
|
6750
|
+
type: 'register_widget_card', initiatorAid,
|
|
6751
|
+
title: typeof finalPayload.title === 'string' ? finalPayload.title : html.filename,
|
|
6752
|
+
expiresAt: Date.now() + AUN_INTERACTION_CARD_TTL_MS,
|
|
6753
|
+
encrypted: typeof context.metadata?.encrypted === 'boolean' ? context.metadata.encrypted : this.shouldEncrypt(channelId),
|
|
6754
|
+
} };
|
|
6755
|
+
}
|
|
6179
6756
|
const logText = opts.logText ?? this.payloadLogText(finalPayload, opts.contentKind);
|
|
6180
|
-
const expiresAt = opts.postSend?.type === 'register_interaction_card'
|
|
6757
|
+
const expiresAt = opts.postSend?.type === 'register_interaction_card' || opts.postSend?.type === 'register_widget_card'
|
|
6181
6758
|
? opts.postSend.expiresAt
|
|
6182
6759
|
: undefined;
|
|
6183
6760
|
if (typeof expiresAt === 'number' && Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
|
|
@@ -6513,49 +7090,6 @@ export class AUNChannel {
|
|
|
6513
7090
|
this.sentCount.set(turnKey, seqInTurn);
|
|
6514
7091
|
return seqInTurn;
|
|
6515
7092
|
}
|
|
6516
|
-
/** An unadmitted outbound text becomes an Owner request, never a send to the peer. */
|
|
6517
|
-
async requestOutboundContact(args) {
|
|
6518
|
-
const selfAid = this.config.aid;
|
|
6519
|
-
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
6520
|
-
const binding = currentContactBinding(selfAid);
|
|
6521
|
-
if (!binding) {
|
|
6522
|
-
return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
|
|
6523
|
-
}
|
|
6524
|
-
const decision = evaluateAppContactAdmission(selfAid, args.to);
|
|
6525
|
-
if (decision.allow || (decision.reason !== 'not_in_contacts' && decision.reason !== 'scope_extension')) {
|
|
6526
|
-
return { ok: false, code: 'CONTACT_DENIED', error: `联系人状态不允许提交申请:${decision.reason};原消息未发送` };
|
|
6527
|
-
}
|
|
6528
|
-
const text = contactIntroductionText(args.payload);
|
|
6529
|
-
if (text === undefined) {
|
|
6530
|
-
return { ok: false, code: 'CONTACT_DENIED', error: '只有纯文本可以向本端 Owner 提交联系申请;原消息未发送' };
|
|
6531
|
-
}
|
|
6532
|
-
if (!consumeContactIntroductionBudget(selfAid, `outbound:${args.to}`)) {
|
|
6533
|
-
return { ok: false, code: 'CONTACT_INTRODUCTION_RATE_LIMIT', error: '联系申请过于频繁,请稍后重试;原消息未发送' };
|
|
6534
|
-
}
|
|
6535
|
-
const request = {
|
|
6536
|
-
...buildContactRequest(binding, args.to, args.sourceMessageId, Date.now(), `申请联系 ${args.to}。以下为本端拟发送的内容,尚未发给对方:\n${text}`, decision.reason),
|
|
6537
|
-
direction: 'outbound',
|
|
6538
|
-
};
|
|
6539
|
-
const remainingTtl = request.received_at_ms + CONTACT_EVENT_TTL_MS - Date.now();
|
|
6540
|
-
if (remainingTtl <= 0) {
|
|
6541
|
-
return { ok: false, code: 'CONTACT_REQUEST_EXPIRED', error: '联系申请已过期,未重新提交;原消息未发送' };
|
|
6542
|
-
}
|
|
6543
|
-
const sent = await this.sendContentPayload(binding.owner_aid, request, {
|
|
6544
|
-
contentKind: 'custom', dedupeKey: request.event_id, logText: '[friend.request.v1 outbound]',
|
|
6545
|
-
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true } },
|
|
6546
|
-
ttl: remainingTtl,
|
|
6547
|
-
});
|
|
6548
|
-
if (!sent.messageId && !sent.queued) {
|
|
6549
|
-
return { ok: false, code: sent.code ?? 'CONTACT_OWNER_REQUEST_FAILED',
|
|
6550
|
-
error: `向本端 Owner 提交联系申请失败:${sent.error ?? '未获得发送或排队回执'};原消息未发送` };
|
|
6551
|
-
}
|
|
6552
|
-
return { ok: true, receipt: {
|
|
6553
|
-
event_id: request.event_id, owner_aid: binding.owner_aid, target_aid: args.to,
|
|
6554
|
-
status: sent.messageId ? 'sent' : 'queued',
|
|
6555
|
-
...(sent.messageId ? { message_id: sent.messageId } : {}),
|
|
6556
|
-
...(sent.outboxId ? { outbox_id: sent.outboxId } : {}),
|
|
6557
|
-
} };
|
|
6558
|
-
}
|
|
6559
7093
|
async sendDaemonMsg(args) {
|
|
6560
7094
|
try {
|
|
6561
7095
|
resolveAunSendDevice(args.deviceId, 'msg', args.payload);
|
|
@@ -6589,6 +7123,55 @@ export class AUNChannel {
|
|
|
6589
7123
|
code: e?.code,
|
|
6590
7124
|
};
|
|
6591
7125
|
}
|
|
7126
|
+
// Friend invitations are durable control messages. Keep the validated
|
|
7127
|
+
// application payload intact, require E2EE, and use the business ID as the
|
|
7128
|
+
// retry key so reconnects cannot create a second logical invitation.
|
|
7129
|
+
const durableInvite = finalPayload.type === FRIEND_INVITE_TYPE || finalPayload.type === FRIEND_INVITE_PROOF_TYPE;
|
|
7130
|
+
if (durableInvite) {
|
|
7131
|
+
if (args.encrypt !== true || args.ttl !== undefined || args.rawPayload !== true) {
|
|
7132
|
+
return { ok: false, error: 'friend invite controls require encrypted persistent raw delivery', code: 'FRIEND_CONTROL_REQUIREMENTS' };
|
|
7133
|
+
}
|
|
7134
|
+
const parsedInvite = finalPayload.type === FRIEND_INVITE_TYPE
|
|
7135
|
+
? parseFriendInvite(finalPayload, this.config.aid, args.to)
|
|
7136
|
+
: parseFriendInviteProof(finalPayload, this.config.aid, args.to)?.invite;
|
|
7137
|
+
if (!parsedInvite)
|
|
7138
|
+
return { ok: false, error: 'invalid friend invite control payload', code: 'INVALID_FRIEND_INVITE' };
|
|
7139
|
+
const businessId = finalPayload.type === FRIEND_INVITE_TYPE
|
|
7140
|
+
? finalPayload.invite_id
|
|
7141
|
+
: finalPayload.proof_id;
|
|
7142
|
+
const expiresAt = parsedInvite.expires_at_ms;
|
|
7143
|
+
if (expiresAt <= Date.now()) {
|
|
7144
|
+
return { ok: false, status: 'failed', encrypt: true, error: 'friend invite has expired', code: 'FRIEND_INVITE_EXPIRED' };
|
|
7145
|
+
}
|
|
7146
|
+
const sent = await this.sendContentPayload(args.to, finalPayload, {
|
|
7147
|
+
contentKind: 'custom', dedupeKey: `${finalPayload.type}:${businessId}`,
|
|
7148
|
+
logText: `[${finalPayload.type}]`,
|
|
7149
|
+
context: { delivery: { chatType: 'private' }, metadata: { encrypted: true, source: 'daemon' } },
|
|
7150
|
+
ttl: Math.max(1, expiresAt - Date.now()),
|
|
7151
|
+
});
|
|
7152
|
+
if (sent.messageId)
|
|
7153
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', encrypt: true };
|
|
7154
|
+
if (sent.queued)
|
|
7155
|
+
return { ok: true, status: 'queued', encrypt: true, outbox_id: sent.outboxId, error: sent.error, code: sent.code };
|
|
7156
|
+
return { ok: false, status: 'failed', encrypt: true, outbox_id: sent.outboxId, error: sent.error ?? 'friend invite control send failed', code: sent.code };
|
|
7157
|
+
}
|
|
7158
|
+
if (finalPayload.type === 'widget_card') {
|
|
7159
|
+
if (args.ttl !== undefined || args.deviceId || args.service) {
|
|
7160
|
+
return { ok: false, code: 'INVALID_WIDGET_TARGET', error: 'WidgetCard requires persistent conversation delivery' };
|
|
7161
|
+
}
|
|
7162
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
|
|
7163
|
+
const sent = await this.sendContentPayload(args.to, finalPayload, {
|
|
7164
|
+
contentKind: 'card', context: { delivery: { chatType: 'private' },
|
|
7165
|
+
sessionId: args.log?.sessionId,
|
|
7166
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7167
|
+
metadata: { encrypted: encrypt } },
|
|
7168
|
+
});
|
|
7169
|
+
if (sent.messageId)
|
|
7170
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', encrypt };
|
|
7171
|
+
if (sent.queued)
|
|
7172
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, encrypt };
|
|
7173
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed', encrypt };
|
|
7174
|
+
}
|
|
6592
7175
|
if (!this.connected || !this.client) {
|
|
6593
7176
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6594
7177
|
}
|
|
@@ -6599,9 +7182,6 @@ export class AUNChannel {
|
|
|
6599
7182
|
code: 'INVALID_REQUEST_TTL',
|
|
6600
7183
|
};
|
|
6601
7184
|
}
|
|
6602
|
-
const contactBlock = await this.prepareAppContactOutbound(args.to, args.service ? { chatType: 'private', service: args.service } : { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
|
|
6603
|
-
if (contactBlock)
|
|
6604
|
-
return { ok: false, code: contactBlock.code, error: contactBlock.error };
|
|
6605
7185
|
if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
|
|
6606
7186
|
return {
|
|
6607
7187
|
ok: false,
|
|
@@ -6690,6 +7270,9 @@ export class AUNChannel {
|
|
|
6690
7270
|
const selfAddressed = args.to.replace(/^@/, '').toLowerCase() === this.config.aid.replace(/^@/, '').toLowerCase();
|
|
6691
7271
|
if (!selfAddressed && args.log?.content !== undefined) {
|
|
6692
7272
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
7273
|
+
const logContent = args.log.contentAuthoritative
|
|
7274
|
+
? args.log.content
|
|
7275
|
+
: (classified.content || args.log.content);
|
|
6693
7276
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.to, this.config.aid);
|
|
6694
7277
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
6695
7278
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -6699,7 +7282,7 @@ export class AUNChannel {
|
|
|
6699
7282
|
threadId: args.log.threadId ?? (typeof finalPayload.thread_id === 'string' ? finalPayload.thread_id : null),
|
|
6700
7283
|
chatType: 'private',
|
|
6701
7284
|
msgId: messageId,
|
|
6702
|
-
content:
|
|
7285
|
+
content: logContent,
|
|
6703
7286
|
encrypt,
|
|
6704
7287
|
chatmode,
|
|
6705
7288
|
msgType: classified.msgType ?? args.log.msgType,
|
|
@@ -6709,7 +7292,7 @@ export class AUNChannel {
|
|
|
6709
7292
|
handoff_trace: args.log.handoffTrace,
|
|
6710
7293
|
transport: this.sendReceiptFromResult(result),
|
|
6711
7294
|
}));
|
|
6712
|
-
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(
|
|
7295
|
+
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(logContent, 'utf-8'), logContent, false, encrypt, chatmode, 'send');
|
|
6713
7296
|
logWritten = true;
|
|
6714
7297
|
}
|
|
6715
7298
|
return {
|
|
@@ -6732,6 +7315,13 @@ export class AUNChannel {
|
|
|
6732
7315
|
};
|
|
6733
7316
|
}
|
|
6734
7317
|
}
|
|
7318
|
+
/** Reuse the channel-owned storage connection and standard attachment format. */
|
|
7319
|
+
async uploadPaymentImage(data, filename) {
|
|
7320
|
+
if (!this.client || !this.connected)
|
|
7321
|
+
throw new Error('AUN channel is not connected for payment image upload');
|
|
7322
|
+
const uploaded = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image' });
|
|
7323
|
+
return uploaded.attachment;
|
|
7324
|
+
}
|
|
6735
7325
|
/**
|
|
6736
7326
|
* Send an online/offline system notice to the bound Owner as an AUN volatile
|
|
6737
7327
|
* message: nothing is persisted in the outbox or the local message log, and
|
|
@@ -6781,9 +7371,22 @@ export class AUNChannel {
|
|
|
6781
7371
|
contentType: file.contentType,
|
|
6782
7372
|
text: file.text,
|
|
6783
7373
|
transcript: file.transcript,
|
|
7374
|
+
title: file.title,
|
|
6784
7375
|
});
|
|
6785
7376
|
return built.payload;
|
|
6786
7377
|
}
|
|
7378
|
+
/**
|
|
7379
|
+
* 归档 daemon 侧代发的文件(`ec msg send --file` 走这条路径,不经 outbox)。
|
|
7380
|
+
* 与 outbox 投递同一落点与命名规则;归档失败只记日志、返回 null,不阻断发送。
|
|
7381
|
+
* 返回值是写进本地历史的正文:`[文件: 名 → $AGENT_DIR/attachments/…]`。
|
|
7382
|
+
*/
|
|
7383
|
+
archiveDaemonFile(channelId, filePath, as) {
|
|
7384
|
+
const archived = this.archiveOutgoingAttachment(channelId, filePath);
|
|
7385
|
+
if (!archived)
|
|
7386
|
+
return null;
|
|
7387
|
+
const label = as === 'image' ? '图片' : as === 'video' ? '视频' : as === 'voice' ? '语音' : '文件';
|
|
7388
|
+
return `[${label}: ${path.basename(filePath)} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]`;
|
|
7389
|
+
}
|
|
6787
7390
|
/** Daemon-side transport for `ec group send` running inside an agent task. */
|
|
6788
7391
|
async sendDaemonGroupMsg(args) {
|
|
6789
7392
|
if (!args.groupId) {
|
|
@@ -6812,6 +7415,20 @@ export class AUNChannel {
|
|
|
6812
7415
|
else if (payloadMentions !== undefined) {
|
|
6813
7416
|
finalPayload.mentions = payloadMentions;
|
|
6814
7417
|
}
|
|
7418
|
+
if (finalPayload.type === 'widget_card') {
|
|
7419
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
|
|
7420
|
+
const sent = await this.sendContentPayload(args.groupId, finalPayload, {
|
|
7421
|
+
contentKind: 'card', context: { delivery: { chatType: 'group', groupId: args.groupId },
|
|
7422
|
+
sessionId: args.log?.sessionId,
|
|
7423
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7424
|
+
metadata: { encrypted: encrypt } },
|
|
7425
|
+
});
|
|
7426
|
+
if (sent.messageId)
|
|
7427
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', group_id: args.groupId, encrypt };
|
|
7428
|
+
if (sent.queued)
|
|
7429
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, group_id: args.groupId, encrypt };
|
|
7430
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed' };
|
|
7431
|
+
}
|
|
6815
7432
|
if (!this.connected || !this.client) {
|
|
6816
7433
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6817
7434
|
}
|
|
@@ -6838,7 +7455,9 @@ export class AUNChannel {
|
|
|
6838
7455
|
let logWritten = false;
|
|
6839
7456
|
if (args.log?.content !== undefined) {
|
|
6840
7457
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
6841
|
-
const content =
|
|
7458
|
+
const content = args.log.contentAuthoritative
|
|
7459
|
+
? args.log.content
|
|
7460
|
+
: (classified.content || args.log.content);
|
|
6842
7461
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.groupId, this.config.aid);
|
|
6843
7462
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
6844
7463
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -6940,7 +7559,7 @@ export class AUNChannel {
|
|
|
6940
7559
|
echoText += `\n${echoTraceLine({
|
|
6941
7560
|
node: 'EvolCore.reply',
|
|
6942
7561
|
dir: 'ret',
|
|
6943
|
-
hop: Math.max(0, hop - 1
|
|
7562
|
+
hop: Math.max(0, hop) - 1,
|
|
6944
7563
|
ver,
|
|
6945
7564
|
now: doneTs,
|
|
6946
7565
|
extra: `conn_uptime=${this.connectedAt ? Math.round((doneTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7025,7 +7644,7 @@ export class AUNChannel {
|
|
|
7025
7644
|
echoText += `\n${echoTraceLine({
|
|
7026
7645
|
node: 'EvolCore.reply',
|
|
7027
7646
|
dir: 'ret',
|
|
7028
|
-
hop: echoTraceNextHop(echoText),
|
|
7647
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
7029
7648
|
ver,
|
|
7030
7649
|
now: replyTs,
|
|
7031
7650
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7081,11 +7700,6 @@ export class AUNChannel {
|
|
|
7081
7700
|
const finalText = entry.text;
|
|
7082
7701
|
const delivery = this.requirePersistedDelivery(channelId, entry.delivery);
|
|
7083
7702
|
const context = this.withDelivery(entry.context, delivery);
|
|
7084
|
-
if (!entry.deliveryReceipt) {
|
|
7085
|
-
const blocked = await this.prepareAppContactOutbound(channelId, delivery, { type: 'text', text: entry.text });
|
|
7086
|
-
if (blocked)
|
|
7087
|
-
return blocked;
|
|
7088
|
-
}
|
|
7089
7703
|
const operationId = entry.dedupeKey
|
|
7090
7704
|
|| (typeof context?.metadata?.operationId === 'string' ? context.metadata.operationId : undefined);
|
|
7091
7705
|
if (operationId) {
|
|
@@ -7112,9 +7726,7 @@ export class AUNChannel {
|
|
|
7112
7726
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7113
7727
|
// ext assembly (isFinal, seqInTurn, turnMessageCount, loop, fullaccess) is handled
|
|
7114
7728
|
// centrally by withSessionState → buildWireExt; nothing to pre-merge here.
|
|
7115
|
-
const payload = await this.withSessionState(channelId, withAunAttention(
|
|
7116
|
-
type: 'text', text: finalText,
|
|
7117
|
-
}, context?.attention), context);
|
|
7729
|
+
const payload = await this.withSessionState(channelId, withAunAttention(echoTextPayload(finalText), context?.attention), context);
|
|
7118
7730
|
// sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
|
|
7119
7731
|
// 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
|
|
7120
7732
|
if (context?.debug)
|
|
@@ -7355,18 +7967,65 @@ export class AUNChannel {
|
|
|
7355
7967
|
}
|
|
7356
7968
|
}
|
|
7357
7969
|
async deliverPayloadEntry(entry) {
|
|
7358
|
-
if (!entry.deliveryReceipt &&
|
|
7970
|
+
if (!entry.deliveryReceipt && entry.dedupeKey?.startsWith('template-update:')) {
|
|
7971
|
+
const notice = entry.payload?.template_update;
|
|
7972
|
+
if (!notice || entry.dedupeKey !== 'template-update:' + notice.noticeId
|
|
7973
|
+
|| typeof notice.targetAid !== 'string' || !/^[a-z0-9][a-z0-9_-]*(\.[a-z0-9-]+)+$/.test(notice.targetAid)) {
|
|
7974
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_INVALID', error: 'Invalid durable template notice' };
|
|
7975
|
+
}
|
|
7976
|
+
const owner = await ownerResolver.refreshForAuthorization(notice.targetAid);
|
|
7977
|
+
if (owner.refreshFailure || owner.consensusStatus !== 'consensus') {
|
|
7978
|
+
return { ok: false, status: 'retry', code: 'UPDATE_OWNERSHIP_UNAVAILABLE', error: 'Current Agent Owner is unavailable' };
|
|
7979
|
+
}
|
|
7980
|
+
const { TemplateJobs, templateFingerprint, compareTemplateVersions } = await import('../agent-template/jobs.js');
|
|
7981
|
+
const installed = new TemplateJobs(resolvePaths().root).installation(notice.targetAid);
|
|
7982
|
+
const config = loadAgent(notice.targetAid);
|
|
7983
|
+
if (owner.ownerAid !== entry.channelId || config?.update?.mode === 'disabled' || !installed
|
|
7984
|
+
|| installed.ownerAid !== entry.channelId || installed.hostAid !== this.config.aid
|
|
7985
|
+
|| templateFingerprint(installed.source) !== notice.sourceDigest
|
|
7986
|
+
|| installed.release && compareTemplateVersions(installed.release.version, notice.candidateVersion) >= 0) {
|
|
7987
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_STALE', error: 'Owner, source, policy or installed version changed' };
|
|
7988
|
+
}
|
|
7989
|
+
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
7990
|
+
}
|
|
7991
|
+
if (!entry.deliveryReceipt && entry.postSend?.type === 'register_payment_delivery') {
|
|
7992
|
+
const record = paymentStore(this.config.aid).read(entry.postSend.requestId);
|
|
7993
|
+
const binding = currentContactBinding(this.config.aid);
|
|
7994
|
+
if (!binding)
|
|
7995
|
+
return { ok: false, status: 'retry', code: 'PAYMENT_OWNERSHIP_UNAVAILABLE', error: 'Payment Owner is not currently verified' };
|
|
7996
|
+
if (!record || !sameContactBinding(record.binding, binding) || entry.channelId !== binding.owner_aid
|
|
7997
|
+
|| entry.delivery?.chatType !== 'private' || entry.payload?.thread_id !== record.threadId) {
|
|
7998
|
+
return { ok: false, status: 'permanent', code: 'PAYMENT_OWNERSHIP_CHANGED', error: 'Payment no longer belongs to this Owner conversation' };
|
|
7999
|
+
}
|
|
8000
|
+
}
|
|
8001
|
+
if (entry.payload?.type === 'friend.request.v1' && entry.payload.direction === 'outbound') {
|
|
8002
|
+
return { ok: false, status: 'permanent', code: 'OUTBOUND_APPROVAL_RETIRED', error: 'outbound contact approval is no longer required' };
|
|
8003
|
+
}
|
|
8004
|
+
if (!entry.deliveryReceipt && ((typeof entry.payload?.type === 'string' && entry.payload.type.startsWith('friend.'))
|
|
8005
|
+
|| isContactApprovalCard(entry.payload))) {
|
|
7359
8006
|
const selfAid = this.config.aid;
|
|
7360
8007
|
const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'contact.outbox' });
|
|
7361
8008
|
const binding = verifiedContactBinding(selfAid, view);
|
|
7362
8009
|
if (!binding)
|
|
7363
8010
|
return { ok: false, status: 'retry', code: 'CONTACT_OWNERSHIP_UNAVAILABLE', error: 'current Owner relation could not be verified' };
|
|
7364
|
-
|
|
8011
|
+
const routePayload = isContactApprovalCard(entry.payload) ? entry.payload?.friend_request ?? {} : entry.payload;
|
|
8012
|
+
if (!friendPayloadRouteValid(routePayload, entry.channelId, true, binding)) {
|
|
7365
8013
|
return { ok: false, status: 'permanent', code: 'CONTACT_OWNERSHIP_CHANGED', error: 'contact event no longer belongs to the current Owner relation' };
|
|
7366
8014
|
}
|
|
7367
8015
|
// E2EE is mandatory even for a recovered queue entry.
|
|
7368
8016
|
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
7369
8017
|
}
|
|
8018
|
+
if (!entry.deliveryReceipt && isContactApprovalCard(entry.payload)) {
|
|
8019
|
+
const action = entry.postSend;
|
|
8020
|
+
const pending = action?.type === 'register_contact_approval_card'
|
|
8021
|
+
? readPendingContactInbound(this.config.aid, action.pendingKey) : undefined;
|
|
8022
|
+
if (!pending?.message || !pending.approval || !['waiting', 'transferring'].includes(pending.state)
|
|
8023
|
+
|| pending.approval.eventId !== entry.payload?.friend_request?.event_id
|
|
8024
|
+
|| pending.expiresAt <= Date.now()
|
|
8025
|
+
|| normalizeThreadIdForPeer(entry.payload?.thread_id, this.config.aid, entry.channelId) !== pending.approval.originThreadId) {
|
|
8026
|
+
return { ok: false, status: 'permanent', code: 'CONTACT_APPROVAL_STALE', error: 'contact approval card is no longer pending' };
|
|
8027
|
+
}
|
|
8028
|
+
}
|
|
7370
8029
|
const interactionId = entry.postSend?.type === 'register_interaction_card'
|
|
7371
8030
|
? entry.postSend.requestId
|
|
7372
8031
|
: undefined;
|
|
@@ -7383,7 +8042,7 @@ export class AUNChannel {
|
|
|
7383
8042
|
return { ok: true, status: 'sent' };
|
|
7384
8043
|
}
|
|
7385
8044
|
}
|
|
7386
|
-
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card'
|
|
8045
|
+
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card' || entry.postSend?.type === 'register_widget_card'
|
|
7387
8046
|
? entry.postSend.expiresAt
|
|
7388
8047
|
: undefined;
|
|
7389
8048
|
if (typeof interactionExpiresAt === 'number'
|
|
@@ -7412,15 +8071,16 @@ export class AUNChannel {
|
|
|
7412
8071
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7413
8072
|
if (entry.deliveryReceipt) {
|
|
7414
8073
|
try {
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
|
|
7422
|
-
|
|
7423
|
-
|
|
8074
|
+
if (!isContactApprovalCard(payload))
|
|
8075
|
+
this.appendOutboundJsonl(channelId, {
|
|
8076
|
+
...classifyAunPayloadForLog(payload),
|
|
8077
|
+
msgId: entry.deliveryReceipt.messageId,
|
|
8078
|
+
encrypt: entry.deliveryReceipt.encrypt,
|
|
8079
|
+
context,
|
|
8080
|
+
isGroup,
|
|
8081
|
+
source,
|
|
8082
|
+
transport: entry.deliveryReceipt.transport,
|
|
8083
|
+
});
|
|
7424
8084
|
this.runPostSend(entry, entry.deliveryReceipt.messageId);
|
|
7425
8085
|
return {
|
|
7426
8086
|
ok: true,
|
|
@@ -7654,9 +8314,15 @@ export class AUNChannel {
|
|
|
7654
8314
|
}
|
|
7655
8315
|
const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
|
|
7656
8316
|
const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
|
|
7657
|
-
&&
|
|
8317
|
+
&& isProjectionServiceResult(finalPayload.type);
|
|
7658
8318
|
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
7659
|
-
|
|
8319
|
+
// volatile TTL 由调用方按自己的等待期给出;服务应答据此避免在调用方放弃后
|
|
8320
|
+
// 仍被当成持久消息补投一次。
|
|
8321
|
+
const ttl = typeof context?.ttl === 'number' && Number.isInteger(context.ttl)
|
|
8322
|
+
&& context.ttl >= 1 && context.ttl <= MAX_AUN_VOLATILE_TTL_SECONDS
|
|
8323
|
+
? context.ttl
|
|
8324
|
+
: undefined;
|
|
8325
|
+
const params = { payload: finalPayload, encrypt, ...(ttl !== undefined ? { ttl } : {}) };
|
|
7660
8326
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
7661
8327
|
params.to_device_id = context?.toDeviceId;
|
|
7662
8328
|
if (isMenuPayload && typeof context?.metadata?.menuClientSdkVersion === 'string') {
|
|
@@ -7844,7 +8510,7 @@ export class AUNChannel {
|
|
|
7844
8510
|
else if (result.status === 'permanent')
|
|
7845
8511
|
this.markPermanentOutboxFailure(entry, result);
|
|
7846
8512
|
}
|
|
7847
|
-
async buildUploadedImagePayload(data, mimeType, alt) {
|
|
8513
|
+
async buildUploadedImagePayload(data, mimeType, alt, channelId) {
|
|
7848
8514
|
if (!this.connected || !this.client) {
|
|
7849
8515
|
throw new Error('AUN channel is not connected; image cannot be uploaded');
|
|
7850
8516
|
}
|
|
@@ -7870,16 +8536,25 @@ export class AUNChannel {
|
|
|
7870
8536
|
const digest = crypto.createHash('sha256').update(data).digest('hex').slice(0, 12);
|
|
7871
8537
|
const filename = `image-${digest}.${extension}`;
|
|
7872
8538
|
const built = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image', contentType });
|
|
8539
|
+
// 出站图片同样归档到关系目录(与入站图片、收发文件同一落点)。
|
|
8540
|
+
const archived = channelId
|
|
8541
|
+
? this.archiveOutgoingBuffer(channelId, data, filename, contentType)
|
|
8542
|
+
: null;
|
|
7873
8543
|
const imagePayload = { ...built.payload };
|
|
7874
8544
|
setIfDefined(imagePayload, 'alt', alt);
|
|
7875
|
-
return imagePayload;
|
|
8545
|
+
return { payload: imagePayload, archived };
|
|
7876
8546
|
}
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
return blocked;
|
|
8547
|
+
/** 内存中的出站附件归档(图片走这条:数据不落临时文件)。 */
|
|
8548
|
+
archiveOutgoingBuffer(channelId, data, filename, contentType) {
|
|
8549
|
+
try {
|
|
8550
|
+
return saveRelationAttachment(data, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename, allowAnyExtension: true, direction: 'out' });
|
|
7882
8551
|
}
|
|
8552
|
+
catch (error) {
|
|
8553
|
+
logger.warn(`${this.logPrefix()} Outgoing image archive failed for ${filename}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8554
|
+
return null;
|
|
8555
|
+
}
|
|
8556
|
+
}
|
|
8557
|
+
async deliverImageEntry(entry) {
|
|
7883
8558
|
const image = entry.image;
|
|
7884
8559
|
if (!image || typeof image.dataBase64 !== 'string') {
|
|
7885
8560
|
logger.warn(`${this.logPrefix()} deliverImageEntry: missing image data (outbox id=${entry.id})`);
|
|
@@ -7894,11 +8569,14 @@ export class AUNChannel {
|
|
|
7894
8569
|
return { status: 'permanent', error: 'durable image data is invalid', code: 'INVALID_IMAGE_DATA' };
|
|
7895
8570
|
}
|
|
7896
8571
|
try {
|
|
7897
|
-
const imagePayload = await this.buildUploadedImagePayload(data, image.mimeType, image.alt);
|
|
8572
|
+
const { payload: imagePayload, archived } = await this.buildUploadedImagePayload(data, image.mimeType, image.alt, entry.channelId);
|
|
7898
8573
|
entry.type = 'payload';
|
|
7899
8574
|
entry.contentKind = 'image';
|
|
7900
8575
|
entry.payload = this.applyReplyContextToPayload(imagePayload, entry.context);
|
|
7901
|
-
|
|
8576
|
+
// 图片与文件同一规则:历史里记关系目录里的归档路径。
|
|
8577
|
+
entry.logText ??= archived
|
|
8578
|
+
? `[图片: ${image.alt || path.basename(archived.filePath)} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]`
|
|
8579
|
+
: (image.alt ? `[image] ${image.alt}` : '[image]');
|
|
7902
8580
|
delete entry.image;
|
|
7903
8581
|
// Persist the attachment reference before message.send. A failed send then
|
|
7904
8582
|
// retries the compact wire payload without re-uploading the same image.
|
|
@@ -7925,12 +8603,24 @@ export class AUNChannel {
|
|
|
7925
8603
|
return failure;
|
|
7926
8604
|
}
|
|
7927
8605
|
}
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
8606
|
+
/**
|
|
8607
|
+
* 出站附件归档:把要发送的文件在关系目录留一份。
|
|
8608
|
+
*
|
|
8609
|
+
* 与入站同一落点(`$RELATIONS_DIR/<peerKey>/attachments/`)、同一命名规则
|
|
8610
|
+
* (原始文件名,重名 `-N`,内容相同则复用)。归档失败只记日志、不阻断发送:
|
|
8611
|
+
* 发送本身是主路径,历史可读性是附带收益。
|
|
8612
|
+
*/
|
|
8613
|
+
archiveOutgoingAttachment(channelId, absPath, contentType) {
|
|
8614
|
+
try {
|
|
8615
|
+
const buffer = fs.readFileSync(absPath);
|
|
8616
|
+
return saveRelationAttachment(buffer, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename: path.basename(absPath), allowAnyExtension: true, direction: 'out' });
|
|
7933
8617
|
}
|
|
8618
|
+
catch (error) {
|
|
8619
|
+
logger.warn(`${this.logPrefix()} Outgoing attachment archive failed for ${absPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8620
|
+
return null;
|
|
8621
|
+
}
|
|
8622
|
+
}
|
|
8623
|
+
async deliverFileEntry(entry) {
|
|
7934
8624
|
const channelId = entry.channelId;
|
|
7935
8625
|
if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
|
|
7936
8626
|
logger.warn(`${this.logPrefix()} deliverFileEntry: missing file path (outbox id=${entry.id})`);
|
|
@@ -7941,9 +8631,14 @@ export class AUNChannel {
|
|
|
7941
8631
|
const context = this.withDelivery(entry.context, delivery);
|
|
7942
8632
|
const isGroup = delivery.chatType === 'group';
|
|
7943
8633
|
const source = context?.metadata?.source ?? 'daemon';
|
|
8634
|
+
// 归档在两条分支之前做:回执恢复分支也要能引用归档路径。
|
|
8635
|
+
// 该调用是幂等的(同内容复用同一文件,只追加一条元数据),重复执行安全。
|
|
8636
|
+
const fileArchived = this.archiveOutgoingAttachment(channelId, absPath);
|
|
7944
8637
|
if (entry.deliveryReceipt) {
|
|
7945
8638
|
const filename = path.basename(absPath);
|
|
7946
|
-
const logText = entry.logText ??
|
|
8639
|
+
const logText = entry.logText ?? (fileArchived
|
|
8640
|
+
? `[文件: ${filename} → ${toAttachmentMarkedPath(this.config.aid, fileArchived.filePath)}]`
|
|
8641
|
+
: `[file] ${filename}`);
|
|
7947
8642
|
try {
|
|
7948
8643
|
this.appendOutboundJsonl(channelId, {
|
|
7949
8644
|
...classifyAunPayloadForLog({ type: 'file', text: logText }),
|
|
@@ -7969,6 +8664,8 @@ export class AUNChannel {
|
|
|
7969
8664
|
try {
|
|
7970
8665
|
const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
|
|
7971
8666
|
const { filename, size_bytes: size, content_type: contentType } = attachment;
|
|
8667
|
+
// 归档已在分支之前完成(fileArchived);归档失败不阻断发送,历史里落源路径。
|
|
8668
|
+
const archived = fileArchived;
|
|
7972
8669
|
const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
|
|
7973
8670
|
filename,
|
|
7974
8671
|
size,
|
|
@@ -8071,7 +8768,12 @@ export class AUNChannel {
|
|
|
8071
8768
|
const statsContext = isGroup ? await this.groupStatsContext(channelId) : undefined;
|
|
8072
8769
|
this.aidStatsCollector?.recordOutbound(this.config.aid, channelId, Buffer.byteLength(fileText, 'utf-8'), fileText, false, !!params.encrypt, context?.metadata?.chatmode, 'send', statsContext);
|
|
8073
8770
|
this.appendOutboundJsonl(channelId, {
|
|
8074
|
-
...classifyAunPayloadForLog(filePayload),
|
|
8771
|
+
...classifyAunPayloadForLog(filePayload),
|
|
8772
|
+
// 有归档副本就记归档路径;没有则在正文里补源路径,避免历史只剩文件名。
|
|
8773
|
+
...(archived
|
|
8774
|
+
? { content: `[文件: ${filename} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]` }
|
|
8775
|
+
: { content: `[文件: ${filename} → ${absPath}]` }),
|
|
8776
|
+
msgId: sentMid, encrypt: !!params.encrypt,
|
|
8075
8777
|
context, isGroup, source, transport: this.sendReceiptFromResult(sendResult),
|
|
8076
8778
|
});
|
|
8077
8779
|
if (sendResult)
|
|
@@ -8983,21 +9685,25 @@ export class AUNChannelPlugin {
|
|
|
8983
9685
|
if (req.kind.kind === 'action') {
|
|
8984
9686
|
const isAsyncQuestion = /^aq-[a-f0-9]{40}$/.test(req.id);
|
|
8985
9687
|
const action = req.kind;
|
|
8986
|
-
const aunCard =
|
|
8987
|
-
|
|
8988
|
-
|
|
8989
|
-
|
|
8990
|
-
|
|
8991
|
-
|
|
8992
|
-
|
|
8993
|
-
|
|
8994
|
-
|
|
8995
|
-
|
|
8996
|
-
|
|
9688
|
+
const aunCard = action.widget
|
|
9689
|
+
? withAunAttention(await channel.buildDaemonFilePayload({
|
|
9690
|
+
filePath: action.widget.filePath, as: 'widget_card', title: action.title, text: action.body,
|
|
9691
|
+
}))
|
|
9692
|
+
: withAunAttention({
|
|
9693
|
+
type: 'action_card',
|
|
9694
|
+
title: action.title,
|
|
9695
|
+
...(req.sensitive ? { sensitive: true } : {}),
|
|
9696
|
+
...(req.blocking === true ? { blocking: true } : {}),
|
|
9697
|
+
...(action.recommendedOption ? { recommended_option: action.recommendedOption } : {}),
|
|
9698
|
+
actions: action.buttons.map(btn => ({
|
|
9699
|
+
label: action.recommendedOption === btn.key ? `💡 ${btn.label}` : btn.label,
|
|
9700
|
+
value: btn.key, style: btn.style ?? 'default', behavior: 'reply',
|
|
9701
|
+
})),
|
|
9702
|
+
});
|
|
8997
9703
|
// AUN action_card 以 compose behavior 声明自由文本动作。新版客户端
|
|
8998
9704
|
// 在卡片内采集并确认;旧版客户端可继续从主编辑器采集。两者都结构化
|
|
8999
9705
|
// 回传 action_card_reply{behavior:"compose"},Core 不拦截普通消息队列。
|
|
9000
|
-
if (action.allowCustomInput) {
|
|
9706
|
+
if (!action.widget && action.allowCustomInput) {
|
|
9001
9707
|
aunCard.actions.push({
|
|
9002
9708
|
label: '✏️ 手动输入', style: 'default', behavior: 'compose',
|
|
9003
9709
|
...(req.sensitive ? { sensitive: true } : {}),
|
|
@@ -9008,6 +9714,10 @@ export class AUNChannelPlugin {
|
|
|
9008
9714
|
aunCard.text = action.body;
|
|
9009
9715
|
setIfDefined(aunCard, 'format', action.bodyFormat);
|
|
9010
9716
|
}
|
|
9717
|
+
if (action.widget && req.blocking === true)
|
|
9718
|
+
aunCard.blocking = true;
|
|
9719
|
+
if (action.widget && req.sensitive)
|
|
9720
|
+
aunCard.sensitive = true;
|
|
9011
9721
|
if (req.initiatorId && replyCtx?.delivery?.chatType === 'group')
|
|
9012
9722
|
aunCard.initiator = req.initiatorId;
|
|
9013
9723
|
if (isTopicThreadId(replyCtx?.threadId))
|
|
@@ -9032,6 +9742,7 @@ export class AUNChannelPlugin {
|
|
|
9032
9742
|
initiatorAid: req.initiatorId,
|
|
9033
9743
|
delivery: replyCtx?.delivery,
|
|
9034
9744
|
expiresAt: cardExpiresAt,
|
|
9745
|
+
...(action.widget ? { widget: true } : {}),
|
|
9035
9746
|
},
|
|
9036
9747
|
});
|
|
9037
9748
|
return toInteractionReceipt(result);
|
|
@@ -9140,8 +9851,9 @@ export class AUNChannelPlugin {
|
|
|
9140
9851
|
disconnect: (clientCloseBudgetMs) => channel.disconnect(clientCloseBudgetMs),
|
|
9141
9852
|
onProjectPathRequest: () => Promise.resolve(ctx.defaultProjectPath),
|
|
9142
9853
|
registerBridge(bridge, channelType) {
|
|
9854
|
+
channel.setContactReplayReceiptResolver(key => bridge.contactDeliveryReceipt(key), delivery => bridge.finishContactDelivery(delivery));
|
|
9143
9855
|
bridge.register(adapter.channelName, (handler) => channel.onMessage(async (opts) => {
|
|
9144
|
-
handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9856
|
+
await handler(aunOptsToInbound(opts, adapter.channelName, channelType));
|
|
9145
9857
|
}), async (channelId, text, replyContext) => { await channel.sendMessage(channelId, text, replyContext); }, adapter, channelType);
|
|
9146
9858
|
bridge.registerGroupInviteReviewChannel({
|
|
9147
9859
|
selfAid: aid,
|
|
@@ -9208,6 +9920,12 @@ export class AUNChannelPlugin {
|
|
|
9208
9920
|
}, { cache: true }).mentionMode;
|
|
9209
9921
|
});
|
|
9210
9922
|
}
|
|
9923
|
+
if (typeof channel.setPrivateMentionModeResolver === 'function') {
|
|
9924
|
+
// Agent-level only: no peerKey, so a relation-level override cannot leak in.
|
|
9925
|
+
channel.setPrivateMentionModeResolver(async () => {
|
|
9926
|
+
return resolveEffective({ self: aid }, { cache: true }).privateMentionMode;
|
|
9927
|
+
});
|
|
9928
|
+
}
|
|
9211
9929
|
if (typeof channel.setGroupSlashRequireMentionsResolver === 'function') {
|
|
9212
9930
|
channel.setGroupSlashRequireMentionsResolver(async () => {
|
|
9213
9931
|
return resolveEffective({ self: aid }, { cache: true }).groupSlashRequireMentions ?? true;
|