evolcore 0.0.46 → 0.0.48

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.
Files changed (237) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +43 -18
  8. package/dist/agents/codex/app-server-client.js +32 -23
  9. package/dist/agents/codex-runner.js +31 -16
  10. package/dist/agents/ecagent-runner.js +7 -4
  11. package/dist/agents/gemini-runner.js +5 -2
  12. package/dist/agents/runner-types.js +5 -21
  13. package/dist/aun/aid/agentmd.js +5 -1
  14. package/dist/aun/group/fs-download.js +1 -1
  15. package/dist/aun/service-proxy.js +4 -2
  16. package/dist/build-identity.json +1 -0
  17. package/dist/channels/aun.js +100 -32
  18. package/dist/channels/daemon.js +10 -26
  19. package/dist/cli/aun-commands.js +86 -51
  20. package/dist/cli/code-stats.js +19 -8
  21. package/dist/cli/command-log.js +1 -1
  22. package/dist/cli/daemon-commands.js +65 -76
  23. package/dist/cli/daemon-lifecycle-client.js +17 -3
  24. package/dist/cli/directory.js +7 -1
  25. package/dist/cli/ecmsg-gateway.js +5 -2
  26. package/dist/cli/index.js +2 -8
  27. package/dist/cli/init-channel.js +6 -8
  28. package/dist/cli/init.js +74 -46
  29. package/dist/cli/invoke-command.js +1 -1
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/restart-monitor.js +104 -28
  32. package/dist/cli/role.js +61 -17
  33. package/dist/cli/stats.js +3 -3
  34. package/dist/cli/task-context.js +83 -15
  35. package/dist/cli/thread-command.js +16 -51
  36. package/dist/cli/upgrade-command.js +4 -2
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-manager.js +31 -23
  40. package/dist/config/daemon-services.js +30 -3
  41. package/dist/config/gateway-config.js +2 -2
  42. package/dist/config/invoke-ipc-service.js +6 -4
  43. package/dist/config/peer-bind-code.js +3 -4
  44. package/dist/config/peer-book-store.js +59 -218
  45. package/dist/config/peer-book.js +26 -27
  46. package/dist/config/peer-role-resolver.js +16 -1
  47. package/dist/config/provider-identity-migration.js +161 -6
  48. package/dist/config/provider-ipc-service.js +56 -11
  49. package/dist/config/provider-menu-request.js +24 -5
  50. package/dist/config/provider-templates.js +127 -0
  51. package/dist/config/providers-config.js +59 -8
  52. package/dist/config/providers-management.js +467 -49
  53. package/dist/config/role-command-service.js +248 -1
  54. package/dist/config/schema-migration.js +228 -20
  55. package/dist/config/schema-registry.js +6 -2
  56. package/dist/core/agent-application-service.js +6 -1
  57. package/dist/core/agent-runtime.js +10 -5
  58. package/dist/core/auth/agent-delegation.js +10 -4
  59. package/dist/core/auth/auth-gateway.js +2 -1
  60. package/dist/core/auth/delegation-authorization.js +3 -0
  61. package/dist/core/auth/delegation-diagnostics.js +56 -15
  62. package/dist/core/auth/operation-authorizer.js +26 -1
  63. package/dist/core/auth/operation-catalog.js +28 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/command-handler.js +81 -85
  68. package/dist/core/command/menu-catalog.js +1 -0
  69. package/dist/core/command/menu-handler.js +65 -153
  70. package/dist/core/command/menu-protocol.js +7 -1
  71. package/dist/core/command/provider-menu.js +13 -3
  72. package/dist/core/command/role-menu.js +47 -23
  73. package/dist/core/command/slash-handler.js +30 -49
  74. package/dist/core/command/team-workspace-items.js +81 -12
  75. package/dist/core/command/team-workspace-team.js +9 -71
  76. package/dist/core/command/topic-slash.js +9 -30
  77. package/dist/core/daemon-bootstrap.js +19 -10
  78. package/dist/core/daemon-control.js +8 -10
  79. package/dist/core/daemon-lifecycle.js +50 -40
  80. package/dist/core/evolagent-registry.js +22 -3
  81. package/dist/core/file-integrity/store.js +2 -0
  82. package/dist/core/handoff/runtime.js +37 -1
  83. package/dist/core/host-snapshot.js +9 -4
  84. package/dist/core/inference/text-inference.js +3 -1
  85. package/dist/core/initialization/service.js +31 -8
  86. package/dist/core/interaction-router.js +3 -0
  87. package/dist/core/invoke/executors/text.js +72 -19
  88. package/dist/core/ipc-registration.js +6 -4
  89. package/dist/core/memory/consolidation.js +6 -6
  90. package/dist/core/message/aun-ipc-sender.js +165 -55
  91. package/dist/core/message/im-renderer.js +1 -1
  92. package/dist/core/message/message-bridge.js +51 -334
  93. package/dist/core/message/message-log.js +5 -0
  94. package/dist/core/message/message-queue.js +22 -0
  95. package/dist/core/message/message-utils.js +8 -0
  96. package/dist/core/message/response-engine.js +429 -116
  97. package/dist/core/message/send-routing.js +5 -1
  98. package/dist/core/model/catalog-service.js +31 -11
  99. package/dist/core/model/model-capabilities.js +22 -4
  100. package/dist/core/model/model-catalog.js +1 -0
  101. package/dist/core/ownership/owner-resolver.js +355 -60
  102. package/dist/core/permission/protected-paths.js +6 -6
  103. package/dist/core/relation/peer-identity.js +28 -2
  104. package/dist/core/relation/same-owner-proof.js +81 -111
  105. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  106. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  107. package/dist/core/session/session-file-health.js +49 -14
  108. package/dist/core/session/session-fs-store.js +91 -35
  109. package/dist/core/session/session-manager.js +68 -24
  110. package/dist/core/session/session-mapper.js +14 -34
  111. package/dist/core/session/session-transcript.js +5 -1
  112. package/dist/core/task/task-activity-store.js +84 -0
  113. package/dist/core/task/task-image-resources.js +1 -1
  114. package/dist/core/task/task-recovery-service.js +12 -0
  115. package/dist/core/thread/command-parser.js +7 -12
  116. package/dist/core/thread/thread-context-storage.js +3 -2
  117. package/dist/core/thread/thread-operation.js +2 -13
  118. package/dist/core/thread/thread-service.js +15 -46
  119. package/dist/directory/owner-directory-admission.js +1 -1
  120. package/dist/directory/owner-directory-cache.js +45 -28
  121. package/dist/directory/owner-directory-markdown.js +13 -1
  122. package/dist/directory/owner-directory-query-operation.js +29 -3
  123. package/dist/directory/owner-directory-remarks.js +11 -3
  124. package/dist/eck/message-renderer.js +84 -24
  125. package/dist/ecweb/basic-settings-service.js +3 -1
  126. package/dist/ecweb/message-context-service.js +1 -1
  127. package/dist/ecweb/pairing.js +4 -3
  128. package/dist/ecweb/providers-service.js +26 -1
  129. package/dist/ecweb/runtime/lifecycle.js +82 -23
  130. package/dist/ecweb/runtime/proxy-access.js +74 -0
  131. package/dist/ecweb/runtime/supervisor.js +6 -17
  132. package/dist/event-center/registry.js +13 -2
  133. package/dist/event-center/runtime.js +103 -11
  134. package/dist/event-center/script-runner.js +5 -5
  135. package/dist/index.js +129 -93
  136. package/dist/ipc.js +15 -3
  137. package/dist/outputs/events.js +62 -0
  138. package/dist/outputs/protocol.js +102 -0
  139. package/dist/outputs/service.js +279 -0
  140. package/dist/paths.js +3 -0
  141. package/dist/proxy/manager.js +43 -13
  142. package/dist/services/index.js +89 -4
  143. package/dist/services/ipc-operation.js +4 -15
  144. package/dist/services/pack-manager.js +12 -1
  145. package/dist/services/router.js +21 -6
  146. package/dist/services/script-runner.js +5 -4
  147. package/dist/services/validation.js +1 -1
  148. package/dist/stats/budget.js +1 -1
  149. package/dist/stats/db.js +19 -0
  150. package/dist/stats/index.js +1 -1
  151. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  152. package/dist/stats/normalizer.js +2 -0
  153. package/dist/stats/query.js +35 -27
  154. package/dist/stats/role-budget.js +5 -2
  155. package/dist/stats/writer.js +10 -6
  156. package/dist/trigger/audit.js +7 -0
  157. package/dist/trigger/authorization.js +105 -11
  158. package/dist/trigger/feedback.js +10 -0
  159. package/dist/trigger/history.js +37 -11
  160. package/dist/trigger/ipc-service.js +12 -1
  161. package/dist/trigger/manager.js +1 -0
  162. package/dist/trigger/scheduler.js +11 -5
  163. package/dist/trigger/script-executor.js +2 -1
  164. package/dist/trigger/script-sandbox.js +9 -3
  165. package/dist/trigger/state.js +7 -0
  166. package/dist/trigger/validation.js +22 -0
  167. package/dist/utils/aid-bind.js +155 -18
  168. package/dist/utils/atomic-write.js +3 -3
  169. package/dist/utils/cross-platform.js +97 -31
  170. package/dist/utils/error-dict.json +94 -4
  171. package/dist/utils/error-utils.js +40 -4
  172. package/dist/utils/evolcore-version.js +36 -65
  173. package/dist/utils/instance-registry.js +61 -0
  174. package/dist/utils/msg-diag.js +1 -0
  175. package/dist/utils/process-introspect.js +158 -8
  176. package/dist/utils/process-tree.js +50 -2
  177. package/dist/utils/upgrade-jobs.js +4 -4
  178. package/dist/utils/windows-shell-trust.js +2 -0
  179. package/dist/workbench/protocol.js +80 -0
  180. package/dist/workbench/service.js +359 -0
  181. package/ecagent/dist/types.d.ts +6 -2
  182. package/kits/docs/context-assembly.md +1 -1
  183. package/kits/docs/evolcore/INDEX.md +2 -2
  184. package/kits/docs/evolcore/aid.md +3 -1
  185. package/kits/docs/evolcore/config.md +12 -0
  186. package/kits/docs/evolcore/directory.md +22 -3
  187. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  188. package/kits/docs/evolcore/model.md +10 -0
  189. package/kits/docs/evolcore/peer.md +19 -65
  190. package/kits/docs/evolcore/provider.md +133 -5
  191. package/kits/docs/evolcore/role.md +80 -0
  192. package/kits/docs/evolcore/services.md +6 -6
  193. package/kits/docs/evolcore/team-workspace.md +1 -1
  194. package/kits/docs/evolcore/thread-chain.md +14 -15
  195. package/kits/docs/evolcore/tool-authorization.md +5 -0
  196. package/kits/docs/evolcore/trigger.md +10 -0
  197. package/kits/eck_message_manifest.json +12 -0
  198. package/kits/provider-templates.json +1213 -0
  199. package/kits/rules/04-relation.md +3 -3
  200. package/kits/schemas/_meta.json +14 -2
  201. package/kits/schemas/contact-book.schema.4.json +52 -0
  202. package/kits/schemas/providers.schema.3.json +200 -0
  203. package/kits/skills/.switches.json +4 -0
  204. package/kits/skills/ability/references/calling.md +1 -1
  205. package/kits/skills/ec-group/SKILL.md +2 -2
  206. package/kits/skills/ec-identity/SKILL.md +19 -72
  207. package/kits/skills/ec-provider/SKILL.md +221 -0
  208. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  209. package/kits/skills/ec-trigger/SKILL.md +1 -1
  210. package/kits/skills/thread-ops/SKILL.md +34 -21
  211. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  212. package/kits/templates/message-fragments/group-batch.md +1 -1
  213. package/kits/templates/message-fragments/inject-default.md +1 -1
  214. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  215. package/kits/templates/message-fragments/item-group.md +1 -1
  216. package/kits/templates/message-fragments/item-private.md +1 -1
  217. package/kits/templates/message-fragments/thread-context.md +1 -1
  218. package/kits/templates/message-fragments/trigger-session.md +1 -1
  219. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  220. package/kits/templates/roles/admin.json +2 -19
  221. package/kits/templates/roles/member.json +0 -3
  222. package/kits/templates/system-fragments/baseagent.md +6 -0
  223. package/kits/templates/system-fragments/commands.md +3 -3
  224. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  225. package/kits/templates/system-fragments/relation.md +1 -1
  226. package/kits/templates/system-fragments/thread.md +6 -5
  227. package/package.json +6 -4
  228. package/scripts/agent-template/inspect.mjs +4 -1
  229. package/scripts/agent-template/shared/common.mjs +2 -3
  230. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  231. package/scripts/agent-template/shared/template-package.mjs +9 -2
  232. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  233. package/scripts/agent-template/team-pack.mjs +6 -3
  234. package/dist/cli/peer.js +0 -127
  235. package/dist/config/peer-operation-service.js +0 -132
  236. package/dist/config/peer-request-service.js +0 -532
  237. package/dist/core/command/connect-menu.js +0 -624
@@ -2,13 +2,14 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { isValidAid } from '../aun/aid/validation.js';
5
- import { agentConfig, agentPeerAuditPath, agentPeerConfig, agentDir, agentRelationConfig, agentRelationsDir, resolvePaths } from '../paths.js';
5
+ import { agentConfig, agentPeerAuditPath, agentPeerConfig, agentDir, agentRelationConfig, resolvePaths } from '../paths.js';
6
6
  import { atomicReadJson, atomicWrite, atomicWriteJson } from '../utils/atomic-write.js';
7
7
  import { fileCache } from '../core/daemon-file-cache.js';
8
8
  import { unregisterFile } from '../core/file-integrity/store.js';
9
9
  import { ensureManagedLockParent, resolveManagedLockPath } from '../core/runtime-lock.js';
10
- import { formatPeerKey, parsePeerKey, readAunPeerKind, recordAunPeerRoute } from '../core/relation/peer-identity.js';
10
+ import { formatPeerKey, readAunPeerKind } from '../core/relation/peer-identity.js';
11
11
  import { ConfigTarget, notifyConfigWrite, validateConfig } from './config-manager.js';
12
+ import { isPeerBindingEligible } from './peer-book.js';
12
13
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
13
14
  import { parseContactAlias } from './peer-alias.js';
14
15
  import { clearRoleStoreCache } from './role-store.js';
@@ -68,6 +69,39 @@ export function mutatePeerBookTransaction(request, changes) {
68
69
  export function mutatePeerBookTransactionSync(request, changes) {
69
70
  return mutateContactBookSyncInternal(request, changes);
70
71
  }
72
+ /** Commit configuration without reading or creating the optional peer state. */
73
+ export function commitAgentConfigTransactionSync(selfAid, changes) {
74
+ const aid = normalizeAid(selfAid, 'self AID');
75
+ const release = acquireAgentLock(aid);
76
+ try {
77
+ recoverMutation(aid);
78
+ validateTransactionChanges(aid, changes);
79
+ if (!changes.length)
80
+ return;
81
+ writeJournal(aid, { schemaVersion: 1, state: 'prepared', selfAid: aid, changes });
82
+ try {
83
+ for (const change of changes)
84
+ applyTransactionChange(change);
85
+ writeJournal(aid, { schemaVersion: 1, state: 'committed', selfAid: aid, changes });
86
+ removeJournal(aid);
87
+ }
88
+ catch (error) {
89
+ try {
90
+ recoverMutation(aid);
91
+ }
92
+ catch (recovery) {
93
+ throw new AggregateError([error, recovery], 'Configuration write and recovery failed');
94
+ }
95
+ throw error;
96
+ }
97
+ for (const change of changes)
98
+ fileCache.invalidate(change.file);
99
+ clearRoleStoreCache(aid);
100
+ }
101
+ finally {
102
+ release();
103
+ }
104
+ }
71
105
  function enqueueContactMutation(request, changes) {
72
106
  const selfAid = normalizeAid(request.selfAid, 'self AID');
73
107
  const previous = mutationTails.get(selfAid) ?? Promise.resolve();
@@ -87,98 +121,11 @@ function enqueueContactMutation(request, changes) {
87
121
  export function mutatePeerBookSync(request) {
88
122
  return mutateContactBookSyncInternal(request, []);
89
123
  }
90
- export function synchronizeManagementPeersSync(selfAid) {
91
- return mutatePeerBookSync({
92
- selfAid,
93
- actor: 'management-role-sync',
94
- mutation: { type: 'sync-management-roles' },
95
- });
96
- }
97
- /** Synchronize contacts using current verified ownership, never a requested binding target. */
98
- export function synchronizeOwnershipPeersSync(subjectAid) {
99
- synchronizeManagementPeersSync(subjectAid);
100
- const ownerAid = ownerResolver.owner(subjectAid);
101
- if (!ownerAid || !fs.existsSync(agentConfig(subjectAid)) || !fs.existsSync(agentConfig(ownerAid)))
102
- return;
103
- // The registered local Agent establishes the type; ownership only selects its Owner's Contact Book.
104
- const kind = recordAunPeerRoute(ownerAid, subjectAid, 'private');
105
- if (kind.kind !== 'private') {
106
- throw new PeerMutationError('CONTACT_TYPE_UNKNOWN', `Managed Agent type conflicts with Owner relation: ${subjectAid}`);
107
- }
108
- // Add the subject to its local Owner's contacts, preserving existing admission decisions.
109
- mutatePeerBookSync({
110
- selfAid: ownerAid,
111
- actor: 'ownership-contact-sync',
112
- mutation: { type: 'ensure-contacts', primaryIds: [subjectAid] },
113
- });
114
- }
115
124
  /** Read pending relation changes together with verified identity evidence. */
116
125
  export function resolvePeerAidKind(selfAid, aid, changes = []) {
117
126
  const relation = readTransactionJson(agentRelationConfig(selfAid, formatPeerKey('aun', aid)), changes);
118
127
  return readAunPeerKind(selfAid, aid, { relation });
119
128
  }
120
- function managementRoleMapForAgent(selfAid, changes) {
121
- const roles = {};
122
- for (const owner of ownerResolver.protocolOwners(selfAid)) {
123
- if (isValidAid(owner))
124
- roles[owner] = 'owner';
125
- }
126
- const relationsRoot = agentRelationsDir(selfAid);
127
- let entries = [];
128
- try {
129
- entries = fs.readdirSync(relationsRoot, { withFileTypes: true });
130
- }
131
- catch (error) {
132
- if (error.code !== 'ENOENT')
133
- throw error;
134
- }
135
- const peerKeys = new Set(entries.filter(entry => entry.isDirectory()).map(entry => entry.name));
136
- for (const change of changes) {
137
- const parts = path.relative(relationsRoot, change.file).split(path.sep);
138
- if (parts.length === 2 && parts[1] === 'config.json')
139
- peerKeys.add(parts[0]);
140
- }
141
- for (const peerKey of peerKeys) {
142
- if (peerKey.startsWith('_'))
143
- continue;
144
- let parsed;
145
- try {
146
- parsed = parsePeerKey(peerKey);
147
- }
148
- catch {
149
- continue;
150
- }
151
- if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId))
152
- continue;
153
- const config = readTransactionJson(path.join(relationsRoot, peerKey, 'config.json'), changes);
154
- if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind !== 'private')
155
- continue;
156
- if (config?.targetKind !== 'group' && config?.role === 'admin' && roles[parsed.channelId] !== 'owner') {
157
- roles[parsed.channelId] = 'admin';
158
- }
159
- }
160
- return roles;
161
- }
162
- export function synchronizeAllManagementPeersSync() {
163
- const agentsRoot = resolvePaths().agentsDir;
164
- let entries = [];
165
- try {
166
- entries = fs.readdirSync(agentsRoot, { withFileTypes: true });
167
- }
168
- catch (error) {
169
- if (error.code === 'ENOENT')
170
- return 0;
171
- throw error;
172
- }
173
- let changed = 0;
174
- for (const entry of entries) {
175
- if (!entry.isDirectory() || !isValidAid(entry.name) || !fs.existsSync(agentConfig(entry.name)))
176
- continue;
177
- if (synchronizeManagementPeersSync(entry.name).changed)
178
- changed += 1;
179
- }
180
- return changed;
181
- }
182
129
  /** Recover every interrupted Contact transaction before startup reads config. */
183
130
  export function recoverAllPeerBookMutationsSync() {
184
131
  const agentsRoot = resolvePaths().agentsDir;
@@ -228,19 +175,9 @@ function mutateContactBookLocked(request, transactionChanges) {
228
175
  validateTransactionChanges(selfAid, transactionChanges);
229
176
  const next = cloneBook(current);
230
177
  applyMutation(next, request.mutation, selfAid, transactionChanges);
231
- synchronizeManagementRoles(next, selfAid, transactionChanges);
232
- if (request.mutation.type === 'replace') {
233
- const errors = validateConfig(ConfigTarget.Peer, next);
234
- if (errors.length)
235
- throw new PeerMutationError('INVALID_CONTACT_BOOK', errors.join('; '));
236
- }
237
- else {
238
- validateContactBook(next, selfAid, transactionChanges);
239
- }
240
- const omitEmptySync = request.mutation.type === 'sync-management-roles'
241
- && current === null
242
- && Object.keys(next.contacts).length === 0;
243
- const nextRevision = omitEmptySync ? previousRevision : peerRevision(next);
178
+ validateContactBook(next, selfAid, transactionChanges);
179
+ const nextRevision = current === null && Object.keys(next.contacts).length === 0
180
+ ? previousRevision : peerRevision(next);
244
181
  if (nextRevision === previousRevision && transactionChanges.length === 0) {
245
182
  return { changed: false, peerRevision: previousRevision, previousContactRevision: previousRevision, contact: next };
246
183
  }
@@ -286,9 +223,9 @@ function mutateContactBookPreparedLocked(selfAid, prepare) {
286
223
  const prepared = prepare({ contact: next, peerRevision: previousRevision });
287
224
  if (prepared.mutation)
288
225
  applyMutation(next, prepared.mutation, selfAid);
289
- synchronizeManagementRoles(next, selfAid, []);
290
226
  validateContactBook(next, selfAid);
291
- const nextRevision = peerRevision(next);
227
+ const nextRevision = current === null && Object.keys(next.contacts).length === 0
228
+ ? previousRevision : peerRevision(next);
292
229
  if (nextRevision === previousRevision) {
293
230
  return {
294
231
  changed: false,
@@ -349,95 +286,25 @@ function applyMutation(book, mutation, selfAid, changes = []) {
349
286
  applyMutation(book, item, selfAid, changes);
350
287
  return;
351
288
  }
352
- if (mutation.type === 'ensure-contacts') {
353
- for (const rawPrimaryId of mutation.primaryIds) {
354
- const primaryId = normalizeContactAid(rawPrimaryId, selfAid, changes);
355
- if (!contacts[primaryId])
356
- contacts[primaryId] = {};
357
- }
358
- return;
359
- }
360
- if (mutation.type === 'sync-management-roles') {
361
- return;
362
- }
363
- const rawPrimaryId = String(mutation.primaryId || '').trim();
364
- if (isOwner(selfAid, rawPrimaryId)) {
365
- if (mutation.type === 'set-status' && mutation.status !== 'active') {
366
- throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner must remain active');
367
- }
368
- if (mutation.type === 'set-request') {
369
- throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner cannot submit a contact request');
370
- }
371
- }
372
- const prior = contacts[rawPrimaryId];
373
- const preservesAdmission = !!prior && (mutation.type === 'set-display-name' || mutation.type === 'unbind-alias'
374
- || mutation.type === 'expire-request'
375
- || (mutation.type === 'review-request' && mutation.decision !== 'approve')
376
- || (mutation.type === 'set-status' && mutation.status !== 'active'));
377
- const primaryId = normalizeContactAid(mutation.primaryId, selfAid, changes, preservesAdmission);
289
+ const primaryId = normalizeAid(mutation.primaryId, 'peer AID');
378
290
  const existing = contacts[primaryId];
379
291
  if (mutation.type === 'set-status') {
380
- contacts[primaryId] = compactEntry({
381
- ...existing,
382
- status: mutation.status === 'active' ? undefined : mutation.status,
383
- pendingRequest: undefined,
384
- declinedAt: mutation.status === 'declined' ? existing?.declinedAt ?? new Date().toISOString() : undefined,
385
- });
386
- return;
387
- }
388
- if (mutation.type === 'set-request') {
389
- contacts[primaryId] = compactEntry({
390
- ...existing,
391
- status: 'pending',
392
- pendingRequest: { ...mutation.request },
393
- declinedAt: undefined,
394
- });
395
- return;
396
- }
397
- if (mutation.type === 'review-request') {
398
- if (!existing || existing.status !== 'pending' || existing.pendingRequest?.id !== mutation.requestId) {
399
- throw new PeerMutationError('REQUEST_STALE', 'The contact request has changed or was already handled');
292
+ if (mutation.status === 'blocked' && isOwner(selfAid, primaryId)) {
293
+ throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner cannot be blocked');
400
294
  }
401
- if (Date.parse(existing.pendingRequest.expiresAt) <= Date.parse(mutation.now)) {
402
- throw new PeerMutationError('REQUEST_EXPIRED', 'The contact request has expired');
403
- }
404
- if (mutation.decision === 'reject') {
405
- delete contacts[primaryId];
406
- }
407
- else {
408
- contacts[primaryId] = compactEntry({
409
- ...existing,
410
- status: mutation.decision === 'block' ? 'blocked' : undefined,
411
- pendingRequest: undefined,
412
- declinedAt: undefined,
413
- });
295
+ if (mutation.status === 'blocked')
296
+ contacts[primaryId] = { ...existing, status: 'blocked' };
297
+ else if (existing) {
298
+ delete existing.status;
299
+ if (!existing.aliases?.length)
300
+ delete contacts[primaryId];
414
301
  }
415
302
  return;
416
303
  }
417
- if (mutation.type === 'expire-request') {
418
- if (!existing || existing.status !== 'pending' || existing.pendingRequest?.id !== mutation.requestId)
419
- return;
420
- if (Date.parse(existing.pendingRequest.expiresAt) > Date.parse(mutation.now))
421
- return;
422
- contacts[primaryId] = compactEntry({
423
- ...existing,
424
- status: 'declined',
425
- pendingRequest: undefined,
426
- declinedAt: existing.pendingRequest.expiresAt,
427
- });
428
- return;
429
- }
430
- if (mutation.type === 'set-display-name') {
431
- contacts[primaryId] = compactEntry({ ...existing, displayName: mutation.displayName ?? undefined });
432
- return;
433
- }
434
304
  if (mutation.type === 'bind-alias' || mutation.type === 'bind-alias-eligible') {
435
- if (mutation.type === 'bind-alias-eligible') {
436
- const eligible = isOwner(selfAid, primaryId)
437
- || (!!existing && (existing.status === undefined || existing.status === 'active'));
438
- if (!eligible) {
439
- throw new PeerMutationError('CONTACT_NOT_ACTIVE', 'Only an active contact or Agent owner can bind an alias');
440
- }
305
+ normalizeContactAid(primaryId, selfAid, changes);
306
+ if (!isPeerBindingEligible(selfAid, primaryId)) {
307
+ throw new PeerMutationError('CONTACT_NOT_ALLOWED', 'Channel binding requires an admitted private principal');
441
308
  }
442
309
  for (const [owner, entry] of Object.entries(contacts)) {
443
310
  if (owner !== primaryId && entry.aliases?.includes(mutation.alias)) {
@@ -456,19 +323,6 @@ function applyMutation(book, mutation, selfAid, changes = []) {
456
323
  }
457
324
  throw new PeerMutationError('INVALID_MUTATION', `Unsupported Contact Book mutation: ${String(mutation?.type)}`);
458
325
  }
459
- function synchronizeManagementRoles(book, selfAid, changes) {
460
- const roles = managementRoleMapForAgent(selfAid, changes);
461
- for (const [primaryId, entry] of Object.entries(book.contacts)) {
462
- book.contacts[primaryId] = compactEntry({
463
- ...entry,
464
- ...(roles[primaryId] === 'owner' ? { status: undefined, pendingRequest: undefined, declinedAt: undefined } : {}),
465
- managementRole: roles[primaryId],
466
- });
467
- }
468
- for (const [primaryId, managementRole] of Object.entries(roles)) {
469
- book.contacts[primaryId] = compactEntry({ ...book.contacts[primaryId], managementRole });
470
- }
471
- }
472
326
  function validateContactBook(book, selfAid, changes = []) {
473
327
  const schemaErrors = validateConfig(ConfigTarget.Peer, book);
474
328
  if (schemaErrors.length) {
@@ -488,22 +342,6 @@ function validateContactBook(book, selfAid, changes = []) {
488
342
  if (entry.status && isOwner(selfAid, primaryId)) {
489
343
  throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner must remain active');
490
344
  }
491
- if (entry.status === 'pending') {
492
- if (!entry.pendingRequest || !Number.isFinite(Date.parse(entry.pendingRequest.submittedAt))
493
- || !Number.isFinite(Date.parse(entry.pendingRequest.expiresAt))
494
- || Date.parse(entry.pendingRequest.expiresAt) <= Date.parse(entry.pendingRequest.submittedAt)) {
495
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `Invalid pending request for ${primaryId}`);
496
- }
497
- }
498
- else if (entry.pendingRequest) {
499
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `pendingRequest requires pending status for ${primaryId}`);
500
- }
501
- if (entry.status === 'declined' && !Number.isFinite(Date.parse(entry.declinedAt ?? ''))) {
502
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `declinedAt is required for ${primaryId}`);
503
- }
504
- if (entry.status !== 'declined' && entry.declinedAt) {
505
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `declinedAt requires declined status for ${primaryId}`);
506
- }
507
345
  for (const alias of entry.aliases ?? []) {
508
346
  const parsed = parseContactAlias(alias, selfAid);
509
347
  if (!parsed) {
@@ -536,7 +374,6 @@ function cloneBook(book) {
536
374
  contacts[primaryId] = {
537
375
  ...entry,
538
376
  ...(entry.aliases ? { aliases: [...entry.aliases] } : {}),
539
- ...(entry.pendingRequest ? { pendingRequest: { ...entry.pendingRequest } } : {}),
540
377
  };
541
378
  }
542
379
  return { $schema_version: currentVersion('contact-book'), contacts };
@@ -549,8 +386,12 @@ function removeAliasEverywhere(contacts, alias, onlyOwner) {
549
386
  if (onlyOwner && primaryId !== onlyOwner)
550
387
  continue;
551
388
  const aliases = (entry.aliases ?? []).filter(candidate => candidate !== alias);
552
- if (aliases.length !== (entry.aliases ?? []).length)
553
- contacts[primaryId] = compactEntry({ ...entry, aliases });
389
+ if (aliases.length !== (entry.aliases ?? []).length) {
390
+ if (!aliases.length && !entry.status)
391
+ delete contacts[primaryId];
392
+ else
393
+ contacts[primaryId] = compactEntry({ ...entry, aliases: aliases.length ? aliases : undefined });
394
+ }
554
395
  }
555
396
  }
556
397
  function readContactBookFromDisk(selfAid) {
@@ -1,10 +1,13 @@
1
- import { agentPeerConfig } from '../paths.js';
1
+ import path from 'node:path';
2
+ import { agentDir, agentPeerConfig } from '../paths.js';
2
3
  import { isValidAid } from '../aun/aid/validation.js';
3
4
  import { ConfigTarget, read, validateConfig } from './config-manager.js';
4
5
  import { PeerMutationError, peerRevision, resolvePeerAidKind, mutatePeerBookSync } from './peer-book-store.js';
5
6
  import { formatContactAlias, normalizeContactChannelKey, parseContactAlias, } from './peer-alias.js';
6
- import { getOwners } from '../core/ownership/owner-resolver.js';
7
- import { readAunPeerKind } from '../core/relation/peer-identity.js';
7
+ import { readOwnerDirectoryMembership } from '../directory/owner-directory-admission.js';
8
+ import { readRemark, splitAliases } from '../directory/owner-directory-remarks.js';
9
+ import { readAccessPolicy } from './access-policy.js';
10
+ import { ownerResolver } from '../core/ownership/owner-resolver.js';
8
11
  export class PeerBookError extends Error {
9
12
  code;
10
13
  constructor(code, message) {
@@ -71,9 +74,6 @@ export function bindPeerAlias(selfAid, primaryId, channelType, actorId, channelK
71
74
  if (!canonicalChannelKey || !actor) {
72
75
  throw new PeerBookError('INVALID_ALIAS', `Invalid contact alias: ${String(channelKey)}:${String(actorId)}`);
73
76
  }
74
- if (!getPeerSnapshot(selfAid).contacts.has(primary)) {
75
- throw new PeerBookError('NOT_FOUND', `Contact was not found: ${primary}`);
76
- }
77
77
  const alias = formatContactAlias(canonicalChannelKey, actor);
78
78
  try {
79
79
  return mutatePeerBookSync({
@@ -113,7 +113,7 @@ export function clearPeerBookCache() {
113
113
  snapshotByBook = new WeakMap();
114
114
  }
115
115
  export function getPeerSnapshot(selfAid) {
116
- const book = readPeerBook(selfAid, { cache: true }) ?? { $schema_version: 2, contacts: {} };
116
+ const book = readPeerBook(selfAid, { cache: true }) ?? { $schema_version: 4, contacts: {} };
117
117
  const cached = snapshotByBook.get(book);
118
118
  if (cached)
119
119
  return cached;
@@ -134,12 +134,9 @@ export function resolvePeerView(selfAid, primaryId) {
134
134
  const owner = listAgentOwners(selfAid).includes(id);
135
135
  const entry = getPeerSnapshot(selfAid).contacts.get(id);
136
136
  const status = owner ? 'active' : entry?.status ?? 'active';
137
- const managementRole = owner ? 'owner' : entry?.managementRole === 'admin' ? 'admin' : undefined;
138
137
  return {
139
138
  primaryId: id,
140
- ...(entry?.displayName ? { displayName: entry.displayName } : {}),
141
139
  aliases: entry?.aliases ?? [],
142
- ...(managementRole ? { managementRole } : {}),
143
140
  status,
144
141
  blocked: status === 'blocked',
145
142
  isOwner: owner,
@@ -149,21 +146,20 @@ export function resolvePeerView(selfAid, primaryId) {
149
146
  export function isBlockedPeer(selfAid, primaryId) {
150
147
  return resolvePeerView(selfAid, primaryId).blocked;
151
148
  }
152
- export function isAcceptedPeer(selfAid, primaryId, routeKind) {
153
- const id = String(primaryId || '').trim();
154
- const snapshot = getPeerSnapshot(selfAid);
155
- const entry = snapshot.contacts.get(id);
156
- return !!entry && (entry.status === undefined || entry.status === 'active')
157
- && readAunPeerKind(selfAid, id, { routeKind }).kind === 'private';
149
+ /** Identity binding does not grant admission or assign a role. */
150
+ export function isPeerBindingEligible(selfAid, primaryId) {
151
+ if (!isValidAid(primaryId))
152
+ return false;
153
+ if (ownerResolver.owner(selfAid) === primaryId)
154
+ return true;
155
+ if (getPeerSnapshot(selfAid).blockedIndex.has(primaryId))
156
+ return false;
157
+ const membership = readOwnerDirectoryMembership(selfAid, primaryId, true);
158
+ return !!membership && membership.category !== 'unavailable' && !!membership.entry
159
+ && !membership.blocked && !membership.scopeExcluded
160
+ && !readAccessPolicy(selfAid).deniedAids?.includes(primaryId);
158
161
  }
159
- /**
160
- * 对端展示名:联系人簿 displayName → principalId。仅用于展示(预览行/日志),
161
- * 关系键始终用原生 peerId,不受此影响。
162
- *
163
- * 非 AUN 渠道的 actorId 是渠道原生 ID(飞书 open_id 等),直接展示不可读;
164
- * 联系人簿已把它 alias 到主体 AID 上,取其 displayName 即可。
165
- * 未绑定/联系人簿损坏时返回 undefined,由调用方按自己的兜底链继续。
166
- */
162
+ /** Resolve names from the Owner directory and local remarks. */
167
163
  export function resolvePeerDisplayLabel(selfAid, channelType, actorId, channelKey) {
168
164
  const actor = String(actorId || '').trim();
169
165
  if (!String(selfAid || '').trim() || !actor)
@@ -172,7 +168,11 @@ export function resolvePeerDisplayLabel(selfAid, channelType, actorId, channelKe
172
168
  const { principalId } = resolvePrincipal(selfAid, channelType, actor, channelKey);
173
169
  if (!principalId)
174
170
  return undefined;
175
- return resolvePeerView(selfAid, principalId).displayName || principalId;
171
+ const remark = readRemark(path.join(agentDir(selfAid), 'directory'), principalId);
172
+ if (remark?.remark)
173
+ return splitAliases(remark.remark)[0] ?? principalId;
174
+ const membership = readOwnerDirectoryMembership(selfAid, principalId);
175
+ return membership?.entry?.name || principalId;
176
176
  }
177
177
  catch {
178
178
  // 联系人簿损坏(校验失败/alias 冲突)不应影响消息处理
@@ -259,6 +259,5 @@ function normalizePrimaryId(value, selfAid, allowMissing = false) {
259
259
  return id;
260
260
  }
261
261
  function listAgentOwners(selfAid) {
262
- // Keep configured Owners usable while protocol consensus is unavailable.
263
- return getOwners(selfAid);
262
+ return ownerResolver.protocolOwners(selfAid);
264
263
  }
@@ -13,7 +13,7 @@ import { configuredOwnerList } from './owner-config.js';
13
13
  import { tryParseChannelKey } from '../core/channel-loader.js';
14
14
  import { isValidAid } from '../aun/aid/validation.js';
15
15
  import { getOwners, ownerResolver } from '../core/ownership/owner-resolver.js';
16
- import { sameOwnerQualification, sameOwnerRevision, requiresSameOwnerProof } from '../core/relation/same-owner-proof.js';
16
+ import { prepareSameOwnerProof, sameOwnerQualification, sameOwnerRevision, requiresSameOwnerProof } from '../core/relation/same-owner-proof.js';
17
17
  import { readRoleStore } from './role-store.js';
18
18
  import { isOwnerDirectoryContact } from '../directory/owner-directory-admission.js';
19
19
  export function isAuthenticated(userId) {
@@ -89,6 +89,21 @@ export function addStaticAgentOwner(aid, ownerAid) {
89
89
  export function hasStaticAgentOwner(aid) {
90
90
  return listStaticAgentOwners(aid).length > 0;
91
91
  }
92
+ /** Refresh the source principal's proof before resolving an unattended or delayed authorization. */
93
+ export async function resolveFreshPeerRoleDetail(ctx) {
94
+ const proof = ctx.channelType.trim().toLowerCase() === 'aun' && ctx.chatType === 'private'
95
+ ? await prepareSameOwnerProof(ctx.selfAid, ctx.actorId)
96
+ : undefined;
97
+ const detail = resolvePeerRoleDetail(ctx);
98
+ if (!detail.effectiveRole && proof?.qualification === 'unavailable'
99
+ && requiresSameOwnerProof(ctx.selfAid, ctx.actorId)) {
100
+ detail.authorizationFailure = {
101
+ retryable: proof.retryable === true,
102
+ reason: proof.reason ?? 'Same-Owner authorization evidence is unavailable',
103
+ };
104
+ }
105
+ return detail;
106
+ }
92
107
  export function resolvePeerRoleDetail(ctx) {
93
108
  const operatorId = String(ctx.actorId || '').trim();
94
109
  const channelType = String(ctx.channelType || '').trim().toLowerCase();