evolcore 0.0.45 → 0.0.47

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. package/scripts/agent-template/pack.mjs +0 -169
@@ -2,17 +2,17 @@
2
2
  * `ec events` 的 daemon 侧 IPC 操作(events.op)。
3
3
  * daemon-control 风格(不走 delegation argv 哈希);CLI 透传 argv,daemon 解析执行。
4
4
  */
5
+ import path from 'node:path';
5
6
  import { logger } from '../utils/logger.js';
6
- import { Ledger, centerLedger } from './ledger.js';
7
+ import { Ledger, centerLedger } from '../core/pack-ledger.js';
7
8
  import { EventLog } from './event-log.js';
8
9
  import { loadPackDir } from './pack-loader.js';
9
- import { toSdkCatalog } from './pack-manager.js';
10
10
  import { materializeAllowlist } from './admission-materializer.js';
11
11
  import { EventCenterError, errorMessage } from './types.js';
12
- import { installPack, listPackDirs, removePack } from '../core/pack-install.js';
12
+ import { installPack, listPackDirs, removePack, setPackEnabled } from '../core/pack-install.js';
13
13
  import { CenterConfigStore } from './center-config.js';
14
14
  import { agentEventsDir } from '../paths.js';
15
- import { authorizePackTarget, isManagingEventsCommand } from '../core/pack-auth.js';
15
+ import { authorizePackTarget, packOperation } from '../core/pack-auth.js';
16
16
  const HELP = `ec events — 事件中心运维
17
17
 
18
18
  用法:
@@ -20,7 +20,7 @@ const HELP = `ec events — 事件中心运维
20
20
  ec events ledger <包名> [--tail N] 台账
21
21
  ec events tail <包名> [--tail N] 事件日志
22
22
  ec events doctor <包名> 诊断
23
- ec events reload [<包名>] 重载(重新扫描目录并重建订阅)
23
+ ec events reload 重载(重新扫描全部包并重建订阅)
24
24
  ec events rules add <事件> --publish <aid> [--subscribe <aid>] [--deny]
25
25
  ec events rules remove <事件> --publish <aid> [--subscribe <aid>] [--deny]
26
26
  ec events rules show [--event <事件>]
@@ -29,6 +29,7 @@ const HELP = `ec events — 事件中心运维
29
29
  安装与卸载(L 类目录只能由 daemon 代写):
30
30
  ec events pack add <包名> --from <源目录> [--aid <aid>]
31
31
  ec events pack remove <包名> [--aid <aid>] [--purge]
32
+ ec events pack enable / disable <包名> [--aid <aid>]
32
33
  ec events pack list [--aid <aid>]
33
34
 
34
35
  add 遇到已安装的包直接报错,先 remove 再装。
@@ -164,7 +165,12 @@ export function createEventsOperationExecutor(deps) {
164
165
  return { ok: false, code: error.code, error: error.message };
165
166
  }
166
167
  const message = errorMessage(error);
167
- const code = /\b([A-Z][A-Z0-9_]{3,})\b/.exec(message)?.[1] ?? 'INTERNAL_ERROR';
168
+ // 先认 `error.code`(底层用 `Object.assign(err, { code })` 挂的结构化错误码),
169
+ // 从消息文本正则捞 `[A-Z_]{4,}` 只作兜底——文本里没有大写词汇时会退化成
170
+ // INTERNAL_ERROR,把可判定的冲突说成内部故障。
171
+ const code = typeof error?.code === 'string'
172
+ ? error.code
173
+ : /\b([A-Z][A-Z0-9_]{3,})\b/.exec(message)?.[1] ?? 'INTERNAL_ERROR';
168
174
  logger.warn(`[EventCenter] events.op failed: ${code}: ${message}`);
169
175
  return { ok: false, code, error: message };
170
176
  }
@@ -174,26 +180,31 @@ async function execute(deps, parsed) {
174
180
  const { command } = parsed;
175
181
  if (command === 'help')
176
182
  return { ok: true, result: { help: HELP } };
177
- if (command === 'reload') {
178
- const target = resolveAid(deps, parsed);
179
- if (target.error)
180
- return target.error;
181
- await deps.registry.reload(target.aid);
182
- const unit = deps.registry.get(target.aid);
183
- return { ok: true, result: { aid: target.aid, packs: unit?.state.enabledPacks.map(pack => pack.id) ?? [] } };
183
+ // 不支持单包重载:重载一定会全量重扫目录并重建订阅。接受包名只会让调用方
184
+ // 以为自己只影响了一个包。给明确报错,不静默全量。
185
+ if (command === 'reload' && parsed.pack) {
186
+ return { ok: false, code: 'INVALID_ARGV', error: `reload does not accept a pack name (reloads all packs): ${parsed.pack}` };
184
187
  }
185
188
  const target = resolveAid(deps, parsed, { preferDefault: command === 'pack' });
186
189
  if (target.error)
187
190
  return target.error;
188
191
  const aid = target.aid;
192
+ // 授权必须在任何分支之前:`reload` 曾在授权判定之上直接 return,托管会话
193
+ // 只要过得了 IPC 层就能重建整个事件中心。reload 在 PACK_OPERATIONS 里是
194
+ // `read`,所以上移不收紧任何现有能力,只让未通过会话身份检查的调用被拦下。
189
195
  const auth = authorizePackTarget({
190
196
  caller: parsed.caller ?? { kind: 'local-control' },
191
197
  targetAid: aid,
192
198
  ...(deps.daemonAid?.() ? { daemonAid: deps.daemonAid() } : {}),
193
- requiresManagement: isManagingEventsCommand(parsed.command.startsWith('rules:') ? 'rules' : parsed.command),
199
+ operation: packOperation('events', parsed.command, parsed.action),
194
200
  });
195
201
  if (!auth.allowed)
196
202
  return { ok: false, code: auth.code, error: auth.error };
203
+ if (command === 'reload') {
204
+ await deps.registry.reload(aid);
205
+ const unit = deps.registry.get(aid);
206
+ return { ok: true, result: { aid, packs: unit?.state.enabledPacks.map(pack => pack.id) ?? [] } };
207
+ }
197
208
  // ── 包安装/卸载:不需要 unit 已启动(装完再 reload 即可生效)──
198
209
  if (command === 'pack') {
199
210
  const eventsDir = agentEventsDir(aid);
@@ -217,8 +228,9 @@ async function execute(deps, parsed) {
217
228
  // "Connection replaced by new session"),既不干净也拖慢安装。
218
229
  // 没有 events-config.json 时 Bus 永远 stopped,包 active 却收不到事件。
219
230
  const centerStoreBefore = new CenterConfigStore({ eventsDir });
231
+ const before = centerStoreBefore.read();
220
232
  let createdCenter = false;
221
- if (!centerStoreBefore.read().exists) {
233
+ if (!before.exists) {
222
234
  centerStoreBefore.write({
223
235
  enabled: true,
224
236
  authMode: 'allowlist',
@@ -229,13 +241,40 @@ async function execute(deps, parsed) {
229
241
  createdCenter = true;
230
242
  }
231
243
  await deps.registry.reload(aid);
232
- return { ok: true, result: { aid, ...installed, ...(createdCenter ? { createdCenter: true } : {}) } };
244
+ // 配置存在但坏了:包装上了、Bus 却永远不会启动,用户只看到"装了但没反应"。
245
+ // 不在这里替他改文件(会覆盖掉他手写的规则),但必须把原因带回去。
246
+ const configErrors = createdCenter ? [] : before.errors;
247
+ return {
248
+ ok: true,
249
+ result: {
250
+ aid, ...installed,
251
+ ...(createdCenter ? { createdCenter: true } : {}),
252
+ ...(configErrors.length > 0 ? { configErrors } : {}),
253
+ },
254
+ };
233
255
  }
234
256
  if (parsed.action === 'remove') {
235
257
  const removed = removePack({ pack: parsed.pack, targetRoot: eventsDir, purge: parsed.purge === true });
236
258
  await deps.registry.reload(aid);
237
259
  return { ok: true, result: { aid, ...removed } };
238
260
  }
261
+ if (parsed.action === 'enable' || parsed.action === 'disable') {
262
+ const enabled = parsed.action === 'enable';
263
+ const toggled = setPackEnabled({
264
+ targetRoot: eventsDir,
265
+ pack: parsed.pack,
266
+ manifestFile: 'pack.json',
267
+ enabled,
268
+ });
269
+ // 台账记"有人主动改过",与加载时发现 enabled=false 的 pack.disabled 分开。
270
+ new Ledger(path.join(toggled.dir, 'ledger.jsonl')).append({
271
+ action: enabled ? 'pack.enable' : 'pack.disable',
272
+ result: 'ok',
273
+ actor: 'cli',
274
+ });
275
+ await deps.registry.reload(aid);
276
+ return { ok: true, result: { aid, ...toggled } };
277
+ }
239
278
  return { ok: false, code: 'UNKNOWN_COMMAND', error: `unknown pack action: ${parsed.action ?? '(none)'}
240
279
  ${HELP}` };
241
280
  }
@@ -327,16 +366,18 @@ ${HELP}` };
327
366
  const aids = parsed.aids[role];
328
367
  if (!aids)
329
368
  continue;
330
- const result = unit.centerStore.mutateAllowlist({ event: parsed.event, action, role, rule: parsed.rule, aids });
369
+ const result = unit.centerStore.mutateAllowlist({ event: parsed.event, action, role, rule: parsed.rule, aids, actor: 'cli' });
331
370
  applied[role] = { added: result.added, removed: result.removed };
332
- // 联动 Bus:白名单变更立即生效(updateConfig)。
333
- const materialized = materializeAllowlist(result.config, unit.agentDir, unit.aid);
334
- if (result.config.enabled && unit.state.catalog.length > 0 && !materialized.degraded) {
335
- await unit.runtime.busHost.apply({
336
- catalog: toSdkCatalog(unit.state.catalog),
337
- allowlist: materialized.allowlist,
338
- });
339
- }
371
+ // 联动 Bus:走 runtime.updateCenter 而不是直接递给 busHost.apply。
372
+ //
373
+ // 两个理由:
374
+ // 1. 必须带上已注册事件全集。`materializeAllowlist` 的第 4 参缺省时退化成
375
+ // `Object.keys(config.rules)`,没建过规则的事件整条从 SDK allowlist 消失,
376
+ // 本该放行的订阅者被挡。
377
+ // 2. runtime 的 `current` 要一起更新,否则 5 分钟后的 rematerialize 会拿旧
378
+ // 的 center 把这次变更原样回退。
379
+ const materialized = materializeAllowlist(result.config, unit.agentDir, unit.aid, unit.state.catalog.map(entry => entry.event));
380
+ await unit.runtime.updateCenter(result.config, materialized);
340
381
  }
341
382
  return { ok: true, result: { aid, event: parsed.event, applied } };
342
383
  }
@@ -1,16 +1,14 @@
1
1
  /**
2
- * 事件包目录扫描与加载:events/<pack>/pack.json 与 events/events-config.json。
2
+ * 事件包目录扫描与加载:events/<pack>/pack.json。
3
3
  * 每个东西只有一个名字,不接受别名(包主要由 agent 生成,多一个写法就多一次选错的机会)。
4
4
  * 脚本路径做 realpath 全级校验,防符号链接逃逸出包目录。
5
5
  */
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { sha256 } from '../trigger/validation.js';
9
- import { validateCenterConfig, validatePackJson } from './validation.js';
9
+ import { validatePackJson } from './validation.js';
10
10
  import { migrateLegacyFileName } from '../core/legacy-rename.js';
11
11
  import { PACK_ARCHIVED_MARKER as ARCHIVED_MARKER } from '../core/pack-install.js';
12
- import { atomicWriteJson } from '../utils/atomic-write.js';
13
- import { logger } from '../utils/logger.js';
14
12
  /**
15
13
  * 事件包与服务包的文件名一一对应,且**每个东西只有一个名字**(不留别名):
16
14
  *
@@ -28,8 +26,10 @@ export const PACK_JSON = 'pack.json';
28
26
  export const LEDGER_FILE = 'ledger.jsonl';
29
27
  export const SCRIPTS_DIR = 'scripts';
30
28
  export const LOGS_DIR = 'logs';
31
- export const EVENTS_CONFIG_JSON = 'events-config.json';
32
- /** realpath 全级校验:目标真实路径必须仍在包目录内(防中间目录符号链接逃逸)。 */
29
+ /**
30
+ * realpath 全级校验:目标真实路径必须仍在包目录内(防中间目录符号链接逃逸)。
31
+ * 通过时返回**已解析的真实路径**,调用方直接对它 stat,不必再 realpath 一次。
32
+ */
33
33
  function assertInsidePackDir(packDir, target, errors, field) {
34
34
  let realTarget;
35
35
  try {
@@ -37,14 +37,14 @@ function assertInsidePackDir(packDir, target, errors, field) {
37
37
  }
38
38
  catch {
39
39
  errors.push(`${field} not found: ${path.relative(packDir, target)}`);
40
- return false;
40
+ return undefined;
41
41
  }
42
42
  const realPackDir = fs.realpathSync(packDir);
43
43
  if (realTarget !== realPackDir && !realTarget.startsWith(realPackDir + path.sep)) {
44
44
  errors.push(`${field} escapes pack directory via symlink`);
45
- return false;
45
+ return undefined;
46
46
  }
47
- return true;
47
+ return realTarget;
48
48
  }
49
49
  /** 加载单个包目录。返回 null 表示该包 invalid(errors 已填)。 */
50
50
  export function loadPackDir(packDir, errors) {
@@ -93,10 +93,10 @@ export function loadPackDir(packDir, errors) {
93
93
  for (const entry of validated.value.subscribe) {
94
94
  const relativeUnderScripts = entry.handler.script.slice(SCRIPTS_DIR.length + 1);
95
95
  const scriptPath = path.join(scriptsDir ?? canonicalScripts, relativeUnderScripts);
96
- if (!assertInsidePackDir(packDir, scriptPath, errors, `handler.script "${entry.handler.script}"`))
96
+ const realScript = assertInsidePackDir(packDir, scriptPath, errors, `handler.script "${entry.handler.script}"`);
97
+ if (!realScript)
97
98
  continue;
98
- const stat = fs.lstatSync(fs.realpathSync(scriptPath));
99
- if (!stat.isFile()) {
99
+ if (!fs.statSync(realScript).isFile()) {
100
100
  errors.push(`handler.script "${entry.handler.script}" is not a regular file`);
101
101
  }
102
102
  }
@@ -162,46 +162,3 @@ export function loadPacks(eventsDir) {
162
162
  }
163
163
  return { valid, invalid };
164
164
  }
165
- /** 读取 events/events-config.json;不存在返回缺省(enabled=false)。 */
166
- export function loadCenterConfig(eventsDir) {
167
- // 旧名 center.json 一次性迁移成 events-config.json(只搬运,不双读)。
168
- migrateLegacyFileName(eventsDir, 'center.json', EVENTS_CONFIG_JSON, 'events config');
169
- const filePath = path.join(eventsDir, EVENTS_CONFIG_JSON);
170
- let rawText;
171
- try {
172
- rawText = fs.readFileSync(filePath, 'utf8');
173
- }
174
- catch {
175
- return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: false, errors: [] };
176
- }
177
- let raw;
178
- try {
179
- raw = JSON.parse(rawText);
180
- }
181
- catch (error) {
182
- return {
183
- config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } },
184
- exists: true,
185
- errors: [`${EVENTS_CONFIG_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
186
- };
187
- }
188
- // 旧键名 `allowlist` 一次性迁移成 `rules`(它同时装 allow 与 deny,叫 allowlist 会误导)。
189
- // 只搬运、不双读:迁移后写回时只有 rules。authMode 的 'allowlist' 是协议取值,不动。
190
- if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
191
- const record = raw;
192
- if (!('rules' in record) && 'allowlist' in record) {
193
- record.rules = record.allowlist;
194
- delete record.allowlist;
195
- try {
196
- atomicWriteJson(filePath, record);
197
- logger.info(`[migration] ${EVENTS_CONFIG_JSON}: allowlist → rules`);
198
- }
199
- catch { /* 写回失败不影响本次读取 */ }
200
- }
201
- }
202
- const validated = validateCenterConfig(raw);
203
- if (!validated.ok) {
204
- return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: true, errors: validated.errors };
205
- }
206
- return { config: validated.value, exists: true, errors: [] };
207
- }
@@ -3,7 +3,7 @@
3
3
  * 事件名冲突 → 冲突各方全部 invalid(不静默覆盖)。
4
4
  */
5
5
  /** 从加载结果构建运行时状态。disabled 包不参与目录与冲突检测。 */
6
- export function buildPackState(packs, invalidPacks, previousRevision = 0) {
6
+ export function buildPackState(packs, invalidPacks) {
7
7
  const enabled = packs.filter(pack => pack.enabled);
8
8
  const disabledPacks = packs.filter(pack => !pack.enabled).map(pack => pack.id);
9
9
  const eventOwners = new Map();
@@ -56,7 +56,7 @@ export function buildPackState(packs, invalidPacks, previousRevision = 0) {
56
56
  invalidPacks: [...invalidPacks, ...conflictInvalid],
57
57
  catalog,
58
58
  conflicts,
59
- revision: previousRevision + 1,
59
+ revision: 1,
60
60
  };
61
61
  }
62
62
  /** catalog → SDK start/updateConfig 的 catalog 参数(字段名对照旧 bus-config-store.toSdkConfig)。 */
@@ -68,7 +68,9 @@ export function toSdkCatalog(catalog) {
68
68
  schema_version: entry.schemaVersion ?? 1,
69
69
  ...(entry.contentSchema !== undefined ? { content_schema: entry.contentSchema } : {}),
70
70
  default_ttl_seconds: entry.ttl,
71
- max_ttl_seconds: entry.maxTtl ?? Math.max(300, entry.ttl),
71
+ // 缺省同 ttl(types.ts 与 pack.schema.json 都这么写)。曾有个 300 秒地板,
72
+ // 那会让 `ttl: 30` 的包对外宣告「最长可存 300 秒」,与实际默认值不符。
73
+ max_ttl_seconds: entry.maxTtl ?? entry.ttl,
72
74
  };
73
75
  }
74
76
  return out;
@@ -2,20 +2,20 @@
2
2
  * per-aid 事件中心单元注册表:加载 → 解析 → 运行时,生命周期跟随 Trigger 调度器。
3
3
  * 包级失败隔离:坏包只废自己(pack.invalid),不影响其它包与 Bus。
4
4
  */
5
- import fs from 'node:fs';
6
5
  import path from 'node:path';
7
6
  import { logger } from '../utils/logger.js';
8
7
  import { agentEventsDir } from '../paths.js';
9
8
  import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
10
9
  import { BusResolveState, isBusPlaceholder, resolvePackBuses } from './bus-resolver.js';
11
- import { CenterConfigStore } from './center-config.js';
10
+ import { CenterConfigStore, loadCenterConfig } from './center-config.js';
12
11
  import { EventDispatcher } from './dispatcher.js';
13
12
  import { writeEventsIndex } from './index-generator.js';
14
- import { Ledger, centerLedger, packLedger } from './ledger.js';
13
+ import { Ledger, centerLedger, eventPackLedger as packLedger } from '../core/pack-ledger.js';
15
14
  import { buildPackState } from './pack-manager.js';
16
- import { EVENTS_CONFIG_JSON, loadCenterConfig, loadPacks, PACK_JSON } from './pack-loader.js';
15
+ import { loadPacks } from './pack-loader.js';
17
16
  import { EventRuntime } from './runtime.js';
18
- import { materializeAllowlist } from './admission-materializer.js';
17
+ import { explicitAllowlist, materializeAllowlist } from './admission-materializer.js';
18
+ import { PublicationLog } from './event-log.js';
19
19
  import { ScriptRunner } from './script-runner.js';
20
20
  import { errorMessage } from './types.js';
21
21
  import { readBusResolverContext } from './directory-source.js';
@@ -153,6 +153,7 @@ export class EventCenterRegistry {
153
153
  center: scanned.center,
154
154
  resolutions: scanned.resolutions,
155
155
  materializedAllowlist: scanned.materializedAllowlist,
156
+ materializeReason: scanned.materializeReason,
156
157
  contactsWatch: scanned.contactsWatch,
157
158
  });
158
159
  }
@@ -165,7 +166,9 @@ export class EventCenterRegistry {
165
166
  this.scanLedgerSigs.delete(aid);
166
167
  if (!unit)
167
168
  return;
168
- this.detachEventsWatcher(unit);
169
+ // 单元没了,`.index.md` 就是过期清单。manifest 侧因 `hasEventPacks` 变 false 而
170
+ // 不会注入,但文件留在盘上会让"磁盘有什么"与"实际有什么"对不上;空集写回等于删文件。
171
+ writeEventsIndex(unit.eventsDir, []);
169
172
  await Promise.allSettled([unit.runtime.close(), unit.dispatcher.close()]);
170
173
  }
171
174
  async closeAll() {
@@ -205,6 +208,14 @@ export class EventCenterRegistry {
205
208
  });
206
209
  }
207
210
  }
211
+ // `enabled: false` 是合法状态:包不加载、目录与日志保留。写一条台账,
212
+ // 否则"这个包为什么没生效"只能靠猜——`pack.disabled` 这个 action 一直没人写。
213
+ // disabledPacks 只有 id,没有 PackConfig,路径按 events/<id>/ledger.jsonl 拼。
214
+ for (const packId of state.disabledPacks) {
215
+ this.ledgerOnce(aid, `${packId}#disabled`, 'disabled', () => {
216
+ new Ledger(path.join(eventsDir, packId, 'ledger.jsonl')).append({ action: 'pack.disabled', result: 'ok', actor: ledgerActor });
217
+ });
218
+ }
208
219
  // ③ 占位符解析(strict 失败 → 该包退出运行;keep-last 沿用上次结果)。
209
220
  const context = readBusResolverContext(aid, agentDirPath);
210
221
  const resolveState = BusResolveState.forEventsDir(eventsDir);
@@ -255,14 +266,31 @@ export class EventCenterRegistry {
255
266
  // contacts 监听需求:包里有占位符引用(含被解析淘汰的包——它们在 enabledPacks 里)
256
267
  // 或上次解析有失败/degraded(等 contacts 到位后重解析)。
257
268
  const usesPlaceholderRefs = loaded.valid.some(pack => [...pack.publish, ...pack.subscribe].some(entry => isBusPlaceholder(entry.bus)));
269
+ if (materialized.degraded) {
270
+ logger.warn(`[EventCenter] ${aid} admission degraded; keeping the last deployed allowlist: ${materialized.reason ?? 'unknown'}`);
271
+ // 首次启动时退回 `events-config.json` 里显式声明的规则:那是人写下的、不依赖
272
+ // contacts 快照的唯一权威来源。再不行就让 SDK 侧保持空表——宁可收不到,也不放宽。
273
+ const fallback = explicitAllowlist(centerResult.config);
274
+ return {
275
+ agentDirPath,
276
+ eventsDir,
277
+ state: runtimeState,
278
+ resolutions,
279
+ center: centerResult.config,
280
+ ...(Object.keys(fallback).length > 0
281
+ ? { materializedAllowlist: fallback }
282
+ : { materializeReason: materialized.reason ?? 'contacts snapshot unavailable' }),
283
+ contactsWatch: usesPlaceholderRefs || wantsResolveRefresh,
284
+ resolverSignature: resolverSignatureOf(context),
285
+ };
286
+ }
258
287
  return {
259
288
  agentDirPath,
260
289
  eventsDir,
261
290
  state: runtimeState,
262
291
  resolutions,
263
292
  center: centerResult.config,
264
- // 首次启动没有"上一份 allowlist",物化失败必须 fail-closed 等下次重物化。
265
- materializedAllowlist: materialized.degraded ? {} : materialized.allowlist,
293
+ materializedAllowlist: materialized.allowlist,
266
294
  contactsWatch: usesPlaceholderRefs || wantsResolveRefresh,
267
295
  resolverSignature: resolverSignatureOf(context),
268
296
  };
@@ -282,6 +310,8 @@ export class EventCenterRegistry {
282
310
  const existingUnit = this.units.get(aid);
283
311
  if (existingUnit) {
284
312
  this.units.delete(aid);
313
+ // 必须摘掉旧的目录监听与去抖定时器(`remove()` 里有这一步,这里先前漏了)。
314
+ // 否则每次调度器重启都会多留一个 `fs.watch` 句柄,Windows 上很快耗尽。
285
315
  await Promise.allSettled([existingUnit.runtime.close(), existingUnit.dispatcher.close()]);
286
316
  }
287
317
  this.cleanupLegacySubscriptionTriggers(aid);
@@ -320,6 +350,15 @@ export class EventCenterRegistry {
320
350
  ...(entry.event ? { event: entry.event } : {}), ...(entry.action ? { direction: entry.action } : {}),
321
351
  reason: entry.reason, code: 'FORBIDDEN',
322
352
  }),
353
+ // 读 unit 上的实时 state:reload 会原地替换包集合,闭包不能捕获初值。
354
+ onPublished: publication => {
355
+ const live = this.units.get(aid);
356
+ const pack = (live?.state ?? runtimeState).enabledPacks.find(candidate => candidate.id === publication.packId);
357
+ if (!pack)
358
+ return;
359
+ const { packId: _packId, ...record } = publication;
360
+ PublicationLog.forPack(pack).append(record);
361
+ },
323
362
  onGateStatus: installed => centerLedger(eventsDir).append({
324
363
  action: installed ? 'gate.installed' : 'gate.degraded', result: installed ? 'ok' : 'failed', actor: 'daemon',
325
364
  ...(installed ? {} : { reason: 'sdk_request_handler_unavailable' }),
@@ -366,12 +405,12 @@ export class EventCenterRegistry {
366
405
  resolverSignature: scanned.resolverSignature,
367
406
  };
368
407
  this.units.set(aid, unit);
369
- this.attachEventsWatcher(unit);
370
408
  await runtime.start({
371
409
  state: runtimeState,
372
410
  center: centerConfig,
373
411
  resolutions,
374
412
  materializedAllowlist: scanned.materializedAllowlist,
413
+ materializeReason: scanned.materializeReason,
375
414
  contactsWatch: scanned.contactsWatch,
376
415
  });
377
416
  }
@@ -396,49 +435,6 @@ export class EventCenterRegistry {
396
435
  logger.warn(`[EventCenter] ${aid} contacts-triggered reload failed: ${errorMessage(error)}`);
397
436
  });
398
437
  }
399
- // ── M3:events/ 目录监听(改 pack.json/center.json 自动 reload)────────
400
- // 原生 recursive fs.watch(win32 单句柄;chokidar 在 Windows 有句柄爆炸教训)。
401
- // 只认包清单与 center.json:.index.md 在监听目录内(reload 自己写,会自触发),
402
- // ledger/logs/scripts 是运行产物,全排除。error 即降级拆除,回到手动 reload。
403
- attachEventsWatcher(unit) {
404
- if (unit.eventsWatcher || this.options.watchEvents === false)
405
- return;
406
- // 旧名文件(center.json / 关注的事件.json)首次加载时就地迁移成规范名,磁盘上不再出现,无需监听。
407
- const watched = new Set([PACK_JSON, EVENTS_CONFIG_JSON]);
408
- try {
409
- const watcher = fs.watch(unit.eventsDir, { recursive: true }, (_kind, filename) => {
410
- const base = filename ? path.basename(filename.toString()) : '';
411
- if (!watched.has(base))
412
- return;
413
- if (unit.eventsReloadTimer)
414
- clearTimeout(unit.eventsReloadTimer);
415
- unit.eventsReloadTimer = setTimeout(() => {
416
- unit.eventsReloadTimer = undefined;
417
- this.reload(unit.aid).catch(error => {
418
- logger.warn(`[EventCenter] ${unit.aid} watcher reload failed: ${errorMessage(error)}`);
419
- });
420
- }, 2_000);
421
- unit.eventsReloadTimer.unref?.();
422
- });
423
- watcher.on('error', () => this.detachEventsWatcher(unit));
424
- unit.eventsWatcher = watcher;
425
- }
426
- catch {
427
- // 目录缺失或平台不支持 recursive:不监听即可,手动 reload 仍可用。
428
- }
429
- }
430
- detachEventsWatcher(unit) {
431
- if (unit.eventsReloadTimer)
432
- clearTimeout(unit.eventsReloadTimer);
433
- unit.eventsReloadTimer = undefined;
434
- try {
435
- unit.eventsWatcher?.close();
436
- }
437
- catch {
438
- // 已失效。
439
- }
440
- unit.eventsWatcher = undefined;
441
- }
442
438
  /** 一次性清理旧事件总线遗留的订阅 Trigger(事件源 bus:event 已无人发布,纯残留)。 */
443
439
  cleanupLegacySubscriptionTriggers(aid) {
444
440
  const scheduler = this.options.getScheduler?.(aid);