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
@@ -7,7 +7,7 @@ import { RUNTIME_HOME_ENV, WEB_PACKAGE_NAME } from '../../product.js';
7
7
  import { resolveGlobalPkgAsync } from '../../utils/npm-ops.js';
8
8
  import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './launch.js';
9
9
  import * as platform from '../../utils/cross-platform.js';
10
- import { getProcessStartTimeAsync } from '../../utils/process-introspect.js';
10
+ import { getProcessStartTimeAsync, startTimeMatches } from '../../utils/process-introspect.js';
11
11
  import { matchesEcwebInstanceHealth, parseEcwebInstanceRecord } from '../../contracts/ecweb-instance.js';
12
12
  import { sanitizeMenuLogValue } from '../../core/command/menu-protocol.js';
13
13
  import { stopEcwebProcess } from './lifecycle.js';
@@ -107,8 +107,10 @@ async function probe(record, timeoutMs) {
107
107
  const response = await fetch(`http://127.0.0.1:${record.port}/api/health`, {
108
108
  signal,
109
109
  });
110
- if (!response.ok)
110
+ if (!response.ok) {
111
+ await response.body?.cancel().catch(() => { });
111
112
  return { healthy: false, reason: `HTTP ${response.status}` };
113
+ }
112
114
  return matchesEcwebInstanceHealth(await response.json(), record)
113
115
  ? { healthy: true }
114
116
  : { healthy: false, reason: '健康响应或实例身份不匹配' };
@@ -170,25 +172,41 @@ export function createEcwebSupervisor(options) {
170
172
  }
171
173
  };
172
174
  const setActiveFromEntry = async (entry, owned) => {
175
+ // Recheck after the HTTP response and asynchronous identity lookup. Child
176
+ // exit events can invalidate even a liveness query that returned true.
177
+ const actual = await getProcessStartTimeAsync(entry.record.pid);
178
+ const running = await isAlive(entry.record);
179
+ if (!running || (entry.observedChild && child !== entry.observedChild)) {
180
+ lastHealthFailure = '实例进程在健康检查期间退出';
181
+ return false;
182
+ }
183
+ if (actual !== null && entry.observedStartedAt != null && !startTimeMatches(entry.observedStartedAt, actual)) {
184
+ lastHealthFailure = '实例 PID 在健康检查期间被复用';
185
+ return false;
186
+ }
187
+ if (!stopping && entry.record.port !== desiredPort)
188
+ return false;
173
189
  active = {
174
190
  pid: entry.record.pid,
175
191
  port: entry.record.port,
176
192
  // Capture the current PID start time rather than trusting the record.
177
193
  // Older ECWeb builds could write a clock-skewed `startedAt` value.
178
- startedAt: await getProcessStartTimeAsync(entry.record.pid)
179
- ?? (typeof entry.record.startedAt === 'number' ? entry.record.startedAt : null),
194
+ startedAt: actual ?? (typeof entry.record.startedAt === 'number' ? entry.record.startedAt : null),
180
195
  owned,
181
196
  };
197
+ return true;
182
198
  };
183
199
  const findHealthyInstance = async () => {
184
200
  lastHealthFailure = '未发现有效的 ECWeb 实例注册';
185
201
  for (const entry of readEntries()) {
202
+ entry.observedChild = child?.pid === entry.record.pid ? child : undefined;
186
203
  if (!await isAlive(entry.record)) {
187
204
  lastHealthFailure = '实例进程不存在';
188
205
  removeEntry(entry);
189
206
  continue;
190
207
  }
191
208
  const actual = await getProcessStartTimeAsync(entry.record.pid);
209
+ entry.observedStartedAt = actual;
192
210
  if (actual !== null && entry.record.startedAt !== undefined
193
211
  && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
194
212
  lastHealthFailure = '实例 PID 启动时间不匹配';
@@ -228,50 +246,50 @@ export function createEcwebSupervisor(options) {
228
246
  logFd = null;
229
247
  };
230
248
  const stopTrackedProcess = (identity, onTiming) => {
231
- const target = child?.pid === identity.pid ? child : null;
232
- const requestShutdown = target?.connected ? () => {
233
- try {
234
- if (!target.connected)
235
- return false;
236
- // The callback handles an asynchronously closed channel without an
237
- // unhandled child 'error' event. Exit confirmation remains separate.
238
- target.send({ type: 'ecweb.shutdown' }, () => { });
239
- return true;
240
- }
241
- catch {
242
- return false;
243
- }
244
- } : undefined;
245
- return stopEcwebProcess(identity, undefined, onTiming, requestShutdown);
249
+ const target = child?.pid === identity.pid ? child : undefined;
250
+ return stopEcwebProcess(identity, undefined, onTiming, target);
246
251
  };
247
252
  const killActive = async (onTiming) => {
248
253
  intentionalStop = true;
249
254
  const current = active;
255
+ const retiringChild = child && (!current || child.pid === current.pid) ? child : null;
250
256
  // Keep stop intent with the child: its exit event may arrive after a
251
257
  // replacement has reset the supervisor's intentionalStop flag.
252
- if (child && (!current || child.pid === current.pid))
253
- expectedChildExits.add(child);
254
- if (!current) {
255
- // During the short window between spawn() and ECWeb writing its
256
- // instance record there is no `active` entry yet, but the daemon still
257
- // owns the child and must not leave it behind on shutdown.
258
- const pendingPid = child?.pid;
259
- if (pendingPid && (await platform.isProcessRunningAsync(pendingPid))) {
260
- await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
258
+ if (retiringChild)
259
+ expectedChildExits.add(retiringChild);
260
+ try {
261
+ if (!current) {
262
+ // During the short window between spawn() and ECWeb writing its
263
+ // instance record there is no `active` entry yet, but the daemon still
264
+ // owns the child and must not leave it behind on shutdown.
265
+ const pendingPid = child?.pid;
266
+ if (pendingPid && (await platform.isProcessRunningAsync(pendingPid))) {
267
+ await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
268
+ }
269
+ child = null;
270
+ childIdentityStartedAt = null;
271
+ healthy = false;
272
+ checkedAt = undefined;
273
+ return;
261
274
  }
275
+ await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
276
+ removeEntriesForPid(current.pid);
277
+ active = null;
262
278
  child = null;
263
279
  childIdentityStartedAt = null;
264
280
  healthy = false;
265
281
  checkedAt = undefined;
266
- return;
267
282
  }
268
- await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
269
- removeEntriesForPid(current.pid);
270
- active = null;
271
- child = null;
272
- childIdentityStartedAt = null;
273
- healthy = false;
274
- checkedAt = undefined;
283
+ catch (error) {
284
+ // A failed replacement must not suppress a later real crash forever.
285
+ // Global shutdown and disabled services still retain their stop intent.
286
+ if (!stopping && desiredEnabled && runtimeMode === 'managed') {
287
+ intentionalStop = false;
288
+ if (retiringChild)
289
+ expectedChildExits.delete(retiringChild);
290
+ }
291
+ throw error;
292
+ }
275
293
  };
276
294
  const spawnEcweb = async () => {
277
295
  if (stopping || !desiredEnabled || runtimeMode !== 'managed')
@@ -422,15 +440,16 @@ export function createEcwebSupervisor(options) {
422
440
  }
423
441
  if (!desiredEnabled || runtimeMode !== 'managed')
424
442
  return;
425
- healthy = instance !== null;
443
+ const previousActive = active;
444
+ const adopted = instance !== null && await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
445
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
446
+ return;
447
+ healthy = adopted;
426
448
  checkedAt = Date.now();
427
- if (instance) {
449
+ if (instance && adopted) {
428
450
  launchRequested = false;
429
451
  cancelRecovery();
430
- const changed = !active || active.pid !== instance.record.pid || active.port !== instance.record.port;
431
- await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
432
- if (stopping || !desiredEnabled || runtimeMode !== 'managed')
433
- return;
452
+ const changed = !previousActive || previousActive.pid !== instance.record.pid || previousActive.port !== instance.record.port;
434
453
  failureCount = 0;
435
454
  hasBeenReady = true;
436
455
  settleInitialHealth?.('ok');
@@ -475,6 +494,10 @@ export function createEcwebSupervisor(options) {
475
494
  if (recoveryTimer)
476
495
  clearTimeout(recoveryTimer);
477
496
  recoveryTimer = null;
497
+ // The timer may already be waiting for an in-flight health probe. Cancel
498
+ // that request too, while preserving explicitly requested restarts.
499
+ if (launchRequested === 'recovery')
500
+ launchRequested = false;
478
501
  };
479
502
  const scheduleRecovery = () => {
480
503
  if (!healthy && desiredEnabled && !stopping)
@@ -515,6 +538,8 @@ export function createEcwebSupervisor(options) {
515
538
  await startInFlight.catch(() => { });
516
539
  if (stopping)
517
540
  return;
541
+ // A health probe joined above may have scheduled another recovery.
542
+ cancelRecovery();
518
543
  await killActive();
519
544
  if (stopping)
520
545
  return;
@@ -525,7 +550,7 @@ export function createEcwebSupervisor(options) {
525
550
  return restartInFlight;
526
551
  };
527
552
  const scheduleCheck = () => {
528
- if (stopping)
553
+ if (stopping || timer)
529
554
  return;
530
555
  const interval = active || hasBeenReady ? SERVICE_HEALTH_INTERVALS.http.running : SERVICE_HEALTH_INTERVALS.http.startup;
531
556
  timer = setTimeout(() => {
@@ -541,7 +566,6 @@ export function createEcwebSupervisor(options) {
541
566
  return;
542
567
  if (!desiredEnabled || runtimeMode !== 'managed') {
543
568
  settleInitialHealth?.('skipped');
544
- scheduleCheck();
545
569
  return;
546
570
  }
547
571
  // Give an independently started ECWeb time to publish its instance record.
@@ -552,11 +576,12 @@ export function createEcwebSupervisor(options) {
552
576
  await setActiveFromEntry(existing, false);
553
577
  return;
554
578
  }
555
- if (existing) {
579
+ if (existing && await setActiveFromEntry(existing, false)) {
580
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
581
+ return;
556
582
  healthy = true;
557
583
  checkedAt = Date.now();
558
584
  hasBeenReady = true;
559
- await setActiveFromEntry(existing, false);
560
585
  options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
561
586
  settleInitialHealth?.('ok');
562
587
  }
@@ -566,9 +591,6 @@ export function createEcwebSupervisor(options) {
566
591
  launchRequested = 'manual';
567
592
  await check();
568
593
  }
569
- if (stopping)
570
- return;
571
- scheduleCheck();
572
594
  };
573
595
  const configure = async (config) => {
574
596
  if (stopping)
@@ -598,6 +620,7 @@ export function createEcwebSupervisor(options) {
598
620
  await restartInFlight.catch(() => { });
599
621
  if (stopping)
600
622
  return;
623
+ cancelRecovery();
601
624
  if (runtimeMode === 'external') {
602
625
  child?.removeAllListeners();
603
626
  child = null;
@@ -625,11 +648,17 @@ export function createEcwebSupervisor(options) {
625
648
  };
626
649
  return {
627
650
  start() {
651
+ // A failed initial inspection must not disable supervision permanently.
628
652
  if (!startup)
629
653
  startup = start().catch(error => {
654
+ healthy = false;
655
+ checkedAt = Date.now();
656
+ failureCount = failureThreshold;
657
+ lastHealthFailure = error instanceof Error ? error.message : String(error);
630
658
  settleInitialHealth?.('failed');
659
+ scheduleRecovery();
631
660
  throw error;
632
- });
661
+ }).finally(scheduleCheck);
633
662
  return startup;
634
663
  },
635
664
  configure(config) {
@@ -112,7 +112,7 @@ export function materializeAllowlist(config, agentDir, selfAid, registeredEvents
112
112
  }
113
113
  return { allowlist, degraded: false, admittedAids: [...base] };
114
114
  }
115
- function explicitAllowlist(config) {
115
+ export function explicitAllowlist(config) {
116
116
  const result = {};
117
117
  for (const [event, entry] of Object.entries(config.rules)) {
118
118
  result[event] = {
@@ -1,3 +1,4 @@
1
+ import { getSdkBusBinding } from './types.js';
1
2
  const facadeGates = new WeakMap();
2
3
  const coreGates = new WeakMap();
3
4
  /** Wrap the SDK's remote request handler when its runtime service map is available. */
@@ -17,12 +18,12 @@ export function installEventBusRequestGate(facadeValue, busAid, gate) {
17
18
  const aid = typeof args[0] === 'string' ? args[0] : '';
18
19
  const nextGate = state.gates.get(aid);
19
20
  if (aid && nextGate)
20
- installCoreGate(this.buses?.get(aid)?.service, nextGate);
21
+ installCoreGate(getSdkBusBinding(this, aid)?.service, nextGate);
21
22
  return started;
22
23
  };
23
24
  }
24
25
  state.gates.set(busAid, gate);
25
- return installCoreGate(facade.buses.get(busAid)?.service, gate);
26
+ return installCoreGate(getSdkBusBinding(facade, busAid)?.service, gate);
26
27
  }
27
28
  function installCoreGate(service, gate) {
28
29
  if (!service || typeof service.handle !== 'function')
@@ -36,11 +37,54 @@ function installCoreGate(service, gate) {
36
37
  const state = { originalHandle, gate };
37
38
  coreGates.set(service, state);
38
39
  service.handle = async function (senderAid, request, ...rest) {
39
- await state.gate(senderAid, request, this);
40
- return state.originalHandle.call(this, senderAid, request, ...rest);
40
+ const after = await state.gate(senderAid, request, this);
41
+ const result = await state.originalHandle.call(this, senderAid, request, ...rest);
42
+ if (typeof after === 'function') {
43
+ try {
44
+ after(result);
45
+ }
46
+ catch {
47
+ // 记录回调失败不能影响 SDK 请求结果。
48
+ }
49
+ }
50
+ return result;
41
51
  };
42
52
  return true;
43
53
  }
54
+ /**
55
+ * 发布请求被受理时,当前对该事件有效订阅的 Agent 数(按 AID 去重)。
56
+ * SDK 不公开逐次投递明细,这是 Bus 宿主在 publish 之前能拿到的最准快照。
57
+ * 读不到 SDK 内部结构时返回 null,不伪造数字。
58
+ */
59
+ export function countActiveSubscribers(service, event) {
60
+ const core = service;
61
+ const subscriptions = core?.subscriptions;
62
+ const leases = core?.leases;
63
+ if (!(subscriptions instanceof Map) || !(leases instanceof Map))
64
+ return null;
65
+ const now = Date.now();
66
+ const aids = new Set();
67
+ for (const sub of subscriptions.values()) {
68
+ if (!sub || sub.event !== event)
69
+ continue;
70
+ const lease = sub.leaseId ? leases.get(sub.leaseId) : undefined;
71
+ if (!lease)
72
+ continue;
73
+ if (typeof lease.expires_at === 'number' && lease.expires_at <= now)
74
+ continue;
75
+ if (lease.auth_mode === 'credential'
76
+ && typeof lease.authorization_until === 'number' && lease.authorization_until <= now)
77
+ continue;
78
+ const scopeOk = !Array.isArray(lease.scope)
79
+ || lease.scope.some(item => item.event_name === event && item.action === 'subscribe');
80
+ if (!scopeOk)
81
+ continue;
82
+ const aid = lease.aid ?? sub.aid;
83
+ if (typeof aid === 'string' && aid)
84
+ aids.add(aid);
85
+ }
86
+ return aids.size;
87
+ }
44
88
  export function evaluateEventBusRequest(senderAid, request, materialized, service) {
45
89
  const operation = typeof request.op === 'string' ? request.op : 'unknown';
46
90
  const deny = (reason, event, action) => ({
@@ -8,7 +8,7 @@
8
8
  * - SDK 失租后 binding 自行关闭且门面不感知,用定时探测兜底。
9
9
  */
10
10
  import { logger } from '../utils/logger.js';
11
- import { EventCenterError, errorCode, errorMessage, } from './types.js';
11
+ import { EventCenterError, errorCode, errorMessage, getSdkBusBinding, } from './types.js';
12
12
  import { installEventBusRequestGate } from './bus-gate.js';
13
13
  function withTimeout(promise, ms, code) {
14
14
  let timer;
@@ -128,7 +128,7 @@ export class BusHost {
128
128
  if (this.statusValue !== 'running' || !this.handle)
129
129
  return { available: false, subscribers: [], reason: 'bus_not_running' };
130
130
  const facade = this.handle.EventService;
131
- const service = facade.buses?.get?.(this.options.aid)?.service;
131
+ const service = getSdkBusBinding(facade, this.options.aid)?.service;
132
132
  if (!service?.subscriptions)
133
133
  return { available: false, subscribers: [], reason: 'sdk_subscriber_details_unavailable' };
134
134
  try {
@@ -242,7 +242,7 @@ export class BusHost {
242
242
  /** binding 是否仍持有实例租约。优先读 SDK 内部状态,读不到时用 stats 探测。 */
243
243
  async leaseAlive() {
244
244
  const service = this.handle?.EventService;
245
- const running = service?.buses?.get?.(this.options.aid)?.binding?.running;
245
+ const running = getSdkBusBinding(service, this.options.aid)?.binding?.running;
246
246
  if (typeof running === 'boolean')
247
247
  return running;
248
248
  try {
@@ -4,10 +4,61 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { atomicWriteJson } from '../utils/atomic-write.js';
7
- import { centerLedger } from './ledger.js';
8
- import { EVENTS_CONFIG_JSON } from './pack-loader.js';
7
+ import { centerLedger } from '../core/pack-ledger.js';
8
+ import { migrateLegacyFileName } from '../core/legacy-rename.js';
9
+ import { logger } from '../utils/logger.js';
9
10
  import { EventCenterError } from './types.js';
10
11
  import { AID_PATTERN, validateCenterConfig } from './validation.js';
12
+ export const EVENTS_CONFIG_JSON = 'events-config.json';
13
+ function defaultCenterConfig() {
14
+ return {
15
+ enabled: false, authMode: 'allowlist',
16
+ admission: { coupling: 'on', rematerializeMs: 300_000 },
17
+ rules: {}, rateLimit: { perMinute: 60, perHour: 600 },
18
+ };
19
+ }
20
+ function readCenterConfig(filePath, migrateLegacyRules) {
21
+ let rawText;
22
+ try {
23
+ rawText = fs.readFileSync(filePath, 'utf8');
24
+ }
25
+ catch {
26
+ return { config: defaultCenterConfig(), exists: false, errors: [] };
27
+ }
28
+ let raw;
29
+ try {
30
+ raw = JSON.parse(rawText);
31
+ }
32
+ catch (error) {
33
+ return {
34
+ config: defaultCenterConfig(), exists: true,
35
+ errors: [`${EVENTS_CONFIG_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
36
+ };
37
+ }
38
+ // 仅运行时加载迁移旧键;普通读取与写入前核验均不改磁盘。
39
+ if (migrateLegacyRules && raw && typeof raw === 'object' && !Array.isArray(raw)) {
40
+ const record = raw;
41
+ if (!('rules' in record) && 'allowlist' in record) {
42
+ record.rules = record.allowlist;
43
+ delete record.allowlist;
44
+ try {
45
+ atomicWriteJson(filePath, record);
46
+ logger.info(`[migration] ${EVENTS_CONFIG_JSON}: allowlist → rules`);
47
+ }
48
+ catch { /* 写回失败不影响本次读取 */ }
49
+ }
50
+ }
51
+ const validated = validateCenterConfig(raw);
52
+ if (!validated.ok) {
53
+ return { config: defaultCenterConfig(), exists: true, errors: validated.errors };
54
+ }
55
+ return { config: validated.value, exists: true, errors: [] };
56
+ }
57
+ /** 运行时加载:迁移旧名/旧字段后读取,缺省不启动 Bus。 */
58
+ export function loadCenterConfig(eventsDir) {
59
+ migrateLegacyFileName(eventsDir, 'center.json', EVENTS_CONFIG_JSON, 'events config');
60
+ return readCenterConfig(path.join(eventsDir, EVENTS_CONFIG_JSON), true);
61
+ }
11
62
  export class CenterConfigStore {
12
63
  filePath;
13
64
  ledger;
@@ -35,29 +86,7 @@ export class CenterConfigStore {
35
86
  }
36
87
  /** 读取并校验;校验失败返回缺省并带 errors(Bus 不启动,不覆盖磁盘)。 */
37
88
  read() {
38
- let rawText;
39
- try {
40
- rawText = fs.readFileSync(this.filePath, 'utf8');
41
- }
42
- catch {
43
- return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: false, errors: [] };
44
- }
45
- let raw;
46
- try {
47
- raw = JSON.parse(rawText);
48
- }
49
- catch (error) {
50
- return {
51
- config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } },
52
- exists: true,
53
- errors: [`${EVENTS_CONFIG_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
54
- };
55
- }
56
- const validated = validateCenterConfig(raw);
57
- if (!validated.ok) {
58
- return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, rules: {}, rateLimit: { perMinute: 60, perHour: 600 } }, exists: true, errors: validated.errors };
59
- }
60
- return { config: validated.value, exists: true, errors: [] };
89
+ return readCenterConfig(this.filePath, false);
61
90
  }
62
91
  write(config) {
63
92
  fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
@@ -118,9 +147,9 @@ export class CenterConfigStore {
118
147
  ...(added.length ? { added } : {}),
119
148
  ...(removed.length ? { removed } : {}),
120
149
  ...(input.rule ? { rule: input.rule } : {}),
121
- // 目前唯一的写入口是 CLI 与菜单,没有脚本侧通道;`by`/actor=script 曾是死代码。
122
- // 等真出现脚本改规则的需求时再引入,避免文档承诺一个不存在的分支。
123
- actor: 'menu',
150
+ // 目前只有 CLI 与菜单两个写入口,没有脚本侧通道;等真出现脚本改规则的需求时
151
+ // 再引入 script 分支,避免文档承诺一个不存在的取值。
152
+ actor: input.actor ?? 'menu',
124
153
  });
125
154
  return { config, changed: entry, added, removed };
126
155
  }
@@ -5,6 +5,7 @@
5
5
  import { logger } from '../utils/logger.js';
6
6
  import { matchTriggerEvent } from '../trigger/event-source.js';
7
7
  import { EventLog } from './event-log.js';
8
+ import { eventPackLedger as packLedger } from '../core/pack-ledger.js';
8
9
  export const DEFAULT_DISPATCHER_LIMITS = { maxConcurrency: 5, queueSize: 100 };
9
10
  /**
10
11
  * 包内一条 subscribe 条目实际指向的 bus AID。
@@ -123,6 +124,13 @@ export class EventDispatcher {
123
124
  // 无沙箱执行必须留痕:事后排查「这个脚本为什么能读到不该读的东西」靠它。
124
125
  ...(outcome.sandboxAbsent ? { sandboxAbsent: outcome.sandboxAbsent } : {}),
125
126
  });
127
+ if (outcome.sandboxAbsent) {
128
+ // 日志按天轮转、只留近期;台账才是长期答案。
129
+ packLedger(item.pack).append({
130
+ action: 'script.unsandboxed', event: item.event.eventName,
131
+ reason: outcome.sandboxAbsent,
132
+ });
133
+ }
126
134
  if (outcome.outcome === 'error' || outcome.outcome === 'timeout') {
127
135
  logger.warn(`[EventCenter] ${item.pack.id} handler for ${item.event.eventName} ${outcome.outcome}: ${outcome.error?.code ?? ''} ${outcome.error?.message ?? ''}`);
128
136
  }
@@ -1,6 +1,7 @@
1
1
  /**
2
- * 事件日志(logs/events-YYYYMMDD.jsonl):写前日志,先 received 再执行脚本,结束补 handled。
3
- * 行结构按 docs/event-center/schema/event-log.schema.json(additionalProperties: false)。
2
+ * 事件处理日志(events-YYYYMMDD.jsonl)和发布日志(publications-YYYYMMDD.jsonl)。
3
+ * 处理日志先 received 再执行脚本,结束补 handled;发布日志记录发布方和订阅数量。
4
+ * 行结构分别按 docs/event-center/schema/{event-log,publication-log}.schema.json。
4
5
  * P0 恒落 data 原文(dataHash 逻辑留接口)。
5
6
  */
6
7
  import fs from 'node:fs';
@@ -67,44 +68,85 @@ export class EventLog {
67
68
  }
68
69
  /** 按天分文件(本地日期);IO 失败吞掉。 */
69
70
  write(line) {
70
- const now = new Date();
71
- const date = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
72
- try {
73
- fs.mkdirSync(this.logsDir, { recursive: true });
74
- fs.appendFileSync(path.join(this.logsDir, `events-${date}.jsonl`), `${JSON.stringify(line)}\n`, 'utf8');
75
- }
76
- catch {
77
- // 日志写失败不中断事件处理。
78
- }
71
+ appendDailyRecord(this.logsDir, 'events', line);
79
72
  }
80
73
  /** 读某包最近的事件日志行(CLI tail 用)。 */
81
74
  tail(count) {
82
- let files;
83
- try {
84
- files = fs.readdirSync(this.logsDir).filter(name => /^events-\d{8}\.jsonl$/.test(name)).sort();
85
- }
86
- catch {
87
- return [];
88
- }
89
- const lines = [];
90
- for (const file of [...files].reverse()) {
75
+ const lines = readDailyRecordLines(this.logsDir, /^events-\d{8}\.jsonl$/, count);
76
+ return lines.slice(-count).map(line => {
91
77
  try {
92
- const text = fs.readFileSync(path.join(this.logsDir, file), 'utf8');
93
- lines.unshift(...text.split('\n').filter(Boolean));
78
+ return JSON.parse(line);
94
79
  }
95
80
  catch {
96
- break;
81
+ return { ts: 0, kind: 'dropped', reason: 'unparseable log line' };
97
82
  }
98
- if (lines.length >= count)
99
- break;
100
- }
83
+ });
84
+ }
85
+ }
86
+ export class PublicationLog {
87
+ logsDir;
88
+ constructor(logsDir) {
89
+ this.logsDir = logsDir;
90
+ }
91
+ static forPack(pack) {
92
+ return new PublicationLog(pack.paths.logsDir);
93
+ }
94
+ /** 追加一行;IO 失败吞掉,记录失败不影响事件投递。 */
95
+ append(record) {
96
+ const { ts, ...rest } = record;
97
+ const line = { ts: ts ?? Date.now(), ...rest };
98
+ appendDailyRecord(this.logsDir, 'publications', line);
99
+ }
100
+ /** 读某包最近的发布记录(menu timeline / CLI 用)。 */
101
+ tail(count) {
102
+ const lines = readDailyRecordLines(this.logsDir, /^publications-\d{8}\.jsonl$/, count);
101
103
  return lines.slice(-count).map(line => {
102
104
  try {
103
105
  return JSON.parse(line);
104
106
  }
105
107
  catch {
106
- return { ts: 0, kind: 'dropped', reason: 'unparseable log line' };
108
+ return { ts: 0, event: '', bus: '', publisher: '', subscribers: null, source: 'remote' };
107
109
  }
108
110
  });
109
111
  }
110
112
  }
113
+ /** 两种记录按本地日期分文件;日志写入失败不影响事件投递。 */
114
+ function appendDailyRecord(logsDir, stream, record) {
115
+ const now = new Date();
116
+ const date = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
117
+ try {
118
+ fs.mkdirSync(logsDir, { recursive: true });
119
+ fs.appendFileSync(path.join(logsDir, `${stream}-${date}.jsonl`), `${JSON.stringify(record)}\n`, 'utf8');
120
+ }
121
+ catch { }
122
+ }
123
+ function readDailyRecordLines(logsDir, pattern, count) {
124
+ let files;
125
+ try {
126
+ files = fs.readdirSync(logsDir).filter(name => pattern.test(name)).sort();
127
+ }
128
+ catch {
129
+ return [];
130
+ }
131
+ const lines = [];
132
+ for (const file of [...files].reverse()) {
133
+ try {
134
+ // 只要该文件末尾能凑够 count 的那几条;不整个 chunk 展开进 unshift——
135
+ // `unshift(...chunk)` 是函数调用,单文件超过 V8 参数上限(约 12 万)会
136
+ // 抛 RangeError,被下面 catch 吞掉后静默返回半截结果。逐行 unshift 又
137
+ // 会把搬动代价放大到 O(chunk × 已有长度),热包一天十几万行时够慢。
138
+ const text = fs.readFileSync(path.join(logsDir, file), 'utf8');
139
+ const all = text.split('\n').filter(Boolean);
140
+ const need = Math.min(all.length, count - lines.length);
141
+ if (need <= 0)
142
+ break;
143
+ lines.unshift(...all.slice(all.length - need));
144
+ }
145
+ catch {
146
+ break;
147
+ }
148
+ if (lines.length >= count)
149
+ break;
150
+ }
151
+ return lines;
152
+ }
@@ -50,7 +50,12 @@ export function writeEventsIndex(eventsDir, enabledPacks, resolutions) {
50
50
  }
51
51
  }
52
52
  lines.push('');
53
- lines.push('本机管理: ec events status / ledger / tail / reload');
53
+ // 分档写出:各档权限不同,混成一行会让模型以为 pack add 和 status 一样随手可调,
54
+ // 试一次被拒才发现(详见 $KITS_DOCS/evolcore/event-center.md)。
55
+ lines.push('本机管理:');
56
+ lines.push(' 只读(member 及以上): status / ledger / tail / doctor / reload / rules show / pack list');
57
+ lines.push(' owner|admin: rules add|remove, pack add|remove|enable|disable');
58
+ lines.push(' 发布: publish(只能发本包已声明的事件,接收方准入另行判定)');
54
59
  lines.push('');
55
60
  try {
56
61
  fs.mkdirSync(eventsDir, { recursive: true });