evolcore 0.0.43-test.3 → 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 (109) hide show
  1. package/CHANGELOG.md +36 -0
  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 +130 -35
  11. package/dist/aun/aid/agentmd.js +31 -12
  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/service-proxy.js +3 -0
  16. package/dist/channels/aun.js +26 -5
  17. package/dist/channels/daemon.js +10 -2
  18. package/dist/cli/agent-command.js +5 -0
  19. package/dist/cli/agent-create.js +28 -6
  20. package/dist/cli/agent.js +9 -3
  21. package/dist/cli/aun-commands.js +2 -2
  22. package/dist/cli/daemon-commands.js +30 -18
  23. package/dist/cli/directory.js +4 -7
  24. package/dist/cli/getmeta-command.js +2 -1
  25. package/dist/cli/init.js +13 -5
  26. package/dist/cli/trigger-command.js +20 -14
  27. package/dist/config/boot-log.js +12 -2
  28. package/dist/config/config-field-policy.js +2 -0
  29. package/dist/config/config-manager.js +9 -4
  30. package/dist/config/peer-role-resolver.js +1 -1
  31. package/dist/config/role-schema.js +3 -3
  32. package/dist/config/schema-migration.js +121 -0
  33. package/dist/core/agent-application-service.js +11 -0
  34. package/dist/core/agent-ipc-registration.js +2 -0
  35. package/dist/core/agent-runtime.js +41 -9
  36. package/dist/core/auth/auth-gateway.js +3 -3
  37. package/dist/core/auth/operation-authorizer.js +2 -1
  38. package/dist/core/baseagent-loader.js +11 -3
  39. package/dist/core/bootstrap-service.js +8 -0
  40. package/dist/core/channel-loader.js +61 -23
  41. package/dist/core/command/agent-control.js +4 -1
  42. package/dist/core/command/chatmode-config.js +46 -0
  43. package/dist/core/command/command-handler.js +5 -14
  44. package/dist/core/command/daemon-diagnostics.js +2 -1
  45. package/dist/core/command/menu-catalog.js +1 -1
  46. package/dist/core/command/menu-handler.js +16 -16
  47. package/dist/core/command/slash-handler.js +4 -26
  48. package/dist/core/daemon-lifecycle.js +35 -17
  49. package/dist/core/event-catalog.js +19 -0
  50. package/dist/core/evolagent-registry.js +3 -0
  51. package/dist/core/ipc-registration.js +6 -0
  52. package/dist/core/message/im-renderer.js +24 -19
  53. package/dist/core/message/message-admission.js +11 -2
  54. package/dist/core/message/response-engine.js +17 -18
  55. package/dist/core/model/model-capabilities.js +37 -0
  56. package/dist/core/model/model-catalog.js +6 -2
  57. package/dist/core/ownership/owner-resolver.js +6 -6
  58. package/dist/core/permission/ec-command-parser.js +47 -12
  59. package/dist/core/plugin-lifecycle.js +6 -2
  60. package/dist/core/relation/pa-team.js +7 -2
  61. package/dist/directory/owner-directory-cache.js +4 -2
  62. package/dist/directory/owner-directory-query-operation.js +5 -7
  63. package/dist/ecweb/runtime/lifecycle.js +29 -5
  64. package/dist/ecweb/runtime/supervisor.js +83 -27
  65. package/dist/index.js +198 -38
  66. package/dist/proxy/service-supervisor.js +377 -141
  67. package/dist/trigger/audit.js +3 -2
  68. package/dist/trigger/authorization.js +2 -3
  69. package/dist/trigger/history.js +4 -3
  70. package/dist/trigger/ipc-service.js +24 -19
  71. package/dist/trigger/manager.js +3 -5
  72. package/dist/trigger/parser.js +4 -21
  73. package/dist/trigger/patch.js +3 -15
  74. package/dist/trigger/scheduler.js +45 -10
  75. package/dist/trigger/validation.js +0 -13
  76. package/dist/utils/error-utils.js +8 -0
  77. package/dist/utils/macos-autostart.js +31 -0
  78. package/dist/utils/model-prices.jsonl +15 -8
  79. package/dist/utils/process-introspect.js +21 -1
  80. package/dist/utils/startup-trace.js +7 -1
  81. package/dist/utils/windows-autostart.js +1 -0
  82. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  83. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  84. package/kits/docs/evolcore/INDEX.md +1 -1
  85. package/kits/docs/evolcore/file-navigation.md +63 -49
  86. package/kits/docs/evolcore/menu-protocol.md +1 -0
  87. package/kits/docs/evolcore/model.md +5 -3
  88. package/kits/docs/evolcore/response.md +2 -0
  89. package/kits/docs/evolcore/thread-chain.md +1 -1
  90. package/kits/docs/evolcore/tool-authorization.md +4 -1
  91. package/kits/docs/evolcore/trigger.md +10 -7
  92. package/kits/eck_manifest.json +0 -21
  93. package/kits/rules/01-overview.md +42 -44
  94. package/kits/rules/02-navigation.md +44 -53
  95. package/kits/rules/03-identity.md +21 -25
  96. package/kits/rules/04-relation.md +23 -33
  97. package/kits/rules/05-venue.md +24 -25
  98. package/kits/schemas/_meta.json +13 -26
  99. package/kits/schemas/agent-config.schema.19.json +10 -6
  100. package/kits/schemas/relation-config.schema.12.json +2 -2
  101. package/kits/schemas/role-config.schema.2.json +5 -5
  102. package/kits/skills/ec-service-proxy/SKILL.md +10 -0
  103. package/kits/skills/ec-trigger/SKILL.md +1 -1
  104. package/kits/templates/system-fragments/commands.md +1 -1
  105. package/kits/templates/system-fragments/identity.md +0 -1
  106. package/package.json +18 -13
  107. package/kits/schemas/agent-config.schema.20.json +0 -925
  108. package/kits/schemas/relation-config.schema.13.json +0 -289
  109. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -121,7 +121,7 @@ export function resolvePeerRoleDetail(ctx) {
121
121
  const valid = !store.diagnostics.some(diagnostic => diagnostic.code === 'INVALID_ROLE_REGISTRY'
122
122
  || diagnostic.code === 'MISSING_ROLE_REGISTRY');
123
123
  const role = valid ? normalizeDefaultRole(store.registry.defaultRoles.paTeam ?? 'member', ctx.selfAid) : null;
124
- return resultFor(role, 'pa-team-default', actor, ctx.selfAid);
124
+ return resultFor(role, 'internal-contact-default', actor, ctx.selfAid);
125
125
  }
126
126
  if (ctx.chatType === 'private') {
127
127
  if (actorRole)
@@ -33,12 +33,12 @@ export function rolePermissionFields() {
33
33
  patterns: field.patterns?.map((pattern) => ({ ...pattern, kind: 'pattern' })),
34
34
  }));
35
35
  }
36
- /** Read compatibility for policies saved before group delivery became proactive-only. */
36
+ /** Read compatibility for published v1 policies; current policies validate strictly. */
37
37
  export function normalizeRoleGroupChatmodeCompat(value) {
38
38
  if (!isRecord(value) || !isRecord(value.permissions))
39
39
  return value;
40
40
  const version = value.$schema_version ?? 1;
41
- if (version !== 1 && version !== 2)
41
+ if (version !== 1)
42
42
  return value;
43
43
  const group = value.permissions['chatmode.group'];
44
44
  if (!isRecord(group))
@@ -82,7 +82,7 @@ export function validateRoleConfig(value) {
82
82
  const compatible = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(value));
83
83
  const schema = loadSchema('role-config');
84
84
  const normalized = isRecord(compatible)
85
- && (!Object.hasOwn(compatible, '$schema_version') || compatible.$schema_version === 1 || compatible.$schema_version === 2)
85
+ && (!Object.hasOwn(compatible, '$schema_version') || compatible.$schema_version === 1)
86
86
  ? { ...compatible, $schema_version: schema.version }
87
87
  : compatible;
88
88
  if (!schema.validate(normalized)) {
@@ -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')
@@ -42,10 +42,10 @@ export function buildAuthSubject(input) {
42
42
  actor: roleDetail.actor,
43
43
  processOwners,
44
44
  }));
45
- const teamContext = roleDetail.source === 'pa-team-default'
45
+ const internalContactContext = roleDetail.source === 'internal-contact-default'
46
46
  || (input.channelType === 'aun' && chatType === 'private' && input.selfAid && actorId
47
47
  && (paTeamQualification(input.selfAid, actorId) === 'matched' || requiresPaTeamVerification(input.selfAid, actorId)));
48
- const suppliedRole = !teamContext && input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
48
+ const suppliedRole = !internalContactContext && input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
49
49
  const role = suppliedRole ?? roleDetail.effectiveRole ?? 'none';
50
50
  const processRole = isFullAccessRun
51
51
  ? 'fullaccess-run'
@@ -152,7 +152,7 @@ export async function authorizeFreshOperation(params) {
152
152
  channel: subject.channel, channelType: subject.channelType, channelId: subject.channelId,
153
153
  chatType: subject.chatType, conversationId: subject.conversationId,
154
154
  fromControlChannel: subject.fromControlChannel,
155
- identity: subject.roleSource === 'pa-team-default' || (subject.role === 'owner' && subject.principalId)
155
+ identity: subject.roleSource === 'internal-contact-default' || (subject.role === 'owner' && subject.principalId)
156
156
  ? undefined : subject.identity,
157
157
  });
158
158
  if (subject.processRole === 'fullaccess-run') {
@@ -695,7 +695,8 @@ function checkConstraints(ctx, constraints, resolvedConfigCommand) {
695
695
  if (constraints.privateOnly && ctx.chatType !== 'private') {
696
696
  return { ok: false, reason: 'This command is only allowed in private chats' };
697
697
  }
698
- if (constraints.groupOnly && ctx.chatType !== 'group') {
698
+ if (constraints.groupOnly && ctx.chatType !== 'group'
699
+ && ctx.role !== 'owner' && ctx.role !== 'admin') {
699
700
  const target = stringArg(ctx.intent.args.targetId) ?? stringArg(ctx.intent.args.peer) ?? '<unknown>';
700
701
  const sameGroup = constraints.currentRelationOnly ? ' and may only target that same group' : '';
701
702
  return {
@@ -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
  }),
@@ -785,17 +785,20 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
785
785
  ?? (Array.isArray(a.owners) ? a.owners[0] : undefined);
786
786
  const rawModel = supplied.model ?? a.model;
787
787
  const rawEffort = supplied.effort ?? a.effort;
788
- for (const [field, value] of [['model', rawModel], ['effort', rawEffort]]) {
788
+ const rawProvider = supplied.provider ?? a.provider;
789
+ for (const [field, value] of [['provider', rawProvider], ['model', rawModel], ['effort', rawEffort]]) {
789
790
  if (value !== undefined && typeof value !== 'string') {
790
791
  return { error: `${field} 必须是字符串`, code: 'INVALID_ARGS' };
791
792
  }
792
793
  }
794
+ const provider = typeof rawProvider === 'string' && rawProvider.trim() ? rawProvider.trim() : undefined;
793
795
  const effort = typeof rawEffort === 'string' && rawEffort.trim() && rawEffort.trim() !== 'auto'
794
796
  ? rawEffort.trim() : undefined;
795
797
  const plan = {
796
798
  aid,
797
799
  project: supplied.project ?? a.project ?? '',
798
800
  baseagent: supplied.baseagent ?? a.baseagent,
801
+ ...(provider ? { provider } : {}),
799
802
  ...(typeof rawModel === 'string' && rawModel.trim() ? { model: rawModel.trim() } : {}),
800
803
  ...(effort ? { effort } : {}),
801
804
  ownerAid,
@@ -0,0 +1,46 @@
1
+ import { ConfigError, ConfigTarget, mutateConfig, routeFieldPath, } from '../../config/config-manager.js';
2
+ import { formatPeerKey, parsePeerKey, readAunPeerKind } from '../relation/peer-identity.js';
3
+ /** Both command entry points authorize the operation before calling this writer. */
4
+ export function writeChatmodeConfig(target, value, subject) {
5
+ const route = routeFieldPath(`chatmode.${target.field}`, target.scope);
6
+ mutateConfig(route.target, target.sel, config => {
7
+ if (route.target === ConfigTarget.Relation && value === 'paactive') {
8
+ const denied = () => new ConfigError('NOT_APPLICABLE', 'paactive 仅支持已确认的 AUN 私聊关系');
9
+ if (target.field !== 'private' || !target.sel.self || !target.sel.peerKey)
10
+ throw denied();
11
+ let peer;
12
+ try {
13
+ peer = parsePeerKey(target.sel.peerKey);
14
+ }
15
+ catch {
16
+ throw denied();
17
+ }
18
+ if (peer.channelType !== 'aun')
19
+ throw denied();
20
+ // Request args select a relation, but cannot supply its kind. Only use
21
+ // authenticated routing when it names this exact Agent and conversation.
22
+ let routeKind;
23
+ if (!subject.fromControlChannel && subject.selfAid === target.sel.self
24
+ && subject.channelType === 'aun' && subject.conversationId === peer.channelId
25
+ && (!subject.peerKey || subject.peerKey === formatPeerKey('aun', peer.channelId))) {
26
+ if (subject.chatType === 'group' || subject.menuTransportChatType === 'group') {
27
+ routeKind = 'group';
28
+ }
29
+ else if (subject.chatType === 'private' && subject.actorId === peer.channelId) {
30
+ routeKind = 'private';
31
+ }
32
+ }
33
+ const resolution = readAunPeerKind(target.sel.self, peer.channelId, {
34
+ routeKind, relation: config,
35
+ });
36
+ if (resolution.kind !== 'private')
37
+ throw denied();
38
+ config.targetKind = 'private';
39
+ }
40
+ const block = config.chatmode && typeof config.chatmode === 'object' && !Array.isArray(config.chatmode)
41
+ ? { ...config.chatmode }
42
+ : {};
43
+ block[target.field] = value;
44
+ config.chatmode = block;
45
+ });
46
+ }