evolcore 0.0.43-test.2 → 0.0.43-test.4

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 (173) hide show
  1. package/CHANGELOG.md +44 -1
  2. package/bin/ecmsg.js +229 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +0 -37
  10. package/dist/agents/ecagent-runner.js +138 -36
  11. package/dist/aun/aid/agentmd.js +52 -13
  12. package/dist/aun/menu/client.js +8 -7
  13. package/dist/aun/menu/index.js +1 -1
  14. package/dist/aun/menu/transport.js +8 -5
  15. package/dist/aun/msg/p2p.js +4 -2
  16. package/dist/aun/service-proxy.js +3 -0
  17. package/dist/channels/aun.js +105 -53
  18. package/dist/channels/daemon.js +14 -2
  19. package/dist/cli/agent-command.js +5 -0
  20. package/dist/cli/agent-create.js +31 -11
  21. package/dist/cli/agent.js +9 -3
  22. package/dist/cli/aun-commands.js +19 -21
  23. package/dist/cli/daemon-commands.js +30 -18
  24. package/dist/cli/directory.js +98 -56
  25. package/dist/cli/getmeta-command.js +2 -1
  26. package/dist/cli/index.js +1 -1
  27. package/dist/cli/init.js +13 -5
  28. package/dist/cli/peer.js +2 -1
  29. package/dist/cli/task-context.js +3 -1
  30. package/dist/cli/trigger-command.js +20 -14
  31. package/dist/config/access-policy.js +0 -1
  32. package/dist/config/boot-log.js +12 -2
  33. package/dist/config/builtin-role-templates.js +2 -2
  34. package/dist/config/builtin-roles.js +2 -1
  35. package/dist/config/config-field-policy.js +7 -0
  36. package/dist/config/config-manager.js +30 -10
  37. package/dist/config/peer-role-resolver.js +23 -1
  38. package/dist/config/role-schema.js +25 -1
  39. package/dist/config/role-service.js +9 -4
  40. package/dist/config/role-store.js +30 -8
  41. package/dist/config/schema-migration.js +121 -0
  42. package/dist/core/agent-application-service.js +11 -0
  43. package/dist/core/agent-ipc-registration.js +2 -0
  44. package/dist/core/agent-runtime.js +41 -9
  45. package/dist/core/auth/auth-gateway.js +14 -4
  46. package/dist/core/auth/operation-authorizer.js +19 -1
  47. package/dist/core/auth/operation-catalog.js +12 -2
  48. package/dist/core/baseagent-loader.js +11 -3
  49. package/dist/core/bootstrap-service.js +8 -0
  50. package/dist/core/channel-loader.js +61 -23
  51. package/dist/core/channel-runtime.js +5 -0
  52. package/dist/core/command/agent-control.js +5 -2
  53. package/dist/core/command/agentmd-menu-request.js +50 -0
  54. package/dist/core/command/agentmd-menu.js +156 -0
  55. package/dist/core/command/chatmode-config.js +46 -0
  56. package/dist/core/command/command-handler.js +44 -17
  57. package/dist/core/command/daemon-diagnostics.js +2 -1
  58. package/dist/core/command/menu-catalog.js +14 -1
  59. package/dist/core/command/menu-handler.js +74 -24
  60. package/dist/core/command/menu-protocol.js +8 -0
  61. package/dist/core/command/role-menu.js +23 -9
  62. package/dist/core/command/slash-handler.js +52 -47
  63. package/dist/core/daemon-lifecycle.js +43 -17
  64. package/dist/core/event-catalog.js +19 -0
  65. package/dist/core/evolagent-registry.js +3 -0
  66. package/dist/core/evolagent.js +5 -4
  67. package/dist/core/ipc-registration.js +6 -0
  68. package/dist/core/lifecycle-notice.js +185 -0
  69. package/dist/core/message/aun-ipc-sender.js +30 -24
  70. package/dist/core/message/contact-admission.js +1 -19
  71. package/dist/core/message/im-renderer.js +81 -40
  72. package/dist/core/message/message-admission.js +21 -62
  73. package/dist/core/message/message-bridge.js +18 -5
  74. package/dist/core/message/message-utils.js +9 -0
  75. package/dist/core/message/peer-mode.js +16 -8
  76. package/dist/core/message/response-engine.js +67 -47
  77. package/dist/core/model/model-capabilities.js +37 -0
  78. package/dist/core/model/model-catalog.js +6 -2
  79. package/dist/core/ownership/owner-resolver.js +74 -36
  80. package/dist/core/permission/ec-command-parser.js +62 -13
  81. package/dist/core/plugin-lifecycle.js +6 -2
  82. package/dist/core/relation/pa-team.js +132 -0
  83. package/dist/core/role/runtime-policy.js +4 -3
  84. package/dist/core/thread/thread-service.js +6 -4
  85. package/dist/directory/owner-directory-admission.js +0 -3
  86. package/dist/directory/owner-directory-cache.js +201 -17
  87. package/dist/directory/owner-directory-markdown.js +44 -21
  88. package/dist/directory/owner-directory-policy.js +1 -1
  89. package/dist/directory/owner-directory-query-operation.js +218 -98
  90. package/dist/directory/owner-directory-request-operation.js +76 -0
  91. package/dist/directory/owner-directory-scope.js +35 -4
  92. package/dist/directory/owner-directory-search.js +76 -23
  93. package/dist/directory/owner-directory-store.js +5 -38
  94. package/dist/directory/owner-directory-text.js +60 -0
  95. package/dist/eck/kit-renderer.js +6 -3
  96. package/dist/eck/message-renderer.js +2 -5
  97. package/dist/ecweb/message-context-service.js +4 -0
  98. package/dist/ecweb/runtime/lifecycle.js +29 -5
  99. package/dist/ecweb/runtime/supervisor.js +83 -27
  100. package/dist/index.js +209 -38
  101. package/dist/paths.js +4 -2
  102. package/dist/product.js +1 -0
  103. package/dist/proxy/service-supervisor.js +377 -141
  104. package/dist/response-system/engines/v1/index.js +2 -4
  105. package/dist/response-system/modes/single-session/index.js +1 -1
  106. package/dist/trigger/audit.js +3 -2
  107. package/dist/trigger/authorization.js +2 -3
  108. package/dist/trigger/history.js +4 -3
  109. package/dist/trigger/ipc-service.js +24 -19
  110. package/dist/trigger/manager.js +3 -5
  111. package/dist/trigger/parser.js +4 -21
  112. package/dist/trigger/patch.js +3 -15
  113. package/dist/trigger/scheduler.js +53 -13
  114. package/dist/trigger/validation.js +0 -13
  115. package/dist/utils/error-utils.js +15 -5
  116. package/dist/utils/macos-autostart.js +31 -0
  117. package/dist/utils/model-prices.jsonl +15 -8
  118. package/dist/utils/process-introspect.js +21 -1
  119. package/dist/utils/startup-trace.js +7 -1
  120. package/dist/utils/windows-autostart.js +1 -0
  121. package/ecagent/README.md +18 -0
  122. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  123. package/ecagent/dist/harness/agent-harness.js +24 -8
  124. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  125. package/ecagent/dist/harness/compaction/compaction.js +7 -4
  126. package/ecagent/dist/harness/types.d.ts +1 -0
  127. package/kits/docs/channels/aun.md +1 -1
  128. package/kits/docs/context-assembly.md +1 -1
  129. package/kits/docs/evolcore/INDEX.md +5 -2
  130. package/kits/docs/evolcore/directory.md +125 -35
  131. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  132. package/kits/docs/evolcore/file-navigation.md +279 -0
  133. package/kits/docs/evolcore/menu-protocol.md +1 -0
  134. package/kits/docs/evolcore/model.md +5 -3
  135. package/kits/docs/evolcore/msg.md +1 -0
  136. package/kits/docs/evolcore/peer.md +2 -1
  137. package/kits/docs/evolcore/response.md +4 -2
  138. package/kits/docs/evolcore/task.md +2 -0
  139. package/kits/docs/evolcore/thread-chain.md +1 -1
  140. package/kits/docs/evolcore/tool-authorization.md +4 -1
  141. package/kits/docs/evolcore/trigger.md +10 -7
  142. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  143. package/kits/eck_manifest.json +6 -23
  144. package/kits/eck_manifest.memory.json +26 -1
  145. package/kits/rules/01-overview.md +42 -44
  146. package/kits/rules/02-navigation.md +44 -53
  147. package/kits/rules/03-identity.md +21 -25
  148. package/kits/rules/04-relation.md +23 -33
  149. package/kits/rules/05-venue.md +24 -25
  150. package/kits/schemas/_meta.json +10 -10
  151. package/kits/schemas/agent-config.schema.19.json +10 -6
  152. package/kits/schemas/relation-config.schema.12.json +2 -2
  153. package/kits/schemas/role-config.schema.2.json +5 -5
  154. package/kits/schemas/role-registry.schema.1.json +3 -2
  155. package/kits/skills/ec-service-proxy/SKILL.md +10 -0
  156. package/kits/skills/ec-trigger/SKILL.md +1 -1
  157. package/kits/templates/soul/00-GUIDE.md +20 -42
  158. package/kits/templates/system-fragments/channel.md +2 -2
  159. package/kits/templates/system-fragments/commands.md +1 -1
  160. package/kits/templates/system-fragments/directory-contacts.md +1 -1
  161. package/kits/templates/system-fragments/identity.md +0 -1
  162. package/kits/templates/system-fragments/personal-assistant.md +2 -17
  163. package/kits/templates/system-fragments/reply.md +7 -0
  164. package/kits/templates/system-fragments/session.md +6 -2
  165. package/package.json +18 -13
  166. package/dist/eck/paactive-context.js +0 -45
  167. package/dist/response-system/engines/v1/paactive-flow.js +0 -18
  168. package/kits/eck_manifest.paactive.json +0 -528
  169. package/kits/eck_message_manifest.paactive.json +0 -233
  170. package/kits/templates/message-fragments/paactive/item.md +0 -3
  171. package/kits/templates/system-fragments/paactive/channel.md +0 -25
  172. package/kits/templates/system-fragments/paactive/reply.md +0 -25
  173. package/kits/templates/system-fragments/paactive/session.md +0 -32
@@ -5,12 +5,14 @@ import { resolvePaths } from '../paths.js';
5
5
  import { ConfigError } from './config-manager.js';
6
6
  import { firstConfiguredOwner } from './owner-config.js';
7
7
  import { resolveLegacyBaseagentModelSelection } from '../agents/baseagent.js';
8
+ import { loadSchema } from './schema-registry.js';
8
9
  const MIGRATION_KIND = {
9
10
  'auxiliary-model-v1': 'auxiliary-model',
10
11
  'agent-only-model-v1': 'agent-only-model',
11
12
  'agent-model-provider-v1': 'agent-only-model',
12
13
  'provider-service-type-v1': 'provider-service-type',
13
14
  'relation-config-v11-v1': 'agent-only-model',
15
+ 'published-schema-consolidation-v1': 'agent-only-model',
14
16
  'legacy-model-selection-v1': 'agent-only-model',
15
17
  'access-policy-v17-v1': 'agent-only-model',
16
18
  'peer-file-v1': 'agent-only-model',
@@ -1542,6 +1544,125 @@ export async function ensureRelationConfigVersionMigrationOnStartup() {
1542
1544
  throw new ConfigError('RELATION_CONFIG_VERSION_MIGRATION_FAILED', `Automatic relation-config version migration failed: ${detail}`, { cause: error });
1543
1545
  }
1544
1546
  }
1547
+ // ── Published schema consolidation: retired v20/v13 → v19/v12 ───────────────
1548
+ /**
1549
+ * The unpublished v20/v13 schemas only split the group-chatmode consolidation
1550
+ * from v19/v12. Once those files were removed, persisted configs created in
1551
+ * the short release window must be restamped before the contact-book startup
1552
+ * gate decides they are an unknown future format.
1553
+ */
1554
+ const PUBLISHED_SCHEMA_CONSOLIDATIONS = [
1555
+ { logicalName: 'agent-config', from: 20, to: 19 },
1556
+ { logicalName: 'relation-config', from: 13, to: 12 },
1557
+ ];
1558
+ function restampPublishedSchemaConsolidation(value, file, consolidation) {
1559
+ if (value.$schema_version !== consolidation.from)
1560
+ return null;
1561
+ const next = { ...value, $schema_version: consolidation.to };
1562
+ const schema = loadSchema(consolidation.logicalName, consolidation.to);
1563
+ if (!schema.validate(next)) {
1564
+ const detail = (schema.validate.errors ?? [])
1565
+ .map(error => `${error.instancePath || '/'} ${error.message}`)
1566
+ .join('; ');
1567
+ throw new Error(`${file}: retired ${consolidation.logicalName} schema v${consolidation.from} `
1568
+ + `is not compatible with published v${consolidation.to}: ${detail}`);
1569
+ }
1570
+ return next;
1571
+ }
1572
+ function planPublishedSchemaConsolidationMigration(home) {
1573
+ const changes = [];
1574
+ const summary = {
1575
+ agentsScanned: 0,
1576
+ relationsScanned: 0,
1577
+ filesRestamped: 0,
1578
+ };
1579
+ const agentsRoot = path.join(home, 'agents');
1580
+ if (!fs.existsSync(agentsRoot))
1581
+ return { home, changes, summary };
1582
+ const agentConsolidation = PUBLISHED_SCHEMA_CONSOLIDATIONS[0];
1583
+ const relationConsolidation = PUBLISHED_SCHEMA_CONSOLIDATIONS[1];
1584
+ for (const entry of fs.readdirSync(agentsRoot, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
1585
+ if (!entry.isDirectory() || !validAid(entry.name))
1586
+ continue;
1587
+ const directory = path.join(agentsRoot, entry.name);
1588
+ const agentFile = path.join(directory, 'config.json');
1589
+ if (fs.existsSync(agentFile)) {
1590
+ summary.agentsScanned += 1;
1591
+ let parsed;
1592
+ try {
1593
+ parsed = readJson(agentFile);
1594
+ }
1595
+ catch {
1596
+ continue;
1597
+ }
1598
+ if (isRecord(parsed.value)) {
1599
+ const next = restampPublishedSchemaConsolidation(parsed.value, agentFile, agentConsolidation);
1600
+ if (next) {
1601
+ changes.push({ file: agentFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1602
+ summary.filesRestamped += 1;
1603
+ }
1604
+ }
1605
+ }
1606
+ for (const relationFile of walkRelationConfigs(path.join(directory, 'relations'))) {
1607
+ summary.relationsScanned += 1;
1608
+ let parsed;
1609
+ try {
1610
+ parsed = readJson(relationFile);
1611
+ }
1612
+ catch {
1613
+ continue;
1614
+ }
1615
+ if (!isRecord(parsed.value))
1616
+ continue;
1617
+ const next = restampPublishedSchemaConsolidation(parsed.value, relationFile, relationConsolidation);
1618
+ if (!next)
1619
+ continue;
1620
+ changes.push({ file: relationFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1621
+ summary.filesRestamped += 1;
1622
+ }
1623
+ }
1624
+ return { home, changes, summary };
1625
+ }
1626
+ export function runPublishedSchemaConsolidationMigration(options = {}) {
1627
+ const id = 'published-schema-consolidation-v1';
1628
+ const home = path.resolve(options.home || resolvePaths().root);
1629
+ const release = acquireLock(home, id);
1630
+ try {
1631
+ assertDaemonStopped(home);
1632
+ recoverJournal(home, id);
1633
+ const plan = planPublishedSchemaConsolidationMigration(home);
1634
+ const backup = options.apply ? applyMigration(plan, id) : null;
1635
+ return {
1636
+ ok: true,
1637
+ mode: options.apply ? 'applied' : 'dry-run',
1638
+ home,
1639
+ changedFiles: plan.changes.length,
1640
+ backup,
1641
+ summary: plan.summary,
1642
+ };
1643
+ }
1644
+ finally {
1645
+ release();
1646
+ }
1647
+ }
1648
+ export async function ensurePublishedSchemaConsolidationMigrationOnStartup() {
1649
+ const home = resolvePaths().root;
1650
+ try {
1651
+ const result = runPublishedSchemaConsolidationMigration({ home, apply: true });
1652
+ if (result.changedFiles === 0)
1653
+ return null;
1654
+ return {
1655
+ mode: 'applied',
1656
+ changedFiles: result.changedFiles,
1657
+ backup: result.backup,
1658
+ summary: result.summary,
1659
+ };
1660
+ }
1661
+ catch (error) {
1662
+ const detail = error instanceof Error ? error.message : String(error);
1663
+ throw new ConfigError('PUBLISHED_SCHEMA_CONSOLIDATION_MIGRATION_FAILED', `Automatic published schema consolidation failed: ${detail}`, { cause: error });
1664
+ }
1665
+ }
1545
1666
  // ── Agent 消息准入重写:v16 → v17 → v18 ──────────────────────────────────────
1546
1667
  const ACCESS_POLICY_TARGET_VERSION = 18;
1547
1668
  /**
@@ -181,6 +181,7 @@ export class AgentApplicationService {
181
181
  }
182
182
  async load(aid) {
183
183
  try {
184
+ await this.deps.beforeAgentOperation?.(aid);
184
185
  assertAgentAidAvailable(aid);
185
186
  await this.deps.hotLoad(aid);
186
187
  return { ok: true, aid };
@@ -191,6 +192,7 @@ export class AgentApplicationService {
191
192
  }
192
193
  async reload(aid, options = {}) {
193
194
  try {
195
+ await this.deps.beforeAgentOperation?.(aid);
194
196
  if (!aid) {
195
197
  if (options.force) {
196
198
  return { ok: false, code: 'INVALID_ARGS', error: '--force requires a target Agent AID' };
@@ -207,6 +209,7 @@ export class AgentApplicationService {
207
209
  }
208
210
  async resync() {
209
211
  try {
212
+ await this.deps.beforeAgentOperation?.();
210
213
  return { ok: true, results: await this.deps.resync() };
211
214
  }
212
215
  catch (error) {
@@ -237,6 +240,7 @@ export class AgentApplicationService {
237
240
  }
238
241
  async setConfig(aid, key, rawValue) {
239
242
  try {
243
+ await this.deps.beforeAgentOperation?.(aid);
240
244
  initConfigManager();
241
245
  const resolved = resolveConfigCommand(['config', 'set', key, rawValue, '--self', aid]);
242
246
  if (!resolved.ok)
@@ -269,6 +273,7 @@ export class AgentApplicationService {
269
273
  async setEnabled(aid, enabled, force) {
270
274
  let config;
271
275
  try {
276
+ await this.deps.beforeAgentOperation?.(aid);
272
277
  if (enabled)
273
278
  assertAgentAidAvailable(aid);
274
279
  config = loadAgent(aid);
@@ -315,6 +320,12 @@ export class AgentApplicationService {
315
320
  return { ok: true, aid, enabled, reloaded: result.ok };
316
321
  }
317
322
  async delete(aid, purge = false) {
323
+ try {
324
+ await this.deps.beforeAgentOperation?.(aid);
325
+ }
326
+ catch (error) {
327
+ return errorFrom(error);
328
+ }
318
329
  await this.initialization?.cancel(aid);
319
330
  const paths = resolvePaths();
320
331
  const agentDir = path.join(paths.agentsDir, aid);
@@ -304,6 +304,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
304
304
  aid,
305
305
  project: value('--project'),
306
306
  baseagent: value('--baseagent'),
307
+ provider: value('--provider'),
307
308
  ...ownerOptions,
308
309
  name: value('--name'),
309
310
  description: value('--description'),
@@ -322,6 +323,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
322
323
  aid: plan.aid,
323
324
  project: plan.project,
324
325
  baseagent: plan.baseagent,
326
+ provider: plan.provider,
325
327
  owner: plan.owner,
326
328
  name: plan.name,
327
329
  description: plan.description,
@@ -50,16 +50,44 @@ export function loadStartupAgentRegistry(agentRegistry) {
50
50
  }
51
51
  return { primaryAgent, runtimeStatus };
52
52
  }
53
- export async function createStartupAgentRunners({ agentRegistry, agentLoader, sessionManager, primaryAgent, }) {
53
+ export async function createStartupAgentRunners({ agentRegistry, agentLoader, sessionManager, primaryAgent, agentInstances: publishedInstances, agentMap: publishedMap, configureInstances, isCancelled, onAgentCreated, }) {
54
54
  const creationErrors = [];
55
- const agentInstances = await agentLoader.createAll(agentRegistry, {
55
+ const agentInstances = publishedInstances ?? [];
56
+ const agentMap = publishedMap ?? new Map();
57
+ const primaryBaseagent = primaryAgent?.baseagent ?? 'claude';
58
+ const createdInstances = await agentLoader.createAll(agentRegistry, {
56
59
  onSessionIdUpdate: async (sessionId, agentSessionId, context) => (await sessionManager.updateAgentSessionIdBySessionId(sessionId, agentSessionId, context?.turn)),
57
- }, creationErrors);
58
- const agentMap = new Map();
59
- for (const instance of agentInstances) {
60
- agentMap.set(`${instance.evolagentName}::${instance.baseagent}`, instance.agent);
60
+ }, creationErrors, async (agent, instances, timing) => {
61
+ if (isCancelled?.()) {
62
+ await disposeAgentInstances(instances);
63
+ await onAgentCreated?.(agent, [], timing);
64
+ return;
65
+ }
66
+ try {
67
+ configureInstances?.(instances);
68
+ }
69
+ catch (error) {
70
+ await disposeAgentInstances(instances);
71
+ throw error;
72
+ }
73
+ agentInstances.push(...instances);
74
+ for (const instance of instances) {
75
+ agentMap.set(`${instance.evolagentName}::${instance.baseagent}`, instance.agent);
76
+ }
77
+ if (primaryAgent?.aid === agent.aid
78
+ ? !instances.some(instance => instance.baseagent === primaryBaseagent)
79
+ : !instances.some(instance => instance.baseagent === agent.baseagent)) {
80
+ const errors = creationErrors.filter(error => error.evolagentName === agent.name);
81
+ agent.status = 'error';
82
+ agent.error = errors.length > 0
83
+ ? errors.map(({ baseagent, message }) => `${baseagent}: ${message}`).join('; ')
84
+ : `No agent runner created for ${agent.aid}::${primaryAgent?.aid === agent.aid ? primaryBaseagent : agent.baseagent}`;
85
+ }
86
+ await onAgentCreated?.(agent, instances, timing);
87
+ }, () => !isCancelled?.());
88
+ if (!isCancelled?.()) {
89
+ agentInstances.splice(0, agentInstances.length, ...createdInstances);
61
90
  }
62
- const primaryBaseagent = primaryAgent?.baseagent ?? 'claude';
63
91
  const primaryRunnerKey = primaryAgent ? `${primaryAgent.aid}::${primaryBaseagent}` : '<empty>::claude';
64
92
  const agentRunner = primaryAgent ? agentMap.get(primaryRunnerKey) : agentInstances[0]?.agent;
65
93
  let runtimeError;
@@ -105,7 +133,7 @@ export async function completeStartupAgentRuntime(agentRegistry, current) {
105
133
  }
106
134
  return current;
107
135
  }
108
- export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionManager, agentMap, permissionGateway, processor, channelLoader, channelInstances, registerChannelInstance, unregisterRuntimeChannel, markChannelConnected, bootstrapService, aidStatsCollector, handoffRuntime, messageQueue, }) {
136
+ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionManager, agentMap, permissionGateway, processor, channelLoader, channelInstances, registerChannelInstance, unregisterRuntimeChannel, markChannelConnected, bootstrapService, aidStatsCollector, handoffRuntime, messageQueue, awaitStartupAgent, }) {
109
137
  const reloadHooks = buildReloadHooks({
110
138
  channelLoader,
111
139
  channelInstances,
@@ -161,6 +189,7 @@ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionMa
161
189
  return createRunnerReloadTransaction({ aid: candidate.aid, agentMap, staged, onDisposeError });
162
190
  },
163
191
  });
192
+ reloadHooks.beforeAgentOperation = async (aid) => { await awaitStartupAgent?.(aid); };
164
193
  const reloadOwnedMutes = new Set();
165
194
  const reloadCoordinator = new AgentReloadCoordinator({
166
195
  registry: agentRegistry,
@@ -185,7 +214,8 @@ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionMa
185
214
  await new Promise(resolve => setTimeout(resolve, 25));
186
215
  }
187
216
  },
188
- acquireWorkGate: aid => {
217
+ acquireWorkGate: async (aid) => {
218
+ await awaitStartupAgent?.(aid);
189
219
  const agentName = agentRegistry.get(aid)?.name;
190
220
  if (!agentName)
191
221
  return;
@@ -521,6 +551,8 @@ const AUDITED_WORKFLOW_SHA256 = {
521
551
  '0.5.28': 'cd736d1fcce0812013ba7d7c2148f86c8f3d3d2d39e451e52a0f9cc2a4d4fb51',
522
552
  '0.5.29': '24ac11a456607019dbbf5e7d247f4632520d7bd70bf0e49d4efa36d2898e7648',
523
553
  '0.5.30': '4f63c8116035ec509ffea67dd0a8fc3f0300a78ba89eefdd8c65af6d9da91517',
554
+ '0.5.31': 'c37811b6b589166b3fc90d51707572ca09d0253db593832add489dec0026a0e3',
555
+ '0.5.32': '7333bede3bb0a5dc5cd7e500dc2c91d23c5c772590659540c640d5f6eabc2f1d',
524
556
  };
525
557
  export function initializationBindPreflightFailure(error) {
526
558
  if (!(error instanceof Error) || error.code !== 'ECONNRESET')
@@ -8,6 +8,7 @@ import { ownerResolver, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AG
8
8
  import { getOperationMeta } from './operation-catalog.js';
9
9
  import { constrainRuntimePermissionMode, resolveRuntimePermissionMode } from '../role/runtime-policy.js';
10
10
  import { buildAuthorizationEventKey } from '../audit/event-key.js';
11
+ import { preparePaTeamQualification, paTeamQualification, requiresPaTeamVerification } from '../relation/pa-team.js';
11
12
  export function isCrossAgentTriggerOperationAllowed(input) {
12
13
  return input.control || input.daemonOwner === true || input.taskAgentAid === input.targetAgentAid;
13
14
  }
@@ -41,7 +42,10 @@ export function buildAuthSubject(input) {
41
42
  actor: roleDetail.actor,
42
43
  processOwners,
43
44
  }));
44
- const suppliedRole = input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
45
+ const internalContactContext = roleDetail.source === 'internal-contact-default'
46
+ || (input.channelType === 'aun' && chatType === 'private' && input.selfAid && actorId
47
+ && (paTeamQualification(input.selfAid, actorId) === 'matched' || requiresPaTeamVerification(input.selfAid, actorId)));
48
+ const suppliedRole = !internalContactContext && input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
45
49
  const role = suppliedRole ?? roleDetail.effectiveRole ?? 'none';
46
50
  const processRole = isFullAccessRun
47
51
  ? 'fullaccess-run'
@@ -111,16 +115,21 @@ export async function authorizeFreshOperation(params) {
111
115
  && ['owner', 'owners'].includes(configCommand.field.split('.')[0]);
112
116
  const force = changesOwner || ['ec.aid.bind', 'ec.aid.unbind', 'ec.aid.transfer']
113
117
  .includes(params.intent.operation) || params.intent.operation === 'config.restore';
118
+ const forceAgentMdEditor = params.source === 'menu'
119
+ && ['ec.aid.agentmd.get', 'ec.aid.agentmd.put'].includes(params.intent.operation);
114
120
  const operation = getOperationMeta(params.intent.operation);
115
121
  const sensitive = force || params.intent.dangerous || operation?.dangerous || operation?.category !== 'read'
116
122
  || configCommand?.dangerous || subject.processRole === 'fullaccess-run';
117
123
  try {
124
+ if (subject.channelType === 'aun' && subject.chatType === 'private') {
125
+ await preparePaTeamQualification(subject.selfAid, subject.actorId);
126
+ }
118
127
  await refreshOwnershipForAuthorization(subject.selfAid, {
119
- force,
128
+ force: force || forceAgentMdEditor,
120
129
  ...(sensitive ? {} : { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS }),
121
130
  includeDaemon: subject.isDaemonOwner || subject.processRole === 'fullaccess-run'
122
131
  || params.intent.scope === 'process' || params.intent.scope === 'control' || force,
123
- allowTransient: !force,
132
+ allowTransient: !force && !forceAgentMdEditor,
124
133
  });
125
134
  const targetAid = operation?.authorizationTarget === 'same-owner-agent'
126
135
  && subject.processRole !== 'fullaccess-run'
@@ -143,7 +152,8 @@ export async function authorizeFreshOperation(params) {
143
152
  channel: subject.channel, channelType: subject.channelType, channelId: subject.channelId,
144
153
  chatType: subject.chatType, conversationId: subject.conversationId,
145
154
  fromControlChannel: subject.fromControlChannel,
146
- identity: subject.role === 'owner' && subject.principalId ? undefined : subject.identity,
155
+ identity: subject.roleSource === 'internal-contact-default' || (subject.role === 'owner' && subject.principalId)
156
+ ? undefined : subject.identity,
147
157
  });
148
158
  if (subject.processRole === 'fullaccess-run') {
149
159
  if (!subject.authorizedBy || !ownerResolver.daemonOwners().includes(subject.authorizedBy)) {
@@ -111,6 +111,23 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
111
111
  if (!opMeta) {
112
112
  return denyDecision(ctx, 'NOT_ALLOWED', `Unknown operation: ${operation}`, operation, intent.scope);
113
113
  }
114
+ // The App editor is narrower than public Agent-tool reads and daemon management.
115
+ // No configured role, control token or daemon Owner may impersonate the protocol Owner.
116
+ if (['ec.aid.agentmd.get', 'ec.aid.agentmd.put'].includes(operation) && ctx.source !== 'agent-tool') {
117
+ const view = ctx.selfAid ? ownerResolver.snapshot(ctx.selfAid) : undefined;
118
+ const c = view?.consensus;
119
+ const target = intent.args.aid ?? intent.args.targetAgentAid ?? ctx.selfAid;
120
+ const allowed = ctx.source === 'menu' && intent.scope === 'agent' && ctx.chatType === 'private'
121
+ && !ctx.fromControlChannel && target === ctx.selfAid
122
+ && !!ctx.principalId && ctx.actorId === ctx.principalId
123
+ && view?.consensusStatus === 'consensus' && !view.refreshFailure
124
+ && c?.status === 'consensus' && c.sub_aid === ctx.selfAid && c.lock === 'locked'
125
+ && Number.isSafeInteger(c.relation_version) && c.relation_version > 0
126
+ && ownerResolver.owner(ctx.selfAid) === ctx.principalId && c.owner_aid === ctx.principalId;
127
+ return allowed
128
+ ? { allow: true, operation, scope: intent.scope, role, dangerous: opMeta.dangerous, matchedRule: 'agentmd-protocol-owner' }
129
+ : denyDecision(ctx, 'NOT_ALLOWED', 'AgentMD editor requires the current protocol Owner on its Agent channel', operation, intent.scope, opMeta.dangerous);
130
+ }
114
131
  if (isFieldConfigOperation(operation) && !resolvedConfigCommand) {
115
132
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation is required', operation, intent.scope, opMeta.dangerous);
116
133
  }
@@ -678,7 +695,8 @@ function checkConstraints(ctx, constraints, resolvedConfigCommand) {
678
695
  if (constraints.privateOnly && ctx.chatType !== 'private') {
679
696
  return { ok: false, reason: 'This command is only allowed in private chats' };
680
697
  }
681
- if (constraints.groupOnly && ctx.chatType !== 'group') {
698
+ if (constraints.groupOnly && ctx.chatType !== 'group'
699
+ && ctx.role !== 'owner' && ctx.role !== 'admin') {
682
700
  const target = stringArg(ctx.intent.args.targetId) ?? stringArg(ctx.intent.args.peer) ?? '<unknown>';
683
701
  const sameGroup = constraints.currentRelationOnly ? ' and may only target that same group' : '';
684
702
  return {
@@ -169,6 +169,16 @@ const OPERATIONS = [
169
169
  authorizationTarget: 'same-owner-agent',
170
170
  authorizationPolicy: { authority: 'agent-owner', permissionMode: 'bypass', mode: 'require' },
171
171
  },
172
+ {
173
+ id: 'ec.directory.request',
174
+ category: 'write-own',
175
+ dangerous: false,
176
+ defaultScopes: ['agent'],
177
+ description: 'Send an encrypted app-v1 friend invitation to a target AID',
178
+ sources: ['agent-tool'],
179
+ authorizationTarget: 'current-agent',
180
+ authorizationPolicy: { authority: 'agent-owner', permissionMode: 'bypass', mode: 'require' },
181
+ },
172
182
  ...PROVIDER_OPERATIONS,
173
183
  {
174
184
  id: 'proxy.read',
@@ -1279,7 +1289,7 @@ const OPERATIONS = [
1279
1289
  dangerous: false,
1280
1290
  defaultScopes: ['relation', 'agent'],
1281
1291
  description: 'Read and verify a public Agent agent.md',
1282
- sources: ['agent-tool'],
1292
+ sources: ['agent-tool', 'menu'],
1283
1293
  },
1284
1294
  {
1285
1295
  id: 'ec.aid.agentmd.put',
@@ -1287,7 +1297,7 @@ const OPERATIONS = [
1287
1297
  dangerous: true,
1288
1298
  defaultScopes: ['agent'],
1289
1299
  description: 'Sign and publish the current Agent local agent.md',
1290
- sources: ['agent-tool'],
1300
+ sources: ['agent-tool', 'menu'],
1291
1301
  minimumPermissionMode: 'request',
1292
1302
  authorizationTarget: 'current-agent',
1293
1303
  },
@@ -24,7 +24,10 @@ async function mapWithConcurrency(items, limit, fn) {
24
24
  results[index] = await fn(items[index], index);
25
25
  }
26
26
  });
27
- await Promise.all(workers);
27
+ const outcomes = await Promise.allSettled(workers);
28
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected');
29
+ if (failed)
30
+ throw failed.reason;
28
31
  return results;
29
32
  }
30
33
  /** Agent Loader — produces one runner per (EvolAgent × baseagent). */
@@ -41,14 +44,19 @@ export class AgentLoader {
41
44
  * Iterate over all EvolAgents in the registry × all registered plugins.
42
45
  * Each successful (agent, plugin) pair yields one runner instance.
43
46
  */
44
- async createAll(registry, callbacks, creationErrors) {
47
+ async createAll(registry, callbacks, creationErrors, onAgentCreated, shouldCreateAgent = () => true) {
45
48
  const instances = [];
46
49
  const allAgents = registry.runnableAgents();
47
50
  // 各 agent 的 runner 创建互不共享状态(每个 plugin 只读自己的 config,
48
51
  // 结果写回各自的 instances 数组),串行只会把 21 个 agent 的创建时间叠加起来。
49
52
  // 限并发而不是 Promise.all:codex 插件在缓存未命中时会拉起外部进程,全量并发会
50
53
  // 在同一瞬间抢占 CPU。顺序按 allAgents 保持,输出与串行一致。
51
- const created = await mapWithConcurrency(allAgents, 4, (agent) => this.createForAgent(agent, callbacks, creationErrors));
54
+ const created = await mapWithConcurrency(allAgents, 4, async (agent) => {
55
+ const startedAtMs = Date.now();
56
+ const instances = shouldCreateAgent() ? await this.createForAgent(agent, callbacks, creationErrors) : [];
57
+ await onAgentCreated?.(agent, instances, { startedAtMs, completedAtMs: Date.now() });
58
+ return instances;
59
+ });
52
60
  for (const agentInstances of created)
53
61
  instances.push(...agentInstances);
54
62
  return instances;
@@ -35,6 +35,14 @@ export async function completeBootstrapWithWelcome(service, aid, welcome, sessio
35
35
  error: `Fresh Ownership consensus is required before activating ${aid}`,
36
36
  };
37
37
  }
38
+ // `bootstrapWelcome: false` 的 agent 不发首次欢迎消息,只走上下线通知。
39
+ // 这类 agent 由别的 agent 调度使用(PA 团队成员),给 Owner 逐个发自我介绍是噪音。
40
+ // 归属共识检查仍然要做——不发的只是消息,不是审批。
41
+ const skipWelcome = config?.bootstrapWelcome === false;
42
+ if (skipWelcome) {
43
+ const result = service.completeBootstrap(aid, { allowSuppliedOwnerPending: suppliedOwnerPending });
44
+ return { ...result, reloaded: true, welcomeQueued: false };
45
+ }
38
46
  const deliveries = owners.length ? postBootstrapWelcomeStatus(aid, owners).deliveries : [];
39
47
  const alreadyPrepared = deliveries.length > 0 && deliveries.every(delivery => delivery.status !== 'not_prepared');
40
48
  if (config?.initialization?.mode !== 'supplied' && !alreadyPrepared) {
@@ -9,6 +9,14 @@ import { logger } from '../utils/logger.js';
9
9
  import { assertAgentAidAvailable } from '../config/config-manager.js';
10
10
  import { PluginHandle } from './plugin-lifecycle.js';
11
11
  import { ContactBindRegistry } from './contact-bind-registry.js';
12
+ /**
13
+ * 进程退出时给 AUN 渠道的 WebSocket 关闭握手留的时间。
14
+ *
15
+ * SDK 的 `client.close()` 要等服务端回 close 帧才算完(实测 2.4s),而 daemon 关完
16
+ * 渠道就 `exit(0)`,没等完的 socket 本来就随进程消失。100ms 足够让正常握手把帧发出去,
17
+ * 等不到就直接放手。
18
+ */
19
+ const CLOSE_HANDSHAKE_BUDGET_MS = 100;
12
20
  function isMissingChannelDependency(error) {
13
21
  const code = error?.code;
14
22
  return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND';
@@ -20,8 +28,8 @@ export function resolveShowActivities(inst) {
20
28
  }
21
29
  /**
22
30
  * showMiddleResult / showIdleMonitor 策略。
23
- * show_activities 对 interactive/paactive 私聊中间输出生效:
24
- * all → 文本 + activity;text → 仅文本;none → 全部静默。
31
+ * 默认策略:私聊使用 mode,群聊使用 none。
32
+ * 响应引擎优先使用显式 show_activities 配置,再回退到本策略。
25
33
  */
26
34
  export function middleOutputModePolicy(mode, chatType, _identity) {
27
35
  if (chatType !== 'private')
@@ -200,7 +208,7 @@ export class ChannelLoader {
200
208
  return null;
201
209
  }
202
210
  let teardown;
203
- const lifecycle = new PluginHandle(`${ctx.agentName}::${inst.name}`, () => teardown?.());
211
+ const lifecycle = new PluginHandle(`${ctx.agentName}::${inst.name}`, (budgetMs) => teardown?.(budgetMs));
204
212
  try {
205
213
  const runtime = await plugin.createInstance(inst, { ...ctx, lifecycle });
206
214
  if (!runtime) {
@@ -213,12 +221,12 @@ export class ChannelLoader {
213
221
  const connect = runtime.connect.bind(runtime);
214
222
  runtime.lifecycle = lifecycle;
215
223
  entry.runtime = runtime;
216
- runtime.disconnect = () => {
224
+ runtime.disconnect = (clientCloseBudgetMs) => {
217
225
  if (inst.type === 'aun' || (snapshot.status !== 'failed' && snapshot.status !== 'unavailable')) {
218
226
  snapshot.status = 'disconnected';
219
227
  delete snapshot.reason;
220
228
  }
221
- return lifecycle.dispose().catch(error => {
229
+ return lifecycle.dispose({ teardownBudgetMs: clientCloseBudgetMs }).catch(error => {
222
230
  snapshot.status = 'failed';
223
231
  snapshot.reason = { code: 'DISCONNECT_FAILED', message: '渠道资源清理失败' };
224
232
  throw error;
@@ -270,42 +278,71 @@ export class ChannelLoader {
270
278
  throw error;
271
279
  }
272
280
  }
273
- async connectAll(instances, { concurrency = 3, intervalMs = 50, onConnected, onFailed } = {}) {
281
+ async connectAll(instances, { concurrency = 3, intervalMs = 50, beforeConnect, shouldConnect, onConnected, onFailed } = {}) {
274
282
  const connected = [];
275
283
  const failed = [];
276
284
  const inflight = new Set();
277
- for (const inst of instances) {
278
- while (inflight.size >= concurrency) {
279
- await Promise.race(inflight);
285
+ const reportFailure = (inst, error) => {
286
+ failed.push({ name: inst.adapter.channelName, error });
287
+ logger.warn(`[connectAll] ${inst.adapter.channelName} connect failed: ${error}`);
288
+ if (onFailed) {
289
+ void Promise.resolve().then(() => onFailed(inst, error)).catch(callbackError => {
290
+ logger.warn(`[connectAll] ${inst.adapter.channelName} onFailed callback failed: ${callbackError}`);
291
+ });
280
292
  }
293
+ };
294
+ const startConnection = (inst) => {
281
295
  const task = (async () => {
282
296
  try {
283
297
  await inst.connect();
284
298
  connected.push(inst.adapter.channelName);
285
- // Fire callback without blocking the connection pipeline
286
299
  if (onConnected) {
287
- Promise.resolve(onConnected(inst)).catch((callbackErr) => {
300
+ void Promise.resolve().then(() => onConnected(inst)).catch(callbackErr => {
288
301
  logger.warn(`[connectAll] ${inst.adapter.channelName} onConnected callback failed: ${callbackErr}`);
289
302
  });
290
303
  }
291
304
  }
292
305
  catch (e) {
293
- failed.push({ name: inst.adapter.channelName, error: e });
294
- logger.warn(`[connectAll] ${inst.adapter.channelName} connect failed: ${e}`);
295
- // Fire callback without blocking the connection pipeline
296
- if (onFailed) {
297
- Promise.resolve(onFailed(inst, e)).catch((callbackErr) => {
298
- logger.warn(`[connectAll] ${inst.adapter.channelName} onFailed callback failed: ${callbackErr}`);
299
- });
300
- }
306
+ reportFailure(inst, e);
301
307
  }
302
308
  })();
303
309
  const tracked = task.finally(() => { inflight.delete(tracked); });
304
310
  inflight.add(tracked);
305
- if (intervalMs > 0) {
306
- await new Promise(r => setTimeout(r, intervalMs));
311
+ };
312
+ // Readiness waits run outside connection slots. Only ready channels join
313
+ // the admission tail, so a slow Agent cannot block another Agent's connect.
314
+ let dispatchTail = Promise.resolve();
315
+ await Promise.all(instances.map(async (inst) => {
316
+ try {
317
+ if (beforeConnect && !(await beforeConnect(inst))) {
318
+ {
319
+ const entry = [...this.instanceStatuses.values()].find(candidate => candidate.runtime === inst);
320
+ if (entry) {
321
+ entry.snapshot.status = 'unavailable';
322
+ entry.snapshot.reason = {
323
+ code: 'AGENT_RUNTIME_UNAVAILABLE',
324
+ message: '所属 Agent 的运行器未成功创建',
325
+ };
326
+ }
327
+ }
328
+ return;
329
+ }
330
+ const dispatch = dispatchTail.then(async () => {
331
+ while (inflight.size >= Math.max(1, concurrency))
332
+ await Promise.race(inflight);
333
+ if (shouldConnect?.(inst) === false)
334
+ return;
335
+ startConnection(inst);
336
+ if (intervalMs > 0)
337
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
338
+ });
339
+ dispatchTail = dispatch.catch(() => undefined);
340
+ await dispatch;
307
341
  }
308
- }
342
+ catch (error) {
343
+ reportFailure(inst, error);
344
+ }
345
+ }));
309
346
  await Promise.allSettled(inflight);
310
347
  if (failed.length > 0) {
311
348
  logger.warn(`[connectAll] ${failed.length} channel(s) failed initial connect: ${failed.map(f => f.name).join(', ')}`);
@@ -333,8 +370,9 @@ export class ChannelLoader {
333
370
  let timedOut = false;
334
371
  let timeout;
335
372
  try {
373
+ // 传预算让 AUN 渠道的 WS 关闭握手只等一小会儿;其他渠道忽略这个参数。
336
374
  await Promise.race([
337
- inst.disconnect(),
375
+ inst.disconnect(CLOSE_HANDSHAKE_BUDGET_MS),
338
376
  new Promise(resolve => {
339
377
  timeout = setTimeout(() => { timedOut = true; resolve(); }, timeoutMs);
340
378
  }),
@@ -93,6 +93,7 @@ export function createChannelConnectionRuntime(dependencies) {
93
93
  }),
94
94
  agent ? dependencies.ensureTriggerSchedulerStarted(agent) : Promise.resolve(),
95
95
  Promise.resolve().then(() => dependencies.sendOnlineNoticeForChannel(instance)),
96
+ Promise.resolve().then(() => dependencies.sendLifecycleNoticeForChannel?.(instance)),
96
97
  dependencies.trySendPendingRestartNotice(),
97
98
  ]);
98
99
  };
@@ -168,6 +169,10 @@ export function createChannelStartupNotifications({ channelInstances, agentRegis
168
169
  let pendingRestartNoticeSent = false;
169
170
  let pendingRestartRetry;
170
171
  const sendOnlineNoticeForChannel = (inst) => {
172
+ // AUN 的上线提示改走 volatile 生命周期通知(见 lifecycle-notice.ts),
173
+ // 这里只保留非 AUN 渠道的 durable 通知,避免同时开启时重复两条。
174
+ if (inst.channelType === 'aun')
175
+ return;
171
176
  const name = inst.adapter.channelName;
172
177
  const agent = agentRegistry.resolveByChannel(inst.adapter.channelKey) ?? agentRegistry.resolveByChannel(name);
173
178
  if (!agent || !upmsg)