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,290 @@
1
+ /**
2
+ * 单个 agent 的事件中心 Bus 宿主:专用 slot client + fastaun EventService。
3
+ * 移植自旧 src/aun/event-bus/bus-host.ts(配置源改为事件包合并目录 + center.json 白名单):
4
+ * - apply(config):写路径(center.json 变更/白名单变更),成功 ⇒ running;失败抛错且配置不变。
5
+ * - ensureRunning(config):生命周期入口,失败转后台自愈(指数退避,DEVICE_CONFLICT 固定间隔)。
6
+ * - SDK 失租后 binding 自行关闭且门面不感知,用定时探测兜底。
7
+ */
8
+ import { logger } from '../utils/logger.js';
9
+ import { EVENT_CENTER_BUS_SLOT, EventCenterError, errorCode, errorMessage, } from './types.js';
10
+ import { installEventBusRequestGate } from './bus-gate.js';
11
+ function withTimeout(promise, ms, code) {
12
+ let timer;
13
+ return Promise.race([
14
+ promise,
15
+ new Promise((_, reject) => {
16
+ timer = setTimeout(() => reject(new EventCenterError(code, `timed out after ${ms}ms`)), ms);
17
+ timer.unref?.();
18
+ }),
19
+ ]).finally(() => { if (timer)
20
+ clearTimeout(timer); });
21
+ }
22
+ export class BusHost {
23
+ options;
24
+ handle;
25
+ statusValue = 'stopped';
26
+ detail = null;
27
+ config;
28
+ probeTimer;
29
+ retryTimer;
30
+ retryDelay = 0;
31
+ generation = 0;
32
+ op = Promise.resolve();
33
+ closed = false;
34
+ gateInstalledValue = false;
35
+ constructor(options) {
36
+ this.options = options;
37
+ }
38
+ get status() { return this.statusValue; }
39
+ get statusDetail() { return this.detail; }
40
+ get gateInstalled() { return this.gateInstalledValue; }
41
+ /** Retry capability detection without restarting the Bus. */
42
+ refreshGate() {
43
+ if (!this.options.requestGate || !this.handle)
44
+ return false;
45
+ this.gateInstalledValue = installEventBusRequestGate(this.handle.client.EventService, this.options.aid, this.options.requestGate);
46
+ return this.gateInstalledValue;
47
+ }
48
+ /** 串行化所有生命周期操作。 */
49
+ serial(action) {
50
+ const next = this.op.then(action, action);
51
+ this.op = next.catch(() => { });
52
+ return next;
53
+ }
54
+ setStatus(status, detail = null) {
55
+ if (this.statusValue !== status || this.detail !== detail) {
56
+ logger.info(`[EventCenter] ${this.options.aid} bus ${this.statusValue} → ${status}${detail ? ` (${detail})` : ''}`);
57
+ }
58
+ this.statusValue = status;
59
+ this.detail = detail;
60
+ }
61
+ /** 写路径:同步生效或失败(失败不改变当前运行配置)。 */
62
+ apply(config) {
63
+ return this.serial(async () => {
64
+ if (this.closed)
65
+ throw new EventCenterError('BUS_UNAVAILABLE', 'event center bus host is closed');
66
+ if (!config || Object.keys(config.catalog).length === 0) {
67
+ await this.stopInner();
68
+ this.config = undefined;
69
+ return;
70
+ }
71
+ if (this.statusValue === 'running' && this.handle) {
72
+ await this.handle.client.EventService.updateConfig(this.options.aid, config);
73
+ this.config = config;
74
+ return;
75
+ }
76
+ // 未运行(stopped / 自愈中):同步启动一次,成功后接管。
77
+ this.clearRetry();
78
+ await this.startInner(config, true);
79
+ });
80
+ }
81
+ /** 生命周期入口:失败转后台自愈。 */
82
+ ensureRunning(config) {
83
+ return this.serial(async () => {
84
+ // close() 置 closed 是为了让调用方显式停用;但 EventRuntime.close() 之后
85
+ // 同一个 BusHost 实例会被 reload 复用(registry.reload = remove + ensureStarted)。
86
+ // 不在这里复位,reload 后 Bus 永远起不来,且重试链被 closed 短路,
87
+ // 表现为 publish/subscribe 都在、Bus 却停在 stopped/conflict。
88
+ if (this.closed) {
89
+ this.closed = false;
90
+ this.generation++;
91
+ }
92
+ this.config = config;
93
+ if (this.statusValue === 'running')
94
+ return;
95
+ try {
96
+ await this.startInner(config, false);
97
+ }
98
+ catch (error) {
99
+ this.scheduleRetry(error);
100
+ }
101
+ });
102
+ }
103
+ async stats(params = {}) {
104
+ if (this.statusValue !== 'running' || !this.handle)
105
+ return null;
106
+ return await this.handle.client.EventService.stats(this.options.aid, params);
107
+ }
108
+ /**
109
+ * The SDK currently exposes subscriber counts through stats but not the AID
110
+ * list. Read the in-process service snapshot when the SDK facade exposes it;
111
+ * callers must handle unavailable as a normal capability result.
112
+ */
113
+ subscribers() {
114
+ if (this.statusValue !== 'running' || !this.handle)
115
+ return { available: false, subscribers: [], reason: 'bus_not_running' };
116
+ const facade = this.handle.client.EventService;
117
+ const service = facade.buses?.get?.(this.options.aid)?.service;
118
+ if (!service?.subscriptions)
119
+ return { available: false, subscribers: [], reason: 'sdk_subscriber_details_unavailable' };
120
+ try {
121
+ service.pruneSubscriptions?.();
122
+ }
123
+ catch { /* stats remains usable if pruning is private/unavailable */ }
124
+ const subscribers = [];
125
+ for (const sub of service.subscriptions.values()) {
126
+ const aid = typeof sub.aid === 'string' ? sub.aid : '';
127
+ const event = typeof sub.event === 'string' ? sub.event : '';
128
+ if (!aid || !event)
129
+ continue;
130
+ const lease = typeof sub.leaseId === 'string' ? service.leases?.get(sub.leaseId) : undefined;
131
+ const expiresAt = typeof lease?.expires_at === 'number' ? lease.expires_at : undefined;
132
+ subscribers.push({ aid, event, ...(typeof sub.leaseId === 'string' ? { leaseId: sub.leaseId } : {}), ...(expiresAt !== undefined ? { expiresAt } : {}), active: expiresAt === undefined || expiresAt > Date.now() });
133
+ }
134
+ subscribers.sort((a, b) => a.event.localeCompare(b.event) || a.aid.localeCompare(b.aid));
135
+ return { available: true, subscribers };
136
+ }
137
+ stop() {
138
+ return this.serial(async () => {
139
+ await this.stopInner();
140
+ });
141
+ }
142
+ async close() {
143
+ this.closed = true;
144
+ await this.stop();
145
+ }
146
+ async startInner(config, strict) {
147
+ const generation = ++this.generation;
148
+ const previousStatus = this.statusValue;
149
+ const previousDetail = this.detail;
150
+ this.setStatus('starting');
151
+ const aid = this.options.aid;
152
+ try {
153
+ await withTimeout((async () => {
154
+ if (!this.handle)
155
+ this.handle = await this.options.createClient(aid, EVENT_CENTER_BUS_SLOT);
156
+ const service = this.handle.client.EventService;
157
+ // 配置唯一真源是包目录+center.json;SDK state.load 会覆盖 start 参数,因此 load 返回同一份配置。
158
+ const current = this.config ?? config;
159
+ this.refreshGate();
160
+ await service.start(aid, {
161
+ catalog: current.catalog,
162
+ allowlist: current.allowlist,
163
+ state: {
164
+ load: () => ({ service_aid: aid, catalog: current.catalog, allowlist: current.allowlist, issued_grants: [], paused_cids: [] }),
165
+ save: () => { },
166
+ },
167
+ });
168
+ this.refreshGate();
169
+ await service.updateConfig(aid, config);
170
+ })(), this.options.startTimeoutMs ?? 10_000, 'BUS_UNAVAILABLE');
171
+ }
172
+ catch (error) {
173
+ if (generation === this.generation) {
174
+ await this.releaseClient();
175
+ const code = errorCode(error);
176
+ const conflict = code === 'DEVICE_CONFLICT';
177
+ if (strict) {
178
+ this.setStatus(previousStatus === 'starting' ? 'stopped' : previousStatus, previousDetail);
179
+ if (previousStatus !== 'running' && previousStatus !== 'stopped')
180
+ this.scheduleRetry(error);
181
+ }
182
+ else {
183
+ this.setStatus(conflict ? 'conflict' : 'error', `${code}: ${errorMessage(error)}`);
184
+ }
185
+ throw new EventCenterError(conflict ? 'BUS_CONFLICT' : 'BUS_UNAVAILABLE', conflict ? 'another instance of this agent already hosts the event bus' : `event bus unavailable: ${errorMessage(error)}`, { retryable: !conflict });
186
+ }
187
+ throw error;
188
+ }
189
+ this.config = config;
190
+ this.retryDelay = 0;
191
+ this.setStatus('running');
192
+ this.startProbe();
193
+ }
194
+ async stopInner() {
195
+ this.generation++;
196
+ this.clearRetry();
197
+ this.stopProbe();
198
+ if (this.handle && (this.statusValue === 'running' || this.statusValue === 'lease_lost')) {
199
+ const service = this.handle.client.EventService;
200
+ try {
201
+ await withTimeout(service.drain(this.options.aid), 2_000, 'TIMEOUT');
202
+ }
203
+ catch { }
204
+ try {
205
+ await service.close(this.options.aid);
206
+ }
207
+ catch { }
208
+ }
209
+ await this.releaseClient();
210
+ this.setStatus('stopped');
211
+ }
212
+ async releaseClient() {
213
+ const handle = this.handle;
214
+ this.handle = undefined;
215
+ this.gateInstalledValue = false;
216
+ if (handle) {
217
+ try {
218
+ await handle.close();
219
+ }
220
+ catch (error) {
221
+ logger.warn(`[EventCenter] ${this.options.aid} bus client close failed: ${errorMessage(error)}`);
222
+ }
223
+ }
224
+ }
225
+ /** binding 是否仍持有实例租约。优先读 SDK 内部状态,读不到时用 stats 探测。 */
226
+ async leaseAlive() {
227
+ const service = this.handle?.client.EventService;
228
+ const running = service?.buses?.get?.(this.options.aid)?.binding?.running;
229
+ if (typeof running === 'boolean')
230
+ return running;
231
+ try {
232
+ await this.handle.client.EventService.stats(this.options.aid, {});
233
+ return true;
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ }
239
+ startProbe() {
240
+ this.stopProbe();
241
+ const generation = this.generation;
242
+ this.probeTimer = setInterval(() => {
243
+ void this.serial(async () => {
244
+ if (generation !== this.generation || this.statusValue !== 'running' || !this.handle)
245
+ return;
246
+ if (await this.leaseAlive())
247
+ return;
248
+ this.stopProbe();
249
+ this.setStatus('lease_lost', 'SERVICE_LEASE_LOST');
250
+ this.scheduleRetry(new EventCenterError('SERVICE_LEASE_LOST', 'event bus lease lost'));
251
+ });
252
+ }, this.options.probeIntervalMs ?? 15_000);
253
+ this.probeTimer.unref?.();
254
+ }
255
+ stopProbe() {
256
+ if (this.probeTimer)
257
+ clearInterval(this.probeTimer);
258
+ this.probeTimer = undefined;
259
+ }
260
+ clearRetry() {
261
+ if (this.retryTimer)
262
+ clearTimeout(this.retryTimer);
263
+ this.retryTimer = undefined;
264
+ }
265
+ scheduleRetry(error) {
266
+ if (this.closed || !this.config)
267
+ return;
268
+ this.clearRetry();
269
+ const conflict = errorCode(error) === 'DEVICE_CONFLICT' || (error instanceof EventCenterError && error.code === 'BUS_CONFLICT');
270
+ const max = this.options.maxBackoffMs ?? 60_000;
271
+ this.retryDelay = conflict
272
+ ? (this.options.conflictRetryMs ?? 60_000)
273
+ : Math.min(max, this.retryDelay ? this.retryDelay * 2 : 1_000);
274
+ const generation = this.generation;
275
+ this.retryTimer = setTimeout(() => {
276
+ this.retryTimer = undefined;
277
+ void this.serial(async () => {
278
+ if (this.closed || generation !== this.generation || this.statusValue === 'running')
279
+ return;
280
+ try {
281
+ await this.startInner(this.config, false);
282
+ }
283
+ catch (retryError) {
284
+ this.scheduleRetry(retryError);
285
+ }
286
+ });
287
+ }, this.retryDelay);
288
+ this.retryTimer.unref?.();
289
+ }
290
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * bus 占位符解析:$self / $owner / $pa / $pa.<role> / 字面 AID。
3
+ * 设计:detailed-design.md §三。$pa.<role> 多匹配取 AID 字典序第一个,不报错、不并发。
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { atomicWriteJson } from '../utils/atomic-write.js';
8
+ import { AID_PATTERN, ROLE_NAME_PATTERN } from './validation.js';
9
+ export class BusResolveError extends Error {
10
+ code;
11
+ constructor(code, message) {
12
+ super(message);
13
+ this.code = code;
14
+ this.name = 'BusResolveError';
15
+ }
16
+ }
17
+ export function isBusPlaceholder(ref) {
18
+ return ref === '$self' || ref === '$owner' || ref === '$pa' || ref.startsWith('$pa.');
19
+ }
20
+ /** 解析单个 bus 引用。失败抛 BusResolveError。 */
21
+ export function resolveBusRef(ref, context) {
22
+ if (ref === '$self') {
23
+ if (!context.self)
24
+ throw new BusResolveError('INVALID_AID', '$self resolved to empty AID');
25
+ return context.self;
26
+ }
27
+ if (ref === '$owner') {
28
+ if (!context.owner)
29
+ throw new BusResolveError('OWNER_MISSING', 'this AID has no owner');
30
+ return context.owner;
31
+ }
32
+ if (ref === '$pa') {
33
+ if (!context.pa)
34
+ throw new BusResolveError('PA_MISSING', 'contacts has no personal_assistant');
35
+ return context.pa;
36
+ }
37
+ if (ref.startsWith('$pa.')) {
38
+ const role = ref.slice('$pa.'.length);
39
+ if (!ROLE_NAME_PATTERN.test(role)) {
40
+ throw new BusResolveError('INVALID_ROLE', `invalid role name: ${role}`);
41
+ }
42
+ const candidates = context.paRoles?.[role];
43
+ if (!candidates || candidates.length === 0) {
44
+ throw new BusResolveError('ROLE_NOT_FOUND', `pa_roles has no role "${role}"`);
45
+ }
46
+ // 多匹配取字典序第一个:同一目录在多个 Agent 上解析结果稳定可复现。
47
+ return [...candidates].sort()[0];
48
+ }
49
+ if (!AID_PATTERN.test(ref)) {
50
+ throw new BusResolveError('INVALID_AID', `invalid literal AID: ${ref}`);
51
+ }
52
+ return ref;
53
+ }
54
+ /**
55
+ * 解析一个包内全部 bus 引用(publish + subscribe 去重)。
56
+ * strict:任一失败即失败(failures 非空,resolved 不含该引用)。
57
+ * keep-last:失败引用沿用 lastResolved 中的上次结果并记 degraded;无上次结果仍算失败。
58
+ */
59
+ export function resolvePackBuses(refs, context, strategy, lastResolved) {
60
+ const resolved = new Map();
61
+ const failures = [];
62
+ const degraded = [];
63
+ for (const ref of new Set(refs)) {
64
+ try {
65
+ resolved.set(ref, resolveBusRef(ref, context));
66
+ }
67
+ catch (error) {
68
+ if (error instanceof BusResolveError) {
69
+ const last = lastResolved?.get(ref);
70
+ if (strategy === 'keep-last' && last) {
71
+ resolved.set(ref, last);
72
+ degraded.push({ ref, lastAid: last });
73
+ }
74
+ else {
75
+ failures.push({ ref, code: error.code, message: error.message });
76
+ }
77
+ }
78
+ else {
79
+ throw error;
80
+ }
81
+ }
82
+ }
83
+ return { resolved, failures, degraded };
84
+ }
85
+ /** keep-last 上次成功解析的持久化:events/.bus-resolve-state.json,结构 { <packId>: { <ref>: aid } }。 */
86
+ export class BusResolveState {
87
+ filePath;
88
+ data = {};
89
+ constructor(filePath) {
90
+ this.filePath = filePath;
91
+ }
92
+ static forEventsDir(eventsDir) {
93
+ return new BusResolveState(path.join(eventsDir, '.bus-resolve-state.json'));
94
+ }
95
+ load() {
96
+ try {
97
+ const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
98
+ this.data = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
99
+ }
100
+ catch {
101
+ this.data = {};
102
+ }
103
+ }
104
+ get(packId) {
105
+ const entry = this.data[packId];
106
+ return new Map(Object.entries(entry ?? {}));
107
+ }
108
+ set(packId, resolved) {
109
+ this.data[packId] = Object.fromEntries(resolved);
110
+ }
111
+ save() {
112
+ try {
113
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
114
+ atomicWriteJson(this.filePath, this.data);
115
+ }
116
+ catch {
117
+ // 持久化失败不致命:下次 keep-last 退化为 strict 行为。
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * center.json 管理:读、原子写、白名单增删查;变更联动 SDK updateConfig 由调用方(runtime)执行。
3
+ */
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { atomicWriteJson } from '../utils/atomic-write.js';
7
+ import { centerLedger } from './ledger.js';
8
+ import { CENTER_JSON } from './pack-loader.js';
9
+ import { EventCenterError } from './types.js';
10
+ import { validateCenterConfig } from './validation.js';
11
+ export class CenterConfigStore {
12
+ filePath;
13
+ ledger;
14
+ constructor(options) {
15
+ this.filePath = path.join(options.eventsDir, CENTER_JSON);
16
+ this.ledger = options.ledger ?? centerLedger(options.eventsDir);
17
+ }
18
+ /** 读取并校验;校验失败返回缺省并带 errors(Bus 不启动,不覆盖磁盘)。 */
19
+ read() {
20
+ let rawText;
21
+ try {
22
+ rawText = fs.readFileSync(this.filePath, 'utf8');
23
+ }
24
+ catch {
25
+ return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} }, exists: false, errors: [] };
26
+ }
27
+ let raw;
28
+ try {
29
+ raw = JSON.parse(rawText);
30
+ }
31
+ catch (error) {
32
+ return {
33
+ config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} },
34
+ exists: true,
35
+ errors: [`${CENTER_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
36
+ };
37
+ }
38
+ const validated = validateCenterConfig(raw);
39
+ if (!validated.ok) {
40
+ return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} }, exists: true, errors: validated.errors };
41
+ }
42
+ return { config: validated.value, exists: true, errors: [] };
43
+ }
44
+ write(config) {
45
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
46
+ atomicWriteJson(this.filePath, {
47
+ v: 1,
48
+ enabled: config.enabled,
49
+ authMode: config.authMode,
50
+ admission: config.admission,
51
+ allowlist: config.allowlist,
52
+ });
53
+ }
54
+ /** 白名单增删。返回更新后的配置;不做磁盘之外的生效动作。 */
55
+ mutateAllowlist(input) {
56
+ const { config } = this.read();
57
+ const current = config.allowlist[input.event];
58
+ const entry = current
59
+ ? { allow: { publish: [...current.allow.publish], subscribe: [...current.allow.subscribe] }, deny: { publish: [...current.deny.publish], subscribe: [...current.deny.subscribe] } }
60
+ : { allow: { publish: [], subscribe: [] }, deny: { publish: [], subscribe: [] } };
61
+ const rules = input.rule === 'deny' ? entry.deny : entry.allow;
62
+ const list = input.role === 'publish' ? rules.publish : rules.subscribe;
63
+ const added = [];
64
+ const removed = [];
65
+ for (const aid of input.aids) {
66
+ if (input.action === 'add') {
67
+ const opposite = input.role === 'publish'
68
+ ? (input.rule === 'deny' ? entry.allow.publish : entry.deny.publish)
69
+ : (input.rule === 'deny' ? entry.allow.subscribe : entry.deny.subscribe);
70
+ if (opposite.includes(aid)) {
71
+ throw new EventCenterError('INVALID_ARGS', `AID appears in both allow and deny for ${input.event}/${input.role}: ${aid}`);
72
+ }
73
+ if (!list.includes(aid)) {
74
+ list.push(aid);
75
+ added.push(aid);
76
+ }
77
+ }
78
+ else {
79
+ const index = list.indexOf(aid);
80
+ if (index >= 0) {
81
+ list.splice(index, 1);
82
+ removed.push(aid);
83
+ }
84
+ }
85
+ }
86
+ config.allowlist[input.event] = entry;
87
+ this.write(config);
88
+ this.ledger.append({
89
+ action: 'allowlist.update',
90
+ result: 'ok',
91
+ event: input.event,
92
+ ...(added.length ? { added } : {}),
93
+ ...(removed.length ? { removed } : {}),
94
+ ...(input.rule ? { rule: input.rule } : {}),
95
+ ...(input.by ? { by: input.by } : {}),
96
+ actor: input.by ? 'script' : 'menu',
97
+ });
98
+ return { config, changed: entry, added, removed };
99
+ }
100
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 事件中心专用 AUN client 工厂:独立 slot(bus/sub/pub 三条连接,绝不复用 daemon 主连接)。
3
+ * 流程与旧 src/aun/event-bus/client-factory.ts 一致:getAidStore → loadClient → authenticate → connect。
4
+ */
5
+ import os from 'node:os';
6
+ import { getAidStore, loadClient } from '../aun/aid/store.js';
7
+ export const createEventClient = async (aid, slotId) => {
8
+ const store = await getAidStore({ slotId });
9
+ let client;
10
+ try {
11
+ client = await loadClient(store, aid);
12
+ await client.authenticate();
13
+ await client.connect({
14
+ extra_info: { app: 'evolcore', role: slotId, pid: process.pid, hostname: os.hostname() },
15
+ auto_reconnect: true,
16
+ background_sync: false,
17
+ retry_max_attempts: 0,
18
+ retry_initial_delay: 1.0,
19
+ retry_max_delay: 60.0,
20
+ });
21
+ const handle = client;
22
+ return {
23
+ client: handle,
24
+ async close() {
25
+ try {
26
+ await handle.close();
27
+ }
28
+ finally {
29
+ await store.close();
30
+ }
31
+ },
32
+ };
33
+ }
34
+ catch (error) {
35
+ try {
36
+ if (client)
37
+ await client.close();
38
+ }
39
+ catch {
40
+ // 已在失败路径上,二次关闭错误忽略。
41
+ }
42
+ try {
43
+ await store.close();
44
+ }
45
+ catch {
46
+ // 同上。
47
+ }
48
+ throw error;
49
+ }
50
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * daemon 接线:事件中心随 agent 的 Trigger 调度器启停(与旧事件总线相同的生命周期挂点)。
3
+ * daemon 自身的 Trigger owner 不是 agent,不承载事件中心。
4
+ */
5
+ import fs from 'node:fs';
6
+ import { agentDir } from '../paths.js';
7
+ import { createEventClient } from './client-factory.js';
8
+ import { EventCenterRegistry } from './registry.js';
9
+ /**
10
+ * 解析 agent 工程目录:只接受真实存在的目录。
11
+ *
12
+ * `EvolAgent.projectPath` 在 `projects.defaultPath` 为空时回落到 `process.cwd()`,
13
+ * 那会把整个 EvolCore 仓当成工程目录,沙箱边界与 trigger 的 cwd 都会漂。
14
+ * 这里改为 fail-closed 到 `undefined`:沙箱明确报 `SCRIPT_SANDBOX_UNAVAILABLE`,
15
+ * 而不是拿到一个语义可疑的目录继续跑。
16
+ */
17
+ export function resolveAgentProjectPath(aid, candidate) {
18
+ const trimmed = candidate?.trim();
19
+ if (!trimmed)
20
+ return undefined;
21
+ try {
22
+ return fs.statSync(trimmed).isDirectory() ? trimmed : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ export function createDaemonEventCenter(options) {
29
+ const registry = new EventCenterRegistry({
30
+ agentDir,
31
+ createClient: options.createClient ?? createEventClient,
32
+ getProjectPath: options.getProjectPath
33
+ ?? (aid => resolveAgentProjectPath(aid, options.agentRegistry.get(aid)?.projectPath)),
34
+ getScheduler: aid => options.triggerSchedulers.get(aid),
35
+ });
36
+ options.triggerSchedulers.addLifecycleListener({
37
+ started: aid => {
38
+ if (options.agentRegistry.get(aid))
39
+ void registry.ensureStarted(aid);
40
+ },
41
+ removed: aid => { void registry.remove(aid); },
42
+ suspending: () => { void registry.closeAll(); },
43
+ });
44
+ return registry;
45
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 占位符解析上下文的数据源:直读 agents/<aid>/directory/contacts.json。
3
+ * 与 OwnerDirectoryCache 同一文件(cachePath('contacts')),只读、防御式:
4
+ * 文件缺失/字段非法 → 相应上下文项留空(strict 包会因此 invalid)。
5
+ * pa_roles 为新增顶层字段,暂不参与 content_digest。
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { AID_PATTERN } from './validation.js';
10
+ export function readBusResolverContext(aid, agentDir) {
11
+ const context = { self: aid, paRoles: {} };
12
+ let raw;
13
+ try {
14
+ raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
15
+ }
16
+ catch {
17
+ return context;
18
+ }
19
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
20
+ return context;
21
+ const record = raw;
22
+ const ownerAid = identityAid(record.owner);
23
+ if (ownerAid)
24
+ context.owner = ownerAid;
25
+ const paAid = identityAid(record.personal_assistant);
26
+ if (paAid)
27
+ context.pa = paAid;
28
+ const paRoles = parsePaRoles(record.pa_roles);
29
+ if (paRoles)
30
+ context.paRoles = paRoles;
31
+ return context;
32
+ }
33
+ function identityAid(value) {
34
+ if (!value || typeof value !== 'object')
35
+ return undefined;
36
+ const aid = value.aid;
37
+ return typeof aid === 'string' && AID_PATTERN.test(aid) ? aid : undefined;
38
+ }
39
+ function parsePaRoles(value) {
40
+ if (!value || typeof value !== 'object' || Array.isArray(value))
41
+ return undefined;
42
+ const out = {};
43
+ for (const [role, aids] of Object.entries(value)) {
44
+ if (!/^[a-z0-9_-]+$/.test(role))
45
+ continue;
46
+ if (!Array.isArray(aids))
47
+ continue;
48
+ const valid = aids.filter((item) => typeof item === 'string' && AID_PATTERN.test(item));
49
+ if (valid.length > 0)
50
+ out[role] = valid;
51
+ }
52
+ return out;
53
+ }