evolcore 0.0.41-test.2 → 0.0.42-test.0

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 (190) hide show
  1. package/CHANGELOG.md +38 -2
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -16,7 +16,7 @@ import { logger } from '../utils/logger.js';
16
16
  import { ErrorType } from '../utils/error-utils.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
18
  import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
19
- import { resolveEcagentConfig } from './baseagent.js';
19
+ import { resolveEcagentConfig, resolveRuntimeBaseagentModelSelection } from './baseagent.js';
20
20
  import { resolveProviderServiceForBaseagent } from '../config/providers.js';
21
21
  import { buildModelRequestHeaders } from './request-identity.js';
22
22
  import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
@@ -36,9 +36,15 @@ class AsyncEventQueue {
36
36
  values = [];
37
37
  waiters = [];
38
38
  ended = false;
39
+ dropped = 0;
40
+ endedAt;
41
+ get droppedCount() { return this.dropped; }
42
+ get closedAt() { return this.endedAt; }
39
43
  push(value) {
40
- if (this.ended)
44
+ if (this.ended) {
45
+ this.dropped++;
41
46
  return;
47
+ }
42
48
  const waiter = this.waiters.shift();
43
49
  if (waiter)
44
50
  waiter({ value, done: false });
@@ -49,6 +55,7 @@ class AsyncEventQueue {
49
55
  if (this.ended)
50
56
  return;
51
57
  this.ended = true;
58
+ this.endedAt = Date.now();
52
59
  for (const waiter of this.waiters.splice(0))
53
60
  waiter({ value: undefined, done: true });
54
61
  }
@@ -855,7 +862,14 @@ export class EcagentRunner {
855
862
  if (this.pendingInterrupts.get(key) === stream)
856
863
  this.pendingInterrupts.delete(key);
857
864
  }
858
- hasActiveStream(key) { return this.activeStreams.has(key) || !!this.runtimes.get(key)?.harness; }
865
+ hasActiveStream(key) { return this.getExecutionState(key) !== 'idle'; }
866
+ hasActiveOperation(sessionId) { return this.getExecutionState(sessionId) !== 'idle'; }
867
+ getExecutionState(sessionId) {
868
+ const runs = this.sessionRuns.get(sessionId);
869
+ if ([...(runs ?? [])].some(run => run.cancelled))
870
+ return 'interrupting';
871
+ return runs?.size || this.activeStreams.has(sessionId) || this.runtimes.get(sessionId)?.harness ? 'running' : 'idle';
872
+ }
859
873
  updateSessionId(sessionId, agentSessionId) {
860
874
  const previousRuntime = this.runtimes.get(sessionId);
861
875
  const applyLocal = () => {
@@ -913,6 +927,13 @@ export class EcagentRunner {
913
927
  lifecycle.done = run;
914
928
  this.sessionRunTails.set(sessionId, run);
915
929
  const release = () => {
930
+ if (queue.droppedCount > 0 || lifecycle.cancelled) {
931
+ logger.info('[EcagentRunner] Closed stream events retained in diagnostics', {
932
+ sessionId, taskId: modelOverride?.turn?.taskId, generation: modelOverride?.turn?.generation,
933
+ droppedEventCount: queue.droppedCount, cancelled: lifecycle.cancelled,
934
+ queueEndedAt: queue.closedAt, runSettledAt: Date.now(),
935
+ });
936
+ }
916
937
  runs.delete(lifecycle);
917
938
  if (this.sessionRuns.get(sessionId) === runs && runs.size === 0)
918
939
  this.sessionRuns.delete(sessionId);
@@ -990,19 +1011,47 @@ export class EcagentRunner {
990
1011
  throw new Error('ecagent run interrupted');
991
1012
  }
992
1013
  harness.on('tool_call', async (event, signal) => {
1014
+ const cancelledDecision = () => ({
1015
+ block: true, reason: '工具调用已取消',
1016
+ details: { cancelled: true, blockedByHook: false, abortSource: lifecycle.cancelled ? 'runner_interrupt' : 'abort_signal', decisionSource: 'infrastructure' },
1017
+ });
993
1018
  if (lifecycle.cancelled || signal?.aborted)
994
- return { block: true, reason: '工具调用已取消' };
1019
+ return cancelledDecision();
995
1020
  const pauseController = this.permissionContexts.get(request.sessionId)?.pauseController;
996
1021
  if (pauseController) {
997
1022
  const pauseResult = await pauseController.waitAtToolBoundary(signal);
998
1023
  if (pauseResult === 'cancelled')
999
- return { block: true, reason: '工具调用已取消' };
1024
+ return cancelledDecision();
1000
1025
  }
1001
1026
  const decision = await this.authorizeTool(request.sessionId, request.projectPath, permissionMode, event.toolName, event.input, stats.numTurns + 1);
1002
- return lifecycle.cancelled || signal?.aborted ? { block: true, reason: '工具调用已取消' } : decision;
1027
+ const cancelled = lifecycle.cancelled || signal?.aborted;
1028
+ const result = decision.block
1029
+ ? { ...decision, details: { ...decision.details, ...(cancelled ? { cancelled: true, abortSource: lifecycle.cancelled ? 'runner_interrupt' : 'abort_signal' } : {}) } }
1030
+ : cancelled ? cancelledDecision() : decision;
1031
+ logger.info('[EcagentRunner] Tool authorization', {
1032
+ sessionId: request.sessionId, taskId: request.modelOverride?.turn?.taskId,
1033
+ generation: request.modelOverride?.turn?.generation, callId: event.toolCallId, toolName: event.toolName,
1034
+ decision: result.block ? 'deny' : 'allow', reason: result.reason, ...result.details,
1035
+ });
1036
+ return result;
1003
1037
  });
1004
1038
  let inputAccepted = false;
1005
1039
  const unsubscribe = harness.subscribe(event => {
1040
+ if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
1041
+ logger.info('[EcagentRunner] Tool lifecycle', {
1042
+ sessionId: request.sessionId, taskId: request.modelOverride?.turn?.taskId,
1043
+ generation: request.modelOverride?.turn?.generation, callId: event.toolCallId,
1044
+ toolName: event.toolName, phase: event.type, cancelled: lifecycle.cancelled,
1045
+ ...(event.type === 'tool_execution_end' ? {
1046
+ isError: event.isError, executed: event.result?.details?.executed,
1047
+ executionState: event.result?.details?.executionState,
1048
+ blockedByHook: event.result?.details?.blockedByHook,
1049
+ policyCode: event.result?.details?.policyCode,
1050
+ reason: typeof event.result?.details?.reason === 'string' ? event.result.details.reason.slice(0, 512) : undefined,
1051
+ abortSource: event.result?.details?.abortSource,
1052
+ } : {}),
1053
+ });
1054
+ }
1006
1055
  // The harness persists a user message before publishing message_end.
1007
1056
  // Failures in createTurnState/before_agent_start must leave context pending.
1008
1057
  if (!inputAccepted && event.type === 'message_end' && event.message.role === 'user') {
@@ -1225,10 +1274,19 @@ export class EcagentRunner {
1225
1274
  return;
1226
1275
  }
1227
1276
  if (event.type === 'tool_execution_end') {
1277
+ const details = event.result?.details ?? {};
1228
1278
  queue.push({
1229
1279
  type: 'tool_result', name: event.toolName, result: extractToolResult(event.result),
1230
1280
  isError: event.isError, error: event.isError ? extractToolResult(event.result) : undefined,
1231
1281
  callId: event.toolCallId,
1282
+ ...(details.blockedByHook ? {
1283
+ decision: 'deny', decisionSource: details.decisionSource ?? 'runner',
1284
+ policyCode: details.policyCode, reason: details.reason, executed: false, executionState: 'blocked',
1285
+ } : details.cancelled ? {
1286
+ decision: 'error', decisionSource: 'infrastructure', executed: details.executed === true, executionState: 'interrupted',
1287
+ errorCode: 'EXECUTION_FAILED', errorDetailCode: 'OPERATION_ABORTED',
1288
+ } : {}),
1289
+ ...(details.cancelled ? { cancelled: true, abortSource: details.abortSource } : {}),
1232
1290
  });
1233
1291
  return;
1234
1292
  }
@@ -1264,6 +1322,16 @@ export class EcagentRunner {
1264
1322
  };
1265
1323
  }
1266
1324
  async authorizeTool(sessionId, projectPath, mode, toolName, input, turn) {
1325
+ const decision = await this.evaluateToolPermission(sessionId, projectPath, mode, toolName, input, turn);
1326
+ return decision.block ? {
1327
+ ...decision,
1328
+ details: {
1329
+ decision: 'deny', decisionSource: 'policy', executed: false, executionState: 'blocked',
1330
+ blockedByHook: true, reason: decision.reason, ...decision.details,
1331
+ },
1332
+ } : decision;
1333
+ }
1334
+ async evaluateToolPermission(sessionId, projectPath, mode, toolName, input, turn) {
1267
1335
  const permissionContext = this.permissionContexts.get(sessionId);
1268
1336
  try {
1269
1337
  await assertOwnershipAuthorization(permissionContext);
@@ -1316,7 +1384,7 @@ export class EcagentRunner {
1316
1384
  const descriptionCheck = checkBashDescription(toolName, input);
1317
1385
  if (descriptionCheck) {
1318
1386
  await recordBlockedOperation(descriptionCheck.policyCode);
1319
- return { block: true, reason: descriptionCheck.message };
1387
+ return { block: true, reason: descriptionCheck.message, details: { policyCode: descriptionCheck.policyCode } };
1320
1388
  }
1321
1389
  }
1322
1390
  if (mode === 'fullaccess') {
@@ -1330,12 +1398,12 @@ export class EcagentRunner {
1330
1398
  if (decision.allow)
1331
1399
  return {};
1332
1400
  await recordBlockedOperation(decision.code);
1333
- return { block: true, reason: decision.reason };
1401
+ return { block: true, reason: decision.reason, details: { policyCode: decision.code } };
1334
1402
  }
1335
1403
  const policy = permissionContext?.policyHook?.(toolName, input, { turn });
1336
1404
  if (policy?.block) {
1337
1405
  await recordBlockedOperation(policy.policyCode ?? 'session_policy_hook');
1338
- return { block: true, reason: policy.reason || '当前会话策略拒绝此工具调用' };
1406
+ return { block: true, reason: policy.reason || '当前会话策略拒绝此工具调用', details: { policyCode: policy.policyCode ?? 'session_policy_hook' } };
1339
1407
  }
1340
1408
  const preflight = evaluateToolPreflight(toolName, input, {
1341
1409
  sessionId,
@@ -1352,7 +1420,7 @@ export class EcagentRunner {
1352
1420
  if (preflight.policyCode) {
1353
1421
  await recordBlockedOperation(preflight.policyCode, input, preflight.matchedPath);
1354
1422
  }
1355
- return { block: true, reason: preflight.message };
1423
+ return { block: true, reason: preflight.message, details: { policyCode: preflight.policyCode } };
1356
1424
  }
1357
1425
  if (preflight.behavior === 'allow')
1358
1426
  return {};
@@ -1378,7 +1446,7 @@ export class EcagentRunner {
1378
1446
  }
1379
1447
  const prompt = permissionContext?.sendPrompt ?? this.sendPromptFn;
1380
1448
  const decision = await requestDangerousCommandPermission(this.permissionGateway, sessionId, toolName, checkedInput, prompt, permissionContext, `ecagent:${mode}`, mode);
1381
- return decision.matched && decision.decision === 'deny' ? { block: true, reason: '危险操作未获人工批准' } : {};
1449
+ return decision.matched && decision.decision === 'deny' ? { block: true, reason: '危险操作未获人工批准', details: { decisionSource: 'approval' } } : {};
1382
1450
  }
1383
1451
  async interrupt(sessionKey) {
1384
1452
  this.permissionContexts.get(sessionKey)?.pauseController?.cancel();
@@ -1616,11 +1684,12 @@ export class EcagentAgentPlugin {
1616
1684
  return false;
1617
1685
  }
1618
1686
  }
1619
- createAgent(agent, callbacks) {
1687
+ async createAgent(agent, callbacks) {
1620
1688
  const override = agent.config.baseagents?.ecagent;
1621
1689
  if (!override)
1622
1690
  return null;
1623
- const configured = { ...override };
1691
+ const selection = await resolveRuntimeBaseagentModelSelection('ecagent', override);
1692
+ const configured = { ...override, model: selection.model };
1624
1693
  const resolved = resolveEcagentConfig({ agents: { ecagent: configured } }, configured);
1625
1694
  return { evolagentName: agent.name, baseagent: 'ecagent', agent: new EcagentRunner(resolved, callbacks, { agentAid: agent.aid }) };
1626
1695
  }
@@ -4,6 +4,7 @@ import path from 'path';
4
4
  import { parseDocument } from 'yaml';
5
5
  import { validateAgentMdDocument } from '@agentunion/fastaun';
6
6
  import { getAidStore, loadAid, SLOT } from './store.js';
7
+ import { isValidAid } from './identity.js';
7
8
  import { agentMdPath, aidLocalDir, resolveRoot } from '../../paths.js';
8
9
  export const DEFAULT_AGENT_DESCRIPTION = 'EvolCore AI agent.';
9
10
  /**
@@ -57,32 +58,16 @@ export function validateAgentTag(tag) {
57
58
  }
58
59
  return null;
59
60
  }
60
- /**
61
- * Validate an agent.md tags value. Count constraints are optional because
62
- * existing published agent.md files may contain fewer than three tags.
63
- */
64
- export function validateAgentTags(tags, options = {}) {
61
+ /** Validate an agent.md tags value: each tag's charset and length, no count constraint. */
62
+ export function validateAgentTags(tags) {
65
63
  if (!Array.isArray(tags))
66
64
  return ['must be an array of strings'];
67
65
  const errors = [];
68
- const normalized = new Set();
69
66
  tags.forEach((tag, index) => {
70
67
  const error = validateAgentTag(tag);
71
- if (error) {
68
+ if (error)
72
69
  errors.push(`tag ${index + 1} ${error}`);
73
- return;
74
- }
75
- const value = tag.trim();
76
- normalized.add(value);
77
70
  });
78
- const minCount = options.minCount;
79
- const maxCount = options.maxCount;
80
- if (minCount !== undefined && normalized.size < minCount) {
81
- errors.push(`must contain at least ${minCount} unique tags`);
82
- }
83
- if (maxCount !== undefined && normalized.size > maxCount) {
84
- errors.push(`must contain at most ${maxCount} unique tags`);
85
- }
86
71
  return errors;
87
72
  }
88
73
  function resolveAgentMdAunPath(opts) {
@@ -280,6 +265,27 @@ export function invalidateAgentDisplayName(aid, aunPath) {
280
265
  displayNameRevision.set(key, (displayNameRevision.get(key) ?? 0) + 1);
281
266
  }
282
267
  }
268
+ export function buildOwnershipStatement(ownerAid, subAid, relationVersion = 1, now = Math.trunc(Date.now() / 1000)) {
269
+ const owner = ownerAid?.trim();
270
+ const sub = subAid?.trim();
271
+ if (!owner)
272
+ throw new Error('owner AID is required for an ownership statement');
273
+ if (!sub)
274
+ throw new Error('sub AID is required for an ownership statement');
275
+ if (!Number.isSafeInteger(relationVersion) || relationVersion < 1) {
276
+ throw new Error(`ownership relation_version must be a positive integer: ${relationVersion}`);
277
+ }
278
+ return {
279
+ version: 2,
280
+ declaration_id: crypto.randomUUID(),
281
+ owner_aid: owner,
282
+ sub_aid: sub,
283
+ relation_version: relationVersion,
284
+ declared_at: now,
285
+ };
286
+ }
287
+ /** Types that must not carry owner/ownership per the agent.md schema. */
288
+ const NO_OWNERSHIP_TYPES = new Set(['human', 'group', 'org']);
283
289
  export function buildInitialAgentMd(opts) {
284
290
  const agentName = opts.name?.trim() || opts.aid.split('.')[0];
285
291
  // 未指定类型时用 DEFAULT_AGENT_TYPE(agent);指定了就必须落在 AGENT_TYPES 白名单内。
@@ -295,7 +301,20 @@ export function buildInitialAgentMd(opts) {
295
301
  if (tagErrors.length > 0)
296
302
  throw new Error(`Invalid agent.md tags: ${tagErrors.join('; ')}`);
297
303
  const tags = [...new Set(rawTags.map(tag => tag.trim()))];
298
- return `---\naid: ${yamlDoubleQuote(opts.aid)}\nname: ${yamlDoubleQuote(agentName)}\ntype: ${yamlDoubleQuote(agentType)}\nversion: "1.0.0"\ndescription: ${yamlDoubleQuote(description)}\ntags:\n${tags.map(tag => ` - ${yamlDoubleQuote(tag)}\n`).join('')}---\n`;
304
+ const owner = opts.owner?.trim();
305
+ if (owner && NO_OWNERSHIP_TYPES.has(agentType)) {
306
+ throw new Error(`agent.md type "${agentType}" must not declare owner or ownership`);
307
+ }
308
+ const statement = opts.ownershipStatement ?? (owner ? buildOwnershipStatement(owner, opts.aid) : undefined);
309
+ if (statement && !owner)
310
+ throw new Error('ownership statement requires an owner AID');
311
+ if (statement && (statement.owner_aid !== owner || statement.sub_aid !== opts.aid)) {
312
+ throw new Error('ownership statement identity must match the agent.md owner and AID');
313
+ }
314
+ const ownershipBlock = statement
315
+ ? `owner: ${yamlDoubleQuote(statement.owner_aid)}\nownership:\n statement:\n version: 2\n declaration_id: ${yamlDoubleQuote(statement.declaration_id)}\n owner_aid: ${yamlDoubleQuote(statement.owner_aid)}\n sub_aid: ${yamlDoubleQuote(statement.sub_aid)}\n relation_version: ${statement.relation_version}\n declared_at: ${statement.declared_at}\n`
316
+ : '';
317
+ return `---\naid: ${yamlDoubleQuote(opts.aid)}\nname: ${yamlDoubleQuote(agentName)}\ntype: ${yamlDoubleQuote(agentType)}\n${ownershipBlock}version: "1.0.0"\ndescription: ${yamlDoubleQuote(description)}\ntags:\n${tags.map(tag => ` - ${yamlDoubleQuote(tag)}\n`).join('')}---\n`;
299
318
  }
300
319
  function ensureTrailingNewline(content) {
301
320
  return content.endsWith('\n') ? content : `${content}\n`;
@@ -310,7 +329,7 @@ function yamlDoubleQuote(value) {
310
329
  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
311
330
  }
312
331
  /** Validate the gateway-facing agent.md frontmatter before signing or upload. */
313
- export function validateAgentMdFrontmatter(content, expectedAid) {
332
+ export function validateAgentMdFrontmatter(content, expectedAid, options = {}) {
314
333
  const errors = [];
315
334
  const payload = stripAgentMdSignature(content);
316
335
  const payloadBytes = Buffer.byteLength(payload, 'utf8');
@@ -389,6 +408,60 @@ export function validateAgentMdFrontmatter(content, expectedAid) {
389
408
  errors.push(`agent.md frontmatter tags ${tagErrors.join('; ')}`);
390
409
  }
391
410
  }
411
+ // 0.5.28: 上传方向 schema 对齐
412
+ // human 身份禁止出现 Ownership 相关字段(含空值/null)
413
+ // 普通非 human、非 group/org 上传前必须有 owner 字段
414
+ const agentType = typeof values.type === 'string' ? values.type : undefined;
415
+ if (agentType === 'human') {
416
+ for (const forbidden of ['owner', 'ownership', 'ownership_proof', 'ownership_release']) {
417
+ if (values[forbidden] !== undefined && values[forbidden] !== null) {
418
+ errors.push(`agent.md frontmatter "${forbidden}" must not appear in human agent documents`);
419
+ }
420
+ }
421
+ }
422
+ else if (agentType && agentType !== 'group' && agentType !== 'org') {
423
+ if (!values['owner'] && !options.allowUnowned) {
424
+ errors.push('agent.md frontmatter "owner" is required for non-human agents before upload');
425
+ }
426
+ else if (values['owner'] && (values['ownership'] === undefined || values['ownership'] === null)) {
427
+ // Ownership 2.1:nameplate 里出现 owner 就必须同时给出 ownership.statement,
428
+ // 只写 owner 会被 SDK 的 validateOwnershipAgentFrontmatter 拒绝。
429
+ errors.push('agent.md frontmatter "ownership.statement" is required when "owner" is declared');
430
+ }
431
+ }
432
+ const ownership = values['ownership'];
433
+ if (ownership !== undefined && ownership !== null) {
434
+ const statement = ownership?.['statement'];
435
+ if (!statement || typeof statement !== 'object' || Array.isArray(statement)) {
436
+ errors.push('agent.md frontmatter ownership.statement must be a mapping');
437
+ }
438
+ else {
439
+ const s = statement;
440
+ if (s.version !== 2)
441
+ errors.push('agent.md ownership.statement.version must be integer 2');
442
+ if (typeof s.declaration_id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.declaration_id)) {
443
+ errors.push('agent.md ownership.statement.declaration_id must be a lowercase UUIDv4');
444
+ }
445
+ if (typeof s.owner_aid !== 'string' || !isValidAid(s.owner_aid)) {
446
+ errors.push('agent.md ownership.statement.owner_aid must be a complete AID');
447
+ }
448
+ if (typeof s.sub_aid !== 'string' || !isValidAid(s.sub_aid)) {
449
+ errors.push('agent.md ownership.statement.sub_aid must be a complete AID');
450
+ }
451
+ if (typeof s.relation_version !== 'number' || !Number.isSafeInteger(s.relation_version) || s.relation_version < 1) {
452
+ errors.push('agent.md ownership.statement.relation_version must be a positive integer');
453
+ }
454
+ if (typeof s.declared_at !== 'number' || !Number.isSafeInteger(s.declared_at) || s.declared_at < 1) {
455
+ errors.push('agent.md ownership.statement.declared_at must be a positive integer');
456
+ }
457
+ if (typeof values['owner'] === 'string' && typeof s.owner_aid === 'string' && values['owner'] !== s.owner_aid) {
458
+ errors.push('agent.md ownership.statement.owner_aid must match the owner field');
459
+ }
460
+ if (aid && typeof s.sub_aid === 'string' && s.sub_aid !== aid) {
461
+ errors.push('agent.md ownership.statement.sub_aid must match the AID');
462
+ }
463
+ }
464
+ }
392
465
  return { valid: errors.length === 0, errors };
393
466
  }
394
467
  /**
@@ -717,12 +790,16 @@ export async function agentmdPut(content, opts) {
717
790
  return withAgentMdWriteLock(lockKey, () => publishAgentMd(content, opts));
718
791
  }
719
792
  /**
720
- * Apply the creation form's profile to the card produced by the SDK's initial
721
- * Owner binding. Ownership declarations are SDK output: never reconstruct them
722
- * from the form or replace the owned card with an unowned initial template.
793
+ * Apply a profile to an SDK-owned card. Ownership declarations are SDK output:
794
+ * never reconstruct them from the form or replace the owned card with an
795
+ * unowned template. Existing relation versions are preserved during updates.
723
796
  */
724
797
  export async function agentmdPutInitializationProfile(content, opts) {
725
- const validation = validateAgentMdFrontmatter(content, opts.aid);
798
+ const ownerAid = opts.ownerAid.trim().toLowerCase();
799
+ // The form is a profile draft, not the document sent to the gateway. It is
800
+ // intentionally allowed to omit ownership; the signed remote card below is
801
+ // the only source for the immutable owner/ownership block.
802
+ const validation = validateAgentMdFrontmatter(content, opts.aid, { allowUnowned: true });
726
803
  if (!validation.valid) {
727
804
  throw new Error(`invalid agent.md frontmatter: ${validation.errors.join('; ')}`);
728
805
  }
@@ -744,8 +821,10 @@ export async function agentmdPutInitializationProfile(content, opts) {
744
821
  const { frontmatter } = validateAgentMdDocument(payload, { expectedAid: opts.aid, forUpload: true });
745
822
  const ownership = frontmatter.ownership;
746
823
  const statement = ownership?.statement;
747
- if (frontmatter.owner !== opts.ownerAid || statement?.owner_aid !== opts.ownerAid
748
- || statement.sub_aid !== opts.aid || statement.relation_version !== 1) {
824
+ if (frontmatter.owner !== ownerAid || statement?.owner_aid !== ownerAid
825
+ || statement.sub_aid !== opts.aid
826
+ || typeof statement.relation_version !== 'number' || !Number.isSafeInteger(statement.relation_version)
827
+ || statement.relation_version < 1) {
749
828
  throw Object.assign(new Error('Initial agent.md ownership no longer matches the creation'), { code: 'INITIALIZE_OWNER_CONFLICT' });
750
829
  }
751
830
  const version = current.remoteVersion;
@@ -39,7 +39,7 @@ export function suppressSdkLogs() {
39
39
  };
40
40
  }
41
41
  // ==================== SDK package ====================
42
- export const MIN_AUN_CORE_SDK = [0, 5, 28];
42
+ export const MIN_AUN_CORE_SDK = [0, 5, 29];
43
43
  export const AUN_CORE_SDK_PKG = '@agentunion/fastaun';
44
44
  function compareVersion(a, min) {
45
45
  const parts = a.split('.').map(n => parseInt(n, 10));
@@ -2,7 +2,7 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { parseDocument } from 'yaml';
5
- import { aidCreate } from './index.js';
5
+ import { aidCreateIdentityOnly } from './index.js';
6
6
  import { DEFAULT_AID_DOMAIN, normalizeAidDomain } from './domain.js';
7
7
  import { getAidStore, loadClient, SLOT } from './store.js';
8
8
  import { LocalTokenStore, validateAgentMdDocument, verifyAgentMdUpload, } from '@agentunion/fastaun';
@@ -10,7 +10,7 @@ import { AUN_KEYSTORE_ENCRYPTION_SEED } from './encryption-seed-policy.js';
10
10
  import { isValidAid } from './validation.js';
11
11
  import { agentMdPath, resolvePaths } from '../../paths.js';
12
12
  import { PeerIdentityCache } from '../../core/relation/peer-identity.js';
13
- import { agentmdPut, buildInitialAgentMd, invalidateAgentDisplayName, stripAgentMdSignature } from './agentmd.js';
13
+ import { agentmdPutInitializationProfile, buildInitialAgentMd, invalidateAgentDisplayName, stripAgentMdSignature } from './agentmd.js';
14
14
  import { logger, logOwnershipEvent } from '../../utils/logger.js';
15
15
  const MAX_ATTEMPTS = 5;
16
16
  export { DEFAULT_AID_DOMAIN } from './domain.js';
@@ -52,7 +52,7 @@ function readJsonFile(filePath) {
52
52
  return undefined;
53
53
  }
54
54
  }
55
- function hasCanonicalControlFrontmatter(content, aid, name, aunRoot) {
55
+ function hasCanonicalControlFrontmatter(content, aid, name, aunRoot, ownerAid) {
56
56
  try {
57
57
  // A frontmatter-only match is insufficient here: an unsigned or malformed
58
58
  // local card must be republished so the SDK can produce a valid signature.
@@ -76,6 +76,13 @@ function hasCanonicalControlFrontmatter(content, aid, name, aunRoot) {
76
76
  && values.type.trim().toLowerCase() === 'host';
77
77
  if (!canonical)
78
78
  return false;
79
+ const owner = typeof values.owner === 'string' ? values.owner.trim().toLowerCase() : '';
80
+ const statement = values.ownership?.statement;
81
+ if (!owner || ownerAid && owner !== ownerAid.toLowerCase()
82
+ || statement?.owner_aid !== owner || statement.sub_aid !== aid
83
+ || typeof statement.relation_version !== 'number' || !Number.isSafeInteger(statement.relation_version)
84
+ || statement.relation_version < 1)
85
+ return false;
79
86
  // The SDK validator checks that a signature block is well formed, but it
80
87
  // deliberately does not verify the signature against the local cert.
81
88
  // A damaged or stale control card must be republished, otherwise peers
@@ -135,7 +142,7 @@ export async function ensureControlAgentMd(aid, opts = {}) {
135
142
  catch { /* missing */ }
136
143
  const metadata = readJsonFile(metadataPath);
137
144
  const remoteMissing = String(metadata?.remote_status ?? '').trim().toLowerCase() === 'missing';
138
- const canonical = !!existing && hasCanonicalControlFrontmatter(existing, normalizedAid, name, aunRoot);
145
+ const canonical = !!existing && hasCanonicalControlFrontmatter(existing, normalizedAid, name, aunRoot, opts.ownerAid);
139
146
  const needsPublish = !canonical || remoteMissing;
140
147
  let hadOwnershipFields;
141
148
  if (existing) {
@@ -169,7 +176,33 @@ export async function ensureControlAgentMd(aid, opts = {}) {
169
176
  tags: CONTROL_AGENT_TAGS,
170
177
  });
171
178
  try {
172
- await agentmdPut(content, { aid: normalizedAid, store: opts.store, aunPath: aunRoot });
179
+ const existingOwner = (() => {
180
+ if (!existing)
181
+ return undefined;
182
+ try {
183
+ const frontmatter = stripAgentMdSignature(existing).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
184
+ if (!frontmatter)
185
+ return undefined;
186
+ const fields = parseDocument(frontmatter).toJS();
187
+ const value = typeof fields?.owner === 'string' ? fields.owner.trim().toLowerCase() : '';
188
+ return isValidAid(value) ? value : undefined;
189
+ }
190
+ catch {
191
+ return undefined;
192
+ }
193
+ })();
194
+ const ownerAid = opts.ownerAid ?? existingOwner;
195
+ if (ownerAid) {
196
+ await agentmdPutInitializationProfile(content, {
197
+ aid: normalizedAid,
198
+ ownerAid,
199
+ store: opts.store,
200
+ aunPath: aunRoot,
201
+ });
202
+ }
203
+ else {
204
+ throw Object.assign(new Error('control AID Owner is unavailable; refusing to publish an unowned host agent.md'), { code: 'CONTROL_OWNER_REQUIRED' });
205
+ }
173
206
  logOwnershipEvent('control.card.published', diagnostic);
174
207
  }
175
208
  catch (error) {
@@ -281,15 +314,15 @@ export async function generateControlAid(aidDomain, options = {}) {
281
314
  continue;
282
315
  }
283
316
  try {
284
- const created = await aidCreate(candidate, {
317
+ // Register the identity without an Owner. fastaun 0.5.29's
318
+ // AIDStore.register({ owner }) submits a bind request internally;
319
+ // init has its own durable, observable bind submission and must not
320
+ // create a second invitation. The caller publishes the Ownership
321
+ // card after that explicit submission.
322
+ const created = await aidCreateIdentityOnly(candidate, {
285
323
  type: 'host', ...(options.silent ? { silent: true } : {}),
286
324
  });
287
- try {
288
- await ensureControlAgentMd(created.aid, { store: created.store });
289
- }
290
- catch (e) {
291
- logger.warn(`[control-aid] ${created.aid} agent.md 发布失败(控制面可继续,后续启动会重试): ${e instanceof Error ? e.message : String(e)}`);
292
- }
325
+ logger.info(`[control-aid] ${created.aid} 已注册,等待 Owner 绑定后发布 host agent.md`);
293
326
  // 清理 aidCreate 内部另开的 client/store——关闭失败不可丢弃已注册的 AID(否则下次 init
294
327
  // 会把它当冲突,白白消耗一次重试)。close 异常降级为 warn。
295
328
  try {
@@ -398,6 +431,25 @@ export async function submitControlAidRegistration(aid, owner, options = {}) {
398
431
  connection_kind: 'short', short_ttl_ms: 30_000, auto_reconnect: false, background_sync: false,
399
432
  connect_timeout: 10, call_timeout: 10,
400
433
  }));
434
+ // fastaun 0.5.29 may have submitted a registration-time bind in older
435
+ // callers. Reconcile the live projection before creating another task.
436
+ // A pending single-sided declaration is already an accepted invitation;
437
+ // its operation ID is not recoverable from the SDK, so report submitted
438
+ // without sending a duplicate request.
439
+ const current = await bounded(client.checkOwnershipConsensus(aid, true));
440
+ if (current.status === 'consensus' && current.sub_aid === aid && current.owner_aid === ownerAid) {
441
+ return result('already_bound');
442
+ }
443
+ if (current.status === 'single_sided' && current.sub_aid === aid
444
+ && current.owner_md?.owner_aid === ownerAid && current.relation_version === 1 && current.lock === 'unlocked') {
445
+ return result('submitted');
446
+ }
447
+ if (current.status === 'unavailable' || current.status === 'invalid' || current.status === 'not_applicable') {
448
+ return result('unknown', {
449
+ code: current.code ?? 'BIND_STATE_UNAVAILABLE',
450
+ message: current.reason ?? `Ownership status is ${current.status}`,
451
+ });
452
+ }
401
453
  task = await bounded(client.bindOwneraid(ownerAid));
402
454
  if (task.operation !== 'bind' || task.sub_aid !== aid || task.owner_aid !== ownerAid
403
455
  || task.new_owner_aid !== undefined || !REGISTRATION_OPERATION_ID.test(task.operation_id)
@@ -409,7 +461,7 @@ export async function submitControlAidRegistration(aid, owner, options = {}) {
409
461
  if (task.status === 'completed') {
410
462
  let consensus;
411
463
  try {
412
- consensus = await bounded(client.checkOwnershipConsensus(aid));
464
+ consensus = await bounded(client.checkOwnershipConsensus(aid, true));
413
465
  }
414
466
  catch (error) {
415
467
  return result('unknown', {