evolcore 0.0.45 → 0.0.47

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. package/scripts/agent-template/pack.mjs +0 -169
@@ -32,10 +32,12 @@ import { normalizeRoleEffortCompat, normalizeRoleGroupChatmodeCompat } from './r
32
32
  import { mutatePeerBookTransactionSync, resolvePeerAidKind } from './peer-book-store.js';
33
33
  import { DAEMON_SCHEMA_NAME } from '../product.js';
34
34
  import { normalizeDaemonServices } from './daemon-services.js';
35
- import { assertProviderSelectionWrite, resolveProviderModelOverrides, validateProvidersFile } from './providers-config.js';
35
+ import { assertProviderSelectionWrite, resolveProviderModelSettings, validateProvidersFile } from './providers-config.js';
36
+ import { resolveProviderSelectionModel } from '../core/model/model-catalog.js';
36
37
  import { assertOwnerConfigRecord, configuredOwnerList, normalizeOwnerConfigTree, withOwnerListCompatibility } from './owner-config.js';
37
38
  import { getOwners, getPrimaryOwner, ownerResolver } from '../core/ownership/owner-resolver.js';
38
39
  import { resolveBaseagentModelSelection } from '../agents/baseagent.js';
40
+ import { assertProjectPathReference } from '../utils/project-path.js';
39
41
  // AUN gateway discovery belongs to fastaun. Keep the retired gatewayUrl
40
42
  // compatibility handling beside the rest of the configuration read/write
41
43
  // policy so all config callers share one implementation.
@@ -369,15 +371,18 @@ export function assertContactBookV2Ready() {
369
371
  return;
370
372
  const issues = [];
371
373
  const contactMigrationAgentSchemaMax = 6;
372
- const supportedSchemas = (name, minimumVersion) => (listSchemaVersions(name)
373
- .filter(version => version >= minimumVersion)
374
- .map(version => loadSchema(name, version)));
375
- const agentSchemas = supportedSchemas('agent-config', contactMigrationAgentSchemaMax);
374
+ const versions = new Map();
375
+ const supportedVersions = (name, minimumVersion) => {
376
+ let supported = versions.get(name);
377
+ if (!supported) {
378
+ supported = listSchemaVersions(name).filter(version => version >= minimumVersion);
379
+ versions.set(name, supported);
380
+ }
381
+ return supported;
382
+ };
376
383
  /** 当前 Agent 配置版本:介于迁移上限与它之间的版本都由别处校验,本门禁放行。 */
377
384
  const agentConfigCurrentVersion = currentVersion('agent-config');
378
- const contactSchemas = supportedSchemas('contact-book', 2);
379
- const relationSchemas = supportedSchemas('relation-config', 5);
380
- const inspect = (file, schemas, skipNewerAgentSchema = false) => {
385
+ const inspect = (file, name, minimumVersion, skipNewerAgentSchema = false) => {
381
386
  let value;
382
387
  try {
383
388
  value = JSON.parse(fs.readFileSync(file, 'utf8'));
@@ -387,7 +392,6 @@ export function assertContactBookV2Ready() {
387
392
  return;
388
393
  }
389
394
  value = stripLegacyAunGatewayConfig(value, file, message => configWarn(message));
390
- const candidates = Array.isArray(schemas) ? schemas : [schemas];
391
395
  const schemaVersion = value?.$schema_version;
392
396
  if (skipNewerAgentSchema && typeof schemaVersion === 'number'
393
397
  && schemaVersion > contactMigrationAgentSchemaMax
@@ -400,12 +404,22 @@ export function assertContactBookV2Ready() {
400
404
  // 仍然拒绝——那是本程序不认识的未来格式。
401
405
  return;
402
406
  }
403
- if (!candidates.some(schema => schema.validate(value))) {
404
- const detail = (candidates.at(-1)?.validate.errors ?? [])
405
- .map(error => `${error.instancePath || '/'} ${error.message}`)
406
- .join('; ');
407
- issues.push({ file, detail });
408
- }
407
+ const supported = supportedVersions(name, minimumVersion);
408
+ // Healthy files only need their own schema. Keep the full historical
409
+ // fallback for malformed/legacy input, including the previous diagnostics.
410
+ if (typeof schemaVersion === 'number' && supported.includes(schemaVersion)
411
+ && loadSchema(name, schemaVersion).validate(value))
412
+ return;
413
+ let lastSchema;
414
+ for (const version of supported) {
415
+ lastSchema = loadSchema(name, version);
416
+ if (lastSchema.validate(value))
417
+ return;
418
+ }
419
+ const detail = (lastSchema?.validate.errors ?? [])
420
+ .map(error => `${error.instancePath || '/'} ${error.message}`)
421
+ .join('; ');
422
+ issues.push({ file, detail });
409
423
  };
410
424
  const walkRelationConfigs = (dir) => {
411
425
  if (!fs.existsSync(dir))
@@ -427,14 +441,14 @@ export function assertContactBookV2Ready() {
427
441
  const agentFile = path.join(dir, 'config.json');
428
442
  if (!fs.existsSync(agentFile))
429
443
  continue;
430
- inspect(agentFile, agentSchemas, true);
444
+ inspect(agentFile, 'agent-config', contactMigrationAgentSchemaMax, true);
431
445
  const contactFile = path.join(dir, 'contact.json');
432
446
  if (fs.existsSync(contactFile)) {
433
- inspect(contactFile, contactSchemas);
447
+ inspect(contactFile, 'contact-book', 2);
434
448
  inspectContactBookDomain(contactFile, agentFile, issues);
435
449
  }
436
450
  for (const relationFile of walkRelationConfigs(path.join(dir, 'relations'))) {
437
- inspect(relationFile, relationSchemas);
451
+ inspect(relationFile, 'relation-config', 5);
438
452
  }
439
453
  }
440
454
  const correctionReceipt = path.join(root, 'data', 'contact-book-v2-relation-role-authority.json');
@@ -984,7 +998,7 @@ export function write(target, value, sel, opts = {}) {
984
998
  : target === ConfigTarget.Agent ? read(ConfigTarget.Defaults, undefined, { cache: false }) ?? {}
985
999
  : resolveAgentConfig({ self: sel?.self }, { cache: false });
986
1000
  try {
987
- assertProviderSelectionWrite(normalized, previous, inherited, (providerId, serviceType, baseagent) => resolveProviderModelOverrides(providerId, serviceType, read(ConfigTarget.Providers) ?? { providers: {} }, baseagent));
1001
+ assertProviderSelectionWrite(normalized, previous, inherited, (providerId, serviceType, baseagent) => resolveProviderModelSettings(providerId, serviceType, read(ConfigTarget.Providers) ?? { providers: {} }, baseagent), (providerId, serviceType, baseagent, model) => resolveProviderSelectionModel(providerId, serviceType, baseagent, model));
988
1002
  }
989
1003
  catch (error) {
990
1004
  throw new ConfigError('VALIDATION_ERROR', error instanceof Error ? error.message : String(error));
@@ -1256,6 +1270,7 @@ function validateOrThrow(schema, value, target) {
1256
1270
  ...validateProcessOnlyFields(target, value),
1257
1271
  ...validateProcessAidDomain(target, value),
1258
1272
  ...validateProcessServiceNames(target, value),
1273
+ ...validateDefaultProjectReference(target, value),
1259
1274
  ];
1260
1275
  if (!ok || scopeErrors.length > 0) {
1261
1276
  const errs = [
@@ -1270,6 +1285,20 @@ function validateOrThrow(schema, value, target) {
1270
1285
  throw new ConfigError('SCHEMA_INVALID', `${target} 配置不合 schema(${schema.logicalName}.v${schema.version}): ${errs}`);
1271
1286
  }
1272
1287
  }
1288
+ function validateDefaultProjectReference(target, value) {
1289
+ if (target !== ConfigTarget.Defaults)
1290
+ return [];
1291
+ const configured = value?.projects?.defaultPath;
1292
+ if (typeof configured !== 'string')
1293
+ return [];
1294
+ try {
1295
+ assertProjectPathReference(configured);
1296
+ return [];
1297
+ }
1298
+ catch (error) {
1299
+ return [error.message];
1300
+ }
1301
+ }
1273
1302
  function validateProcessOnlyFields(target, value) {
1274
1303
  if (target === ConfigTarget.Process || !value || typeof value !== 'object')
1275
1304
  return [];
@@ -1380,6 +1409,7 @@ export function validateConfig(target, value) {
1380
1409
  ...validateProcessOnlyFields(target, normalized),
1381
1410
  ...validateProcessAidDomain(target, normalized),
1382
1411
  ...validateProcessServiceNames(target, normalized),
1412
+ ...validateDefaultProjectReference(target, normalized),
1383
1413
  ];
1384
1414
  if (target === ConfigTarget.Agent) {
1385
1415
  try {
@@ -13,6 +13,7 @@ import { ownerResolver } from '../core/ownership/owner-resolver.js';
13
13
  import { parseContactAlias } from './peer-alias.js';
14
14
  import { clearRoleStoreCache } from './role-store.js';
15
15
  import { currentVersion } from './schema-registry.js';
16
+ import { setTimeout as waitForLock } from 'node:timers/promises';
16
17
  const LOCK_NAME = '.contact-book-mutation.lock';
17
18
  const JOURNAL_NAME = '.contact-book-mutation.json';
18
19
  const LOCK_WAIT_MS = 5_000;
@@ -53,7 +54,7 @@ export function mutatePeerBookPrepared(selfAid, prepare) {
53
54
  mutationTails.set(normalizedAid, tail);
54
55
  return previous
55
56
  .catch(() => { })
56
- .then(() => mutateContactBookPreparedSyncInternal(normalizedAid, prepare))
57
+ .then(() => withAgentLock(normalizedAid, () => mutateContactBookPreparedLocked(normalizedAid, prepare)))
57
58
  .finally(() => {
58
59
  release();
59
60
  if (mutationTails.get(normalizedAid) === tail)
@@ -75,7 +76,7 @@ function enqueueContactMutation(request, changes) {
75
76
  mutationTails.set(selfAid, tail);
76
77
  return previous
77
78
  .catch(() => { })
78
- .then(() => mutateContactBookSyncInternal({ ...request, selfAid }, changes))
79
+ .then(() => withAgentLock(selfAid, () => mutateContactBookLocked({ ...request, selfAid }, changes)))
79
80
  .finally(() => {
80
81
  release();
81
82
  if (mutationTails.get(selfAid) === tail)
@@ -150,10 +151,10 @@ function managementRoleMapForAgent(selfAid, changes) {
150
151
  if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId))
151
152
  continue;
152
153
  const config = readTransactionJson(path.join(relationsRoot, peerKey, 'config.json'), changes);
153
- if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind !== 'private')
154
- continue;
155
154
  if (config?.targetKind !== 'group' && config?.role === 'admin' && roles[parsed.channelId] !== 'owner') {
156
- roles[parsed.channelId] = 'admin';
155
+ if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind === 'private') {
156
+ roles[parsed.channelId] = 'admin';
157
+ }
157
158
  }
158
159
  }
159
160
  return roles;
@@ -173,7 +174,14 @@ export function synchronizeAllManagementPeersSync() {
173
174
  for (const entry of entries) {
174
175
  if (!entry.isDirectory() || !isValidAid(entry.name) || !fs.existsSync(agentConfig(entry.name)))
175
176
  continue;
176
- if (synchronizeManagementPeersSync(entry.name).changed)
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)
177
185
  changed += 1;
178
186
  }
179
187
  return changed;
@@ -200,142 +208,142 @@ export function recoverAllPeerBookMutationsSync() {
200
208
  }
201
209
  return recovered;
202
210
  }
203
- function mutateContactBookSyncInternal(request, transactionChanges) {
211
+ function mutateContactBookSyncInternal(request, transactionChanges, deferUnobservedOwner = false) {
204
212
  const selfAid = normalizeAid(request.selfAid, 'self AID');
205
213
  const release = acquireAgentLock(selfAid);
206
214
  try {
207
- recoverMutation(selfAid);
208
- const file = agentPeerConfig(selfAid);
209
- const current = readContactBookFromDisk(selfAid);
210
- const previousRevision = peerRevision(current);
211
- if (request.expectedContactRevision !== undefined
212
- && request.expectedContactRevision !== previousRevision) {
213
- throw new PeerMutationError('CONFLICT', 'Contact book changed since it was read', {
214
- expectedContactRevision: request.expectedContactRevision,
215
- peerRevision: previousRevision,
216
- });
217
- }
218
- validateTransactionChanges(selfAid, transactionChanges);
219
- const next = cloneBook(current);
220
- applyMutation(next, request.mutation, selfAid, transactionChanges);
221
- synchronizeManagementRoles(next, selfAid, transactionChanges);
222
- if (request.mutation.type === 'replace') {
223
- const errors = validateConfig(ConfigTarget.Peer, next);
224
- if (errors.length)
225
- throw new PeerMutationError('INVALID_CONTACT_BOOK', errors.join('; '));
226
- }
227
- else {
228
- validateContactBook(next, selfAid, transactionChanges);
229
- }
230
- const omitEmptySync = request.mutation.type === 'sync-management-roles'
231
- && current === null
232
- && Object.keys(next.contacts).length === 0;
233
- const nextRevision = omitEmptySync ? previousRevision : peerRevision(next);
234
- if (nextRevision === previousRevision && transactionChanges.length === 0) {
235
- return { changed: false, peerRevision: previousRevision, previousContactRevision: previousRevision, contact: next };
236
- }
237
- const before = readTextOrNull(file);
238
- const after = `${JSON.stringify(next, null, 2)}\n`;
239
- const changes = [
240
- ...(nextRevision === previousRevision ? [] : [{ file, before, after }]),
241
- ...transactionChanges,
242
- ];
243
- writeJournal(selfAid, { schemaVersion: 1, state: 'prepared', selfAid, changes });
244
- try {
245
- for (const change of changes)
246
- applyTransactionChange(change);
247
- writeJournal(selfAid, { schemaVersion: 1, state: 'committed', selfAid, changes });
248
- removeJournal(selfAid);
249
- }
250
- catch (error) {
251
- recoverMutation(selfAid);
252
- throw error;
253
- }
254
- if (nextRevision !== previousRevision) {
255
- notifyConfigWrite(ConfigTarget.Peer, { self: selfAid });
256
- appendAudit(selfAid, request, previousRevision, nextRevision);
257
- }
258
- for (const change of transactionChanges)
259
- fileCache.invalidate(change.file);
260
- if (transactionChanges.length)
261
- clearRoleStoreCache(selfAid);
262
- return {
263
- changed: nextRevision !== previousRevision,
264
- peerRevision: nextRevision,
265
- previousContactRevision: previousRevision,
266
- contact: next,
267
- };
215
+ return mutateContactBookLocked({ ...request, selfAid }, transactionChanges, deferUnobservedOwner);
268
216
  }
269
217
  finally {
270
218
  release();
271
219
  }
272
220
  }
273
- function mutateContactBookPreparedSyncInternal(selfAid, prepare) {
274
- const release = acquireAgentLock(selfAid);
221
+ /** The caller owns the contact lock; the entire critical section is synchronous. */
222
+ function mutateContactBookLocked(request, transactionChanges, deferUnobservedOwner = false) {
223
+ const selfAid = request.selfAid;
224
+ recoverMutation(selfAid);
225
+ const file = agentPeerConfig(selfAid);
226
+ const current = readContactBookFromDisk(selfAid);
227
+ const previousRevision = peerRevision(current);
228
+ if (request.expectedContactRevision !== undefined
229
+ && request.expectedContactRevision !== previousRevision) {
230
+ throw new PeerMutationError('CONFLICT', 'Contact book changed since it was read', {
231
+ expectedContactRevision: request.expectedContactRevision,
232
+ peerRevision: previousRevision,
233
+ });
234
+ }
235
+ validateTransactionChanges(selfAid, transactionChanges);
236
+ const next = cloneBook(current);
237
+ 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);
251
+ if (nextRevision === previousRevision && transactionChanges.length === 0) {
252
+ return { changed: false, peerRevision: previousRevision, previousContactRevision: previousRevision, contact: next };
253
+ }
254
+ const before = readTextOrNull(file);
255
+ const after = `${JSON.stringify(next, null, 2)}\n`;
256
+ const changes = [
257
+ ...(nextRevision === previousRevision ? [] : [{ file, before, after }]),
258
+ ...transactionChanges,
259
+ ];
260
+ writeJournal(selfAid, { schemaVersion: 1, state: 'prepared', selfAid, changes });
275
261
  try {
262
+ for (const change of changes)
263
+ applyTransactionChange(change);
264
+ writeJournal(selfAid, { schemaVersion: 1, state: 'committed', selfAid, changes });
265
+ removeJournal(selfAid);
266
+ }
267
+ catch (error) {
276
268
  recoverMutation(selfAid);
277
- const file = agentPeerConfig(selfAid);
278
- const current = readContactBookFromDisk(selfAid);
279
- const previousRevision = peerRevision(current);
280
- const next = cloneBook(current);
281
- const prepared = prepare({ contact: next, peerRevision: previousRevision });
282
- if (prepared.mutation)
283
- applyMutation(next, prepared.mutation, selfAid);
284
- synchronizeManagementRoles(next, selfAid, []);
285
- validateContactBook(next, selfAid);
286
- const nextRevision = peerRevision(next);
287
- if (nextRevision === previousRevision) {
288
- return {
289
- changed: false,
290
- peerRevision: previousRevision,
291
- previousContactRevision: previousRevision,
292
- contact: next,
293
- value: prepared.value,
294
- };
295
- }
296
- const preparedChanges = prepared.beforeCommit?.({
297
- contact: next,
298
- previousContactRevision: previousRevision,
299
- peerRevision: nextRevision,
300
- });
301
- const before = readTextOrNull(file);
302
- const after = `${JSON.stringify(next, null, 2)}\n`;
303
- const additionalChanges = preparedChanges === undefined
304
- ? []
305
- : Array.isArray(preparedChanges) ? preparedChanges : [preparedChanges];
306
- const changes = [
307
- { file, before, after },
308
- ...additionalChanges,
309
- ];
310
- validateTransactionChanges(selfAid, changes);
311
- writeJournal(selfAid, { schemaVersion: 1, state: 'prepared', selfAid, changes });
312
- try {
313
- for (const change of changes)
314
- applyTransactionChange(change);
315
- writeJournal(selfAid, { schemaVersion: 1, state: 'committed', selfAid, changes });
316
- removeJournal(selfAid);
317
- }
318
- catch (error) {
319
- recoverMutation(selfAid);
320
- throw error;
321
- }
269
+ throw error;
270
+ }
271
+ if (nextRevision !== previousRevision) {
322
272
  notifyConfigWrite(ConfigTarget.Peer, { self: selfAid });
323
- appendAudit(selfAid, {
324
- selfAid,
325
- actor: prepared.actor,
326
- mutation: prepared.mutation,
327
- }, previousRevision, nextRevision);
273
+ appendAudit(selfAid, request, previousRevision, nextRevision);
274
+ }
275
+ for (const change of transactionChanges)
276
+ fileCache.invalidate(change.file);
277
+ if (transactionChanges.length)
278
+ clearRoleStoreCache(selfAid);
279
+ return {
280
+ changed: nextRevision !== previousRevision,
281
+ peerRevision: nextRevision,
282
+ previousContactRevision: previousRevision,
283
+ contact: next,
284
+ };
285
+ }
286
+ /** The caller owns the contact lock; prepare and commit must not yield. */
287
+ function mutateContactBookPreparedLocked(selfAid, prepare) {
288
+ recoverMutation(selfAid);
289
+ const file = agentPeerConfig(selfAid);
290
+ const current = readContactBookFromDisk(selfAid);
291
+ const previousRevision = peerRevision(current);
292
+ const next = cloneBook(current);
293
+ const prepared = prepare({ contact: next, peerRevision: previousRevision });
294
+ if (prepared.mutation)
295
+ applyMutation(next, prepared.mutation, selfAid);
296
+ synchronizeManagementRoles(next, selfAid, []);
297
+ validateContactBook(next, selfAid);
298
+ const nextRevision = peerRevision(next);
299
+ if (nextRevision === previousRevision) {
328
300
  return {
329
- changed: true,
330
- peerRevision: nextRevision,
301
+ changed: false,
302
+ peerRevision: previousRevision,
331
303
  previousContactRevision: previousRevision,
332
304
  contact: next,
333
305
  value: prepared.value,
334
306
  };
335
307
  }
336
- finally {
337
- release();
308
+ const preparedChanges = prepared.beforeCommit?.({
309
+ contact: next,
310
+ previousContactRevision: previousRevision,
311
+ peerRevision: nextRevision,
312
+ });
313
+ const before = readTextOrNull(file);
314
+ const after = `${JSON.stringify(next, null, 2)}\n`;
315
+ const additionalChanges = preparedChanges === undefined
316
+ ? []
317
+ : Array.isArray(preparedChanges) ? preparedChanges : [preparedChanges];
318
+ const changes = [
319
+ { file, before, after },
320
+ ...additionalChanges,
321
+ ];
322
+ validateTransactionChanges(selfAid, changes);
323
+ writeJournal(selfAid, { schemaVersion: 1, state: 'prepared', selfAid, changes });
324
+ try {
325
+ for (const change of changes)
326
+ applyTransactionChange(change);
327
+ writeJournal(selfAid, { schemaVersion: 1, state: 'committed', selfAid, changes });
328
+ removeJournal(selfAid);
338
329
  }
330
+ catch (error) {
331
+ recoverMutation(selfAid);
332
+ throw error;
333
+ }
334
+ notifyConfigWrite(ConfigTarget.Peer, { self: selfAid });
335
+ appendAudit(selfAid, {
336
+ selfAid,
337
+ actor: prepared.actor,
338
+ mutation: prepared.mutation,
339
+ }, previousRevision, nextRevision);
340
+ return {
341
+ changed: true,
342
+ peerRevision: nextRevision,
343
+ previousContactRevision: previousRevision,
344
+ contact: next,
345
+ value: prepared.value,
346
+ };
339
347
  }
340
348
  function applyMutation(book, mutation, selfAid, changes = []) {
341
349
  if (mutation.type === 'replace') {
@@ -455,13 +463,14 @@ function applyMutation(book, mutation, selfAid, changes = []) {
455
463
  }
456
464
  throw new PeerMutationError('INVALID_MUTATION', `Unsupported Contact Book mutation: ${String(mutation?.type)}`);
457
465
  }
458
- function synchronizeManagementRoles(book, selfAid, changes) {
466
+ function synchronizeManagementRoles(book, selfAid, changes, deferUnobservedOwner = false) {
459
467
  const roles = managementRoleMapForAgent(selfAid, changes);
468
+ const ownershipPending = deferUnobservedOwner && ownerResolver.snapshot(selfAid).checkedAt === undefined;
460
469
  for (const [primaryId, entry] of Object.entries(book.contacts)) {
461
470
  book.contacts[primaryId] = compactEntry({
462
471
  ...entry,
463
472
  ...(roles[primaryId] === 'owner' ? { status: undefined, pendingRequest: undefined, declinedAt: undefined } : {}),
464
- managementRole: roles[primaryId],
473
+ managementRole: roles[primaryId] ?? (ownershipPending && entry.managementRole === 'owner' ? 'owner' : undefined),
465
474
  });
466
475
  }
467
476
  for (const [primaryId, managementRole] of Object.entries(roles)) {
@@ -570,6 +579,37 @@ function readTransactionJson(file, changes) {
570
579
  }
571
580
  }
572
581
  function acquireAgentLock(selfAid) {
582
+ const attempts = agentLockAttempts(selfAid);
583
+ for (;;) {
584
+ const attempt = attempts.next();
585
+ if (attempt.done)
586
+ return attempt.value;
587
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, attempt.value);
588
+ }
589
+ }
590
+ /** Wait asynchronously only while contended, then commit and release in the same turn. */
591
+ async function withAgentLock(selfAid, run) {
592
+ const attempts = agentLockAttempts(selfAid);
593
+ try {
594
+ for (;;) {
595
+ const attempt = attempts.next();
596
+ if (attempt.done) {
597
+ try {
598
+ return run();
599
+ }
600
+ finally {
601
+ attempt.value();
602
+ }
603
+ }
604
+ await waitForLock(attempt.value);
605
+ }
606
+ }
607
+ finally {
608
+ attempts.return(() => { });
609
+ }
610
+ }
611
+ /** Both entry points share publication, ownership, stale recovery and timeout rules. */
612
+ function* agentLockAttempts(selfAid) {
573
613
  const legacyLockDir = path.join(agentDir(selfAid), LOCK_NAME);
574
614
  const lockDir = resolveManagedLockPath('contact', selfAid, legacyLockDir);
575
615
  const ownerFile = path.join(lockDir, 'owner.json');
@@ -611,7 +651,7 @@ function acquireAgentLock(selfAid) {
611
651
  throw error;
612
652
  throw new PeerMutationError('LOCK_TIMEOUT', `Timed out waiting for contact mutation lock: ${lockDir}`);
613
653
  }
614
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS);
654
+ yield LOCK_RETRY_MS;
615
655
  }
616
656
  }
617
657
  }
@@ -15,6 +15,7 @@ import { isValidAid } from '../aun/aid/validation.js';
15
15
  import { getOwners, ownerResolver } from '../core/ownership/owner-resolver.js';
16
16
  import { sameOwnerQualification, sameOwnerRevision, requiresSameOwnerProof } from '../core/relation/same-owner-proof.js';
17
17
  import { readRoleStore } from './role-store.js';
18
+ import { isOwnerDirectoryContact } from '../directory/owner-directory-admission.js';
18
19
  export function isAuthenticated(userId) {
19
20
  return isValidAid(String(userId || '').trim());
20
21
  }
@@ -146,14 +147,33 @@ export function resolvePeerRoleDetail(ctx) {
146
147
  const winner = selectHighestRank(candidates, ctx.selfAid);
147
148
  if (winner)
148
149
  return resultFor(winner.role, winner.source, actor, ctx.selfAid);
149
- // Group members get the normal interactive member policy when no explicit
150
- // group/actor/default assignment exists. Private conversations retain the
151
- // read-only visitor fallback.
152
- const fallbackRole = ctx.chatType === 'group' ? 'member' : 'visitor';
150
+ // 没有显式 group/actor/default 指派时一律降级 visitor(只读):
151
+ // `member` 是联系人权限,不是缺省值。不在联系人里就是 visitor。
152
+ const fallbackRole = 'visitor';
153
153
  return roleRegistryExists(ctx.selfAid) && roleExists(fallbackRole, ctx.selfAid)
154
154
  ? resultFor(fallbackRole, 'builtin-fallback', actor, ctx.selfAid)
155
155
  : resultFor(null, 'none', actor, ctx.selfAid);
156
156
  }
157
+ /** 发送方与当前 Agent 的关系角色;群成员角色不替代直接关系。 */
158
+ export function resolveSenderRelationRole(input) {
159
+ try {
160
+ const detail = resolvePeerRoleDetail({
161
+ selfAid: input.selfAid,
162
+ channelKey: input.channelKey,
163
+ channelType: input.channelType,
164
+ chatType: input.chatType,
165
+ actorId: input.senderAid,
166
+ conversationId: input.conversationId ?? '',
167
+ });
168
+ if (detail && (detail.source === 'relation-actor' || detail.source === 'agent-owner'
169
+ || detail.source === 'internal-contact-default'))
170
+ return detail.effectiveRole ?? 'visitor';
171
+ return isOwnerDirectoryContact(input.selfAid, input.senderAid) ? 'member' : 'visitor';
172
+ }
173
+ catch {
174
+ return 'visitor';
175
+ }
176
+ }
157
177
  export function createSessionIdentityResolver(agentRegistry) {
158
178
  return (channel, userId, chatType, conversationId) => {
159
179
  const parsed = tryParseChannelKey(channel);