evolcore 0.0.47 → 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 (218) hide show
  1. package/CHANGELOG.md +56 -1
  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 +34 -17
  8. package/dist/agents/codex-runner.js +31 -16
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/service-proxy.js +4 -2
  14. package/dist/build-identity.json +1 -0
  15. package/dist/channels/aun.js +81 -24
  16. package/dist/channels/daemon.js +9 -25
  17. package/dist/cli/aun-commands.js +86 -51
  18. package/dist/cli/code-stats.js +19 -8
  19. package/dist/cli/command-log.js +1 -1
  20. package/dist/cli/daemon-commands.js +44 -43
  21. package/dist/cli/directory.js +7 -1
  22. package/dist/cli/ecmsg-gateway.js +5 -2
  23. package/dist/cli/index.js +2 -8
  24. package/dist/cli/init-channel.js +4 -6
  25. package/dist/cli/init.js +72 -50
  26. package/dist/cli/invoke-command.js +1 -1
  27. package/dist/cli/provider-command.js +74 -13
  28. package/dist/cli/role.js +61 -17
  29. package/dist/cli/stats.js +3 -3
  30. package/dist/cli/thread-command.js +16 -51
  31. package/dist/config/boot-log.js +3 -9
  32. package/dist/config/builtin-roles.js +5 -7
  33. package/dist/config/config-manager.js +2 -6
  34. package/dist/config/daemon-services.js +30 -3
  35. package/dist/config/gateway-config.js +2 -2
  36. package/dist/config/invoke-ipc-service.js +6 -4
  37. package/dist/config/peer-bind-code.js +3 -4
  38. package/dist/config/peer-book-store.js +62 -229
  39. package/dist/config/peer-book.js +26 -27
  40. package/dist/config/peer-role-resolver.js +16 -1
  41. package/dist/config/provider-identity-migration.js +4 -1
  42. package/dist/config/provider-ipc-service.js +56 -11
  43. package/dist/config/provider-menu-request.js +24 -5
  44. package/dist/config/provider-templates.js +127 -0
  45. package/dist/config/providers-config.js +59 -8
  46. package/dist/config/providers-management.js +467 -49
  47. package/dist/config/role-command-service.js +248 -1
  48. package/dist/config/schema-migration.js +105 -4
  49. package/dist/core/agent-application-service.js +6 -1
  50. package/dist/core/agent-runtime.js +4 -0
  51. package/dist/core/auth/agent-delegation.js +2 -1
  52. package/dist/core/auth/auth-gateway.js +2 -1
  53. package/dist/core/auth/delegation-authorization.js +3 -0
  54. package/dist/core/auth/operation-authorizer.js +25 -0
  55. package/dist/core/auth/operation-catalog.js +28 -64
  56. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  57. package/dist/core/channel-loader.js +18 -0
  58. package/dist/core/command/agent-control.js +32 -0
  59. package/dist/core/command/command-handler.js +81 -85
  60. package/dist/core/command/menu-catalog.js +1 -0
  61. package/dist/core/command/menu-handler.js +61 -149
  62. package/dist/core/command/menu-protocol.js +7 -1
  63. package/dist/core/command/provider-menu.js +13 -3
  64. package/dist/core/command/role-menu.js +47 -23
  65. package/dist/core/command/slash-handler.js +26 -43
  66. package/dist/core/command/team-workspace-items.js +81 -12
  67. package/dist/core/command/team-workspace-team.js +9 -71
  68. package/dist/core/command/topic-slash.js +9 -30
  69. package/dist/core/daemon-bootstrap.js +8 -1
  70. package/dist/core/daemon-control.js +7 -7
  71. package/dist/core/evolagent-registry.js +14 -1
  72. package/dist/core/file-integrity/store.js +2 -0
  73. package/dist/core/handoff/runtime.js +37 -1
  74. package/dist/core/inference/text-inference.js +3 -1
  75. package/dist/core/initialization/service.js +11 -6
  76. package/dist/core/interaction-router.js +3 -0
  77. package/dist/core/invoke/executors/text.js +72 -19
  78. package/dist/core/ipc-registration.js +2 -1
  79. package/dist/core/message/aun-ipc-sender.js +165 -55
  80. package/dist/core/message/im-renderer.js +1 -1
  81. package/dist/core/message/message-bridge.js +51 -334
  82. package/dist/core/message/message-log.js +5 -0
  83. package/dist/core/message/message-queue.js +22 -0
  84. package/dist/core/message/message-utils.js +8 -0
  85. package/dist/core/message/response-engine.js +429 -116
  86. package/dist/core/message/send-routing.js +5 -1
  87. package/dist/core/model/catalog-service.js +31 -11
  88. package/dist/core/model/model-capabilities.js +22 -4
  89. package/dist/core/model/model-catalog.js +1 -0
  90. package/dist/core/ownership/owner-resolver.js +328 -50
  91. package/dist/core/permission/protected-paths.js +6 -6
  92. package/dist/core/relation/peer-identity.js +23 -1
  93. package/dist/core/relation/same-owner-proof.js +81 -112
  94. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  95. package/dist/core/session/session-file-health.js +13 -7
  96. package/dist/core/session/session-fs-store.js +91 -35
  97. package/dist/core/session/session-manager.js +68 -24
  98. package/dist/core/session/session-mapper.js +14 -34
  99. package/dist/core/session/session-transcript.js +5 -1
  100. package/dist/core/task/task-activity-store.js +84 -0
  101. package/dist/core/task/task-recovery-service.js +12 -0
  102. package/dist/core/thread/command-parser.js +7 -12
  103. package/dist/core/thread/thread-context-storage.js +3 -2
  104. package/dist/core/thread/thread-operation.js +2 -13
  105. package/dist/core/thread/thread-service.js +15 -46
  106. package/dist/directory/owner-directory-admission.js +1 -1
  107. package/dist/directory/owner-directory-cache.js +45 -28
  108. package/dist/directory/owner-directory-markdown.js +13 -1
  109. package/dist/directory/owner-directory-query-operation.js +29 -3
  110. package/dist/directory/owner-directory-remarks.js +11 -3
  111. package/dist/eck/message-renderer.js +84 -24
  112. package/dist/ecweb/basic-settings-service.js +3 -1
  113. package/dist/ecweb/message-context-service.js +1 -1
  114. package/dist/ecweb/pairing.js +4 -3
  115. package/dist/ecweb/providers-service.js +26 -1
  116. package/dist/ecweb/runtime/lifecycle.js +18 -8
  117. package/dist/ecweb/runtime/proxy-access.js +74 -0
  118. package/dist/ecweb/runtime/supervisor.js +4 -2
  119. package/dist/event-center/registry.js +13 -2
  120. package/dist/event-center/runtime.js +103 -11
  121. package/dist/event-center/script-runner.js +5 -5
  122. package/dist/index.js +92 -59
  123. package/dist/ipc.js +13 -2
  124. package/dist/outputs/events.js +62 -0
  125. package/dist/outputs/protocol.js +102 -0
  126. package/dist/outputs/service.js +279 -0
  127. package/dist/paths.js +3 -0
  128. package/dist/proxy/manager.js +43 -13
  129. package/dist/services/index.js +89 -4
  130. package/dist/services/ipc-operation.js +4 -15
  131. package/dist/services/pack-manager.js +12 -1
  132. package/dist/services/router.js +21 -6
  133. package/dist/services/script-runner.js +5 -4
  134. package/dist/services/validation.js +1 -1
  135. package/dist/stats/budget.js +1 -1
  136. package/dist/stats/db.js +19 -0
  137. package/dist/stats/index.js +1 -1
  138. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  139. package/dist/stats/normalizer.js +2 -0
  140. package/dist/stats/query.js +35 -27
  141. package/dist/stats/role-budget.js +5 -2
  142. package/dist/stats/writer.js +10 -6
  143. package/dist/trigger/audit.js +7 -0
  144. package/dist/trigger/authorization.js +105 -11
  145. package/dist/trigger/feedback.js +10 -0
  146. package/dist/trigger/history.js +37 -11
  147. package/dist/trigger/ipc-service.js +12 -1
  148. package/dist/trigger/manager.js +1 -0
  149. package/dist/trigger/scheduler.js +7 -5
  150. package/dist/trigger/script-executor.js +2 -1
  151. package/dist/trigger/script-sandbox.js +9 -3
  152. package/dist/trigger/validation.js +22 -0
  153. package/dist/utils/cross-platform.js +73 -26
  154. package/dist/utils/error-dict.json +94 -4
  155. package/dist/utils/error-utils.js +27 -4
  156. package/dist/utils/evolcore-version.js +36 -65
  157. package/dist/utils/msg-diag.js +1 -0
  158. package/dist/utils/process-introspect.js +12 -7
  159. package/dist/utils/process-tree.js +50 -2
  160. package/dist/utils/windows-shell-trust.js +2 -0
  161. package/dist/workbench/protocol.js +80 -0
  162. package/dist/workbench/service.js +359 -0
  163. package/ecagent/dist/types.d.ts +6 -2
  164. package/kits/docs/context-assembly.md +1 -1
  165. package/kits/docs/evolcore/INDEX.md +2 -2
  166. package/kits/docs/evolcore/config.md +12 -0
  167. package/kits/docs/evolcore/directory.md +22 -3
  168. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  169. package/kits/docs/evolcore/model.md +10 -0
  170. package/kits/docs/evolcore/peer.md +19 -65
  171. package/kits/docs/evolcore/provider.md +123 -3
  172. package/kits/docs/evolcore/role.md +80 -0
  173. package/kits/docs/evolcore/services.md +6 -6
  174. package/kits/docs/evolcore/team-workspace.md +1 -1
  175. package/kits/docs/evolcore/thread-chain.md +14 -15
  176. package/kits/docs/evolcore/tool-authorization.md +5 -0
  177. package/kits/docs/evolcore/trigger.md +10 -0
  178. package/kits/eck_message_manifest.json +12 -0
  179. package/kits/provider-templates.json +1213 -0
  180. package/kits/rules/04-relation.md +3 -3
  181. package/kits/schemas/_meta.json +14 -2
  182. package/kits/schemas/contact-book.schema.4.json +52 -0
  183. package/kits/schemas/providers.schema.3.json +200 -0
  184. package/kits/skills/.switches.json +4 -0
  185. package/kits/skills/ability/references/calling.md +1 -1
  186. package/kits/skills/ec-group/SKILL.md +2 -2
  187. package/kits/skills/ec-identity/SKILL.md +19 -72
  188. package/kits/skills/ec-provider/SKILL.md +221 -0
  189. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  190. package/kits/skills/ec-trigger/SKILL.md +1 -1
  191. package/kits/skills/thread-ops/SKILL.md +34 -21
  192. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  193. package/kits/templates/message-fragments/group-batch.md +1 -1
  194. package/kits/templates/message-fragments/inject-default.md +1 -1
  195. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  196. package/kits/templates/message-fragments/item-group.md +1 -1
  197. package/kits/templates/message-fragments/item-private.md +1 -1
  198. package/kits/templates/message-fragments/thread-context.md +1 -1
  199. package/kits/templates/message-fragments/trigger-session.md +1 -1
  200. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  201. package/kits/templates/roles/admin.json +2 -19
  202. package/kits/templates/roles/member.json +0 -3
  203. package/kits/templates/system-fragments/baseagent.md +6 -0
  204. package/kits/templates/system-fragments/commands.md +3 -3
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +1 -1
  207. package/kits/templates/system-fragments/thread.md +6 -5
  208. package/package.json +6 -4
  209. package/scripts/agent-template/inspect.mjs +4 -1
  210. package/scripts/agent-template/shared/common.mjs +2 -3
  211. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  212. package/scripts/agent-template/shared/template-package.mjs +9 -2
  213. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  214. package/scripts/agent-template/team-pack.mjs +6 -3
  215. package/dist/cli/peer.js +0 -127
  216. package/dist/config/peer-operation-service.js +0 -132
  217. package/dist/config/peer-request-service.js +0 -532
  218. 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,105 +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 (config?.targetKind !== 'group' && config?.role === 'admin' && roles[parsed.channelId] !== 'owner') {
155
- if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind === 'private') {
156
- roles[parsed.channelId] = 'admin';
157
- }
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
- // Startup has not observed protocol ownership yet. Do not erase its old
178
- // display projection just to recreate it on the first verified update.
179
- // Permission consumers resolve ownership independently of this field.
180
- if (mutateContactBookSyncInternal({
181
- selfAid: entry.name,
182
- actor: 'management-role-sync',
183
- mutation: { type: 'sync-management-roles' },
184
- }, [], true).changed)
185
- changed += 1;
186
- }
187
- return changed;
188
- }
189
129
  /** Recover every interrupted Contact transaction before startup reads config. */
190
130
  export function recoverAllPeerBookMutationsSync() {
191
131
  const agentsRoot = resolvePaths().agentsDir;
@@ -208,18 +148,18 @@ export function recoverAllPeerBookMutationsSync() {
208
148
  }
209
149
  return recovered;
210
150
  }
211
- function mutateContactBookSyncInternal(request, transactionChanges, deferUnobservedOwner = false) {
151
+ function mutateContactBookSyncInternal(request, transactionChanges) {
212
152
  const selfAid = normalizeAid(request.selfAid, 'self AID');
213
153
  const release = acquireAgentLock(selfAid);
214
154
  try {
215
- return mutateContactBookLocked({ ...request, selfAid }, transactionChanges, deferUnobservedOwner);
155
+ return mutateContactBookLocked({ ...request, selfAid }, transactionChanges);
216
156
  }
217
157
  finally {
218
158
  release();
219
159
  }
220
160
  }
221
161
  /** The caller owns the contact lock; the entire critical section is synchronous. */
222
- function mutateContactBookLocked(request, transactionChanges, deferUnobservedOwner = false) {
162
+ function mutateContactBookLocked(request, transactionChanges) {
223
163
  const selfAid = request.selfAid;
224
164
  recoverMutation(selfAid);
225
165
  const file = agentPeerConfig(selfAid);
@@ -235,19 +175,9 @@ function mutateContactBookLocked(request, transactionChanges, deferUnobservedOwn
235
175
  validateTransactionChanges(selfAid, transactionChanges);
236
176
  const next = cloneBook(current);
237
177
  applyMutation(next, request.mutation, selfAid, transactionChanges);
238
- synchronizeManagementRoles(next, selfAid, transactionChanges, deferUnobservedOwner);
239
- if (request.mutation.type === 'replace') {
240
- const errors = validateConfig(ConfigTarget.Peer, next);
241
- if (errors.length)
242
- throw new PeerMutationError('INVALID_CONTACT_BOOK', errors.join('; '));
243
- }
244
- else {
245
- validateContactBook(next, selfAid, transactionChanges);
246
- }
247
- const omitEmptySync = request.mutation.type === 'sync-management-roles'
248
- && current === null
249
- && Object.keys(next.contacts).length === 0;
250
- 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);
251
181
  if (nextRevision === previousRevision && transactionChanges.length === 0) {
252
182
  return { changed: false, peerRevision: previousRevision, previousContactRevision: previousRevision, contact: next };
253
183
  }
@@ -293,9 +223,9 @@ function mutateContactBookPreparedLocked(selfAid, prepare) {
293
223
  const prepared = prepare({ contact: next, peerRevision: previousRevision });
294
224
  if (prepared.mutation)
295
225
  applyMutation(next, prepared.mutation, selfAid);
296
- synchronizeManagementRoles(next, selfAid, []);
297
226
  validateContactBook(next, selfAid);
298
- const nextRevision = peerRevision(next);
227
+ const nextRevision = current === null && Object.keys(next.contacts).length === 0
228
+ ? previousRevision : peerRevision(next);
299
229
  if (nextRevision === previousRevision) {
300
230
  return {
301
231
  changed: false,
@@ -356,95 +286,25 @@ function applyMutation(book, mutation, selfAid, changes = []) {
356
286
  applyMutation(book, item, selfAid, changes);
357
287
  return;
358
288
  }
359
- if (mutation.type === 'ensure-contacts') {
360
- for (const rawPrimaryId of mutation.primaryIds) {
361
- const primaryId = normalizeContactAid(rawPrimaryId, selfAid, changes);
362
- if (!contacts[primaryId])
363
- contacts[primaryId] = {};
364
- }
365
- return;
366
- }
367
- if (mutation.type === 'sync-management-roles') {
368
- return;
369
- }
370
- const rawPrimaryId = String(mutation.primaryId || '').trim();
371
- if (isOwner(selfAid, rawPrimaryId)) {
372
- if (mutation.type === 'set-status' && mutation.status !== 'active') {
373
- throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner must remain active');
374
- }
375
- if (mutation.type === 'set-request') {
376
- throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner cannot submit a contact request');
377
- }
378
- }
379
- const prior = contacts[rawPrimaryId];
380
- const preservesAdmission = !!prior && (mutation.type === 'set-display-name' || mutation.type === 'unbind-alias'
381
- || mutation.type === 'expire-request'
382
- || (mutation.type === 'review-request' && mutation.decision !== 'approve')
383
- || (mutation.type === 'set-status' && mutation.status !== 'active'));
384
- const primaryId = normalizeContactAid(mutation.primaryId, selfAid, changes, preservesAdmission);
289
+ const primaryId = normalizeAid(mutation.primaryId, 'peer AID');
385
290
  const existing = contacts[primaryId];
386
291
  if (mutation.type === 'set-status') {
387
- contacts[primaryId] = compactEntry({
388
- ...existing,
389
- status: mutation.status === 'active' ? undefined : mutation.status,
390
- pendingRequest: undefined,
391
- declinedAt: mutation.status === 'declined' ? existing?.declinedAt ?? new Date().toISOString() : undefined,
392
- });
393
- return;
394
- }
395
- if (mutation.type === 'set-request') {
396
- contacts[primaryId] = compactEntry({
397
- ...existing,
398
- status: 'pending',
399
- pendingRequest: { ...mutation.request },
400
- declinedAt: undefined,
401
- });
402
- return;
403
- }
404
- if (mutation.type === 'review-request') {
405
- if (!existing || existing.status !== 'pending' || existing.pendingRequest?.id !== mutation.requestId) {
406
- throw new PeerMutationError('REQUEST_STALE', 'The contact request has changed or was already handled');
407
- }
408
- if (Date.parse(existing.pendingRequest.expiresAt) <= Date.parse(mutation.now)) {
409
- throw new PeerMutationError('REQUEST_EXPIRED', 'The contact request has expired');
292
+ if (mutation.status === 'blocked' && isOwner(selfAid, primaryId)) {
293
+ throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner cannot be blocked');
410
294
  }
411
- if (mutation.decision === 'reject') {
412
- delete contacts[primaryId];
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];
413
301
  }
414
- else {
415
- contacts[primaryId] = compactEntry({
416
- ...existing,
417
- status: mutation.decision === 'block' ? 'blocked' : undefined,
418
- pendingRequest: undefined,
419
- declinedAt: undefined,
420
- });
421
- }
422
- return;
423
- }
424
- if (mutation.type === 'expire-request') {
425
- if (!existing || existing.status !== 'pending' || existing.pendingRequest?.id !== mutation.requestId)
426
- return;
427
- if (Date.parse(existing.pendingRequest.expiresAt) > Date.parse(mutation.now))
428
- return;
429
- contacts[primaryId] = compactEntry({
430
- ...existing,
431
- status: 'declined',
432
- pendingRequest: undefined,
433
- declinedAt: existing.pendingRequest.expiresAt,
434
- });
435
- return;
436
- }
437
- if (mutation.type === 'set-display-name') {
438
- contacts[primaryId] = compactEntry({ ...existing, displayName: mutation.displayName ?? undefined });
439
302
  return;
440
303
  }
441
304
  if (mutation.type === 'bind-alias' || mutation.type === 'bind-alias-eligible') {
442
- if (mutation.type === 'bind-alias-eligible') {
443
- const eligible = isOwner(selfAid, primaryId)
444
- || (!!existing && (existing.status === undefined || existing.status === 'active'));
445
- if (!eligible) {
446
- throw new PeerMutationError('CONTACT_NOT_ACTIVE', 'Only an active contact or Agent owner can bind an alias');
447
- }
305
+ normalizeContactAid(primaryId, selfAid, changes);
306
+ if (!isPeerBindingEligible(selfAid, primaryId)) {
307
+ throw new PeerMutationError('CONTACT_NOT_ALLOWED', 'Channel binding requires an admitted private principal');
448
308
  }
449
309
  for (const [owner, entry] of Object.entries(contacts)) {
450
310
  if (owner !== primaryId && entry.aliases?.includes(mutation.alias)) {
@@ -463,20 +323,6 @@ function applyMutation(book, mutation, selfAid, changes = []) {
463
323
  }
464
324
  throw new PeerMutationError('INVALID_MUTATION', `Unsupported Contact Book mutation: ${String(mutation?.type)}`);
465
325
  }
466
- function synchronizeManagementRoles(book, selfAid, changes, deferUnobservedOwner = false) {
467
- const roles = managementRoleMapForAgent(selfAid, changes);
468
- const ownershipPending = deferUnobservedOwner && ownerResolver.snapshot(selfAid).checkedAt === undefined;
469
- for (const [primaryId, entry] of Object.entries(book.contacts)) {
470
- book.contacts[primaryId] = compactEntry({
471
- ...entry,
472
- ...(roles[primaryId] === 'owner' ? { status: undefined, pendingRequest: undefined, declinedAt: undefined } : {}),
473
- managementRole: roles[primaryId] ?? (ownershipPending && entry.managementRole === 'owner' ? 'owner' : undefined),
474
- });
475
- }
476
- for (const [primaryId, managementRole] of Object.entries(roles)) {
477
- book.contacts[primaryId] = compactEntry({ ...book.contacts[primaryId], managementRole });
478
- }
479
- }
480
326
  function validateContactBook(book, selfAid, changes = []) {
481
327
  const schemaErrors = validateConfig(ConfigTarget.Peer, book);
482
328
  if (schemaErrors.length) {
@@ -496,22 +342,6 @@ function validateContactBook(book, selfAid, changes = []) {
496
342
  if (entry.status && isOwner(selfAid, primaryId)) {
497
343
  throw new PeerMutationError('OWNER_PROTECTED', 'An Agent owner must remain active');
498
344
  }
499
- if (entry.status === 'pending') {
500
- if (!entry.pendingRequest || !Number.isFinite(Date.parse(entry.pendingRequest.submittedAt))
501
- || !Number.isFinite(Date.parse(entry.pendingRequest.expiresAt))
502
- || Date.parse(entry.pendingRequest.expiresAt) <= Date.parse(entry.pendingRequest.submittedAt)) {
503
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `Invalid pending request for ${primaryId}`);
504
- }
505
- }
506
- else if (entry.pendingRequest) {
507
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `pendingRequest requires pending status for ${primaryId}`);
508
- }
509
- if (entry.status === 'declined' && !Number.isFinite(Date.parse(entry.declinedAt ?? ''))) {
510
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `declinedAt is required for ${primaryId}`);
511
- }
512
- if (entry.status !== 'declined' && entry.declinedAt) {
513
- throw new PeerMutationError('INVALID_CONTACT_BOOK', `declinedAt requires declined status for ${primaryId}`);
514
- }
515
345
  for (const alias of entry.aliases ?? []) {
516
346
  const parsed = parseContactAlias(alias, selfAid);
517
347
  if (!parsed) {
@@ -544,7 +374,6 @@ function cloneBook(book) {
544
374
  contacts[primaryId] = {
545
375
  ...entry,
546
376
  ...(entry.aliases ? { aliases: [...entry.aliases] } : {}),
547
- ...(entry.pendingRequest ? { pendingRequest: { ...entry.pendingRequest } } : {}),
548
377
  };
549
378
  }
550
379
  return { $schema_version: currentVersion('contact-book'), contacts };
@@ -557,8 +386,12 @@ function removeAliasEverywhere(contacts, alias, onlyOwner) {
557
386
  if (onlyOwner && primaryId !== onlyOwner)
558
387
  continue;
559
388
  const aliases = (entry.aliases ?? []).filter(candidate => candidate !== alias);
560
- if (aliases.length !== (entry.aliases ?? []).length)
561
- 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
+ }
562
395
  }
563
396
  }
564
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();
@@ -194,6 +194,9 @@ export function planProviderIdentityMigration(home, registry, options = {}) {
194
194
  if (staticUrls && targetBase !== sourceBase && new URL(targetBase).origin === new URL(sourceBase).origin) {
195
195
  const resolved = new URL(rawService.path || '.', sourceBase.endsWith('/') ? sourceBase : `${sourceBase}/`);
196
196
  service = { ...rawService, path: `${resolved.pathname}${resolved.search}${resolved.hash}` };
197
+ if (rawService.catalogPath !== undefined) {
198
+ service.catalogPath = new URL(rawService.catalogPath, sourceBase.replace(/\/+$/u, '') + '/').pathname;
199
+ }
197
200
  }
198
201
  if (Object.hasOwn(services, serviceType)) {
199
202
  const existing = services[serviceType];
@@ -209,7 +212,7 @@ export function planProviderIdentityMigration(home, registry, options = {}) {
209
212
  : isDeepStrictEqual(existing.path, service.path);
210
213
  if (!sameEndpoint)
211
214
  conflicts.push(`services.${serviceType}.path`);
212
- for (const field of ['style', 'models', 'modelPolicy']) {
215
+ for (const field of ['style', 'models', 'modelPolicy', 'catalogPath', 'apiKey', 'headers', 'queryParams']) {
213
216
  if (!isDeepStrictEqual(existing[field], service[field]))
214
217
  conflicts.push(`services.${serviceType}.${field}`);
215
218
  }