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
@@ -7,7 +7,7 @@
7
7
  * killing the wrong process).
8
8
  */
9
9
  import fs from 'fs';
10
- import { spawnSync } from 'child_process';
10
+ import { execFile, spawnSync } from 'child_process';
11
11
  const isWindows = process.platform === 'win32';
12
12
  const isMacOS = process.platform === 'darwin';
13
13
  function readLinuxClockTicks() {
@@ -52,6 +52,69 @@ function approximateSelfStartTime() {
52
52
  */
53
53
  const START_TIME_CACHE_TTL_MS = 5000;
54
54
  const startTimeCache = new Map();
55
+ const startTimeQueries = new Map();
56
+ /** Daemon lifecycle queries must not block IPC, probes or startup timers. */
57
+ export async function getProcessStartTimeAsync(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0)
59
+ return null;
60
+ if (pid === process.pid)
61
+ return getProcessStartTime(pid);
62
+ const cached = startTimeCache.get(pid);
63
+ if (cached && Date.now() - cached.at < START_TIME_CACHE_TTL_MS)
64
+ return cached.startedAt;
65
+ const pending = startTimeQueries.get(pid);
66
+ if (pending)
67
+ return pending;
68
+ const query = (async () => {
69
+ let startedAt;
70
+ if (isWindows) {
71
+ const output = await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command',
72
+ `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
73
+ startedAt = parseCimDate(output) ?? parseDateString(output);
74
+ if (startedAt === null) {
75
+ const fallback = await processQuery('wmic', ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'], 5000);
76
+ const creation = fallback.match(/CreationDate=([^\r\n]+)/)?.[1]?.trim();
77
+ startedAt = creation ? parseCimDate(creation) ?? parseDateString(creation) : null;
78
+ }
79
+ }
80
+ else if (isMacOS) {
81
+ startedAt = parseDateString(await processQuery('ps', ['-p', String(pid), '-o', 'lstart='], 5000));
82
+ }
83
+ else {
84
+ startedAt = getStartTimeLinux(pid);
85
+ }
86
+ // Do not cache an identity for a child that exited during the query.
87
+ if (startedAt !== null) {
88
+ try {
89
+ process.kill(pid, 0);
90
+ }
91
+ catch (error) {
92
+ if (error.code !== 'EPERM')
93
+ startedAt = null;
94
+ }
95
+ }
96
+ if (startedAt === null)
97
+ startTimeCache.delete(pid);
98
+ else
99
+ startTimeCache.set(pid, { at: Date.now(), startedAt });
100
+ return startedAt;
101
+ })();
102
+ startTimeQueries.set(pid, query);
103
+ try {
104
+ return await query;
105
+ }
106
+ finally {
107
+ if (startTimeQueries.get(pid) === query)
108
+ startTimeQueries.delete(pid);
109
+ }
110
+ }
111
+ function processQuery(command, args, timeout) {
112
+ return new Promise(resolve => {
113
+ execFile(command, args, { encoding: 'utf8', timeout, windowsHide: true }, (error, stdout) => {
114
+ resolve(error ? '' : stdout.replace(/^\uFEFF/, '').trim());
115
+ });
116
+ });
117
+ }
55
118
  /**
56
119
  * 获取进程启动时间(Unix 毫秒)。
57
120
  * 拿不到时返回 null,调用方应保守处理(不杀该 PID)。
@@ -182,6 +245,8 @@ function parseDateString(value) {
182
245
  return Number.isNaN(parsed) ? null : parsed;
183
246
  }
184
247
  let snapshotCache = null;
248
+ let snapshotQuery = null;
249
+ let snapshotGeneration = 0;
185
250
  /**
186
251
  * 同一次启动流程里多处调用共享快照。
187
252
  *
@@ -204,9 +269,37 @@ export function getProcessSnapshot(options = {}) {
204
269
  snapshotCache = { at: now, snapshot };
205
270
  return snapshot;
206
271
  }
272
+ /** The restart monitor shares one snapshot per phase without blocking IPC/timers. */
273
+ export async function getProcessSnapshotAsync(options = {}) {
274
+ if (!options.fresh && snapshotCache && Date.now() - snapshotCache.at < SNAPSHOT_TTL_MS) {
275
+ return snapshotCache.snapshot;
276
+ }
277
+ if (snapshotQuery)
278
+ return snapshotQuery;
279
+ const generation = snapshotGeneration;
280
+ const query = (async () => {
281
+ const snapshot = isWindows
282
+ ? parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000))
283
+ ?? { complete: false, startedAt: new Map(), commandLines: new Map() }
284
+ : readProcessSnapshot();
285
+ if (generation === snapshotGeneration)
286
+ snapshotCache = { at: Date.now(), snapshot };
287
+ return snapshot;
288
+ })();
289
+ snapshotQuery = query;
290
+ try {
291
+ return await query;
292
+ }
293
+ finally {
294
+ if (snapshotQuery === query)
295
+ snapshotQuery = null;
296
+ }
297
+ }
207
298
  /** 让测试或长驻进程主动失效快照。 */
208
299
  export function invalidateProcessSnapshot() {
209
300
  snapshotCache = null;
301
+ snapshotQuery = null;
302
+ snapshotGeneration++;
210
303
  }
211
304
  function readProcessSnapshot() {
212
305
  if (isWindows) {
@@ -220,10 +313,13 @@ function readProcessSnapshot() {
220
313
  }
221
314
  return { complete: false, startedAt: new Map(), commandLines: new Map() };
222
315
  }
316
+ const WINDOWS_SNAPSHOT_SCRIPT = 'Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress';
223
317
  function readWindowsSnapshot() {
224
- const script = "Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress";
225
- const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
226
- const raw = (result.stdout || '').replace(/^/, '').trim();
318
+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
319
+ return result.status === 0 ? parseWindowsSnapshot(result.stdout || '') : null;
320
+ }
321
+ function parseWindowsSnapshot(output) {
322
+ const raw = output.replace(/^\uFEFF/, '').trim();
227
323
  if (!raw)
228
324
  return null;
229
325
  let rows;
@@ -236,17 +332,19 @@ function readWindowsSnapshot() {
236
332
  }
237
333
  const startedAt = new Map();
238
334
  const commandLines = new Map();
335
+ const pids = new Set();
239
336
  for (const row of rows) {
240
- if (!Number.isInteger(row.ProcessId))
241
- continue;
337
+ if (!row || !Number.isInteger(row.ProcessId))
338
+ return null;
242
339
  const pid = row.ProcessId;
340
+ pids.add(pid);
243
341
  const started = coerceCimCreation(row.CreationDate);
244
342
  if (started !== null)
245
343
  startedAt.set(pid, started);
246
344
  if (typeof row.CommandLine === 'string')
247
345
  commandLines.set(pid, row.CommandLine);
248
346
  }
249
- return { complete: true, startedAt, commandLines };
347
+ return { complete: true, pids, startedAt, commandLines };
250
348
  }
251
349
  /**
252
350
  * ConvertTo-Json 对日期序列化的形状取决于 PowerShell 版本:可能是 CIM 字符串、
@@ -275,6 +373,7 @@ function coerceCimCreation(value) {
275
373
  }
276
374
  function readLinuxSnapshot() {
277
375
  const startedAt = new Map();
376
+ const pids = new Set();
278
377
  let complete = true;
279
378
  let btimeSec = null;
280
379
  try {
@@ -296,6 +395,7 @@ function readLinuxSnapshot() {
296
395
  if (!/^\d+$/.test(name))
297
396
  continue;
298
397
  const pid = Number(name);
398
+ pids.add(pid);
299
399
  try {
300
400
  const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf-8');
301
401
  const tail = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
@@ -308,7 +408,7 @@ function readLinuxSnapshot() {
308
408
  // 进程在枚举过程中退出:从快照里缺席即视为不存在。
309
409
  }
310
410
  }
311
- return { complete, startedAt, commandLines: new Map() };
411
+ return { complete, pids, startedAt, commandLines: new Map() };
312
412
  }
313
413
  /**
314
414
  * 用快照判断「pid 是否仍是当初记录的那个进程」。
@@ -325,8 +425,7 @@ export function snapshotProcessState(snapshot, pid, recordedStartedAt) {
325
425
  return 'unknown';
326
426
  const actual = snapshot.startedAt.get(pid);
327
427
  if (actual === undefined)
328
- return 'dead';
329
- // 拿不到创建时间时保守认为活着(与 isAlive 的既有约定一致)。
428
+ return snapshot.pids?.has(pid) || snapshot.commandLines.has(pid) ? 'unknown' : 'dead';
330
429
  return startTimeMatches(recordedStartedAt, actual) ? 'alive' : 'dead';
331
430
  }
332
431
  /**
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * 生命周期阶段埋点 —— 记录一次启动或停止里各阶段各花了多久,供 ECWeb 甘特图展示。
3
3
  *
4
- * 两类进程各写一条记录,用同一 traceId 关联:
4
+ * CLI、重启监控器和 daemon 用同一 traceId 关联:
5
5
  * - CLI(ec start / ec stop)source='cli'
6
6
  * - Daemon(dist) source='daemon'
7
7
  *
8
8
  * 启动与停止共用同一套结构,只用 `kind` 区分('startup' / 'stop'):
9
- * 两者都是「一串首尾相接的阶段」,都用绝对毫秒时间戳对齐成一条时间轴。
9
+ * 主流程阶段首尾相接,后台任务可重叠;都用绝对毫秒时间戳对齐。
10
+ * daemon 在控制面 ready 和后台任务结束时追加快照,读取时保留同一进程的最后一版。
10
11
  *
11
12
  * 起算点(startedAtMs)对启动是本进程启动时刻;对停止是调用方显式传入的
12
13
  * 起算点——CLI 传 `ec stop` 的进程启动时刻,daemon 传收到 shutdown 请求的时刻。
@@ -19,6 +20,78 @@ import fs from 'node:fs';
19
20
  import path from 'node:path';
20
21
  import crypto from 'node:crypto';
21
22
  import { resolvePaths } from '../paths.js';
23
+ export const STARTUP_CPU_PROFILE_REQUEST = 'startup-cpu-profile.once';
24
+ export const STARTUP_CPU_PROFILE_MAX_MS = 90_000;
25
+ export async function startRequestedStartupCpuProfile(traceId) {
26
+ const paths = resolvePaths();
27
+ try {
28
+ fs.unlinkSync(path.join(paths.instanceDir, STARTUP_CPU_PROFILE_REQUEST));
29
+ }
30
+ catch (error) {
31
+ if (error.code !== 'ENOENT') {
32
+ const { logger } = await import('./logger.js');
33
+ logger.warn('[StartupCPU] Failed to consume profiling request', error);
34
+ }
35
+ return undefined;
36
+ }
37
+ const { logger } = await import('./logger.js');
38
+ let session;
39
+ try {
40
+ const { Session } = await import('node:inspector/promises');
41
+ session = new Session();
42
+ session.connect();
43
+ await session.post('Profiler.enable');
44
+ await session.post('Profiler.setSamplingInterval', { interval: 1_000 });
45
+ await session.post('Profiler.start');
46
+ }
47
+ catch (error) {
48
+ try {
49
+ session?.disconnect();
50
+ }
51
+ catch { }
52
+ logger.warn('[StartupCPU] CPU profiling unavailable; startup continues', error);
53
+ return undefined;
54
+ }
55
+ const activeSession = session;
56
+ const startedAt = Date.now();
57
+ const stamp = new Date(startedAt).toISOString().replace(/[-:.]/g, '');
58
+ const file = path.join(paths.logs, `startup-${stamp}-${process.pid}.cpuprofile`);
59
+ let stopping;
60
+ let timer;
61
+ const controller = {
62
+ file,
63
+ stop(reason) {
64
+ return stopping ??= (async () => {
65
+ clearTimeout(timer);
66
+ const stoppedAt = Date.now();
67
+ try {
68
+ const { profile } = await activeSession.post('Profiler.stop');
69
+ await fs.promises.mkdir(paths.logs, { recursive: true });
70
+ await fs.promises.writeFile(file, JSON.stringify(profile), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
71
+ logger.info(`[StartupCPU] Saved CPU profile: ${file} reason=${reason} durationMs=${stoppedAt - startedAt} traceId=${traceId}`);
72
+ await fs.promises.writeFile(`${file}.json`, JSON.stringify({
73
+ traceId, pid: process.pid, node: process.version, startedAt, stoppedAt,
74
+ durationMs: stoppedAt - startedAt, reason, samplingIntervalUs: 1_000,
75
+ boundary: 'daemon-election-won-to-normal-task-ready',
76
+ }, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
77
+ }
78
+ catch (error) {
79
+ logger.warn('[StartupCPU] Failed to save CPU profile; startup continues', error);
80
+ }
81
+ finally {
82
+ try {
83
+ activeSession.disconnect();
84
+ }
85
+ catch { }
86
+ }
87
+ })();
88
+ },
89
+ };
90
+ timer = setTimeout(() => { void controller.stop('timeout'); }, STARTUP_CPU_PROFILE_MAX_MS);
91
+ timer.unref();
92
+ logger.info(`[StartupCPU] One-shot CPU profiling started: ${file} traceId=${traceId}`);
93
+ return controller;
94
+ }
22
95
  /** 保留的启动/停止次数(按 traceId 去重后) */
23
96
  export const STARTUP_TRACE_KEEP = 50;
24
97
  /** CLI 传 traceId 给 daemon 的环境变量,让两侧记录落进同一次启动。 */
@@ -48,10 +121,11 @@ export class StartupTracer {
48
121
  spans = [];
49
122
  meta = {};
50
123
  processStartMs;
51
- cursorName = null;
52
- cursorStartMs = 0;
53
- cursorDetail;
124
+ cursor;
54
125
  finished = false;
126
+ readyAtMs;
127
+ taskReadyAtMs;
128
+ pendingTasks = new Set();
55
129
  constructor(source, opts = {}) {
56
130
  this.source = source;
57
131
  this.kind = opts.kind ?? 'startup';
@@ -63,34 +137,114 @@ export class StartupTracer {
63
137
  }
64
138
  this.traceId = traceId ?? newStartupTraceId();
65
139
  this.processStartMs = opts.processStartMs ?? processStartOfThisProcess();
66
- this.cursorStartMs = this.processStartMs;
67
- if (opts.firstPhase)
68
- this.cursorName = opts.firstPhase;
140
+ if (opts.firstPhase) {
141
+ this.cursor = { name: opts.firstPhase, startMs: this.processStartMs, segments: [],
142
+ ...(opts.initialPhase ? { current: { phase: opts.initialPhase, startMs: this.processStartMs } } : {}) };
143
+ }
69
144
  }
70
145
  get id() { return this.traceId; }
71
146
  get startedAtMs() { return this.processStartMs; }
72
147
  get traceKind() { return this.kind; }
73
148
  /** 结束当前阶段,开始新阶段。 */
74
- mark(name, detail) {
149
+ mark(name, detail, options = {}) {
75
150
  if (this.finished)
76
151
  return;
77
152
  const now = Date.now();
78
153
  this.closeCursor(now);
79
- this.cursorName = name;
80
- this.cursorStartMs = now;
81
- this.cursorDetail = detail;
154
+ this.cursor = { name, startMs: now, detail, summary: options.summary, segments: [],
155
+ ...(options.initialPhase ? { current: { phase: options.initialPhase, startMs: now } } : {}) };
82
156
  }
83
157
  /** 给当前打开的阶段补一句附注。 */
84
158
  note(detail) {
85
- if (this.finished || !this.cursorName)
159
+ if (this.finished || !this.cursor)
86
160
  return;
87
- this.cursorDetail = detail;
161
+ this.cursor.detail = detail;
162
+ }
163
+ /** 切换当前线性阶段的等待、排队或执行状态,不创建额外甘特行。 */
164
+ phase(phase, detail) {
165
+ if (this.finished || !this.cursor)
166
+ return;
167
+ this.changePhase(this.cursor, phase, detail);
168
+ }
169
+ /** 只观察已有外部依赖,不增加等待、重试或超时。 */
170
+ async waitForDependency(promise, detail) {
171
+ const cursor = this.cursor;
172
+ this.phase('waiting', detail);
173
+ try {
174
+ return await promise;
175
+ }
176
+ finally {
177
+ if (this.cursor === cursor)
178
+ this.phase('running');
179
+ }
88
180
  }
89
181
  /** 直接登记一段已测好的区间(用于拿到外部时间戳的场景)。 */
90
- addSpan(name, startMs, endMs, detail) {
182
+ addSpan(name, startMs, endMs, detail, status) {
91
183
  if (this.finished)
92
184
  return;
93
- this.spans.push({ name, startMs, durationMs: Math.max(0, endMs - startMs), ...(detail ? { detail } : {}) });
185
+ this.spans.push({ name, startMs, durationMs: Math.max(0, endMs - startMs), ...(detail ? { detail } : {}), ...(status ? { status } : {}) });
186
+ }
187
+ /** 观察由已有生命周期回调报告完成的任务,不增加轮询或就绪依赖。 */
188
+ startTask(name, detail, options = {}) {
189
+ const task = { name, startMs: Date.now(), detail, summary: options.summary, segments: [] };
190
+ if (options.initialPhase)
191
+ task.current = { phase: options.initialPhase, startMs: task.startMs };
192
+ if (!this.finished)
193
+ this.pendingTasks.add(task);
194
+ const settle = (status = 'ok') => {
195
+ if (this.finished || !this.pendingTasks.has(task))
196
+ return;
197
+ this.spans.push({ ...this.taskSnapshot(task, Date.now()), status });
198
+ this.pendingTasks.delete(task);
199
+ if (this.readyAtMs !== undefined) {
200
+ if (this.pendingTasks.size === 0)
201
+ this.finish(true);
202
+ else
203
+ this.persist(true);
204
+ }
205
+ };
206
+ return Object.assign(settle, {
207
+ phase: (phase, phaseDetail) => {
208
+ if (this.finished || !this.pendingTasks.has(task))
209
+ return;
210
+ this.changePhase(task, phase, phaseDetail);
211
+ },
212
+ });
213
+ }
214
+ /** 观察实际任务(含依赖等待),保持原有返回值和异常传播。 */
215
+ track(name, run, detail, options) {
216
+ const settle = this.startTask(name, detail, options);
217
+ try {
218
+ return run(settle.phase).then(value => {
219
+ settle(value === false ? 'cancelled' : 'ok');
220
+ return value;
221
+ }, error => {
222
+ settle('failed');
223
+ throw error;
224
+ });
225
+ }
226
+ catch (error) {
227
+ settle('failed');
228
+ return Promise.reject(error);
229
+ }
230
+ }
231
+ /** 保存控制面就绪快照;后台任务结束后自动补写同一进程的最新快照。 */
232
+ ready() {
233
+ if (this.finished || this.readyAtMs !== undefined)
234
+ return;
235
+ this.readyAtMs = Date.now();
236
+ this.closeCursor(this.readyAtMs);
237
+ if (this.pendingTasks.size === 0)
238
+ this.finish(true);
239
+ else
240
+ this.persist(true);
241
+ }
242
+ /** 正常启动边界;由实际任务准入条件发布,与控制面早就绪分别记录。 */
243
+ tasksReady() {
244
+ if (this.finished || this.readyAtMs === undefined || this.taskReadyAtMs !== undefined)
245
+ return;
246
+ this.taskReadyAtMs = Date.now();
247
+ this.persist(true);
94
248
  }
95
249
  /** 瞬时事件(时长为 0 的标记)。 */
96
250
  point(name, detail) {
@@ -115,9 +269,14 @@ export class StartupTracer {
115
269
  return;
116
270
  const now = Date.now();
117
271
  this.closeCursor(now);
272
+ for (const task of this.pendingTasks) {
273
+ this.spans.push({ ...this.taskSnapshot(task, now), status: 'cancelled' });
274
+ }
275
+ this.pendingTasks.clear();
118
276
  this.finished = true;
119
- if (this.cursorName)
120
- this.cursorName = null;
277
+ this.persist(this.readyAtMs !== undefined || ok, now);
278
+ }
279
+ persist(ok, now = Date.now()) {
121
280
  const record = {
122
281
  traceId: this.traceId,
123
282
  kind: this.kind,
@@ -127,6 +286,17 @@ export class StartupTracer {
127
286
  startedAt: new Date(this.processStartMs).toISOString(),
128
287
  ok,
129
288
  totalMs: Math.max(0, now - this.processStartMs),
289
+ ...(this.taskReadyAtMs === undefined ? {} : { taskReadyAtMs: this.taskReadyAtMs }),
290
+ ...(this.readyAtMs === undefined ? {} : {
291
+ readyAtMs: this.readyAtMs,
292
+ backgroundState: this.pendingTasks.size ? 'pending'
293
+ : this.spans.some(span => span.status === 'failed') ? 'failed'
294
+ : this.spans.some(span => span.status === 'cancelled') ? 'interrupted' : 'complete',
295
+ pendingTasks: [...this.pendingTasks].map(task => {
296
+ const { durationMs, ...snapshot } = this.taskSnapshot(task, now);
297
+ return snapshot;
298
+ }),
299
+ }),
130
300
  meta: this.meta,
131
301
  spans: this.spans,
132
302
  };
@@ -138,18 +308,30 @@ export class StartupTracer {
138
308
  }
139
309
  }
140
310
  closeCursor(now) {
141
- if (!this.cursorName)
311
+ if (!this.cursor)
142
312
  return;
143
- const span = {
144
- name: this.cursorName,
145
- startMs: this.cursorStartMs,
146
- durationMs: Math.max(0, now - this.cursorStartMs),
147
- };
148
- if (this.cursorDetail)
149
- span.detail = this.cursorDetail;
150
- this.spans.push(span);
151
- this.cursorName = null;
152
- this.cursorDetail = undefined;
313
+ this.spans.push(this.taskSnapshot(this.cursor, now));
314
+ this.cursor = undefined;
315
+ }
316
+ changePhase(task, phase, detail) {
317
+ if (task.current?.phase === phase && task.current.detail === detail)
318
+ return;
319
+ const now = Date.now();
320
+ if (task.current && now > task.current.startMs) {
321
+ task.segments.push({ ...task.current, durationMs: now - task.current.startMs });
322
+ }
323
+ task.current = { phase, startMs: now, ...(detail ? { detail } : {}) };
324
+ }
325
+ /** Snapshot open segments without mutating their boundaries or writing at every transition. */
326
+ taskSnapshot(task, now) {
327
+ const segments = task.segments.slice();
328
+ if (task.current && now > task.current.startMs) {
329
+ segments.push({ ...task.current, durationMs: now - task.current.startMs });
330
+ }
331
+ return { name: task.name, startMs: task.startMs, durationMs: Math.max(0, now - task.startMs),
332
+ ...(task.detail ? { detail: task.detail } : {}),
333
+ ...(task.summary ? { summary: true } : {}),
334
+ ...(segments.length ? { segments } : {}) };
153
335
  }
154
336
  }
155
337
  /** 本进程启动时刻。用 uptime 回推,能覆盖 node 启动 + 模块加载 + tsx 编译。 */
@@ -175,25 +357,18 @@ function trimStartupTrace(file) {
175
357
  const lines = raw.split('\n').filter(line => line.trim());
176
358
  if (lines.length <= STARTUP_TRACE_KEEP * 2 + 20)
177
359
  return;
178
- const ids = [];
360
+ const latest = new Map();
179
361
  for (const line of lines) {
180
362
  try {
181
- const id = JSON.parse(line).traceId;
363
+ const record = JSON.parse(line);
364
+ const id = record.traceId;
182
365
  if (id)
183
- ids.push(id);
184
- }
185
- catch { /* 坏行丢弃 */ }
186
- }
187
- const keep = new Set(Array.from(new Set(ids.sort())).slice(-STARTUP_TRACE_KEEP));
188
- const kept = [];
189
- for (const line of lines) {
190
- try {
191
- const id = JSON.parse(line).traceId;
192
- if (id && keep.has(id))
193
- kept.push(line);
366
+ latest.set(`${id}:${record.kind ?? 'startup'}:${record.source}:${record.pid}:${record.startedAtMs}`, { id, line });
194
367
  }
195
368
  catch { /* 坏行丢弃 */ }
196
369
  }
370
+ const keep = new Set([...new Set([...latest.values()].map(record => record.id))].sort().slice(-STARTUP_TRACE_KEEP));
371
+ const kept = [...latest.values()].filter(record => keep.has(record.id)).map(record => record.line);
197
372
  const tmp = `${file}.${process.pid}.tmp`;
198
373
  fs.writeFileSync(tmp, `${kept.join('\n')}\n`, 'utf-8');
199
374
  fs.renameSync(tmp, file);
@@ -224,7 +399,7 @@ export function formatSlowestSpans(spans, limit = 3, prefixPattern = /^[a-z]+\./
224
399
  * ——否则 `ec stop` 只报 CLI 的 1.2 秒,真正慢的 18 秒藏在对端。
225
400
  */
226
401
  export function findTraceRecord(traceId, source) {
227
- return readStartupTraces().find(record => record.traceId === traceId && record.source === source) ?? null;
402
+ return readStartupTraces().reverse().find(record => record.traceId === traceId && record.source === source) ?? null;
228
403
  }
229
404
  /** 读原始记录(ECWeb 侧也有一份独立实现,不复用本文件的路径工具)。 */
230
405
  export function readStartupTraces() {
@@ -247,5 +422,8 @@ export function readStartupTraces() {
247
422
  }
248
423
  catch { /* 坏行跳过 */ }
249
424
  }
250
- return records;
425
+ // 同一进程在 ready 和各后台任务完成时追加快照,只读取最后一版。
426
+ return [...new Map(records.map(record => [
427
+ `${record.traceId}:${record.kind ?? 'startup'}:${record.source}:${record.pid}:${record.startedAtMs}`, record,
428
+ ])).values()];
251
429
  }