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
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import fs from 'fs';
19
19
  import path from 'path';
20
- import { resolvePaths, agentDir, agentPersonalDir, kitsTemplatesDir, SOUL_PERSONA_FILE, } from './paths.js';
20
+ import { resolvePaths, agentDir, agentOutputDir, agentPersonalDir, kitsTemplatesDir, SOUL_PERSONA_FILE, } from './paths.js';
21
21
  import { atomicReadJson, atomicWriteJson } from './utils/atomic-write.js';
22
22
  import { registerFile as registerFileIntegrity } from './core/file-integrity/store.js';
23
23
  import { checkAgentDir, isValidAid } from './aun/aid/validation.js';
@@ -675,6 +675,7 @@ export function ensureAgentDirSkeleton(aid) {
675
675
  for (const sub of subs) {
676
676
  fs.mkdirSync(path.join(root, sub), { recursive: true });
677
677
  }
678
+ fs.mkdirSync(agentOutputDir(aid), { recursive: true });
678
679
  ensureSoulDir(aid);
679
680
  }
680
681
  /** soul 目录骨架:模板位于 `kits/templates/soul/`,文件名与目标完全一致。 */
@@ -39,6 +39,17 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
39
39
  if (!taskSession || taskSession.selfAID !== delegation.grant.selfAid) {
40
40
  return fail('INVALID_DELEGATION', 'delegation does not match the current session');
41
41
  }
42
+ let templateOperation;
43
+ if (sub === 'template') {
44
+ try {
45
+ const { parseTemplateCommand } = await import('../cli/agent-template.js');
46
+ const parsed = parseTemplateCommand(argv.slice(2));
47
+ templateOperation = 'agent.template.' + (parsed.action === 'status' ? 'query' : parsed.action);
48
+ }
49
+ catch (error) {
50
+ return fail(error.code ?? 'INVALID_ARGUMENT', error.message);
51
+ }
52
+ }
42
53
  if (shorthand)
43
54
  argv = ['agent', 'show', ...argv.slice(1)];
44
55
  const taskAid = delegation.grant.selfAid;
@@ -53,7 +64,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
53
64
  if (delegation.grant.chatType !== 'private')
54
65
  return fail('NOT_ALLOWED', 'welcome requires a private conversation');
55
66
  }
56
- const targetAid = sub === 'list'
67
+ const targetAid = sub === 'list' || sub === 'template'
57
68
  ? undefined
58
69
  : sub === 'welcome'
59
70
  ? taskAid
@@ -71,7 +82,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
71
82
  return fail('INVALID_ARGS', error.message);
72
83
  }
73
84
  }
74
- const operation = sub === 'list' ? 'agent.list'
85
+ const operation = templateOperation ?? (sub === 'list' ? 'agent.list'
75
86
  : sub === 'show' ? 'agent.show'
76
87
  : sub === 'welcome' ? 'agent.welcome'
77
88
  : sub === 'rename' ? 'agent.rename'
@@ -80,7 +91,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
80
91
  : sub === 'enable' ? 'agent.enable'
81
92
  : sub === 'disable' ? 'agent.disable'
82
93
  : sub === 'reload' ? 'agent.reload'
83
- : sub === 'delete' ? 'agent.delete' : undefined;
94
+ : sub === 'delete' ? 'agent.delete' : undefined);
84
95
  if (!operation)
85
96
  return fail('INVALID_ARGS', `unsupported managed agent command: ${sub}`);
86
97
  if (sub === 'delete' && argv.includes('--purge') && !argv.includes('--confirm-purge')) {
@@ -109,7 +120,7 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
109
120
  subject,
110
121
  intent: {
111
122
  operation,
112
- scope: operation === 'agent.show' || operation === 'agent.welcome' || operation === 'agent.rename'
123
+ scope: templateOperation ? 'process' : operation === 'agent.show' || operation === 'agent.welcome' || operation === 'agent.rename'
113
124
  ? 'agent'
114
125
  : operation === 'agent.reload' && targetAid
115
126
  ? 'agent'
@@ -129,6 +140,16 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
129
140
  const reasonCode = decision.command?.reasonCode;
130
141
  return fail(decision.code, decision.reason, reasonCode);
131
142
  }
143
+ if (templateOperation) {
144
+ try {
145
+ const { executeTemplateCommand } = await import('../cli/agent-template.js');
146
+ const result = await executeTemplateCommand(delegation.grant.actorId, argv.slice(2));
147
+ return result.ok ? { ok: true, result } : result;
148
+ }
149
+ catch (error) {
150
+ return fail(error.code ?? 'INVALID_ARGUMENT', error.message);
151
+ }
152
+ }
132
153
  const { execAgentAction, execAgentOptions, execAgentQuery } = await import('./command/agent-control.js');
133
154
  if (operation === 'agent.list') {
134
155
  const result = await execAgentOptions({ options: 'all' }, agentApplicationService);
@@ -19,10 +19,7 @@ export class AgentReloadCoordinator {
19
19
  return Math.max(0, this.deps.getBusyCount(aid));
20
20
  }
21
21
  runExclusive(aid, operation, options = {}) {
22
- const previous = this.inFlight.get(aid) ?? Promise.resolve();
23
- const pending = previous
24
- .catch(() => undefined)
25
- .then(async () => {
22
+ return this.runRunnerOperation(aid, async () => {
26
23
  const releaseWorkGate = await this.deps.acquireWorkGate?.(aid);
27
24
  try {
28
25
  const busyCount = this.busyCount(aid);
@@ -36,6 +33,11 @@ export class AgentReloadCoordinator {
36
33
  await releaseWorkGate?.();
37
34
  }
38
35
  });
36
+ }
37
+ /** Serialize runner creation with mutations, without rejecting the task that requested it as busy. */
38
+ runRunnerOperation(aid, operation) {
39
+ const previous = this.inFlight.get(aid) ?? Promise.resolve();
40
+ const pending = previous.catch(() => undefined).then(operation);
39
41
  this.inFlight.set(aid, pending);
40
42
  return pending.finally(() => {
41
43
  if (this.inFlight.get(aid) === pending)
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
+ import { BaseagentRunnerUnavailableError } from '../agents/runner-types.js';
3
4
  import { buildReloadHooks } from './channel-loader.js';
4
5
  import { AgentReloadBusyError, AgentReloadCoordinator } from './agent-reload-coordinator.js';
5
6
  import { detectDuplicates } from './evolagent-registry.js';
@@ -50,13 +51,90 @@ export function loadStartupAgentRegistry(agentRegistry) {
50
51
  }
51
52
  return { primaryAgent, runtimeStatus };
52
53
  }
53
- export async function createStartupAgentRunners({ agentRegistry, agentLoader, sessionManager, primaryAgent, agentInstances: publishedInstances, agentMap: publishedMap, configureInstances, isCancelled, onAgentCreated, onAgentReady, startupPriority, }) {
54
+ /** The map is the cache; only simultaneous requests share an in-flight promise. */
55
+ export function createOnDemandAgentRunners(deps) {
56
+ const pending = new Map();
57
+ const assertRunning = () => {
58
+ if (deps.isCancelled())
59
+ throw new Error('Daemon is shutting down');
60
+ };
61
+ const ensure = (aid, baseagent) => {
62
+ const key = `${aid}::${baseagent}`;
63
+ if (deps.isCancelled())
64
+ return Promise.reject(new Error('Daemon is shutting down'));
65
+ if (pending.has(key))
66
+ return pending.get(key);
67
+ // Admission waits outside the mutation lock: startup never needs a lock
68
+ // held by a caller waiting for the same Agent's initial publication.
69
+ const operation = (async () => {
70
+ await deps.waitForStartup(aid);
71
+ assertRunning();
72
+ await deps.coordinator.runRunnerOperation(aid, async () => {
73
+ assertRunning();
74
+ const agent = deps.agentRegistry.get(aid);
75
+ const available = agent && agent.config.enabled !== false && agent.status !== 'disabled' && agent.status !== 'stopped'
76
+ ? deps.agentLoader.enabledBaseagents(agent) : [];
77
+ if (!agent || !available.includes(baseagent)) {
78
+ throw new BaseagentRunnerUnavailableError(aid, baseagent, available);
79
+ }
80
+ if (deps.agentMap.has(key))
81
+ return;
82
+ const errors = [];
83
+ const startedAt = Date.now();
84
+ const instances = await deps.agentLoader.createForAgent(agent, deps.callbacks, errors, backend => backend === baseagent, assertRunning);
85
+ try {
86
+ assertRunning();
87
+ if (deps.agentRegistry.get(aid) !== agent)
88
+ throw new Error(`Agent changed while loading ${key}`);
89
+ const instance = instances.find(candidate => candidate.baseagent === baseagent);
90
+ if (!instance) {
91
+ const loaded = [...deps.agentMap.keys()].filter(key => key.startsWith(`${aid}::`))
92
+ .map(key => key.slice(aid.length + 2));
93
+ const error = new BaseagentRunnerUnavailableError(aid, baseagent, loaded);
94
+ if (errors.length)
95
+ error.cause = new Error(errors.map(item => item.message).join('; '));
96
+ throw error;
97
+ }
98
+ deps.configure(instances);
99
+ deps.agentMap.set(key, instance.agent);
100
+ }
101
+ catch (error) {
102
+ await disposeAgentInstances(instances);
103
+ throw error;
104
+ }
105
+ deps.onLoaded?.();
106
+ logger.info(`[Runner] Loaded on demand: ${key} duration=${Date.now() - startedAt}ms`);
107
+ });
108
+ })();
109
+ const result = operation.finally(() => { if (pending.get(key) === result)
110
+ pending.delete(key); });
111
+ pending.set(key, result);
112
+ return result;
113
+ };
114
+ return {
115
+ ensure,
116
+ isLoading: (aid, baseagent) => pending.has(`${aid}::${baseagent}`),
117
+ // Called after cancellation; late creations dispose themselves instead of
118
+ // publishing into the map after shutdown has taken its disposal snapshot.
119
+ waitForIdle: async () => { await Promise.allSettled([...pending.values()]); },
120
+ };
121
+ }
122
+ export async function createStartupAgentRunners({ agentRegistry, agentLoader, sessionManager, primaryAgent, agentInstances: publishedInstances, agentMap: publishedMap, configureInstances, isCancelled, onAgentCreated, onAgentReady, startupPriority, onAgentStarting, preloadAids, onAgentDeferred, waitForClassification, }) {
54
123
  const creationErrors = [];
55
124
  const agentInstances = publishedInstances ?? [];
56
125
  const agentMap = publishedMap ?? new Map();
57
126
  const primaryBaseagent = primaryAgent?.baseagent ?? 'claude';
58
127
  const published = new Set();
59
128
  const activeSettled = new Set();
129
+ const deferredAgents = new Set();
130
+ if (preloadAids) {
131
+ for (const agent of agentRegistry.runnableAgents()) {
132
+ if (preloadAids.has(agent.aid))
133
+ continue;
134
+ deferredAgents.add(agent.aid);
135
+ await onAgentDeferred?.(agent);
136
+ }
137
+ }
60
138
  const publish = (instances) => {
61
139
  const fresh = instances.filter(instance => !published.has(instance));
62
140
  if (!fresh.length)
@@ -119,14 +197,20 @@ export async function createStartupAgentRunners({ agentRegistry, agentLoader, se
119
197
  : `No agent runner created for ${agent.aid}::${primaryAgent?.aid === agent.aid ? primaryBaseagent : agent.baseagent}`;
120
198
  }
121
199
  await onAgentCreated?.(agent, instances, timing);
122
- }, () => !isCancelled?.(), activeReady, startupPriority);
200
+ }, () => !isCancelled?.(), activeReady, startupPriority, onAgentStarting, preloadAids, waitForClassification ? async (agent) => {
201
+ if (await waitForClassification(agent.aid))
202
+ return true;
203
+ deferredAgents.add(agent.aid);
204
+ await onAgentDeferred?.(agent);
205
+ return false;
206
+ } : undefined);
123
207
  if (!isCancelled?.()) {
124
208
  agentInstances.splice(0, agentInstances.length, ...createdInstances);
125
209
  }
126
210
  const primaryRunnerKey = primaryAgent ? `${primaryAgent.aid}::${primaryBaseagent}` : '<empty>::claude';
127
211
  const agentRunner = primaryAgent ? agentMap.get(primaryRunnerKey) : agentInstances[0]?.agent;
128
212
  let runtimeError;
129
- if (primaryAgent && !agentRunner) {
213
+ if (primaryAgent && !agentRunner && !deferredAgents.has(primaryAgent.aid)) {
130
214
  const primaryCreationErrors = creationErrors.filter(error => error.evolagentName === primaryAgent.name);
131
215
  const creationDetail = primaryCreationErrors.length > 0
132
216
  ? primaryCreationErrors.map(({ baseagent, message }) => `${baseagent}: ${message}`).join('; ')
@@ -142,7 +226,7 @@ export async function createStartupAgentRunners({ agentRegistry, agentLoader, se
142
226
  logger.info('✓ Agent Runtime empty; no runners created');
143
227
  }
144
228
  else {
145
- logger.info(`✓ Runners ready (primary key: ${primaryRunnerKey}, total: ${agentMap.size}, keys: ${[...agentMap.keys()].join(', ')})`);
229
+ logger.info(`✓ Runner startup complete (loaded: ${agentMap.size}, on demand: ${deferredAgents.size}, primary key: ${primaryRunnerKey})`);
146
230
  }
147
231
  return { agentInstances, agentMap, primaryBaseagent, primaryRunnerKey, runtimeError };
148
232
  }
@@ -202,11 +286,14 @@ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionMa
202
286
  handoffRuntime,
203
287
  stageAgentRunners: async (candidate) => {
204
288
  const creationErrors = [];
289
+ // Preserve backends already in use, without loading unused configuration.
290
+ const needed = new Set([...(candidate.config.enabled === false ? [] : [candidate.baseagent]), ...[...agentMap.keys()]
291
+ .filter(key => key.startsWith(`${candidate.aid}::`)).map(key => key.slice(candidate.aid.length + 2))]);
205
292
  const staged = candidate.config.enabled === false
206
293
  ? []
207
294
  : await agentLoader.createForAgent(candidate, {
208
295
  onSessionIdUpdate: async (sessionId, agentSessionId, context) => (await sessionManager.updateAgentSessionIdBySessionId(sessionId, agentSessionId, context?.turn)),
209
- }, creationErrors);
296
+ }, creationErrors, backend => needed.has(backend));
210
297
  const onDisposeError = (instance, error) => {
211
298
  logger.warn(`[Reload] Failed to dispose runner ${instance.evolagentName}::${instance.baseagent}: ${error instanceof Error ? error.message : String(error)}`);
212
299
  };
@@ -214,12 +301,19 @@ export function createAgentReloadRuntime({ agentRegistry, agentLoader, sessionMa
214
301
  await disposeAgentInstances(staged, onDisposeError);
215
302
  throw new Error(creationErrors.map(error => `${error.baseagent}: ${error.message}`).join('; '));
216
303
  }
217
- if (candidate.config.enabled !== false && staged.length === 0 && candidate.config.active_baseagent) {
304
+ if (candidate.config.enabled !== false && !staged.some(instance => instance.baseagent === candidate.baseagent)) {
305
+ await disposeAgentInstances(staged, onDisposeError);
218
306
  throw new Error(`No runner could be created for ${candidate.aid}::${candidate.config.active_baseagent}`);
219
307
  }
220
- for (const instance of staged) {
221
- instance.agent.setPermissionGateway?.(permissionGateway);
222
- instance.agent.setCompactStartCallback?.((sessionId) => processor.handleCompactStart(sessionId));
308
+ try {
309
+ for (const instance of staged) {
310
+ instance.agent.setPermissionGateway?.(permissionGateway);
311
+ instance.agent.setCompactStartCallback?.((sessionId) => processor.handleCompactStart(sessionId));
312
+ }
313
+ }
314
+ catch (error) {
315
+ await disposeAgentInstances(staged, onDisposeError);
316
+ throw error;
223
317
  }
224
318
  return createRunnerReloadTransaction({ aid: candidate.aid, agentMap, staged, onDisposeError });
225
319
  },
@@ -423,7 +517,7 @@ export function createAgentRuntimeOperations({ agentRegistry, agentLoader, sessi
423
517
  const creationErrors = [];
424
518
  const newAgentInstances = await agentLoader.createForAgent(agent, {
425
519
  onSessionIdUpdate: async (sessionId, agentSessionId, context) => (await sessionManager.updateAgentSessionIdBySessionId(sessionId, agentSessionId, context?.turn)),
426
- }, creationErrors);
520
+ }, creationErrors, backend => backend === agent.baseagent);
427
521
  for (const instance of newAgentInstances) {
428
522
  agentMap.set(`${instance.evolagentName}::${instance.baseagent}`, instance.agent);
429
523
  instance.agent.setPermissionGateway?.(permissionGateway);
@@ -590,6 +684,8 @@ const AUDITED_WORKFLOW_SHA256 = {
590
684
  '0.5.32': '7333bede3bb0a5dc5cd7e500dc2c91d23c5c772590659540c640d5f6eabc2f1d',
591
685
  // 0.5.33 adds batch_id propagation; audited start/read/write/notify ordering is unchanged.
592
686
  '0.5.33': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
687
+ // 0.5.34 retains this exact workflow; real SDK read/execute boundaries were revalidated.
688
+ '0.5.34': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
593
689
  };
594
690
  export function initializationBindPreflightFailure(error) {
595
691
  if (!(error instanceof Error) || error.code !== 'ECONNRESET')
@@ -5,6 +5,7 @@ import { hashDelegatedCommandArgv, hasTrustedFullAccessDelegation, trustedExecut
5
5
  import { isManagementRole } from '../../config/builtin-roles.js';
6
6
  import { parsePeerKey } from '../relation/peer-identity.js';
7
7
  import { executeParsedProviderOperation, parseProviderCommand } from '../../config/provider-ipc-service.js';
8
+ import { executeInvokeOperation, parseInvokeArgv } from '../../config/invoke-ipc-service.js';
8
9
  import { MAIN_CLI_BIN } from '../../product.js';
9
10
  import { executeUpgradeOperation, parseUpgradeCommand } from '../../cli/upgrade-command.js';
10
11
  export function createDelegatedUpgradeOperationExecutor({ agentDelegationRegistry, sessionManager, getProcessOwners, }) {
@@ -130,6 +131,71 @@ export function createDelegatedProviderOperationExecutor({ agentDelegationRegist
130
131
  function hashProviderArgv(argv) {
131
132
  return hashDelegatedCommandArgv([MAIN_CLI_BIN, ...argv]);
132
133
  }
134
+ /**
135
+ * 托管会话内的 `ec invoke`。
136
+ *
137
+ * 调用一个已登记的端点不改变任何状态,所以不走 provider 那样的写操作审批;
138
+ * 但仍要求真实的委托令牌,且只允许当前 Agent 自己发起。
139
+ */
140
+ export function createDelegatedInvokeOperationExecutor({ agentDelegationRegistry, sessionManager, getProcessOwners, }) {
141
+ return async function executeDelegatedInvokeOperation(params) {
142
+ const validation = agentDelegationRegistry.validate(params.delegationToken, params.sessionId, params.delegationCommandHash);
143
+ if (!validation.ok)
144
+ return { ok: false, code: validation.code, error: validation.reason };
145
+ const grant = validation.grant;
146
+ const session = await sessionManager.getSessionById(params.sessionId);
147
+ if (!session || session.selfAID !== grant.selfAid) {
148
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'delegation does not match the current session' };
149
+ }
150
+ let parsed;
151
+ try {
152
+ parsed = parseInvokeArgv(params.argv);
153
+ }
154
+ catch (error) {
155
+ return { ok: false, code: 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error) };
156
+ }
157
+ let conversationId;
158
+ try {
159
+ conversationId = parsePeerKey(grant.peerKey).channelId;
160
+ }
161
+ catch {
162
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'delegation contains an invalid relation key' };
163
+ }
164
+ const subject = buildAuthSubject({
165
+ selfAid: grant.selfAid,
166
+ sessionId: params.sessionId,
167
+ requestId: params.requestId,
168
+ actorId: grant.actorId,
169
+ channel: grant.channel,
170
+ channelType: grant.channelType,
171
+ channelId: conversationId,
172
+ chatType: grant.chatType,
173
+ conversationId,
174
+ processOwners: getProcessOwners(),
175
+ ...trustedExecutionIdentityInput(grant),
176
+ });
177
+ return executeAuditedOperation({
178
+ source: 'agent-tool',
179
+ subject,
180
+ intent: {
181
+ operation: 'invoke.execute',
182
+ scope: 'process',
183
+ source: 'agent-tool',
184
+ args: { providerId: parsed.providerId, service: parsed.serviceType },
185
+ },
186
+ auditMetadata: {
187
+ argvHash: hashDelegatedCommandArgv([MAIN_CLI_BIN, ...params.argv]),
188
+ taskId: grant.taskId,
189
+ messageId: grant.messageId,
190
+ sessionId: params.sessionId,
191
+ agentAid: grant.selfAid,
192
+ },
193
+ }, async (onExecutionStarted) => {
194
+ onExecutionStarted();
195
+ return executeInvokeOperation({ argv: params.argv, input: params.input });
196
+ });
197
+ };
198
+ }
133
199
  export function createDelegationAuthorizer({ agentDelegationRegistry, sessionManager, getProcessOwners, }) {
134
200
  return async function authorizeManagedAgentOperation(params, operation) {
135
201
  const delegation = params.delegationGrant
@@ -8,6 +8,8 @@ import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
8
8
  import { sameGroupAid } from '../../aun/group/index.js';
9
9
  import { ownerResolver } from '../ownership/owner-resolver.js';
10
10
  const DAEMON_OWNER_PROCESS_OPERATIONS = new Set([
11
+ ...['inspect', 'build', 'push', 'pull', 'deploy', 'query'].map(action => 'agent.template.' + action),
12
+ 'model.provider.catalog',
11
13
  'agent.list',
12
14
  'agent.create',
13
15
  'agent.initialize',
@@ -156,6 +156,28 @@ 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.rules.current', 'Read event rules (allow/deny)'],
163
+ ['event.rules.update', 'Update event rules (allow/deny)'],
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
+ ['event.publishStats.current', 'Read per-pack event publication statistics'],
170
+ ['event.records.list', 'Read event delivery records'],
171
+ ].map(([id, description]) => ({
172
+ id,
173
+ category: id.endsWith('.current') || id.endsWith('.list') ? 'read' : 'write-agent',
174
+ dangerous: !id.endsWith('.current') && !id.endsWith('.list'),
175
+ defaultScopes: ['agent'],
176
+ description,
177
+ sources: ['menu'],
178
+ authorizationTarget: 'current-agent',
179
+ minimumAgentRole: 'owner',
180
+ })),
159
181
  ...['read', 'result-read', 'install', 'configure', 'enable', 'disable', 'invoke', 'publish', 'upgrade', 'rollback', 'uninstall', 'grant', 'retire'].map(action => ({
160
182
  id: 'ability.' + action, category: action === 'read' ? 'read' : 'write-agent',
161
183
  dangerous: action !== 'read', defaultScopes: ['agent'], description: 'Manage AID ability plugins: ' + action,
@@ -207,6 +229,13 @@ const OPERATIONS = [
207
229
  sources: ['agent-tool'],
208
230
  },
209
231
  // ── Model Operations ──
232
+ ...['inspect', 'build', 'push', 'pull', 'deploy', 'query'].map(action => ({
233
+ id: 'agent.template.' + action, category: 'process',
234
+ dangerous: !['inspect', 'query'].includes(action), defaultScopes: ['process'],
235
+ description: 'Agent template ' + action, sources: ['menu', 'control', 'agent-tool', 'ecweb'],
236
+ })),
237
+ { id: 'model.provider.catalog', category: 'process', dangerous: false, defaultScopes: ['process'],
238
+ description: 'Read a Provider model catalog without changing Agent configuration', sources: ['menu', 'control', 'ecweb'] },
210
239
  {
211
240
  id: 'baseagent.models.list',
212
241
  category: 'read',