evolcore 0.0.43-test.5 → 0.0.43-test.7

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 (259) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +281 -81
  3. package/dist/agents/baseagent-availability.js +20 -5
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +36 -3
  7. package/dist/agents/codex-runner.js +75 -8
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/msg/p2p.js +6 -1
  10. package/dist/aun/service-proxy.js +18 -6
  11. package/dist/channels/aun.js +306 -30
  12. package/dist/cli/agent-create.js +18 -8
  13. package/dist/cli/aun-commands.js +9 -1
  14. package/dist/cli/daemon-commands.js +34 -65
  15. package/dist/cli/daemon-lifecycle-client.js +61 -0
  16. package/dist/cli/ecmsg-gateway.js +38 -3
  17. package/dist/cli/events-command.js +73 -0
  18. package/dist/cli/index.js +31 -14
  19. package/dist/cli/init.js +75 -0
  20. package/dist/cli/invoke-command.js +182 -0
  21. package/dist/cli/managed-command-guard.js +6 -1
  22. package/dist/cli/provider-command.js +1 -1
  23. package/dist/cli/restart-monitor.js +67 -50
  24. package/dist/cli/services-command.js +111 -0
  25. package/dist/cli/task-context.js +38 -1
  26. package/dist/cli/team-workspace-command.js +134 -0
  27. package/dist/cli/thread-command.js +6 -2
  28. package/dist/cli/watch-logs.js +6 -4
  29. package/dist/cli/watch-msg.js +1 -1
  30. package/dist/config/boot-log.js +6 -4
  31. package/dist/config/builtin-roles.js +2 -2
  32. package/dist/config/config-field-policy.js +2 -2
  33. package/dist/config/config-manager.js +1 -8
  34. package/dist/config/invoke-ipc-service.js +118 -0
  35. package/dist/config/peer-role-resolver.js +1 -1
  36. package/dist/config/provider-identity-migration.js +92 -17
  37. package/dist/config/provider-local-sync.js +2 -0
  38. package/dist/config/providers-config.js +13 -0
  39. package/dist/config/providers-management.js +100 -10
  40. package/dist/config/role-service.js +8 -8
  41. package/dist/config/role-store.js +22 -22
  42. package/dist/config/schema-migration.js +86 -88
  43. package/dist/config/snapshot.js +70 -41
  44. package/dist/config-store.js +2 -1
  45. package/dist/core/agent-reload-coordinator.js +6 -4
  46. package/dist/core/agent-runtime.js +146 -15
  47. package/dist/core/auth/delegation-authorization.js +66 -0
  48. package/dist/core/auth/operation-catalog.js +20 -0
  49. package/dist/core/baseagent-loader.js +75 -42
  50. package/dist/core/channel-loader.js +45 -13
  51. package/dist/core/channel-runtime.js +116 -45
  52. package/dist/core/command/agent-control.js +1 -1
  53. package/dist/core/command/agent-storage-menu.js +1 -1
  54. package/dist/core/command/chatmode-config.js +2 -36
  55. package/dist/core/command/command-handler.js +58 -16
  56. package/dist/core/command/data-root-resolver.js +32 -23
  57. package/dist/core/command/eventcenter-menu.js +338 -0
  58. package/dist/core/command/menu-catalog.js +8 -0
  59. package/dist/core/command/menu-handler.js +206 -87
  60. package/dist/core/command/menu-protocol.js +142 -22
  61. package/dist/core/command/menu-query-batch.js +194 -0
  62. package/dist/core/command/role-menu.js +27 -15
  63. package/dist/core/command/slash-gate.js +1 -1
  64. package/dist/core/command/slash-handler.js +34 -42
  65. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  66. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  67. package/dist/core/command/team-workspace-initializer.js +2 -0
  68. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  69. package/dist/core/command/team-workspace-job-store.js +88 -0
  70. package/dist/core/command/team-workspace-management-service.js +2 -0
  71. package/dist/core/command/team-workspace-management-store.js +96 -0
  72. package/dist/core/command/team-workspace-management.js +265 -0
  73. package/dist/core/command/team-workspace-members-menu.js +88 -0
  74. package/dist/core/command/team-workspace-store.js +612 -0
  75. package/dist/core/command/team-workspace-team.js +193 -0
  76. package/dist/core/daemon-control.js +45 -15
  77. package/dist/core/daemon-lifecycle.js +478 -75
  78. package/dist/core/handoff/dispatcher.js +9 -3
  79. package/dist/core/handoff/runtime.js +130 -42
  80. package/dist/core/handoff/store.js +190 -2
  81. package/dist/core/handoff/types.js +5 -0
  82. package/dist/core/initialization/service.js +4 -4
  83. package/dist/core/invoke/executors/index.js +13 -0
  84. package/dist/core/invoke/executors/media.js +283 -0
  85. package/dist/core/invoke/executors/text.js +198 -0
  86. package/dist/core/invoke/invoke-service.js +157 -0
  87. package/dist/core/invoke/style-router.js +48 -0
  88. package/dist/core/invoke/types.js +19 -0
  89. package/dist/core/ipc-registration.js +51 -11
  90. package/dist/core/lifecycle-notice.js +10 -4
  91. package/dist/core/memory/consolidation.js +7 -5
  92. package/dist/core/message/aun-ipc-sender.js +149 -19
  93. package/dist/core/message/im-renderer.js +28 -84
  94. package/dist/core/message/message-bridge.js +57 -4
  95. package/dist/core/message/message-queue.js +46 -4
  96. package/dist/core/message/message-utils.js +10 -2
  97. package/dist/core/message/peer-mode.js +7 -34
  98. package/dist/core/message/pending-hints.js +4 -10
  99. package/dist/core/message/response-engine.js +163 -52
  100. package/dist/core/message/send-options.js +7 -4
  101. package/dist/core/message/send-routing.js +55 -7
  102. package/dist/core/ownership/owner-resolver.js +8 -0
  103. package/dist/core/permission/ec-command-parser.js +14 -3
  104. package/dist/core/permission/protected-paths.js +12 -2
  105. package/dist/core/permission/shell-environment.js +9 -0
  106. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  107. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  108. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  109. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  110. package/dist/core/session/session-file-health.js +243 -0
  111. package/dist/core/session/session-fs-store.js +163 -3
  112. package/dist/core/session/session-idle-monitor.js +9 -1
  113. package/dist/core/session/session-manager.js +36 -2
  114. package/dist/core/task/task-recovery-service.js +13 -2
  115. package/dist/core/thread/command-parser.js +9 -2
  116. package/dist/core/thread/thread-operation.js +21 -2
  117. package/dist/core/thread/thread-route.js +13 -2
  118. package/dist/directory/owner-directory-admission.js +42 -30
  119. package/dist/directory/owner-directory-cache.js +143 -126
  120. package/dist/directory/owner-directory-query-operation.js +9 -8
  121. package/dist/eck/kit-renderer.js +7 -5
  122. package/dist/ecweb/basic-settings-service.js +1 -1
  123. package/dist/ecweb/message-context-service.js +0 -4
  124. package/dist/ecweb/runtime/lifecycle.js +14 -8
  125. package/dist/ecweb/runtime/supervisor.js +62 -30
  126. package/dist/event-center/admission-materializer.js +114 -0
  127. package/dist/event-center/bus-gate.js +136 -0
  128. package/dist/event-center/bus-host.js +290 -0
  129. package/dist/event-center/bus-resolver.js +120 -0
  130. package/dist/event-center/center-config.js +100 -0
  131. package/dist/event-center/client-factory.js +50 -0
  132. package/dist/event-center/daemon.js +45 -0
  133. package/dist/event-center/directory-source.js +53 -0
  134. package/dist/event-center/dispatcher.js +157 -0
  135. package/dist/event-center/event-log.js +110 -0
  136. package/dist/event-center/index-generator.js +63 -0
  137. package/dist/event-center/ipc-operation.js +308 -0
  138. package/dist/event-center/ledger.js +52 -0
  139. package/dist/event-center/pack-loader.js +202 -0
  140. package/dist/event-center/pack-manager.js +85 -0
  141. package/dist/event-center/registry.js +238 -0
  142. package/dist/event-center/runtime.js +641 -0
  143. package/dist/event-center/script-runner.js +356 -0
  144. package/dist/event-center/types.js +35 -0
  145. package/dist/event-center/validation.js +413 -0
  146. package/dist/index.js +751 -268
  147. package/dist/ipc.js +66 -12
  148. package/dist/paths.js +20 -0
  149. package/dist/product.js +14 -0
  150. package/dist/proxy/manager.js +43 -18
  151. package/dist/proxy/service-supervisor.js +78 -35
  152. package/dist/response-system/engines/v1/index.js +0 -1
  153. package/dist/response-system/modes/single-session/index.js +1 -1
  154. package/dist/services/dispatcher.js +100 -0
  155. package/dist/services/idempotency.js +90 -0
  156. package/dist/services/identity.js +52 -0
  157. package/dist/services/index-generator.js +70 -0
  158. package/dist/services/index.js +449 -0
  159. package/dist/services/ipc-operation.js +458 -0
  160. package/dist/services/ledger.js +52 -0
  161. package/dist/services/message-log.js +112 -0
  162. package/dist/services/pack-manager.js +204 -0
  163. package/dist/services/reply.js +55 -0
  164. package/dist/services/router.js +95 -0
  165. package/dist/services/script-runner.js +422 -0
  166. package/dist/services/service-payload.js +70 -0
  167. package/dist/services/types.js +18 -0
  168. package/dist/services/validation.js +297 -0
  169. package/dist/trigger/application-service.js +21 -1
  170. package/dist/trigger/audit.js +19 -4
  171. package/dist/trigger/authorization.js +14 -5
  172. package/dist/trigger/event-source.js +1 -1
  173. package/dist/trigger/history.js +176 -7
  174. package/dist/trigger/ipc-service.js +3 -1
  175. package/dist/trigger/manager.js +1 -3
  176. package/dist/trigger/scheduler.js +78 -5
  177. package/dist/trigger/script-sandbox.js +118 -22
  178. package/dist/utils/cross-platform.js +175 -13
  179. package/dist/utils/evolcore-version.js +69 -27
  180. package/dist/utils/host-info.js +11 -8
  181. package/dist/utils/instance-registry.js +19 -13
  182. package/dist/utils/npm-ops.js +48 -0
  183. package/dist/utils/process-introspect.js +109 -10
  184. package/dist/utils/startup-trace.js +222 -44
  185. package/dist/utils/windows-shell-trust.js +80 -6
  186. package/kits/docs/INDEX.md +2 -2
  187. package/kits/docs/aun/ABILITY_CALLING.md +10 -17
  188. package/kits/docs/context-assembly.md +1 -1
  189. package/kits/docs/evolcore/INDEX.md +5 -2
  190. package/kits/docs/evolcore/ability.md +4 -0
  191. package/kits/docs/evolcore/aid.md +1 -1
  192. package/kits/docs/evolcore/ctl.md +2 -1
  193. package/kits/docs/evolcore/event-center.md +207 -0
  194. package/kits/docs/evolcore/file-navigation.md +10 -264
  195. package/kits/docs/evolcore/fs.md +3 -2
  196. package/kits/docs/evolcore/group.md +2 -2
  197. package/kits/docs/evolcore/memory-architecture.md +2 -0
  198. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  199. package/kits/docs/evolcore/menu-protocol.md +21 -0
  200. package/kits/docs/evolcore/msg.md +27 -8
  201. package/kits/docs/evolcore/provider.md +23 -3
  202. package/kits/docs/evolcore/response.md +5 -5
  203. package/kits/docs/evolcore/services.md +277 -0
  204. package/kits/docs/evolcore/task.md +2 -0
  205. package/kits/docs/evolcore/team-workspace.md +41 -0
  206. package/kits/eck_manifest.json +45 -7
  207. package/kits/eck_message_manifest.json +3 -3
  208. package/kits/rules/02-navigation.md +10 -1
  209. package/kits/rules/06-channel.md +5 -6
  210. package/kits/schemas/_meta.json +17 -6
  211. package/kits/schemas/agent-config.schema.19.json +5 -7
  212. package/kits/schemas/agent-config.schema.20.json +936 -0
  213. package/kits/schemas/daemon.schema.1.json +5 -0
  214. package/kits/schemas/daemon.schema.2.json +5 -0
  215. package/kits/schemas/daemon.schema.3.json +2 -1
  216. package/kits/schemas/daemon.schema.4.json +2 -1
  217. package/kits/schemas/daemon.schema.5.json +2 -1
  218. package/kits/schemas/daemon.schema.6.json +1 -1
  219. package/kits/schemas/daemon.schema.7.json +1 -1
  220. package/kits/schemas/daemon.schema.8.json +2 -1
  221. package/kits/schemas/daemon.schema.9.json +2 -1
  222. package/kits/schemas/relation-config.schema.12.json +2 -3
  223. package/kits/schemas/role-config.schema.2.json +4 -4
  224. package/kits/schemas/role-registry.schema.1.json +2 -2
  225. package/kits/schemas/single-session.schema.1.json +1 -1
  226. package/kits/schemas/single-session.schema.2.json +1 -1
  227. package/kits/schemas/single-session.schema.3.json +1 -1
  228. package/kits/skills/.switches.json +1 -5
  229. package/kits/skills/ability/SKILL.md +56 -0
  230. package/kits/skills/ability/references/calling.md +56 -0
  231. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  232. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  233. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  234. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  235. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  236. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  237. package/kits/skills/ec-group/SKILL.md +8 -5
  238. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  239. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  240. package/kits/skills/ec-trigger/SKILL.md +4 -4
  241. package/kits/skills/personal-assistant/SKILL.md +6 -6
  242. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  243. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  244. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  245. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  246. package/kits/skills/thread-ops/SKILL.md +10 -10
  247. package/kits/templates/system-fragments/channel.md +3 -3
  248. package/kits/templates/system-fragments/commands.md +9 -7
  249. package/kits/templates/system-fragments/reply.md +2 -6
  250. package/kits/templates/system-fragments/session.md +1 -1
  251. package/kits/templates/system-fragments/thread.md +11 -9
  252. package/package.json +5 -6
  253. package/dist/cli/pa-workspace-command.js +0 -225
  254. package/dist/core/command/pa-workspace-store.js +0 -468
  255. package/dist/core/relation/pa-team.js +0 -132
  256. package/kits/docs/evolcore/pa-workspace.md +0 -51
  257. package/kits/skills/aid-ability/SKILL.md +0 -244
  258. package/kits/skills/ec-ability/SKILL.md +0 -67
  259. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -156,6 +156,26 @@ const PROVIDER_OPERATIONS = ['list', 'show', 'create', 'import', 'update', 'dele
156
156
  allowDelegatedRead: action === 'list' || action === 'show' },
157
157
  }));
158
158
  const OPERATIONS = [
159
+ ...[
160
+ ['event.center.current', 'Read event center status'],
161
+ ['event.center.update', 'Update event center status'],
162
+ ['event.allowlist.current', 'Read event allowlist'],
163
+ ['event.allowlist.update', 'Update event allowlist'],
164
+ ['event.packs.list', 'List event packs'],
165
+ ['event.register.list', 'List registered events'],
166
+ ['event.register.update', 'Update registered events'],
167
+ ['event.subscribers.list', 'List event subscribers'],
168
+ ['event.stats.current', 'Read event publication statistics'],
169
+ ].map(([id, description]) => ({
170
+ id,
171
+ category: id.endsWith('.current') || id.endsWith('.list') ? 'read' : 'write-agent',
172
+ dangerous: !id.endsWith('.current') && !id.endsWith('.list'),
173
+ defaultScopes: ['agent'],
174
+ description,
175
+ sources: ['menu'],
176
+ authorizationTarget: 'current-agent',
177
+ minimumAgentRole: 'owner',
178
+ })),
159
179
  ...['read', 'result-read', 'install', 'configure', 'enable', 'disable', 'invoke', 'publish', 'upgrade', 'rollback', 'uninstall', 'grant', 'retire'].map(action => ({
160
180
  id: 'ability.' + action, category: action === 'read' ? 'read' : 'write-agent',
161
181
  dangerous: action !== 'read', defaultScopes: ['agent'], description: 'Manage AID ability plugins: ' + action,
@@ -7,32 +7,32 @@
7
7
  */
8
8
  import { logger } from '../utils/logger.js';
9
9
  import { PluginHandle } from './plugin-lifecycle.js';
10
- /**
11
- * 有界并发 map:保持输入顺序返回结果。
12
- *
13
- * 不用 Promise.all 是因为这里的任务会拉起外部进程,全量并发会让它们同时抢 CPU;
14
- * 也不需要通用工具库——只有这一处用。
15
- */
16
- async function mapWithConcurrency(items, limit, fn) {
17
- const results = new Array(items.length);
18
- let cursor = 0;
19
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
20
- while (true) {
21
- const index = cursor++;
22
- if (index >= items.length)
23
- return;
24
- results[index] = await fn(items[index], index);
25
- }
26
- });
27
- const outcomes = await Promise.allSettled(workers);
28
- const failed = outcomes.find((outcome) => outcome.status === 'rejected');
29
- if (failed)
30
- throw failed.reason;
31
- return results;
32
- }
33
10
  /** Agent Loader — produces one runner per (EvolAgent × baseagent). */
34
11
  export class AgentLoader {
35
12
  plugins = new Map();
13
+ creationSlots = new Map();
14
+ enabledBaseagents(agent) {
15
+ return [...this.plugins].filter(([, plugin]) => plugin.isEnabled(agent)).map(([name]) => name);
16
+ }
17
+ async withCreationSlot(backend, create) {
18
+ let slots = this.creationSlots.get(backend);
19
+ if (!slots)
20
+ this.creationSlots.set(backend, slots = { active: 0, waiting: [] });
21
+ if (slots.active < 4)
22
+ slots.active++;
23
+ else
24
+ await new Promise(resolve => slots.waiting.push(resolve));
25
+ try {
26
+ return await create();
27
+ }
28
+ finally {
29
+ const next = slots.waiting.shift();
30
+ if (next)
31
+ next();
32
+ else
33
+ slots.active--;
34
+ }
35
+ }
36
36
  register(plugin) {
37
37
  if (this.plugins.has(plugin.name)) {
38
38
  throw new Error(`Agent plugin '${plugin.name}' already registered`);
@@ -41,30 +41,60 @@ export class AgentLoader {
41
41
  logger.debug(`Registered agent plugin: ${plugin.name}`);
42
42
  }
43
43
  /**
44
- * Iterate over all EvolAgents in the registry × all registered plugins.
45
- * Each successful (agent, plugin) pair yields one runner instance.
44
+ * Create each Agent's selected backend. Other backends are created on demand.
46
45
  */
47
- async createAll(registry, callbacks, creationErrors, onAgentCreated, shouldCreateAgent = () => true) {
48
- const instances = [];
49
- const allAgents = registry.runnableAgents();
50
- // 各 agent 的 runner 创建互不共享状态(每个 plugin 只读自己的 config,
51
- // 结果写回各自的 instances 数组),串行只会把 21 个 agent 的创建时间叠加起来。
52
- // 限并发而不是 Promise.all:codex 插件在缓存未命中时会拉起外部进程,全量并发会
53
- // 在同一瞬间抢占 CPU。顺序按 allAgents 保持,输出与串行一致。
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;
46
+ async createAll(registry, callbacks, creationErrors, onAgentCreated, shouldCreateAgent = () => true, onActiveCreated, startupPriority, onAgentStarting, preloadAids, prepareAgent) {
47
+ const allAgents = registry.runnableAgents().filter(agent => !preloadAids || preloadAids.has(agent.aid));
48
+ const created = allAgents.map(() => []);
49
+ const agentsByBackend = new Map();
50
+ allAgents.forEach((agent, index) => {
51
+ const indices = agentsByBackend.get(agent.baseagent) ?? [];
52
+ indices.push(index);
53
+ agentsByBackend.set(agent.baseagent, indices);
59
54
  });
60
- for (const agentInstances of created)
61
- instances.push(...agentInstances);
62
- return instances;
55
+ // Independent bounded lanes keep a slow backend from holding other Agents.
56
+ // Deferred groups wait outside those lanes, so waiting consumes no capacity.
57
+ const outcomes = await Promise.allSettled([...agentsByBackend.values()].map(async (indices) => {
58
+ for (const priority of startupPriority ? [true, false] : [true]) {
59
+ const group = indices.filter(index => !startupPriority || startupPriority.aids.has(allAgents[index].aid) === priority);
60
+ if (!group.length)
61
+ continue;
62
+ if (!priority)
63
+ await startupPriority.waitForDeferred();
64
+ // Classification waits must not occupy creation slots. createForAgent
65
+ // bounds actual process work to four per backend, including demand loads.
66
+ const prepared = await Promise.allSettled(group.map(async (index) => {
67
+ const agent = allAgents[index];
68
+ if (prepareAgent && !await prepareAgent(agent))
69
+ return;
70
+ const startedAtMs = Date.now();
71
+ if (shouldCreateAgent()) {
72
+ onAgentStarting?.(agent);
73
+ created[index] = await this.createForAgent(agent, callbacks, creationErrors, backend => backend === agent.baseagent, () => {
74
+ if (!shouldCreateAgent())
75
+ throw new Error('Agent startup cancelled');
76
+ });
77
+ }
78
+ const timing = { startedAtMs, completedAtMs: Date.now() };
79
+ await onActiveCreated?.(agent, created[index], timing);
80
+ await onAgentCreated?.(agent, created[index], timing);
81
+ }));
82
+ const failed = prepared.find((outcome) => outcome.status === 'rejected');
83
+ if (failed)
84
+ throw failed.reason;
85
+ }
86
+ }));
87
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected');
88
+ if (failed)
89
+ throw failed.reason;
90
+ return created.flat();
63
91
  }
64
92
  /** Create runners for one EvolAgent, used by runtime hot-load. */
65
- async createForAgent(agent, callbacks, creationErrors) {
93
+ async createForAgent(agent, callbacks, creationErrors, selectPlugin = () => true, onCreating) {
66
94
  const instances = [];
67
95
  for (const [pluginName, plugin] of this.plugins) {
96
+ if (!selectPlugin(pluginName))
97
+ continue;
68
98
  if (!plugin.isEnabled(agent)) {
69
99
  logger.debug(`Plugin '${pluginName}' disabled for agent '${agent.name}', skipping`);
70
100
  continue;
@@ -72,7 +102,10 @@ export class AgentLoader {
72
102
  let teardown;
73
103
  const lifecycle = new PluginHandle(`${agent.name}::${pluginName}`, () => teardown?.());
74
104
  try {
75
- const instance = await plugin.createAgent(agent, callbacks, lifecycle);
105
+ const instance = await this.withCreationSlot(pluginName, async () => {
106
+ onCreating?.();
107
+ return await plugin.createAgent(agent, callbacks, lifecycle);
108
+ });
76
109
  if (!instance) {
77
110
  await lifecycle.dispose();
78
111
  logger.debug(`Plugin '${pluginName}' returned null for agent '${agent.name}', skipping`);
@@ -43,6 +43,13 @@ export function showActivitiesPolicy(mode, chatType, _identity) {
43
43
  export class ChannelLoader {
44
44
  processDebug;
45
45
  aunDefaultEncrypt;
46
+ connectionAdmission;
47
+ setConnectionAdmission(admit) {
48
+ this.connectionAdmission = admit;
49
+ }
50
+ connectInstance(instance) {
51
+ return this.connectionAdmission ? this.connectionAdmission(instance) : instance.connect();
52
+ }
46
53
  plugins = new Map();
47
54
  providerStatuses = new Map();
48
55
  instanceStatuses = new Map();
@@ -141,15 +148,12 @@ export class ChannelLoader {
141
148
  * AUN is always created implicitly from agent.aid (no explicit entry required).
142
149
  */
143
150
  async createForAgent(agent) {
151
+ const aun = await this.createAunForAgent(agent);
152
+ const external = await this.createExternalForAgent(agent);
153
+ return [...aun, ...external];
154
+ }
155
+ async createAunForAgent(agent) {
144
156
  assertAgentAidAvailable(agent.aid);
145
- const ctx = {
146
- agentName: agent.aid,
147
- defaultProjectPath: agent.config.projects?.defaultPath ?? process.cwd(),
148
- debug: this.processDebug,
149
- aunDefaultEncrypt: this.aunDefaultEncrypt,
150
- };
151
- // Build the full list of config instances to create.
152
- // AUN is synthesised from agent.aid; any explicit aun entry in channels[] is skipped.
153
157
  const aunEffName = agent.effectiveChannelName('aun', 'main');
154
158
  const aunInst = {
155
159
  type: 'aun',
@@ -158,14 +162,26 @@ export class ChannelLoader {
158
162
  enabled: true,
159
163
  keystorePath: agent.config.aun?.keystorePath,
160
164
  };
161
- const configInsts = [aunInst];
165
+ return this._buildInstances([aunInst], this.buildContext(agent));
166
+ }
167
+ async createExternalForAgent(agent) {
168
+ assertAgentAidAvailable(agent.aid);
169
+ const configInsts = [];
162
170
  for (const inst of agent.config.channels) {
163
171
  if (inst.type === 'aun')
164
172
  continue;
165
173
  const effName = agent.effectiveChannelName(inst.type, inst.name);
166
174
  configInsts.push({ ...inst, name: effName });
167
175
  }
168
- return this._buildInstances(configInsts, ctx);
176
+ return this._buildInstances(configInsts, this.buildContext(agent));
177
+ }
178
+ buildContext(agent) {
179
+ return {
180
+ agentName: agent.aid,
181
+ defaultProjectPath: agent.config.projects?.defaultPath ?? process.cwd(),
182
+ debug: this.processDebug,
183
+ aunDefaultEncrypt: this.aunDefaultEncrypt,
184
+ };
169
185
  }
170
186
  /** Build runtime instances for a list of config instances + context. */
171
187
  async _buildInstances(configInsts, ctx) {
@@ -278,7 +294,9 @@ export class ChannelLoader {
278
294
  throw error;
279
295
  }
280
296
  }
281
- async connectAll(instances, { concurrency = 3, intervalMs = 50, beforeConnect, shouldConnect, onConnected, onFailed } = {}) {
297
+ async connectAll(instances, { concurrency = 3, intervalMs = 50, beforeConnect, shouldConnect, onConnected, onFailed, connect, sharedAdmission = false } = {}) {
298
+ if (sharedAdmission && !connect)
299
+ throw new Error('Shared connection admission requires a connect callback');
282
300
  const connected = [];
283
301
  const failed = [];
284
302
  const inflight = new Set();
@@ -294,7 +312,9 @@ export class ChannelLoader {
294
312
  const startConnection = (inst) => {
295
313
  const task = (async () => {
296
314
  try {
297
- await inst.connect();
315
+ const started = await (connect ? connect(inst) : this.connectInstance(inst));
316
+ if (started === false || inst.lifecycle?.signal.aborted || shouldConnect?.(inst) === false)
317
+ return;
298
318
  connected.push(inst.adapter.channelName);
299
319
  if (onConnected) {
300
320
  void Promise.resolve().then(() => onConnected(inst)).catch(callbackErr => {
@@ -327,6 +347,13 @@ export class ChannelLoader {
327
347
  }
328
348
  return;
329
349
  }
350
+ if (sharedAdmission) {
351
+ // Do not hide ready priority work behind a second FIFO whose slots
352
+ // include time spent waiting in the actual shared admission queue.
353
+ if (shouldConnect?.(inst) !== false)
354
+ startConnection(inst);
355
+ return;
356
+ }
330
357
  const dispatch = dispatchTail.then(async () => {
331
358
  while (inflight.size >= Math.max(1, concurrency))
332
359
  await Promise.race(inflight);
@@ -538,7 +565,12 @@ export function buildReloadHooks(deps) {
538
565
  try {
539
566
  registerChannelInstance(newInst);
540
567
  onChannelStarted?.(newInst);
541
- await newInst.connect();
568
+ const started = await channelLoader.connectInstance(newInst);
569
+ if (started === false) {
570
+ await newInst.disconnect();
571
+ unregisterChannelInstance?.(channelName);
572
+ return;
573
+ }
542
574
  channelInstances.push(newInst);
543
575
  await onChannelConnected?.(newInst);
544
576
  logger.info(`[Reload] Started channel: ${channelName}`);
@@ -16,6 +16,7 @@ import { isManagementRole } from '../config/builtin-roles.js';
16
16
  import { pendingInterruptHints } from './message/pending-hints.js';
17
17
  import { logger } from '../utils/logger.js';
18
18
  import { sessionLocalTopicId } from './thread/topic-id.js';
19
+ import { StartupTaskQueue } from './daemon-lifecycle.js';
19
20
  export function createAgentStorageClientResolver(channelInstances) {
20
21
  return (channelKey, targetAid) => {
21
22
  const instance = channelInstances.find(candidate => candidate.channelType === 'aun'
@@ -27,14 +28,15 @@ export function createAgentStorageClientResolver(channelInstances) {
27
28
  return client?.aid === targetAid ? client : undefined;
28
29
  };
29
30
  }
30
- export function bindStartupChannelsToAgents(channelInstances, agentRegistry, agentInstances) {
31
+ export function bindStartupChannelsToAgents(channelInstances, agentRegistry, agentInstances, onDemandAids) {
31
32
  for (const instance of channelInstances) {
32
33
  const agent = agentRegistry.resolveByChannel(instance.adapter.channelKey);
33
- if (!agent || agent.status === 'error')
34
+ if (!agent || agent.status === 'error' || agent.status === 'disabled')
34
35
  continue;
35
36
  agent.channels.set(instance.adapter.channelKey, instance.adapter);
36
37
  const hasRunner = agentInstances.some(runner => runner.evolagentName === agent.aid);
37
- if (agent.status === 'stopped' && hasRunner)
38
+ // Agent admission is separate from whether its backend is already loaded.
39
+ if (agent.status === 'stopped' && (hasRunner || onDemandAids?.has(agent.aid)))
38
40
  agent.status = 'running';
39
41
  }
40
42
  }
@@ -61,58 +63,133 @@ export function preloadChannelThreads(channelInstances, sessionManager) {
61
63
  }
62
64
  export function createChannelConnectionRuntime(dependencies) {
63
65
  const { channelInstances, connectedChannels } = dependencies;
64
- const queuePendingObserverHints = (aid, channelKey) => (pendingInterruptHints(dependencies.sessionsDir, aid)
65
- .filter(pending => pending.channelKey === channelKey)
66
- .map(pending => dependencies.responseEngine.scheduleObserverHint({ ...pending, selfAid: aid })
67
- .then(result => {
68
- if (result === 'SESSION_NOT_FOUND')
69
- logger.warn(`[ObserverHint] recovery target missing hint=${pending.hintId}`);
70
- })
71
- .catch(error => logger.warn(`[ObserverHint] recovery failed hint=${pending.hintId}: ${error}`))));
66
+ const followups = new StartupTaskQueue();
67
+ const connections = new Map();
68
+ const subscriptions = new Map();
69
+ const queuePendingObserverHints = async (aid, channelKey) => {
70
+ const pending = await pendingInterruptHints(dependencies.sessionsDir, aid, channelKey);
71
+ if (dependencies.isCancelled?.())
72
+ return;
73
+ const results = await Promise.allSettled(pending.map(pending => dependencies.responseEngine.scheduleObserverHint({ ...pending, selfAid: aid })
74
+ .then(result => {
75
+ if (result === 'SESSION_NOT_FOUND')
76
+ logger.warn(`[ObserverHint] recovery target missing hint=${pending.hintId}`);
77
+ })
78
+ .catch(error => {
79
+ logger.warn(`[ObserverHint] recovery failed hint=${pending.hintId}: ${error}`);
80
+ throw error;
81
+ })));
82
+ const failure = results.find(result => result.status === 'rejected');
83
+ if (failure?.status === 'rejected')
84
+ throw failure.reason;
85
+ };
72
86
  const markChannelConnected = async (instance) => {
73
87
  const name = instance.adapter.channelName;
74
88
  const key = instance.adapter.channelKey;
75
- if (connectedChannels.has(key))
89
+ if (dependencies.isCancelled?.() || !channelInstances.includes(instance)
90
+ || instance.lifecycle?.signal.aborted || instance.channel.getStatus?.().connected === false)
91
+ return;
92
+ if (connections.get(key)?.instance === instance)
76
93
  return;
94
+ const connection = { instance };
95
+ connections.set(key, connection);
77
96
  connectedChannels.add(name);
78
97
  connectedChannels.add(key);
79
98
  const type = instance.channelType || name;
80
99
  dependencies.eventBus.publish({ type: 'channel:connected', channel: type.toLowerCase(), channelName: name, timestamp: Date.now() });
81
100
  const agent = dependencies.resolveOwningAgent(key, name);
101
+ if (instance.channelType === 'aun' && agent && !dependencies.isStartupRecoveryPending()) {
102
+ void queuePendingObserverHints(agent.aid, key)
103
+ .catch(error => logger.warn(`[ObserverHint] reconnect recovery failed for ${agent.aid}: ${error}`));
104
+ }
105
+ const valid = () => !dependencies.isCancelled?.()
106
+ && connections.get(key) === connection && channelInstances.includes(instance)
107
+ && instance.lifecycle?.signal.aborted !== true
108
+ && instance.channel.getStatus?.().connected !== false;
109
+ const enqueue = (name, run) => followups.run(async () => {
110
+ try {
111
+ await run();
112
+ }
113
+ catch (error) {
114
+ logger.warn(`[ChannelStartup] ${key} ${name} failed: ${error}`);
115
+ }
116
+ }, valid);
117
+ // AUN protocol work and external platform notices have separate assembly.
82
118
  if (instance.channelType === 'aun' && agent) {
83
- const recoveries = queuePendingObserverHints(agent.aid, key);
84
- if (dependencies.isStartupRecoveryPending())
85
- dependencies.startupObserverRecoveries.push(...recoveries);
119
+ let authorizationReady = false;
120
+ while (valid() && !authorizationReady) {
121
+ await enqueue('authorization', async () => {
122
+ authorizationReady = await dependencies.refreshAunAuthorization?.(agent.aid) !== false;
123
+ });
124
+ if (valid() && !authorizationReady) {
125
+ await new Promise(resolve => { const timer = setTimeout(resolve, 1_000); timer.unref?.(); });
126
+ }
127
+ }
128
+ if (valid())
129
+ await enqueue('lifecycle notice', () => dependencies.sendLifecycleNoticeForChannel?.(instance));
86
130
  }
87
- await Promise.all([
88
- dependencies.bootstrapService.tryStartBootstrap({
89
- adapter: instance.adapter,
90
- channelKey: key,
91
- channelType: instance.channelType || type,
92
- source: 'connected',
93
- }),
94
- agent ? dependencies.ensureTriggerSchedulerStarted(agent) : Promise.resolve(),
95
- Promise.resolve().then(() => dependencies.sendOnlineNoticeForChannel(instance)),
96
- Promise.resolve().then(() => dependencies.sendLifecycleNoticeForChannel?.(instance)),
97
- dependencies.trySendPendingRestartNotice(),
98
- ]);
131
+ else {
132
+ await enqueue('online notice', () => dependencies.sendOnlineNoticeForChannel(instance));
133
+ }
134
+ await enqueue('bootstrap', () => dependencies.bootstrapService.tryStartBootstrap({
135
+ adapter: instance.adapter,
136
+ channelKey: key,
137
+ channelType: instance.channelType || type,
138
+ source: 'connected',
139
+ }));
140
+ await enqueue('restart notice', () => dependencies.trySendPendingRestartNotice());
99
141
  };
100
142
  const markChannelDisconnected = (channelName) => {
101
143
  connectedChannels.delete(channelName);
102
- const instance = channelInstances.find(candidate => candidate.adapter.channelName === channelName);
144
+ const instance = channelInstances.find(candidate => candidate.adapter.channelName === channelName
145
+ || candidate.adapter.channelKey === channelName);
103
146
  if (instance)
104
147
  connectedChannels.delete(instance.adapter.channelKey);
148
+ if (instance)
149
+ connectedChannels.delete(instance.adapter.channelName);
150
+ if (instance)
151
+ connections.delete(instance.adapter.channelKey);
105
152
  };
106
153
  const unregisterRuntimeChannel = (channelName) => {
154
+ for (const [instance, unsubscribe] of subscriptions) {
155
+ if (instance.adapter.channelName === channelName || instance.adapter.channelKey === channelName) {
156
+ unsubscribe();
157
+ subscriptions.delete(instance);
158
+ }
159
+ }
107
160
  markChannelDisconnected(channelName);
108
161
  dependencies.processor.unregisterChannel(channelName);
109
162
  dependencies.commandHandler.unregisterChannel(channelName);
110
163
  dependencies.messageBridge.removeChannel(channelName);
111
164
  };
112
- return { markChannelConnected, markChannelDisconnected, unregisterRuntimeChannel, queuePendingObserverHints };
165
+ const observeChannel = (instance) => {
166
+ if (instance.channelType !== 'aun' || subscriptions.has(instance)
167
+ || typeof instance.channel.onTransportState !== 'function')
168
+ return;
169
+ const unsubscribe = instance.channel.onTransportState((ready) => {
170
+ if (!channelInstances.includes(instance) || instance.lifecycle?.signal.aborted)
171
+ return;
172
+ if (ready)
173
+ void markChannelConnected(instance).catch(error => logger.warn(`[ChannelStartup] ${instance.adapter.channelKey}: ${error}`));
174
+ else if (connections.get(instance.adapter.channelKey)?.instance === instance)
175
+ markChannelDisconnected(instance.adapter.channelKey);
176
+ });
177
+ subscriptions.set(instance, unsubscribe);
178
+ instance.lifecycle?.defer(unsubscribe, 'AUN transport readiness');
179
+ };
180
+ return {
181
+ markChannelConnected, markChannelDisconnected, unregisterRuntimeChannel, queuePendingObserverHints, observeChannel,
182
+ stop: () => {
183
+ followups.stop();
184
+ connections.clear();
185
+ for (const unsubscribe of subscriptions.values())
186
+ unsubscribe();
187
+ subscriptions.clear();
188
+ },
189
+ };
113
190
  }
114
191
  export function registerChannelInstance(inst, dependencies) {
115
- const { defaultProjectPath, defaultPolicy, processor, commandHandler, interactionRouter, messageBridge, eventBus, sessionManager, responseEngine, resolveOwningAgent, } = dependencies;
192
+ const { defaultProjectPath, defaultPolicy, processor, commandHandler, interactionRouter, messageBridge, eventBus, sessionManager, resolveOwningAgent, } = dependencies;
116
193
  wrapChannelSend(inst, {
117
194
  eventBus,
118
195
  sessionManager,
@@ -142,21 +219,15 @@ export function registerChannelInstance(inst, dependencies) {
142
219
  const channelType = inst.channelType || inst.adapter.channelName;
143
220
  inst.registerBridge?.(messageBridge, channelType);
144
221
  inst.registerHooks?.({ eventBus, sessionManager, lifecycle: inst.lifecycle });
145
- const channelForObserver = inst.channel;
146
- if (typeof channelForObserver.setObserverConfigResolver === 'function') {
222
+ if (inst.channelType === 'aun') {
147
223
  const channelKey = inst.adapter.channelKey;
148
- channelForObserver.setObserverConfigResolver(() => {
149
- const owningAgent = resolveOwningAgent(channelKey, inst.adapter.channelName);
150
- return {
151
- observable: owningAgent?.getObservable() ?? false,
152
- owners: owningAgent ? getOwners(owningAgent.aid) : [],
153
- };
224
+ inst.channel.setObserverConfigResolver(() => {
225
+ const agent = dependencies.resolveOwningAgent(channelKey, inst.adapter.channelName);
226
+ return { observable: agent?.getObservable() ?? false, owners: agent ? getOwners(agent.aid) : [] };
154
227
  });
155
- }
156
- if (inst.channelType === 'aun') {
157
- channelForObserver.setObserverHintRuntime({
158
- hasSession: target => responseEngine.hasObserverTargetSession(target),
159
- schedule: target => responseEngine.scheduleObserverHint(target),
228
+ inst.channel.setObserverHintRuntime({
229
+ hasSession: (target) => dependencies.responseEngine.hasObserverTargetSession(target),
230
+ schedule: (target) => dependencies.responseEngine.scheduleObserverHint(target),
160
231
  });
161
232
  }
162
233
  inst.channel.onRecall?.((messageId, selfAID) => {
@@ -171,11 +242,11 @@ export function createChannelStartupNotifications({ channelInstances, agentRegis
171
242
  const sendOnlineNoticeForChannel = (inst) => {
172
243
  // AUN 的上线提示改走 volatile 生命周期通知(见 lifecycle-notice.ts),
173
244
  // 这里只保留非 AUN 渠道的 durable 通知,避免同时开启时重复两条。
174
- if (inst.channelType === 'aun')
245
+ if (!upmsg || inst.channelType === 'aun')
175
246
  return;
176
247
  const name = inst.adapter.channelName;
177
248
  const agent = agentRegistry.resolveByChannel(inst.adapter.channelKey) ?? agentRegistry.resolveByChannel(name);
178
- if (!agent || !upmsg)
249
+ if (!agent)
179
250
  return;
180
251
  const ownerAid = getFirstStaticAgentOwner(agent.aid);
181
252
  if (!ownerAid)
@@ -146,7 +146,7 @@ async function execOneShotCreate(a, peerId, service, subject) {
146
146
  }
147
147
  if (a.chatmode !== undefined && (!a.chatmode || typeof a.chatmode !== 'object' || Array.isArray(a.chatmode)
148
148
  || Object.entries(a.chatmode).some(([key, value]) => !['private', 'group', 'nothuman'].includes(key)
149
- || !(key === 'group' ? ['proactive'] : ['interactive', 'proactive', ...(key === 'private' ? ['paactive'] : [])]).includes(value)))) {
149
+ || !(key === 'group' ? ['proactive'] : ['interactive', 'proactive']).includes(value)))) {
150
150
  return { error: 'chatmode 必须包含有效的 private/group/nothuman 模式', code: 'INVALID_ARGS' };
151
151
  }
152
152
  let avatarUrl;
@@ -4,7 +4,7 @@ import { readAunPeerKind } from '../relation/peer-identity.js';
4
4
  import { listStaticAgentOwners } from '../../config/peer-role-resolver.js';
5
5
  import { authorizeOperation } from '../auth/auth-gateway.js';
6
6
  import { auditCommandAuthorization } from '../auth/authorization-audit.js';
7
- import { DataRootError } from './pa-workspace-store.js';
7
+ import { DataRootError } from './team-workspace-store.js';
8
8
  const ROOT_TTL_MS = 10 * 60_000;
9
9
  const OPERATIONS = {
10
10
  root: 'file.root.storage', list: 'file.storage.list', query: 'file.storage.query',
@@ -1,42 +1,8 @@
1
- import { ConfigError, ConfigTarget, mutateConfig, routeFieldPath, } from '../../config/config-manager.js';
2
- import { formatPeerKey, parsePeerKey, readAunPeerKind } from '../relation/peer-identity.js';
1
+ import { mutateConfig, routeFieldPath, } from '../../config/config-manager.js';
3
2
  /** Both command entry points authorize the operation before calling this writer. */
4
- export function writeChatmodeConfig(target, value, subject) {
3
+ export function writeChatmodeConfig(target, value) {
5
4
  const route = routeFieldPath(`chatmode.${target.field}`, target.scope);
6
5
  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
6
  const block = config.chatmode && typeof config.chatmode === 'object' && !Array.isArray(config.chatmode)
41
7
  ? { ...config.chatmode }
42
8
  : {};