evolcore 0.0.47 → 0.0.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trustedContactInboundDelivery } from './contact-pending-inbound.js';
|
|
1
2
|
import { loadAgent } from '../../config-store.js';
|
|
2
3
|
import { subscribeUpgradeJob } from '../../utils/upgrade-jobs.js';
|
|
3
4
|
import { initializationBlocksTasks } from '../../cli/agent-create.js';
|
|
@@ -10,34 +11,31 @@ import { containsAgentMdMenuRequest } from '../command/agentmd-menu-request.js';
|
|
|
10
11
|
import { currentContactBinding, sameContactBinding } from './contact-admission.js';
|
|
11
12
|
import { logger, logPreview } from '../../utils/logger.js';
|
|
12
13
|
import { StreamDebouncer } from './stream-debouncer.js';
|
|
13
|
-
import { appendMessageLog, appendMessageLogStrict, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
|
|
14
|
-
import { buildEnvelope
|
|
14
|
+
import { appendMessageLog, appendMessageLogStrict, appendInboundMessageLogOnce, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
|
|
15
|
+
import { buildEnvelope } from './message-utils.js';
|
|
15
16
|
import { chatDirPath } from '../session/session-fs-store.js';
|
|
16
|
-
import {
|
|
17
|
+
import { readTopicStatus } from '../session/session-mapper.js';
|
|
17
18
|
import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
|
|
18
19
|
import { agentDir, resolvePaths } from '../../paths.js';
|
|
19
|
-
import {
|
|
20
|
+
import { resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
|
|
20
21
|
import { resolvePeerView, resolvePeerDisplayLabel, resolvePrincipal } from '../../config/peer-book.js';
|
|
21
|
-
import { findPeerRequestNote, expirePendingPeerRequests, reviewPeerRequest, submitPeerRequest, peerRequestSubmissionProtocolResult, queryOwnPeerRequestStatus, } from '../../config/peer-request-service.js';
|
|
22
22
|
import { isValidAid } from '../../aun/aid/validation.js';
|
|
23
23
|
import { prepareOwnerDirectoryAdmission } from '../../directory/owner-directory-admission.js';
|
|
24
24
|
import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
|
|
25
25
|
import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
|
|
26
|
-
import { isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
|
|
26
|
+
import { isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
|
|
27
27
|
import { resolveEffective } from '../../config/config-manager.js';
|
|
28
28
|
import { createDecisionInferenceProvider } from '../inference/text-inference.js';
|
|
29
29
|
import { AutoMentionGate } from './auto-mention-gate.js';
|
|
30
30
|
import { syncGroupRulesContext } from '../../eck/group-rules-sync.js';
|
|
31
31
|
import { readSoulContent } from '../soul.js';
|
|
32
32
|
import { authorizeAccess, buildAuthSubject } from '../auth/auth-gateway.js';
|
|
33
|
-
import { MenuDiagnosticLimiter, deliverMenuResponse, isRetryableMenuTransportError, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, beginMenuDeliveryTiming, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, } from '../command/menu-protocol.js';
|
|
33
|
+
import { MenuDiagnosticLimiter, deliverMenuResponse, isRetryableMenuTransportError, MenuRequestDeduper, hasValidMenuId, menuFailure, menuPayloadFingerprint, menuSuccess, normalizeMenuError, parseMenuControl, validateMenuRequest, evaluateEvolMenuVersionGate, evolMenuResponseTransportMetadata, isAunMenuTokenRequired, menuCommandForName, normalizeMenuResponseTiming, withMenuProcessingTime, beginMenuDeliveryTiming, logMenuRequestCompleted, logMenuRequestReceived, logMenuResponseRetry, traceMenuStage, } from '../command/menu-protocol.js';
|
|
34
34
|
import { resolveExplicitMenuExecutionContext, validateMenuCatalogArgs, validateMenuValueBatchArgs } from '../command/menu-catalog.js';
|
|
35
35
|
import { MenuTokenStore } from '../command/menu-token-store.js';
|
|
36
36
|
import { SessionRenewService } from '../session/session-renew.js';
|
|
37
37
|
import { createRootCausation, deriveCausation, normalizeCausation } from '../causation/context.js';
|
|
38
38
|
import { recordCausationSpan } from '../causation/audit.js';
|
|
39
|
-
import { renderActionAsText } from '../interaction-router.js';
|
|
40
|
-
import { planApprovalRoute } from '../permission/approval-gateway.js';
|
|
41
39
|
import { guardGroupSlashCommand, parseFullAccessCommand } from '../command/slash-gate.js';
|
|
42
40
|
import { createAgentPolicyAuthorization, createSessionFullAccessAuthorization } from '../role/runtime-policy.js';
|
|
43
41
|
import { auditFullAccessEvent } from '../auth/authorization-audit.js';
|
|
@@ -48,6 +46,22 @@ const REJECTABLE_PEER_TYPES = new Set(['ai', 'bot', 'agent', 'service']);
|
|
|
48
46
|
const REJECTION_MAX = 3;
|
|
49
47
|
const REJECTION_WINDOW_MS = 60 * 60 * 1000;
|
|
50
48
|
const rejectionState = new Map();
|
|
49
|
+
/**
|
|
50
|
+
* Topic admission runs after session resolution and before task queueing.
|
|
51
|
+
*
|
|
52
|
+
* 纯函数,导出以便单测直接覆盖各状态组合(回退 / 丢弃 / 是否回文案)。
|
|
53
|
+
*/
|
|
54
|
+
export function decideTopicInbound(input) {
|
|
55
|
+
if (!input.isTopic)
|
|
56
|
+
return { action: 'proceed', reopen: false, replyArchived: false };
|
|
57
|
+
if (input.topicStatus === 'archived') {
|
|
58
|
+
return { action: 'drop-archived', reopen: false, replyArchived: input.chatType !== 'group' };
|
|
59
|
+
}
|
|
60
|
+
if (input.topicStatus === 'closed') {
|
|
61
|
+
return { action: 'proceed', reopen: true, replyArchived: false };
|
|
62
|
+
}
|
|
63
|
+
return { action: 'proceed', reopen: false, replyArchived: false };
|
|
64
|
+
}
|
|
51
65
|
export function shouldBlockInboundContact(input) {
|
|
52
66
|
if (!input.selfAid) {
|
|
53
67
|
return { blocked: false, status: 'unsupported-channel' };
|
|
@@ -467,175 +481,6 @@ export class MessageBridge {
|
|
|
467
481
|
}
|
|
468
482
|
return false;
|
|
469
483
|
}
|
|
470
|
-
async handleContactRequestProtocol(input) {
|
|
471
|
-
const { context, msg, content, owningAgent, adapter, sendReply } = input;
|
|
472
|
-
const requestMatch = /^\s*\/request(?:\s+([\s\S]*?))?\s*$/i.exec(content);
|
|
473
|
-
let protocolType;
|
|
474
|
-
let protocolPayload;
|
|
475
|
-
try {
|
|
476
|
-
const parsed = JSON.parse(content);
|
|
477
|
-
protocolPayload = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
478
|
-
? parsed
|
|
479
|
-
: undefined;
|
|
480
|
-
protocolType = protocolPayload?.type === 'contact.request.query'
|
|
481
|
-
? 'query'
|
|
482
|
-
: protocolPayload?.type === 'contact.request.submit' ? 'submit' : undefined;
|
|
483
|
-
}
|
|
484
|
-
catch { /* slash command */ }
|
|
485
|
-
if (!requestMatch && !protocolType)
|
|
486
|
-
return false;
|
|
487
|
-
if (context.channelType === 'aun') {
|
|
488
|
-
// The App owns requests; retired commands cannot create a second approval state.
|
|
489
|
-
return true;
|
|
490
|
-
}
|
|
491
|
-
// Slash commands keep their human-facing response semantics. Structured
|
|
492
|
-
// App requests use contact.request.response and never fall through to the
|
|
493
|
-
// normal command/session pipeline.
|
|
494
|
-
if (requestMatch) {
|
|
495
|
-
// Blacklist remains the first gate even though slash controls are
|
|
496
|
-
// recognized before ordinary admission. Let the normal blocked path
|
|
497
|
-
// decide whether an agent/bot/service gets a limited rejection.
|
|
498
|
-
if (context.contactStatus === 'blocked')
|
|
499
|
-
return false;
|
|
500
|
-
if (context.channelType !== 'aun') {
|
|
501
|
-
await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
|
|
502
|
-
return true;
|
|
503
|
-
}
|
|
504
|
-
if (context.chatType !== 'private') {
|
|
505
|
-
await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
|
|
506
|
-
return true;
|
|
507
|
-
}
|
|
508
|
-
if (!context.primaryId || context.principal?.principalStatus !== 'native_aid') {
|
|
509
|
-
await this.sendAdmissionControlReply(context, msg, sendReply, '无法验证当前 AUN 身份,未提交联系人申请。');
|
|
510
|
-
return true;
|
|
511
|
-
}
|
|
512
|
-
try {
|
|
513
|
-
const submission = await submitPeerRequest({
|
|
514
|
-
selfAid: context.selfAid,
|
|
515
|
-
applicantAid: context.primaryId,
|
|
516
|
-
note: requestMatch[1],
|
|
517
|
-
sourceChannelKey: context.channelKey,
|
|
518
|
-
routeKind: 'private',
|
|
519
|
-
});
|
|
520
|
-
if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
|
|
521
|
-
void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
|
|
522
|
-
.catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
523
|
-
}
|
|
524
|
-
await this.sendAdmissionControlReply(context, msg, sendReply, this.contactRequestReply(submission));
|
|
525
|
-
}
|
|
526
|
-
catch (error) {
|
|
527
|
-
logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
528
|
-
await this.sendAdmissionControlReply(context, msg, sendReply, '当前无法受理联系人申请,请稍后再试。');
|
|
529
|
-
}
|
|
530
|
-
return true;
|
|
531
|
-
}
|
|
532
|
-
// The structured protocol is AUN-only. For a blocked external alias,
|
|
533
|
-
// return false so the existing blacklist response/silence policy applies;
|
|
534
|
-
// never emit a custom payload through a non-AUN adapter.
|
|
535
|
-
if (context.contactStatus === 'blocked' && context.channelType !== 'aun')
|
|
536
|
-
return false;
|
|
537
|
-
if (context.channelType !== 'aun')
|
|
538
|
-
return true;
|
|
539
|
-
if (context.chatType !== 'private')
|
|
540
|
-
return true;
|
|
541
|
-
if (context.principal?.principalStatus !== 'native_aid' || !context.primaryId) {
|
|
542
|
-
await this.sendContactRequestProtocolResponse(adapter, msg, {
|
|
543
|
-
status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
|
|
544
|
-
}, owningAgent?.name);
|
|
545
|
-
return true;
|
|
546
|
-
}
|
|
547
|
-
if (context.contactStatus === 'blocked') {
|
|
548
|
-
await this.sendContactRequestProtocolResponse(adapter, msg, {
|
|
549
|
-
status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
|
|
550
|
-
}, owningAgent?.name);
|
|
551
|
-
return true;
|
|
552
|
-
}
|
|
553
|
-
let result;
|
|
554
|
-
if (protocolType === 'query') {
|
|
555
|
-
try {
|
|
556
|
-
result = await queryOwnPeerRequestStatus({
|
|
557
|
-
selfAid: context.selfAid,
|
|
558
|
-
applicantAid: context.primaryId,
|
|
559
|
-
requestId: protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'request_id')
|
|
560
|
-
? protocolPayload.request_id
|
|
561
|
-
: undefined,
|
|
562
|
-
});
|
|
563
|
-
}
|
|
564
|
-
catch (error) {
|
|
565
|
-
logger.warn(`[MessageBridge] Contact request query failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
566
|
-
result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
else {
|
|
570
|
-
try {
|
|
571
|
-
if (protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'note')
|
|
572
|
-
&& typeof protocolPayload?.note !== 'string') {
|
|
573
|
-
await this.sendContactRequestProtocolResponse(adapter, msg, {
|
|
574
|
-
status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
|
|
575
|
-
}, owningAgent?.name);
|
|
576
|
-
return true;
|
|
577
|
-
}
|
|
578
|
-
const submission = await submitPeerRequest({
|
|
579
|
-
selfAid: context.selfAid,
|
|
580
|
-
applicantAid: context.primaryId,
|
|
581
|
-
note: typeof protocolPayload?.note === 'string' ? protocolPayload.note : undefined,
|
|
582
|
-
sourceChannelKey: context.channelKey,
|
|
583
|
-
routeKind: 'private',
|
|
584
|
-
});
|
|
585
|
-
result = peerRequestSubmissionProtocolResult(submission);
|
|
586
|
-
if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
|
|
587
|
-
void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
|
|
588
|
-
.catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
catch (error) {
|
|
592
|
-
logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
593
|
-
result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
await this.sendContactRequestProtocolResponse(adapter, msg, result, owningAgent?.name);
|
|
597
|
-
return true;
|
|
598
|
-
}
|
|
599
|
-
contactRequestReply(result) {
|
|
600
|
-
switch (result.code) {
|
|
601
|
-
case 'submitted': return '联系人申请已提交,等待管理员审核。';
|
|
602
|
-
case 'resubmitted': return '联系人申请已更新,等待管理员审核。';
|
|
603
|
-
case 'already-contact': return '你已经是联系人。';
|
|
604
|
-
case 'owner': return '你已经是 Owner。';
|
|
605
|
-
case 'blocked': return CONTACT_REJECTION_NOTICE;
|
|
606
|
-
case 'rate-limited': return '联系人申请过于频繁,请稍后再试。';
|
|
607
|
-
case 'capacity': return '当前申请较多,请稍后再试。';
|
|
608
|
-
case 'no-owner': return '当前无法受理联系人申请。';
|
|
609
|
-
case 'invalid-applicant': return '无法验证当前 AUN 身份,未提交联系人申请。';
|
|
610
|
-
case 'invalid-note': return '申请说明不能超过 500 个字符。';
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
async sendContactRequestProtocolResponse(adapter, msg, result, agentName) {
|
|
614
|
-
if (!adapter?.send)
|
|
615
|
-
return;
|
|
616
|
-
await adapter.send(buildEnvelope({
|
|
617
|
-
taskId: `contact-request-${randomBytes(4).toString('hex')}`,
|
|
618
|
-
channel: adapter.channelName,
|
|
619
|
-
channelId: msg.channelId,
|
|
620
|
-
agentName: agentName ?? '<unknown>',
|
|
621
|
-
replyContext: {
|
|
622
|
-
...(msg.replyContext ?? {}),
|
|
623
|
-
metadata: {
|
|
624
|
-
...(msg.replyContext?.metadata ?? {}),
|
|
625
|
-
...evolMenuResponseTransportMetadata(msg.protectedHeaders?.sdk_version),
|
|
626
|
-
},
|
|
627
|
-
},
|
|
628
|
-
}), {
|
|
629
|
-
kind: 'custom',
|
|
630
|
-
channelType: 'aun',
|
|
631
|
-
payload: {
|
|
632
|
-
type: 'contact.request.response',
|
|
633
|
-
status: result.status,
|
|
634
|
-
request_id: result.requestId,
|
|
635
|
-
expires_at: result.expiresAt,
|
|
636
|
-
},
|
|
637
|
-
});
|
|
638
|
-
}
|
|
639
484
|
async sendAdmissionControlReply(context, msg, sendReply, text) {
|
|
640
485
|
if (!text || !consumeAdmissionReplyBudget(context))
|
|
641
486
|
return false;
|
|
@@ -685,155 +530,6 @@ export class MessageBridge {
|
|
|
685
530
|
}
|
|
686
531
|
return '当前不接受非联系人消息。联系人申请仅支持 AUN 私聊。';
|
|
687
532
|
}
|
|
688
|
-
async deliverContactReviewCard(selfAid, applicantAid, submission, owningAgent) {
|
|
689
|
-
if (!this.interactionRouter || !submission.requestId || !submission.expiresAt || !submission.submittedAt) {
|
|
690
|
-
return false;
|
|
691
|
-
}
|
|
692
|
-
const ownerAdapterKey = formatChannelKey({ type: 'aun', selfAID: selfAid, name: 'main' });
|
|
693
|
-
const ownerAdapter = this.processor.getChannelInfo?.(ownerAdapterKey)?.adapter;
|
|
694
|
-
const resolveApproverCandidates = () => ({
|
|
695
|
-
owners: listStaticAgentOwners(selfAid, { fresh: true }),
|
|
696
|
-
admins: listStaticAgentAdmins(selfAid, { fresh: true }),
|
|
697
|
-
});
|
|
698
|
-
const { owners, admins } = resolveApproverCandidates();
|
|
699
|
-
const route = planApprovalRoute({
|
|
700
|
-
id: submission.requestId,
|
|
701
|
-
sessionId: `contact-request:${selfAid}:${submission.requestId}`,
|
|
702
|
-
toolName: 'contact.request.review',
|
|
703
|
-
toolInput: { applicantAid, requestId: submission.requestId },
|
|
704
|
-
summary: `Review contact request from ${applicantAid}`,
|
|
705
|
-
grantable: true,
|
|
706
|
-
// Contact membership is an Agent-owner decision. Do not use the broader
|
|
707
|
-
// agent_manager policy here: that policy intentionally prefers an Admin,
|
|
708
|
-
// which made request cards invisible to the configured Owner.
|
|
709
|
-
approverPolicy: 'agent_owner',
|
|
710
|
-
createdAt: Date.parse(submission.submittedAt),
|
|
711
|
-
}, {
|
|
712
|
-
userId: applicantAid,
|
|
713
|
-
chatType: 'private',
|
|
714
|
-
selfAid,
|
|
715
|
-
approvalRouting: {
|
|
716
|
-
approverPolicy: 'agent_owner',
|
|
717
|
-
owners,
|
|
718
|
-
admins,
|
|
719
|
-
resolveApproverCandidates,
|
|
720
|
-
ownerAdapter,
|
|
721
|
-
forceHandoff: true,
|
|
722
|
-
selfAid,
|
|
723
|
-
originSessionId: `contact-request:${selfAid}:${submission.requestId}`,
|
|
724
|
-
originChannel: 'aun',
|
|
725
|
-
originChannelId: applicantAid,
|
|
726
|
-
originPeerId: applicantAid,
|
|
727
|
-
originPrincipalId: applicantAid,
|
|
728
|
-
},
|
|
729
|
-
});
|
|
730
|
-
if (route.kind !== 'handoff') {
|
|
731
|
-
logger.warn(`[MessageBridge] Contact review route unavailable: self=${selfAid} request=${submission.requestId} reason=${route.kind === 'unavailable' ? route.reason : 'local-route-not-allowed'}`);
|
|
732
|
-
return false;
|
|
733
|
-
}
|
|
734
|
-
let note = '申请说明不可用';
|
|
735
|
-
try {
|
|
736
|
-
note = findPeerRequestNote(selfAid, submission.requestId) || '(未填写)';
|
|
737
|
-
}
|
|
738
|
-
catch { }
|
|
739
|
-
const expiresAtMs = Date.parse(submission.expiresAt);
|
|
740
|
-
const sessionId = `contact-request:${selfAid}:${submission.requestId}`;
|
|
741
|
-
const interaction = {
|
|
742
|
-
type: 'interaction',
|
|
743
|
-
id: submission.requestId,
|
|
744
|
-
channelId: route.approverOperatorId,
|
|
745
|
-
sessionId,
|
|
746
|
-
initiatorId: route.approverOperatorId,
|
|
747
|
-
expiresAt: expiresAtMs,
|
|
748
|
-
kind: {
|
|
749
|
-
kind: 'action',
|
|
750
|
-
title: '联系人申请审核',
|
|
751
|
-
bodyFormat: 'plain',
|
|
752
|
-
body: `申请人:${applicantAid}\n申请说明:${note}\n提交时间:${submission.submittedAt}\n截止时间:${submission.expiresAt}\n\n此卡片只处理当前这一次联系人申请。申请人重新提交、已被他人处理或审批超时,均不会修改当前联系人状态。卡片因重启或投递失效时,可在联系人列表处理仍未到期的 pending;已过期申请需由申请人重新发送 /request。`,
|
|
753
|
-
buttons: [
|
|
754
|
-
{ key: 'approve', label: '通过', style: 'primary' },
|
|
755
|
-
{ key: 'reject', label: '拒绝', style: 'default' },
|
|
756
|
-
{ key: 'block', label: '拉黑', style: 'danger', confirm: { title: '拉黑申请人', body: `确定拉黑 ${applicantAid}?` } },
|
|
757
|
-
],
|
|
758
|
-
},
|
|
759
|
-
};
|
|
760
|
-
this.interactionRouter.register(submission.requestId, sessionId, async (action, _values, operatorId) => {
|
|
761
|
-
if (action !== 'approve' && action !== 'reject' && action !== 'block')
|
|
762
|
-
return false;
|
|
763
|
-
const reviewed = await reviewPeerRequest({
|
|
764
|
-
selfAid,
|
|
765
|
-
primaryId: applicantAid,
|
|
766
|
-
requestId: submission.requestId,
|
|
767
|
-
expectedContactRevision: submission.peerRevision,
|
|
768
|
-
approverId: route.approverOperatorId,
|
|
769
|
-
actorId: String(operatorId || ''),
|
|
770
|
-
decision: action,
|
|
771
|
-
});
|
|
772
|
-
try {
|
|
773
|
-
await this.sendContactReviewOutcome(route.adapter, route.approverOperatorId, applicantAid, reviewed.code, owningAgent?.name);
|
|
774
|
-
}
|
|
775
|
-
catch (error) {
|
|
776
|
-
logger.warn(`[MessageBridge] Contact review outcome notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
|
|
777
|
-
}
|
|
778
|
-
if (reviewed.code === 'approved' || reviewed.code === 'rejected' || reviewed.code === 'blocked') {
|
|
779
|
-
try {
|
|
780
|
-
await this.notifyContactApplicant(route.adapter, applicantAid, reviewed.code, submission.requestId, submission.expiresAt, owningAgent?.name);
|
|
781
|
-
}
|
|
782
|
-
catch (error) {
|
|
783
|
-
logger.warn(`[MessageBridge] Contact applicant notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
|
|
784
|
-
}
|
|
785
|
-
return true;
|
|
786
|
-
}
|
|
787
|
-
return false;
|
|
788
|
-
}, {
|
|
789
|
-
timeoutMs: Math.max(1, expiresAtMs - Date.now()),
|
|
790
|
-
initiatorId: route.approverOperatorId,
|
|
791
|
-
initiatorChannelKey: route.approverChannelKey,
|
|
792
|
-
onTimeout: () => { void expirePendingPeerRequests(selfAid); },
|
|
793
|
-
onCancel: reason => route.adapter.invalidateInteraction?.(submission.requestId, reason),
|
|
794
|
-
});
|
|
795
|
-
const envelope = buildEnvelope({
|
|
796
|
-
taskId: `contact-request-${submission.requestId}`,
|
|
797
|
-
sessionId,
|
|
798
|
-
channel: route.adapter.channelName,
|
|
799
|
-
channelId: route.approverOperatorId,
|
|
800
|
-
agentName: owningAgent?.name ?? selfAid,
|
|
801
|
-
chatmode: 'interactive',
|
|
802
|
-
replyContext: { delivery: { chatType: 'private' }, metadata: { source: 'handoff', chatmode: 'interactive' } },
|
|
803
|
-
});
|
|
804
|
-
const receipt = await sendInteractionPayload(route.adapter, envelope, interaction, renderActionAsText(interaction), envelope.replyContext);
|
|
805
|
-
const accepted = isInteractionSendAccepted(receipt);
|
|
806
|
-
if (!accepted)
|
|
807
|
-
await this.interactionRouter.cancel(submission.requestId, 'delivery_failed');
|
|
808
|
-
return accepted;
|
|
809
|
-
}
|
|
810
|
-
async sendContactReviewOutcome(adapter, ownerAid, applicantAid, code, agentName) {
|
|
811
|
-
const text = code === 'approved' ? `已通过 ${applicantAid} 的联系人申请。`
|
|
812
|
-
: code === 'rejected' ? `已拒绝 ${applicantAid} 的联系人申请。`
|
|
813
|
-
: code === 'blocked' ? `已拉黑 ${applicantAid}。`
|
|
814
|
-
: code === 'request-expired' ? '审核已过期。'
|
|
815
|
-
: code === 'request-stale' ? '申请已更新或已被处理。'
|
|
816
|
-
: code === 'revision-conflict' ? '联系人列表已变化,请从联系人列表重新审核。'
|
|
817
|
-
: '当前无审核权限。';
|
|
818
|
-
await adapter.send(buildEnvelope({ channel: adapter.channelName, channelId: ownerAid, agentName: agentName ?? '<unknown>', delivery: { chatType: 'private' } }), { kind: 'system.notice', text, subtype: 'contact-review' });
|
|
819
|
-
}
|
|
820
|
-
async notifyContactApplicant(adapter, applicantAid, code, requestId, expiresAt, agentName) {
|
|
821
|
-
await adapter.send(buildEnvelope({
|
|
822
|
-
channel: adapter.channelName,
|
|
823
|
-
channelId: applicantAid,
|
|
824
|
-
agentName: agentName ?? '<unknown>',
|
|
825
|
-
replyContext: { delivery: { chatType: 'private' }, metadata: evolMenuResponseTransportMetadata() },
|
|
826
|
-
}), {
|
|
827
|
-
kind: 'custom',
|
|
828
|
-
channelType: 'aun',
|
|
829
|
-
payload: {
|
|
830
|
-
type: 'contact.request.response',
|
|
831
|
-
status: code === 'approved' ? 'APPROVED' : code === 'rejected' ? 'REJECTED' : 'NOT_ALLOWED',
|
|
832
|
-
request_id: requestId,
|
|
833
|
-
expires_at: expiresAt,
|
|
834
|
-
},
|
|
835
|
-
});
|
|
836
|
-
}
|
|
837
533
|
getDebouncer(channelName, channelType) {
|
|
838
534
|
let d = this.debouncers.get(channelName);
|
|
839
535
|
if (!d) {
|
|
@@ -862,6 +558,19 @@ export class MessageBridge {
|
|
|
862
558
|
register(channelName, onMessage, sendReply, adapter, channelType) {
|
|
863
559
|
const effectiveChannelType = channelType || channelName;
|
|
864
560
|
onMessage(async (msg) => {
|
|
561
|
+
const contactDelivery = trustedContactInboundDelivery(msg.contactDelivery);
|
|
562
|
+
const logInbound = contactDelivery
|
|
563
|
+
? (dir, entry) => appendInboundMessageLogOnce(dir, entry, `contact-inbound-${contactDelivery.key}`)
|
|
564
|
+
: appendMessageLog;
|
|
565
|
+
let contactFailed = false;
|
|
566
|
+
if (contactDelivery) {
|
|
567
|
+
const receipt = this.messageQueue.contactDeliveryReceipt(contactDelivery.key);
|
|
568
|
+
if (receipt) {
|
|
569
|
+
contactDelivery.receipt = receipt;
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
contactDelivery.validate();
|
|
573
|
+
}
|
|
865
574
|
let releaseAdmission;
|
|
866
575
|
let releaseSessionIngress;
|
|
867
576
|
const releaseIngress = () => {
|
|
@@ -896,6 +605,10 @@ export class MessageBridge {
|
|
|
896
605
|
const menuControl = resolvedChannelType === 'aun'
|
|
897
606
|
? parseMenuControl(content)
|
|
898
607
|
: { isMenu: false };
|
|
608
|
+
if (menuControl.isMenu) {
|
|
609
|
+
Object.assign(msg, menuTiming);
|
|
610
|
+
this.logMenuInbound(channelName, msg, menuControl);
|
|
611
|
+
}
|
|
899
612
|
const isPrivateMenuTokenRequest = menuControl.isMenu
|
|
900
613
|
&& menuControl.type === 'menu.token.request'
|
|
901
614
|
&& chatType === 'private';
|
|
@@ -914,10 +627,10 @@ export class MessageBridge {
|
|
|
914
627
|
// a sender against an expired or invalidated ownership cache.
|
|
915
628
|
const ownership = ownerResolver.snapshot(selfAid);
|
|
916
629
|
if (ownership.connected || ownership.relation) {
|
|
917
|
-
await ownerResolver.refresh(selfAid, {
|
|
630
|
+
await traceMenuStage(menuControl.isMenu ? menuControl.request : undefined, this.menuFlowContext(channelName, msg), menuTiming, 'bridge.ownership', () => ownerResolver.refresh(selfAid, {
|
|
918
631
|
maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
|
|
919
632
|
allowTransient: true,
|
|
920
|
-
});
|
|
633
|
+
}));
|
|
921
634
|
}
|
|
922
635
|
}
|
|
923
636
|
const admissionPreflight = evaluateInboundAdmissionPreflight({
|
|
@@ -939,16 +652,15 @@ export class MessageBridge {
|
|
|
939
652
|
return;
|
|
940
653
|
}
|
|
941
654
|
}
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
msg,
|
|
945
|
-
content,
|
|
946
|
-
owningAgent,
|
|
947
|
-
adapter,
|
|
948
|
-
sendReply,
|
|
949
|
-
})) {
|
|
655
|
+
// Retired controls must not enter the command/session/LLM pipeline.
|
|
656
|
+
if (/^\s*\/request(?:\s|$)/i.test(content))
|
|
950
657
|
return;
|
|
658
|
+
try {
|
|
659
|
+
const legacyControl = JSON.parse(content);
|
|
660
|
+
if (typeof legacyControl?.type === 'string' && legacyControl.type.startsWith('contact.request.'))
|
|
661
|
+
return;
|
|
951
662
|
}
|
|
663
|
+
catch { /* ordinary text */ }
|
|
952
664
|
const ownershipFailure = selfAid ? ownerResolver.snapshot(selfAid) : undefined;
|
|
953
665
|
if (!trustedHandoffEcho && !admissionPreflight.context.isOwner
|
|
954
666
|
&& admissionPreflight.allow
|
|
@@ -990,6 +702,8 @@ export class MessageBridge {
|
|
|
990
702
|
return;
|
|
991
703
|
}
|
|
992
704
|
if (!trustedHandoffEcho && selfAid && actorId && this.groupInviteReviewService) {
|
|
705
|
+
if (contactDelivery && /^\s*\/invites(?:\s|$)/i.test(content))
|
|
706
|
+
contactDelivery.startCommand();
|
|
993
707
|
const inviteCommand = await this.groupInviteReviewService.handleCommand({
|
|
994
708
|
selfAid,
|
|
995
709
|
ownerAid: actorId,
|
|
@@ -1053,10 +767,6 @@ export class MessageBridge {
|
|
|
1053
767
|
});
|
|
1054
768
|
return;
|
|
1055
769
|
}
|
|
1056
|
-
// AUN captures this mark at its adapter boundary. Legacy/test
|
|
1057
|
-
// adapters fall back to the bridge entry mark captured above.
|
|
1058
|
-
Object.assign(msg, menuTiming);
|
|
1059
|
-
this.logMenuInbound(channelName, msg, menuControl);
|
|
1060
770
|
if (!hasValidMenuId(menuControl)) {
|
|
1061
771
|
this.logMenuDiagnostic('missing-id', channelName, msg, menuControl);
|
|
1062
772
|
logMenuRequestCompleted(menuControl.request, undefined, this.menuFlowContext(channelName, msg), {
|
|
@@ -1351,7 +1061,7 @@ export class MessageBridge {
|
|
|
1351
1061
|
const inboundReplyTo = typeof msg.replyContext?.metadata?.refMessageId === 'string'
|
|
1352
1062
|
? msg.replyContext.metadata.refMessageId
|
|
1353
1063
|
: null;
|
|
1354
|
-
|
|
1064
|
+
logInbound(chatDir, buildInboundEntry({
|
|
1355
1065
|
from: msg.peerId || 'unknown',
|
|
1356
1066
|
to: msg.selfAID || 'self',
|
|
1357
1067
|
threadId: msg.threadId ?? '',
|
|
@@ -1377,6 +1087,8 @@ export class MessageBridge {
|
|
|
1377
1087
|
logger.debug(`[MessageBridge] Failed to log inbound command: ${e}`);
|
|
1378
1088
|
}
|
|
1379
1089
|
}
|
|
1090
|
+
if (contactDelivery && isCmd)
|
|
1091
|
+
contactDelivery.startCommand();
|
|
1380
1092
|
if (msg.source !== 'handoff'
|
|
1381
1093
|
&& !executionPermissionOverride
|
|
1382
1094
|
&& await this.handleCommand(cmdContent, channelName, msg.channelId, (text) => {
|
|
@@ -1385,6 +1097,10 @@ export class MessageBridge {
|
|
|
1385
1097
|
return sendReply(msg.channelId, text, msg.replyContext);
|
|
1386
1098
|
}, msg.peerId, msg.threadId, msg.chatType, msg.source, msg.replyContext, msg.messageId, msg.selfAID, authSubject))
|
|
1387
1099
|
return;
|
|
1100
|
+
// A quick-command prefix may be unknown to the handler and fall through
|
|
1101
|
+
// to model input. No command ran, so a failed queue commit may retry it.
|
|
1102
|
+
if (contactDelivery && isCmd)
|
|
1103
|
+
contactDelivery.cancelCommand?.();
|
|
1388
1104
|
// 3. session 解析(使用 Channel 层填充的 chatType)
|
|
1389
1105
|
if (!(await this.canCreateThreadSession(channelName, msg, chatType))) {
|
|
1390
1106
|
// 静默丢弃:绝不向群里注入回复。
|
|
@@ -1495,7 +1211,43 @@ export class MessageBridge {
|
|
|
1495
1211
|
if (!releaseAdmission)
|
|
1496
1212
|
releaseAdmission = await this.acquireAdmission(admissionRoute);
|
|
1497
1213
|
const hadMainSession = msg.threadId ? true : this.sessionManager.hasMainSession(channelName, msg.channelId, msg.channelType || effectiveChannelType, msg.selfAID || selfAid);
|
|
1498
|
-
|
|
1214
|
+
const boundContactSession = contactDelivery?.sessionId
|
|
1215
|
+
? await this.sessionManager.getSessionById(contactDelivery.sessionId) : undefined;
|
|
1216
|
+
if (contactDelivery?.sessionId && (!boundContactSession || boundContactSession.selfAID !== selfAid
|
|
1217
|
+
|| boundContactSession.channelId !== msg.channelId
|
|
1218
|
+
|| (sessionTopicThreadId(boundContactSession) ?? '') !== (isTopicThreadId(msg.threadId) ? msg.threadId : '')))
|
|
1219
|
+
throw new Error('contact replay bound session is unavailable');
|
|
1220
|
+
if (boundContactSession)
|
|
1221
|
+
boundContactSession.identity = identity;
|
|
1222
|
+
let session = boundContactSession ?? diagnosticSession ?? await this.sessionManager.getOrCreateSession(channelName, msg.channelId, effectiveProjectPath, msg.threadId, Object.keys(metadata).length ? metadata : undefined, this.extractTopicName(msg), msg.peerId, chatType, owningAgent?.baseagent, msg.selfAID, msg.channelType || effectiveChannelType, msg.peerType, identity, readTopicStatus(msg) ?? readTopicStatus(msg.replyContext?.metadata));
|
|
1223
|
+
// 归档话题不再入队;closed 收到新消息时回退 active,主话题不受此状态影响。
|
|
1224
|
+
const topicGate = decideTopicInbound({
|
|
1225
|
+
isTopic: isTopicSession(session),
|
|
1226
|
+
topicStatus: session.topicStatus,
|
|
1227
|
+
chatType,
|
|
1228
|
+
});
|
|
1229
|
+
if (topicGate.action === 'drop-archived') {
|
|
1230
|
+
logger.info(`[MessageBridge] 话题已归档,丢弃入站消息 session=${session.id} from=${msg.peerId} chatType=${chatType}`);
|
|
1231
|
+
if (topicGate.replyArchived && adapter?.send) {
|
|
1232
|
+
await adapter.send(buildEnvelope({
|
|
1233
|
+
taskId: `archived-${randomBytes(5).toString('hex')}`,
|
|
1234
|
+
channel: channelName,
|
|
1235
|
+
channelId: msg.channelId,
|
|
1236
|
+
chatmode: 'interactive',
|
|
1237
|
+
replyContext: {
|
|
1238
|
+
...msg.replyContext,
|
|
1239
|
+
...(msg.threadId ? { threadId: msg.threadId } : {}),
|
|
1240
|
+
},
|
|
1241
|
+
}), { kind: 'result.text', text: '话题已归档', isFinal: true }).catch((error) => {
|
|
1242
|
+
logger.warn(`[MessageBridge] 归档提示发送失败 session=${session.id}: ${error}`);
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
if (topicGate.reopen) {
|
|
1248
|
+
await this.sessionManager.setTopicStatus(session.id, 'active');
|
|
1249
|
+
session.topicStatus = 'active';
|
|
1250
|
+
}
|
|
1499
1251
|
if (isTopicSession(session) && typeof this.messageQueue.reserveSessionIngress === 'function') {
|
|
1500
1252
|
releaseSessionIngress = this.messageQueue.reserveSessionIngress(session.id);
|
|
1501
1253
|
}
|
|
@@ -1508,7 +1260,7 @@ export class MessageBridge {
|
|
|
1508
1260
|
const inboundCausation = restoredCausation
|
|
1509
1261
|
? deriveCausation(restoredCausation)
|
|
1510
1262
|
: createRootCausation();
|
|
1511
|
-
const renewResult = session.metadata?.diagnostic ? { session } : await this.sessionRenewService.resolve({
|
|
1263
|
+
const renewResult = session.metadata?.diagnostic || boundContactSession ? { session } : await this.sessionRenewService.resolve({
|
|
1512
1264
|
session,
|
|
1513
1265
|
channelName,
|
|
1514
1266
|
channelType: msg.channelType || effectiveChannelType,
|
|
@@ -1525,6 +1277,8 @@ export class MessageBridge {
|
|
|
1525
1277
|
causation: inboundCausation,
|
|
1526
1278
|
});
|
|
1527
1279
|
session = renewResult.session;
|
|
1280
|
+
if (contactDelivery)
|
|
1281
|
+
contactDelivery.bindSession(session.id);
|
|
1528
1282
|
if (!executionPermissionOverride && selfAid && owningAgent?.aid === selfAid) {
|
|
1529
1283
|
executionPermissionOverride = createAgentPolicyAuthorization({
|
|
1530
1284
|
agentAid: selfAid, actor: roleDetail.actor, chatType,
|
|
@@ -1594,7 +1348,6 @@ export class MessageBridge {
|
|
|
1594
1348
|
mentions: msg.mentions, mentionAids: msg.mentionAids, threadId: msg.threadId,
|
|
1595
1349
|
isMentioned: msg.isMentioned,
|
|
1596
1350
|
topicName: this.extractTopicName(msg),
|
|
1597
|
-
label: session.label,
|
|
1598
1351
|
topicStatus: session.topicStatus,
|
|
1599
1352
|
replyContext: msg.replyContext,
|
|
1600
1353
|
source: msg.source,
|
|
@@ -1709,7 +1462,7 @@ export class MessageBridge {
|
|
|
1709
1462
|
}
|
|
1710
1463
|
}
|
|
1711
1464
|
if (!handoffCandidate)
|
|
1712
|
-
|
|
1465
|
+
logInbound(inboundEntry.chatDir, inboundEntry.entry);
|
|
1713
1466
|
if (autoResult && autoResult.batch.length > 1) {
|
|
1714
1467
|
for (const item of autoResult.batch.slice(0, -1)) {
|
|
1715
1468
|
const member = item.value;
|
|
@@ -1744,20 +1497,24 @@ export class MessageBridge {
|
|
|
1744
1497
|
if (fullMessage.messageId && currentSessionBusy) {
|
|
1745
1498
|
adapter?.acknowledge?.(fullMessage.messageId).catch(() => { });
|
|
1746
1499
|
}
|
|
1747
|
-
const isInterrupt = chatType !== 'group' && !handoffCandidate;
|
|
1748
|
-
const attentionPolicy = fullMessage.attentionPolicy;
|
|
1500
|
+
const isInterrupt = chatType !== 'group' && !handoffCandidate && !contactDelivery;
|
|
1501
|
+
const attentionPolicy = contactDelivery ? 'defer' : fullMessage.attentionPolicy;
|
|
1749
1502
|
const shouldInterrupt = isInterrupt || attentionPolicy === 'interrupt';
|
|
1750
1503
|
const enqueueAgentName = owningAgent?.name ?? '<unknown>';
|
|
1751
1504
|
const selfAID = session.selfAID;
|
|
1752
1505
|
const doEnqueue = async (m) => {
|
|
1753
1506
|
// A cancellation can arrive while this message is being debounced.
|
|
1754
|
-
if (!isDiagnosticSessionActive(session, this.sessionManager.getChatDir(session)))
|
|
1507
|
+
if (!isDiagnosticSessionActive(session, this.sessionManager.getChatDir(session))) {
|
|
1508
|
+
if (contactDelivery)
|
|
1509
|
+
throw new Error('contact replay session is no longer active');
|
|
1755
1510
|
return;
|
|
1756
|
-
|
|
1511
|
+
}
|
|
1512
|
+
const enqueue = handoffCandidate || contactDelivery ? this.messageQueue.enqueuePersisted.bind(this.messageQueue) : this.messageQueue.enqueue.bind(this.messageQueue);
|
|
1757
1513
|
try {
|
|
1758
1514
|
return await enqueue(session.id, m, session.projectPath, {
|
|
1759
1515
|
interruptible: shouldInterrupt,
|
|
1760
1516
|
attentionPolicy,
|
|
1517
|
+
contactDelivery,
|
|
1761
1518
|
interruptSamePeer: !shouldInterrupt && !attentionPolicy, // 旧群聊路径保留同人连发打断
|
|
1762
1519
|
priority: attentionPolicy === 'interrupt',
|
|
1763
1520
|
agentName: enqueueAgentName,
|
|
@@ -1780,7 +1537,7 @@ export class MessageBridge {
|
|
|
1780
1537
|
throw error;
|
|
1781
1538
|
}
|
|
1782
1539
|
};
|
|
1783
|
-
if (handoffCandidate) {
|
|
1540
|
+
if (handoffCandidate || contactDelivery) {
|
|
1784
1541
|
await doEnqueue(fullMessage);
|
|
1785
1542
|
}
|
|
1786
1543
|
else if (isInterrupt) {
|
|
@@ -1799,6 +1556,7 @@ export class MessageBridge {
|
|
|
1799
1556
|
}
|
|
1800
1557
|
}
|
|
1801
1558
|
catch (error) {
|
|
1559
|
+
contactFailed = true;
|
|
1802
1560
|
if (isRetryableMenuTransportError(error)) {
|
|
1803
1561
|
logger.warn(`[MessageBridge] Retryable response delivery unavailable for ${channelName}:`, error);
|
|
1804
1562
|
}
|
|
@@ -1808,9 +1566,18 @@ export class MessageBridge {
|
|
|
1808
1566
|
finally {
|
|
1809
1567
|
releaseAdmission?.();
|
|
1810
1568
|
releaseIngress();
|
|
1569
|
+
if (contactDelivery && !contactFailed && !contactDelivery.receipt) {
|
|
1570
|
+
this.messageQueue.finishContactDelivery(contactDelivery);
|
|
1571
|
+
}
|
|
1811
1572
|
}
|
|
1812
1573
|
});
|
|
1813
1574
|
}
|
|
1575
|
+
contactDeliveryReceipt(key) {
|
|
1576
|
+
return this.messageQueue.contactDeliveryReceipt(key);
|
|
1577
|
+
}
|
|
1578
|
+
finishContactDelivery(delivery) {
|
|
1579
|
+
this.messageQueue.finishContactDelivery(delivery);
|
|
1580
|
+
}
|
|
1814
1581
|
async acquireAdmission(key) {
|
|
1815
1582
|
const previous = this.admissionLocks.get(key) ?? Promise.resolve();
|
|
1816
1583
|
let release;
|
|
@@ -1869,23 +1636,26 @@ export class MessageBridge {
|
|
|
1869
1636
|
// Menu IDs are the protocol's stable correlation key. Bind it, together
|
|
1870
1637
|
// with the active EvolCore session, before authorization so every
|
|
1871
1638
|
// CommandAudit record and denial can be joined to the same request.
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
if (!activeSession && typeof this.sessionManager.getActiveSession === 'function') {
|
|
1882
|
-
try {
|
|
1883
|
-
activeSession = await this.sessionManager.getActiveSession(channel, msg.channelId);
|
|
1639
|
+
const activeSession = await traceMenuStage(parsed.request, this.menuFlowContext(channel, msg), msg, 'menu.context', async () => {
|
|
1640
|
+
let session;
|
|
1641
|
+
if (msg.threadId && typeof this.sessionManager.getThreadSession === 'function') {
|
|
1642
|
+
try {
|
|
1643
|
+
session = await this.sessionManager.getThreadSession(channel, msg.channelId, msg.threadId);
|
|
1644
|
+
}
|
|
1645
|
+
catch {
|
|
1646
|
+
session = undefined;
|
|
1647
|
+
}
|
|
1884
1648
|
}
|
|
1885
|
-
|
|
1886
|
-
|
|
1649
|
+
if (!session && typeof this.sessionManager.getActiveSession === 'function') {
|
|
1650
|
+
try {
|
|
1651
|
+
session = await this.sessionManager.getActiveSession(channel, msg.channelId);
|
|
1652
|
+
}
|
|
1653
|
+
catch {
|
|
1654
|
+
session = undefined;
|
|
1655
|
+
}
|
|
1887
1656
|
}
|
|
1888
|
-
|
|
1657
|
+
return session;
|
|
1658
|
+
});
|
|
1889
1659
|
const menuAuthSubject = {
|
|
1890
1660
|
...authSubject,
|
|
1891
1661
|
requestId: parsed.id,
|
|
@@ -1939,9 +1709,9 @@ export class MessageBridge {
|
|
|
1939
1709
|
const dedupKey = [msg.selfAID || channel, channelType, msg.chatType || 'private', scope, msg.peerId,
|
|
1940
1710
|
msg.peerDeviceId || '', msg.peerSlotId || '', msg.threadId || '', parsed.id].join('\u001f');
|
|
1941
1711
|
let afterResponse;
|
|
1942
|
-
const deduped = await this.menuDeduper.execute(dedupKey, menuPayloadFingerprint(parsed.raw), () => isTokenRequest
|
|
1712
|
+
const deduped = await traceMenuStage(parsed.request, this.menuFlowContext(channel, msg), msg, 'menu.execute', () => this.menuDeduper.execute(dedupKey, menuPayloadFingerprint(parsed.raw), () => isTokenRequest
|
|
1943
1713
|
? this.issueMenuTokenResponse(header, channel, msg)
|
|
1944
|
-
: this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; }));
|
|
1714
|
+
: this.dispatchMenuRequest(parsed.request, header, channel, msg, menuAuthSubject, effect => { afterResponse = effect; })));
|
|
1945
1715
|
if ('conflict' in deduped) {
|
|
1946
1716
|
this.logMenuDiagnostic('request-conflict', channel, msg, parsed, 'CONFLICT');
|
|
1947
1717
|
await this.sendMenuResponse(adapter, channel, msg, menuFailure(header, {
|
|
@@ -2219,7 +1989,7 @@ export class MessageBridge {
|
|
|
2219
1989
|
const deliveryTiming = beginMenuDeliveryTiming(msg);
|
|
2220
1990
|
let deliveryOutcome;
|
|
2221
1991
|
try {
|
|
2222
|
-
await deliverMenuResponse(async () => {
|
|
1992
|
+
await traceMenuStage(request, flowContext, msg, 'menu.delivery', () => deliverMenuResponse(async () => {
|
|
2223
1993
|
Object.assign(timedResponse, withMenuProcessingTime(timedResponse, msg));
|
|
2224
1994
|
await adapter.send(envelope, { kind: 'custom', channelType: channel, payload: timedResponse });
|
|
2225
1995
|
}, {
|
|
@@ -2247,7 +2017,7 @@ export class MessageBridge {
|
|
|
2247
2017
|
},
|
|
2248
2018
|
onRetry: (attempt, error, delay) => logMenuResponseRetry(request, flowContext, attempt, delay, error),
|
|
2249
2019
|
onComplete: outcome => { deliveryOutcome = outcome; },
|
|
2250
|
-
});
|
|
2020
|
+
}));
|
|
2251
2021
|
logMenuRequestCompleted(request, timedResponse, flowContext, { delivery: 'sent', ...deliveryOutcome, ...deliveryTiming() });
|
|
2252
2022
|
const upgradeData = 'data' in response ? response.data : undefined;
|
|
2253
2023
|
if (request.type === 'menu.action' && request.action === 'upgrade' && (request.name === 'system' || request.cmd === '/system') && upgradeData?.jobId) {
|