evolcore 0.0.41-test.0 → 0.0.41-test.2
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 +62 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/baseagent.js +88 -49
- package/dist/agents/claude-runner.js +177 -92
- package/dist/agents/codex-runner.js +146 -71
- package/dist/agents/ecagent-runner.js +1 -1
- package/dist/agents/gemini-runner.js +1 -1
- package/dist/aun/aid/agentmd.js +98 -11
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +26 -2
- package/dist/aun/aid/identity.js +91 -0
- package/dist/aun/aid/index.js +1 -1
- package/dist/aun/aid/managed-operation.js +1 -1
- package/dist/aun/aid/ownership-operation.js +23 -22
- package/dist/aun/group/fs-download.js +39 -0
- package/dist/aun/group/identity.js +36 -21
- package/dist/aun/group/operations.js +5 -0
- package/dist/aun/menu/client.js +27 -0
- package/dist/aun/msg/managed-operation.js +68 -7
- package/dist/aun/msg/p2p.js +8 -8
- package/dist/aun/service-proxy.js +53 -12
- package/dist/channels/aun.js +633 -32
- package/dist/channels/daemon.js +15 -1
- package/dist/cli/agent-command.js +5 -2
- package/dist/cli/agent-create.js +991 -233
- package/dist/cli/agent.js +49 -10
- package/dist/cli/aid-bind-command.js +48 -19
- package/dist/cli/aun-commands.js +48 -36
- package/dist/cli/daemon-commands.js +679 -697
- package/dist/cli/fs-command.js +64 -2
- package/dist/cli/index.js +72 -5
- package/dist/cli/init-channel.js +1 -1
- package/dist/cli/init.js +75 -1
- package/dist/cli/managed-command-guard.js +17 -1
- package/dist/cli/model.js +40 -40
- package/dist/cli/provider-command.js +57 -0
- package/dist/cli/proxy-command.js +92 -0
- package/dist/cli/restart-monitor.js +4 -2
- package/dist/cli/role.js +85 -0
- package/dist/cli/stats.js +10 -3
- package/dist/cli/task-context.js +19 -0
- package/dist/config/access-policy.js +7 -2
- package/dist/config/boot-log.js +39 -1
- package/dist/config/config-field-policy.js +17 -39
- package/dist/config/config-manager.js +183 -44
- package/dist/config/config-operation-service.js +5 -19
- package/dist/config/contact-book-store.js +47 -21
- package/dist/config/contact-book.js +18 -12
- package/dist/config/contact-operation-service.js +3 -4
- package/dist/config/contact-request-service.js +11 -0
- package/dist/config/daemon-services.js +11 -0
- package/dist/config/gateway-config.js +88 -594
- package/dist/config/owner-config.js +2 -2
- package/dist/config/peer-role-resolver.js +15 -12
- package/dist/config/provider-ipc-service.js +132 -0
- package/dist/config/provider-menu-request.js +58 -0
- package/dist/config/providers-config.js +12 -7
- package/dist/config/providers-import.js +3 -21
- package/dist/config/providers-management.js +78 -5
- package/dist/config/resolved-config-op.js +11 -1
- package/dist/config/role-command-service.js +166 -0
- package/dist/config/role-request-service.js +193 -0
- package/dist/config/schema-migration.js +1000 -25
- package/dist/config-store.js +89 -4
- package/dist/contracts/ecweb-instance.js +41 -0
- package/dist/contracts/ecweb-service-protocol.js +4 -1
- package/dist/core/agent-application-service.js +60 -11
- package/dist/core/agent-create-status.js +203 -0
- package/dist/core/agent-creation-claim.js +177 -0
- package/dist/core/agent-ipc-registration.js +39 -18
- package/dist/core/agent-runtime.js +194 -24
- package/dist/core/auth/agent-delegation.js +6 -3
- package/dist/core/auth/auth-gateway.js +67 -2
- package/dist/core/auth/authorization-audit.js +58 -11
- package/dist/core/auth/delegation-authorization.js +5 -2
- package/dist/core/auth/operation-authorizer.js +43 -6
- package/dist/core/auth/operation-catalog.js +45 -7
- package/dist/core/channel-loader.js +2 -0
- package/dist/core/command/agent-control.js +260 -21
- package/dist/core/command/agent-storage-menu.js +5 -3
- package/dist/core/command/cli-intent-parser.js +8 -3
- package/dist/core/command/command-handler.js +112 -154
- package/dist/core/command/connect-menu.js +11 -3
- package/dist/core/command/data-root-resolver.js +5 -4
- package/dist/core/command/memory-slash.js +16 -8
- package/dist/core/command/menu-catalog.js +10 -6
- package/dist/core/command/menu-handler.js +106 -73
- package/dist/core/command/menu-protocol.js +15 -1
- package/dist/core/command/provider-menu.js +46 -0
- package/dist/core/command/role-menu.js +147 -30
- package/dist/core/command/slash-handler.js +125 -255
- package/dist/core/daemon-control.js +26 -27
- package/dist/core/event-catalog.js +10 -0
- package/dist/core/evolagent-registry.js +7 -5
- package/dist/core/evolagent.js +10 -8
- package/dist/core/file-integrity/store.js +11 -0
- package/dist/core/handoff/ipc-registration.js +3 -0
- package/dist/core/inference/text-inference.js +31 -40
- package/dist/core/initialization/service.js +491 -0
- package/dist/core/ipc-registration.js +40 -24
- package/dist/core/memory/consolidation-context.js +51 -5
- package/dist/core/memory/consolidation-ops-records.js +96 -1
- package/dist/core/memory/consolidation-trigger.js +208 -191
- package/dist/core/memory/consolidation.js +333 -35
- package/dist/core/memory/index-manager.js +27 -5
- package/dist/core/memory/memory-admin.js +45 -5
- package/dist/core/memory/memory-writer.js +163 -18
- package/dist/core/memory/relation-idle-monitor.js +119 -58
- package/dist/core/memory/relation-sweep.js +55 -45
- package/dist/core/message/aun-ipc-sender.js +81 -69
- package/dist/core/message/im-renderer.js +25 -4
- package/dist/core/message/message-admission.js +89 -4
- package/dist/core/message/message-bridge.js +66 -21
- package/dist/core/message/response-engine.js +108 -35
- package/dist/core/model/catalog-service.js +5 -3
- package/dist/core/model/config-scope.js +29 -71
- package/dist/core/model/field-scope.js +1 -1
- package/dist/core/model/model-catalog.js +30 -41
- package/dist/core/model/model-diagnostics.js +4 -3
- package/dist/core/model/model-fallback.js +10 -7
- package/dist/core/model/model-permission.js +3 -2
- package/dist/core/ownership/owner-resolver.js +772 -158
- package/dist/core/permission/approval-gateway.js +103 -403
- package/dist/core/permission/ec-command-parser.js +62 -6
- package/dist/core/permission/index.js +1 -0
- package/dist/core/permission/permission-result.js +78 -0
- package/dist/core/permission/sandbox-runtime.js +18 -1
- package/dist/core/permission/tool-policy.js +21 -46
- package/dist/core/relation/peer-identity.js +64 -1
- package/dist/core/role/runtime-policy.js +72 -13
- package/dist/core/session/session-capsule.js +1 -1
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +20 -0
- package/dist/core/session/session-renew.js +3 -3
- package/dist/core/skill/index-generator.js +15 -5
- package/dist/core/system-session/memory.js +43 -8
- package/dist/core/thread/thread-service.js +19 -6
- package/dist/directory/owner-directory-admission.js +95 -0
- package/dist/directory/owner-directory-authorization.js +309 -0
- package/dist/directory/owner-directory-cache.js +635 -0
- package/dist/eck/kit-renderer.js +2 -2
- package/dist/ecweb/basic-settings-service.js +33 -40
- package/dist/ecweb/init-menu.js +32 -0
- package/dist/ecweb/message-context-service.js +110 -0
- package/dist/index.js +93 -19
- package/dist/ipc.js +247 -29
- package/dist/paths.js +7 -0
- package/dist/proxy/command.js +122 -0
- package/dist/proxy/ipc-service.js +68 -0
- package/dist/proxy/manager.js +484 -0
- package/dist/proxy/service-supervisor.js +603 -0
- package/dist/response-system/engines/v1/proactive-flow.js +16 -6
- package/dist/trigger/authorization.js +27 -17
- package/dist/trigger/feedback.js +2 -3
- package/dist/trigger/ipc-service.js +105 -78
- package/dist/trigger/local-files.js +2 -1
- package/dist/trigger/manager.js +5 -3
- package/dist/trigger/scheduler.js +88 -6
- package/dist/utils/atomic-write.js +28 -0
- package/dist/utils/cross-platform.js +14 -0
- package/dist/utils/ecweb-supervisor.js +258 -83
- package/dist/utils/error-utils.js +26 -2
- package/dist/utils/logger.js +92 -6
- package/dist/utils/package-version-info.js +4 -2
- package/dist/utils/welcome.js +1 -1
- package/kits/docs/INDEX.md +1 -0
- package/kits/docs/aun/SDK.md +4 -1
- package/kits/docs/channels/aun.md +9 -0
- package/kits/docs/evolcore/INDEX.md +1 -0
- package/kits/docs/evolcore/agent.md +8 -1
- package/kits/docs/evolcore/aid.md +67 -17
- package/kits/docs/evolcore/config.md +28 -7
- package/kits/docs/evolcore/contact.md +3 -0
- package/kits/docs/evolcore/fs.md +11 -0
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -2
- package/kits/docs/evolcore/memory-consolidation.md +32 -8
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +4 -0
- package/kits/docs/evolcore/model.md +23 -20
- package/kits/docs/evolcore/msg.md +4 -7
- package/kits/docs/evolcore/provider.md +50 -0
- package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
- package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
- package/kits/rules/01-overview.md +3 -0
- package/kits/rules/04-relation.md +1 -1
- package/kits/schemas/_meta.json +37 -4
- package/kits/schemas/agent-config.schema.13.json +8 -3
- package/kits/schemas/agent-config.schema.16.json +891 -0
- package/kits/schemas/daemon.schema.9.json +366 -0
- package/kits/schemas/defaults.schema.5.json +406 -127
- package/kits/schemas/relation-config.schema.11.json +277 -0
- package/kits/schemas/role-config.schema.1.json +7 -7
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ec-agent-create/SKILL.md +3 -0
- package/kits/skills/ec-identity/SKILL.md +2 -2
- package/kits/skills/ec-service-proxy/SKILL.md +118 -0
- package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
- package/kits/skills/personal-assistant/SKILL.md +176 -0
- package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
- package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
- package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
- package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
- package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
- package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
- package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
- package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
- package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
- package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
- package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
- package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
- package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
- package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
- package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
- package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
- package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
- package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
- package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
- package/kits/skills/thread-ops/SKILL.md +5 -0
- package/kits/templates/memory-consolidation/forget.md +19 -6
- package/kits/templates/memory-consolidation/notes.md +1 -1
- package/kits/templates/memory-consolidation/profile.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +20 -3
- package/kits/templates/roles/member.json +8 -1
- package/kits/templates/system-fragments/baseagent.md +2 -2
- package/kits/templates/system-fragments/memory.md +4 -4
- package/kits/templates/system-fragments/venue.md +1 -1
- package/package.json +7 -3
- package/dist/core/message/create-status.js +0 -96
package/dist/channels/aun.js
CHANGED
|
@@ -4,6 +4,9 @@ import crypto from 'crypto';
|
|
|
4
4
|
import { performance } from 'node:perf_hooks';
|
|
5
5
|
import fs from 'fs';
|
|
6
6
|
import { ownerResolver } from '../core/ownership/owner-resolver.js';
|
|
7
|
+
import { OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/owner-directory-cache.js';
|
|
8
|
+
import { OwnerDirectoryAuthorization } from '../directory/owner-directory-authorization.js';
|
|
9
|
+
import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-admission.js';
|
|
7
10
|
import path from 'path';
|
|
8
11
|
import os from 'os';
|
|
9
12
|
import { logger, localTimestamp } from '../utils/logger.js';
|
|
@@ -18,13 +21,15 @@ import { appendAidEvent } from '../utils/instance-registry.js';
|
|
|
18
21
|
import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
|
|
19
22
|
import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
|
|
20
23
|
import { chatDirPath } from '../core/session/session-fs-store.js';
|
|
24
|
+
import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
|
|
25
|
+
import { sessionFullAccessStatus } from '../core/role/runtime-policy.js';
|
|
21
26
|
import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
|
|
22
27
|
import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
|
|
23
28
|
import { appendAidLifecycle } from '../aun/aid/identity.js';
|
|
24
29
|
import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
|
|
25
30
|
import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
|
|
26
31
|
import { loadAgent } from '../config-store.js';
|
|
27
|
-
import { configuredOwnerList } from '../config/owner-config.js';
|
|
32
|
+
import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
|
|
28
33
|
import { resolveAgentLifecycle } from '../config/lifecycle.js';
|
|
29
34
|
import { resolveEffective } from '../config/config-manager.js';
|
|
30
35
|
import { isManagementRole } from '../config/builtin-roles.js';
|
|
@@ -46,11 +51,14 @@ import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOu
|
|
|
46
51
|
import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
|
|
47
52
|
import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
|
|
48
53
|
import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
|
|
49
|
-
import { isTopicThreadId } from '../core/thread/topic-id.js';
|
|
54
|
+
import { isTopicThreadId, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
55
|
+
import { ThreadService } from '../core/thread/thread-service.js';
|
|
50
56
|
import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js';
|
|
51
57
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
52
58
|
const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
|
|
53
59
|
const AUN_INBOUND_DEDUP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
60
|
+
const OWNER_DIRECTORY_RETRY_BASE_MS = 1_000;
|
|
61
|
+
const OWNER_DIRECTORY_RETRY_MAX_MS = 60_000;
|
|
54
62
|
const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
|
|
55
63
|
const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
|
|
56
64
|
const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
|
|
@@ -61,6 +69,11 @@ const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
|
|
|
61
69
|
const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
|
|
62
70
|
const AUN_MAX_FIELD_SIZE = 256 * 1024;
|
|
63
71
|
const AUN_MIN_FIELD_SIZE = 1024;
|
|
72
|
+
const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
|
|
73
|
+
const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
|
|
74
|
+
'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
|
|
75
|
+
'action_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
76
|
+
]);
|
|
64
77
|
function jsonUtf8Size(value) {
|
|
65
78
|
return Buffer.byteLength(JSON.stringify(value), 'utf8');
|
|
66
79
|
}
|
|
@@ -684,6 +697,8 @@ function errorCodeForLog(error) {
|
|
|
684
697
|
}
|
|
685
698
|
export class AUNChannel {
|
|
686
699
|
config;
|
|
700
|
+
// Keep each target's attempt across channel recreation; reset only on process restart.
|
|
701
|
+
static configuredOwnerBindAttempts = new Set();
|
|
687
702
|
managedMenuClient = new ManagedMenuClient(params => {
|
|
688
703
|
if (!this.connected || !this.client)
|
|
689
704
|
return Promise.reject(new Error('AUN channel is not connected'));
|
|
@@ -695,10 +710,22 @@ export class AUNChannel {
|
|
|
695
710
|
return this.managedMenuClient.request(options);
|
|
696
711
|
}
|
|
697
712
|
client = null;
|
|
713
|
+
configuredOwnerBind;
|
|
714
|
+
configuredOwnerBindEpoch = 0;
|
|
715
|
+
configuredOwnerBindRecheck = false;
|
|
716
|
+
ownerDirectoryCache;
|
|
717
|
+
ownerDirectoryWatch;
|
|
718
|
+
ownerDirectoryFlight;
|
|
719
|
+
ownerDirectoryRecheck = false;
|
|
720
|
+
ownerDirectoryRetryTimer;
|
|
721
|
+
ownerDirectoryRetryAttempts = 0;
|
|
722
|
+
ownerDirectoryObserved;
|
|
723
|
+
ownerDirectoryResolvedSignature;
|
|
698
724
|
store = null;
|
|
699
725
|
/** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
|
|
700
726
|
gatewayUrl = '';
|
|
701
727
|
projectPathProvider;
|
|
728
|
+
sessionStateResolver;
|
|
702
729
|
messageHandler;
|
|
703
730
|
recallHandler;
|
|
704
731
|
connected = false;
|
|
@@ -1488,6 +1515,321 @@ export class AUNChannel {
|
|
|
1488
1515
|
logger.warn(`${this.logPrefix()} topic.renamed failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1489
1516
|
});
|
|
1490
1517
|
}
|
|
1518
|
+
stopOwnerDirectoryRefresh() {
|
|
1519
|
+
this.ownerDirectoryWatch?.stop();
|
|
1520
|
+
this.ownerDirectoryWatch = undefined;
|
|
1521
|
+
if (this.ownerDirectoryRetryTimer)
|
|
1522
|
+
clearTimeout(this.ownerDirectoryRetryTimer);
|
|
1523
|
+
this.ownerDirectoryRetryTimer = undefined;
|
|
1524
|
+
this.ownerDirectoryRetryAttempts = 0;
|
|
1525
|
+
this.ownerDirectoryFlight = undefined;
|
|
1526
|
+
this.ownerDirectoryRecheck = false;
|
|
1527
|
+
this.ownerDirectoryObserved = undefined;
|
|
1528
|
+
this.ownerDirectoryResolvedSignature = undefined;
|
|
1529
|
+
this.ownerDirectoryCache?.authorization.dispose();
|
|
1530
|
+
this.ownerDirectoryCache = undefined;
|
|
1531
|
+
}
|
|
1532
|
+
/** One watch and retry chain per live connection; never opens another SDK client. */
|
|
1533
|
+
startOwnerDirectoryRefresh() {
|
|
1534
|
+
const client = this.client;
|
|
1535
|
+
if (!client || !this.connected || this.intentionalDisconnect || this.config.pureIdentity)
|
|
1536
|
+
return;
|
|
1537
|
+
if (this.ownerDirectoryWatch?.client === client)
|
|
1538
|
+
return;
|
|
1539
|
+
this.stopOwnerDirectoryRefresh();
|
|
1540
|
+
const selfAid = this.config.aid.replace(/^@/, '');
|
|
1541
|
+
this.ownerDirectoryWatch = {
|
|
1542
|
+
client,
|
|
1543
|
+
stop: ownerResolver.onUpdate(subjectAid => {
|
|
1544
|
+
if (subjectAid !== selfAid || this.ownerDirectoryWatch?.client !== client || !this.connected)
|
|
1545
|
+
return;
|
|
1546
|
+
const view = ownerResolver.snapshot(selfAid);
|
|
1547
|
+
const previous = this.ownerDirectoryObserved;
|
|
1548
|
+
this.ownerDirectoryObserved = view;
|
|
1549
|
+
if (view.refreshFailure || view.consensusStatus === 'invalid' || view.consensusStatus === 'unavailable') {
|
|
1550
|
+
if (view.refreshFailure || view.consensus?.status === view.consensusStatus) {
|
|
1551
|
+
if (this.ownerDirectoryFlight) {
|
|
1552
|
+
this.scheduleOwnerDirectoryRetry(view);
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
void this.getOwnerDirectoryRuntime(undefined, false).catch(error => {
|
|
1556
|
+
logger.warn(`${this.logPrefix()} Owner directory state processing failed: ${errorCodeForLog(error) || 'UNKNOWN'}`);
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
else {
|
|
1560
|
+
// Material invalidation needs a new check, not a warning about an unchecked snapshot.
|
|
1561
|
+
this.queueOwnerDirectoryRefresh();
|
|
1562
|
+
}
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
this.clearOwnerDirectoryRetry();
|
|
1566
|
+
if (!previous || previous.refreshFailure || previous.consensusStatus !== view.consensusStatus
|
|
1567
|
+
|| previous.ownerAid !== view.ownerAid
|
|
1568
|
+
|| previous.consensus?.relation_version !== view.consensus?.relation_version) {
|
|
1569
|
+
this.queueOwnerDirectoryRefresh();
|
|
1570
|
+
}
|
|
1571
|
+
}),
|
|
1572
|
+
};
|
|
1573
|
+
this.queueOwnerDirectoryRefresh();
|
|
1574
|
+
}
|
|
1575
|
+
clearOwnerDirectoryRetry() {
|
|
1576
|
+
if (this.ownerDirectoryRetryTimer)
|
|
1577
|
+
clearTimeout(this.ownerDirectoryRetryTimer);
|
|
1578
|
+
this.ownerDirectoryRetryTimer = undefined;
|
|
1579
|
+
this.ownerDirectoryRetryAttempts = 0;
|
|
1580
|
+
}
|
|
1581
|
+
scheduleOwnerDirectoryRetry(ownership) {
|
|
1582
|
+
const retryable = ownership.refreshFailure
|
|
1583
|
+
? ownership.refreshFailure.kind === 'transient'
|
|
1584
|
+
: ownership.consensusStatus === 'unavailable' && ownership.consensus?.retryable === true;
|
|
1585
|
+
if (!retryable) {
|
|
1586
|
+
this.clearOwnerDirectoryRetry();
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
const client = this.client;
|
|
1590
|
+
if (!client || this.ownerDirectoryWatch?.client !== client || !this.connected
|
|
1591
|
+
|| this.intentionalDisconnect || this.ownerDirectoryRetryTimer)
|
|
1592
|
+
return;
|
|
1593
|
+
const delay = Math.min(OWNER_DIRECTORY_RETRY_BASE_MS * 2 ** Math.min(this.ownerDirectoryRetryAttempts++, 6), OWNER_DIRECTORY_RETRY_MAX_MS);
|
|
1594
|
+
logger.debug(`${this.logPrefix()} Owner 核验暂时失败,${delay}ms 后重试:selfAid=${ownership.subjectAid}`);
|
|
1595
|
+
this.ownerDirectoryRetryTimer = setTimeout(() => {
|
|
1596
|
+
this.ownerDirectoryRetryTimer = undefined;
|
|
1597
|
+
if (this.ownerDirectoryWatch?.client === client && this.connected)
|
|
1598
|
+
this.queueOwnerDirectoryRefresh();
|
|
1599
|
+
}, delay);
|
|
1600
|
+
this.ownerDirectoryRetryTimer.unref();
|
|
1601
|
+
}
|
|
1602
|
+
queueOwnerDirectoryRefresh() {
|
|
1603
|
+
const watch = this.ownerDirectoryWatch;
|
|
1604
|
+
if (!watch || !this.connected)
|
|
1605
|
+
return;
|
|
1606
|
+
if (this.ownerDirectoryFlight) {
|
|
1607
|
+
this.ownerDirectoryRecheck = true;
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1610
|
+
this.ownerDirectoryResolvedSignature = undefined;
|
|
1611
|
+
const promise = Promise.resolve().then(async () => {
|
|
1612
|
+
if (this.ownerDirectoryWatch !== watch || !this.connected)
|
|
1613
|
+
return;
|
|
1614
|
+
await this.passiveOwnerDirectoryRefresh(watch);
|
|
1615
|
+
}).catch(error => {
|
|
1616
|
+
logger.warn(`${this.logPrefix()} Owner directory passive refresh failed: ${errorCodeForLog(error) || 'UNKNOWN'}`);
|
|
1617
|
+
}).finally(() => {
|
|
1618
|
+
if (this.ownerDirectoryFlight !== promise)
|
|
1619
|
+
return;
|
|
1620
|
+
const resolvedSignature = this.ownerDirectoryResolvedSignature;
|
|
1621
|
+
const recheck = this.ownerDirectoryRecheck;
|
|
1622
|
+
this.ownerDirectoryFlight = undefined;
|
|
1623
|
+
this.ownerDirectoryResolvedSignature = undefined;
|
|
1624
|
+
this.ownerDirectoryRecheck = false;
|
|
1625
|
+
if (recheck && this.ownerDirectoryWatch === watch && this.connected) {
|
|
1626
|
+
const current = ownerResolver.snapshot(this.config.aid.replace(/^@/, ''));
|
|
1627
|
+
// The result of this flight already covers its own consensus notification.
|
|
1628
|
+
if (this.ownerDirectoryViewSignature(current) !== resolvedSignature)
|
|
1629
|
+
this.queueOwnerDirectoryRefresh();
|
|
1630
|
+
}
|
|
1631
|
+
});
|
|
1632
|
+
this.ownerDirectoryFlight = promise;
|
|
1633
|
+
}
|
|
1634
|
+
ownerDirectoryViewSignature(view) {
|
|
1635
|
+
return JSON.stringify([
|
|
1636
|
+
view.revision,
|
|
1637
|
+
view.consensusStatus,
|
|
1638
|
+
view.ownerAid,
|
|
1639
|
+
view.consensus?.relation_version,
|
|
1640
|
+
view.refreshFailure?.attemptId,
|
|
1641
|
+
]);
|
|
1642
|
+
}
|
|
1643
|
+
ownerDirectoryFailureReason(ownership) {
|
|
1644
|
+
const code = (ownership.refreshFailure?.code ?? ownership.consensus?.code ?? '').toUpperCase();
|
|
1645
|
+
const reason = ownership.refreshFailure?.reason ?? ownership.consensus?.reason ?? '';
|
|
1646
|
+
if (/TIMEOUT|ETIMEDOUT/.test(code) || /timed out|timeout/i.test(reason))
|
|
1647
|
+
return '核验超时';
|
|
1648
|
+
if (/projection|relation_version|NS relation changed|digest does not match/i.test(reason))
|
|
1649
|
+
return '关系信息不一致或发生变化';
|
|
1650
|
+
if (/CLIENT_DISCONNECTED|CONNECTION|NETWORK|ECONN|ENET|EHOST|EAI_AGAIN|ENOTFOUND/.test(code)
|
|
1651
|
+
|| /gateway|network|connection|socket hang up|not connected|fetch failed|temporarily unavailable/i.test(reason)) {
|
|
1652
|
+
return '连接或网络暂不可用';
|
|
1653
|
+
}
|
|
1654
|
+
if (ownership.consensusStatus === 'invalid')
|
|
1655
|
+
return '关系材料校验未通过';
|
|
1656
|
+
return '未取得可用核验结果';
|
|
1657
|
+
}
|
|
1658
|
+
async getOwnerDirectoryRuntime(expectedOwnerAid, verifyOwnership = true, expectedWatch) {
|
|
1659
|
+
const selfAid = this.config.aid.replace(/^@/, '');
|
|
1660
|
+
const client = this.client;
|
|
1661
|
+
logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime called: selfAid=${selfAid}, connected=${this.connected}, pureIdentity=${!!this.config.pureIdentity}`);
|
|
1662
|
+
if (!client || !this.connected || this.config.pureIdentity) {
|
|
1663
|
+
logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime early return: client=${!!client}, connected=${this.connected}, pureIdentity=${!!this.config.pureIdentity}`);
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
const ownership = verifyOwnership
|
|
1667
|
+
? await ownerResolver.refresh(selfAid, {
|
|
1668
|
+
force: !!expectedOwnerAid, allowTransient: !expectedOwnerAid, source: 'directory.runtime',
|
|
1669
|
+
})
|
|
1670
|
+
: ownerResolver.snapshot(selfAid);
|
|
1671
|
+
if (this.client !== client || !this.connected
|
|
1672
|
+
|| (expectedWatch && (this.ownerDirectoryWatch !== expectedWatch || expectedWatch.client !== client))) {
|
|
1673
|
+
logger.debug(`${this.logPrefix()} 跳过 Owner 目录刷新:连接已切换或断开,selfAid=${selfAid} clientChanged=${this.client !== client} connected=${this.connected}`);
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
if (expectedWatch && this.ownerDirectoryFlight) {
|
|
1677
|
+
this.ownerDirectoryResolvedSignature = this.ownerDirectoryViewSignature(ownership);
|
|
1678
|
+
}
|
|
1679
|
+
const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
|
|
1680
|
+
const expectedContext = expectedOwnerAid ? ` expectedOwnerAid=${expectedOwnerAid}` : '';
|
|
1681
|
+
const queryFailed = !!ownership.refreshFailure
|
|
1682
|
+
|| ownership.consensusStatus === 'invalid'
|
|
1683
|
+
|| (ownership.consensusStatus === 'unavailable' && ownership.consensus?.status === 'unavailable');
|
|
1684
|
+
if (queryFailed) {
|
|
1685
|
+
const code = ownership.refreshFailure?.code ?? ownership.consensus?.code ?? ownership.consensusStatus;
|
|
1686
|
+
const reason = this.ownerDirectoryFailureReason(ownership);
|
|
1687
|
+
const message = ownership.consensusStatus === 'invalid' ? 'Owner 关系核验未通过'
|
|
1688
|
+
: ownership.refreshFailure?.kind === 'permanent' ? 'Owner 关系核验失败' : 'Owner 关系核验暂不可用';
|
|
1689
|
+
logger.warn(`${this.logPrefix()} ${message}:selfAid=${selfAid} status=${ownership.consensusStatus} code=${code} 原因=${reason}${expectedContext}`);
|
|
1690
|
+
this.scheduleOwnerDirectoryRetry(ownership);
|
|
1691
|
+
}
|
|
1692
|
+
else if (ownership.consensusStatus === 'unavailable') {
|
|
1693
|
+
logger.debug(`${this.logPrefix()} 等待 Owner 关系核验完成,暂缓名录刷新:selfAid=${selfAid}${expectedContext}`);
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
else {
|
|
1697
|
+
this.clearOwnerDirectoryRetry();
|
|
1698
|
+
}
|
|
1699
|
+
if (!ownerAid) {
|
|
1700
|
+
if (!queryFailed) {
|
|
1701
|
+
const reason = ownership.consensusStatus === 'single_sided' ? '绑定待确认'
|
|
1702
|
+
: ownership.consensusStatus === 'unbound' ? '尚未绑定 Owner'
|
|
1703
|
+
: ownership.consensusStatus === 'released' ? 'Owner 关系已释放'
|
|
1704
|
+
: '未解析到 Owner';
|
|
1705
|
+
logger.info(`${this.logPrefix()} 跳过 Owner 目录刷新:${reason},selfAid=${selfAid} status=${ownership.consensusStatus}${expectedContext}`);
|
|
1706
|
+
}
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
if (expectedOwnerAid && (ownership.consensusStatus !== 'consensus'
|
|
1710
|
+
|| ownership.refreshFailure || ownership.ownerAid !== expectedOwnerAid)) {
|
|
1711
|
+
logger.info(`${this.logPrefix()} 跳过 Owner 目录刷新:Owner 与预期不符,selfAid=${selfAid} ownerAid=${ownerAid} expectedOwnerAid=${expectedOwnerAid}`);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
logger.debug(`${this.logPrefix()} Owner 目录运行时就绪:selfAid=${selfAid} ownerAid=${ownerAid} status=${ownership.consensusStatus}${expectedContext}`);
|
|
1715
|
+
if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid) {
|
|
1716
|
+
this.ownerDirectoryCache?.authorization.dispose();
|
|
1717
|
+
const directory = path.join(this.agentDir, 'directory');
|
|
1718
|
+
const cache = new OwnerDirectoryCache({
|
|
1719
|
+
selfAid,
|
|
1720
|
+
ownerAid,
|
|
1721
|
+
directory,
|
|
1722
|
+
client,
|
|
1723
|
+
onError: (scope, error) => logger.warn(`${this.logPrefix()} Owner ${scope} directory refresh failed: ${error instanceof Error ? error.message : String(error)}`),
|
|
1724
|
+
});
|
|
1725
|
+
const isCurrent = () => this.client === client && this.connected
|
|
1726
|
+
&& this.ownerDirectoryCache?.cache === cache
|
|
1727
|
+
&& (ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid)) === ownerAid;
|
|
1728
|
+
const authorization = new OwnerDirectoryAuthorization({
|
|
1729
|
+
selfAid, ownerAid, directory, cache, client, isCurrent,
|
|
1730
|
+
send: (payload, deviceId, ttl) => this.sendDaemonMsg({
|
|
1731
|
+
to: ownerAid, payload, deviceId, ttl, rawPayload: true, encrypt: true,
|
|
1732
|
+
}),
|
|
1733
|
+
});
|
|
1734
|
+
this.ownerDirectoryCache = { client, ownerAid, cache, authorization };
|
|
1735
|
+
registerOwnerDirectoryAdmission({ selfAid, ownerAid, cache, isCurrent });
|
|
1736
|
+
}
|
|
1737
|
+
return this.ownerDirectoryCache;
|
|
1738
|
+
}
|
|
1739
|
+
async refreshOwnerDirectoryCache(expectedOwnerAid) {
|
|
1740
|
+
const runtime = await this.getOwnerDirectoryRuntime(expectedOwnerAid);
|
|
1741
|
+
if (!runtime)
|
|
1742
|
+
return;
|
|
1743
|
+
if (expectedOwnerAid)
|
|
1744
|
+
await runtime.cache.handleOwnerChangedEvent(expectedOwnerAid);
|
|
1745
|
+
else {
|
|
1746
|
+
// Active authorization request removed: Owner now pushes grants via the
|
|
1747
|
+
// owner.directory.grant event. Only refresh already-authorized caches here.
|
|
1748
|
+
await runtime.cache.refreshIfNeeded();
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
/** Verify Ownership first; refresh existing grants without initiating an authorization request. */
|
|
1752
|
+
async passiveOwnerDirectoryRefresh(expectedWatch) {
|
|
1753
|
+
const runtime = await this.getOwnerDirectoryRuntime(undefined, true, expectedWatch);
|
|
1754
|
+
if (!runtime)
|
|
1755
|
+
return;
|
|
1756
|
+
await runtime.cache.refreshIfNeeded();
|
|
1757
|
+
}
|
|
1758
|
+
// Active authorization request disabled: Owner now pushes grants via the
|
|
1759
|
+
// owner.directory.grant event. Retained for reference / future re-enablement.
|
|
1760
|
+
/* disabled: active authorization removed
|
|
1761
|
+
private async requestOwnerDirectoryAuthorization(senderAid: string): Promise<void> {
|
|
1762
|
+
const runtime = await this.getOwnerDirectoryRuntime(senderAid);
|
|
1763
|
+
await runtime?.authorization.ensureAuthorization();
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
private checkOwnerDirectoryAuthorizationOnMessage(senderAid: string, payload: unknown): void {
|
|
1767
|
+
const currentOwner = ownerResolver.owner(this.config.aid.replace(/^@/, ''));
|
|
1768
|
+
const type = payload && typeof payload === 'object' ? (payload as Record<string, unknown>).type : undefined;
|
|
1769
|
+
if (currentOwner && senderAid !== currentOwner) return;
|
|
1770
|
+
if (typeof payload !== 'string' && !AUN_SESSION_STATE_PAYLOAD_TYPES.has(String(type))
|
|
1771
|
+
&& type !== 'merge' && type !== 'quote') return;
|
|
1772
|
+
void this.requestOwnerDirectoryAuthorization(senderAid).catch(error => {
|
|
1773
|
+
logger.warn(`${this.logPrefix()} Owner directory authorization check failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
*/
|
|
1777
|
+
async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
|
|
1778
|
+
const grant = parseOwnerDirectoryGrantAbilityResponse(record.responsePayload);
|
|
1779
|
+
if (!grant && !record.requestId.startsWith('owner-directory-auto-'))
|
|
1780
|
+
return;
|
|
1781
|
+
const runtime = await this.getOwnerDirectoryRuntime(senderAid);
|
|
1782
|
+
if (!runtime)
|
|
1783
|
+
return;
|
|
1784
|
+
if (runtime.authorization.ownsRequest(record)) {
|
|
1785
|
+
await runtime.authorization.acceptResponse(record);
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
if (grant) {
|
|
1789
|
+
runtime.cache.saveAuthorization(grant);
|
|
1790
|
+
if (runtime.cache.scopeAccess('agents') === 'authorized')
|
|
1791
|
+
await runtime.authorization.ensureAuthorization();
|
|
1792
|
+
await runtime.cache.handleOwnerChangedEvent(senderAid);
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
handleOwnerDirectoryChangedEvent(payload, senderAid) {
|
|
1796
|
+
const record = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
1797
|
+
? payload : undefined;
|
|
1798
|
+
if (record?.data?.schema_version !== 1) {
|
|
1799
|
+
logger.debug(`${this.logPrefix()} owner.directory.changed ignored: invalid schema_version`);
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
void this.refreshOwnerDirectoryCache(senderAid).catch(error => {
|
|
1803
|
+
logger.warn(`${this.logPrefix()} owner.directory.changed processing failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
handleOwnerDirectoryGrantEvent(payload, senderAid) {
|
|
1807
|
+
const record = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
1808
|
+
? payload : undefined;
|
|
1809
|
+
if (record?.data?.schema_version !== 1 || !record?.data?.grant) {
|
|
1810
|
+
logger.warn(`${this.logPrefix()} owner.directory.grant ignored: invalid schema (schema_version=${record?.data?.schema_version}, hasGrant=${!!record?.data?.grant})`);
|
|
1811
|
+
return;
|
|
1812
|
+
}
|
|
1813
|
+
logger.info(`${this.logPrefix()} owner.directory.grant received from ${senderAid}`);
|
|
1814
|
+
void this.handleOwnerDirectoryGrantFromOwner(senderAid, record.data.grant).catch(error => {
|
|
1815
|
+
logger.warn(`${this.logPrefix()} owner.directory.grant processing failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
async handleOwnerDirectoryGrantFromOwner(senderAid, grant) {
|
|
1819
|
+
const selfAid = this.config.aid.replace(/^@/, '');
|
|
1820
|
+
const parsed = parseOwnerDirectoryGrantAbilityResponse(grant);
|
|
1821
|
+
if (!parsed) {
|
|
1822
|
+
logger.warn(`${this.logPrefix()} owner.directory.grant: invalid grant payload (does not match evol-directory-access-v1 contract)`);
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
const runtime = await this.getOwnerDirectoryRuntime(senderAid);
|
|
1826
|
+
if (!runtime)
|
|
1827
|
+
return;
|
|
1828
|
+
runtime.cache.saveAuthorization(parsed);
|
|
1829
|
+
logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}, pulling directory`);
|
|
1830
|
+
await runtime.cache.handleOwnerChangedEvent(senderAid);
|
|
1831
|
+
logger.info(`${this.logPrefix()} owner.directory.grant: directory sync complete for ${selfAid}`);
|
|
1832
|
+
}
|
|
1491
1833
|
buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
|
|
1492
1834
|
if (!groupId)
|
|
1493
1835
|
throw new Error('buildGroupReplyContext requires groupId');
|
|
@@ -1822,6 +2164,8 @@ export class AUNChannel {
|
|
|
1822
2164
|
}
|
|
1823
2165
|
}
|
|
1824
2166
|
async _initClientInner() {
|
|
2167
|
+
this.configuredOwnerBindEpoch++;
|
|
2168
|
+
this.stopOwnerDirectoryRefresh();
|
|
1825
2169
|
this.observerGroupMembers.clear();
|
|
1826
2170
|
for (const groupId of new Set([
|
|
1827
2171
|
...this.observerGroupMembershipEpoch.keys(),
|
|
@@ -2122,12 +2466,14 @@ export class AUNChannel {
|
|
|
2122
2466
|
this.connected = true;
|
|
2123
2467
|
this.connectedAt = Date.now();
|
|
2124
2468
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
2469
|
+
this.reconcileConfiguredOwnerBinding();
|
|
2125
2470
|
if (!this.config.pureIdentity) {
|
|
2126
2471
|
void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
|
|
2127
2472
|
logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2128
2473
|
});
|
|
2129
2474
|
}
|
|
2130
2475
|
logger.info(`${this.logPrefix()} Connected as ${this._aid}`);
|
|
2476
|
+
this.startOwnerDirectoryRefresh();
|
|
2131
2477
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'connected', aid: this.config.aid, gateway: this.gatewayUrl });
|
|
2132
2478
|
appendAidLifecycle({ ts: Date.now(), iso: new Date().toISOString(), event: 'connected', aid: this.config.aid, gateway: this.gatewayUrl });
|
|
2133
2479
|
}
|
|
@@ -2148,7 +2494,7 @@ export class AUNChannel {
|
|
|
2148
2494
|
logger.warn(`${this.logPrefix()} agent config not found for ${aidName}, skipping welcome message`);
|
|
2149
2495
|
return false;
|
|
2150
2496
|
}
|
|
2151
|
-
await ownerResolver.refresh(aidName);
|
|
2497
|
+
await ownerResolver.refresh(aidName, { source: 'bootstrap.welcome' });
|
|
2152
2498
|
const owners = ownerResolver.owners(aidName);
|
|
2153
2499
|
if (owners.length === 0) {
|
|
2154
2500
|
logger.info(`${this.logPrefix()} No owner configured, skipping post-bootstrap welcome message`);
|
|
@@ -2239,15 +2585,19 @@ export class AUNChannel {
|
|
|
2239
2585
|
* already-active agent from manufacturing another welcome message.
|
|
2240
2586
|
*/
|
|
2241
2587
|
async reconcilePostBootstrapWelcome() {
|
|
2242
|
-
await this.repairBootstrapRoutes();
|
|
2243
2588
|
const configuredAid = this.config.aid;
|
|
2244
2589
|
const aid = configuredAid.startsWith('@') ? configuredAid.slice(1) : configuredAid;
|
|
2590
|
+
const pendingEntries = findPostBootstrapWelcomeOutbox(aid);
|
|
2591
|
+
if (pendingEntries.length === 0)
|
|
2592
|
+
return postBootstrapWelcomeStatus(aid, ownerResolver.owners(aid));
|
|
2593
|
+
await this.repairBootstrapRoutes();
|
|
2594
|
+
// Route repair may replace the persisted entry object (including its
|
|
2595
|
+
// delivery target), so drain the freshly reloaded entry instead of the
|
|
2596
|
+
// stale pre-repair snapshot.
|
|
2245
2597
|
const entries = findPostBootstrapWelcomeOutbox(aid);
|
|
2246
2598
|
const agentConfig = loadAgent(aid);
|
|
2247
|
-
await ownerResolver.refresh(aid);
|
|
2599
|
+
await ownerResolver.refresh(aid, { source: 'bootstrap.welcome' });
|
|
2248
2600
|
const owners = ownerResolver.owners(aid);
|
|
2249
|
-
if (entries.length === 0)
|
|
2250
|
-
return postBootstrapWelcomeStatus(aid, owners);
|
|
2251
2601
|
if (!agentConfig || resolveAgentLifecycle(agentConfig) !== 'active') {
|
|
2252
2602
|
logger.info(`${this.logPrefix()} Post-bootstrap welcome prepared; waiting for lifecycle=active`);
|
|
2253
2603
|
return postBootstrapWelcomeStatus(aid, owners);
|
|
@@ -2558,6 +2908,12 @@ export class AUNChannel {
|
|
|
2558
2908
|
payload,
|
|
2559
2909
|
});
|
|
2560
2910
|
if (responseRecord) {
|
|
2911
|
+
// An ignored device response or an ACK must not update authorization state.
|
|
2912
|
+
if (responseRecord.state === 'completed' && responseRecord.responseMessageId === messageId) {
|
|
2913
|
+
void this.handleOwnerDirectoryAuthorizationResponse(fromAid, responseRecord).catch(error => {
|
|
2914
|
+
logger.warn(`${this.logPrefix()} Owner directory authorization result processing failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2915
|
+
});
|
|
2916
|
+
}
|
|
2561
2917
|
logger.info(`${this.logPrefix()} AUN request response matched: request_id=${responseRecord.requestId} mid=${messageId}`);
|
|
2562
2918
|
const responseLog = classifyAunPayloadForLog(payload);
|
|
2563
2919
|
this.appendInboundPayloadJsonl(fromAid, fromAid, messageId, !!env.encrypted, false, responseLog, undefined, receivedAt, seq);
|
|
@@ -2611,6 +2967,8 @@ export class AUNChannel {
|
|
|
2611
2967
|
logger.debug(`${this.logPrefix()} P2P dropped: echo from self (from=${fromAid} mid=${messageId})`);
|
|
2612
2968
|
return;
|
|
2613
2969
|
}
|
|
2970
|
+
// Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
|
|
2971
|
+
// this.checkOwnerDirectoryAuthorizationOnMessage(fromAid, payload);
|
|
2614
2972
|
// 记录入站消息加密状态,透传到出站 ReplyContext
|
|
2615
2973
|
const msgEncrypted = !!env.encrypted;
|
|
2616
2974
|
if (!msgEncrypted)
|
|
@@ -2649,6 +3007,14 @@ export class AUNChannel {
|
|
|
2649
3007
|
});
|
|
2650
3008
|
return;
|
|
2651
3009
|
}
|
|
3010
|
+
if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.changed') {
|
|
3011
|
+
this.handleOwnerDirectoryChangedEvent(payload, fromAid);
|
|
3012
|
+
return;
|
|
3013
|
+
}
|
|
3014
|
+
if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.grant') {
|
|
3015
|
+
this.handleOwnerDirectoryGrantEvent(payload, fromAid);
|
|
3016
|
+
return;
|
|
3017
|
+
}
|
|
2652
3018
|
// action_card_reply 已在 extractTextPayload 中消费,不分发给 agent
|
|
2653
3019
|
if (p2pPayloadType === 'action_card_reply') {
|
|
2654
3020
|
this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
|
|
@@ -2833,6 +3199,8 @@ export class AUNChannel {
|
|
|
2833
3199
|
logger.debug(`${this.logPrefix()} Group dropped: own message (group=${groupId} mid=${messageId})`);
|
|
2834
3200
|
return;
|
|
2835
3201
|
}
|
|
3202
|
+
// Active authorization request removed: Owner now pushes grants via owner.directory.grant event.
|
|
3203
|
+
// this.checkOwnerDirectoryAuthorizationOnMessage(senderAid, payload);
|
|
2836
3204
|
// 短 echo 快速通道:连通性测试要尽量低延迟,命中后绕过所有 await(后续 mention 过滤)
|
|
2837
3205
|
{
|
|
2838
3206
|
const firstLineFast = text.split('\n')[0] || '';
|
|
@@ -3669,6 +4037,7 @@ export class AUNChannel {
|
|
|
3669
4037
|
return;
|
|
3670
4038
|
this.lastConnectionStateSignature = signature;
|
|
3671
4039
|
if (this.intentionalDisconnect && state === 'disconnected') {
|
|
4040
|
+
this.stopOwnerDirectoryRefresh();
|
|
3672
4041
|
this.connected = false;
|
|
3673
4042
|
this.connectedAt = 0;
|
|
3674
4043
|
return;
|
|
@@ -3685,13 +4054,18 @@ export class AUNChannel {
|
|
|
3685
4054
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
3686
4055
|
this.trace('IN', source, data);
|
|
3687
4056
|
logger.info(`${this.logPrefix()} Connected`);
|
|
4057
|
+
this.reconcileConfiguredOwnerBinding();
|
|
4058
|
+
this.startOwnerDirectoryRefresh();
|
|
3688
4059
|
// 不在这里清 flapCount —— 短命连接一上来就会触发本分支,
|
|
3689
4060
|
// 必须等 disconnected 时根据 lifetime 决定是否清零
|
|
3690
4061
|
this.drainOutbox();
|
|
3691
4062
|
}
|
|
3692
4063
|
else if (state === 'disconnected' || state === 'reconnecting') {
|
|
4064
|
+
this.stopOwnerDirectoryRefresh();
|
|
3693
4065
|
const wasConnected = this.connected;
|
|
3694
4066
|
this.connected = false;
|
|
4067
|
+
if (wasConnected)
|
|
4068
|
+
this.configuredOwnerBindEpoch++;
|
|
3695
4069
|
this.clearQueuedObserverSends(state);
|
|
3696
4070
|
// The nine-state SDK emits standby -> retry_backoff -> reconnecting for
|
|
3697
4071
|
// one reconnect cycle. Count the connected-to-down edge once instead of
|
|
@@ -3744,6 +4118,8 @@ export class AUNChannel {
|
|
|
3744
4118
|
}
|
|
3745
4119
|
}
|
|
3746
4120
|
else if (state === 'terminal_failed') {
|
|
4121
|
+
this.stopOwnerDirectoryRefresh();
|
|
4122
|
+
this.configuredOwnerBindEpoch++;
|
|
3747
4123
|
this.connected = false;
|
|
3748
4124
|
this.connectedAt = 0;
|
|
3749
4125
|
this.trace('IN', source, data);
|
|
@@ -3796,6 +4172,81 @@ export class AUNChannel {
|
|
|
3796
4172
|
}
|
|
3797
4173
|
}
|
|
3798
4174
|
}
|
|
4175
|
+
configuredOwnerAid() {
|
|
4176
|
+
const config = loadAgent(this.config.aid);
|
|
4177
|
+
if (!config)
|
|
4178
|
+
return undefined;
|
|
4179
|
+
const lifecycle = resolveAgentLifecycle(config);
|
|
4180
|
+
if (lifecycle === null || lifecycle === 'active')
|
|
4181
|
+
return undefined;
|
|
4182
|
+
return firstConfiguredOwner(config);
|
|
4183
|
+
}
|
|
4184
|
+
reconcileConfiguredOwnerBinding() {
|
|
4185
|
+
const client = this.client;
|
|
4186
|
+
const subjectAid = this.config.aid;
|
|
4187
|
+
const epoch = this.configuredOwnerBindEpoch;
|
|
4188
|
+
if (!client || !this.connected || this.intentionalDisconnect || this.config.pureIdentity)
|
|
4189
|
+
return;
|
|
4190
|
+
if (this.configuredOwnerBind) {
|
|
4191
|
+
if (this.configuredOwnerBind.client !== client || this.configuredOwnerBind.epoch !== epoch) {
|
|
4192
|
+
this.configuredOwnerBindRecheck = true;
|
|
4193
|
+
}
|
|
4194
|
+
return;
|
|
4195
|
+
}
|
|
4196
|
+
// Queue the work after installing the guard; config failures must not fail the channel connection.
|
|
4197
|
+
const promise = Promise.resolve()
|
|
4198
|
+
.then(() => this.submitConfiguredOwnerBinding(subjectAid, client, epoch))
|
|
4199
|
+
.catch(error => {
|
|
4200
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
4201
|
+
logger.warn(`${this.logPrefix()} Configured Owner binding invitation failed: ${reason}`);
|
|
4202
|
+
});
|
|
4203
|
+
const tracked = promise.finally(() => {
|
|
4204
|
+
if (this.configuredOwnerBind?.promise !== tracked)
|
|
4205
|
+
return;
|
|
4206
|
+
this.configuredOwnerBind = undefined;
|
|
4207
|
+
const recheck = this.configuredOwnerBindRecheck;
|
|
4208
|
+
this.configuredOwnerBindRecheck = false;
|
|
4209
|
+
if (recheck)
|
|
4210
|
+
this.reconcileConfiguredOwnerBinding();
|
|
4211
|
+
});
|
|
4212
|
+
this.configuredOwnerBind = { client, epoch, promise: tracked };
|
|
4213
|
+
}
|
|
4214
|
+
isCurrentConfiguredOwnerBind(client, epoch) {
|
|
4215
|
+
return this.client === client && this.configuredOwnerBindEpoch === epoch
|
|
4216
|
+
&& this.connected && !this.intentionalDisconnect;
|
|
4217
|
+
}
|
|
4218
|
+
async submitConfiguredOwnerBinding(subjectAid, client, epoch) {
|
|
4219
|
+
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
4220
|
+
return;
|
|
4221
|
+
const configuredOwnerAid = this.configuredOwnerAid();
|
|
4222
|
+
if (!configuredOwnerAid
|
|
4223
|
+
|| AUNChannel.configuredOwnerBindAttempts.has(JSON.stringify([subjectAid, configuredOwnerAid]))
|
|
4224
|
+
|| ownerResolver.hasRejectedOwnerBinding(subjectAid, configuredOwnerAid))
|
|
4225
|
+
return;
|
|
4226
|
+
ownerResolver.setConnected(subjectAid, client, true);
|
|
4227
|
+
const current = await ownerResolver.refresh(subjectAid, { force: true, source: 'channel.binding' });
|
|
4228
|
+
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
4229
|
+
return;
|
|
4230
|
+
// The config may change while the fresh consensus query is in flight.
|
|
4231
|
+
const ownerAid = this.configuredOwnerAid();
|
|
4232
|
+
if (!ownerAid || ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid))
|
|
4233
|
+
return;
|
|
4234
|
+
if (current.task?.operation === 'bind' && current.task.owner_aid === ownerAid
|
|
4235
|
+
&& current.task.status === 'rejected') {
|
|
4236
|
+
return;
|
|
4237
|
+
}
|
|
4238
|
+
if (current.consensusStatus === 'consensus')
|
|
4239
|
+
return;
|
|
4240
|
+
if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus))
|
|
4241
|
+
return;
|
|
4242
|
+
const attemptKey = JSON.stringify([subjectAid, ownerAid]);
|
|
4243
|
+
if (AUNChannel.configuredOwnerBindAttempts.has(attemptKey))
|
|
4244
|
+
return;
|
|
4245
|
+
// Claim before awaiting submission: an error or lost receipt must not cause automatic resends.
|
|
4246
|
+
AUNChannel.configuredOwnerBindAttempts.add(attemptKey);
|
|
4247
|
+
await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
|
|
4248
|
+
&& !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid));
|
|
4249
|
+
}
|
|
3799
4250
|
/** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
|
|
3800
4251
|
isKickReason(reason) {
|
|
3801
4252
|
if (!reason)
|
|
@@ -3870,6 +4321,7 @@ export class AUNChannel {
|
|
|
3870
4321
|
this.reconnectTimer = null;
|
|
3871
4322
|
}
|
|
3872
4323
|
// Force close SDK client,中断它内部的重连循环
|
|
4324
|
+
this.stopOwnerDirectoryRefresh();
|
|
3873
4325
|
if (this.client) {
|
|
3874
4326
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
3875
4327
|
this.trace('OUT', 'client.close', { reason: `takeover_${reason}` });
|
|
@@ -3895,6 +4347,7 @@ export class AUNChannel {
|
|
|
3895
4347
|
// initClient 完成后再次校验 generation,防止 initClient 期间被新的 takeover 取代
|
|
3896
4348
|
if (gen !== this.reconnectGeneration) {
|
|
3897
4349
|
logger.info(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded but generation stale, closing stale client`);
|
|
4350
|
+
this.stopOwnerDirectoryRefresh();
|
|
3898
4351
|
if (this.client) {
|
|
3899
4352
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
3900
4353
|
this.client.close().catch(() => { });
|
|
@@ -3941,6 +4394,9 @@ export class AUNChannel {
|
|
|
3941
4394
|
onProjectPathRequest(provider) {
|
|
3942
4395
|
this.projectPathProvider = provider;
|
|
3943
4396
|
}
|
|
4397
|
+
setSessionStateResolver(resolver) {
|
|
4398
|
+
this.sessionStateResolver = resolver;
|
|
4399
|
+
}
|
|
3944
4400
|
onMessage(handler) {
|
|
3945
4401
|
this.messageHandler = handler;
|
|
3946
4402
|
}
|
|
@@ -4066,6 +4522,57 @@ export class AUNChannel {
|
|
|
4066
4522
|
finalPayload.debug = { ...context.debug, sentAt: localTimestamp() };
|
|
4067
4523
|
return finalPayload;
|
|
4068
4524
|
}
|
|
4525
|
+
/**
|
|
4526
|
+
* Assemble the wire `ext` dictionary by merging all caller-supplied ext
|
|
4527
|
+
* sources and computing derived fields (turnMessageCount).
|
|
4528
|
+
* loop/fullaccess are intentionally excluded — withSessionState appends them
|
|
4529
|
+
* after querying live session state so they are never stale on retries.
|
|
4530
|
+
*/
|
|
4531
|
+
buildWireExt(channelId, threadId, contextExt, payloadExt) {
|
|
4532
|
+
const ext = {
|
|
4533
|
+
...(contextExt ?? {}),
|
|
4534
|
+
...(payloadExt ?? {}),
|
|
4535
|
+
};
|
|
4536
|
+
if (ext.isFinal) {
|
|
4537
|
+
const turnKey = `${channelId}\0${threadId ?? ''}`;
|
|
4538
|
+
ext.turnMessageCount = this.sentCount.get(turnKey) ?? 1;
|
|
4539
|
+
}
|
|
4540
|
+
return Object.keys(ext).length > 0 ? ext : undefined;
|
|
4541
|
+
}
|
|
4542
|
+
/** Refresh display hints at delivery, including outbox retries; they never grant permissions. */
|
|
4543
|
+
async withSessionState(channelId, payload, context) {
|
|
4544
|
+
if (!AUN_SESSION_STATE_PAYLOAD_TYPES.has(payload.type))
|
|
4545
|
+
return payload;
|
|
4546
|
+
const threadId = isTopicThreadId(payload.thread_id) ? payload.thread_id : context?.threadId;
|
|
4547
|
+
const ext = {
|
|
4548
|
+
...(this.buildWireExt(channelId, threadId, context?.ext, payload.ext && typeof payload.ext === 'object' && !Array.isArray(payload.ext)
|
|
4549
|
+
? payload.ext
|
|
4550
|
+
: undefined) ?? {}),
|
|
4551
|
+
};
|
|
4552
|
+
// Never reuse a caller's or an earlier delivery attempt's state hints.
|
|
4553
|
+
delete ext.loop;
|
|
4554
|
+
delete ext.fullaccess;
|
|
4555
|
+
try {
|
|
4556
|
+
const state = await this.sessionStateResolver?.(channelId, {
|
|
4557
|
+
...context,
|
|
4558
|
+
...(!context?.sessionId && typeof payload.session_id === 'string' ? { sessionId: payload.session_id } : {}),
|
|
4559
|
+
...(isTopicThreadId(payload.thread_id) ? { threadId: payload.thread_id } : {}),
|
|
4560
|
+
});
|
|
4561
|
+
if (typeof state?.loop === 'boolean')
|
|
4562
|
+
ext.loop = state.loop;
|
|
4563
|
+
if (typeof state?.fullaccess === 'boolean')
|
|
4564
|
+
ext.fullaccess = state.fullaccess;
|
|
4565
|
+
}
|
|
4566
|
+
catch (error) {
|
|
4567
|
+
logger.warn(`${this.logPrefix()} Outbound session state unavailable: channel=${channelId} error=${String(error)}`);
|
|
4568
|
+
}
|
|
4569
|
+
const result = { ...payload };
|
|
4570
|
+
if (Object.keys(ext).length > 0)
|
|
4571
|
+
result.ext = ext;
|
|
4572
|
+
else
|
|
4573
|
+
delete result.ext;
|
|
4574
|
+
return result;
|
|
4575
|
+
}
|
|
4069
4576
|
/**
|
|
4070
4577
|
* Validate AUN-specific structured fields before crossing the durable
|
|
4071
4578
|
* send boundary. Return a copy when mentions are present so callers do not
|
|
@@ -4161,6 +4668,10 @@ export class AUNChannel {
|
|
|
4161
4668
|
fallback.chatmode = truncateUtf8ToBytes(payload.chatmode, 32);
|
|
4162
4669
|
if (typeof payload.thread_id === 'string')
|
|
4163
4670
|
fallback.thread_id = payload.thread_id;
|
|
4671
|
+
if (typeof payload.topicName === 'string')
|
|
4672
|
+
fallback.topicName = truncateUtf8ToBytes(payload.topicName, 256);
|
|
4673
|
+
if (typeof payload.name_updated_at === 'number')
|
|
4674
|
+
fallback.name_updated_at = payload.name_updated_at;
|
|
4164
4675
|
logger.info(`${this.logPrefix()} Thought payload reduced to fallback (${Buffer.byteLength(JSON.stringify(fallback), 'utf8')} bytes)`);
|
|
4165
4676
|
return fallback;
|
|
4166
4677
|
}
|
|
@@ -4361,6 +4872,9 @@ export class AUNChannel {
|
|
|
4361
4872
|
logger.error(`${this.logPrefix()} Dropped durable AUN payload: invalid payload.mentions (${detail}) code=${code} channel=${channelId}`);
|
|
4362
4873
|
return { ok: false, status: 'permanent', error: detail, code };
|
|
4363
4874
|
}
|
|
4875
|
+
if (delivery.chatType === 'private') {
|
|
4876
|
+
normalizedPayload = this.withCurrentTopicName(channelId, normalizedPayload);
|
|
4877
|
+
}
|
|
4364
4878
|
if (!this.client || !this.connected) {
|
|
4365
4879
|
return { ok: false, status: 'retry', error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
4366
4880
|
}
|
|
@@ -4381,7 +4895,7 @@ export class AUNChannel {
|
|
|
4381
4895
|
if (payloadWithCausationRef.thread_id === '')
|
|
4382
4896
|
delete payloadWithCausationRef.thread_id;
|
|
4383
4897
|
// Truncate payload if too large (AUN SDK limit: 1MB)
|
|
4384
|
-
const truncatedPayload = this.truncatePayloadIfNeeded(payloadWithCausationRef, label);
|
|
4898
|
+
const truncatedPayload = this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
4385
4899
|
const params = { payload: truncatedPayload, encrypt };
|
|
4386
4900
|
const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
|
|
4387
4901
|
if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
|
|
@@ -4440,6 +4954,31 @@ export class AUNChannel {
|
|
|
4440
4954
|
return { ok: false, status: failure.status, error: failure.error, code: failure.code };
|
|
4441
4955
|
}
|
|
4442
4956
|
}
|
|
4957
|
+
withCurrentTopicName(peer, payload) {
|
|
4958
|
+
const threadId = payload.thread_id;
|
|
4959
|
+
if (!isTopicThreadId(threadId))
|
|
4960
|
+
return payload;
|
|
4961
|
+
const entry = ThreadService.findThreadById(this.config.aid, threadId);
|
|
4962
|
+
const type = payload.type;
|
|
4963
|
+
if (!entry || typeof threadId !== 'string' || threadId !== entry.threadId
|
|
4964
|
+
|| typeof type !== 'string' || !AUN_TOPIC_NAME_PAYLOAD_TYPES.has(type)
|
|
4965
|
+
|| entry.peer.trim().toLowerCase() !== peer.trim().toLowerCase()
|
|
4966
|
+
|| (entry.channelType && entry.channelType !== 'aun')) {
|
|
4967
|
+
return payload;
|
|
4968
|
+
}
|
|
4969
|
+
const name = entry.name.trim();
|
|
4970
|
+
if (!name || name === '话题会话' || name === '默认会话')
|
|
4971
|
+
return payload;
|
|
4972
|
+
// Older indexes lack a name version; use their stable creation timestamp.
|
|
4973
|
+
const nameUpdatedAt = entry.nameUpdatedAt ?? entry.createdAt;
|
|
4974
|
+
if (!Number.isSafeInteger(nameUpdatedAt) || nameUpdatedAt <= 0)
|
|
4975
|
+
return payload;
|
|
4976
|
+
return {
|
|
4977
|
+
...payload,
|
|
4978
|
+
topicName: name,
|
|
4979
|
+
name_updated_at: nameUpdatedAt,
|
|
4980
|
+
};
|
|
4981
|
+
}
|
|
4443
4982
|
recordDurableOutbound(channelId, payload, messageId, encrypt, context, isGroup, contentKind, logText, result, statsContext) {
|
|
4444
4983
|
const causation = normalizeCausation(context?.metadata?.causation);
|
|
4445
4984
|
if (!isGroup && causation)
|
|
@@ -4909,6 +5448,16 @@ export class AUNChannel {
|
|
|
4909
5448
|
}
|
|
4910
5449
|
if (args.debug)
|
|
4911
5450
|
finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
|
|
5451
|
+
if (!preserveRawPayload) {
|
|
5452
|
+
finalPayload = this.withCurrentTopicName(args.to, finalPayload);
|
|
5453
|
+
}
|
|
5454
|
+
if (!preserveRawPayload) {
|
|
5455
|
+
finalPayload = await this.withSessionState(args.to, finalPayload, {
|
|
5456
|
+
sessionId: args.log?.sessionId,
|
|
5457
|
+
threadId: args.log?.threadId ?? undefined,
|
|
5458
|
+
delivery: { chatType: 'private' },
|
|
5459
|
+
});
|
|
5460
|
+
}
|
|
4912
5461
|
const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
|
|
4913
5462
|
const sendParams = {
|
|
4914
5463
|
to: args.to,
|
|
@@ -5010,7 +5559,7 @@ export class AUNChannel {
|
|
|
5010
5559
|
// Validate before deep-cleaning so undefined entries cannot be silently
|
|
5011
5560
|
// removed from a malformed mentions array.
|
|
5012
5561
|
const validatedPayload = this.normalizeAunPayloadMentions(args.payload);
|
|
5013
|
-
|
|
5562
|
+
let finalPayload = this.stripUndefinedDeep(validatedPayload);
|
|
5014
5563
|
if (finalPayload.thread_id === '')
|
|
5015
5564
|
delete finalPayload.thread_id;
|
|
5016
5565
|
const payloadMentions = Object.prototype.hasOwnProperty.call(finalPayload, 'mentions')
|
|
@@ -5031,6 +5580,11 @@ export class AUNChannel {
|
|
|
5031
5580
|
}
|
|
5032
5581
|
if (args.debug)
|
|
5033
5582
|
finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
|
|
5583
|
+
finalPayload = await this.withSessionState(args.groupId, finalPayload, {
|
|
5584
|
+
sessionId: args.log?.sessionId,
|
|
5585
|
+
threadId: args.log?.threadId ?? undefined,
|
|
5586
|
+
delivery: { chatType: 'group', groupId: args.groupId },
|
|
5587
|
+
});
|
|
5034
5588
|
const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
|
|
5035
5589
|
const result = await this.callAndTrace('group.send', {
|
|
5036
5590
|
group_id: args.groupId,
|
|
@@ -5178,19 +5732,11 @@ export class AUNChannel {
|
|
|
5178
5732
|
}
|
|
5179
5733
|
// 从 context.metadata.source 读取 source,默认为 'daemon'
|
|
5180
5734
|
const source = context?.metadata?.source ?? 'daemon';
|
|
5181
|
-
//
|
|
5182
|
-
//
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
if (ext?.isFinal) {
|
|
5187
|
-
const turnKey = `${channelId}\0${context?.threadId ?? ''}`;
|
|
5188
|
-
const total = this.sentCount.get(turnKey) ?? 1;
|
|
5189
|
-
ext = { ...ext, turnMessageCount: total };
|
|
5190
|
-
}
|
|
5191
|
-
const payload = withAunAttention({ type: 'text', text: finalText }, context?.attention);
|
|
5192
|
-
if (ext && Object.keys(ext).length > 0)
|
|
5193
|
-
payload.ext = ext;
|
|
5735
|
+
// ext assembly (isFinal, seqInTurn, turnMessageCount, loop, fullaccess) is handled
|
|
5736
|
+
// centrally by withSessionState → buildWireExt; nothing to pre-merge here.
|
|
5737
|
+
const payload = await this.withSessionState(channelId, withAunAttention({
|
|
5738
|
+
type: 'text', text: finalText,
|
|
5739
|
+
}, context?.attention), context);
|
|
5194
5740
|
// sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
|
|
5195
5741
|
// 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
|
|
5196
5742
|
if (context?.debug)
|
|
@@ -5210,6 +5756,9 @@ export class AUNChannel {
|
|
|
5210
5756
|
payload.chatmode = context.metadata.chatmode;
|
|
5211
5757
|
if (context?.metadata?.forkAnchor)
|
|
5212
5758
|
payload.fork_anchor = context.metadata.forkAnchor;
|
|
5759
|
+
if (delivery.chatType === 'private') {
|
|
5760
|
+
Object.assign(payload, this.withCurrentTopicName(channelId, payload));
|
|
5761
|
+
}
|
|
5213
5762
|
const causation = normalizeCausation(context?.metadata?.causation);
|
|
5214
5763
|
const causationRef = delivery.chatType !== 'group' && causation
|
|
5215
5764
|
? `caus_${crypto.randomUUID().replace(/-/g, '')}`
|
|
@@ -5596,9 +6145,14 @@ export class AUNChannel {
|
|
|
5596
6145
|
// Same diagnostic dictionary as text payloads (sessionId/agentSessionId/model).
|
|
5597
6146
|
if (context?.debug)
|
|
5598
6147
|
payloadWithChatmode.debug = { ...context.debug, sentAt: localTimestamp() };
|
|
6148
|
+
let thoughtPayload = payloadWithChatmode;
|
|
6149
|
+
if (delivery.chatType === 'private') {
|
|
6150
|
+
thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
|
|
6151
|
+
}
|
|
6152
|
+
thoughtPayload = this.limitThoughtPayload(thoughtPayload);
|
|
5599
6153
|
const params = {
|
|
5600
6154
|
context: { type: 'task', id: taskId },
|
|
5601
|
-
payload:
|
|
6155
|
+
payload: thoughtPayload,
|
|
5602
6156
|
encrypt,
|
|
5603
6157
|
};
|
|
5604
6158
|
try {
|
|
@@ -5640,6 +6194,9 @@ export class AUNChannel {
|
|
|
5640
6194
|
if (!isThoughtTooLargeError(error))
|
|
5641
6195
|
throw error;
|
|
5642
6196
|
thoughtPayload = this.thoughtPayloadFallback(thoughtPayload);
|
|
6197
|
+
if (delivery.chatType === 'private') {
|
|
6198
|
+
thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
|
|
6199
|
+
}
|
|
5643
6200
|
params.payload = thoughtPayload;
|
|
5644
6201
|
thoughtText = this.activityLogText(thoughtPayload);
|
|
5645
6202
|
logger.warn(`${this.logPrefix()} Retrying ${method} with minimal payload after server size rejection`);
|
|
@@ -5676,7 +6233,7 @@ export class AUNChannel {
|
|
|
5676
6233
|
// Validate before checking connection state so malformed producer payloads
|
|
5677
6234
|
// are reported deterministically instead of being hidden by a disconnect.
|
|
5678
6235
|
const validatedPayload = this.normalizeAunPayloadMentions(payload);
|
|
5679
|
-
|
|
6236
|
+
let finalPayload = this.stripUndefinedDeep(withAunAttention(validatedPayload, context?.attention));
|
|
5680
6237
|
if (!this.connected || !this.client) {
|
|
5681
6238
|
return {
|
|
5682
6239
|
ok: false,
|
|
@@ -5698,7 +6255,11 @@ export class AUNChannel {
|
|
|
5698
6255
|
finalPayload.thread_id = context.threadId;
|
|
5699
6256
|
if (context?.replyToMessageId && !finalPayload.ref_message_id)
|
|
5700
6257
|
finalPayload.ref_message_id = context.replyToMessageId;
|
|
6258
|
+
if (!isGroup) {
|
|
6259
|
+
Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
|
|
6260
|
+
}
|
|
5701
6261
|
const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
|
|
6262
|
+
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
5702
6263
|
const params = { payload: finalPayload, encrypt };
|
|
5703
6264
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
5704
6265
|
params.to_device_id = context?.toDeviceId;
|
|
@@ -6007,13 +6568,16 @@ export class AUNChannel {
|
|
|
6007
6568
|
try {
|
|
6008
6569
|
const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
|
|
6009
6570
|
const { filename, size_bytes: size, content_type: contentType } = attachment;
|
|
6010
|
-
const filePayload = buildAunFilePayload({
|
|
6571
|
+
const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
|
|
6011
6572
|
filename,
|
|
6012
6573
|
size,
|
|
6013
6574
|
contentType,
|
|
6014
6575
|
attachment: { ...attachment },
|
|
6015
6576
|
context,
|
|
6016
|
-
});
|
|
6577
|
+
}), context);
|
|
6578
|
+
if (!isGroup) {
|
|
6579
|
+
Object.assign(filePayload, this.withCurrentTopicName(channelId, filePayload));
|
|
6580
|
+
}
|
|
6017
6581
|
const fileTargetAid = channelId;
|
|
6018
6582
|
const encryptTarget = isGroup ? channelId : fileTargetAid;
|
|
6019
6583
|
const encrypt = context?.metadata?.encrypted != null
|
|
@@ -6142,7 +6706,12 @@ export class AUNChannel {
|
|
|
6142
6706
|
async drainOutbox() {
|
|
6143
6707
|
if (!this.connected || !this.client)
|
|
6144
6708
|
return;
|
|
6145
|
-
|
|
6709
|
+
const bootstrapPending = [
|
|
6710
|
+
...outbox.findByDedupePrefix(this.config.aid, bootstrapInitialMessageOperationPrefix(this.config.aid)),
|
|
6711
|
+
...findPostBootstrapWelcomeOutbox(this.config.aid),
|
|
6712
|
+
].some(entry => !entry.terminal && !entry.deliveryResult);
|
|
6713
|
+
if (bootstrapPending)
|
|
6714
|
+
await this.repairBootstrapRoutes(false);
|
|
6146
6715
|
const drainQueue = async (queue) => {
|
|
6147
6716
|
if (!outbox.hasPending(this.config.aid, queue))
|
|
6148
6717
|
return;
|
|
@@ -6185,14 +6754,16 @@ export class AUNChannel {
|
|
|
6185
6754
|
await drainQueue('activity');
|
|
6186
6755
|
}
|
|
6187
6756
|
/** Repair bootstrap outbox entries to the configured personal Owner route. */
|
|
6188
|
-
async repairBootstrapRoutes() {
|
|
6757
|
+
async repairBootstrapRoutes(includeTerminal = true) {
|
|
6189
6758
|
const aid = this.config.aid.replace(/^@/, '');
|
|
6190
|
-
await ownerResolver.refresh(aid);
|
|
6191
|
-
const owners = ownerResolver.owners(aid);
|
|
6192
6759
|
const entries = [
|
|
6193
|
-
...outbox.findByDedupePrefix(aid, bootstrapInitialMessageOperationPrefix(aid), { includeTerminal
|
|
6194
|
-
...findPostBootstrapWelcomeOutbox(aid, { includeTerminal
|
|
6760
|
+
...outbox.findByDedupePrefix(aid, bootstrapInitialMessageOperationPrefix(aid), { includeTerminal }),
|
|
6761
|
+
...findPostBootstrapWelcomeOutbox(aid, { includeTerminal }),
|
|
6195
6762
|
].filter((entry) => !!entry?.channelId);
|
|
6763
|
+
if (entries.length === 0)
|
|
6764
|
+
return;
|
|
6765
|
+
await ownerResolver.refresh(aid, { source: includeTerminal ? 'bootstrap.welcome' : 'bootstrap.outbox' });
|
|
6766
|
+
const owners = ownerResolver.owners(aid);
|
|
6196
6767
|
for (const entry of entries) {
|
|
6197
6768
|
const isInitial = entry.dedupeKey?.startsWith(bootstrapInitialMessageOperationPrefix(aid));
|
|
6198
6769
|
const isOwnerSpecific = entry.dedupeKey?.startsWith(`bootstrap-complete:v2:${aid}:`);
|
|
@@ -6360,6 +6931,8 @@ export class AUNChannel {
|
|
|
6360
6931
|
await this.sendStructuredOrThrow(channelId, payloadObj, context);
|
|
6361
6932
|
}
|
|
6362
6933
|
async disconnect() {
|
|
6934
|
+
this.configuredOwnerBindEpoch++;
|
|
6935
|
+
this.stopOwnerDirectoryRefresh();
|
|
6363
6936
|
if (this.client)
|
|
6364
6937
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
6365
6938
|
this.managedMenuClient.close();
|
|
@@ -6619,6 +7192,10 @@ export class AUNChannelPlugin {
|
|
|
6619
7192
|
: (envelope.replyContext || envelope.delivery)
|
|
6620
7193
|
? { ...(envelope.replyContext ?? {}), delivery }
|
|
6621
7194
|
: undefined;
|
|
7195
|
+
if (envelope.sessionId && !replyCtx?.sessionId
|
|
7196
|
+
&& (payload.kind === 'result.text' || payload.kind === 'result.image' || payload.kind === 'result.file')) {
|
|
7197
|
+
replyCtx = { ...(replyCtx ?? {}), delivery, sessionId: envelope.sessionId };
|
|
7198
|
+
}
|
|
6622
7199
|
const attention = aunOutboundAttention(payload);
|
|
6623
7200
|
if (replyCtx) {
|
|
6624
7201
|
replyCtx = { ...replyCtx };
|
|
@@ -7106,6 +7683,30 @@ export class AUNChannelPlugin {
|
|
|
7106
7683
|
},
|
|
7107
7684
|
registerHooks(hookCtx) {
|
|
7108
7685
|
channel.setEventBus(hookCtx.eventBus);
|
|
7686
|
+
channel.setSessionStateResolver(async (channelId, context) => {
|
|
7687
|
+
const delivery = context?.delivery;
|
|
7688
|
+
if (!delivery)
|
|
7689
|
+
return undefined;
|
|
7690
|
+
const threadId = isTopicThreadId(context.threadId) ? context.threadId : undefined;
|
|
7691
|
+
const session = context.sessionId
|
|
7692
|
+
? await hookCtx.sessionManager.getSessionById(context.sessionId)
|
|
7693
|
+
: threadId
|
|
7694
|
+
? await hookCtx.sessionManager.getThreadSession(adapter.channelKey, channelId, threadId, aid)
|
|
7695
|
+
: hookCtx.sessionManager.getActiveSessionSync(adapter.channelKey, channelId, 'aun', aid);
|
|
7696
|
+
if (!session || session.selfAID !== aid || session.channel !== adapter.channelKey
|
|
7697
|
+
|| session.channelId !== channelId || session.chatType !== delivery.chatType
|
|
7698
|
+
|| sessionTopicThreadId(session) !== threadId
|
|
7699
|
+
|| (delivery.chatType === 'group' && session.metadata?.groupId !== delivery.groupId))
|
|
7700
|
+
return undefined;
|
|
7701
|
+
const target = resolveSessionLoopTarget(session);
|
|
7702
|
+
if (!target)
|
|
7703
|
+
return undefined;
|
|
7704
|
+
return {
|
|
7705
|
+
loop: readSessionLoopConfig(target)?.enabled === true,
|
|
7706
|
+
...(session.chatType === 'private'
|
|
7707
|
+
? { fullaccess: sessionFullAccessStatus(session, channelId).effective } : {}),
|
|
7708
|
+
};
|
|
7709
|
+
});
|
|
7109
7710
|
// 话题改名通知消费器:直接改本端索引,不经过 Agent 队列。
|
|
7110
7711
|
channel.setThreadRenameHandler(async (input) => {
|
|
7111
7712
|
const { ThreadService } = await import('../core/thread/thread-service.js');
|