evolcore 0.0.43-test.3 → 0.0.43-test.5

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 (192) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/ecmsg.js +492 -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 +12 -54
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +56 -12
  12. package/dist/aun/aid/control-aid.js +15 -0
  13. package/dist/aun/aid/identity.js +8 -0
  14. package/dist/aun/aid/ownership-operation.js +12 -3
  15. package/dist/aun/menu/client.js +8 -7
  16. package/dist/aun/menu/index.js +1 -1
  17. package/dist/aun/menu/transport.js +8 -5
  18. package/dist/aun/service-proxy.js +3 -0
  19. package/dist/channels/aun.js +56 -22
  20. package/dist/channels/daemon.js +12 -4
  21. package/dist/cli/agent-command.js +5 -0
  22. package/dist/cli/agent-create.js +32 -8
  23. package/dist/cli/agent.js +9 -3
  24. package/dist/cli/aid-bind-command.js +3 -0
  25. package/dist/cli/aun-commands.js +12 -5
  26. package/dist/cli/code-stats.js +451 -213
  27. package/dist/cli/ctl-command.js +1 -3
  28. package/dist/cli/daemon-commands.js +42 -21
  29. package/dist/cli/directory.js +7 -8
  30. package/dist/cli/ecmsg-gateway.js +204 -0
  31. package/dist/cli/getmeta-command.js +2 -1
  32. package/dist/cli/index.js +6 -0
  33. package/dist/cli/init.js +58 -18
  34. package/dist/cli/provider-command.js +82 -5
  35. package/dist/cli/restart-monitor.js +11 -19
  36. package/dist/cli/stats.js +8 -1
  37. package/dist/cli/task-context.js +3 -0
  38. package/dist/cli/trigger-command.js +20 -14
  39. package/dist/config/boot-log.js +23 -2
  40. package/dist/config/config-field-policy.js +2 -0
  41. package/dist/config/config-manager.js +13 -17
  42. package/dist/config/daemon-services.js +1 -0
  43. package/dist/config/peer-role-resolver.js +6 -6
  44. package/dist/config/provider-identity-migration.js +202 -0
  45. package/dist/config/provider-identity.js +37 -0
  46. package/dist/config/provider-ipc-service.js +40 -3
  47. package/dist/config/provider-local-sync.js +153 -0
  48. package/dist/config/providers-config.js +32 -4
  49. package/dist/config/providers-management.js +144 -68
  50. package/dist/config/providers.js +4 -1
  51. package/dist/config/role-schema.js +3 -3
  52. package/dist/config/schema-migration.js +188 -3
  53. package/dist/core/agent-application-service.js +11 -0
  54. package/dist/core/agent-ipc-registration.js +2 -0
  55. package/dist/core/agent-runtime.js +45 -11
  56. package/dist/core/auth/auth-gateway.js +8 -6
  57. package/dist/core/auth/delegation-diagnostics.js +6 -2
  58. package/dist/core/auth/operation-authorizer.js +5 -2
  59. package/dist/core/auth/operation-catalog.js +6 -4
  60. package/dist/core/baseagent-loader.js +11 -3
  61. package/dist/core/bootstrap-service.js +8 -0
  62. package/dist/core/channel-loader.js +61 -23
  63. package/dist/core/command/agent-control.js +4 -1
  64. package/dist/core/command/chatmode-config.js +46 -0
  65. package/dist/core/command/cli-intent-parser.js +2 -1
  66. package/dist/core/command/command-handler.js +16 -20
  67. package/dist/core/command/daemon-diagnostics.js +2 -1
  68. package/dist/core/command/menu-catalog.js +1 -1
  69. package/dist/core/command/menu-handler.js +16 -16
  70. package/dist/core/command/menu-protocol.js +4 -2
  71. package/dist/core/command/provider-menu.js +4 -2
  72. package/dist/core/command/role-menu.js +2 -2
  73. package/dist/core/command/slash-handler.js +56 -42
  74. package/dist/core/daemon-lifecycle.js +35 -17
  75. package/dist/core/event-catalog.js +19 -0
  76. package/dist/core/evolagent-registry.js +3 -0
  77. package/dist/core/handoff/runtime.js +9 -3
  78. package/dist/core/initialization/service.js +4 -3
  79. package/dist/core/ipc-registration.js +6 -0
  80. package/dist/core/message/aun-ipc-sender.js +81 -3
  81. package/dist/core/message/im-renderer.js +24 -19
  82. package/dist/core/message/message-admission.js +13 -2
  83. package/dist/core/message/response-engine.js +40 -41
  84. package/dist/core/message/send-options.js +40 -0
  85. package/dist/core/message/send-routing.js +310 -0
  86. package/dist/core/model/model-capabilities.js +37 -0
  87. package/dist/core/model/model-catalog.js +6 -2
  88. package/dist/core/ownership/owner-resolver.js +117 -14
  89. package/dist/core/permission/ec-command-parser.js +195 -27
  90. package/dist/core/permission/readonly-shell-query.js +66 -7
  91. package/dist/core/permission/tool-error-code.js +13 -1
  92. package/dist/core/permission/tool-policy.js +74 -20
  93. package/dist/core/plugin-lifecycle.js +6 -2
  94. package/dist/core/relation/pa-team.js +7 -2
  95. package/dist/core/relation/same-owner-proof.js +131 -0
  96. package/dist/core/session/session-idle-monitor.js +94 -16
  97. package/dist/core/session/session-manager.js +69 -16
  98. package/dist/core/thread/thread-route.js +5 -2
  99. package/dist/directory/owner-directory-cache.js +690 -99
  100. package/dist/directory/owner-directory-markdown.js +146 -36
  101. package/dist/directory/owner-directory-query-operation.js +7 -9
  102. package/dist/directory/owner-directory-scope.js +12 -0
  103. package/dist/directory/owner-directory-search.js +5 -1
  104. package/dist/directory/owner-directory-store.js +28 -0
  105. package/dist/ecweb/basic-settings-service.js +15 -1
  106. package/dist/ecweb/message-context-service.js +2 -2
  107. package/dist/ecweb/providers-service.js +3 -1
  108. package/dist/ecweb/runtime/lifecycle.js +38 -5
  109. package/dist/ecweb/runtime/supervisor.js +157 -49
  110. package/dist/index.js +202 -38
  111. package/dist/paths.js +2 -1
  112. package/dist/proxy/manager.js +2 -0
  113. package/dist/proxy/service-supervisor.js +379 -143
  114. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  115. package/dist/trigger/application-service.js +1 -0
  116. package/dist/trigger/audit.js +3 -2
  117. package/dist/trigger/authorization.js +2 -3
  118. package/dist/trigger/event-source.js +4 -0
  119. package/dist/trigger/feedback.js +26 -2
  120. package/dist/trigger/history.js +4 -3
  121. package/dist/trigger/ipc-service.js +24 -19
  122. package/dist/trigger/manager.js +3 -5
  123. package/dist/trigger/parser.js +4 -21
  124. package/dist/trigger/patch.js +3 -15
  125. package/dist/trigger/scheduler.js +48 -13
  126. package/dist/trigger/system-definitions.js +2 -2
  127. package/dist/trigger/validation.js +4 -13
  128. package/dist/utils/autostart.js +2 -2
  129. package/dist/utils/cross-platform.js +36 -8
  130. package/dist/utils/error-utils.js +8 -0
  131. package/dist/utils/macos-autostart.js +31 -0
  132. package/dist/utils/model-prices.jsonl +15 -8
  133. package/dist/utils/process-introspect.js +21 -1
  134. package/dist/utils/public-suffix.js +5811 -0
  135. package/dist/utils/startup-trace.js +7 -1
  136. package/dist/utils/windows-autostart.js +42 -7
  137. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  138. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  139. package/ecagent/dist/harness/env/nodejs.js +46 -2
  140. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  141. package/kits/docs/channels/aun.md +1 -1
  142. package/kits/docs/channels/feishu.md +2 -2
  143. package/kits/docs/context-assembly.md +20 -4
  144. package/kits/docs/evolcore/INDEX.md +3 -2
  145. package/kits/docs/evolcore/agent.md +2 -2
  146. package/kits/docs/evolcore/aid.md +8 -2
  147. package/kits/docs/evolcore/ctl.md +13 -4
  148. package/kits/docs/evolcore/directory.md +48 -15
  149. package/kits/docs/evolcore/file-navigation.md +63 -49
  150. package/kits/docs/evolcore/group.md +6 -6
  151. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  152. package/kits/docs/evolcore/menu-protocol.md +33 -3
  153. package/kits/docs/evolcore/model.md +5 -3
  154. package/kits/docs/evolcore/msg.md +28 -27
  155. package/kits/docs/evolcore/provider.md +39 -5
  156. package/kits/docs/evolcore/response.md +3 -1
  157. package/kits/docs/evolcore/thread-chain.md +12 -14
  158. package/kits/docs/evolcore/tool-authorization.md +21 -1
  159. package/kits/docs/evolcore/trigger.md +12 -9
  160. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  161. package/kits/docs/prompt-loading-architecture.md +30 -20
  162. package/kits/eck_manifest.auxiliary.json +5 -5
  163. package/kits/eck_manifest.json +28 -49
  164. package/kits/eck_manifest.memory.json +18 -18
  165. package/kits/rules/01-overview.md +43 -45
  166. package/kits/rules/02-navigation.md +44 -53
  167. package/kits/rules/03-identity.md +21 -25
  168. package/kits/rules/04-relation.md +23 -33
  169. package/kits/rules/05-venue.md +24 -25
  170. package/kits/rules/06-channel.md +3 -3
  171. package/kits/schemas/_meta.json +20 -27
  172. package/kits/schemas/agent-config.schema.19.json +10 -6
  173. package/kits/schemas/providers.schema.2.json +74 -0
  174. package/kits/schemas/relation-config.schema.12.json +2 -2
  175. package/kits/schemas/role-config.schema.2.json +5 -5
  176. package/kits/schemas/role-registry.schema.1.json +1 -1
  177. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  178. package/kits/skills/ec-service-proxy/SKILL.md +3 -0
  179. package/kits/skills/ec-trigger/SKILL.md +4 -4
  180. package/kits/skills/ec-trigger/references/examples.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +5 -5
  182. package/kits/templates/system-fragments/commands.md +3 -2
  183. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  184. package/kits/templates/system-fragments/identity.md +0 -1
  185. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  186. package/kits/templates/system-fragments/reply.md +47 -28
  187. package/kits/templates/system-fragments/session.md +2 -9
  188. package/kits/templates/system-fragments/thread.md +5 -5
  189. package/package.json +17 -13
  190. package/kits/schemas/agent-config.schema.20.json +0 -925
  191. package/kits/schemas/relation-config.schema.13.json +0 -289
  192. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -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')
@@ -556,7 +588,7 @@ async function withInitializationClient(aid, action) {
556
588
  // An entered bind can have remote effects. Its adapter may only mark an
557
589
  // audited read-only preflight as not started; all other failures stay unknown.
558
590
  actionStarted = true;
559
- return await action(client);
591
+ return await action(client, store);
560
592
  }
561
593
  catch (error) {
562
594
  if (!actionStarted) {
@@ -582,7 +614,9 @@ async function withInitializationClient(aid, action) {
582
614
  }
583
615
  }
584
616
  export async function bindInitializationOwner(aid, ownerAid) {
585
- return withInitializationClient(aid, async (client) => {
617
+ return withInitializationClient(aid, async (client, store) => {
618
+ const { assertHumanAgentOwner } = await import('../aun/aid/agentmd.js');
619
+ await assertHumanAgentOwner(ownerAid, { store });
586
620
  try {
587
621
  return await client.bindOwneraid(ownerAid);
588
622
  }
@@ -8,7 +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
+ import { prepareSameOwnerProof, sameOwnerQualification, requiresSameOwnerProof } from '../relation/same-owner-proof.js';
12
12
  export function isCrossAgentTriggerOperationAllowed(input) {
13
13
  return input.control || input.daemonOwner === true || input.taskAgentAid === input.targetAgentAid;
14
14
  }
@@ -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
- && (paTeamQualification(input.selfAid, actorId) === 'matched' || requiresPaTeamVerification(input.selfAid, actorId)));
48
- const suppliedRole = !teamContext && input.identity?.role && input.identity.role !== 'none' ? input.identity.role : undefined;
47
+ && (sameOwnerQualification(input.selfAid, actorId) === 'matched' || requiresSameOwnerProof(input.selfAid, actorId)));
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'
@@ -122,7 +122,7 @@ export async function authorizeFreshOperation(params) {
122
122
  || configCommand?.dangerous || subject.processRole === 'fullaccess-run';
123
123
  try {
124
124
  if (subject.channelType === 'aun' && subject.chatType === 'private') {
125
- await preparePaTeamQualification(subject.selfAid, subject.actorId);
125
+ await prepareSameOwnerProof(subject.selfAid, subject.actorId);
126
126
  }
127
127
  await refreshOwnershipForAuthorization(subject.selfAid, {
128
128
  force: force || forceAgentMdEditor,
@@ -152,7 +152,9 @@ 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
+ || (subject.channelType === 'aun' && subject.principalId
157
+ && ownerResolver.owner(subject.selfAid) === subject.principalId)
156
158
  ? undefined : subject.identity,
157
159
  });
158
160
  if (subject.processRole === 'fullaccess-run') {
@@ -147,8 +147,12 @@ export class DelegationDiagnostics {
147
147
  return 'session_mismatch';
148
148
  if (credential.kind === 'task')
149
149
  return this.taskCause(credential);
150
- const approval = commandHash ? this.find('approval', tokenHash, sessionId, commandHash) : undefined;
151
- const activeTokenHash = approval?.activeTokenHash ?? credential.activeTokenHash;
150
+ const candidate = commandHash ? this.find('approval', tokenHash, sessionId, commandHash) : undefined;
151
+ const approval = candidate?.taskId === credential.taskId
152
+ && candidate?.activeTokenHash === credential.activeTokenHash
153
+ && candidate?.runtimeEpoch === credential.runtimeEpoch
154
+ ? candidate : undefined;
155
+ const activeTokenHash = credential.activeTokenHash;
152
156
  const task = activeTokenHash
153
157
  ? this.find('task', activeTokenHash, sessionId)
154
158
  : undefined;
@@ -522,7 +522,9 @@ function authorizeCatalogPolicy(ctx, meta) {
522
522
  if (!policy)
523
523
  return undefined;
524
524
  if (policy.authority === 'daemon-owner') {
525
- return scope === policy.scope && policy.channel === 'control' && ctx.fromControlChannel
525
+ const delegatedRead = policy.allowDelegatedRead === true && ctx.source === 'agent-tool'
526
+ && meta.category === 'read' && !meta.dangerous;
527
+ return scope === policy.scope && policy.channel === 'control' && (ctx.fromControlChannel || delegatedRead)
526
528
  && hasDaemonOwnerRole(ctx) && ctx.processRole !== 'daemon-service'
527
529
  ? allow('daemon-owner', 'catalog-daemon-owner')
528
530
  : deny('This operation requires DaemonOwner process control');
@@ -695,7 +697,8 @@ function checkConstraints(ctx, constraints, resolvedConfigCommand) {
695
697
  if (constraints.privateOnly && ctx.chatType !== 'private') {
696
698
  return { ok: false, reason: 'This command is only allowed in private chats' };
697
699
  }
698
- if (constraints.groupOnly && ctx.chatType !== 'group') {
700
+ if (constraints.groupOnly && ctx.chatType !== 'group'
701
+ && ctx.role !== 'owner' && ctx.role !== 'admin') {
699
702
  const target = stringArg(ctx.intent.args.targetId) ?? stringArg(ctx.intent.args.peer) ?? '<unknown>';
700
703
  const sameGroup = constraints.currentRelationOnly ? ' and may only target that same group' : '';
701
704
  return {
@@ -144,14 +144,16 @@ const QUEUE_OPERATIONS = [['read', 'Read the current Agent message queue'], ['cl
144
144
  *
145
145
  * 参照设计文档 docs/command-execution-role-permission-design.md 第 5 节
146
146
  */
147
- const PROVIDER_OPERATIONS = ['list', 'show', 'create', 'import', 'update', 'delete'].map(action => ({
147
+ const PROVIDER_OPERATIONS = ['list', 'show', 'create', 'import', 'update', 'delete', 'sync'].map(action => ({
148
148
  id: 'provider.' + action,
149
149
  category: action === 'list' || action === 'show' ? 'read' : 'process',
150
150
  dangerous: action !== 'list' && action !== 'show',
151
151
  defaultScopes: ['process'],
152
152
  description: 'Manage the daemon Provider registry: ' + action,
153
- sources: ['menu', 'control', 'ecweb'],
154
- authorizationPolicy: { authority: 'daemon-owner', scope: 'process', channel: 'control' },
153
+ sources: action === 'sync' ? ['control']
154
+ : action === 'list' || action === 'show' ? ['menu', 'control', 'ecweb', 'agent-tool'] : ['menu', 'control', 'ecweb'],
155
+ authorizationPolicy: { authority: 'daemon-owner', scope: 'process', channel: 'control',
156
+ allowDelegatedRead: action === 'list' || action === 'show' },
155
157
  }));
156
158
  const OPERATIONS = [
157
159
  ...['read', 'result-read', 'install', 'configure', 'enable', 'disable', 'invoke', 'publish', 'upgrade', 'rollback', 'uninstall', 'grant', 'retire'].map(action => ({
@@ -1264,7 +1266,7 @@ const OPERATIONS = [
1264
1266
  {
1265
1267
  id: 'ec.aid.bind', category: 'write-agent', dangerous: true, defaultScopes: ['agent'],
1266
1268
  minimumPermissionMode: 'request',
1267
- description: 'Request or decide a protocol Owner binding using the subject SDK client', sources: ['agent-tool', 'menu.cli'],
1269
+ description: 'Request or decide a protocol Owner binding, or reset its local automatic-invitation rejection', sources: ['agent-tool', 'menu.cli'],
1268
1270
  },
1269
1271
  {
1270
1272
  id: 'ec.aid.transfer', category: 'write-agent', dangerous: true, defaultScopes: ['agent'],
@@ -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
+ }
@@ -256,7 +256,8 @@ function parseAidCommand(argv, source, defaultSelfAid) {
256
256
  ...(subjectAid ? { self: subjectAid } : {}),
257
257
  ...(command.subjectAid ? { subjectAid: command.subjectAid } : {}),
258
258
  ...(command.action === 'status' && command.refresh ? { refresh: true } : {}),
259
- ...(command.action === 'bind' ? { ownerAid: command.ownerAid } : {}),
259
+ ...(command.action === 'bind' || command.action === 'reset-rejection' ? { ownerAid: command.ownerAid } : {}),
260
+ ...(command.action === 'reset-rejection' ? { action: command.action } : {}),
260
261
  ...(command.action === 'transfer' ? { subAid: command.subAid, newOwnerAid: command.newOwnerAid } : {}),
261
262
  ...(command.action === 'accept' || command.action === 'reject'
262
263
  ? { decision: command.action, operationId: command.operationId } : {}),