evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  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 +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -2,12 +2,12 @@ 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
- import { resolveGlobalPkg } from '../../utils/npm-ops.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';
@@ -52,7 +52,7 @@ function readExitDiagnostics(filePath, startOffset) {
52
52
  }
53
53
  }
54
54
  }
55
- function isAlive(record) {
55
+ async function isAlive(record) {
56
56
  if (!Number.isInteger(record.pid) || record.pid <= 0)
57
57
  return false;
58
58
  // ECWeb versions before the supervisor used a different Linux boot-time
@@ -61,7 +61,7 @@ function isAlive(record) {
61
61
  // scoped to this EVOLCORE_HOME; use liveness here and let the HTTP probe be
62
62
  // the ownership/health check. PID/start-time validation remains in the
63
63
  // explicit kill path below.
64
- return platform.isProcessRunning(record.pid);
64
+ return platform.isProcessRunningAsync(record.pid);
65
65
  }
66
66
  function readEntries() {
67
67
  const dir = resolvePaths().instanceDir;
@@ -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,9 @@ 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
+ const settleInitialHealth = options.startupTrace?.startTask('daemon.ecwebHealthReady');
129
+ let healthConfig = options.health;
130
+ let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
126
131
  let desiredPort = options.port;
127
132
  let desiredEnabled = options.enabled ?? true;
128
133
  let runtimeMode = options.runtimeMode ?? 'managed';
@@ -132,6 +137,7 @@ export function createEcwebSupervisor(options) {
132
137
  let logFd = null;
133
138
  let timer = null;
134
139
  let failureCount = 0;
140
+ let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
135
141
  let healthy = false;
136
142
  let startInFlight = null;
137
143
  let childStartedAt = 0;
@@ -147,6 +153,7 @@ export function createEcwebSupervisor(options) {
147
153
  let recoveryAttempts = [];
148
154
  let recoveryExhausted = false;
149
155
  let intentionalStop = false;
156
+ const expectedChildExits = new WeakSet();
150
157
  let launchRequested = false;
151
158
  let hasBeenReady = false;
152
159
  let configureQueue = Promise.resolve();
@@ -160,33 +167,40 @@ export function createEcwebSupervisor(options) {
160
167
  catch { }
161
168
  }
162
169
  };
163
- const setActiveFromEntry = (entry, owned) => {
170
+ const setActiveFromEntry = async (entry, owned) => {
164
171
  active = {
165
172
  pid: entry.record.pid,
166
173
  port: entry.record.port,
167
174
  // Capture the current PID start time rather than trusting the record.
168
175
  // Older ECWeb builds could write a clock-skewed `startedAt` value.
169
- startedAt: getProcessStartTime(entry.record.pid)
176
+ startedAt: await getProcessStartTimeAsync(entry.record.pid)
170
177
  ?? (typeof entry.record.startedAt === 'number' ? entry.record.startedAt : null),
171
178
  owned,
172
179
  };
173
180
  };
174
181
  const findHealthyInstance = async () => {
182
+ lastHealthFailure = '未发现有效的 ECWeb 实例注册';
175
183
  for (const entry of readEntries()) {
176
- if (!isAlive(entry.record)) {
184
+ if (!await isAlive(entry.record)) {
185
+ lastHealthFailure = '实例进程不存在';
177
186
  removeEntry(entry);
178
187
  continue;
179
188
  }
180
- const actual = getProcessStartTime(entry.record.pid);
189
+ const actual = await getProcessStartTimeAsync(entry.record.pid);
181
190
  if (actual !== null && entry.record.startedAt !== undefined
182
191
  && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
192
+ lastHealthFailure = '实例 PID 启动时间不匹配';
183
193
  removeEntry(entry);
184
194
  continue;
185
195
  }
186
- if (entry.record.port !== desiredPort)
196
+ if (entry.record.port !== desiredPort) {
197
+ lastHealthFailure = `实例端口与配置不匹配 (期望: ${desiredPort})`;
187
198
  continue;
188
- if (await probe(entry.record))
199
+ }
200
+ const result = await probe(entry.record, healthConfig?.timeoutMs ?? 1500);
201
+ if (result.healthy)
189
202
  return entry;
203
+ lastHealthFailure = result.reason;
190
204
  }
191
205
  return null;
192
206
  };
@@ -211,23 +225,44 @@ export function createEcwebSupervisor(options) {
211
225
  catch { }
212
226
  logFd = null;
213
227
  };
228
+ const stopTrackedProcess = (identity, onTiming) => {
229
+ const target = child?.pid === identity.pid ? child : null;
230
+ const requestShutdown = target?.connected ? () => {
231
+ try {
232
+ if (!target.connected)
233
+ return false;
234
+ // The callback handles an asynchronously closed channel without an
235
+ // unhandled child 'error' event. Exit confirmation remains separate.
236
+ target.send({ type: 'ecweb.shutdown' }, () => { });
237
+ return true;
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ } : undefined;
243
+ return stopEcwebProcess(identity, undefined, onTiming, requestShutdown);
244
+ };
214
245
  const killActive = async (onTiming) => {
215
246
  intentionalStop = true;
216
247
  const current = active;
248
+ // Keep stop intent with the child: its exit event may arrive after a
249
+ // replacement has reset the supervisor's intentionalStop flag.
250
+ if (child && (!current || child.pid === current.pid))
251
+ expectedChildExits.add(child);
217
252
  if (!current) {
218
253
  // During the short window between spawn() and ECWeb writing its
219
254
  // instance record there is no `active` entry yet, but the daemon still
220
255
  // owns the child and must not leave it behind on shutdown.
221
256
  const pendingPid = child?.pid;
222
- if (pendingPid && platform.isProcessRunning(pendingPid)) {
223
- await stopEcwebProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, undefined, onTiming);
257
+ if (pendingPid && (await platform.isProcessRunningAsync(pendingPid))) {
258
+ await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
224
259
  }
225
260
  child = null;
226
261
  childIdentityStartedAt = null;
227
262
  healthy = false;
228
263
  return;
229
264
  }
230
- await stopEcwebProcess({ pid: current.pid, startedAt: current.startedAt }, undefined, onTiming);
265
+ await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
231
266
  removeEntriesForPid(current.pid);
232
267
  active = null;
233
268
  child = null;
@@ -239,9 +274,12 @@ export function createEcwebSupervisor(options) {
239
274
  return;
240
275
  intentionalStop = false;
241
276
  hasBeenReady = false;
277
+ failureCount = 0;
242
278
  const root = resolvePaths().root;
243
279
  const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
244
- const globalPkg = resolveGlobalPkg(WEB_PACKAGE_NAME);
280
+ const globalPkg = await resolveGlobalPkgAsync(WEB_PACKAGE_NAME);
281
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
282
+ return;
245
283
  let launch = resolveEcwebLaunchCommand(['--home', root, '--port', String(desiredPort)], {
246
284
  installedPkg: globalPkg,
247
285
  });
@@ -276,7 +314,9 @@ export function createEcwebSupervisor(options) {
276
314
  scheduleRecovery();
277
315
  return;
278
316
  }
279
- const occupiedPids = platform.findProcessByPort(desiredPort);
317
+ const occupiedPids = await platform.findProcessByPortAsync(desiredPort);
318
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
319
+ return;
280
320
  if (occupiedPids.length > 0) {
281
321
  options.logger.error(`ECWeb 启动已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
282
322
  failureCount = failureThreshold;
@@ -296,7 +336,7 @@ export function createEcwebSupervisor(options) {
296
336
  spawned = spawn(launch.command, launch.args, {
297
337
  cwd,
298
338
  detached: true,
299
- stdio: ['ignore', childLogFd, childLogFd],
339
+ stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
300
340
  windowsHide: platform.isWindows,
301
341
  env: {
302
342
  ...process.env,
@@ -315,7 +355,6 @@ export function createEcwebSupervisor(options) {
315
355
  closeLogStream();
316
356
  child = spawned;
317
357
  childStartedAt = Date.now();
318
- childIdentityStartedAt = spawned.pid ? getProcessStartTime(spawned.pid) : null;
319
358
  spawned.once('error', (error) => {
320
359
  options.logger.error(`ECWeb 子进程创建失败: ${error.message}`);
321
360
  if (child !== spawned || intentionalStop || stopping)
@@ -324,8 +363,13 @@ export function createEcwebSupervisor(options) {
324
363
  scheduleRecovery();
325
364
  });
326
365
  spawned.once('exit', (code, signal) => {
327
- options.logger.warn(`ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
328
- const diagnostics = child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
366
+ const expectedExit = stopping || expectedChildExits.has(spawned);
367
+ const exitMessage = `ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`;
368
+ if (expectedExit)
369
+ options.logger.info(`${exitMessage},主动停止`);
370
+ else
371
+ options.logger.warn(exitMessage);
372
+ const diagnostics = !expectedExit && child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
329
373
  if (diagnostics)
330
374
  options.logger.warn(`ECWeb 退出诊断(最近日志,含异常栈如有):\n${diagnostics}`);
331
375
  if (child === spawned) {
@@ -333,28 +377,26 @@ export function createEcwebSupervisor(options) {
333
377
  childStartedAt = 0;
334
378
  childIdentityStartedAt = null;
335
379
  healthy = false;
336
- if (!stopping && !intentionalStop) {
380
+ if (!expectedExit) {
337
381
  if (active?.pid === spawned.pid)
338
382
  active = null;
339
383
  failureCount = failureThreshold;
340
- const occupiedPids = platform.findProcessByPort(desiredPort);
341
- if (occupiedPids.length > 0) {
342
- recoveryExhausted = true;
343
- options.logger.error(`ECWeb 自动恢复已停止:端口 ${desiredPort} 被占用 (PID: ${occupiedPids.join(', ')})`);
344
- }
345
- else {
346
- scheduleRecovery();
347
- }
384
+ scheduleRecovery();
348
385
  }
349
386
  }
350
387
  closeLogStream();
351
388
  });
352
389
  spawned.unref();
390
+ spawned.channel?.unref();
353
391
  if (!spawned.pid) {
354
392
  closeLogStream();
355
393
  options.logger.warn('ECWeb 启动失败:未取得子进程 PID');
356
394
  return;
357
395
  }
396
+ const startedAt = await getProcessStartTimeAsync(spawned.pid);
397
+ if (child !== spawned)
398
+ return;
399
+ childIdentityStartedAt = startedAt;
358
400
  options.logger.info(`✓ ECWeb supervisor 已启动 (PID: ${spawned.pid}),日志: ${logFile}`);
359
401
  // ECWeb writes its own instance record after binding. Do not fabricate a
360
402
  // record here; the watchdog will adopt the real record on its next tick.
@@ -370,7 +412,7 @@ export function createEcwebSupervisor(options) {
370
412
  if (stopping) {
371
413
  // 保留已核验的实例身份供 stop 清理,但不再接管运行状态或进入恢复分支。
372
414
  if (instance)
373
- setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
415
+ await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
374
416
  return;
375
417
  }
376
418
  if (!desiredEnabled || runtimeMode !== 'managed')
@@ -380,17 +422,28 @@ export function createEcwebSupervisor(options) {
380
422
  launchRequested = false;
381
423
  cancelRecovery();
382
424
  const changed = !active || active.pid !== instance.record.pid || active.port !== instance.record.port;
383
- setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
425
+ await setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
426
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
427
+ return;
384
428
  failureCount = 0;
385
429
  hasBeenReady = true;
430
+ settleInitialHealth?.('ok');
386
431
  if (changed)
387
432
  options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${instance.record.pid}, 端口: ${instance.record.port})`);
388
433
  return;
389
434
  }
390
- if (!launchRequested && !hasBeenReady && child?.pid && platform.isProcessRunning(child.pid)
391
- && Date.now() - childStartedAt < 45_000)
435
+ if (!launchRequested && !hasBeenReady && child?.pid && (await platform.isProcessRunningAsync(child.pid))
436
+ && Date.now() - childStartedAt < (healthConfig?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS))
437
+ return;
438
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed')
392
439
  return;
393
440
  if (launchRequested) {
441
+ // A successful probe above cancels recovery without spending a retry.
442
+ // Charge the allowance only when an automatic restart actually begins.
443
+ if (launchRequested === 'recovery') {
444
+ recoveryAttempts.push(Date.now());
445
+ options.logger.warn(`ECWeb 自动恢复执行 (尝试: ${recoveryAttempts.length}/${SERVICE_RESTART_MAX_ATTEMPTS}, PID: ${active?.pid ?? child?.pid ?? 'unknown'})`);
446
+ }
394
447
  launchRequested = false;
395
448
  startInFlight = (async () => {
396
449
  await killActive();
@@ -402,6 +455,8 @@ export function createEcwebSupervisor(options) {
402
455
  failureCount += 1;
403
456
  if (failureCount < failureThreshold)
404
457
  return;
458
+ if (failureCount === failureThreshold)
459
+ options.logger.warn(`ECWeb 健康检查未通过 (PID: ${active?.pid ?? child?.pid ?? 'unknown'}, 连续失败: ${failureCount}, 启动后: ${childStartedAt ? Date.now() - childStartedAt : 0}ms, 原因: ${lastHealthFailure})`);
405
460
  scheduleRecovery();
406
461
  };
407
462
  const check = () => {
@@ -416,8 +471,10 @@ export function createEcwebSupervisor(options) {
416
471
  recoveryTimer = null;
417
472
  };
418
473
  const scheduleRecovery = () => {
474
+ if (!healthy && desiredEnabled && !stopping)
475
+ settleInitialHealth?.('failed');
419
476
  if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
420
- || restartConfig?.enabled === false || recoveryTimer || recoveryExhausted)
477
+ || restartConfig?.enabled === false || recoveryTimer || launchRequested || recoveryExhausted)
421
478
  return;
422
479
  const now = Date.now();
423
480
  recoveryAttempts = recoveryAttempts.filter(timestamp => now - timestamp <= SERVICE_RESTART_WINDOW_MS);
@@ -426,13 +483,13 @@ export function createEcwebSupervisor(options) {
426
483
  options.logger.error('ECWeb 自动恢复已达到 15 分钟内 3 次上限,请修复后 reset-failure');
427
484
  return;
428
485
  }
429
- recoveryAttempts.push(now);
430
- const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** (recoveryAttempts.length - 1));
486
+ const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** recoveryAttempts.length);
487
+ options.logger.warn(`ECWeb 自动恢复排期 (尝试: ${recoveryAttempts.length + 1}/${SERVICE_RESTART_MAX_ATTEMPTS}, 退避: ${delay}ms)`);
431
488
  recoveryTimer = setTimeout(() => {
432
489
  recoveryTimer = null;
433
490
  if (stopping || !desiredEnabled || runtimeMode !== 'managed' || restartConfig?.enabled === false)
434
491
  return;
435
- launchRequested = true;
492
+ launchRequested = 'recovery';
436
493
  void check().catch(error => options.logger.error('ECWeb 自动恢复失败: ' + String(error)));
437
494
  }, delay);
438
495
  recoveryTimer.unref?.();
@@ -456,7 +513,7 @@ export function createEcwebSupervisor(options) {
456
513
  if (stopping)
457
514
  return;
458
515
  failureCount = failureThreshold;
459
- launchRequested = true;
516
+ launchRequested = 'manual';
460
517
  await check();
461
518
  })().finally(() => { restartInFlight = null; });
462
519
  return restartInFlight;
@@ -477,6 +534,7 @@ export function createEcwebSupervisor(options) {
477
534
  if (stopping)
478
535
  return;
479
536
  if (!desiredEnabled || runtimeMode !== 'managed') {
537
+ settleInitialHealth?.('skipped');
480
538
  scheduleCheck();
481
539
  return;
482
540
  }
@@ -484,18 +542,19 @@ export function createEcwebSupervisor(options) {
484
542
  const existing = await waitForHealthyInstance(1_500);
485
543
  if (stopping) {
486
544
  if (existing)
487
- setActiveFromEntry(existing, false);
545
+ await setActiveFromEntry(existing, false);
488
546
  return;
489
547
  }
490
548
  if (existing) {
491
549
  healthy = true;
492
550
  hasBeenReady = true;
493
- setActiveFromEntry(existing, false);
551
+ await setActiveFromEntry(existing, false);
494
552
  options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
553
+ settleInitialHealth?.('ok');
495
554
  }
496
555
  else {
497
556
  failureCount = failureThreshold;
498
- launchRequested = true;
557
+ launchRequested = 'manual';
499
558
  await check();
500
559
  }
501
560
  if (stopping)
@@ -510,11 +569,16 @@ export function createEcwebSupervisor(options) {
510
569
  const nextMode = config.runtimeMode ?? 'managed';
511
570
  const modeChanged = nextMode !== runtimeMode;
512
571
  const recoveryChanged = JSON.stringify(config.restart) !== JSON.stringify(restartConfig);
572
+ const healthChanged = JSON.stringify(config.health) !== JSON.stringify(healthConfig);
513
573
  desiredEnabled = config.enabled;
514
574
  desiredPort = config.port;
515
575
  runtimeMode = nextMode;
576
+ if (!desiredEnabled || runtimeMode !== 'managed')
577
+ settleInitialHealth?.('skipped');
516
578
  restartConfig = config.restart;
517
- if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged)
579
+ healthConfig = config.health;
580
+ failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
581
+ if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged && !healthChanged)
518
582
  return;
519
583
  cancelRecovery();
520
584
  if (checkInFlight)
@@ -536,7 +600,7 @@ export function createEcwebSupervisor(options) {
536
600
  recoveryAttempts = [];
537
601
  recoveryExhausted = false;
538
602
  failureCount = desiredEnabled ? failureThreshold : 0;
539
- launchRequested = desiredEnabled;
603
+ launchRequested = desiredEnabled ? 'manual' : false;
540
604
  if (desiredEnabled && !stopping)
541
605
  await check();
542
606
  }
@@ -552,7 +616,10 @@ export function createEcwebSupervisor(options) {
552
616
  return {
553
617
  start() {
554
618
  if (!startup)
555
- startup = start();
619
+ startup = start().catch(error => {
620
+ settleInitialHealth?.('failed');
621
+ throw error;
622
+ });
556
623
  return startup;
557
624
  },
558
625
  configure(config) {
@@ -567,7 +634,8 @@ export function createEcwebSupervisor(options) {
567
634
  await restart();
568
635
  },
569
636
  status() {
570
- const running = active && platform.isProcessRunning(active.pid);
637
+ // Report the latest supervised state; status reads must not run tasklist.
638
+ const running = active !== null;
571
639
  const ready = running && healthy && active.port === desiredPort;
572
640
  return {
573
641
  enabled: desiredEnabled,
@@ -577,6 +645,7 @@ export function createEcwebSupervisor(options) {
577
645
  };
578
646
  },
579
647
  stop(onTiming) {
648
+ settleInitialHealth?.('cancelled');
580
649
  if (onTiming) {
581
650
  stopTimingListeners.add(onTiming);
582
651
  for (const timing of completedStopTimings) {