evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -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,129 +41,56 @@ 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, onActiveCreated, startupPriority) {
48
- const instances = [];
49
- const allAgents = registry.runnableAgents();
50
- // A slow CLI consumes only its backend's slots. Keeping one bounded lane
51
- // per plugin prevents four pending Codex probes from starving Claude or
52
- // ecagent Agents later in registry order. Active work precedes standby
53
- // work within each lane, without a barrier between different backends.
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));
54
48
  const created = allAgents.map(() => []);
55
- const startedAt = allAgents.map(() => Date.now());
56
- const activeResolvers = [];
57
- const activeReady = allAgents.map(() => new Promise(resolve => activeResolvers.push(resolve)));
58
49
  const agentsByBackend = new Map();
59
50
  allAgents.forEach((agent, index) => {
60
51
  const indices = agentsByBackend.get(agent.baseagent) ?? [];
61
52
  indices.push(index);
62
53
  agentsByBackend.set(agent.baseagent, indices);
63
54
  });
64
- const lanes = [...new Set([...this.plugins.keys(), ...agentsByBackend.keys()])];
65
- const completed = allAgents.map(() => 0);
66
- const completeBackend = async (index) => {
67
- if (++completed[index] !== lanes.length)
68
- return;
69
- const agent = allAgents[index];
70
- created[index].sort((left, right) => (left.baseagent === agent.baseagent ? -1 : right.baseagent === agent.baseagent ? 1
71
- : lanes.indexOf(left.baseagent) - lanes.indexOf(right.baseagent)));
72
- await onAgentCreated?.(agent, created[index], { startedAtMs: startedAt[index], completedAtMs: Date.now() });
73
- };
74
- const outcomes = await Promise.allSettled(lanes.map(async (backend) => {
75
- // Priority standby work may wait for a different backend. Keep that wait
76
- // outside this lane's capacity so deferred active runners can proceed
77
- // after a degraded release, while sharing the same four creation slots.
78
- let activeCreations = 0;
79
- const waitingCreations = [];
80
- const create = async (agent) => {
81
- if (activeCreations < 4)
82
- activeCreations++;
83
- else
84
- await new Promise(resolve => waitingCreations.push(resolve));
85
- try {
86
- return shouldCreateAgent()
87
- ? await this.createForAgent(agent, callbacks, creationErrors, name => name === backend) : [];
88
- }
89
- finally {
90
- const next = waitingCreations.shift();
91
- if (next)
92
- next();
93
- else
94
- activeCreations--;
95
- }
96
- };
97
- const standbyTasks = [];
98
- try {
99
- for (const priority of startupPriority ? [true, false] : [true]) {
100
- // Wait outside bounded lanes: deferred Agents cannot occupy capacity
101
- // needed to publish a recovering Agent's active or standby runner.
102
- const groupIndices = allAgents.map((_, index) => index).filter(index => !startupPriority || startupPriority.aids.has(allAgents[index].aid) === priority);
103
- if (!groupIndices.length)
104
- continue;
105
- if (!priority)
106
- await startupPriority.waitForDeferred();
107
- const activeIndices = groupIndices.filter(index => allAgents[index].baseagent === backend);
108
- try {
109
- await mapWithConcurrency(activeIndices, 4, async (index) => {
110
- const agent = allAgents[index];
111
- startedAt[index] = Date.now();
112
- try {
113
- const active = await create(agent);
114
- created[index].push(...active);
115
- await onActiveCreated?.(agent, active, { startedAtMs: startedAt[index], completedAtMs: Date.now() });
116
- await completeBackend(index);
117
- }
118
- finally {
119
- activeResolvers[index]();
120
- }
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');
121
76
  });
122
77
  }
123
- finally {
124
- // A publication callback failure must not strand another lane waiting
125
- // for an Agent this lane could no longer admit.
126
- for (const index of activeIndices)
127
- activeResolvers[index]();
128
- }
129
- const standby = mapWithConcurrency(groupIndices, 4, async (index) => {
130
- const agent = allAgents[index];
131
- if (agent.baseagent === backend)
132
- return;
133
- // The same Agent's active publication configures task callbacks before
134
- // standby publication; other Agents' active lanes remain independent.
135
- await activeReady[index];
136
- created[index].push(...await create(agent));
137
- await completeBackend(index);
138
- }).then(() => { });
139
- standbyTasks.push(standby);
140
- // Observe immediately, then propagate after every lane task settles.
141
- void standby.catch(() => { });
142
- if (!startupPriority)
143
- await standby;
144
- }
145
- const standbyOutcomes = await Promise.allSettled(standbyTasks);
146
- const failure = standbyOutcomes.find((outcome) => outcome.status === 'rejected');
147
- if (failure)
148
- throw failure.reason;
149
- }
150
- finally {
151
- // A callback failure can retire this lane before its deferred group.
152
- // Other backends must still be able to settle their standby waits.
153
- for (const index of agentsByBackend.get(backend) ?? [])
154
- activeResolvers[index]();
155
- await Promise.allSettled(standbyTasks);
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;
156
85
  }
157
86
  }));
158
87
  const failed = outcomes.find((outcome) => outcome.status === 'rejected');
159
88
  if (failed)
160
89
  throw failed.reason;
161
- for (const agentInstances of created)
162
- instances.push(...agentInstances);
163
- return instances;
90
+ return created.flat();
164
91
  }
165
92
  /** Create runners for one EvolAgent, used by runtime hot-load. */
166
- async createForAgent(agent, callbacks, creationErrors, selectPlugin = () => true) {
93
+ async createForAgent(agent, callbacks, creationErrors, selectPlugin = () => true, onCreating) {
167
94
  const instances = [];
168
95
  for (const [pluginName, plugin] of this.plugins) {
169
96
  if (!selectPlugin(pluginName))
@@ -175,7 +102,10 @@ export class AgentLoader {
175
102
  let teardown;
176
103
  const lifecycle = new PluginHandle(`${agent.name}::${pluginName}`, () => teardown?.());
177
104
  try {
178
- 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
+ });
179
109
  if (!instance) {
180
110
  await lifecycle.dispose();
181
111
  logger.debug(`Plugin '${pluginName}' returned null for agent '${agent.name}', skipping`);
@@ -294,7 +294,9 @@ export class ChannelLoader {
294
294
  throw error;
295
295
  }
296
296
  }
297
- async connectAll(instances, { concurrency = 3, intervalMs = 50, beforeConnect, shouldConnect, onConnected, onFailed, connect } = {}) {
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');
298
300
  const connected = [];
299
301
  const failed = [];
300
302
  const inflight = new Set();
@@ -345,6 +347,13 @@ export class ChannelLoader {
345
347
  }
346
348
  return;
347
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
+ }
348
357
  const dispatch = dispatchTail.then(async () => {
349
358
  while (inflight.size >= Math.max(1, concurrency))
350
359
  await Promise.race(inflight);
@@ -28,14 +28,15 @@ export function createAgentStorageClientResolver(channelInstances) {
28
28
  return client?.aid === targetAid ? client : undefined;
29
29
  };
30
30
  }
31
- export function bindStartupChannelsToAgents(channelInstances, agentRegistry, agentInstances) {
31
+ export function bindStartupChannelsToAgents(channelInstances, agentRegistry, agentInstances, onDemandAids) {
32
32
  for (const instance of channelInstances) {
33
33
  const agent = agentRegistry.resolveByChannel(instance.adapter.channelKey);
34
- if (!agent || agent.status === 'error')
34
+ if (!agent || agent.status === 'error' || agent.status === 'disabled')
35
35
  continue;
36
36
  agent.channels.set(instance.adapter.channelKey, instance.adapter);
37
37
  const hasRunner = agentInstances.some(runner => runner.evolagentName === agent.aid);
38
- 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)))
39
40
  agent.status = 'running';
40
41
  }
41
42
  }
@@ -65,8 +66,10 @@ export function createChannelConnectionRuntime(dependencies) {
65
66
  const followups = new StartupTaskQueue();
66
67
  const connections = new Map();
67
68
  const subscriptions = new Map();
68
- const queuePendingObserverHints = async (aid, channelKey) => {
69
- const pending = await pendingInterruptHints(dependencies.sessionsDir, aid, channelKey);
69
+ const queuePendingObserverHints = async (aid, channelKey, snapshot) => {
70
+ const pending = await (snapshot
71
+ ? pendingInterruptHints(dependencies.sessionsDir, aid, channelKey, snapshot)
72
+ : pendingInterruptHints(dependencies.sessionsDir, aid, channelKey));
70
73
  if (dependencies.isCancelled?.())
71
74
  return;
72
75
  const results = await Promise.allSettled(pending.map(pending => dependencies.responseEngine.scheduleObserverHint({ ...pending, selfAid: aid })
@@ -350,17 +353,22 @@ export function createChannelStartupNotifications({ channelInstances, agentRegis
350
353
  ...(restartDelivery.delivery ? { delivery: restartDelivery.delivery } : {}),
351
354
  replyContext: Object.keys(replyContext).length > 0 ? replyContext : undefined,
352
355
  });
353
- const restartNotice = pending.outcome === 'rolled-back'
356
+ const restartNotice = pending.outcome === 'rollback-failed'
354
357
  ? {
355
- text: `⚠️ 服务已重启,但运行的是上一个版本。${pending.outcomeReason ? `原因:${pending.outcomeReason}。` : ''}本次改动未生效,请检查后重试。`,
356
- subtype: 'restarted-rolled-back',
358
+ text: `❌ 升级失败且整包回滚未成功,服务未确认恢复。${pending.outcomeReason ? `原因:${pending.outcomeReason}。` : ''}请检查安装目录和备份。`,
359
+ subtype: 'restarted-rollback-failed',
357
360
  }
358
- : pending.outcome === 'upgraded'
361
+ : pending.outcome === 'rolled-back'
359
362
  ? {
360
- text: `✅ 服务重启成功!${pending.outcomeReason ? `${pending.outcomeReason}` : ''}`,
361
- subtype: 'restarted-upgraded',
363
+ text: `⚠️ 服务已重启,但运行的是上一个版本。${pending.outcomeReason ? `原因:${pending.outcomeReason}。` : ''}本次改动未生效,请检查后重试。`,
364
+ subtype: 'restarted-rolled-back',
362
365
  }
363
- : { text: '✅ 服务重启成功!', subtype: 'restarted' };
366
+ : pending.outcome === 'upgraded'
367
+ ? {
368
+ text: `✅ 服务重启成功!${pending.outcomeReason ? `${pending.outcomeReason}` : ''}`,
369
+ subtype: 'restarted-upgraded',
370
+ }
371
+ : { text: '✅ 服务重启成功!', subtype: 'restarted' };
364
372
  await sendSystemPayload(adapter, envelope, {
365
373
  kind: 'system.notice',
366
374
  text: restartNotice.text,
@@ -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;
@@ -1160,7 +1160,7 @@ export function resolveProjectPath(explicit, aid, defaults) {
1160
1160
  return deriveAgentProjectPath(root, aid);
1161
1161
  }
1162
1162
  /** name=agent 的 menu.query:查单个 agent 详情,附构建进度(D3)。 */
1163
- export async function execAgentQuery(args, service, subject) {
1163
+ export async function execAgentQuery(args, service, subject, runtime) {
1164
1164
  const aid = args?.aid;
1165
1165
  if (!aid)
1166
1166
  return { error: '缺少 aid', code: 'INVALID_ARGS' };
@@ -1224,8 +1224,18 @@ export async function execAgentQuery(args, service, subject) {
1224
1224
  const safeAgentConfig = safeConfig ?? {};
1225
1225
  const ownership = ownerResolver.snapshot(aid);
1226
1226
  const fullaccessStatus = agentFullAccessStatus(aid, subject?.principalId ?? subject?.actorId);
1227
+ // This cross-relation counter is only available to the verified Agent Owner
1228
+ // over a private AUN transport. It never includes counterpart identities.
1229
+ const canReadActivePeers = subject?.selfAid === aid && subject.role === 'owner'
1230
+ && subject.channelType === 'aun' && subject.chatType === 'private'
1231
+ && subject.menuTransportChatType !== 'group' && !subject.fromControlChannel
1232
+ && !!subject.principalId && ownerResolver.isOwner(aid, subject.principalId);
1233
+ const activePeers = canReadActivePeers ? runtime?.getActivePrivatePeerCountBySelfAID?.(aid) : undefined;
1227
1234
  const data = {
1228
1235
  ...res,
1236
+ ...(typeof activePeers === 'number' && Number.isSafeInteger(activePeers) && activePeers >= 0 ? {
1237
+ sessions: { ...res.sessions, active_peers: activePeers },
1238
+ } : {}),
1229
1239
  ...(initialization ? { initialization } : {}),
1230
1240
  ...(usable === undefined ? {} : { usable }),
1231
1241
  config: {
@@ -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',
@@ -0,0 +1,147 @@
1
+ import { isValidAid } from '../../aun/aid/validation.js';
2
+ import { getAgentTemplateService } from '../../agent-template/service.js';
3
+ import { TEMPLATE_ACTIONS, templateError } from '../../agent-template/types.js';
4
+ import { authorizeFreshOperation } from '../auth/auth-gateway.js';
5
+ import { getProviderCatalog } from '../model/model-catalog.js';
6
+ export function isTemplateRequest(request) {
7
+ return (request.name === 'agent' || request.cmd === '/agent')
8
+ && (TEMPLATE_ACTIONS.includes(request.action) || request.args?.view === 'template-job');
9
+ }
10
+ export function isProviderModelCatalog(request) {
11
+ return (request.name === 'model' || request.cmd === '/model') && request.args?.view === 'catalog' && request.args?.scope === 'process';
12
+ }
13
+ export function validateTemplateRequest(request) {
14
+ try {
15
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
16
+ const memberKey = (key) => /^[a-z0-9][a-z0-9_-]{0,31}$/.test(key);
17
+ const validateSelections = (value) => {
18
+ if (value.providers !== undefined && !record(value.providers)
19
+ || value.externalAids !== undefined && (!record(value.externalAids)
20
+ || Object.entries(value.externalAids).some(([from, to]) => !isValidAid(from) || typeof to !== 'string' || !isValidAid(to)))) {
21
+ throw new Error('Invalid member Provider or external AID selections');
22
+ }
23
+ for (const [name, selection] of Object.entries(value.providers ?? {})) {
24
+ if (!['claude', 'codex', 'ecagent', 'gemini'].includes(name) || !record(selection)
25
+ || Object.keys(selection).some(k => !['provider', 'model', 'effort'].includes(k))
26
+ || !/^provider-\d{8}$/.test(selection.provider) || selection.model !== undefined && (typeof selection.model !== 'string' || !selection.model.trim())
27
+ || selection.effort !== undefined && selection.effort !== null && !['low', 'medium', 'high', 'xhigh', 'max'].includes(selection.effort)) {
28
+ throw new Error('Invalid Provider/model/effort selection');
29
+ }
30
+ }
31
+ };
32
+ const args = request.args;
33
+ if (!args || typeof args !== 'object' || Array.isArray(args))
34
+ throw new Error('args object required');
35
+ let allowed;
36
+ if (args.view === 'template-job') {
37
+ if (request.type !== 'menu.query' || !!args.jobId === !!args.requestId)
38
+ throw new Error('Use query with jobId or requestId');
39
+ if (args.jobId !== undefined && !/^job_[a-f0-9-]{36}$/.test(args.jobId)
40
+ || args.requestId !== undefined && (typeof args.requestId !== 'string' || !args.requestId.trim() || args.requestId.length > 200))
41
+ throw new Error('Invalid task identifier');
42
+ allowed = ['view', 'jobId', 'requestId'];
43
+ }
44
+ else {
45
+ if (request.type !== 'menu.action')
46
+ throw new Error('Template actions use menu.action');
47
+ const fields = { inspect: ['aid'], build: ['aid', 'template', 'include'],
48
+ push: ['buildId', 'ownerAid', 'targetPath', 'releasedFindings'], pull: ['location', 'download', 'digest', 'targetAid', 'targets'],
49
+ deploy: ['pullId', 'providers', 'externalAids', 'members'] };
50
+ allowed = fields[request.action];
51
+ if (!allowed)
52
+ throw new Error('Unsupported template action');
53
+ if (['inspect', 'build'].includes(request.action) && !isValidAid(args.aid))
54
+ throw new Error('aid required');
55
+ if (request.action === 'build' && (!args.template?.version || !args.template?.name || !args.include))
56
+ throw new Error('template.version/name and include required');
57
+ if (request.action === 'pull' && (!isValidAid(args.location?.aid)
58
+ || typeof args.location?.path !== 'string' || !args.location.path.startsWith('/templates/')
59
+ || !/^[A-Za-z0-9]{10}$/.test(args.download?.shareId) || !/^sha256:[a-f0-9]{64}$/.test(args.digest)))
60
+ throw new Error('Invalid package location, shareId, digest or targetAid');
61
+ if (request.action === 'pull') {
62
+ if (args.targets === undefined) {
63
+ if (!isValidAid(args.targetAid))
64
+ throw new Error('targetAid or targets mapping required');
65
+ }
66
+ else if (args.targetAid !== undefined || !record(args.targets) || !Object.keys(args.targets).length
67
+ || Object.entries(args.targets).some(([key, aid]) => !memberKey(key) || typeof aid !== 'string' || !isValidAid(aid))
68
+ || new Set(Object.values(args.targets)).size !== Object.keys(args.targets).length) {
69
+ throw new Error('Map members to distinct existing Agent AIDs; do not mix targetAid and targets');
70
+ }
71
+ }
72
+ if (request.action === 'push' && (!/^build_[a-f0-9-]{36}$/.test(args.buildId) || !isValidAid(args.ownerAid)
73
+ || typeof args.targetPath !== 'string' || !args.targetPath.startsWith('/templates/')
74
+ || args.releasedFindings !== undefined && (!Array.isArray(args.releasedFindings) || !args.releasedFindings.every((f) => typeof f === 'string'))))
75
+ throw new Error('Invalid push arguments');
76
+ if (request.action === 'deploy' && (!/^pull_[a-f0-9-]{36}$/.test(args.pullId)
77
+ || args.providers !== undefined && (!args.providers || typeof args.providers !== 'object' || Array.isArray(args.providers))
78
+ || args.externalAids !== undefined && (!args.externalAids || typeof args.externalAids !== 'object' || Array.isArray(args.externalAids)
79
+ || Object.entries(args.externalAids).some(([from, to]) => !isValidAid(from) || typeof to !== 'string' || !isValidAid(to)))))
80
+ throw new Error('Invalid deploy arguments');
81
+ if (request.action === 'deploy') {
82
+ validateSelections(args);
83
+ if (args.members !== undefined) {
84
+ if (!record(args.members) || args.providers !== undefined || args.externalAids !== undefined)
85
+ throw new Error('Use members or single-Agent selections');
86
+ for (const [key, selection] of Object.entries(args.members)) {
87
+ if (!memberKey(key) || !record(selection) || Object.keys(selection).some(k => !['providers', 'externalAids'].includes(k))) {
88
+ throw new Error('Invalid member selection');
89
+ }
90
+ validateSelections(selection);
91
+ }
92
+ }
93
+ }
94
+ }
95
+ if (Object.keys(args).some(k => !allowed.includes(k)))
96
+ throw new Error('Unknown template argument');
97
+ if (request.agent !== undefined)
98
+ throw new Error('Use action target fields, not top-level agent');
99
+ return null;
100
+ }
101
+ catch (error) {
102
+ return { code: 'INVALID_ARGUMENT', message: error.message };
103
+ }
104
+ }
105
+ export async function executeTemplateMenu(request, subject, source) {
106
+ try {
107
+ const invalid = validateTemplateRequest(request);
108
+ if (invalid)
109
+ throw templateError(invalid.code, invalid.message);
110
+ if (!subject?.fromControlChannel || !subject.isDaemonOwner || !subject.principalId
111
+ || subject.processRole === 'daemon-service' || !subject.ecwebManagement && subject.menuEncrypted !== true) {
112
+ throw templateError('NOT_ALLOWED', 'Template operations require an encrypted DaemonOwner Control request', { reason: 'DAEMON_OWNER_REQUIRED' });
113
+ }
114
+ const operation = request.type === 'menu.query' ? 'agent.template.query' : 'agent.template.' + request.action;
115
+ const decision = await authorizeFreshOperation({ source, subject,
116
+ intent: { operation, scope: 'process', source, args: request.args } });
117
+ if (!decision.allow)
118
+ throw templateError('NOT_ALLOWED', 'Template operation denied');
119
+ const service = getAgentTemplateService();
120
+ return { data: request.type === 'menu.query' ? await service.query(subject.principalId, request.args)
121
+ : await service.action(subject.principalId, request.id, request.action, request.args) };
122
+ }
123
+ catch (error) {
124
+ return { error: error.message, code: error.code ?? 'TEMPLATE_FAILED', ...(error.data ? { data: error.data } : {}) };
125
+ }
126
+ }
127
+ export async function executeProviderModelCatalog(request, subject, source) {
128
+ try {
129
+ const args = request.args;
130
+ if (request.type !== 'menu.query' || request.agent !== undefined || !args
131
+ || Object.keys(args).some(k => !['scope', 'view', 'providerId', 'baseagent', 'serviceType', 'refresh'].includes(k))
132
+ || !/^provider-\d{8}$/.test(args.providerId) || !['claude', 'codex', 'ecagent', 'gemini'].includes(args.baseagent)
133
+ || args.refresh !== undefined && typeof args.refresh !== 'boolean'
134
+ || args.serviceType !== undefined && typeof args.serviceType !== 'string')
135
+ throw templateError('INVALID_ARGUMENT', 'Invalid process model catalog query');
136
+ if (!subject?.fromControlChannel || !subject.isDaemonOwner)
137
+ throw templateError('NOT_ALLOWED', 'DaemonOwner Control context required');
138
+ const decision = await authorizeFreshOperation({ source, subject,
139
+ intent: { operation: 'model.provider.catalog', scope: 'process', source, args } });
140
+ if (!decision.allow)
141
+ throw templateError('NOT_ALLOWED', 'Model catalog query denied');
142
+ return { data: await getProviderCatalog(args.providerId, args.serviceType, args.refresh === true, false, args.baseagent) };
143
+ }
144
+ catch (error) {
145
+ return { error: error.message, code: error.code ?? 'MODEL_UNAVAILABLE' };
146
+ }
147
+ }
@@ -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
  : {};