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
@@ -15,7 +15,6 @@ import { logger } from '../../utils/logger.js';
15
15
  import { resolvePeerRoleDetail, roleToSessionIdentity } from '../../config/peer-role-resolver.js';
16
16
  import { ThreadService } from '../thread/thread-service.js';
17
17
  import { isManagementRole } from '../../config/builtin-roles.js';
18
- import { resolveAgentLifecycle } from '../../config/lifecycle.js';
19
18
  import { formatPeerKey } from '../relation/peer-identity.js';
20
19
  import { sameGroupAid } from '../../aun/group/index.js';
21
20
  import crypto from 'crypto';
@@ -57,9 +56,10 @@ import { constrainRuntimePermissionMode, resolveRuntimePermissionMode, validateR
57
56
  import { parsePeerKey } from '../relation/peer-identity.js';
58
57
  import { isQuickCommand } from './slash-gate.js';
59
58
  import { handleSlashCommand } from './slash-handler.js';
60
- import { isChatMode, resolveChatMode } from '../message/peer-mode.js';
59
+ import { resolveChatMode } from '../message/peer-mode.js';
61
60
  import { execMenuAction as menuExecMenuAction, execMenuForEcweb as menuExecMenuForEcweb, execMenuForControl as menuExecMenuForControl, execMenuQuery as menuExecMenuQuery, execMenuUpdate as menuExecMenuUpdate, getMenuItems as menuGetMenuItems, getSubMenuItems as menuGetSubMenuItems, buildTopicForkSourcePayload, } from './menu-handler.js';
62
61
  import { getMenuCatalog, execMenuValueBatch, validateMenuValueBatchArgs } from './menu-catalog.js';
62
+ import { execMenuQueryBatch } from './menu-query-batch.js';
63
63
  import { resolveCurrentSessionLoopTarget, sessionLoopError } from '../session/session-idle-monitor.js';
64
64
  export { isProcessLevelOwner } from './menu-handler.js';
65
65
  const CLI_EXEC_TIMEOUT_MS = 15_000;
@@ -106,6 +106,7 @@ export class CommandHandler {
106
106
  legacySingleRunnerMode;
107
107
  primaryRunnerKey;
108
108
  agentRegistry;
109
+ teamWorkspaceManagementService;
109
110
  memoryConsolidationLauncher;
110
111
  /** /skill refresh 的 daemon 侧入口:重建指定 agent 的技能索引 */
111
112
  skillIndexRefresher;
@@ -234,8 +235,38 @@ export class CommandHandler {
234
235
  logger.error(`[RunnerLookup] unavailable channel=${channel ?? '<none>'} baseagent=${requestedBaseagent || '<missing>'} keys=${[...this.agentMap.keys()].join(',')}`);
235
236
  throw new BaseagentRunnerUnavailableError('<unknown>', requestedBaseagent || '<missing>', []);
236
237
  }
238
+ runnerReadiness;
239
+ configuredBaseagents;
240
+ setRunnerReadiness(ensure, available) {
241
+ this.runnerReadiness = ensure;
242
+ this.configuredBaseagents = available;
243
+ }
244
+ /** Commands that use backend state load it; activity probes keep using getAgent. */
245
+ async ensureAgent(channel, baseagent, selfAid) {
246
+ const owner = selfAid ? this.agentRegistry?.get(selfAid) : channel ? this.agentRegistry?.resolveByChannel(channel) : undefined;
247
+ if (owner && baseagent && this.runnerReadiness) {
248
+ await this.runnerReadiness(owner.aid, baseagent);
249
+ const runner = this.agentMap.get(`${owner.aid}::${baseagent}`);
250
+ if (runner)
251
+ return runner;
252
+ }
253
+ return this.getAgent(channel, baseagent);
254
+ }
255
+ getLoadedAgent(channel, baseagent) {
256
+ const owner = this.agentRegistry?.resolveByChannel(channel);
257
+ if (owner && this.configuredBaseagents) {
258
+ const runner = this.agentMap.get(`${owner.aid}::${baseagent}`);
259
+ if (runner)
260
+ return runner;
261
+ const available = this.configuredBaseagents(owner.aid);
262
+ if (available.includes(baseagent))
263
+ return undefined;
264
+ throw new BaseagentRunnerUnavailableError(owner.aid, baseagent, available);
265
+ }
266
+ return this.getAgent(channel, baseagent);
267
+ }
237
268
  getAvailableBaseagentsForOwner(evolName) {
238
- return loadedBaseagentIds(this.agentMap.keys(), evolName);
269
+ return this.configuredBaseagents?.(evolName) ?? loadedBaseagentIds(this.agentMap.keys(), evolName);
239
270
  }
240
271
  /** Return the stable temporary root for a managed session, if available. */
241
272
  getManagedSessionTempDir(session) {
@@ -255,10 +286,12 @@ export class CommandHandler {
255
286
  getAvailableBaseagents(channel) {
256
287
  const owner = this.agentRegistry?.resolveByChannel(channel);
257
288
  if (!owner) {
258
- return loadedBaseagentIds(this.agentMap.keys());
289
+ return this.configuredBaseagents && this.agentRegistry
290
+ ? [...new Set(this.agentRegistry.list().flatMap(agent => this.configuredBaseagents(agent.aid)))]
291
+ : loadedBaseagentIds(this.agentMap.keys());
259
292
  }
260
293
  const evolName = owner.name || '<unknown>';
261
- return loadedBaseagentIds(this.agentMap.keys(), evolName);
294
+ return this.getAvailableBaseagentsForOwner(evolName);
262
295
  }
263
296
  /** Extract the baseagent component from `primaryRunnerKey` (e.g. `aid::claude` → `claude`). */
264
297
  parseDefaultBaseagent() {
@@ -285,6 +318,14 @@ export class CommandHandler {
285
318
  setAgentRegistry(registry) {
286
319
  this.agentRegistry = registry;
287
320
  }
321
+ setTeamWorkspaceManagementService(service) {
322
+ this.teamWorkspaceManagementService = service;
323
+ }
324
+ /** 事件中心(menu events)。字段名避开既有的进程内 `eventBus`。 */
325
+ eventCenter;
326
+ setEventCenter(registry) {
327
+ this.eventCenter = registry;
328
+ }
288
329
  /** Inject the Core-owned agent application facade after runtime hooks exist. */
289
330
  setAgentApplicationService(service) {
290
331
  this.agentApplicationService = service;
@@ -1038,7 +1079,7 @@ export class CommandHandler {
1038
1079
  return false;
1039
1080
  return !!userId && topic.metadata?.peerId === userId;
1040
1081
  }
1041
- buildTopicMenuItem(s, metadataOnly = false) {
1082
+ async buildTopicMenuItem(s, metadataOnly = false) {
1042
1083
  const displayName = displaySessionTitle(s.name, sessionTopicThreadId(s) || s.id.slice(0, 8));
1043
1084
  const item = {
1044
1085
  value: sessionTopicThreadId(s) ?? '',
@@ -1052,10 +1093,10 @@ export class CommandHandler {
1052
1093
  if (s.agentSessionId) {
1053
1094
  item.agentSessionId = s.agentSessionId;
1054
1095
  if (!metadataOnly) {
1055
- const fileInfo = this.sessionManager.getSessionFileInfo(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1056
- if (fileInfo.turns)
1057
- item.turns = fileInfo.turns;
1058
- const firstMsg = this.sessionManager.readSessionFirstMessage(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1096
+ const summary = await this.sessionManager.readSessionMenuSummary(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1097
+ if (summary.turns)
1098
+ item.turns = summary.turns;
1099
+ const firstMsg = summary.firstMessage;
1059
1100
  if (firstMsg)
1060
1101
  item.preview = firstMsg.length > 80 ? firstMsg.slice(0, 80) + '...' : firstMsg;
1061
1102
  }
@@ -1105,6 +1146,12 @@ export class CommandHandler {
1105
1146
  execQuery: async (cmd, resolvedChannelId, queryArgs, context) => this.execMenuQuery(cmd, channel, resolvedChannelId, context.subject.actorId, queryArgs, context.subject.chatType, context.subject.fromControlChannel, context.subject.identity, context.subject, channelScope === 'control' ? 'control' : 'menu', resolvedChannelId === channelId ? transportReplyContext : undefined),
1106
1147
  });
1107
1148
  }
1149
+ async execMenuQueryBatch(channel, channelId, subject, args, channelScope = 'agent', transportReplyContext) {
1150
+ return execMenuQueryBatch({
1151
+ subject, channelType: this.resolveChannelType(channel), channelScope, channelId, args,
1152
+ execQuery: (cmd, resolvedChannelId, queryArgs, querySubject) => this.execMenuQuery(cmd, channel, resolvedChannelId, querySubject.actorId, queryArgs, querySubject.chatType, querySubject.fromControlChannel, querySubject.identity, querySubject, channelScope === 'control' ? 'control' : 'menu', resolvedChannelId === channelId ? transportReplyContext : undefined),
1153
+ });
1154
+ }
1108
1155
  /** 动态子菜单:根据 cmd 路径返回选项列表(供 menu.query + cmd 使用) */
1109
1156
  async getSubMenuItems(cmd, channel, channelId, userId, args, overrideIdentity, explicitChatType, fromControlChannel = false, authSubject, source = 'menu', transportReplyContext) {
1110
1157
  return await menuGetSubMenuItems.call(this, cmd, channel, channelId, userId, args, overrideIdentity, explicitChatType, fromControlChannel, authSubject, source, transportReplyContext);
@@ -1832,10 +1879,7 @@ export class CommandHandler {
1832
1879
  if (meta?.replyContext?.replyInThread)
1833
1880
  ctx.replyInThread = meta.replyContext.replyInThread;
1834
1881
  const taskId = this.sessionManager.getActiveTaskId(session.id);
1835
- const taskChatmode = taskId && meta?.turnState?.active?.taskId === taskId
1836
- ? meta.turnState.active.recoveryContext?.chatmode
1837
- : undefined;
1838
- const chatmode = isChatMode(taskChatmode) ? taskChatmode : this.resolveEffectiveChatmodeForSession(session);
1882
+ const chatmode = this.resolveEffectiveChatmodeForSession(session);
1839
1883
  const encrypted = this.sessionManager.getSessionEncrypt(session.id);
1840
1884
  // 诊断日志:记录 task_id 解析结果
1841
1885
  logger.info(`[CommandHandler] buildCtlReplyContext: sessionId=${session.id} taskId=${taskId ?? 'none'} chatmode=${chatmode} threadId=${ctx.threadId ?? 'none'} replyTo=${ctx.replyToMessageId ?? 'none'} inThread=${ctx.replyInThread ?? false}`);
@@ -1866,8 +1910,6 @@ export class CommandHandler {
1866
1910
  chatType: session.chatType,
1867
1911
  peerType,
1868
1912
  channelType,
1869
- lifecycle: resolveAgentLifecycle(this.getOwningAgent(session.channel)?.config ?? {}),
1870
- sessionType: session.sessionType ?? session.metadata?.sessionType ?? 'main',
1871
1913
  });
1872
1914
  }
1873
1915
  catch {
@@ -5,8 +5,8 @@ import { isValidAid } from '../../aun/aid/validation.js';
5
5
  import { isStaticAgentOwner } from '../../config/peer-role-resolver.js';
6
6
  import { agentDir, agentRelationSharedDir } from '../../paths.js';
7
7
  import { formatPeerKey, readAunPeerKind } from '../relation/peer-identity.js';
8
- import { DataRootError, paWorkspaceStore } from './pa-workspace-store.js';
9
- export { DataRootError } from './pa-workspace-store.js';
8
+ import { DataRootError, teamWorkspaceStore } from './team-workspace-store.js';
9
+ export { DataRootError } from './team-workspace-store.js';
10
10
  const DEFAULT_ROOT_TTL_MS = 10 * 60 * 1000;
11
11
  const TOKEN_PREFIX = 'dr1';
12
12
  function base64Url(value) {
@@ -31,7 +31,7 @@ export class DataRootResolver {
31
31
  isOwner;
32
32
  resolveAgentPath;
33
33
  resolveRelationSharedPath;
34
- paStore;
34
+ teamStore;
35
35
  constructor(options = {}) {
36
36
  this.secret = options.secret ?? crypto.randomBytes(32);
37
37
  if (this.secret.length < 32)
@@ -41,7 +41,7 @@ export class DataRootResolver {
41
41
  this.isOwner = options.isOwner ?? isStaticAgentOwner;
42
42
  this.resolveAgentPath = options.resolveAgentPath ?? agentDir;
43
43
  this.resolveRelationSharedPath = options.resolveRelationSharedPath ?? agentRelationSharedDir;
44
- this.paStore = options.paStore ?? paWorkspaceStore;
44
+ this.teamStore = options.teamStore ?? teamWorkspaceStore;
45
45
  }
46
46
  issueAgentRoot(subject) {
47
47
  const targetAid = this.targetAid(subject);
@@ -74,18 +74,18 @@ export class DataRootResolver {
74
74
  const rootPath = this.canonicalRoot(this.resolveRelationSharedPath(targetAid, peerKey), agentRoot);
75
75
  return this.issueDescriptor({ scope: 'relation', targetAid, principalId, peerAid, peerKey }, rootPath);
76
76
  }
77
- issuePaWorkspaceRoot(subject) {
77
+ issueTeamWorkspaceRoot(subject) {
78
78
  const targetAid = this.targetAid(subject);
79
79
  this.assertPrivateAun(subject);
80
80
  const principalId = authenticatedPrincipal(subject);
81
81
  if (subject.role !== 'owner' || !this.isOwner(targetAid, principalId)) {
82
- throw new DataRootError('ROOT_FORBIDDEN', 'PA workspace root requires Agent owner permission');
82
+ throw new DataRootError('ROOT_FORBIDDEN', 'Team workspace root requires Agent owner permission');
83
83
  }
84
- const state = this.paStore.require(targetAid);
84
+ const state = this.teamStore.require(targetAid);
85
85
  if (state.ownerAid !== principalId) {
86
- throw new DataRootError('ROOT_FORBIDDEN', 'PA workspace is bound to another owner');
86
+ throw new DataRootError('ROOT_FORBIDDEN', 'Team workspace is bound to another owner');
87
87
  }
88
- return this.issueDescriptor({ scope: 'pa', targetAid, principalId, workspaceId: state.workspaceId }, this.paStore.root(state));
88
+ return this.issueDescriptor({ scope: 'team', targetAid, principalId, workspaceId: state.workspaceId }, this.teamStore.root(state));
89
89
  }
90
90
  resolveRoot(rootId, subject) {
91
91
  const claims = this.verifyToken(rootId);
@@ -120,17 +120,17 @@ export class DataRootResolver {
120
120
  else {
121
121
  this.assertPrivateAun(subject);
122
122
  if (!claims.workspaceId)
123
- throw new DataRootError('ROOT_SCOPE_MISMATCH', 'PA workspace root claims are invalid');
123
+ throw new DataRootError('ROOT_SCOPE_MISMATCH', 'Team workspace root claims are invalid');
124
124
  if (subject.role !== 'owner' || !this.isOwner(targetAid, principalId)) {
125
- throw new DataRootError('ROOT_FORBIDDEN', 'PA workspace root requires Agent owner permission');
125
+ throw new DataRootError('ROOT_FORBIDDEN', 'Team workspace root requires Agent owner permission');
126
126
  }
127
- workspaceState = this.paStore.require(targetAid);
127
+ workspaceState = this.teamStore.require(targetAid);
128
128
  if (workspaceState.ownerAid !== principalId || workspaceState.workspaceId !== claims.workspaceId) {
129
- throw new DataRootError('ROOT_SCOPE_MISMATCH', 'PA workspace binding changed; request a new root');
129
+ throw new DataRootError('ROOT_SCOPE_MISMATCH', 'Team workspace binding changed; request a new root');
130
130
  }
131
- rootPath = this.paStore.root(workspaceState);
131
+ rootPath = this.teamStore.root(workspaceState);
132
132
  }
133
- const revision = this.rootRevision(rootPath);
133
+ const revision = this.descriptorRevision(claims.scope, targetAid, rootPath);
134
134
  if (revision !== claims.revision) {
135
135
  throw new DataRootError('ROOT_SCOPE_MISMATCH', 'Root identity changed; request a new root');
136
136
  }
@@ -148,11 +148,11 @@ export class DataRootResolver {
148
148
  resolvePath(rootId, subject, input, expectType) {
149
149
  const root = this.resolveRoot(rootId, subject);
150
150
  const raw = String(input ?? '').trim();
151
- if (root.scope === 'pa') {
152
- const state = this.paStore.require(root.targetAid);
151
+ if (root.scope === 'team') {
152
+ const state = this.teamStore.require(root.targetAid);
153
153
  if (state.workspaceId !== root.workspaceId)
154
- throw new DataRootError('ROOT_SCOPE_MISMATCH', 'PA workspace binding changed; request a new root');
155
- const resolved = this.paStore.resolvePath(state, raw);
154
+ throw new DataRootError('ROOT_SCOPE_MISMATCH', 'Team workspace binding changed; request a new root');
155
+ const resolved = this.teamStore.resolvePath(state, raw);
156
156
  if (expectType === 'file' && !resolved.stat.isFile()) {
157
157
  throw new DataRootError('NOT_SUPPORTED', 'Path is not a regular file');
158
158
  }
@@ -201,7 +201,7 @@ export class DataRootResolver {
201
201
  const claims = {
202
202
  v: 1,
203
203
  ...base,
204
- revision: this.rootRevision(rootPath),
204
+ revision: this.descriptorRevision(base.scope, base.targetAid, rootPath),
205
205
  issuedAt,
206
206
  expiresAt: issuedAt + this.ttlMs,
207
207
  nonce: crypto.randomBytes(12).toString('base64url'),
@@ -217,7 +217,7 @@ export class DataRootResolver {
217
217
  ? '$AGENTS_DIR/<targetAid>'
218
218
  : claims.scope === 'relation'
219
219
  ? '$AGENTS_DIR/<targetAid>/relations/<peerKey>/shared'
220
- : '$PA_WORKSPACE/<workspaceId>',
220
+ : '$AGENTS_DIR/<targetAid>/workspace',
221
221
  revision: `sha256:${claims.revision}`,
222
222
  expiresAt: claims.expiresAt,
223
223
  readOnly: true,
@@ -256,11 +256,11 @@ export class DataRootResolver {
256
256
  throw new DataRootError('INVALID_ROOT_ID', 'Invalid data rootId payload');
257
257
  }
258
258
  if (claims.v !== 1
259
- || (claims.scope !== 'agent' && claims.scope !== 'relation' && claims.scope !== 'pa')
259
+ || (claims.scope !== 'agent' && claims.scope !== 'relation' && claims.scope !== 'team')
260
260
  || typeof claims.targetAid !== 'string'
261
261
  || typeof claims.principalId !== 'string'
262
262
  || typeof claims.revision !== 'string'
263
- || (claims.scope === 'pa' && typeof claims.workspaceId !== 'string')
263
+ || (claims.scope === 'team' && typeof claims.workspaceId !== 'string')
264
264
  || !Number.isFinite(claims.expiresAt)) {
265
265
  throw new DataRootError('INVALID_ROOT_ID', 'Invalid data rootId claims');
266
266
  }
@@ -292,6 +292,15 @@ export class DataRootResolver {
292
292
  .update(JSON.stringify({ rootPath, dev: stat.dev, ino: stat.ino, birthtimeMs: stat.birthtimeMs }))
293
293
  .digest('hex');
294
294
  }
295
+ descriptorRevision(scope, targetAid, rootPath) {
296
+ const workspaceRevision = this.rootRevision(rootPath);
297
+ if (scope !== 'team')
298
+ return workspaceRevision;
299
+ const outputRoot = this.teamStore.outputRoot(this.teamStore.require(targetAid));
300
+ if (!outputRoot)
301
+ return workspaceRevision;
302
+ return crypto.createHash('sha256').update(`${workspaceRevision}:${this.rootRevision(outputRoot)}`).digest('hex');
303
+ }
295
304
  targetAid(subject) {
296
305
  const targetAid = String(subject.selfAid ?? '').trim();
297
306
  if (!isValidAid(targetAid))
@@ -0,0 +1,338 @@
1
+ /**
2
+ * 事件中心菜单(menu events / /events):center 开关、白名单、包列表、统计。
3
+ * 门控:与 Team Workspace 相同的 owner 私聊约束(由 menu-handler 分发处理)。
4
+ * 设计:docs/event-center/detailed-design.md §八。
5
+ */
6
+ import fs from 'node:fs';
7
+ import { atomicWriteJson } from '../../utils/atomic-write.js';
8
+ import { loadPacks } from '../../event-center/pack-loader.js';
9
+ import { validatePackJson } from '../../event-center/validation.js';
10
+ import { materializeAllowlist } from '../../event-center/admission-materializer.js';
11
+ const VIEWS = new Set(['center', 'allowlist', 'packs', 'register', 'subscribers', 'stats']);
12
+ /** menu-protocol 校验:query view / update resource 白名单。 */
13
+ export function validateEventsMenuRequest(request) {
14
+ const type = String(request.type ?? '');
15
+ const args = request.args;
16
+ if (args !== undefined && (!args || typeof args !== 'object' || Array.isArray(args))) {
17
+ return { code: 'INVALID_ARGUMENT', message: 'events args must be an object' };
18
+ }
19
+ const values = (args ?? {});
20
+ const view = values.view;
21
+ const resource = values.resource;
22
+ if (type === 'menu.query') {
23
+ if (view !== undefined && !VIEWS.has(String(view))) {
24
+ return { code: 'INVALID_ARGS', message: `events view must be one of ${[...VIEWS].join(', ')}` };
25
+ }
26
+ const allowed = view === 'center' ? new Set(['view'])
27
+ : view === 'allowlist' ? new Set(['view', 'event'])
28
+ : view === 'register' ? new Set(['view', 'packId', 'event'])
29
+ : view === 'subscribers' ? new Set(['view', 'event'])
30
+ : view === 'stats' ? new Set(['view', 'event'])
31
+ : new Set(['view', 'packId']);
32
+ const unknown = Object.keys(values).find(key => !allowed.has(key));
33
+ if (unknown)
34
+ return { code: 'INVALID_ARGS', message: `events ${String(view ?? 'packs')} does not accept args.${unknown}` };
35
+ if (['allowlist', 'register', 'subscribers', 'stats'].includes(String(view)) && values.event !== undefined && typeof values.event !== 'string') {
36
+ return { code: 'INVALID_ARGS', message: 'events args.event must be a string' };
37
+ }
38
+ if (['register', 'packs'].includes(String(view)) && values.packId !== undefined && typeof values.packId !== 'string') {
39
+ return { code: 'INVALID_ARGS', message: 'events args.packId must be a string' };
40
+ }
41
+ return undefined;
42
+ }
43
+ if (type === 'menu.update') {
44
+ let updateValues = values;
45
+ const rawValue = request.value;
46
+ if (rawValue !== undefined && resource !== 'center') {
47
+ if (typeof rawValue !== 'string' || !rawValue.trim())
48
+ return { code: 'INVALID_ARGS', message: 'events structured value must be a JSON object string' };
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(rawValue);
52
+ }
53
+ catch {
54
+ return { code: 'INVALID_ARGS', message: 'events value must be valid JSON' };
55
+ }
56
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
57
+ return { code: 'INVALID_ARGS', message: 'events value must be a JSON object' };
58
+ updateValues = { ...parsed, ...values };
59
+ }
60
+ else if (rawValue !== undefined && typeof rawValue !== 'boolean') {
61
+ return { code: 'INVALID_ARGS', message: 'events center value must be a boolean' };
62
+ }
63
+ if (!['center', 'allowlist', 'register'].includes(String(resource))) {
64
+ return { code: 'INVALID_ARGS', message: 'events update resource must be "center", "allowlist" or "register"' };
65
+ }
66
+ const allowed = resource === 'center' ? new Set(['resource', 'enabled', 'admission'])
67
+ : resource === 'allowlist' ? new Set(['resource', 'event', 'rule', 'action', 'role', 'aids'])
68
+ : new Set(['resource', 'packId', 'event', 'action', 'description', 'ttl', 'maxTtl', 'schemaVersion', 'contentSchema']);
69
+ const unknown = Object.keys(updateValues).find(key => !allowed.has(key));
70
+ if (unknown)
71
+ return { code: 'INVALID_ARGS', message: `events ${String(resource ?? 'update')} does not accept args.${unknown}` };
72
+ if (resource === 'center' && updateValues.admission !== undefined) {
73
+ if (!updateValues.admission || typeof updateValues.admission !== 'object' || Array.isArray(updateValues.admission))
74
+ return { code: 'INVALID_ARGS', message: 'events center update requires args.admission (object)' };
75
+ const admission = updateValues.admission;
76
+ const unknownAdmission = Object.keys(admission).find(key => !['coupling', 'rematerializeMs'].includes(key));
77
+ if (unknownAdmission)
78
+ return { code: 'INVALID_ARGS', message: `events admission does not accept ${unknownAdmission}` };
79
+ if (admission.coupling !== undefined && admission.coupling !== 'on')
80
+ return { code: 'INVALID_ARGS', message: 'admission.coupling must be "on"' };
81
+ if (admission.rematerializeMs !== undefined && (!Number.isInteger(admission.rematerializeMs) || Number(admission.rematerializeMs) < 60_000 || Number(admission.rematerializeMs) > 3_600_000))
82
+ return { code: 'INVALID_ARGS', message: 'admission.rematerializeMs must be an integer in [60000, 3600000]' };
83
+ }
84
+ if (resource === 'center') {
85
+ if (updateValues.enabled !== undefined && typeof updateValues.enabled !== 'boolean')
86
+ return { code: 'INVALID_ARGS', message: 'events center args.enabled must be a boolean' };
87
+ if (updateValues.enabled === undefined && updateValues.admission === undefined && typeof rawValue !== 'boolean') {
88
+ return { code: 'INVALID_ARGS', message: 'events center update requires args.enabled, args.admission or a boolean value' };
89
+ }
90
+ }
91
+ if (resource === 'allowlist') {
92
+ if (typeof updateValues.event !== 'string' || !updateValues.event.trim())
93
+ return { code: 'INVALID_ARGS', message: 'allowlist update requires args.event' };
94
+ if (!['allow', 'deny'].includes(String(updateValues.rule ?? 'allow')) || !['add', 'remove'].includes(String(updateValues.action)) || !['publish', 'subscribe'].includes(String(updateValues.role)) || !Array.isArray(updateValues.aids) || updateValues.aids.some(item => typeof item !== 'string')) {
95
+ return { code: 'INVALID_ARGS', message: 'allowlist update requires rule/action/role/aids' };
96
+ }
97
+ }
98
+ if (resource === 'register') {
99
+ if (typeof updateValues.packId !== 'string' || !updateValues.packId.trim() || typeof updateValues.action !== 'string' || !['add', 'update', 'remove'].includes(updateValues.action)) {
100
+ return { code: 'INVALID_ARGS', message: 'register update requires packId and action(add|update|remove)' };
101
+ }
102
+ if (typeof updateValues.event !== 'string' || !updateValues.event.trim())
103
+ return { code: 'INVALID_ARGS', message: 'register update requires event' };
104
+ if (updateValues.action === 'remove' && Object.keys(updateValues).some(key => !['resource', 'packId', 'event', 'action'].includes(key)))
105
+ return { code: 'INVALID_ARGS', message: 'register remove only accepts packId/event/action' };
106
+ }
107
+ return undefined;
108
+ }
109
+ return { code: 'NOT_SUPPORTED', message: 'events supports menu.query and menu.update' };
110
+ }
111
+ function unitOf(context) {
112
+ if (!context.registry || !context.selfAid) {
113
+ return { code: 'EVENT_CENTER_NOT_STARTED', message: 'event center is not available' };
114
+ }
115
+ const unit = context.registry.get(context.selfAid);
116
+ if (!unit) {
117
+ return { code: 'EVENT_CENTER_NOT_STARTED', message: `event center not started for ${context.selfAid}` };
118
+ }
119
+ return unit;
120
+ }
121
+ export async function executeEventsQuery(context, args = {}) {
122
+ const unit = unitOf(context);
123
+ if ('code' in unit)
124
+ throw unit;
125
+ const view = String(args.view ?? 'packs');
126
+ if (view === 'center') {
127
+ const { config, exists } = unit.centerStore.read();
128
+ return {
129
+ enabled: config.enabled,
130
+ authMode: config.authMode,
131
+ admission: config.admission,
132
+ configured: exists,
133
+ eventCount: unit.state.catalog.length,
134
+ bus: unit.runtime.busHost.status,
135
+ gateInstalled: unit.runtime.busHost.gateInstalled,
136
+ };
137
+ }
138
+ if (view === 'allowlist') {
139
+ const { config } = unit.centerStore.read();
140
+ const event = typeof args.event === 'string' ? args.event : undefined;
141
+ const allowlist = event
142
+ ? { [event]: config.allowlist[event] ?? { allow: { publish: [], subscribe: [] }, deny: { publish: [], subscribe: [] } } }
143
+ : config.allowlist;
144
+ return { allowlist };
145
+ }
146
+ if (view === 'register') {
147
+ const packId = typeof args.packId === 'string' ? args.packId : undefined;
148
+ const event = typeof args.event === 'string' ? args.event : undefined;
149
+ const packs = packId
150
+ ? unit.state.enabledPacks.filter(pack => pack.id === packId)
151
+ : unit.state.enabledPacks;
152
+ return {
153
+ events: packs.flatMap(pack => pack.register.map(entry => ({ packId: pack.id, ...entry })))
154
+ .filter(entry => !event || entry.event === event),
155
+ catalog: event ? unit.state.catalog.filter(entry => entry.event === event) : unit.state.catalog,
156
+ invalidPacks: unit.state.invalidPacks,
157
+ };
158
+ }
159
+ if (view === 'subscribers') {
160
+ const result = unit.runtime.busHost.subscribers();
161
+ const event = typeof args.event === 'string' ? args.event : undefined;
162
+ return {
163
+ busAid: unit.aid,
164
+ status: unit.runtime.busHost.status,
165
+ available: result.available,
166
+ ...(result.reason ? { reason: result.reason } : {}),
167
+ subscribers: event ? result.subscribers.filter(item => item.event === event) : result.subscribers,
168
+ };
169
+ }
170
+ if (view === 'stats') {
171
+ const status = unit.runtime.status();
172
+ const aggregate = await unit.runtime.busHost.stats({});
173
+ const requestedEvent = typeof args.event === 'string' ? args.event : undefined;
174
+ const catalog = requestedEvent ? unit.state.catalog.filter(entry => entry.event === requestedEvent) : unit.state.catalog;
175
+ const events = await Promise.all(catalog.map(async (entry) => {
176
+ const stats = await unit.runtime.busHost.stats({ event_name: entry.event });
177
+ return eventStats(entry.event, stats);
178
+ }));
179
+ return {
180
+ bus: { ...status.bus, since: numberOrUndefined(aggregate?.since), asOf: numberOrUndefined(aggregate?.as_of) },
181
+ subscriptions: status.subscriptions,
182
+ publishers: status.publishers,
183
+ counters: mapStatsCounts(aggregate?.counts),
184
+ events,
185
+ };
186
+ }
187
+ // packs
188
+ const resolution = unit.runtime.resolutions;
189
+ return {
190
+ packs: [
191
+ ...unit.state.enabledPacks.map(pack => ({
192
+ id: pack.id,
193
+ name: pack.name,
194
+ status: 'active',
195
+ registers: pack.register.length,
196
+ publishes: pack.publish.length,
197
+ subscribes: pack.subscribe.length,
198
+ })),
199
+ ...unit.state.disabledPacks.map(id => ({ id, name: id, status: 'disabled', registers: 0, publishes: 0, subscribes: 0 })),
200
+ ...unit.state.invalidPacks.map(item => ({ id: item.id, name: item.id, status: 'invalid', errors: item.errors })),
201
+ ],
202
+ resolutions: [...resolution.entries()].map(([packId, refs]) => ({ packId, buses: Object.fromEntries(refs) })),
203
+ };
204
+ }
205
+ export async function executeEventsUpdate(context, args = {}) {
206
+ const unit = unitOf(context);
207
+ if ('code' in unit)
208
+ throw unit;
209
+ const resource = String(args.resource ?? '');
210
+ if (resource === 'center') {
211
+ const { config } = unit.centerStore.read();
212
+ if (args.enabled !== undefined && typeof args.enabled !== 'boolean') {
213
+ throw { code: 'INVALID_ARGS', message: 'events center update requires args.enabled (boolean)' };
214
+ }
215
+ if (args.admission !== undefined && (!args.admission || typeof args.admission !== 'object' || Array.isArray(args.admission))) {
216
+ throw { code: 'INVALID_ARGS', message: 'events center update requires args.admission (object)' };
217
+ }
218
+ const admission = args.admission ?? {};
219
+ if (admission.coupling !== undefined && admission.coupling !== 'on')
220
+ throw { code: 'INVALID_ARGS', message: 'admission.coupling must be "on"' };
221
+ if (admission.rematerializeMs !== undefined && (!Number.isInteger(admission.rematerializeMs) || Number(admission.rematerializeMs) < 60_000 || Number(admission.rematerializeMs) > 3_600_000)) {
222
+ throw { code: 'INVALID_ARGS', message: 'admission.rematerializeMs must be an integer in [60000, 3600000]' };
223
+ }
224
+ const next = {
225
+ ...config,
226
+ enabled: args.enabled ?? config.enabled,
227
+ admission: {
228
+ coupling: 'on',
229
+ rematerializeMs: Number(admission.rematerializeMs ?? config.admission.rematerializeMs),
230
+ },
231
+ };
232
+ unit.centerStore.write(next);
233
+ const materialized = materializeAllowlist(next, unit.agentDir, unit.aid, unit.state.catalog.map(entry => entry.event));
234
+ await unit.runtime.updateCenter(next, materialized);
235
+ return { enabled: next.enabled, bus: unit.runtime.busHost.status, degraded: materialized.degraded, ...(materialized.reason ? { reason: materialized.reason } : {}) };
236
+ }
237
+ if (resource === 'allowlist') {
238
+ const event = typeof args.event === 'string' ? args.event : '';
239
+ const action = args.action === 'remove' ? 'remove' : args.action === 'add' ? 'add' : undefined;
240
+ const role = args.role === 'subscribe' ? 'subscribe' : args.role === 'publish' ? 'publish' : undefined;
241
+ const rule = args.rule === 'deny' ? 'deny' : args.rule === 'allow' || args.rule === undefined ? 'allow' : undefined;
242
+ const aids = Array.isArray(args.aids) && args.aids.every(item => typeof item === 'string') ? args.aids : undefined;
243
+ if (!event || !action || !role || !rule || !aids) {
244
+ throw { code: 'INVALID_ARGS', message: 'events allowlist update requires event/rule(allow|deny)/action(add|remove)/role(publish|subscribe)/aids[]' };
245
+ }
246
+ if (!unit.state.catalog.some(entry => entry.event === event)) {
247
+ throw { code: 'EVENT_NOT_FOUND', message: `event is not registered: ${event}` };
248
+ }
249
+ const result = unit.centerStore.mutateAllowlist({ event, action, role, rule, aids });
250
+ const materialized = materializeAllowlist(result.config, unit.agentDir, unit.aid, unit.state.catalog.map(entry => entry.event));
251
+ await unit.runtime.updateCenter(result.config, materialized);
252
+ return { event, entry: result.changed, added: result.added, removed: result.removed, degraded: materialized.degraded, ...(materialized.reason ? { reason: materialized.reason } : {}) };
253
+ }
254
+ if (resource === 'register') {
255
+ return await updateEventRegistration(context, unit, args);
256
+ }
257
+ throw { code: 'INVALID_ARGS', message: 'events update resource must be "center", "allowlist" or "register"' };
258
+ }
259
+ async function updateEventRegistration(context, unit, args) {
260
+ if (!context.registry)
261
+ throw { code: 'EVENT_CENTER_NOT_STARTED', message: 'event center is not available' };
262
+ const packId = typeof args.packId === 'string' ? args.packId.trim() : '';
263
+ const event = typeof args.event === 'string' ? args.event.trim() : '';
264
+ const action = args.action === 'add' || args.action === 'update' || args.action === 'remove' ? args.action : undefined;
265
+ if (!packId || !action || !event) {
266
+ throw { code: 'INVALID_ARGS', message: 'events register update requires packId/event/action(add|update|remove)' };
267
+ }
268
+ const loaded = loadPacks(unit.eventsDir).valid.find(pack => pack.id === packId);
269
+ if (!loaded)
270
+ throw { code: 'PACK_NOT_FOUND', message: `pack not found or invalid: ${packId}` };
271
+ let raw;
272
+ try {
273
+ raw = JSON.parse(fs.readFileSync(loaded.paths.packJson, 'utf8'));
274
+ }
275
+ catch (error) {
276
+ throw { code: 'PACK_INVALID', message: error instanceof Error ? error.message : String(error) };
277
+ }
278
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
279
+ throw { code: 'PACK_INVALID', message: 'pack.json must be an object' };
280
+ const next = { ...raw };
281
+ const current = Array.isArray(next.register) ? next.register.filter(item => item && typeof item === 'object' && !Array.isArray(item)) : [];
282
+ const index = current.findIndex(item => item.event === event);
283
+ if (action === 'add' && index >= 0)
284
+ throw { code: 'EVENT_EXISTS', message: `event already registered: ${event}` };
285
+ if (action === 'update' && index < 0)
286
+ throw { code: 'EVENT_NOT_FOUND', message: `event is not registered: ${event}` };
287
+ if (action === 'remove') {
288
+ if (index < 0)
289
+ throw { code: 'EVENT_NOT_FOUND', message: `event is not registered: ${event}` };
290
+ current.splice(index, 1);
291
+ }
292
+ else {
293
+ const entry = {
294
+ ...(index >= 0 ? current[index] : {}),
295
+ event,
296
+ ...(args.description !== undefined ? { description: args.description } : {}),
297
+ ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),
298
+ ...(args.maxTtl !== undefined ? { maxTtl: args.maxTtl } : {}),
299
+ ...(args.schemaVersion !== undefined ? { schemaVersion: args.schemaVersion } : {}),
300
+ ...(args.contentSchema !== undefined ? { contentSchema: args.contentSchema } : {}),
301
+ };
302
+ if (index >= 0)
303
+ current[index] = entry;
304
+ else
305
+ current.push(entry);
306
+ }
307
+ next.register = current;
308
+ const validated = validatePackJson(next);
309
+ if (!validated.ok)
310
+ throw { code: 'INVALID_ARGS', message: validated.errors.join('; ') };
311
+ atomicWriteJson(loaded.paths.packJson, next);
312
+ await context.registry.reload(unit.aid);
313
+ const refreshed = context.registry.get(unit.aid);
314
+ return {
315
+ packId,
316
+ action,
317
+ event,
318
+ registered: refreshed?.state.enabledPacks.find(pack => pack.id === packId)?.register ?? [],
319
+ };
320
+ }
321
+ function numberOrUndefined(value) {
322
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
323
+ }
324
+ function mapStatsCounts(value) {
325
+ if (!value || typeof value !== 'object' || Array.isArray(value))
326
+ return null;
327
+ const counts = value;
328
+ const mapped = {};
329
+ for (const [key, item] of Object.entries(counts)) {
330
+ const camel = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
331
+ mapped[camel] = item;
332
+ }
333
+ return mapped;
334
+ }
335
+ function eventStats(event, stats) {
336
+ const counts = mapStatsCounts(stats?.counts) ?? {};
337
+ return { event, ...counts };
338
+ }