evolcore 0.0.41 → 0.0.42
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 +36 -0
- package/bin/codex-managed-hook.mjs +9 -5
- package/dist/agents/baseagent.js +156 -16
- package/dist/agents/claude-runner.js +10 -3
- package/dist/agents/codex/catalog.js +8 -4
- package/dist/agents/codex-runner.js +236 -59
- package/dist/agents/ecagent-runner.js +82 -13
- package/dist/aun/aid/agentmd.js +106 -27
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +65 -13
- package/dist/aun/aid/identity.js +70 -4
- package/dist/aun/aid/index.js +2 -2
- package/dist/aun/service-proxy.js +25 -1
- package/dist/channels/aun.js +242 -209
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +1 -1
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +1 -1
- package/dist/channels/wecom.js +1 -1
- package/dist/cli/agent-command.js +183 -3
- package/dist/cli/agent-create.js +92 -86
- package/dist/cli/agent.js +136 -1
- package/dist/cli/aun-commands.js +137 -35
- package/dist/cli/bench.js +8 -2
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +235 -51
- package/dist/cli/debug-mode.js +1 -1
- package/dist/cli/directory.js +170 -0
- package/dist/cli/index.js +40 -30
- package/dist/cli/init-channel.js +4 -4
- package/dist/cli/init.js +47 -32
- package/dist/cli/managed-command-guard.js +4 -1
- package/dist/cli/model.js +27 -18
- package/dist/cli/pa-workspace-command.js +191 -0
- package/dist/cli/{contact.js → peer.js} +19 -25
- package/dist/cli/restart-monitor.js +11 -4
- package/dist/cli/thread-command.js +47 -18
- package/dist/cli/version.js +18 -18
- package/dist/config/access-policy.js +29 -12
- package/dist/config/boot-log.js +65 -10
- package/dist/config/builtin-roles.js +2 -4
- package/dist/config/config-field-policy.js +3 -0
- package/dist/config/config-manager.js +28 -20
- package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
- package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
- package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
- package/dist/config/{contact-book.js → peer-book.js} +47 -47
- package/dist/config/peer-operation-service.js +132 -0
- package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
- package/dist/config/peer-role-resolver.js +3 -3
- package/dist/config/providers-config.js +17 -8
- package/dist/config/providers.js +1 -1
- package/dist/config/schema-migration.js +336 -39
- package/dist/core/agent-application-service.js +8 -2
- package/dist/core/agent-create-status.js +4 -5
- package/dist/core/agent-ipc-registration.js +5 -4
- package/dist/core/agent-runtime.js +30 -17
- package/dist/core/auth/operation-authorizer.js +0 -24
- package/dist/core/auth/operation-catalog.js +4 -20
- package/dist/core/baseagent-loader.js +27 -3
- package/dist/core/bootstrap-service.js +5 -22
- package/dist/core/capability/capability-manager.js +52 -35
- package/dist/core/channel-loader.js +43 -2
- package/dist/core/channel-runtime.js +2 -2
- package/dist/core/command/agent-control.js +54 -18
- package/dist/core/command/command-handler.js +92 -72
- package/dist/core/command/connect-menu.js +35 -42
- package/dist/core/command/daemon-diagnostics.js +41 -5
- package/dist/core/command/data-root-error.js +10 -0
- package/dist/core/command/data-root-resolver.js +53 -13
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +163 -65
- package/dist/core/command/menu-protocol.js +52 -0
- package/dist/core/command/pa-workspace-calendar.js +223 -0
- package/dist/core/command/pa-workspace-store.js +459 -0
- package/dist/core/command/role-menu.js +2 -2
- package/dist/core/command/slash-gate.js +1 -1
- package/dist/core/command/slash-handler.js +57 -41
- package/dist/core/daemon-lifecycle.js +90 -31
- package/dist/core/evolagent.js +6 -10
- package/dist/core/handoff/runtime.js +11 -4
- package/dist/core/host-snapshot.js +208 -0
- package/dist/core/initialization/service.js +152 -20
- package/dist/core/ipc-registration.js +33 -4
- package/dist/core/memory/batch-meta.js +27 -0
- package/dist/core/memory/consolidation-ops-records.js +44 -1
- package/dist/core/memory/consolidation.js +169 -27
- package/dist/core/message/aun-ipc-sender.js +2 -8
- package/dist/core/message/im-renderer.js +56 -3
- package/dist/core/message/message-admission.js +121 -124
- package/dist/core/message/message-bridge.js +38 -54
- package/dist/core/message/message-queue.js +7 -0
- package/dist/core/message/outbound.js +34 -9
- package/dist/core/message/response-engine.js +154 -73
- package/dist/core/model/catalog-service.js +1 -1
- package/dist/core/model/config-scope.js +2 -2
- package/dist/core/model/model-catalog.js +5 -4
- package/dist/core/model/model-diagnostics.js +6 -5
- package/dist/core/model/model-fallback.js +3 -6
- package/dist/core/model/model-permission.js +1 -1
- package/dist/core/ownership/owner-resolver.js +9 -9
- package/dist/core/permission/approval-gateway.js +1 -1
- package/dist/core/permission/ec-command-parser.js +2 -2
- package/dist/core/permission/tool-canonical.js +96 -46
- package/dist/core/permission/tool-error-code.js +41 -0
- package/dist/core/permission/tool-policy.js +71 -47
- package/dist/core/role/runtime-policy.js +1 -1
- package/dist/core/session/session-idle-monitor.js +10 -0
- package/dist/core/session/session-manager.js +2 -4
- package/dist/core/session/session-title.js +36 -8
- package/dist/core/system-session/memory.js +2 -7
- package/dist/core/thread/command-parser.js +6 -2
- package/dist/core/thread/ipc-operation.js +51 -36
- package/dist/core/thread/thread-operation.js +29 -61
- package/dist/core/thread/thread-service.js +57 -13
- package/dist/directory/canonical-digest.js +54 -0
- package/dist/directory/owner-directory-admission.js +114 -43
- package/dist/directory/owner-directory-agentmd-sync.js +89 -0
- package/dist/directory/owner-directory-cache.js +847 -459
- package/dist/directory/owner-directory-markdown.js +272 -0
- package/dist/directory/owner-directory-query-operation.js +195 -0
- package/dist/directory/owner-directory-remark-operation.js +147 -0
- package/dist/directory/owner-directory-remarks.js +145 -0
- package/dist/directory/owner-directory-scope.js +55 -0
- package/dist/directory/owner-directory-search.js +148 -0
- package/dist/directory/owner-directory-store.js +227 -0
- package/dist/eck/kit-renderer.js +1 -0
- package/dist/ecweb/basic-settings-service.js +4 -1
- package/dist/ecweb/message-context-service.js +13 -9
- package/dist/index.js +195 -37
- package/dist/ipc.js +86 -22
- package/dist/paths.js +11 -8
- package/dist/product.js +2 -0
- package/dist/proxy/manager.js +13 -2
- package/dist/proxy/service-supervisor.js +8 -1
- package/dist/trigger/history.js +23 -0
- package/dist/trigger/scheduler.js +3 -0
- package/dist/utils/atomic-write.js +21 -0
- package/dist/utils/cross-platform.js +35 -0
- package/dist/utils/ecweb-supervisor.js +42 -0
- package/dist/utils/error-utils.js +2 -1
- package/dist/utils/evolcore-version.js +19 -0
- package/dist/utils/host-info.js +242 -5
- package/dist/utils/instance-registry.js +28 -6
- package/dist/utils/logger.js +59 -14
- package/dist/utils/machine-info.js +46 -0
- package/dist/utils/process-introspect.js +166 -2
- package/dist/utils/startup-trace.js +245 -0
- package/ecagent/dist/agent-loop.js +27 -13
- package/ecagent/dist/harness/agent-harness.js +3 -3
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/types.d.ts +1 -0
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
- package/kits/docs/evolcore/INDEX.md +3 -2
- package/kits/docs/evolcore/agent-create.md +17 -27
- package/kits/docs/evolcore/agent.md +4 -1
- package/kits/docs/evolcore/aid.md +3 -1
- package/kits/docs/evolcore/config.md +16 -5
- package/kits/docs/evolcore/ctl.md +9 -0
- package/kits/docs/evolcore/ec-capabilities.md +19 -0
- package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
- package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
- package/kits/docs/evolcore/menu-protocol.md +1 -0
- package/kits/docs/evolcore/model.md +13 -4
- package/kits/docs/evolcore/msg.md +1 -1
- package/kits/docs/evolcore/pa-workspace.md +51 -0
- package/kits/docs/evolcore/peer.md +73 -0
- package/kits/docs/evolcore/thread-chain.md +4 -1
- package/kits/eck_manifest.json +21 -0
- package/kits/rules/06-channel.md +1 -1
- package/kits/schemas/_meta.json +12 -1
- package/kits/schemas/agent-config.schema.16.json +6 -0
- package/kits/schemas/agent-config.schema.17.json +897 -0
- package/kits/schemas/daemon.schema.9.json +8 -1
- package/kits/skills/ec-agent-create/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +45 -27
- package/kits/skills/ec-service-proxy/SKILL.md +7 -2
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
- package/kits/skills/thread-ops/SKILL.md +11 -11
- package/kits/templates/bootstrap-welcome.md +3 -15
- package/kits/templates/message-fragments/item.md +1 -1
- package/kits/templates/system-fragments/bootstrap.md +24 -23
- package/kits/templates/system-fragments/commands.md +12 -5
- package/kits/templates/system-fragments/thread.md +18 -3
- package/package.json +6 -4
- package/dist/config/contact-operation-service.js +0 -235
- package/dist/directory/owner-directory-authorization.js +0 -309
- package/kits/docs/evolcore/contact.md +0 -78
- /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
package/dist/channels/aun.js
CHANGED
|
@@ -5,11 +5,14 @@ import { performance } from 'node:perf_hooks';
|
|
|
5
5
|
import fs from 'fs';
|
|
6
6
|
import { ownerResolver } from '../core/ownership/owner-resolver.js';
|
|
7
7
|
import { OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/owner-directory-cache.js';
|
|
8
|
-
import { OwnerDirectoryAuthorization } from '../directory/owner-directory-authorization.js';
|
|
9
8
|
import { registerOwnerDirectoryAdmission } from '../directory/owner-directory-admission.js';
|
|
9
|
+
import { OwnerDirectoryAgentMdSync } from '../directory/owner-directory-agentmd-sync.js';
|
|
10
|
+
import { parseNotificationSnapshots } from '../directory/owner-directory-store.js';
|
|
11
|
+
import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
|
|
12
|
+
import { resolveAllowExternalContacts } from '../directory/owner-directory-admission.js';
|
|
10
13
|
import path from 'path';
|
|
11
14
|
import os from 'os';
|
|
12
|
-
import { logger, localTimestamp } from '../utils/logger.js';
|
|
15
|
+
import { logger, localTimestamp, logPreview } from '../utils/logger.js';
|
|
13
16
|
import { LogWriter } from '../utils/log-writer.js';
|
|
14
17
|
import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
|
|
15
18
|
import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
|
|
@@ -44,7 +47,7 @@ import { deriveCausation, normalizeCausation } from '../core/causation/context.j
|
|
|
44
47
|
import { recordCausationSpan } from '../core/causation/audit.js';
|
|
45
48
|
import { invalidateAgentDisplayName, refreshAgentDisplayName, resolveAgentDisplayName } from '../aun/aid/agentmd.js';
|
|
46
49
|
import { buildControlAgentName, ensureControlAgentMd } from '../aun/aid/control-aid.js';
|
|
47
|
-
import { readInstalledEvolcoreVersion } from '../utils/evolcore-version.js';
|
|
50
|
+
import { errorTextContainsRaw, readInstalledEvolcoreVersion } from '../utils/evolcore-version.js';
|
|
48
51
|
import { ManagedMenuClient, menuSenderDeviceId, menuTransportParams, } from '../aun/menu/index.js';
|
|
49
52
|
import { toolInputForDisplay } from '../utils/tool-summary.js';
|
|
50
53
|
import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOutbox, pendingPostBootstrapWelcomeOwners, isPostBootstrapWelcomeOperationId, findPostBootstrapWelcomeOutbox, bootstrapInitialMessageOperationPrefix, postBootstrapWelcomeOperationId, preparePostBootstrapWelcomeOutbox, postBootstrapWelcomeStatus, } from '../core/bootstrap-messages.js';
|
|
@@ -57,8 +60,6 @@ import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js'
|
|
|
57
60
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
58
61
|
const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
|
|
59
62
|
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;
|
|
62
63
|
const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
|
|
63
64
|
const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
|
|
64
65
|
const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
|
|
@@ -67,6 +68,9 @@ const OBSERVER_GROUP_MEMBERS_PAGE_SIZE = 200;
|
|
|
67
68
|
const OBSERVER_GROUP_MEMBERS_MAX_PAGES = 100;
|
|
68
69
|
const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
|
|
69
70
|
const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
|
|
71
|
+
const OWNER_DIRECTORY_ACK_TTL_SECONDS = 30;
|
|
72
|
+
const OWNER_DIRECTORY_RETRY_BASE_MS = 1_000;
|
|
73
|
+
const OWNER_DIRECTORY_RETRY_MAX_MS = 60_000;
|
|
70
74
|
const AUN_MAX_FIELD_SIZE = 256 * 1024;
|
|
71
75
|
const AUN_MIN_FIELD_SIZE = 1024;
|
|
72
76
|
const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
|
|
@@ -591,7 +595,7 @@ function rawErrorText(raw) {
|
|
|
591
595
|
}
|
|
592
596
|
function appendRawErrorText(text, raw) {
|
|
593
597
|
const rawText = rawErrorText(raw);
|
|
594
|
-
if (!rawText || text
|
|
598
|
+
if (!rawText || errorTextContainsRaw(text, rawText))
|
|
595
599
|
return text;
|
|
596
600
|
return `${text}\n原因:${rawText}`;
|
|
597
601
|
}
|
|
@@ -719,7 +723,6 @@ export class AUNChannel {
|
|
|
719
723
|
ownerDirectoryRecheck = false;
|
|
720
724
|
ownerDirectoryRetryTimer;
|
|
721
725
|
ownerDirectoryRetryAttempts = 0;
|
|
722
|
-
ownerDirectoryObserved;
|
|
723
726
|
ownerDirectoryResolvedSignature;
|
|
724
727
|
store = null;
|
|
725
728
|
/** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
|
|
@@ -1524,12 +1527,10 @@ export class AUNChannel {
|
|
|
1524
1527
|
this.ownerDirectoryRetryAttempts = 0;
|
|
1525
1528
|
this.ownerDirectoryFlight = undefined;
|
|
1526
1529
|
this.ownerDirectoryRecheck = false;
|
|
1527
|
-
this.ownerDirectoryObserved = undefined;
|
|
1528
1530
|
this.ownerDirectoryResolvedSignature = undefined;
|
|
1529
|
-
this.ownerDirectoryCache?.authorization.dispose();
|
|
1530
1531
|
this.ownerDirectoryCache = undefined;
|
|
1531
1532
|
}
|
|
1532
|
-
/**
|
|
1533
|
+
/** Recheck ownership after material changes; directory content remains event-driven/lazy. */
|
|
1533
1534
|
startOwnerDirectoryRefresh() {
|
|
1534
1535
|
const client = this.client;
|
|
1535
1536
|
if (!client || !this.connected || this.intentionalDisconnect || this.config.pureIdentity)
|
|
@@ -1543,61 +1544,41 @@ export class AUNChannel {
|
|
|
1543
1544
|
stop: ownerResolver.onUpdate(subjectAid => {
|
|
1544
1545
|
if (subjectAid !== selfAid || this.ownerDirectoryWatch?.client !== client || !this.connected)
|
|
1545
1546
|
return;
|
|
1546
|
-
|
|
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
|
-
}
|
|
1547
|
+
this.queueOwnerDirectoryRefresh();
|
|
1571
1548
|
}),
|
|
1572
1549
|
};
|
|
1573
1550
|
this.queueOwnerDirectoryRefresh();
|
|
1574
1551
|
}
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1552
|
+
ownerDirectoryViewSignature(view) {
|
|
1553
|
+
return JSON.stringify([
|
|
1554
|
+
view.revision,
|
|
1555
|
+
view.consensusStatus,
|
|
1556
|
+
view.ownerAid,
|
|
1557
|
+
view.consensus?.relation_version,
|
|
1558
|
+
view.refreshFailure?.attemptId,
|
|
1559
|
+
]);
|
|
1580
1560
|
}
|
|
1581
|
-
scheduleOwnerDirectoryRetry(
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
this.
|
|
1561
|
+
scheduleOwnerDirectoryRetry(view) {
|
|
1562
|
+
if (view.refreshFailure?.kind !== 'transient') {
|
|
1563
|
+
if (this.ownerDirectoryRetryTimer)
|
|
1564
|
+
clearTimeout(this.ownerDirectoryRetryTimer);
|
|
1565
|
+
this.ownerDirectoryRetryTimer = undefined;
|
|
1566
|
+
this.ownerDirectoryRetryAttempts = 0;
|
|
1587
1567
|
return;
|
|
1588
1568
|
}
|
|
1589
1569
|
const client = this.client;
|
|
1590
|
-
|
|
1570
|
+
const watch = this.ownerDirectoryWatch;
|
|
1571
|
+
if (!client || !watch || watch.client !== client || !this.connected
|
|
1591
1572
|
|| this.intentionalDisconnect || this.ownerDirectoryRetryTimer)
|
|
1592
1573
|
return;
|
|
1593
1574
|
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=${
|
|
1575
|
+
logger.debug(`${this.logPrefix()} Owner 核验暂时失败,${delay}ms 后重试:selfAid=${view.subjectAid}`);
|
|
1595
1576
|
this.ownerDirectoryRetryTimer = setTimeout(() => {
|
|
1596
1577
|
this.ownerDirectoryRetryTimer = undefined;
|
|
1597
|
-
if (this.ownerDirectoryWatch
|
|
1578
|
+
if (this.ownerDirectoryWatch === watch && this.connected)
|
|
1598
1579
|
this.queueOwnerDirectoryRefresh();
|
|
1599
1580
|
}, delay);
|
|
1600
|
-
this.ownerDirectoryRetryTimer.unref();
|
|
1581
|
+
this.ownerDirectoryRetryTimer.unref?.();
|
|
1601
1582
|
}
|
|
1602
1583
|
queueOwnerDirectoryRefresh() {
|
|
1603
1584
|
const watch = this.ownerDirectoryWatch;
|
|
@@ -1611,51 +1592,44 @@ export class AUNChannel {
|
|
|
1611
1592
|
const promise = Promise.resolve().then(async () => {
|
|
1612
1593
|
if (this.ownerDirectoryWatch !== watch || !this.connected)
|
|
1613
1594
|
return;
|
|
1614
|
-
await this.
|
|
1595
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1596
|
+
if (this.ownerDirectoryWatch !== watch || !this.connected)
|
|
1597
|
+
return;
|
|
1598
|
+
const view = ownerResolver.snapshot(this.config.aid.replace(/^@/, ''));
|
|
1599
|
+
this.ownerDirectoryResolvedSignature = this.ownerDirectoryViewSignature(view);
|
|
1600
|
+
if (view.refreshFailure?.kind === 'transient')
|
|
1601
|
+
this.scheduleOwnerDirectoryRetry(view);
|
|
1602
|
+
else {
|
|
1603
|
+
if (this.ownerDirectoryRetryTimer)
|
|
1604
|
+
clearTimeout(this.ownerDirectoryRetryTimer);
|
|
1605
|
+
this.ownerDirectoryRetryTimer = undefined;
|
|
1606
|
+
this.ownerDirectoryRetryAttempts = 0;
|
|
1607
|
+
}
|
|
1608
|
+
runtime?.cache.writeStartupPendingIfEmpty();
|
|
1609
|
+
// 写了标记就立即拉一次(只写共享缓存,落地等下一条入站消息),
|
|
1610
|
+
// 否则新接入的 agent 要等有人发消息才有名录。
|
|
1611
|
+
void runtime?.cache.processPendingIfNeeded().catch(error => {
|
|
1612
|
+
logger.warn(`${this.logPrefix()} startup owner directory pull failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1613
|
+
});
|
|
1615
1614
|
}).catch(error => {
|
|
1616
|
-
logger.warn(`${this.logPrefix()} Owner directory
|
|
1615
|
+
logger.warn(`${this.logPrefix()} Owner directory ownership refresh failed: ${errorCodeForLog(error) || 'UNKNOWN'}`);
|
|
1617
1616
|
}).finally(() => {
|
|
1618
1617
|
if (this.ownerDirectoryFlight !== promise)
|
|
1619
1618
|
return;
|
|
1620
|
-
const
|
|
1619
|
+
const resolved = this.ownerDirectoryResolvedSignature;
|
|
1621
1620
|
const recheck = this.ownerDirectoryRecheck;
|
|
1622
1621
|
this.ownerDirectoryFlight = undefined;
|
|
1623
|
-
this.ownerDirectoryResolvedSignature = undefined;
|
|
1624
1622
|
this.ownerDirectoryRecheck = false;
|
|
1623
|
+
this.ownerDirectoryResolvedSignature = undefined;
|
|
1625
1624
|
if (recheck && this.ownerDirectoryWatch === watch && this.connected) {
|
|
1626
|
-
const current = ownerResolver.snapshot(this.config.aid.replace(/^@/, ''));
|
|
1627
|
-
|
|
1628
|
-
if (this.ownerDirectoryViewSignature(current) !== resolvedSignature)
|
|
1625
|
+
const current = this.ownerDirectoryViewSignature(ownerResolver.snapshot(this.config.aid.replace(/^@/, '')));
|
|
1626
|
+
if (current !== resolved)
|
|
1629
1627
|
this.queueOwnerDirectoryRefresh();
|
|
1630
1628
|
}
|
|
1631
1629
|
});
|
|
1632
1630
|
this.ownerDirectoryFlight = promise;
|
|
1633
1631
|
}
|
|
1634
|
-
|
|
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) {
|
|
1632
|
+
async getOwnerDirectoryRuntime() {
|
|
1659
1633
|
const selfAid = this.config.aid.replace(/^@/, '');
|
|
1660
1634
|
const client = this.client;
|
|
1661
1635
|
logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime called: selfAid=${selfAid}, connected=${this.connected}, pureIdentity=${!!this.config.pureIdentity}`);
|
|
@@ -1663,57 +1637,27 @@ export class AUNChannel {
|
|
|
1663
1637
|
logger.debug(`${this.logPrefix()} getOwnerDirectoryRuntime early return: client=${!!client}, connected=${this.connected}, pureIdentity=${!!this.config.pureIdentity}`);
|
|
1664
1638
|
return;
|
|
1665
1639
|
}
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
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
|
-
}
|
|
1640
|
+
// Let Core and the SDK reuse valid consensus; explicit authorization/bind operations
|
|
1641
|
+
// own their fresh checks. Material changes invalidate the SDK cache themselves.
|
|
1642
|
+
const ownership = await ownerResolver.refresh(selfAid, { allowTransient: true, source: 'directory.runtime' });
|
|
1643
|
+
// Fall back to configured owner for agents created before the ownership consensus protocol,
|
|
1644
|
+
// which may not yet have a consensus result but do have owners in config.json.
|
|
1679
1645
|
const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
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();
|
|
1646
|
+
logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'} (protocol=${ownerResolver.owner(selfAid) || 'none'}, known=${ownerResolver.knownOwner(selfAid) || 'none'})`);
|
|
1647
|
+
if (ownership.refreshFailure) {
|
|
1648
|
+
const code = ownership.refreshFailure.code || 'UNKNOWN';
|
|
1649
|
+
logger.warn(`${this.logPrefix()} Owner relationship refresh failed: status=${ownership.consensusStatus} code=${code}`);
|
|
1698
1650
|
}
|
|
1699
|
-
if (!ownerAid) {
|
|
1700
|
-
|
|
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;
|
|
1651
|
+
else if (!ownerAid && ['single_sided', 'unbound', 'released'].includes(ownership.consensusStatus)) {
|
|
1652
|
+
logger.info(`${this.logPrefix()} Owner directory skipped: relationship status=${ownership.consensusStatus}`);
|
|
1708
1653
|
}
|
|
1709
|
-
if (
|
|
1710
|
-
|
|
1711
|
-
logger.info(`${this.logPrefix()} 跳过 Owner 目录刷新:Owner 与预期不符,selfAid=${selfAid} ownerAid=${ownerAid} expectedOwnerAid=${expectedOwnerAid}`);
|
|
1654
|
+
if (!ownerAid || this.client !== client || !this.connected) {
|
|
1655
|
+
logger.debug(`${this.logPrefix()} Owner directory unavailable: owner=${ownerAid ? 'known' : 'unknown'}, connectionChanged=${this.client !== client || !this.connected}`);
|
|
1712
1656
|
return;
|
|
1713
1657
|
}
|
|
1714
|
-
logger.debug(`${this.logPrefix()} Owner 目录运行时就绪:selfAid=${selfAid} ownerAid=${ownerAid} status=${ownership.consensusStatus}${expectedContext}`);
|
|
1715
1658
|
if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid) {
|
|
1716
|
-
|
|
1659
|
+
// Keep the already-verified cache instance and its diagnostics, but let
|
|
1660
|
+
// the new cache implementation own storage and event synchronization.
|
|
1717
1661
|
const directory = path.join(this.agentDir, 'directory');
|
|
1718
1662
|
const cache = new OwnerDirectoryCache({
|
|
1719
1663
|
selfAid,
|
|
@@ -1721,87 +1665,150 @@ export class AUNChannel {
|
|
|
1721
1665
|
directory,
|
|
1722
1666
|
client,
|
|
1723
1667
|
onError: (scope, error) => logger.warn(`${this.logPrefix()} Owner ${scope} directory refresh failed: ${error instanceof Error ? error.message : String(error)}`),
|
|
1668
|
+
onSnapshotChanged: (_scope, aids) => {
|
|
1669
|
+
if (!isCurrent())
|
|
1670
|
+
return;
|
|
1671
|
+
// 名录有新增/变更条目,按差集批量刷新 agent.md(SDK 进程内去重)
|
|
1672
|
+
void this.ownerDirectoryCache?.agentMd.refreshAids(aids);
|
|
1673
|
+
},
|
|
1674
|
+
// 外部联系人默认不注入;个人助理缺省打开,判据与准入共用。
|
|
1675
|
+
allowExternalContacts: () => {
|
|
1676
|
+
try {
|
|
1677
|
+
return resolveAllowExternalContacts(selfAid, this.ownerDirectoryCache?.cache.readSnapshot('contacts'));
|
|
1678
|
+
}
|
|
1679
|
+
catch {
|
|
1680
|
+
return false;
|
|
1681
|
+
}
|
|
1682
|
+
},
|
|
1724
1683
|
});
|
|
1725
1684
|
const isCurrent = () => this.client === client && this.connected
|
|
1726
1685
|
&& this.ownerDirectoryCache?.cache === cache
|
|
1727
1686
|
&& (ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid)) === ownerAid;
|
|
1728
|
-
const
|
|
1729
|
-
selfAid,
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1687
|
+
const agentMd = new OwnerDirectoryAgentMdSync({
|
|
1688
|
+
selfAid,
|
|
1689
|
+
aunPath: this.config.keystorePath || resolveRoot(),
|
|
1690
|
+
store: () => this.store,
|
|
1691
|
+
isCurrent,
|
|
1692
|
+
onUpdated: aid => this.invalidatePeerAgentMd(aid),
|
|
1733
1693
|
});
|
|
1734
|
-
this.ownerDirectoryCache = { client, ownerAid, cache,
|
|
1694
|
+
this.ownerDirectoryCache = { client, ownerAid, cache, agentMd };
|
|
1735
1695
|
registerOwnerDirectoryAdmission({ selfAid, ownerAid, cache, isCurrent });
|
|
1736
1696
|
}
|
|
1737
1697
|
return this.ownerDirectoryCache;
|
|
1738
1698
|
}
|
|
1739
1699
|
async refreshOwnerDirectoryCache(expectedOwnerAid) {
|
|
1740
|
-
|
|
1700
|
+
return this.refreshOwnerDirectoryCacheWithHint(expectedOwnerAid, undefined);
|
|
1701
|
+
}
|
|
1702
|
+
async refreshOwnerDirectoryCacheWithHint(expectedOwnerAid, hint) {
|
|
1703
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1741
1704
|
if (!runtime)
|
|
1742
1705
|
return;
|
|
1743
|
-
if (expectedOwnerAid)
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1706
|
+
if (expectedOwnerAid) {
|
|
1707
|
+
// Extract content_digest strings from hint objects
|
|
1708
|
+
const digests = {};
|
|
1709
|
+
if (hint) {
|
|
1710
|
+
for (const scope of OWNER_DIRECTORY_SCOPES) {
|
|
1711
|
+
const h = hint[scope];
|
|
1712
|
+
if (h?.content_digest)
|
|
1713
|
+
digests[scope] = h.content_digest;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
await runtime.cache.handleOwnerChangedEvent(expectedOwnerAid, Object.keys(digests).length > 0 ? digests : undefined);
|
|
1749
1717
|
}
|
|
1750
1718
|
}
|
|
1751
|
-
/**
|
|
1752
|
-
|
|
1753
|
-
|
|
1719
|
+
/** 对端 agent.md 变了:清掉由它派生的显示名、群名和对端身份缓存,下次查询重新解析。 */
|
|
1720
|
+
invalidatePeerAgentMd(aid) {
|
|
1721
|
+
this.peerInfoRevision++;
|
|
1722
|
+
this.peerInfoCache.delete(aid);
|
|
1723
|
+
this.groupNameCache.delete(aid);
|
|
1724
|
+
invalidateAgentDisplayName(aid);
|
|
1725
|
+
PeerIdentityCache.invalidate('aun', aid, path.join(resolvePaths().agentsDir, this.config.aid));
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Fire-and-forget:每条进入消息队列的消息都走这里。
|
|
1729
|
+
*
|
|
1730
|
+
* ① 有 pending 就补拉一次共享缓存——立即拉取失败后,这里是唯一的重试机会;
|
|
1731
|
+
* ② 无论拉没拉成,都把共享缓存落到本 agent 目录。落地按 content_digest 判重,
|
|
1732
|
+
* 没有新内容时几乎零成本,所以不需要任何"有新内容吗"的标记。
|
|
1733
|
+
*
|
|
1734
|
+
* 两段串行,落地必须等拉取结束,否则可能拿旧数据覆盖刚落的新数据。
|
|
1735
|
+
*/
|
|
1736
|
+
processPendingDirectoryUpdate() {
|
|
1737
|
+
const runtime = this.ownerDirectoryCache;
|
|
1754
1738
|
if (!runtime)
|
|
1755
1739
|
return;
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
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
|
-
*/
|
|
1740
|
+
void runtime.cache.processPendingIfNeeded()
|
|
1741
|
+
.catch(error => {
|
|
1742
|
+
logger.warn(`${this.logPrefix()} processPendingDirectoryUpdate pull failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1743
|
+
})
|
|
1744
|
+
.then(() => runtime.cache.applyFromSharedCache())
|
|
1745
|
+
.catch(error => {
|
|
1746
|
+
logger.warn(`${this.logPrefix()} processPendingDirectoryUpdate apply failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1777
1749
|
async handleOwnerDirectoryAuthorizationResponse(senderAid, record) {
|
|
1750
|
+
// 只认点名发给的那台设备:广播或其它设备的回复不能改写授权状态。
|
|
1751
|
+
// 无 targetDeviceId 的是旧记录,无从校验,放行(调用方已确认 state=completed 且消息匹配)。
|
|
1752
|
+
if (record.targetDeviceId && record.responseDeviceId !== record.targetDeviceId) {
|
|
1753
|
+
logger.warn(`${this.logPrefix()} Owner directory authorization response ignored: device mismatch `
|
|
1754
|
+
+ `(target=${record.targetDeviceId} response=${record.responseDeviceId ?? 'none'})`);
|
|
1755
|
+
return;
|
|
1756
|
+
}
|
|
1778
1757
|
const grant = parseOwnerDirectoryGrantAbilityResponse(record.responsePayload);
|
|
1779
|
-
if (!grant
|
|
1758
|
+
if (!grant)
|
|
1780
1759
|
return;
|
|
1781
|
-
const runtime = await this.getOwnerDirectoryRuntime(
|
|
1760
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1782
1761
|
if (!runtime)
|
|
1783
1762
|
return;
|
|
1784
|
-
|
|
1785
|
-
|
|
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
|
-
}
|
|
1763
|
+
runtime.cache.saveAuthorization(grant);
|
|
1764
|
+
await runtime.cache.handleOwnerChangedEvent(senderAid);
|
|
1794
1765
|
}
|
|
1795
|
-
handleOwnerDirectoryChangedEvent(payload, senderAid) {
|
|
1766
|
+
async handleOwnerDirectoryChangedEvent(payload, senderAid, senderDeviceId) {
|
|
1796
1767
|
const record = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
1797
1768
|
? payload : undefined;
|
|
1798
|
-
if (record?.data
|
|
1769
|
+
if (!record?.data || (record.data.schema_version !== 1 && record.data.schema_version !== 2)) {
|
|
1799
1770
|
logger.debug(`${this.logPrefix()} owner.directory.changed ignored: invalid schema_version`);
|
|
1800
1771
|
return;
|
|
1801
1772
|
}
|
|
1802
|
-
|
|
1773
|
+
const digests = parseNotificationSnapshots(record.data);
|
|
1774
|
+
// ACK 只回传通知自带的 operation_id;旧版通知不带它,也不等 ACK,不能自造一个回过去。
|
|
1775
|
+
const operationId = typeof record.data.operation_id === 'string' && record.data.operation_id.trim()
|
|
1776
|
+
? record.data.operation_id : undefined;
|
|
1777
|
+
try {
|
|
1778
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1779
|
+
if (!runtime)
|
|
1780
|
+
return;
|
|
1781
|
+
// 记标记。真正的网络拉取在 ACK 之后发起(见方法末尾):先拉会把网络耗时
|
|
1782
|
+
// 压进 App 侧的重试窗口,App 可能因此在拿到 ACK 前再发一次通知。
|
|
1783
|
+
await runtime.cache.handleOwnerChangedEvent(senderAid, Object.keys(digests).length > 0 ? Object.fromEntries(Object.entries(digests).map(([k, v]) => [k, v?.content_digest ?? ''])) : undefined);
|
|
1784
|
+
// 重试状态只在发通知的那台设备内存里;拿不到它的设备 ID 就不回,
|
|
1785
|
+
// 广播给 Owner 全部设备既清不掉重试,又会被其它设备当成会话消息展示。
|
|
1786
|
+
if (operationId && senderDeviceId) {
|
|
1787
|
+
// Reply ack so frontend stops retrying for this agent
|
|
1788
|
+
const sent = await this.sendDaemonMsg({
|
|
1789
|
+
to: senderAid,
|
|
1790
|
+
deviceId: senderDeviceId,
|
|
1791
|
+
payload: { type: 'event', event: 'owner.directory.ack', data: {
|
|
1792
|
+
schema_version: 1, operation_id: operationId,
|
|
1793
|
+
agent_aid: this.config.aid.replace(/^@/, ''),
|
|
1794
|
+
} },
|
|
1795
|
+
rawPayload: true,
|
|
1796
|
+
encrypt: true,
|
|
1797
|
+
// 非持久化:ACK 只对 App 在线等待的那次重试有意义,30 秒后作废,不进会话历史。
|
|
1798
|
+
ttl: OWNER_DIRECTORY_ACK_TTL_SECONDS,
|
|
1799
|
+
});
|
|
1800
|
+
if (!sent.ok)
|
|
1801
|
+
logger.warn(`${this.logPrefix()} owner.directory.ack send failed: ${sent.code ?? ''} ${sent.error ?? ''}`);
|
|
1802
|
+
}
|
|
1803
|
+
// 拉取排在 ACK 之后,只写共享缓存、不碰 agent 目录:落地由下一条进队列的消息做。
|
|
1804
|
+
// fire-and-forget,失败由 pending 兜底,下次消息或通知会重试。
|
|
1805
|
+
void runtime.cache.processPendingIfNeeded().catch(error => {
|
|
1806
|
+
logger.warn(`${this.logPrefix()} owner.directory.changed pull failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1807
|
+
});
|
|
1808
|
+
}
|
|
1809
|
+
catch (error) {
|
|
1803
1810
|
logger.warn(`${this.logPrefix()} owner.directory.changed processing failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1804
|
-
}
|
|
1811
|
+
}
|
|
1805
1812
|
}
|
|
1806
1813
|
handleOwnerDirectoryGrantEvent(payload, senderAid) {
|
|
1807
1814
|
const record = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
@@ -1822,13 +1829,17 @@ export class AUNChannel {
|
|
|
1822
1829
|
logger.warn(`${this.logPrefix()} owner.directory.grant: invalid grant payload (does not match evol-directory-access-v1 contract)`);
|
|
1823
1830
|
return;
|
|
1824
1831
|
}
|
|
1825
|
-
const runtime = await this.getOwnerDirectoryRuntime(
|
|
1832
|
+
const runtime = await this.getOwnerDirectoryRuntime();
|
|
1826
1833
|
if (!runtime)
|
|
1827
1834
|
return;
|
|
1828
1835
|
runtime.cache.saveAuthorization(parsed);
|
|
1829
|
-
logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}
|
|
1830
|
-
|
|
1831
|
-
|
|
1836
|
+
logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
|
|
1837
|
+
// 授权变更本身不触发拉取:名录变没变由 owner.directory.changed 说了算。
|
|
1838
|
+
// 只有本地还没有任何快照时才补一次,否则新授权的 agent 要等到下一条入站消息才有名录。
|
|
1839
|
+
if (!runtime.cache.readSnapshot('contacts')) {
|
|
1840
|
+
logger.info(`${this.logPrefix()} owner.directory.grant: no local snapshot yet, scheduling first pull`);
|
|
1841
|
+
await runtime.cache.handleOwnerChangedEvent(senderAid);
|
|
1842
|
+
}
|
|
1832
1843
|
}
|
|
1833
1844
|
buildGroupReplyContext(threadId, senderAid, encrypted, messageId, chatmode, topicName, groupId, label, topicStatus) {
|
|
1834
1845
|
if (!groupId)
|
|
@@ -2164,8 +2175,8 @@ export class AUNChannel {
|
|
|
2164
2175
|
}
|
|
2165
2176
|
}
|
|
2166
2177
|
async _initClientInner() {
|
|
2167
|
-
this.configuredOwnerBindEpoch++;
|
|
2168
2178
|
this.stopOwnerDirectoryRefresh();
|
|
2179
|
+
this.configuredOwnerBindEpoch++;
|
|
2169
2180
|
this.observerGroupMembers.clear();
|
|
2170
2181
|
for (const groupId of new Set([
|
|
2171
2182
|
...this.observerGroupMembershipEpoch.keys(),
|
|
@@ -2237,12 +2248,10 @@ export class AUNChannel {
|
|
|
2237
2248
|
catch {
|
|
2238
2249
|
return;
|
|
2239
2250
|
}
|
|
2240
|
-
this.
|
|
2241
|
-
this.peerInfoCache.delete(aid);
|
|
2242
|
-
this.groupNameCache.delete(aid);
|
|
2243
|
-
invalidateAgentDisplayName(aid);
|
|
2244
|
-
PeerIdentityCache.invalidate('aun', aid, path.join(resolvePaths().agentsDir, this.config.aid));
|
|
2251
|
+
this.invalidatePeerAgentMd(aid);
|
|
2245
2252
|
this.trace('IN', 'agentmd.changed', { aid });
|
|
2253
|
+
// SDK 只在本地无正文时自动下载;名录成员的已有副本在这里立即换新,不等下一次身份解析。
|
|
2254
|
+
void this.ownerDirectoryCache?.agentMd.refreshAid(aid);
|
|
2246
2255
|
// Peer snapshots refresh lazily on the next lookup. The self name is
|
|
2247
2256
|
// held separately by this channel, so refresh it with the existing API.
|
|
2248
2257
|
if (aid === (this._aid || this.config.aid)) {
|
|
@@ -2254,6 +2263,26 @@ export class AUNChannel {
|
|
|
2254
2263
|
});
|
|
2255
2264
|
}
|
|
2256
2265
|
});
|
|
2266
|
+
// 0.5.28: Owner 侧收到 sub 的 agent.md 变更通知(sdk_control 消息在 SDK 内部处理后 emit)
|
|
2267
|
+
client.on('agent_md_changed', (data) => {
|
|
2268
|
+
if (!isCurrentClient() || this.intentionalDisconnect)
|
|
2269
|
+
return;
|
|
2270
|
+
const aid = (data && typeof data === 'object' && typeof data.aid === 'string')
|
|
2271
|
+
? data.aid : undefined;
|
|
2272
|
+
if (!aid)
|
|
2273
|
+
return;
|
|
2274
|
+
this.trace('IN', 'agent_md_changed', { aid, etag: data.etag });
|
|
2275
|
+
// sub 的 agent.md 已变更,使 Ownership 缓存失效并重查;同时刷新名录副本
|
|
2276
|
+
void ownerResolver.refresh(aid, { force: true });
|
|
2277
|
+
void this.ownerDirectoryCache?.agentMd.refreshAid(aid);
|
|
2278
|
+
});
|
|
2279
|
+
client.on('risk_state_changed', (event) => {
|
|
2280
|
+
if (!isCurrentClient())
|
|
2281
|
+
return;
|
|
2282
|
+
const e = event;
|
|
2283
|
+
logger.warn(`${this.logPrefix()} risk_state_changed: state=${e?.state} scope=${e?.scope ?? 'connection'}`);
|
|
2284
|
+
this.trace('IN', 'risk_state_changed', event);
|
|
2285
|
+
});
|
|
2257
2286
|
client.on('message.received', async (data) => {
|
|
2258
2287
|
if (!isCurrentClient())
|
|
2259
2288
|
return;
|
|
@@ -2467,12 +2496,14 @@ export class AUNChannel {
|
|
|
2467
2496
|
this.connectedAt = Date.now();
|
|
2468
2497
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
2469
2498
|
this.reconcileConfiguredOwnerBinding();
|
|
2499
|
+
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
2500
|
+
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
2470
2501
|
if (!this.config.pureIdentity) {
|
|
2471
2502
|
void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
|
|
2472
2503
|
logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2473
2504
|
});
|
|
2474
2505
|
}
|
|
2475
|
-
logger.
|
|
2506
|
+
logger.debug(`${this.logPrefix()} connect() completed as ${this._aid}; awaiting connection.state for lifecycle log`);
|
|
2476
2507
|
this.startOwnerDirectoryRefresh();
|
|
2477
2508
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'connected', aid: this.config.aid, gateway: this.gatewayUrl });
|
|
2478
2509
|
appendAidLifecycle({ ts: Date.now(), iso: new Date().toISOString(), event: 'connected', aid: this.config.aid, gateway: this.gatewayUrl });
|
|
@@ -2659,12 +2690,14 @@ export class AUNChannel {
|
|
|
2659
2690
|
try {
|
|
2660
2691
|
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType);
|
|
2661
2692
|
img = { ...img, attachmentId: attachment.attachmentId, localPath: attachment.filePath };
|
|
2693
|
+
// 和非图片文件一样,把落盘绝对路径放进消息正文,模型可直接用这个路径读文件或传给命令
|
|
2694
|
+
fileParts.push(`[图片: ${name} → ${attachment.filePath}]`);
|
|
2662
2695
|
}
|
|
2663
2696
|
catch (error) {
|
|
2664
2697
|
logger.warn(`${this.logPrefix()} Failed to persist relation attachment for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2665
2698
|
}
|
|
2666
2699
|
images.push(img);
|
|
2667
|
-
//
|
|
2700
|
+
// 图片已注入视觉通道;落盘绝对路径写进消息正文,模型用该路径读文件或传给命令
|
|
2668
2701
|
}
|
|
2669
2702
|
else {
|
|
2670
2703
|
const projectPath = this.projectPathProvider
|
|
@@ -2995,7 +3028,7 @@ export class AUNChannel {
|
|
|
2995
3028
|
const p2pPayloadType = (payload && typeof payload === 'object' && typeof payload.type === 'string')
|
|
2996
3029
|
? payload.type
|
|
2997
3030
|
: '';
|
|
2998
|
-
logger.
|
|
3031
|
+
logger.debug(`${this.logPrefix()} P2P dispatch decision: mid=${messageId} from=${shortAid}(${displayName}) peerType=${peerIdentity.type} payloadType=${p2pPayloadType} chatId=${chatId} encrypt=${msgEncrypted} textPreview=${JSON.stringify(logPreview(text))}`);
|
|
2999
3032
|
if (p2pPayloadType === 'text') {
|
|
3000
3033
|
import('../utils/msg-diag.js').then(m => m.diagLog('aun_in', { aid: this.config.aid, from: fromAid, to: this.config.aid, msgId: messageId, text })).catch(() => { });
|
|
3001
3034
|
}
|
|
@@ -3008,7 +3041,7 @@ export class AUNChannel {
|
|
|
3008
3041
|
return;
|
|
3009
3042
|
}
|
|
3010
3043
|
if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.changed') {
|
|
3011
|
-
this.handleOwnerDirectoryChangedEvent(payload, fromAid);
|
|
3044
|
+
void this.handleOwnerDirectoryChangedEvent(payload, fromAid, menuSenderDeviceId(msg.sender_device_id));
|
|
3012
3045
|
return;
|
|
3013
3046
|
}
|
|
3014
3047
|
if (p2pPayloadType === 'event' && payload?.event === 'owner.directory.grant') {
|
|
@@ -3091,7 +3124,7 @@ export class AUNChannel {
|
|
|
3091
3124
|
return;
|
|
3092
3125
|
}
|
|
3093
3126
|
const msgChatmode = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
3094
|
-
logger.info(`${this.logPrefix()}
|
|
3127
|
+
logger.info(`${this.logPrefix()} message.route: decision=dispatch chatType=private from=${shortAid}(${displayName}) mid=${messageId} payloadType=${p2pPayloadType || 'text'} encrypt=${msgEncrypted} chatmode=${msgChatmode ?? 'none'} textPreview=${JSON.stringify(logPreview(finalText))}`);
|
|
3095
3128
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
|
|
3096
3129
|
const isSystemP2P = p2pPayloadType === 'event';
|
|
3097
3130
|
this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
|
|
@@ -3370,12 +3403,12 @@ export class AUNChannel {
|
|
|
3370
3403
|
: mentionedSelf
|
|
3371
3404
|
? (structMentionSelf ? 'mention.self(struct)' : 'mention.self(text)')
|
|
3372
3405
|
: `${mentionMode}.no-mention`;
|
|
3373
|
-
logger.
|
|
3406
|
+
logger.debug(`${this.logPrefix()} Group mention decision: mid=${messageId} group=${groupId} sender=${shortAid}(${displayName}) peerType=${peerIdentity.type} payloadType=${payloadType} mentionMode=${mentionMode} slashRequireMentions=${groupSlashRequireMentions} reason=${reason} structMentions=${JSON.stringify(payloadMentionEntries)} textMentionSelf=${textMentionSelf} textMentionAll=${textMentionAll} structMentionSelf=${structMentionSelf} structMentionAll=${structMentionAll} encrypt=${msgEncrypted} textPreview=${JSON.stringify(logPreview(text))}`);
|
|
3374
3407
|
// action_card_reply 已在 extractTextPayload 中消费,不分发给 agent
|
|
3375
3408
|
if (payloadType === 'action_card_reply')
|
|
3376
3409
|
return;
|
|
3377
3410
|
const msgChatmode = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
3378
|
-
logger.info(`${this.logPrefix()}
|
|
3411
|
+
logger.info(`${this.logPrefix()} message.route: decision=dispatch chatType=group group=${groupId} sender=${shortAid}(${displayName}) mid=${messageId} payloadType=${payloadType || 'text'} mentionMode=${mentionMode} reason=${reason} encrypt=${msgEncrypted} chatmode=${msgChatmode ?? 'none'} textPreview=${JSON.stringify(logPreview(finalText))}`);
|
|
3379
3412
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: senderAid, msgId: messageId, kind: 'text', len: finalText.length, groupId });
|
|
3380
3413
|
this.aidStatsCollector?.recordInbound(this.config.aid, senderAid, Buffer.byteLength(finalText, 'utf-8'), finalText, payloadType === 'event', msgEncrypted, msgChatmode, payloadType === 'event' ? 'notify' : 'send');
|
|
3381
3414
|
// 渲染用完整 @ 列表:结构化 payload.mentions + 正文 @aid 兜底,去重(含 self / "all")。
|
|
@@ -3416,6 +3449,8 @@ export class AUNChannel {
|
|
|
3416
3449
|
});
|
|
3417
3450
|
}
|
|
3418
3451
|
dispatchMessage(event) {
|
|
3452
|
+
// 懒触发:收到任意消息时检查 pending,有则先拉取名录再继续处理消息
|
|
3453
|
+
void this.processPendingDirectoryUpdate();
|
|
3419
3454
|
const authenticatedDelivery = event.chatType === 'group'
|
|
3420
3455
|
? { chatType: 'group', groupId: event.groupId ?? event.channelId }
|
|
3421
3456
|
: { chatType: 'private' };
|
|
@@ -4037,7 +4072,6 @@ export class AUNChannel {
|
|
|
4037
4072
|
return;
|
|
4038
4073
|
this.lastConnectionStateSignature = signature;
|
|
4039
4074
|
if (this.intentionalDisconnect && state === 'disconnected') {
|
|
4040
|
-
this.stopOwnerDirectoryRefresh();
|
|
4041
4075
|
this.connected = false;
|
|
4042
4076
|
this.connectedAt = 0;
|
|
4043
4077
|
return;
|
|
@@ -4053,7 +4087,7 @@ export class AUNChannel {
|
|
|
4053
4087
|
this.gatewayUrl = evtGateway;
|
|
4054
4088
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
4055
4089
|
this.trace('IN', source, data);
|
|
4056
|
-
logger.info(`${this.logPrefix()}
|
|
4090
|
+
logger.info(`${this.logPrefix()} connection.state: state=connected gateway=${this.gatewayUrl || 'unknown'}`);
|
|
4057
4091
|
this.reconcileConfiguredOwnerBinding();
|
|
4058
4092
|
this.startOwnerDirectoryRefresh();
|
|
4059
4093
|
// 不在这里清 flapCount —— 短命连接一上来就会触发本分支,
|
|
@@ -4061,9 +4095,9 @@ export class AUNChannel {
|
|
|
4061
4095
|
this.drainOutbox();
|
|
4062
4096
|
}
|
|
4063
4097
|
else if (state === 'disconnected' || state === 'reconnecting') {
|
|
4064
|
-
this.stopOwnerDirectoryRefresh();
|
|
4065
4098
|
const wasConnected = this.connected;
|
|
4066
4099
|
this.connected = false;
|
|
4100
|
+
this.stopOwnerDirectoryRefresh();
|
|
4067
4101
|
if (wasConnected)
|
|
4068
4102
|
this.configuredOwnerBindEpoch++;
|
|
4069
4103
|
this.clearQueuedObserverSends(state);
|
|
@@ -4098,7 +4132,7 @@ export class AUNChannel {
|
|
|
4098
4132
|
}
|
|
4099
4133
|
if (state === 'disconnected') {
|
|
4100
4134
|
this.trace('IN', source, data);
|
|
4101
|
-
logger.warn(`${this.logPrefix()}
|
|
4135
|
+
logger.warn(`${this.logPrefix()} connection.state: state=disconnected error=${data.error ?? 'unknown'}`);
|
|
4102
4136
|
}
|
|
4103
4137
|
else {
|
|
4104
4138
|
// reconnecting:节流日志(SDK 自己已经在跑指数退避,不刷屏)
|
|
@@ -4110,7 +4144,7 @@ export class AUNChannel {
|
|
|
4110
4144
|
if (isFirst || isStep || isInterval) {
|
|
4111
4145
|
const suppressed = attempt - this.lastReconnectLogAttempt - 1;
|
|
4112
4146
|
const suffix = suppressed > 0 ? `, ${suppressed} suppressed since last log` : '';
|
|
4113
|
-
logger.info(`${this.logPrefix()}
|
|
4147
|
+
logger.info(`${this.logPrefix()} connection.state: state=reconnecting attempt=${attempt}${suffix}`);
|
|
4114
4148
|
this.lastReconnectLogTime = now;
|
|
4115
4149
|
this.lastReconnectLogAttempt = attempt;
|
|
4116
4150
|
this.trace('IN', source, data);
|
|
@@ -4321,7 +4355,6 @@ export class AUNChannel {
|
|
|
4321
4355
|
this.reconnectTimer = null;
|
|
4322
4356
|
}
|
|
4323
4357
|
// Force close SDK client,中断它内部的重连循环
|
|
4324
|
-
this.stopOwnerDirectoryRefresh();
|
|
4325
4358
|
if (this.client) {
|
|
4326
4359
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
4327
4360
|
this.trace('OUT', 'client.close', { reason: `takeover_${reason}` });
|
|
@@ -4331,22 +4364,22 @@ export class AUNChannel {
|
|
|
4331
4364
|
this.connected = false;
|
|
4332
4365
|
this.clearQueuedObserverSends(`takeover_${reason}`);
|
|
4333
4366
|
const delaySec = Math.round(delayMs / 1000);
|
|
4334
|
-
logger.
|
|
4367
|
+
logger.debug(`${this.logPrefix()} Scheduling TS-layer reconnect (${reason}) in ${delaySec}s`);
|
|
4335
4368
|
this.trace('OUT', 'reconnect.scheduled', { reason, delayMs, generation: gen });
|
|
4336
4369
|
this.reconnectTimer = setTimeout(async () => {
|
|
4337
4370
|
this.reconnectTimer = null;
|
|
4338
4371
|
// 如果在等待期间又触发了新的 takeoverReconnect,本次作废
|
|
4339
4372
|
if (gen !== this.reconnectGeneration) {
|
|
4340
|
-
logger.
|
|
4373
|
+
logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) cancelled: generation stale (${gen} vs ${this.reconnectGeneration})`);
|
|
4341
4374
|
return;
|
|
4342
4375
|
}
|
|
4343
4376
|
try {
|
|
4344
|
-
logger.
|
|
4377
|
+
logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) starting...`);
|
|
4345
4378
|
this.trace('OUT', 'reconnect.start', { reason, generation: gen });
|
|
4346
4379
|
await this.initClient();
|
|
4347
4380
|
// initClient 完成后再次校验 generation,防止 initClient 期间被新的 takeover 取代
|
|
4348
4381
|
if (gen !== this.reconnectGeneration) {
|
|
4349
|
-
logger.
|
|
4382
|
+
logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded but generation stale, closing stale client`);
|
|
4350
4383
|
this.stopOwnerDirectoryRefresh();
|
|
4351
4384
|
if (this.client) {
|
|
4352
4385
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
@@ -4357,7 +4390,7 @@ export class AUNChannel {
|
|
|
4357
4390
|
return;
|
|
4358
4391
|
}
|
|
4359
4392
|
this.trace('OUT', 'reconnect.ok', { reason, generation: gen });
|
|
4360
|
-
logger.
|
|
4393
|
+
logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded`);
|
|
4361
4394
|
}
|
|
4362
4395
|
catch (err) {
|
|
4363
4396
|
this.trace('OUT', 'reconnect.error', { reason, error: String(err), generation: gen });
|
|
@@ -6931,8 +6964,8 @@ export class AUNChannel {
|
|
|
6931
6964
|
await this.sendStructuredOrThrow(channelId, payloadObj, context);
|
|
6932
6965
|
}
|
|
6933
6966
|
async disconnect() {
|
|
6934
|
-
this.configuredOwnerBindEpoch++;
|
|
6935
6967
|
this.stopOwnerDirectoryRefresh();
|
|
6968
|
+
this.configuredOwnerBindEpoch++;
|
|
6936
6969
|
if (this.client)
|
|
6937
6970
|
ownerResolver.detachClient(this.config.aid, this.client);
|
|
6938
6971
|
this.managedMenuClient.close();
|