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
@@ -0,0 +1,641 @@
1
+ /**
2
+ * 单个 agent 的事件中心运行时:Bus 宿主(可选)+ 订阅 client + 发布 client。
3
+ * 回调先注册、后 authorize、再 subscribe(避免订阅生效到回调注册之间漏事件);
4
+ * 包级 / Bus 级失败全部隔离,不互相阻塞。
5
+ */
6
+ import { logger } from '../utils/logger.js';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { BusHost } from './bus-host.js';
10
+ import { packLedger } from './ledger.js';
11
+ import { toSdkAllowlist, toSdkCatalog } from './pack-manager.js';
12
+ import { EVENT_CENTER_PUB_SLOT, EVENT_CENTER_SUB_SLOT, EventCenterError, errorCode, errorMessage } from './types.js';
13
+ import { evaluateEventBusRequest } from './bus-gate.js';
14
+ /** SDK app.pubsub.v1 事件载荷 → 归一化事件。 */
15
+ export function toReceivedEvent(busAid, payload) {
16
+ const eventName = typeof payload.event_name === 'string' ? payload.event_name : '';
17
+ const eventId = typeof payload.event_id === 'string' ? payload.event_id : '';
18
+ const publisher = typeof payload.publisher_aid === 'string' ? payload.publisher_aid : '';
19
+ if (!eventName || !eventId || !publisher)
20
+ return null;
21
+ return {
22
+ busAid,
23
+ eventName,
24
+ eventId,
25
+ publisher,
26
+ receivedAt: Date.now(),
27
+ ...(payload.schema_version !== undefined ? { schemaVersion: Number(payload.schema_version) } : {}),
28
+ data: payload.data,
29
+ };
30
+ }
31
+ /** Bus 配置是否等价:catalog 与 allowlist 都是 JSON 对象,序列化比较足够(不含函数/时间戳)。 */
32
+ function sameBusConfig(left, right) {
33
+ if (left === null || right === null)
34
+ return left === right;
35
+ return JSON.stringify(left.catalog) === JSON.stringify(right.catalog)
36
+ && JSON.stringify(left.allowlist) === JSON.stringify(right.allowlist);
37
+ }
38
+ export class EventRuntime {
39
+ options;
40
+ busHost;
41
+ subClient;
42
+ pubClient;
43
+ unsubscribers = [];
44
+ current;
45
+ rematerializeTimer;
46
+ contactsWatchers = [];
47
+ contactsRefreshTimer;
48
+ lastGateStatus;
49
+ closed = false;
50
+ /** 已生效的订阅:busAid → 事件名集合。reconfigure 用它算差集。 */
51
+ registeredSubBuses = new Map();
52
+ /** 已授权的发布:busAid → 事件名集合。 */
53
+ registeredPubBuses = new Map();
54
+ constructor(options) {
55
+ this.options = options;
56
+ this.busHost = new BusHost({
57
+ aid: options.aid,
58
+ createClient: options.createClient,
59
+ requestGate: (senderAid, request, service) => this.gateRemoteRequest(senderAid, request, service),
60
+ });
61
+ }
62
+ get packs() { return this.current?.state.enabledPacks ?? []; }
63
+ get resolutions() { return this.current?.resolutions ?? new Map(); }
64
+ get center() { return this.current?.center; }
65
+ /** 启动:Bus(可选)→ 订阅 → 发布。任何一侧失败只记日志/台账,不影响其它侧。 */
66
+ async start(input) {
67
+ this.closed = false;
68
+ this.current = input;
69
+ this.configureRematerializeTimer();
70
+ this.configureContactsWatcher();
71
+ // 1. Bus 宿主(center.enabled 且目录非空)。
72
+ if (input.center.enabled && input.state.catalog.length > 0) {
73
+ try {
74
+ await this.busHost.ensureRunning({
75
+ catalog: toSdkCatalog(input.state.catalog),
76
+ allowlist: input.materializedAllowlist ?? this.options.materializeAllowlist?.(input.center, input.state.catalog.map(entry => entry.event))?.allowlist ?? toSdkAllowlist(input.center),
77
+ });
78
+ this.busHost.refreshGate();
79
+ this.reportGateStatus();
80
+ }
81
+ catch (error) {
82
+ logger.warn(`[EventCenter] ${this.options.aid} bus start deferred: ${errorMessage(error)} (自愈重试中)`);
83
+ }
84
+ }
85
+ // 2. 订阅(先回调、后鉴权、再订阅)。
86
+ await this.startSubscribers(input);
87
+ // 3. 发布授权。
88
+ await this.startPublishers(input);
89
+ }
90
+ async updateCenter(center, materialized) {
91
+ if (!this.current)
92
+ return;
93
+ this.current = { ...this.current, center, materializedAllowlist: materialized.allowlist };
94
+ if (center.enabled && this.current.state.catalog.length > 0 && !materialized.degraded) {
95
+ await this.busHost.apply({ catalog: toSdkCatalog(this.current.state.catalog), allowlist: materialized.allowlist });
96
+ }
97
+ else if (!center.enabled || this.current.state.catalog.length === 0) {
98
+ await this.busHost.apply(null);
99
+ }
100
+ this.configureRematerializeTimer();
101
+ this.configureContactsWatcher();
102
+ this.busHost.refreshGate();
103
+ this.reportGateStatus();
104
+ }
105
+ configureRematerializeTimer() {
106
+ if (this.rematerializeTimer) {
107
+ clearInterval(this.rematerializeTimer);
108
+ this.rematerializeTimer = undefined;
109
+ }
110
+ const interval = this.current?.center.admission.rematerializeMs;
111
+ if (this.options.materializeAllowlist && Number.isInteger(interval) && (interval ?? 0) > 0) {
112
+ this.rematerializeTimer = setInterval(() => { void this.rematerialize(); }, interval);
113
+ this.rematerializeTimer.unref?.();
114
+ }
115
+ }
116
+ async rematerialize() {
117
+ const current = this.current;
118
+ const materializer = this.options.materializeAllowlist;
119
+ if (!current || !materializer || !current.center.enabled || current.state.catalog.length === 0)
120
+ return;
121
+ try {
122
+ const result = materializer(current.center, current.state.catalog.map(entry => entry.event));
123
+ if (result.degraded) {
124
+ logger.warn(`[EventCenter] ${this.options.aid} admission materialization degraded: ${result.reason ?? 'unknown'}`);
125
+ return;
126
+ }
127
+ await this.busHost.apply({ catalog: toSdkCatalog(current.state.catalog), allowlist: result.allowlist });
128
+ if (this.current === current)
129
+ this.current = { ...current, materializedAllowlist: result.allowlist };
130
+ this.busHost.refreshGate();
131
+ this.reportGateStatus();
132
+ }
133
+ catch (error) {
134
+ logger.warn(`[EventCenter] ${this.options.aid} admission rematerialization failed: ${errorMessage(error)}`);
135
+ }
136
+ }
137
+ /** 热更新:P0 采用整停整起(退订 → 关闭 → 重新 start)。 */
138
+ async restart(input) {
139
+ await this.stopConnections();
140
+ await this.start(input);
141
+ }
142
+ /**
143
+ * 热更新(增量):不重建任何 AUN 连接,只在现有连接上做 diff。
144
+ *
145
+ * 为什么不能用 `restart()`:Bus 是单设备租约,关掉 client 后服务端要几十秒
146
+ * 才释放,立刻重开必然 DEVICE_CONFLICT;而订阅侧刚建好的 sub client 也会因为
147
+ * 对端 Bus 不可用而 authorize 超时,之后不再重试。结果是"文件改了、Bus 挂着、
148
+ * 订阅丢了"。设计 §8 的热更新表本来就要求:改 handler / args / timeout 只换本地
149
+ * 映射不动订阅,加事件才重新 authorize + subscribe,删事件才 unsubscribe。
150
+ */
151
+ async reconfigure(input) {
152
+ const previous = this.current;
153
+ this.closed = false;
154
+ this.current = input;
155
+ this.configureRematerializeTimer();
156
+ this.configureContactsWatcher();
157
+ // ① Bus:只有 center 配置或 catalog 变了才动;运行中走 updateConfig(不重启 client)。
158
+ const nextBus = input.center.enabled && input.state.catalog.length > 0
159
+ ? {
160
+ catalog: toSdkCatalog(input.state.catalog),
161
+ allowlist: input.materializedAllowlist
162
+ ?? this.options.materializeAllowlist?.(input.center, input.state.catalog.map(entry => entry.event))?.allowlist
163
+ ?? toSdkAllowlist(input.center),
164
+ }
165
+ : null;
166
+ if (!previous || !sameBusConfig(this.busConfigOf(previous), nextBus)) {
167
+ try {
168
+ await this.busHost.apply(nextBus);
169
+ this.busHost.refreshGate();
170
+ this.reportGateStatus();
171
+ }
172
+ catch (error) {
173
+ logger.warn(`[EventCenter] ${this.options.aid} bus apply failed: ${errorMessage(error)}`);
174
+ }
175
+ }
176
+ // ② 订阅:按 bus 求差集。已有 bus 只增删事件,回调与 client 都复用。
177
+ await this.diffSubscribers(input);
178
+ // ③ 发布:新增 bus 或新增事件都要整批重新 authorize(SDK 续期不自动扩 scope)。
179
+ await this.diffPublishers(input);
180
+ }
181
+ /** 当前 bus 配置(未启用或无 catalog 时为 null),用于判定是否需要 apply。 */
182
+ busConfigOf(input) {
183
+ if (!input.center.enabled || input.state.catalog.length === 0)
184
+ return null;
185
+ return {
186
+ catalog: toSdkCatalog(input.state.catalog),
187
+ allowlist: input.materializedAllowlist
188
+ ?? this.options.materializeAllowlist?.(input.center, input.state.catalog.map(entry => entry.event))?.allowlist
189
+ ?? toSdkAllowlist(input.center),
190
+ };
191
+ }
192
+ /** 订阅增量:新增 bus 走完整接入;已有 bus 只补新增事件、退掉删除事件。 */
193
+ async diffSubscribers(input) {
194
+ const desired = new Map();
195
+ for (const target of this.subscriptionTargets(input)) {
196
+ const set = desired.get(target.busAid) ?? new Set();
197
+ for (const event of target.events)
198
+ set.add(event);
199
+ desired.set(target.busAid, set);
200
+ }
201
+ if (desired.size === 0 && this.registeredSubBuses.size === 0)
202
+ return;
203
+ if (!this.subClient) {
204
+ try {
205
+ this.subClient = await this.options.createClient(this.options.aid, EVENT_CENTER_SUB_SLOT);
206
+ }
207
+ catch (error) {
208
+ logger.error(`[EventCenter] ${this.options.aid} sub client create failed: ${errorMessage(error)}`);
209
+ return;
210
+ }
211
+ }
212
+ const client = this.subClient.client.EventService;
213
+ // 退订:已注册但当前包不再需要的 bus / 事件。
214
+ for (const [busAid, events] of [...this.registeredSubBuses]) {
215
+ const wanted = desired.get(busAid);
216
+ const removed = [...events].filter(event => !wanted?.has(event));
217
+ if (removed.length > 0) {
218
+ try {
219
+ await client.unsubscribe(busAid, removed);
220
+ for (const event of removed)
221
+ events.delete(event);
222
+ logger.info(`[EventCenter] ${this.options.aid} unsubscribed ${busAid}: ${removed.join(', ')}`);
223
+ }
224
+ catch (error) {
225
+ logger.warn(`[EventCenter] ${this.options.aid} unsubscribe ${busAid} failed: ${errorMessage(error)}`);
226
+ }
227
+ }
228
+ if (events.size === 0) {
229
+ this.registeredSubBuses.delete(busAid);
230
+ }
231
+ }
232
+ // 订阅:新 bus 完整接入;旧 bus 只补新增事件。
233
+ for (const [busAid, events] of desired) {
234
+ const registered = this.registeredSubBuses.get(busAid);
235
+ const added = [...events].filter(event => !registered?.has(event));
236
+ if (added.length === 0)
237
+ continue;
238
+ try {
239
+ // authorize 必须整批带上前面的全部事件:SDK 续期不会自动扩 scope。
240
+ await client.authorize(busAid, 'sub', 'allowlist', [...events]);
241
+ if (!registered) {
242
+ const off = client.onEvent(busAid, payload => {
243
+ const event = toReceivedEvent(busAid, payload);
244
+ if (event)
245
+ this.options.onEvent(event);
246
+ });
247
+ this.unsubscribers.push(() => { off(); });
248
+ }
249
+ await client.subscribe(busAid, added);
250
+ this.registeredSubBuses.set(busAid, new Set(events));
251
+ for (const target of this.subscriptionTargets(input).filter(item => item.busAid === busAid)) {
252
+ packLedger(target.pack).append({ action: 'subscribe', result: 'ok', bus: busAid, events: target.events, actor: 'daemon.reload', revision: target.pack.revision });
253
+ }
254
+ logger.info(`[EventCenter] ${this.options.aid} subscribed ${busAid}: ${added.join(', ')}`);
255
+ }
256
+ catch (error) {
257
+ logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${errorMessage(error)}`);
258
+ }
259
+ }
260
+ }
261
+ /** 发布增量:新 bus 或新事件都要重新 authorize(整批,不是只授权新增的那个)。 */
262
+ async diffPublishers(input) {
263
+ const desired = new Map();
264
+ for (const target of this.publisherTargets(input)) {
265
+ const set = desired.get(target.busAid) ?? new Set();
266
+ for (const event of target.events)
267
+ set.add(event);
268
+ desired.set(target.busAid, set);
269
+ }
270
+ if (desired.size === 0)
271
+ return;
272
+ if (!this.pubClient) {
273
+ try {
274
+ this.pubClient = await this.options.createClient(this.options.aid, EVENT_CENTER_PUB_SLOT);
275
+ }
276
+ catch (error) {
277
+ logger.error(`[EventCenter] ${this.options.aid} pub client create failed: ${errorMessage(error)}`);
278
+ return;
279
+ }
280
+ }
281
+ const client = this.pubClient.client.EventService;
282
+ for (const [busAid, events] of desired) {
283
+ const registered = this.registeredPubBuses.get(busAid);
284
+ const added = [...events].filter(event => !registered?.has(event));
285
+ if (added.length === 0)
286
+ continue;
287
+ try {
288
+ await client.authorize(busAid, 'pub', 'allowlist', [...events]);
289
+ this.registeredPubBuses.set(busAid, new Set(events));
290
+ logger.info(`[EventCenter] ${this.options.aid} publish authorized ${busAid}: ${[...events].join(', ')}`);
291
+ }
292
+ catch (error) {
293
+ logger.warn(`[EventCenter] ${this.options.aid} publish authorize ${busAid} failed: ${errorMessage(error)}`);
294
+ }
295
+ }
296
+ }
297
+ /** publish 目标按 bus 聚合(reconfigure 与 startPublishers 共用)。 */
298
+ publisherTargets(input) {
299
+ const byBus = new Map();
300
+ for (const pack of input.state.enabledPacks) {
301
+ for (const entry of pack.publish) {
302
+ const busAid = input.resolutions.get(pack.id)?.get(entry.bus) ?? entry.busResolved;
303
+ if (!busAid)
304
+ continue;
305
+ const key = `${busAid}\u0000${pack.id}`;
306
+ const group = byBus.get(key) ?? { pack, busAid, events: new Set() };
307
+ group.events.add(entry.event);
308
+ byBus.set(key, group);
309
+ }
310
+ }
311
+ return [...byBus.values()].map(group => ({ pack: group.pack, busAid: group.busAid, events: [...group.events] }));
312
+ }
313
+ resolvedBus(pack, ref, resolutions) {
314
+ return resolutions.get(pack.id)?.get(ref) ?? pack.subscribe.find(entry => entry.bus === ref)?.busResolved;
315
+ }
316
+ subscriptionTargets(input) {
317
+ const byBus = new Map();
318
+ for (const pack of input.state.enabledPacks) {
319
+ for (const entry of pack.subscribe) {
320
+ const busAid = input.resolutions.get(pack.id)?.get(entry.bus) ?? entry.busResolved;
321
+ if (!busAid)
322
+ continue;
323
+ const key = `${busAid}\u0000${pack.id}`;
324
+ const group = byBus.get(key) ?? { pack, busAid, events: new Set() };
325
+ group.events.add(entry.event);
326
+ byBus.set(key, group);
327
+ }
328
+ }
329
+ return [...byBus.values()].map(group => ({ pack: group.pack, busAid: group.busAid, events: [...group.events] }));
330
+ }
331
+ async startSubscribers(input) {
332
+ const targets = this.subscriptionTargets(input);
333
+ if (targets.length === 0)
334
+ return;
335
+ try {
336
+ this.subClient = await this.options.createClient(this.options.aid, EVENT_CENTER_SUB_SLOT);
337
+ }
338
+ catch (error) {
339
+ logger.error(`[EventCenter] ${this.options.aid} sub client create failed: ${errorMessage(error)}`);
340
+ for (const target of targets) {
341
+ packLedger(target.pack).append({ action: 'subscribe', result: 'failed', bus: target.busAid, events: target.events, code: errorCode(error), reason: errorMessage(error), actor: 'daemon.start', revision: target.pack.revision });
342
+ }
343
+ return;
344
+ }
345
+ // 同一 Bus 聚合订阅集(跨包共享一条连接,角色绑定 per (client, bus))。
346
+ const busEvents = new Map();
347
+ for (const target of targets) {
348
+ const set = busEvents.get(target.busAid) ?? new Set();
349
+ for (const event of target.events)
350
+ set.add(event);
351
+ busEvents.set(target.busAid, set);
352
+ }
353
+ for (const [busAid, events] of busEvents) {
354
+ // ① 鉴权必须先做:SDK 的 onEvent 走 client(bus_aid, 'sub'),而 client() 要求该 bus
355
+ // 已绑定;绑定发生在 authorize() 内部的 bindBus。首次接入某个 bus 时若先调 onEvent,
356
+ // 必然抛 BUS_NOT_BOUND,订阅虽然成功但回调永远挂不上(事件被静默吞掉)。
357
+ try {
358
+ await this.subClient.client.EventService.authorize(busAid, 'sub', 'allowlist', [...events]);
359
+ }
360
+ catch (error) {
361
+ const code = errorCode(error);
362
+ for (const target of targets.filter(item => item.busAid === busAid)) {
363
+ packLedger(target.pack).append({
364
+ action: code === 'FORBIDDEN' ? 'authorize.failed' : 'subscribe',
365
+ result: 'failed', bus: busAid, events: [...events], code, reason: errorMessage(error), actor: 'daemon.start', revision: target.pack.revision,
366
+ });
367
+ }
368
+ logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${code}: ${errorMessage(error)}`);
369
+ continue;
370
+ }
371
+ // ② 回调注册(SDK 按 bus 串行派发,此处必须非阻塞)。
372
+ try {
373
+ const off = this.subClient.client.EventService.onEvent(busAid, payload => {
374
+ const event = toReceivedEvent(busAid, payload);
375
+ if (event)
376
+ this.options.onEvent(event);
377
+ });
378
+ this.unsubscribers.push(() => { off(); });
379
+ }
380
+ catch (error) {
381
+ const code = errorCode(error);
382
+ for (const target of targets.filter(item => item.busAid === busAid)) {
383
+ packLedger(target.pack).append({
384
+ action: 'subscribe', result: 'failed', bus: busAid, events: [...events], code, reason: `onEvent: ${errorMessage(error)}`, actor: 'daemon.start', revision: target.pack.revision,
385
+ });
386
+ }
387
+ logger.warn(`[EventCenter] ${this.options.aid} onEvent(${busAid}) register failed: ${code}: ${errorMessage(error)}`);
388
+ continue;
389
+ }
390
+ // ③ 订阅;失败记台账(FORBIDDEN 等),继续其它 Bus。
391
+ try {
392
+ await this.subClient.client.EventService.subscribe(busAid, [...events]);
393
+ this.registeredSubBuses.set(busAid, new Set(events));
394
+ for (const target of targets.filter(item => item.busAid === busAid)) {
395
+ packLedger(target.pack).append({ action: 'subscribe', result: 'ok', bus: busAid, events: [...events], actor: 'daemon.start', revision: target.pack.revision });
396
+ }
397
+ logger.info(`[EventCenter] ${this.options.aid} subscribed ${busAid}: ${[...events].join(', ')}`);
398
+ }
399
+ catch (error) {
400
+ const code = errorCode(error);
401
+ for (const target of targets.filter(item => item.busAid === busAid)) {
402
+ packLedger(target.pack).append({
403
+ action: code === 'FORBIDDEN' ? 'authorize.failed' : 'subscribe',
404
+ result: 'failed', bus: busAid, events: [...events], code, reason: errorMessage(error), actor: 'daemon.start', revision: target.pack.revision,
405
+ });
406
+ }
407
+ logger.warn(`[EventCenter] ${this.options.aid} subscribe ${busAid} failed: ${code}: ${errorMessage(error)}`);
408
+ }
409
+ }
410
+ }
411
+ async startPublishers(input) {
412
+ const targets = new Map();
413
+ for (const pack of input.state.enabledPacks) {
414
+ for (const entry of pack.publish) {
415
+ const busAid = input.resolutions.get(pack.id)?.get(entry.bus) ?? entry.busResolved;
416
+ if (!busAid)
417
+ continue;
418
+ const group = targets.get(busAid) ?? { packs: [], events: new Set() };
419
+ group.packs.push(pack);
420
+ group.events.add(entry.event);
421
+ targets.set(busAid, group);
422
+ }
423
+ }
424
+ if (targets.size === 0)
425
+ return;
426
+ try {
427
+ this.pubClient = await this.options.createClient(this.options.aid, EVENT_CENTER_PUB_SLOT);
428
+ }
429
+ catch (error) {
430
+ logger.error(`[EventCenter] ${this.options.aid} pub client create failed: ${errorMessage(error)}`);
431
+ return;
432
+ }
433
+ for (const [busAid, group] of targets) {
434
+ try {
435
+ await this.pubClient.client.EventService.authorize(busAid, 'pub', 'allowlist', [...group.events]);
436
+ this.registeredPubBuses.set(busAid, new Set(group.events));
437
+ logger.info(`[EventCenter] ${this.options.aid} publish authorized ${busAid}: ${[...group.events].join(', ')}`);
438
+ }
439
+ catch (error) {
440
+ const code = errorCode(error);
441
+ for (const pack of group.packs) {
442
+ packLedger(pack).append({ action: 'authorize.failed', result: 'failed', bus: busAid, code, reason: errorMessage(error), actor: 'daemon.start', revision: pack.revision });
443
+ }
444
+ logger.warn(`[EventCenter] ${this.options.aid} publish authorize ${busAid} failed: ${code}: ${errorMessage(error)}`);
445
+ }
446
+ }
447
+ }
448
+ /** 发布事件(CLI/IPC 入口)。 */
449
+ async publish(packId, eventName, data, ttlSeconds) {
450
+ if (!this.pubClient)
451
+ throw new EventCenterError('PUB_NOT_CONFIGURED', 'no publish entries loaded; publisher client not started');
452
+ const pack = this.packs.find(candidate => candidate.id === packId);
453
+ if (!pack)
454
+ throw new EventCenterError('PACK_NOT_FOUND', `pack not found or invalid: ${packId}`);
455
+ const entry = pack.publish.find(candidate => candidate.event === eventName);
456
+ if (!entry)
457
+ throw new EventCenterError('EVENT_NOT_FOUND', `pack "${packId}" has no publish entry for "${eventName}"`);
458
+ const busAid = this.resolutions.get(packId)?.get(entry.bus) ?? entry.busResolved;
459
+ if (!busAid)
460
+ throw new EventCenterError('BUS_UNRESOLVED', `bus "${entry.bus}" unresolved for pack "${packId}"`);
461
+ return await this.pubClient.client.EventService.publish(busAid, eventName, data, ttlSeconds !== undefined ? { ttlSeconds } : undefined);
462
+ }
463
+ async stopConnections() {
464
+ if (this.rematerializeTimer) {
465
+ clearInterval(this.rematerializeTimer);
466
+ this.rematerializeTimer = undefined;
467
+ }
468
+ this.stopContactsWatcher();
469
+ // ① 注销回调 ② 退订 ③ drain ④ 关闭 client(订阅侧)。
470
+ for (const off of this.unsubscribers.splice(0)) {
471
+ try {
472
+ off();
473
+ }
474
+ catch { /* 已失效 */ }
475
+ }
476
+ if (this.subClient && this.current) {
477
+ const busEvents = new Map();
478
+ for (const target of this.subscriptionTargets(this.current)) {
479
+ busEvents.set(target.busAid, [...new Set([...(busEvents.get(target.busAid) ?? []), ...target.events])]);
480
+ }
481
+ for (const [busAid, events] of busEvents) {
482
+ try {
483
+ await this.subClient.client.EventService.unsubscribe(busAid, events);
484
+ }
485
+ catch { /* 对端可能已不可达 */ }
486
+ }
487
+ }
488
+ if (this.subClient) {
489
+ try {
490
+ await this.subClient.close();
491
+ }
492
+ catch { /* 忽略 */ }
493
+ this.subClient = undefined;
494
+ }
495
+ if (this.pubClient) {
496
+ try {
497
+ await this.pubClient.close();
498
+ }
499
+ catch { /* 忽略 */ }
500
+ this.pubClient = undefined;
501
+ }
502
+ // 连接已全部关闭,差集基线必须清空:下次接入是全新会话,不是增量。
503
+ this.registeredSubBuses.clear();
504
+ this.registeredPubBuses.clear();
505
+ await this.busHost.close().catch(() => { });
506
+ this.reportGateStatus();
507
+ }
508
+ async close() {
509
+ this.closed = true;
510
+ await this.stopConnections();
511
+ this.current = undefined;
512
+ }
513
+ gateRemoteRequest(senderAid, request, service) {
514
+ const current = this.current;
515
+ const materializer = this.options.materializeAllowlist;
516
+ if (!current || !materializer)
517
+ return;
518
+ if (!current.center.enabled) {
519
+ const decision = { allowed: false, operation: String(request.op ?? 'unknown'), reason: 'bus_disabled' };
520
+ this.rejectBusRequest(senderAid, decision);
521
+ throw Object.assign(new Error('event bus is disabled'), { code: 'FORBIDDEN' });
522
+ }
523
+ let materialized;
524
+ try {
525
+ materialized = materializer(current.center, current.state.catalog.map(entry => entry.event));
526
+ }
527
+ catch (error) {
528
+ logger.warn(`[EventCenter] ${this.options.aid} L2 gate check failed; continuing with SDK allowlist: ${errorMessage(error)}`);
529
+ return;
530
+ }
531
+ if (materialized.degraded) {
532
+ logger.warn(`[EventCenter] ${this.options.aid} L2 gate unavailable (${materialized.reason ?? 'unknown'}); continuing with SDK allowlist`);
533
+ return;
534
+ }
535
+ const decision = evaluateEventBusRequest(senderAid, request, materialized, service);
536
+ if (decision.allowed)
537
+ return;
538
+ this.rejectBusRequest(senderAid, decision);
539
+ throw Object.assign(new Error(`event request rejected: ${decision.reason ?? 'admission'}`), { code: 'FORBIDDEN' });
540
+ }
541
+ rejectBusRequest(senderAid, decision) {
542
+ this.options.onBusRequestRejected?.({
543
+ aid: senderAid,
544
+ operation: decision.operation,
545
+ ...(decision.event ? { event: decision.event } : {}),
546
+ ...(decision.action ? { action: decision.action } : {}),
547
+ reason: decision.reason ?? 'admission',
548
+ });
549
+ logger.warn(`[EventCenter] ${this.options.aid} rejected remote ${decision.operation}`
550
+ + `${decision.event ? ` ${decision.event}` : ''} from ${senderAid}: ${decision.reason ?? 'admission'}`);
551
+ }
552
+ reportGateStatus() {
553
+ const installed = this.busHost.gateInstalled;
554
+ if (this.lastGateStatus === installed)
555
+ return;
556
+ this.lastGateStatus = installed;
557
+ this.options.onGateStatus?.(installed);
558
+ }
559
+ configureContactsWatcher() {
560
+ this.stopContactsWatcher();
561
+ const current = this.current;
562
+ const contactsPath = this.options.contactsPath;
563
+ if (!contactsPath || !current?.center.enabled || current.state.catalog.length === 0)
564
+ return;
565
+ const contactsDir = path.dirname(contactsPath);
566
+ const agentDir = path.dirname(contactsDir);
567
+ const queueRefresh = () => {
568
+ if (this.contactsRefreshTimer)
569
+ clearTimeout(this.contactsRefreshTimer);
570
+ this.contactsRefreshTimer = setTimeout(() => {
571
+ this.contactsRefreshTimer = undefined;
572
+ void this.rematerialize();
573
+ }, 2_000);
574
+ this.contactsRefreshTimer.unref?.();
575
+ };
576
+ const attachContactsWatcher = () => {
577
+ for (const watcher of this.contactsWatchers.splice(1))
578
+ watcher.close();
579
+ try {
580
+ const watcher = fs.watch(contactsDir, (_event, filename) => {
581
+ if (!filename || filename.toString() === path.basename(contactsPath))
582
+ queueRefresh();
583
+ });
584
+ this.contactsWatchers.push(watcher);
585
+ watcher.on('error', error => logger.debug(`[EventCenter] ${this.options.aid} contacts watcher: ${errorMessage(error)}`));
586
+ }
587
+ catch {
588
+ // The parent watcher and periodic refresh remain available if directory/ is absent.
589
+ }
590
+ };
591
+ try {
592
+ const parentWatcher = fs.watch(agentDir, (_event, filename) => {
593
+ if (!filename || filename.toString() === path.basename(contactsDir))
594
+ attachContactsWatcher();
595
+ });
596
+ this.contactsWatchers.push(parentWatcher);
597
+ parentWatcher.on('error', error => logger.debug(`[EventCenter] ${this.options.aid} contacts parent watcher: ${errorMessage(error)}`));
598
+ }
599
+ catch {
600
+ // Periodic materialization is the fallback on filesystems without watch support.
601
+ }
602
+ attachContactsWatcher();
603
+ }
604
+ stopContactsWatcher() {
605
+ if (this.contactsRefreshTimer)
606
+ clearTimeout(this.contactsRefreshTimer);
607
+ this.contactsRefreshTimer = undefined;
608
+ for (const watcher of this.contactsWatchers.splice(0))
609
+ watcher.close();
610
+ }
611
+ /** 状态快照(CLI status 用)。 */
612
+ status() {
613
+ const subscriptions = new Map();
614
+ const publishers = new Map();
615
+ if (this.current) {
616
+ for (const target of this.subscriptionTargets(this.current)) {
617
+ const entry = subscriptions.get(target.busAid) ?? { events: new Set(), packs: new Set() };
618
+ for (const event of target.events)
619
+ entry.events.add(event);
620
+ entry.packs.add(target.pack.id);
621
+ subscriptions.set(target.busAid, entry);
622
+ }
623
+ for (const pack of this.current.state.enabledPacks) {
624
+ for (const item of pack.publish) {
625
+ const busAid = this.current.resolutions.get(pack.id)?.get(item.bus) ?? item.busResolved;
626
+ if (!busAid)
627
+ continue;
628
+ const entry = publishers.get(busAid) ?? { events: new Set(), packs: new Set() };
629
+ entry.events.add(item.event);
630
+ entry.packs.add(pack.id);
631
+ publishers.set(busAid, entry);
632
+ }
633
+ }
634
+ }
635
+ return {
636
+ bus: { status: this.busHost.status, statusDetail: this.busHost.statusDetail },
637
+ subscriptions: [...subscriptions.entries()].map(([busAid, entry]) => ({ busAid, events: [...entry.events], packs: [...entry.packs] })),
638
+ publishers: [...publishers.entries()].map(([busAid, entry]) => ({ busAid, events: [...entry.events], packs: [...entry.packs] })),
639
+ };
640
+ }
641
+ }