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
@@ -3,15 +3,17 @@ import path from 'node:path';
3
3
  import { createServer } from 'node:net';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { parseEcwebInstanceRecord, matchesEcwebInstanceHealth } from '../../contracts/ecweb-instance.js';
6
- import { getProcessSnapshot, getProcessStartTime, startTimeMatches } from '../../utils/process-introspect.js';
6
+ import { getProcessSnapshot, getProcessStartTime, getProcessStartTimeAsync, startTimeMatches } from '../../utils/process-introspect.js';
7
7
  import * as platform from '../../utils/cross-platform.js';
8
8
  import { resolveGlobalPkg } from '../../utils/npm-ops.js';
9
9
  import { resolveEcwebLaunchCommand } from './launch.js';
10
10
  import { WEB_PACKAGE_NAME } from '../../product.js';
11
- function sameProcess(identity) {
11
+ async function sameProcess(identity) {
12
+ if (!platform.isProcessRunning(identity.pid))
13
+ return false;
14
+ const actual = await getProcessStartTimeAsync(identity.pid);
12
15
  if (!platform.isProcessRunning(identity.pid))
13
16
  return false;
14
- const actual = getProcessStartTime(identity.pid);
15
17
  if (identity.startedAt === null || actual === null) {
16
18
  throw new Error(`Cannot verify ECWeb process identity (PID: ${identity.pid}); refusing to terminate it`);
17
19
  }
@@ -21,6 +23,8 @@ function sameProcess(identity) {
21
23
  * Prefer a cooperative IPC request for supervised children on every platform.
22
24
  * Windows taskkill without /F cannot invoke Node's SIGTERM handler; only
23
25
  * POSIX can use SIGTERM when no parent-child IPC channel is available.
26
+ * The cooperative callback must use the captured ChildProcess IPC channel,
27
+ * never a PID-addressed transport. That handle cannot address a reused PID.
24
28
  */
25
29
  const IPC_GRACEFUL_STOP_MS = 3_000;
26
30
  const POSIX_GRACEFUL_STOP_MS = 1_000;
@@ -47,21 +51,23 @@ export async function stopEcwebProcess(identity, timeoutMs = FORCED_STOP_MS, onT
47
51
  catch { }
48
52
  }
49
53
  };
50
- if (!sameProcess(identity))
51
- return;
52
54
  if (requestGracefulStop) {
55
+ // Ask our actual child first. Fresh OS identity queries are only needed
56
+ // before falling back to PID-addressed signals, including on IPC failure.
53
57
  if (await waitForExit(false, IPC_GRACEFUL_STOP_MS, requestGracefulStop))
54
58
  return;
55
- if (!sameProcess(identity))
59
+ if (!await sameProcess(identity))
56
60
  return;
57
61
  }
62
+ else if (!await sameProcess(identity))
63
+ return;
58
64
  if (!platform.isWindows && await waitForExit(false, POSIX_GRACEFUL_STOP_MS))
59
65
  return;
60
- if (!sameProcess(identity))
66
+ if (!await sameProcess(identity))
61
67
  return;
62
68
  if (await waitForExit(true, timeoutMs))
63
69
  return;
64
- if (!sameProcess(identity))
70
+ if (!await sameProcess(identity))
65
71
  return;
66
72
  throw new Error(`ECWeb 进程未能退出 (PID: ${identity.pid})`);
67
73
  }
@@ -3,14 +3,15 @@ import path from 'path';
3
3
  import { spawn } from 'child_process';
4
4
  import { isDevMode, resolvePaths } from '../../paths.js';
5
5
  import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, SERVICE_STARTUP_TIMEOUT_MS, } from '../../config/daemon-services.js';
6
- import { WEB_PACKAGE_NAME } from '../../product.js';
7
- import { resolveGlobalPkg } from '../../utils/npm-ops.js';
6
+ import { RUNTIME_HOME_ENV, WEB_PACKAGE_NAME } from '../../product.js';
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 { getProcessStartTime } from '../../utils/process-introspect.js';
10
+ import { getProcessStartTimeAsync } 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';
14
+ import { sanitizeServiceEnvironment } from '../../core/permission/shell-environment.js';
14
15
  const INSTANCE_FILE_RE = /^(?:ecweb|watch-web)-\d+\.json$/;
15
16
  function sleep(ms) {
16
17
  return new Promise(resolve => setTimeout(resolve, ms));
@@ -52,7 +53,7 @@ function readExitDiagnostics(filePath, startOffset) {
52
53
  }
53
54
  }
54
55
  }
55
- function isAlive(record) {
56
+ async function isAlive(record) {
56
57
  if (!Number.isInteger(record.pid) || record.pid <= 0)
57
58
  return false;
58
59
  // ECWeb versions before the supervisor used a different Linux boot-time
@@ -61,7 +62,7 @@ function isAlive(record) {
61
62
  // scoped to this EVOLCORE_HOME; use liveness here and let the HTTP probe be
62
63
  // the ownership/health check. PID/start-time validation remains in the
63
64
  // explicit kill path below.
64
- return platform.isProcessRunning(record.pid);
65
+ return platform.isProcessRunningAsync(record.pid);
65
66
  }
66
67
  function readEntries() {
67
68
  const dir = resolvePaths().instanceDir;
@@ -125,6 +126,7 @@ async function probe(record, timeoutMs) {
125
126
  * ECWeb's own stale-instance cleanup, and daemon startup.
126
127
  */
127
128
  export function createEcwebSupervisor(options) {
129
+ const settleInitialHealth = options.startupTrace?.startTask('daemon.ecwebHealthReady', undefined, { initialPhase: 'waiting' });
128
130
  let healthConfig = options.health;
129
131
  let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
130
132
  let desiredPort = options.port;
@@ -138,6 +140,7 @@ export function createEcwebSupervisor(options) {
138
140
  let failureCount = 0;
139
141
  let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
140
142
  let healthy = false;
143
+ let checkedAt;
141
144
  let startInFlight = null;
142
145
  let childStartedAt = 0;
143
146
  let childIdentityStartedAt = null;
@@ -166,13 +169,13 @@ export function createEcwebSupervisor(options) {
166
169
  catch { }
167
170
  }
168
171
  };
169
- const setActiveFromEntry = (entry, owned) => {
172
+ const setActiveFromEntry = async (entry, owned) => {
170
173
  active = {
171
174
  pid: entry.record.pid,
172
175
  port: entry.record.port,
173
176
  // Capture the current PID start time rather than trusting the record.
174
177
  // Older ECWeb builds could write a clock-skewed `startedAt` value.
175
- startedAt: getProcessStartTime(entry.record.pid)
178
+ startedAt: await getProcessStartTimeAsync(entry.record.pid)
176
179
  ?? (typeof entry.record.startedAt === 'number' ? entry.record.startedAt : null),
177
180
  owned,
178
181
  };
@@ -180,12 +183,12 @@ export function createEcwebSupervisor(options) {
180
183
  const findHealthyInstance = async () => {
181
184
  lastHealthFailure = '未发现有效的 ECWeb 实例注册';
182
185
  for (const entry of readEntries()) {
183
- if (!isAlive(entry.record)) {
186
+ if (!await isAlive(entry.record)) {
184
187
  lastHealthFailure = '实例进程不存在';
185
188
  removeEntry(entry);
186
189
  continue;
187
190
  }
188
- const actual = getProcessStartTime(entry.record.pid);
191
+ const actual = await getProcessStartTimeAsync(entry.record.pid);
189
192
  if (actual !== null && entry.record.startedAt !== undefined
190
193
  && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
191
194
  lastHealthFailure = '实例 PID 启动时间不匹配';
@@ -253,12 +256,13 @@ export function createEcwebSupervisor(options) {
253
256
  // instance record there is no `active` entry yet, but the daemon still
254
257
  // owns the child and must not leave it behind on shutdown.
255
258
  const pendingPid = child?.pid;
256
- if (pendingPid && platform.isProcessRunning(pendingPid)) {
259
+ if (pendingPid && (await platform.isProcessRunningAsync(pendingPid))) {
257
260
  await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
258
261
  }
259
262
  child = null;
260
263
  childIdentityStartedAt = null;
261
264
  healthy = false;
265
+ checkedAt = undefined;
262
266
  return;
263
267
  }
264
268
  await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
@@ -267,6 +271,7 @@ export function createEcwebSupervisor(options) {
267
271
  child = null;
268
272
  childIdentityStartedAt = null;
269
273
  healthy = false;
274
+ checkedAt = undefined;
270
275
  };
271
276
  const spawnEcweb = async () => {
272
277
  if (stopping || !desiredEnabled || runtimeMode !== 'managed')
@@ -276,7 +281,9 @@ export function createEcwebSupervisor(options) {
276
281
  failureCount = 0;
277
282
  const root = resolvePaths().root;
278
283
  const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
279
- const globalPkg = resolveGlobalPkg(WEB_PACKAGE_NAME);
284
+ const globalPkg = await resolveGlobalPkgAsync(WEB_PACKAGE_NAME);
285
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
286
+ return;
280
287
  let launch = resolveEcwebLaunchCommand(['--home', root, '--port', String(desiredPort)], {
281
288
  installedPkg: globalPkg,
282
289
  });
@@ -311,7 +318,9 @@ export function createEcwebSupervisor(options) {
311
318
  scheduleRecovery();
312
319
  return;
313
320
  }
314
- const occupiedPids = platform.findProcessByPort(desiredPort);
321
+ const occupiedPids = await platform.findProcessByPortAsync(desiredPort);
322
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
323
+ return;
315
324
  if (occupiedPids.length > 0) {
316
325
  options.logger.error(`ECWeb 启动已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
317
326
  failureCount = failureThreshold;
@@ -334,8 +343,8 @@ export function createEcwebSupervisor(options) {
334
343
  stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
335
344
  windowsHide: platform.isWindows,
336
345
  env: {
337
- ...process.env,
338
- EVOLCORE_HOME: root,
346
+ ...sanitizeServiceEnvironment(process.env),
347
+ [RUNTIME_HOME_ENV]: root,
339
348
  EVOLCORE_ECWEB_SUPERVISED: '1',
340
349
  },
341
350
  });
@@ -350,7 +359,6 @@ export function createEcwebSupervisor(options) {
350
359
  closeLogStream();
351
360
  child = spawned;
352
361
  childStartedAt = Date.now();
353
- childIdentityStartedAt = spawned.pid ? getProcessStartTime(spawned.pid) : null;
354
362
  spawned.once('error', (error) => {
355
363
  options.logger.error(`ECWeb 子进程创建失败: ${error.message}`);
356
364
  if (child !== spawned || intentionalStop || stopping)
@@ -373,18 +381,12 @@ export function createEcwebSupervisor(options) {
373
381
  childStartedAt = 0;
374
382
  childIdentityStartedAt = null;
375
383
  healthy = false;
384
+ checkedAt = Date.now();
376
385
  if (!expectedExit) {
377
386
  if (active?.pid === spawned.pid)
378
387
  active = null;
379
388
  failureCount = failureThreshold;
380
- const occupiedPids = platform.findProcessByPort(desiredPort);
381
- if (occupiedPids.length > 0) {
382
- recoveryExhausted = true;
383
- options.logger.error(`ECWeb 自动恢复已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
384
- }
385
- else {
386
- scheduleRecovery();
387
- }
389
+ scheduleRecovery();
388
390
  }
389
391
  }
390
392
  closeLogStream();
@@ -396,6 +398,10 @@ export function createEcwebSupervisor(options) {
396
398
  options.logger.warn('ECWeb 启动失败:未取得子进程 PID');
397
399
  return;
398
400
  }
401
+ const startedAt = await getProcessStartTimeAsync(spawned.pid);
402
+ if (child !== spawned)
403
+ return;
404
+ childIdentityStartedAt = startedAt;
399
405
  options.logger.info(`✓ ECWeb supervisor 已启动 (PID: ${spawned.pid}),日志: ${logFile}`);
400
406
  // ECWeb writes its own instance record after binding. Do not fabricate a
401
407
  // record here; the watchdog will adopt the real record on its next tick.
@@ -411,26 +417,32 @@ export function createEcwebSupervisor(options) {
411
417
  if (stopping) {
412
418
  // 保留已核验的实例身份供 stop 清理,但不再接管运行状态或进入恢复分支。
413
419
  if (instance)
414
- setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
420
+ await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
415
421
  return;
416
422
  }
417
423
  if (!desiredEnabled || runtimeMode !== 'managed')
418
424
  return;
419
425
  healthy = instance !== null;
426
+ checkedAt = Date.now();
420
427
  if (instance) {
421
428
  launchRequested = false;
422
429
  cancelRecovery();
423
430
  const changed = !active || active.pid !== instance.record.pid || active.port !== instance.record.port;
424
- setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
431
+ await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
432
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
433
+ return;
425
434
  failureCount = 0;
426
435
  hasBeenReady = true;
436
+ settleInitialHealth?.('ok');
427
437
  if (changed)
428
438
  options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${instance.record.pid}, 端口: ${instance.record.port})`);
429
439
  return;
430
440
  }
431
- if (!launchRequested && !hasBeenReady && child?.pid && platform.isProcessRunning(child.pid)
441
+ if (!launchRequested && !hasBeenReady && child?.pid && (await platform.isProcessRunningAsync(child.pid))
432
442
  && Date.now() - childStartedAt < (healthConfig?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS))
433
443
  return;
444
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
445
+ return;
434
446
  if (launchRequested) {
435
447
  // A successful probe above cancels recovery without spending a retry.
436
448
  // Charge the allowance only when an automatic restart actually begins.
@@ -465,6 +477,8 @@ export function createEcwebSupervisor(options) {
465
477
  recoveryTimer = null;
466
478
  };
467
479
  const scheduleRecovery = () => {
480
+ if (!healthy && desiredEnabled && !stopping)
481
+ settleInitialHealth?.('failed');
468
482
  if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
469
483
  || restartConfig?.enabled === false || recoveryTimer || launchRequested || recoveryExhausted)
470
484
  return;
@@ -526,23 +540,28 @@ export function createEcwebSupervisor(options) {
526
540
  if (stopping)
527
541
  return;
528
542
  if (!desiredEnabled || runtimeMode !== 'managed') {
543
+ settleInitialHealth?.('skipped');
529
544
  scheduleCheck();
530
545
  return;
531
546
  }
532
547
  // Give an independently started ECWeb time to publish its instance record.
548
+ settleInitialHealth?.phase?.('waiting', 'existing ECWeb instance');
533
549
  const existing = await waitForHealthyInstance(1_500);
534
550
  if (stopping) {
535
551
  if (existing)
536
- setActiveFromEntry(existing, false);
552
+ await setActiveFromEntry(existing, false);
537
553
  return;
538
554
  }
539
555
  if (existing) {
540
556
  healthy = true;
557
+ checkedAt = Date.now();
541
558
  hasBeenReady = true;
542
- setActiveFromEntry(existing, false);
559
+ await setActiveFromEntry(existing, false);
543
560
  options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
561
+ settleInitialHealth?.('ok');
544
562
  }
545
563
  else {
564
+ settleInitialHealth?.phase?.('running');
546
565
  failureCount = failureThreshold;
547
566
  launchRequested = 'manual';
548
567
  await check();
@@ -563,6 +582,8 @@ export function createEcwebSupervisor(options) {
563
582
  desiredEnabled = config.enabled;
564
583
  desiredPort = config.port;
565
584
  runtimeMode = nextMode;
585
+ if (!desiredEnabled || runtimeMode !== 'managed')
586
+ settleInitialHealth?.('skipped');
566
587
  restartConfig = config.restart;
567
588
  healthConfig = config.health;
568
589
  failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
@@ -582,6 +603,7 @@ export function createEcwebSupervisor(options) {
582
603
  child = null;
583
604
  active = null;
584
605
  healthy = false;
606
+ checkedAt = undefined;
585
607
  }
586
608
  else if (enabledChanged || portChanged || modeChanged) {
587
609
  await killActive();
@@ -604,7 +626,10 @@ export function createEcwebSupervisor(options) {
604
626
  return {
605
627
  start() {
606
628
  if (!startup)
607
- startup = start();
629
+ startup = start().catch(error => {
630
+ settleInitialHealth?.('failed');
631
+ throw error;
632
+ });
608
633
  return startup;
609
634
  },
610
635
  configure(config) {
@@ -619,16 +644,23 @@ export function createEcwebSupervisor(options) {
619
644
  await restart();
620
645
  },
621
646
  status() {
622
- const running = active && platform.isProcessRunning(active.pid);
647
+ // Report the latest supervised state; status reads must not run tasklist.
648
+ const running = active !== null;
623
649
  const ready = running && healthy && active.port === desiredPort;
650
+ const health = desiredEnabled && runtimeMode === 'managed' && checkedAt !== undefined ? healthy : null;
624
651
  return {
625
652
  enabled: desiredEnabled,
626
653
  port: desiredPort,
627
654
  state: !desiredEnabled ? 'disabled' : ready ? 'ready' : failureCount >= failureThreshold ? 'failed' : 'starting',
655
+ healthy: health,
656
+ hasProbe: runtimeMode === 'managed',
657
+ endpointHealth: health === null ? 'unknown' : health ? 'healthy' : 'unhealthy',
658
+ ...(health === null ? {} : { checkedAt }),
628
659
  ...(running ? { pid: active.pid } : {}),
629
660
  };
630
661
  },
631
662
  stop(onTiming) {
663
+ settleInitialHealth?.('cancelled');
632
664
  if (onTiming) {
633
665
  stopTimingListeners.add(onTiming);
634
666
  for (const timing of completedStopTimings) {
@@ -0,0 +1,114 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { AID_PATTERN } from './validation.js';
4
+ function aid(value) {
5
+ return typeof value === 'string' && AID_PATTERN.test(value) ? value : undefined;
6
+ }
7
+ function identityAid(value) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value))
9
+ return undefined;
10
+ return aid(value.aid);
11
+ }
12
+ function readContactSnapshot(agentDir, selfAid) {
13
+ let raw;
14
+ try {
15
+ raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
16
+ }
17
+ catch (error) {
18
+ return { error: error instanceof Error && 'code' in error && error.code === 'ENOENT' ? 'contacts_snapshot_missing' : 'contacts_snapshot_unreadable' };
19
+ }
20
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
21
+ return { error: 'contacts_snapshot_invalid' };
22
+ const record = raw;
23
+ const entries = [];
24
+ if (Array.isArray(record.entries)) {
25
+ for (const item of record.entries) {
26
+ if (!item || typeof item !== 'object' || Array.isArray(item))
27
+ continue;
28
+ const value = item;
29
+ const entryAid = aid(value.aid);
30
+ if (!entryAid)
31
+ continue;
32
+ const scopeRaw = value.agent_scope;
33
+ const agentScope = scopeRaw && typeof scopeRaw === 'object' && !Array.isArray(scopeRaw)
34
+ ? { mode: scopeRaw.mode, agentAids: scopeRaw.agent_aids }
35
+ : undefined;
36
+ entries.push({ aid: entryAid, ...(agentScope ? { agentScope } : {}) });
37
+ }
38
+ }
39
+ const blocked = new Set();
40
+ const blockedRaw = record.blocked_aids ?? record.blockedAids;
41
+ if (Array.isArray(blockedRaw)) {
42
+ for (const item of blockedRaw) {
43
+ const blockedAid = typeof item === 'string'
44
+ ? aid(item)
45
+ : item && typeof item === 'object' && !Array.isArray(item) ? aid(item.target_id) : undefined;
46
+ if (blockedAid)
47
+ blocked.add(blockedAid);
48
+ }
49
+ }
50
+ const owner = identityAid(record.owner);
51
+ const personalAssistant = identityAid(record.personal_assistant);
52
+ if (!owner && entries.length === 0 && !personalAssistant)
53
+ return { error: 'contacts_snapshot_empty' };
54
+ return { owner, personalAssistant, entries, blocked };
55
+ }
56
+ function admittedAids(snapshot, selfAid) {
57
+ const result = new Set();
58
+ for (const candidate of [selfAid, snapshot.owner, snapshot.personalAssistant]) {
59
+ // The current contact admission treats the local Agent and the resolved
60
+ // Owner identity as always reachable; event deny rules can still narrow them.
61
+ if (candidate)
62
+ result.add(candidate);
63
+ }
64
+ for (const entry of snapshot.entries) {
65
+ if (snapshot.blocked.has(entry.aid))
66
+ continue;
67
+ if (entry.agentScope?.mode === 'selected') {
68
+ const selected = Array.isArray(entry.agentScope.agentAids) ? entry.agentScope.agentAids : [];
69
+ if (!selected.includes(selfAid))
70
+ continue;
71
+ }
72
+ result.add(entry.aid);
73
+ }
74
+ return [...result].sort();
75
+ }
76
+ /**
77
+ * Materialize the SDK allowlist from the current contacts snapshot. Empty
78
+ * event allow rules mean the contact admission set; a non-empty rule narrows
79
+ * that set. Deny always wins. Temporary grants and other authorization stores
80
+ * are deliberately not consulted here.
81
+ */
82
+ export function materializeAllowlist(config, agentDir, selfAid, registeredEvents) {
83
+ const snapshot = readContactSnapshot(agentDir, selfAid);
84
+ if ('error' in snapshot) {
85
+ return { allowlist: explicitAllowlist(config), degraded: true, admittedAids: [], reason: snapshot.error };
86
+ }
87
+ const base = new Set(admittedAids(snapshot, selfAid));
88
+ const allowlist = {};
89
+ const events = registeredEvents === undefined
90
+ ? Object.keys(config.allowlist)
91
+ : [...new Set(registeredEvents)];
92
+ for (const event of events) {
93
+ const entry = config.allowlist[event] ?? {
94
+ allow: { publish: [], subscribe: [] },
95
+ deny: { publish: [], subscribe: [] },
96
+ };
97
+ const publishAllow = entry.allow.publish.length > 0 ? entry.allow.publish : [...base];
98
+ const subscribeAllow = entry.allow.subscribe.length > 0 ? entry.allow.subscribe : [...base];
99
+ const publish = publishAllow.filter(candidate => base.has(candidate) && !entry.deny.publish.includes(candidate));
100
+ const subscribe = subscribeAllow.filter(candidate => base.has(candidate) && !entry.deny.subscribe.includes(candidate));
101
+ allowlist[event] = { publish_aids: [...new Set(publish)].sort(), subscribe_aids: [...new Set(subscribe)].sort() };
102
+ }
103
+ return { allowlist, degraded: false, admittedAids: [...base] };
104
+ }
105
+ function explicitAllowlist(config) {
106
+ const result = {};
107
+ for (const [event, entry] of Object.entries(config.allowlist)) {
108
+ result[event] = {
109
+ publish_aids: entry.allow.publish.filter(aid => !entry.deny.publish.includes(aid)),
110
+ subscribe_aids: entry.allow.subscribe.filter(aid => !entry.deny.subscribe.includes(aid)),
111
+ };
112
+ }
113
+ return result;
114
+ }
@@ -0,0 +1,136 @@
1
+ const facadeGates = new WeakMap();
2
+ const coreGates = new WeakMap();
3
+ /** Wrap the SDK's remote request handler when its runtime service map is available. */
4
+ export function installEventBusRequestGate(facadeValue, busAid, gate) {
5
+ if (!facadeValue || typeof facadeValue !== 'object')
6
+ return false;
7
+ const facade = facadeValue;
8
+ if (typeof facade.start !== 'function' || !(facade.buses instanceof Map))
9
+ return false;
10
+ let state = facadeGates.get(facade);
11
+ if (!state) {
12
+ const originalStart = facade.start;
13
+ state = { originalStart, gates: new Map() };
14
+ facadeGates.set(facade, state);
15
+ facade.start = function (...args) {
16
+ const started = state.originalStart.apply(this, args);
17
+ const aid = typeof args[0] === 'string' ? args[0] : '';
18
+ const nextGate = state.gates.get(aid);
19
+ if (aid && nextGate)
20
+ installCoreGate(this.buses?.get(aid)?.service, nextGate);
21
+ return started;
22
+ };
23
+ }
24
+ state.gates.set(busAid, gate);
25
+ return installCoreGate(facade.buses.get(busAid)?.service, gate);
26
+ }
27
+ function installCoreGate(service, gate) {
28
+ if (!service || typeof service.handle !== 'function')
29
+ return false;
30
+ const existing = coreGates.get(service);
31
+ if (existing) {
32
+ existing.gate = gate;
33
+ return true;
34
+ }
35
+ const originalHandle = service.handle;
36
+ const state = { originalHandle, gate };
37
+ coreGates.set(service, state);
38
+ service.handle = async function (senderAid, request, ...rest) {
39
+ await state.gate(senderAid, request, this);
40
+ return state.originalHandle.call(this, senderAid, request, ...rest);
41
+ };
42
+ return true;
43
+ }
44
+ export function evaluateEventBusRequest(senderAid, request, materialized, service) {
45
+ const operation = typeof request.op === 'string' ? request.op : 'unknown';
46
+ const deny = (reason, event, action) => ({
47
+ allowed: false, operation, reason, ...(event ? { event } : {}), ...(action ? { action } : {}),
48
+ });
49
+ const admitted = new Set(materialized.admittedAids);
50
+ if (operation === 'unsubscribe')
51
+ return { allowed: true, operation };
52
+ if (operation === 'catalog' || operation === 'stats') {
53
+ return admitted.has(senderAid) ? { allowed: true, operation } : deny('contact_admission');
54
+ }
55
+ if (operation === 'publish') {
56
+ const event = typeof request.event_name === 'string' ? request.event_name : undefined;
57
+ if (!event)
58
+ return { allowed: true, operation };
59
+ return isAllowed(materialized, event, 'publish', senderAid)
60
+ ? { allowed: true, operation, action: 'publish', event }
61
+ : deny('event_rule', event, 'publish');
62
+ }
63
+ if (operation === 'authorize') {
64
+ if (request.auth_mode !== undefined && request.auth_mode !== 'allowlist')
65
+ return deny('unsupported_auth_mode');
66
+ const scope = requestScope(request);
67
+ if (!scope)
68
+ return { allowed: true, operation };
69
+ for (const item of scope) {
70
+ if (!isAllowed(materialized, item.event, item.action, senderAid))
71
+ return deny('event_rule', item.event, item.action);
72
+ }
73
+ return { allowed: true, operation };
74
+ }
75
+ if (operation === 'subscribe') {
76
+ const events = stringList(request.events);
77
+ if (!events)
78
+ return { allowed: true, operation };
79
+ for (const event of events) {
80
+ if (!isAllowed(materialized, event, 'subscribe', senderAid))
81
+ return deny('event_rule', event, 'subscribe');
82
+ }
83
+ return { allowed: true, operation };
84
+ }
85
+ if (operation === 'renew') {
86
+ const leaseId = typeof request.lease_id === 'string' ? request.lease_id : '';
87
+ const leases = service?.leases;
88
+ const lease = leaseId ? leases?.get(leaseId) : undefined;
89
+ if (!admitted.has(senderAid))
90
+ return deny('contact_admission');
91
+ if (!lease?.scope)
92
+ return { allowed: true, operation };
93
+ if (lease.aid !== senderAid || lease.auth_mode === 'credential')
94
+ return deny('lease_scope');
95
+ for (const item of lease.scope) {
96
+ if ((item.action !== 'publish' && item.action !== 'subscribe')
97
+ || typeof item.event_name !== 'string'
98
+ || !isAllowed(materialized, item.event_name, item.action, senderAid)) {
99
+ return deny('event_rule', item.event_name, item.action === 'publish' || item.action === 'subscribe' ? item.action : undefined);
100
+ }
101
+ }
102
+ return { allowed: true, operation };
103
+ }
104
+ return deny('unsupported_operation');
105
+ }
106
+ function isAllowed(materialized, event, action, aid) {
107
+ const entry = materialized.allowlist[event];
108
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
109
+ return false;
110
+ const list = entry[action === 'publish' ? 'publish_aids' : 'subscribe_aids'];
111
+ return Array.isArray(list) && list.includes(aid);
112
+ }
113
+ function stringList(value) {
114
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string'))
115
+ return undefined;
116
+ return value;
117
+ }
118
+ function requestScope(request) {
119
+ if (Array.isArray(request.scope)) {
120
+ const scope = [];
121
+ for (const value of request.scope) {
122
+ if (!value || typeof value !== 'object' || Array.isArray(value))
123
+ return undefined;
124
+ const item = value;
125
+ if (typeof item.event_name !== 'string' || (item.action !== 'publish' && item.action !== 'subscribe'))
126
+ return undefined;
127
+ scope.push({ event: item.event_name, action: item.action });
128
+ }
129
+ return scope.length ? scope : undefined;
130
+ }
131
+ const events = stringList(request.events);
132
+ const actions = stringList(request.actions);
133
+ if (!events || !actions || actions.some(action => action !== 'publish' && action !== 'subscribe'))
134
+ return undefined;
135
+ return events.flatMap(event => actions.map(action => ({ event, action: action })));
136
+ }