evolcore 0.0.43-test.3 → 0.0.43-test.5

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 (192) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/ecmsg.js +492 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +12 -54
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +56 -12
  12. package/dist/aun/aid/control-aid.js +15 -0
  13. package/dist/aun/aid/identity.js +8 -0
  14. package/dist/aun/aid/ownership-operation.js +12 -3
  15. package/dist/aun/menu/client.js +8 -7
  16. package/dist/aun/menu/index.js +1 -1
  17. package/dist/aun/menu/transport.js +8 -5
  18. package/dist/aun/service-proxy.js +3 -0
  19. package/dist/channels/aun.js +56 -22
  20. package/dist/channels/daemon.js +12 -4
  21. package/dist/cli/agent-command.js +5 -0
  22. package/dist/cli/agent-create.js +32 -8
  23. package/dist/cli/agent.js +9 -3
  24. package/dist/cli/aid-bind-command.js +3 -0
  25. package/dist/cli/aun-commands.js +12 -5
  26. package/dist/cli/code-stats.js +451 -213
  27. package/dist/cli/ctl-command.js +1 -3
  28. package/dist/cli/daemon-commands.js +42 -21
  29. package/dist/cli/directory.js +7 -8
  30. package/dist/cli/ecmsg-gateway.js +204 -0
  31. package/dist/cli/getmeta-command.js +2 -1
  32. package/dist/cli/index.js +6 -0
  33. package/dist/cli/init.js +58 -18
  34. package/dist/cli/provider-command.js +82 -5
  35. package/dist/cli/restart-monitor.js +11 -19
  36. package/dist/cli/stats.js +8 -1
  37. package/dist/cli/task-context.js +3 -0
  38. package/dist/cli/trigger-command.js +20 -14
  39. package/dist/config/boot-log.js +23 -2
  40. package/dist/config/config-field-policy.js +2 -0
  41. package/dist/config/config-manager.js +13 -17
  42. package/dist/config/daemon-services.js +1 -0
  43. package/dist/config/peer-role-resolver.js +6 -6
  44. package/dist/config/provider-identity-migration.js +202 -0
  45. package/dist/config/provider-identity.js +37 -0
  46. package/dist/config/provider-ipc-service.js +40 -3
  47. package/dist/config/provider-local-sync.js +153 -0
  48. package/dist/config/providers-config.js +32 -4
  49. package/dist/config/providers-management.js +144 -68
  50. package/dist/config/providers.js +4 -1
  51. package/dist/config/role-schema.js +3 -3
  52. package/dist/config/schema-migration.js +188 -3
  53. package/dist/core/agent-application-service.js +11 -0
  54. package/dist/core/agent-ipc-registration.js +2 -0
  55. package/dist/core/agent-runtime.js +45 -11
  56. package/dist/core/auth/auth-gateway.js +8 -6
  57. package/dist/core/auth/delegation-diagnostics.js +6 -2
  58. package/dist/core/auth/operation-authorizer.js +5 -2
  59. package/dist/core/auth/operation-catalog.js +6 -4
  60. package/dist/core/baseagent-loader.js +11 -3
  61. package/dist/core/bootstrap-service.js +8 -0
  62. package/dist/core/channel-loader.js +61 -23
  63. package/dist/core/command/agent-control.js +4 -1
  64. package/dist/core/command/chatmode-config.js +46 -0
  65. package/dist/core/command/cli-intent-parser.js +2 -1
  66. package/dist/core/command/command-handler.js +16 -20
  67. package/dist/core/command/daemon-diagnostics.js +2 -1
  68. package/dist/core/command/menu-catalog.js +1 -1
  69. package/dist/core/command/menu-handler.js +16 -16
  70. package/dist/core/command/menu-protocol.js +4 -2
  71. package/dist/core/command/provider-menu.js +4 -2
  72. package/dist/core/command/role-menu.js +2 -2
  73. package/dist/core/command/slash-handler.js +56 -42
  74. package/dist/core/daemon-lifecycle.js +35 -17
  75. package/dist/core/event-catalog.js +19 -0
  76. package/dist/core/evolagent-registry.js +3 -0
  77. package/dist/core/handoff/runtime.js +9 -3
  78. package/dist/core/initialization/service.js +4 -3
  79. package/dist/core/ipc-registration.js +6 -0
  80. package/dist/core/message/aun-ipc-sender.js +81 -3
  81. package/dist/core/message/im-renderer.js +24 -19
  82. package/dist/core/message/message-admission.js +13 -2
  83. package/dist/core/message/response-engine.js +40 -41
  84. package/dist/core/message/send-options.js +40 -0
  85. package/dist/core/message/send-routing.js +310 -0
  86. package/dist/core/model/model-capabilities.js +37 -0
  87. package/dist/core/model/model-catalog.js +6 -2
  88. package/dist/core/ownership/owner-resolver.js +117 -14
  89. package/dist/core/permission/ec-command-parser.js +195 -27
  90. package/dist/core/permission/readonly-shell-query.js +66 -7
  91. package/dist/core/permission/tool-error-code.js +13 -1
  92. package/dist/core/permission/tool-policy.js +74 -20
  93. package/dist/core/plugin-lifecycle.js +6 -2
  94. package/dist/core/relation/pa-team.js +7 -2
  95. package/dist/core/relation/same-owner-proof.js +131 -0
  96. package/dist/core/session/session-idle-monitor.js +94 -16
  97. package/dist/core/session/session-manager.js +69 -16
  98. package/dist/core/thread/thread-route.js +5 -2
  99. package/dist/directory/owner-directory-cache.js +690 -99
  100. package/dist/directory/owner-directory-markdown.js +146 -36
  101. package/dist/directory/owner-directory-query-operation.js +7 -9
  102. package/dist/directory/owner-directory-scope.js +12 -0
  103. package/dist/directory/owner-directory-search.js +5 -1
  104. package/dist/directory/owner-directory-store.js +28 -0
  105. package/dist/ecweb/basic-settings-service.js +15 -1
  106. package/dist/ecweb/message-context-service.js +2 -2
  107. package/dist/ecweb/providers-service.js +3 -1
  108. package/dist/ecweb/runtime/lifecycle.js +38 -5
  109. package/dist/ecweb/runtime/supervisor.js +157 -49
  110. package/dist/index.js +202 -38
  111. package/dist/paths.js +2 -1
  112. package/dist/proxy/manager.js +2 -0
  113. package/dist/proxy/service-supervisor.js +379 -143
  114. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  115. package/dist/trigger/application-service.js +1 -0
  116. package/dist/trigger/audit.js +3 -2
  117. package/dist/trigger/authorization.js +2 -3
  118. package/dist/trigger/event-source.js +4 -0
  119. package/dist/trigger/feedback.js +26 -2
  120. package/dist/trigger/history.js +4 -3
  121. package/dist/trigger/ipc-service.js +24 -19
  122. package/dist/trigger/manager.js +3 -5
  123. package/dist/trigger/parser.js +4 -21
  124. package/dist/trigger/patch.js +3 -15
  125. package/dist/trigger/scheduler.js +48 -13
  126. package/dist/trigger/system-definitions.js +2 -2
  127. package/dist/trigger/validation.js +4 -13
  128. package/dist/utils/autostart.js +2 -2
  129. package/dist/utils/cross-platform.js +36 -8
  130. package/dist/utils/error-utils.js +8 -0
  131. package/dist/utils/macos-autostart.js +31 -0
  132. package/dist/utils/model-prices.jsonl +15 -8
  133. package/dist/utils/process-introspect.js +21 -1
  134. package/dist/utils/public-suffix.js +5811 -0
  135. package/dist/utils/startup-trace.js +7 -1
  136. package/dist/utils/windows-autostart.js +42 -7
  137. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  138. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  139. package/ecagent/dist/harness/env/nodejs.js +46 -2
  140. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  141. package/kits/docs/channels/aun.md +1 -1
  142. package/kits/docs/channels/feishu.md +2 -2
  143. package/kits/docs/context-assembly.md +20 -4
  144. package/kits/docs/evolcore/INDEX.md +3 -2
  145. package/kits/docs/evolcore/agent.md +2 -2
  146. package/kits/docs/evolcore/aid.md +8 -2
  147. package/kits/docs/evolcore/ctl.md +13 -4
  148. package/kits/docs/evolcore/directory.md +48 -15
  149. package/kits/docs/evolcore/file-navigation.md +63 -49
  150. package/kits/docs/evolcore/group.md +6 -6
  151. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  152. package/kits/docs/evolcore/menu-protocol.md +33 -3
  153. package/kits/docs/evolcore/model.md +5 -3
  154. package/kits/docs/evolcore/msg.md +28 -27
  155. package/kits/docs/evolcore/provider.md +39 -5
  156. package/kits/docs/evolcore/response.md +3 -1
  157. package/kits/docs/evolcore/thread-chain.md +12 -14
  158. package/kits/docs/evolcore/tool-authorization.md +21 -1
  159. package/kits/docs/evolcore/trigger.md +12 -9
  160. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  161. package/kits/docs/prompt-loading-architecture.md +30 -20
  162. package/kits/eck_manifest.auxiliary.json +5 -5
  163. package/kits/eck_manifest.json +28 -49
  164. package/kits/eck_manifest.memory.json +18 -18
  165. package/kits/rules/01-overview.md +43 -45
  166. package/kits/rules/02-navigation.md +44 -53
  167. package/kits/rules/03-identity.md +21 -25
  168. package/kits/rules/04-relation.md +23 -33
  169. package/kits/rules/05-venue.md +24 -25
  170. package/kits/rules/06-channel.md +3 -3
  171. package/kits/schemas/_meta.json +20 -27
  172. package/kits/schemas/agent-config.schema.19.json +10 -6
  173. package/kits/schemas/providers.schema.2.json +74 -0
  174. package/kits/schemas/relation-config.schema.12.json +2 -2
  175. package/kits/schemas/role-config.schema.2.json +5 -5
  176. package/kits/schemas/role-registry.schema.1.json +1 -1
  177. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  178. package/kits/skills/ec-service-proxy/SKILL.md +3 -0
  179. package/kits/skills/ec-trigger/SKILL.md +4 -4
  180. package/kits/skills/ec-trigger/references/examples.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +5 -5
  182. package/kits/templates/system-fragments/commands.md +3 -2
  183. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  184. package/kits/templates/system-fragments/identity.md +0 -1
  185. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  186. package/kits/templates/system-fragments/reply.md +47 -28
  187. package/kits/templates/system-fragments/session.md +2 -9
  188. package/kits/templates/system-fragments/thread.md +5 -5
  189. package/package.json +17 -13
  190. package/kits/schemas/agent-config.schema.20.json +0 -925
  191. package/kits/schemas/relation-config.schema.13.json +0 -289
  192. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { spawn } from 'child_process';
4
4
  import { isDevMode, resolvePaths } from '../../paths.js';
5
- import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, } from '../../config/daemon-services.js';
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
6
  import { WEB_PACKAGE_NAME } from '../../product.js';
7
7
  import { resolveGlobalPkg } from '../../utils/npm-ops.js';
8
8
  import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './launch.js';
@@ -100,17 +100,20 @@ function removeEntriesForPid(pid) {
100
100
  removeEntry(entry);
101
101
  }
102
102
  }
103
- async function probe(record) {
103
+ async function probe(record, timeoutMs) {
104
+ const signal = AbortSignal.timeout(timeoutMs);
104
105
  try {
105
106
  const response = await fetch(`http://127.0.0.1:${record.port}/api/health`, {
106
- signal: AbortSignal.timeout(1500),
107
+ signal,
107
108
  });
108
109
  if (!response.ok)
109
- return false;
110
- return matchesEcwebInstanceHealth(await response.json(), record);
110
+ return { healthy: false, reason: `HTTP ${response.status}` };
111
+ return matchesEcwebInstanceHealth(await response.json(), record)
112
+ ? { healthy: true }
113
+ : { healthy: false, reason: '健康响应或实例身份不匹配' };
111
114
  }
112
115
  catch {
113
- return false;
116
+ return { healthy: false, reason: signal.aborted ? `健康请求超时 (${timeoutMs}ms)` : '健康请求失败或响应 JSON 无效' };
114
117
  }
115
118
  }
116
119
  /**
@@ -122,7 +125,8 @@ async function probe(record) {
122
125
  * ECWeb's own stale-instance cleanup, and daemon startup.
123
126
  */
124
127
  export function createEcwebSupervisor(options) {
125
- const failureThreshold = Math.max(1, options.failureThreshold ?? 3);
128
+ let healthConfig = options.health;
129
+ let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
126
130
  let desiredPort = options.port;
127
131
  let desiredEnabled = options.enabled ?? true;
128
132
  let runtimeMode = options.runtimeMode ?? 'managed';
@@ -132,11 +136,15 @@ export function createEcwebSupervisor(options) {
132
136
  let logFd = null;
133
137
  let timer = null;
134
138
  let failureCount = 0;
139
+ let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
135
140
  let healthy = false;
136
141
  let startInFlight = null;
137
142
  let childStartedAt = 0;
138
143
  let childIdentityStartedAt = null;
139
144
  let stopping = false;
145
+ let stopInFlight = null;
146
+ const stopTimingListeners = new Set();
147
+ const completedStopTimings = [];
140
148
  let checkInFlight = null;
141
149
  let startup = null;
142
150
  let restartInFlight = null;
@@ -144,10 +152,20 @@ export function createEcwebSupervisor(options) {
144
152
  let recoveryAttempts = [];
145
153
  let recoveryExhausted = false;
146
154
  let intentionalStop = false;
155
+ const expectedChildExits = new WeakSet();
147
156
  let launchRequested = false;
148
157
  let hasBeenReady = false;
149
158
  let configureQueue = Promise.resolve();
150
159
  const logFile = path.join(resolvePaths().logs, 'ecweb-daemon.log');
160
+ const reportStopTiming = (timing) => {
161
+ completedStopTimings.push(timing);
162
+ for (const listener of stopTimingListeners) {
163
+ try {
164
+ listener(timing);
165
+ }
166
+ catch { }
167
+ }
168
+ };
151
169
  const setActiveFromEntry = (entry, owned) => {
152
170
  active = {
153
171
  pid: entry.record.pid,
@@ -160,21 +178,28 @@ export function createEcwebSupervisor(options) {
160
178
  };
161
179
  };
162
180
  const findHealthyInstance = async () => {
181
+ lastHealthFailure = '未发现有效的 ECWeb 实例注册';
163
182
  for (const entry of readEntries()) {
164
183
  if (!isAlive(entry.record)) {
184
+ lastHealthFailure = '实例进程不存在';
165
185
  removeEntry(entry);
166
186
  continue;
167
187
  }
168
188
  const actual = getProcessStartTime(entry.record.pid);
169
189
  if (actual !== null && entry.record.startedAt !== undefined
170
190
  && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
191
+ lastHealthFailure = '实例 PID 启动时间不匹配';
171
192
  removeEntry(entry);
172
193
  continue;
173
194
  }
174
- if (entry.record.port !== desiredPort)
195
+ if (entry.record.port !== desiredPort) {
196
+ lastHealthFailure = `实例端口与配置不匹配 (期望: ${desiredPort})`;
175
197
  continue;
176
- if (await probe(entry.record))
198
+ }
199
+ const result = await probe(entry.record, healthConfig?.timeoutMs ?? 1500);
200
+ if (result.healthy)
177
201
  return entry;
202
+ lastHealthFailure = result.reason;
178
203
  }
179
204
  return null;
180
205
  };
@@ -199,23 +224,44 @@ export function createEcwebSupervisor(options) {
199
224
  catch { }
200
225
  logFd = null;
201
226
  };
202
- const killActive = async () => {
227
+ const stopTrackedProcess = (identity, onTiming) => {
228
+ const target = child?.pid === identity.pid ? child : null;
229
+ const requestShutdown = target?.connected ? () => {
230
+ try {
231
+ if (!target.connected)
232
+ return false;
233
+ // The callback handles an asynchronously closed channel without an
234
+ // unhandled child 'error' event. Exit confirmation remains separate.
235
+ target.send({ type: 'ecweb.shutdown' }, () => { });
236
+ return true;
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ } : undefined;
242
+ return stopEcwebProcess(identity, undefined, onTiming, requestShutdown);
243
+ };
244
+ const killActive = async (onTiming) => {
203
245
  intentionalStop = true;
204
246
  const current = active;
247
+ // Keep stop intent with the child: its exit event may arrive after a
248
+ // replacement has reset the supervisor's intentionalStop flag.
249
+ if (child && (!current || child.pid === current.pid))
250
+ expectedChildExits.add(child);
205
251
  if (!current) {
206
252
  // During the short window between spawn() and ECWeb writing its
207
253
  // instance record there is no `active` entry yet, but the daemon still
208
254
  // owns the child and must not leave it behind on shutdown.
209
255
  const pendingPid = child?.pid;
210
256
  if (pendingPid && platform.isProcessRunning(pendingPid)) {
211
- await stopEcwebProcess({ pid: pendingPid, startedAt: childIdentityStartedAt });
257
+ await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
212
258
  }
213
259
  child = null;
214
260
  childIdentityStartedAt = null;
215
261
  healthy = false;
216
262
  return;
217
263
  }
218
- await stopEcwebProcess({ pid: current.pid, startedAt: current.startedAt });
264
+ await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
219
265
  removeEntriesForPid(current.pid);
220
266
  active = null;
221
267
  child = null;
@@ -223,8 +269,11 @@ export function createEcwebSupervisor(options) {
223
269
  healthy = false;
224
270
  };
225
271
  const spawnEcweb = async () => {
272
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
273
+ return;
226
274
  intentionalStop = false;
227
275
  hasBeenReady = false;
276
+ failureCount = 0;
228
277
  const root = resolvePaths().root;
229
278
  const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
230
279
  const globalPkg = resolveGlobalPkg(WEB_PACKAGE_NAME);
@@ -282,7 +331,7 @@ export function createEcwebSupervisor(options) {
282
331
  spawned = spawn(launch.command, launch.args, {
283
332
  cwd,
284
333
  detached: true,
285
- stdio: ['ignore', childLogFd, childLogFd],
334
+ stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
286
335
  windowsHide: platform.isWindows,
287
336
  env: {
288
337
  ...process.env,
@@ -310,8 +359,13 @@ export function createEcwebSupervisor(options) {
310
359
  scheduleRecovery();
311
360
  });
312
361
  spawned.once('exit', (code, signal) => {
313
- options.logger.warn(`ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
314
- const diagnostics = child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
362
+ const expectedExit = stopping || expectedChildExits.has(spawned);
363
+ const exitMessage = `ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`;
364
+ if (expectedExit)
365
+ options.logger.info(`${exitMessage},主动停止`);
366
+ else
367
+ options.logger.warn(exitMessage);
368
+ const diagnostics = !expectedExit && child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
315
369
  if (diagnostics)
316
370
  options.logger.warn(`ECWeb 退出诊断(最近日志,含异常栈如有):\n${diagnostics}`);
317
371
  if (child === spawned) {
@@ -319,7 +373,7 @@ export function createEcwebSupervisor(options) {
319
373
  childStartedAt = 0;
320
374
  childIdentityStartedAt = null;
321
375
  healthy = false;
322
- if (!stopping && !intentionalStop) {
376
+ if (!expectedExit) {
323
377
  if (active?.pid === spawned.pid)
324
378
  active = null;
325
379
  failureCount = failureThreshold;
@@ -336,6 +390,7 @@ export function createEcwebSupervisor(options) {
336
390
  closeLogStream();
337
391
  });
338
392
  spawned.unref();
393
+ spawned.channel?.unref();
339
394
  if (!spawned.pid) {
340
395
  closeLogStream();
341
396
  options.logger.warn('ECWeb 启动失败:未取得子进程 PID');
@@ -353,6 +408,14 @@ export function createEcwebSupervisor(options) {
353
408
  // Allow the child to bind and publish its instance record before treating
354
409
  // it as crashed. Daemon readiness is not required for HTTP liveness.
355
410
  const instance = await findHealthyInstance();
411
+ if (stopping) {
412
+ // 保留已核验的实例身份供 stop 清理,但不再接管运行状态或进入恢复分支。
413
+ if (instance)
414
+ setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
415
+ return;
416
+ }
417
+ if (!desiredEnabled || runtimeMode !== 'managed')
418
+ return;
356
419
  healthy = instance !== null;
357
420
  if (instance) {
358
421
  launchRequested = false;
@@ -366,9 +429,15 @@ export function createEcwebSupervisor(options) {
366
429
  return;
367
430
  }
368
431
  if (!launchRequested && !hasBeenReady && child?.pid && platform.isProcessRunning(child.pid)
369
- && Date.now() - childStartedAt < 45_000)
432
+ && Date.now() - childStartedAt < (healthConfig?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS))
370
433
  return;
371
434
  if (launchRequested) {
435
+ // A successful probe above cancels recovery without spending a retry.
436
+ // Charge the allowance only when an automatic restart actually begins.
437
+ if (launchRequested === 'recovery') {
438
+ recoveryAttempts.push(Date.now());
439
+ options.logger.warn(`ECWeb 自动恢复执行 (尝试: ${recoveryAttempts.length}/${SERVICE_RESTART_MAX_ATTEMPTS}, PID: ${active?.pid ?? child?.pid ?? 'unknown'})`);
440
+ }
372
441
  launchRequested = false;
373
442
  startInFlight = (async () => {
374
443
  await killActive();
@@ -380,6 +449,8 @@ export function createEcwebSupervisor(options) {
380
449
  failureCount += 1;
381
450
  if (failureCount < failureThreshold)
382
451
  return;
452
+ if (failureCount === failureThreshold)
453
+ options.logger.warn(`ECWeb 健康检查未通过 (PID: ${active?.pid ?? child?.pid ?? 'unknown'}, 连续失败: ${failureCount}, 启动后: ${childStartedAt ? Date.now() - childStartedAt : 0}ms, 原因: ${lastHealthFailure})`);
383
454
  scheduleRecovery();
384
455
  };
385
456
  const check = () => {
@@ -395,7 +466,7 @@ export function createEcwebSupervisor(options) {
395
466
  };
396
467
  const scheduleRecovery = () => {
397
468
  if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
398
- || restartConfig?.enabled === false || recoveryTimer || recoveryExhausted)
469
+ || restartConfig?.enabled === false || recoveryTimer || launchRequested || recoveryExhausted)
399
470
  return;
400
471
  const now = Date.now();
401
472
  recoveryAttempts = recoveryAttempts.filter(timestamp => now - timestamp <= SERVICE_RESTART_WINDOW_MS);
@@ -404,13 +475,13 @@ export function createEcwebSupervisor(options) {
404
475
  options.logger.error('ECWeb 自动恢复已达到 15 分钟内 3 次上限,请修复后 reset-failure');
405
476
  return;
406
477
  }
407
- recoveryAttempts.push(now);
408
- const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** (recoveryAttempts.length - 1));
478
+ const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** recoveryAttempts.length);
479
+ options.logger.warn(`ECWeb 自动恢复排期 (尝试: ${recoveryAttempts.length + 1}/${SERVICE_RESTART_MAX_ATTEMPTS}, 退避: ${delay}ms)`);
409
480
  recoveryTimer = setTimeout(() => {
410
481
  recoveryTimer = null;
411
482
  if (stopping || !desiredEnabled || runtimeMode !== 'managed' || restartConfig?.enabled === false)
412
483
  return;
413
- launchRequested = true;
484
+ launchRequested = 'recovery';
414
485
  void check().catch(error => options.logger.error('ECWeb 自动恢复失败: ' + String(error)));
415
486
  }, delay);
416
487
  recoveryTimer.unref?.();
@@ -428,9 +499,13 @@ export function createEcwebSupervisor(options) {
428
499
  await checkInFlight.catch(() => { });
429
500
  if (startInFlight)
430
501
  await startInFlight.catch(() => { });
502
+ if (stopping)
503
+ return;
431
504
  await killActive();
505
+ if (stopping)
506
+ return;
432
507
  failureCount = failureThreshold;
433
- launchRequested = true;
508
+ launchRequested = 'manual';
434
509
  await check();
435
510
  })().finally(() => { restartInFlight = null; });
436
511
  return restartInFlight;
@@ -456,8 +531,11 @@ export function createEcwebSupervisor(options) {
456
531
  }
457
532
  // Give an independently started ECWeb time to publish its instance record.
458
533
  const existing = await waitForHealthyInstance(1_500);
459
- if (stopping)
534
+ if (stopping) {
535
+ if (existing)
536
+ setActiveFromEntry(existing, false);
460
537
  return;
538
+ }
461
539
  if (existing) {
462
540
  healthy = true;
463
541
  hasBeenReady = true;
@@ -466,7 +544,7 @@ export function createEcwebSupervisor(options) {
466
544
  }
467
545
  else {
468
546
  failureCount = failureThreshold;
469
- launchRequested = true;
547
+ launchRequested = 'manual';
470
548
  await check();
471
549
  }
472
550
  if (stopping)
@@ -481,11 +559,14 @@ export function createEcwebSupervisor(options) {
481
559
  const nextMode = config.runtimeMode ?? 'managed';
482
560
  const modeChanged = nextMode !== runtimeMode;
483
561
  const recoveryChanged = JSON.stringify(config.restart) !== JSON.stringify(restartConfig);
562
+ const healthChanged = JSON.stringify(config.health) !== JSON.stringify(healthConfig);
484
563
  desiredEnabled = config.enabled;
485
564
  desiredPort = config.port;
486
565
  runtimeMode = nextMode;
487
566
  restartConfig = config.restart;
488
- if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged)
567
+ healthConfig = config.health;
568
+ failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
569
+ if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged && !healthChanged)
489
570
  return;
490
571
  cancelRecovery();
491
572
  if (checkInFlight)
@@ -507,7 +588,7 @@ export function createEcwebSupervisor(options) {
507
588
  recoveryAttempts = [];
508
589
  recoveryExhausted = false;
509
590
  failureCount = desiredEnabled ? failureThreshold : 0;
510
- launchRequested = desiredEnabled;
591
+ launchRequested = desiredEnabled ? 'manual' : false;
511
592
  if (desiredEnabled && !stopping)
512
593
  await check();
513
594
  }
@@ -547,38 +628,65 @@ export function createEcwebSupervisor(options) {
547
628
  ...(running ? { pid: active.pid } : {}),
548
629
  };
549
630
  },
550
- async stop() {
551
- if (stopping)
552
- return;
631
+ stop(onTiming) {
632
+ if (onTiming) {
633
+ stopTimingListeners.add(onTiming);
634
+ for (const timing of completedStopTimings) {
635
+ try {
636
+ onTiming(timing);
637
+ }
638
+ catch { }
639
+ }
640
+ }
641
+ if (stopInFlight)
642
+ return stopInFlight;
553
643
  stopping = true;
644
+ launchRequested = false;
554
645
  cancelRecovery();
555
646
  if (timer)
556
647
  clearTimeout(timer);
557
648
  timer = null;
558
- if (startup)
559
- await startup.catch(() => { });
560
- if (checkInFlight)
561
- await checkInFlight.catch(() => { });
562
- if (restartInFlight)
563
- await restartInFlight.catch(() => { });
564
- await configureQueue.catch(() => { });
565
- if (startInFlight) {
649
+ const waitForOperation = async (phase, operation) => {
650
+ if (!operation)
651
+ return;
652
+ const startMs = Date.now();
653
+ let detail;
566
654
  try {
567
- await startInFlight;
655
+ await operation;
568
656
  }
569
- catch { }
570
- }
571
- if (runtimeMode === 'managed')
572
- await killActive();
573
- if (child) {
657
+ catch (error) {
658
+ detail = `失败: ${error instanceof Error ? error.message : String(error)}`;
659
+ }
660
+ finally {
661
+ try {
662
+ onTiming?.({ phase, startMs, endMs: Date.now(), detail });
663
+ }
664
+ catch { }
665
+ }
666
+ };
667
+ stopInFlight = (async () => {
574
668
  try {
575
- child.removeAllListeners();
669
+ await waitForOperation('startup', startup);
670
+ await waitForOperation('healthCheck', checkInFlight);
671
+ await waitForOperation('restart', restartInFlight);
672
+ await waitForOperation('configure', configureQueue);
673
+ await waitForOperation('launch', startInFlight);
674
+ if (runtimeMode === 'managed')
675
+ await killActive(reportStopTiming);
576
676
  }
577
- catch { }
578
- child = null;
579
- childStartedAt = 0;
580
- }
581
- closeLogStream();
677
+ finally {
678
+ if (child) {
679
+ try {
680
+ child.removeAllListeners();
681
+ }
682
+ catch { }
683
+ child = null;
684
+ childStartedAt = 0;
685
+ }
686
+ closeLogStream();
687
+ }
688
+ })();
689
+ return stopInFlight;
582
690
  },
583
691
  };
584
692
  }