evolcore 0.0.41-test.0 → 0.0.41-test.2

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 (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -1,6 +1,5 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import os from 'os';
4
3
  import { spawn, execFile } from 'child_process';
5
4
  import { promisify } from 'util';
6
5
  import readline from 'readline';
@@ -20,23 +19,21 @@ import { ecwebVersionRequirementError, resolveEcwebLaunchCommand, resolveEcwebEx
20
19
  import { isHostChinese } from '../utils/locale.js';
21
20
  import { scanInstances, cleanupInstances, findOrphanProcesses } from '../utils/instance-registry.js';
22
21
  import { filterLogFiles, deriveLogTypes, computePreChecked, validateLogTypes, shortLogName as shortLogNameLocal, isWatchLogFile } from './watch-logs.js';
23
- import { displaySessionTitle } from '../core/session/session-title.js';
24
- import { isNonAgentSessionChannel } from '../core/system-channels.js';
25
22
  import { printCodeStats } from './code-stats.js';
26
23
  import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.js';
24
+ import { matchesEcwebInstanceHealth, parseEcwebInstanceRecord } from '../contracts/ecweb-instance.js';
27
25
  import { AGENT_DELEGATION_TOKEN_ENV, readDelegationCredential } from '../core/auth/agent-delegation.js';
28
26
  import { MAIN_CLI_BIN, RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, TARGET_PACKAGE_ROOT_ENV, WEB_CLI_BIN, WEB_PACKAGE_NAME, } from '../product.js';
29
27
  import { readRestartRequest, updateRestartRequest } from '../utils/restart-safety.js';
30
28
  import { rotateStdoutLog } from '../utils/log-writer.js';
31
29
  import { inspectDataMigrationRequirement } from '../core/data-migration.js';
32
30
  import { isInitCancelledError, printInitCancelHint } from './init-cancel.js';
33
- import { computeBuildId } from '../utils/evolcore-version.js';
31
+ import { readFastaunVersion } from '../utils/evolcore-version.js';
34
32
  import { readHostInfo } from '../utils/host-info.js';
35
33
  import { queryStatusActivity, queryStatusActivityByAgent } from '../stats/query.js';
36
34
  import { listCodexAppServerProcesses, unregisterCodexAppServerProcess } from '../agents/codex/app-server-registry.js';
37
35
  import { DEFAULT_ECWEB_PORT, ecwebService, setEcwebEnabled } from '../config/daemon-services.js';
38
36
  import { checkCodexProjectPath, inspectCodexManagedHook, ensureCodexManagedHook, runCodexHookLaunchDiagnostic, } from '../agents/codex/diagnostics.js';
39
- import { isTopicThreadId } from '../core/thread/topic-id.js';
40
37
  import { formatClaudeSandboxDependencies, formatCodexSandboxAvailability, inspectClaudeSandboxDependencies, inspectCodexSandboxAvailability, probeClaudeSandboxDependencies, probeCodexSandboxAvailability, } from '../core/permission/sandbox-runtime.js';
41
38
  const execFileAsync = promisify(execFile);
42
39
  export async function confirmCodexHookRebind(state, packageRoot) {
@@ -235,6 +232,7 @@ function buildDaemonEnv(p, opts) {
235
232
  EVENT_LOG: process.env.EVENT_LOG || 'true',
236
233
  ...(opts.diagnose ? { EVOLCORE_DIAGNOSE: '1' } : {}),
237
234
  ...(opts.bindBootstrap ? { EVOLCORE_BIND_BOOTSTRAP: '1' } : {}),
235
+ ...(opts.webInit ? { EVOLCORE_WEB_INIT: '1' } : {}),
238
236
  ...(opts.debug ? { EVOLCORE_DEBUG_MODE: '1' } : {}),
239
237
  };
240
238
  }
@@ -600,18 +598,41 @@ function printStartupInfo(opts = {}, asMode) {
600
598
  aunVer = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'node_modules', '@agentunion', 'fastaun', 'package.json'), 'utf-8')).version;
601
599
  }
602
600
  catch { }
601
+ const ecwebVer = readEcwebPackageVersion();
603
602
  const pidPart = opts.pid ? ` (PID: ${opts.pid})` : '';
604
- const aunPart = aunVer ? ` fastaun v${aunVer}` : '';
603
+ const componentParts = [
604
+ ecwebVer ? `ec-web v${ecwebVer}` : '',
605
+ aunVer ? `fastaun v${aunVer}` : '',
606
+ ].filter(Boolean);
607
+ const componentPart = componentParts.length > 0 ? ` ${componentParts.join(' ')}` : '';
605
608
  const prefix = opts.running ? '✓ EvolCore is running , v' : ' EvolCore v';
606
- console.log(`${prefix}${version}${pidPart}${aunPart}`);
609
+ const versionLine = `${prefix}${version}${pidPart}${componentPart}`;
610
+ const useStatusColor = opts.statusLayout && !!process.stdout.isTTY && !process.env.NO_COLOR;
611
+ console.log(useStatusColor ? `\x1b[42;30;1m ${versionLine} \x1b[0m` : versionLine);
607
612
  console.log(` 包路径: ${pkgRoot}`);
608
- console.log(` 安装类型: ${isNpmInstall ? 'npm全局安装' : '开发仓(link)'}`);
613
+ console.log(` EVOLCORE_HOME: ${resolveRoot()}`);
614
+ const installType = isNpmInstall ? 'npm全局安装' : '开发仓(link)';
609
615
  // asMode 只是"本次请求",是否生效要看 daemon 是否真的由这次启动拉起,标清楚别和实际模式混淆
610
616
  const modeLine = describeRunMode(opts.runMode ?? asMode, !isNpmInstall);
611
- console.log(` ${asMode && !opts.runMode ? `${modeLine}(--as-mode 请求)` : modeLine}`);
612
- console.log(` CLI执行: ${cliRunsSource ? '源码(tsx)' : '编译产物(dist)'}`);
613
- console.log(` Daemon执行: ${daemonRunsDist ? '编译产物(dist)' : '未知'}`);
614
- console.log(` 代码时间: ${latestMtime ? formatLocalTime(latestMtime) : '?'}`);
617
+ const modeDetails = modeLine.replace(/^运行模式:\s*/, '');
618
+ if (opts.statusLayout) {
619
+ console.log(` 安装类型: ${installType} 运行模式: ${modeDetails}`);
620
+ }
621
+ else {
622
+ console.log(` 安装类型: ${installType}`);
623
+ console.log(` ${asMode && !opts.runMode ? `${modeLine}(--as-mode 请求)` : modeLine}`);
624
+ }
625
+ const cliExecution = cliRunsSource ? '源码(tsx)' : '编译产物(dist)';
626
+ const daemonExecution = daemonRunsDist ? '编译产物(dist)' : '未知';
627
+ if (opts.statusLayout) {
628
+ console.log(` CLI执行: ${cliExecution} Daemon执行: ${daemonExecution}`);
629
+ }
630
+ else {
631
+ console.log(` CLI执行: ${cliExecution}`);
632
+ console.log(` Daemon执行: ${daemonExecution}`);
633
+ }
634
+ if (!opts.statusLayout)
635
+ console.log(` 代码时间: ${latestMtime ? formatLocalTime(latestMtime) : '?'}`);
615
636
  }
616
637
  export async function cmdStart(opts = {}) {
617
638
  // Measure from process start so the reported time includes CLI bootstrap
@@ -1205,145 +1226,273 @@ const AID_STATUS_LABELS = {
1205
1226
  failed: '✗ Failed',
1206
1227
  disabled: '○ Disabled',
1207
1228
  };
1208
- function renderAunAidsTable(aids) {
1209
- // Column widths(视觉宽度):AGENT 列按实际名字最长值动态扩展
1210
- const agentNames = aids.map(a => (a.agentName || '?').replace(/\.agentid\.pub$/, ''));
1211
- const COL_AGENT = Math.max(5, ...agentNames.map(n => n.length)) + 2;
1212
- const COL_AID = 32;
1213
- const COL_STATUS = 16;
1214
- const COL_QUEUE = 12;
1215
- const COL_RECONN = 8;
1216
- const COL_LAST = 14;
1217
- // 表头
1218
- console.log(' ' +
1219
- padRight('AGENT', COL_AGENT) +
1220
- padRight('AID', COL_AID) +
1221
- padRight('STATUS', COL_STATUS) +
1222
- padRight('QUEUE', COL_QUEUE) +
1223
- padRight('RECONN', COL_RECONN) +
1224
- padRight('LAST ATTEMPT', COL_LAST) +
1225
- 'NOTE');
1226
- for (let i = 0; i < aids.length; i++) {
1227
- const a = aids[i];
1228
- const agent = agentNames[i];
1229
- const aid = (a.aid || '?').slice(0, COL_AID - 1);
1230
- // 队列状态
1231
- const queueStatus = a.queueStatus || { processing: 0, queued: 0 };
1232
- const hasActiveTask = queueStatus.processing > 0;
1233
- // STATUS:如果有任务执行则显示 ✓ Working
1234
- const statusLabel = (a.status === 'connected' && hasActiveTask)
1235
- ? '✓ Working'
1236
- : (AID_STATUS_LABELS[a.status] || a.status || '?');
1237
- // QUEUE:显示 "处理中/排队中",空闲时显示 "—"
1238
- const queueLabel = (queueStatus.processing === 0 && queueStatus.queued === 0)
1239
- ? '—'
1240
- : `${queueStatus.processing}/${queueStatus.queued}`;
1241
- const reconn = String(a.reconnectCount ?? 0);
1242
- const lastAttempt = a.lastAttemptAt
1243
- ? formatTimeAgo(Date.now() - a.lastAttemptAt)
1244
- : '—';
1245
- let note = '';
1246
- if (a.status === 'connected' && a.lastConnectedAt) {
1247
- note = `uptime ${formatTimeAgo(Date.now() - a.lastConnectedAt).replace('前', '')}`;
1248
- }
1249
- else if (a.status === 'aid_blocked' && a.blockedBy) {
1250
- const home = (a.blockedBy.evolcoreHome || '').replace(os.homedir(), '~');
1251
- const ag = a.blockedBy.agentName ? `, agent=${a.blockedBy.agentName}` : '';
1252
- note = `held by PID ${a.blockedBy.pid} (HOME=${home}${ag})`;
1253
- }
1254
- else if (a.lastError) {
1255
- note = a.lastError;
1256
- }
1257
- console.log(' ' +
1258
- padRight(agent, COL_AGENT) +
1259
- padRight(aid, COL_AID) +
1260
- padRight(statusLabel, COL_STATUS) +
1261
- padRight(queueLabel, COL_QUEUE) +
1262
- padRight(reconn, COL_RECONN) +
1263
- padRight(lastAttempt, COL_LAST) +
1264
- note);
1229
+ function truncateVisualWidth(value, width) {
1230
+ if (visualWidth(value) <= width)
1231
+ return value;
1232
+ let result = '';
1233
+ for (const char of value) {
1234
+ if (visualWidth(result + char) > width - 1)
1235
+ break;
1236
+ result += char;
1237
+ }
1238
+ return `${result}…`;
1239
+ }
1240
+ function renderAunAidsTable(agents, controlAid) {
1241
+ const hasControlAid = typeof controlAid?.aid === 'string' && controlAid.aid.length > 0;
1242
+ const rows = agents.filter(agent => agent.aid !== controlAid?.aid).map(agent => {
1243
+ const disabled = agent?.status === 'disabled';
1244
+ const queue = agent?.queue;
1245
+ const model = [agent?.baseagent, agent?.model].filter(Boolean).join('/') || '—';
1246
+ const activity = agent?.activity ?? {};
1247
+ const usage = agent?.usage ?? {};
1248
+ const tokens = typeof usage.tokens?.total === 'number' ? formatStatusCount(usage.tokens.total) : '—';
1249
+ const callsAndTokens = agent ? `${formatStatusCount(usage.calls)} / ${tokens}` : '—';
1250
+ const cost = usage.cost;
1251
+ const official = typeof cost?.official?.cny === 'number' ? `¥${cost.official.cny.toFixed(2)}` : '未计价';
1252
+ const gateway = typeof cost?.gateway?.cny === 'number' ? `¥${cost.gateway.cny.toFixed(2)}` : '未计价';
1253
+ const coverageRows = cost?.coverage?.rows;
1254
+ const coverage = Number.isFinite(coverageRows) && coverageRows > 0
1255
+ ? ` (${cost.coverage.official?.cnyPricedRows ?? 0}/${coverageRows})` : '';
1256
+ const fees = agent ? `${official}/${gateway}${coverage}` : '—';
1257
+ return {
1258
+ name: agent.name,
1259
+ aid: agent.aid,
1260
+ status: agent.statusLabel,
1261
+ queue: disabled ? '' : queue ? `${queue.processing ?? 0}/${queue.pending ?? 0}` : '—',
1262
+ activity: disabled ? '' : [activity.received, activity.sent, activity.errors, activity.interrupts, activity.completed]
1263
+ .map(formatStatusCount).join('/'),
1264
+ model,
1265
+ callsAndTokens,
1266
+ fees,
1267
+ };
1268
+ });
1269
+ if (hasControlAid) {
1270
+ rows.push({
1271
+ name: 'DAEMON',
1272
+ aid: controlAid.aid,
1273
+ status: controlAid.connected ? '已连接' : '未连接',
1274
+ queue: '',
1275
+ activity: '',
1276
+ model: '',
1277
+ callsAndTokens: '',
1278
+ fees: '',
1279
+ });
1265
1280
  }
1281
+ const columns = [
1282
+ { key: 'name', label: 'Agent', width: 14 },
1283
+ { key: 'aid', label: 'AID', width: 25 },
1284
+ { key: 'status', label: '运行状态', width: Math.max(8, ...rows.map(row => visualWidth(row.status))) },
1285
+ { key: 'queue', label: '执行/排队', width: 9 },
1286
+ { key: 'activity', label: '收/发/错/断/完', width: 19 },
1287
+ { key: 'model', label: '基座 / 模型', width: 22 },
1288
+ { key: 'callsAndTokens', label: '调用 / Token', width: 14 },
1289
+ { key: 'fees', label: '费用 官/网(CNY)', width: 22 },
1290
+ ];
1291
+ const renderRow = (values) => columns
1292
+ .map((column, index) => padRight(truncateVisualWidth(values[index] ?? '', column.width), column.width))
1293
+ .join(' ').trimEnd();
1294
+ console.log(renderRow(columns.map(column => column.label)));
1295
+ for (const row of rows)
1296
+ console.log(renderRow(columns.map(column => row[column.key])));
1266
1297
  }
1267
- function readStatusDefaultsConfig(file) {
1268
- try {
1269
- return JSON.parse(fs.readFileSync(file, 'utf-8'));
1270
- }
1271
- catch (error) {
1272
- const detail = error?.code ? String(error.code) : error instanceof Error ? error.message : String(error);
1273
- console.log(`⚠ Channel configuration unavailable (${detail})`);
1298
+ function localDayStartMs(now = new Date()) {
1299
+ return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
1300
+ }
1301
+ function formatStatusCount(value) {
1302
+ if (typeof value !== 'number' || !Number.isFinite(value))
1303
+ return '—';
1304
+ if (value >= 1_000_000_000)
1305
+ return `${(value / 1_000_000_000).toFixed(2)}B`;
1306
+ if (value >= 1_000_000)
1307
+ return `${(value / 1_000_000).toFixed(2)}M`;
1308
+ if (value >= 10_000)
1309
+ return `${(value / 1_000).toFixed(1)}K`;
1310
+ return Math.round(value).toLocaleString('en-US');
1311
+ }
1312
+ function formatStatusUptime(value) {
1313
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
1274
1314
  return null;
1275
- }
1315
+ const seconds = Math.floor(value / 1000);
1316
+ if (seconds < 60)
1317
+ return `${seconds} 秒`;
1318
+ const minutes = Math.floor(seconds / 60);
1319
+ if (minutes < 60)
1320
+ return `${minutes} 分钟`;
1321
+ const days = Math.floor(minutes / 1440);
1322
+ const hours = Math.floor(minutes / 60) % 24;
1323
+ const remainingMinutes = minutes % 60;
1324
+ return [
1325
+ days > 0 ? `${days} 天` : '',
1326
+ hours > 0 ? `${hours} 小时` : '',
1327
+ remainingMinutes > 0 ? `${remainingMinutes} 分` : '',
1328
+ ].filter(Boolean).join(' ');
1329
+ }
1330
+ function formatStatusCurrency(value) {
1331
+ return typeof value === 'number' && Number.isFinite(value) ? `¥${value.toFixed(2)}` : '未计价';
1332
+ }
1333
+ function formatStatusCost(cost, provider) {
1334
+ const amount = formatStatusCurrency(cost?.[provider]?.cny);
1335
+ const rows = cost?.coverage?.rows;
1336
+ const pricedRows = cost?.coverage?.[provider]?.cnyPricedRows;
1337
+ return Number.isFinite(rows) && rows > 0 && Number.isFinite(pricedRows)
1338
+ ? `${amount} (${pricedRows}/${rows})` : amount;
1339
+ }
1340
+ function renderStatusTable(headers, rows, rightAlignedColumns = [], minWidths = []) {
1341
+ const widths = headers.map((header, index) => Math.max(visualWidth(header), minWidths[index] ?? 0, ...rows.map(row => visualWidth(row[index] ?? ''))));
1342
+ const render = (row) => ' ' + widths.map((width, index) => {
1343
+ const value = row[index] ?? '';
1344
+ return rightAlignedColumns.includes(index)
1345
+ ? ' '.repeat(Math.max(0, width - visualWidth(value))) + value
1346
+ : padRight(value, width);
1347
+ }).join(' │ ').trimEnd();
1348
+ console.log(render(headers));
1349
+ console.log(' ' + widths.map(width => '─'.repeat(width)).join('──┼──'));
1350
+ for (const row of rows)
1351
+ console.log(render(row));
1352
+ }
1353
+ function renderStatusFields(rows) {
1354
+ const labelWidth = Math.max(18, ...rows.map(([label]) => visualWidth(label)));
1355
+ for (const [label, value] of rows)
1356
+ console.log(` ${padRight(label, labelWidth)} ${value}`);
1357
+ }
1358
+ function statusChannelLabel(type) {
1359
+ const labels = {
1360
+ aun: 'AUN',
1361
+ feishu: '飞书(feishu)',
1362
+ dingtalk: '钉钉(dingtalk)',
1363
+ wechat: '微信(wechat)',
1364
+ qqbot: 'QQ机器人(qqbot)',
1365
+ wecom: '企业微信(wecom)',
1366
+ };
1367
+ return labels[type] ?? type;
1368
+ }
1369
+ function statusChannelCounts(channels) {
1370
+ const counts = new Map();
1371
+ const add = (type, connected) => {
1372
+ const count = counts.get(type) ?? { connected: 0, total: 0 };
1373
+ count.total++;
1374
+ if (connected)
1375
+ count.connected++;
1376
+ counts.set(type, count);
1377
+ };
1378
+ for (const channel of channels)
1379
+ add(channel.type, channel.connected);
1380
+ const order = ['aun', 'feishu', 'dingtalk', 'wechat', 'qqbot', 'wecom'];
1381
+ const types = [...order.filter(type => counts.has(type)), ...[...counts.keys()].filter(type => !order.includes(type)).sort()];
1382
+ return types.map(type => {
1383
+ const count = counts.get(type);
1384
+ return { type, ...count };
1385
+ });
1276
1386
  }
1277
- function showConfigChannels(config) {
1278
- const groups = [];
1279
- const channelChecks = [
1280
- { type: 'feishu', isValid: (inst) => !!inst.appId && inst.enabled !== false },
1281
- { type: 'wechat', isValid: (inst) => !!inst.token && inst.enabled !== false },
1282
- { type: 'aun', isValid: (inst) => !!inst.aid && inst.enabled !== false && !inst.aid.includes('your-') && !inst.aid.includes('placeholder') },
1283
- { type: 'dingtalk', isValid: (inst) => !!inst.clientId && inst.enabled !== false && !inst.clientId.includes('your-') && !inst.clientId.includes('placeholder') },
1284
- { type: 'qqbot', isValid: (inst) => !!inst.appId && inst.enabled !== false && !inst.appId.includes('your-') && !inst.appId.includes('placeholder') },
1285
- { type: 'wecom', isValid: (inst) => !!inst.botId && inst.enabled !== false && !inst.botId.includes('your-') && !inst.botId.includes('placeholder') },
1387
+ function renderStatusOverview(snapshot) {
1388
+ const host = snapshot.host;
1389
+ const cpuCount = host?.hardware?.cpuCount;
1390
+ const totalMemory = host?.hardware?.memoryTotalBytes;
1391
+ const processCpu = snapshot.runtime.processMetrics.cpuPercent
1392
+ ? ` · 进程 ${snapshot.runtime.processMetrics.cpuPercent}%` : '';
1393
+ const processMemory = snapshot.runtime.processMetrics.memoryBytes !== null
1394
+ ? ` · 进程 ${formatBytes(snapshot.runtime.processMetrics.memoryBytes)}` : '';
1395
+ const uptime = formatStatusUptime(snapshot.daemon.uptimeMs);
1396
+ console.log('\n运行概览');
1397
+ console.log('─'.repeat(72));
1398
+ const overviewFields = [
1399
+ ['服务状态', snapshot.overall.status === 'running' ? `运行中${uptime ? `(${uptime})` : ''}`
1400
+ : snapshot.overall.status === 'restarting' ? '正在重启' : snapshot.overall.status === 'stopped' ? '已停止' : '状态未知'],
1401
+ ...(snapshot.overall.degraded ? [['降级状态', '已降级']] : []),
1402
+ ['IPC', `${snapshot.daemon.ipc.reachable ? '可达' : '不可达'} (${snapshot.daemon.ipc.latencyMs} ms)`],
1403
+ ['CPU', `${Number.isFinite(cpuCount) ? `${cpuCount} 核` : '主机信息不可用'}${processCpu}`],
1404
+ ['Memory', `${Number.isFinite(totalMemory) ? `${formatBytes(totalMemory)} 主机总量` : '主机信息不可用'}${processMemory}`],
1286
1405
  ];
1287
- for (const { type, isValid } of channelChecks) {
1288
- const raw = config.channels?.[type];
1289
- if (!raw)
1290
- continue;
1291
- if (Array.isArray(raw)) {
1292
- const names = raw.filter(isValid).map((inst) => inst.name || type);
1293
- if (names.length > 0)
1294
- groups.push({ type, instances: names });
1295
- }
1296
- else if (isValid(raw)) {
1297
- groups.push({ type, instances: [raw.name || type] });
1298
- }
1406
+ renderStatusFields(overviewFields);
1407
+ const baseagents = snapshot.baseagents?.items;
1408
+ const activity = snapshot.activity;
1409
+ if (activity) {
1410
+ const windows = [activity.lastHour, activity.today];
1411
+ const countRow = (label, field) => [
1412
+ label, ...windows.map(window => formatStatusCount(window?.[field])),
1413
+ ];
1414
+ const tokenRow = (label, field) => [
1415
+ label, ...windows.map(window => formatStatusCount(window?.tokens?.[field])),
1416
+ ];
1417
+ console.log('\n活动与用量');
1418
+ renderStatusTable(['指标', '最近一小时', '今日'], [
1419
+ countRow('收到消息', 'received'),
1420
+ countRow('发出消息', 'sent'),
1421
+ countRow('完成任务', 'completed'),
1422
+ countRow('错误', 'errors'),
1423
+ countRow('中断', 'interrupts'),
1424
+ countRow('模型调用', 'modelCalls'),
1425
+ ['平均响应', ...windows.map(window => typeof window?.avgResponseMs === 'number'
1426
+ && Number.isFinite(window.avgResponseMs) ? `${(window.avgResponseMs / 1000).toFixed(1)} s` : '—')],
1427
+ tokenRow('Token 总量', 'total'),
1428
+ tokenRow(' 输入', 'input'),
1429
+ tokenRow(' 输出', 'output'),
1430
+ tokenRow(' 缓存读取', 'cacheRead'),
1431
+ tokenRow(' 缓存创建', 'cacheCreation'),
1432
+ ['官方费用 (CNY)', ...windows.map(window => formatStatusCost(window?.cost, 'official'))],
1433
+ ['网关费用 (CNY)', ...windows.map(window => formatStatusCost(window?.cost, 'gateway'))],
1434
+ ], [1, 2], [18, 22, 22]);
1435
+ console.log(' 费用括号 = 已计价 / 总记录;未计价记录不计入费用。');
1436
+ }
1437
+ if (Array.isArray(baseagents) && baseagents.length > 0) {
1438
+ const ready = baseagents.filter((item) => item.state === 'ready').length;
1439
+ const stateLabels = {
1440
+ ready: '✓', available: '可用', unavailable: '不可用', unknown: '未知',
1441
+ };
1442
+ console.log(`\n基座(${ready}/${baseagents.length} 就绪)`);
1443
+ renderStatusTable(baseagents.map((item) => item.label ?? item.id), [baseagents.map((item) => stateLabels[item.state] ?? item.state ?? '未知')]);
1444
+ }
1445
+ console.log('\n渠道连接');
1446
+ const channelCounts = statusChannelCounts(snapshot.channels.items);
1447
+ if (channelCounts.length > 0) {
1448
+ const headers = channelCounts.map(channel => {
1449
+ const label = statusChannelLabel(channel.type);
1450
+ return channel.connected === channel.total ? label
1451
+ : `${label}(${channel.connected === 0 ? '已断开' : '部分断开'})`;
1452
+ });
1453
+ renderStatusTable(headers, [channelCounts.map(channel => `${channel.connected}/${channel.total}`)]);
1299
1454
  }
1300
- if (groups.length > 0) {
1301
- for (const g of groups) {
1302
- if (g.instances.length === 1) {
1303
- console.log(` ${g.instances[0]}: ✓ Configured`);
1304
- }
1305
- else {
1306
- console.log(` ${g.type}: [${g.instances.join(', ')}]`);
1307
- }
1455
+ else {
1456
+ console.log(snapshot.channels.source === 'daemon' ? ' 无其他渠道' : ' 状态不可用');
1457
+ }
1458
+ if (snapshot.triggers?.source === 'runtime+history') {
1459
+ console.log('\n触发器');
1460
+ renderStatusTable(['启用', '今日执行', '今日失败'], [[
1461
+ formatStatusCount(snapshot.triggers.enabled),
1462
+ formatStatusCount(snapshot.triggers.today?.calls),
1463
+ formatStatusCount(snapshot.triggers.today?.failures),
1464
+ ]], [0, 1, 2], [12, 12, 12]);
1465
+ }
1466
+ }
1467
+ function renderStatusServiceProxy(serviceProxy) {
1468
+ console.log('\n服务代理(配置)');
1469
+ if (serviceProxy?.source !== 'unavailable' && Array.isArray(serviceProxy?.items)) {
1470
+ const configured = serviceProxy.items;
1471
+ if (configured.length > 0) {
1472
+ renderStatusTable(['服务', '状态', '来源', '协议', '可见性'], configured.map((item) => [
1473
+ item.name,
1474
+ !item.serviceEnabled ? '服务已禁用' : item.proxyEnabled ? '已启用' : '代理已禁用',
1475
+ item.source ?? '—',
1476
+ item.serviceType ?? '—',
1477
+ item.visibility ?? '—',
1478
+ ]), [], [12, 10, 10, 6, 10]);
1308
1479
  }
1309
1480
  }
1310
1481
  else {
1311
- console.log(' (no channels configured)');
1482
+ console.log(' 状态不可用');
1312
1483
  }
1313
1484
  }
1314
- function showLiveChannels(status) {
1315
- const channels = status?.channels;
1316
- if (!channels || typeof channels !== 'object' || Array.isArray(channels))
1317
- return false;
1318
- const entries = Object.entries(channels);
1319
- console.log('🔌 Channels (live status):');
1320
- if (entries.length === 0) {
1321
- console.log(' (no channel instances loaded)');
1322
- return true;
1323
- }
1324
- for (const [name, channel] of entries) {
1325
- const state = channel?.connected === true ? '✓ Connected'
1326
- : channel?.connected === false ? '✗ Disconnected' : '? Unknown';
1327
- const type = typeof channel?.channelType === 'string' ? ` (${channel.channelType})` : '';
1328
- console.log(` ${name}: ${state}${type}`);
1485
+ function renderStatusAgents(agents, aunAids, queue, controlAid, registered = agents.length) {
1486
+ const safeAunAids = Array.isArray(aunAids) ? aunAids : [];
1487
+ const safeAgents = Array.isArray(agents) ? agents : [];
1488
+ const queueLabel = queue
1489
+ ? `执行中 ${formatStatusCount(queue.processing)} / 等待 ${formatStatusCount(queue.pending)}` : '不可用';
1490
+ console.log(`\n🤖 AGENTs (${registered} Agent · ${safeAunAids.length} AUN AID · 全局队列 ${queueLabel})`);
1491
+ if (safeAgents.length === 0 && safeAunAids.length === 0 && !controlAid?.aid) {
1492
+ console.log(' (没有已登记 Agent)');
1493
+ return;
1329
1494
  }
1330
- return true;
1331
- }
1332
- function localDayStartMs(now = new Date()) {
1333
- return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
1334
- }
1335
- function statusActivityJson(window) {
1336
- return {
1337
- received: window.received,
1338
- sent: window.sent,
1339
- completed: window.completed,
1340
- errors: window.errors,
1341
- interrupts: window.interrupts,
1342
- avgResponseMs: window.avgResponseMs,
1343
- modelCalls: window.modelCalls,
1344
- tokens: window.tokens,
1345
- cost: window.cost,
1346
- };
1495
+ renderAunAidsTable(safeAgents, controlAid);
1347
1496
  }
1348
1497
  function readLocalPackageVersion() {
1349
1498
  try {
@@ -1354,517 +1503,259 @@ function readLocalPackageVersion() {
1354
1503
  return null;
1355
1504
  }
1356
1505
  }
1357
- async function cmdStatusJson() {
1506
+ function readEcwebPackageVersion() {
1507
+ try {
1508
+ const installed = resolveGlobalPkg(WEB_PACKAGE_NAME);
1509
+ const packageDir = installed ? path.dirname(installed.path) : path.join(getPackageRoot(), 'ecweb');
1510
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
1511
+ return typeof pkg.version === 'string' ? pkg.version : null;
1512
+ }
1513
+ catch {
1514
+ return null;
1515
+ }
1516
+ }
1517
+ function readProcessMetrics(pid, processVisible) {
1518
+ if (!pid || !processVisible)
1519
+ return { cpuPercent: null, memoryBytes: null };
1520
+ try {
1521
+ const info = platform.getProcessInfo(pid);
1522
+ const memoryKb = typeof info.memory === 'string' ? Number.parseInt(info.memory, 10) : Number.NaN;
1523
+ return {
1524
+ cpuPercent: info.cpu ?? null,
1525
+ memoryBytes: Number.isFinite(memoryKb) ? memoryKb * 1024 : null,
1526
+ };
1527
+ }
1528
+ catch {
1529
+ return { cpuPercent: null, memoryBytes: null };
1530
+ }
1531
+ }
1532
+ function projectStatusAgentItems(evolcoreHome, now, statusAgents, fallbackAgents, agentStats, aunAids) {
1533
+ const sourceByAid = new Map((statusAgents ?? fallbackAgents).map(agent => [agent.aid, agent]));
1534
+ for (const aun of aunAids) {
1535
+ if (!sourceByAid.has(aun.aid))
1536
+ sourceByAid.set(aun.aid, { aid: aun.aid, name: aun.agentName, status: 'unknown' });
1537
+ }
1538
+ const sourceAgents = [...sourceByAid.values()];
1539
+ const aids = sourceAgents.map((agent) => String(agent.aid ?? agent.name ?? ''));
1540
+ const todayStart = localDayStartMs(new Date(now));
1541
+ const todayByAid = queryStatusActivityByAgent(evolcoreHome, todayStart, now, aids);
1542
+ const lastHourByAid = queryStatusActivityByAgent(evolcoreHome, now - 3_600_000, now, aids);
1543
+ const statsByAid = new Map((Array.isArray(agentStats) ? agentStats : [])
1544
+ .filter(item => typeof item?.aid === 'string').map(item => [item.aid, item]));
1545
+ const aunByAid = new Map((Array.isArray(aunAids) ? aunAids : [])
1546
+ .filter(item => typeof item?.aid === 'string').map(item => [item.aid, item]));
1547
+ const activityFields = ['received', 'sent', 'errors', 'interrupts', 'completed'];
1548
+ return sourceAgents.map((agent) => {
1549
+ const aid = String(agent.aid ?? agent.name ?? '');
1550
+ const today = todayByAid.get(aid);
1551
+ const lastHour = lastHourByAid.get(aid);
1552
+ const runtime = statsByAid.get(aid);
1553
+ const aun = aunByAid.get(aid);
1554
+ const usage = agent.usage ?? {};
1555
+ const snapshotToday = agent.activity ?? {};
1556
+ const lastHourActivity = runtime ?? lastHour;
1557
+ const activityToday = Object.fromEntries(activityFields.map(field => [
1558
+ field,
1559
+ typeof snapshotToday[field] === 'number' ? snapshotToday[field] : today[field],
1560
+ ]));
1561
+ return {
1562
+ ...agent,
1563
+ aid,
1564
+ name: agent.name ?? aid,
1565
+ baseagent: agent.baseagent ?? null,
1566
+ model: agent.model ?? null,
1567
+ effort: agent.effort ?? null,
1568
+ statusLabel: agent.status === 'disabled' ? '未启用' : [
1569
+ agent.status === 'running' ? '运行' : agent.status === 'error' ? '错误' : agent.status === 'stopped' ? '已停止' : '',
1570
+ aun?.status === 'connected' ? '在线'
1571
+ : aun?.status === 'reconnecting' ? '重连中'
1572
+ : aun?.status === 'aid_blocked' ? '被阻止'
1573
+ : aun?.status === 'kicked' ? '已踢出'
1574
+ : aun?.status === 'failed' ? '失败'
1575
+ : aun?.status === 'disabled' ? '已禁用' : aun?.status ?? '未连接',
1576
+ typeof aun?.reconnectCount === 'number' && aun.reconnectCount > 0 ? `${aun.reconnectCount}次` : '',
1577
+ ].filter(Boolean).join('/'),
1578
+ connectionStatus: aun?.status ?? null,
1579
+ reconnectCount: aun?.reconnectCount ?? null,
1580
+ queue: runtime
1581
+ ? { pending: runtime.queued ?? 0, processing: runtime.processing ?? 0 }
1582
+ : agent.queue ?? (aun?.queueStatus
1583
+ ? { pending: aun.queueStatus.queued ?? 0, processing: aun.queueStatus.processing ?? 0 } : null),
1584
+ activity: Object.fromEntries(activityFields.map(field => [field, lastHourActivity[field]])),
1585
+ activityWindow: 'lastHour',
1586
+ activityToday,
1587
+ usage: {
1588
+ calls: usage.calls ?? usage.modelCalls ?? today.modelCalls,
1589
+ tokens: usage.tokens ?? today.tokens,
1590
+ cost: usage.cost ?? today.cost,
1591
+ },
1592
+ };
1593
+ });
1594
+ }
1595
+ async function collectStatusSnapshot() {
1358
1596
  const p = resolvePaths();
1359
1597
  const started = Date.now();
1360
- const instanceStatus = scanInstances();
1361
- const aliveMains = instanceStatus.mains.filter(instance => instance.alive);
1598
+ const instances = scanInstances();
1599
+ const aliveMains = instances.mains.filter(instance => instance.alive);
1600
+ const restartMonitors = instances.restartMonitors.filter(instance => instance.alive);
1362
1601
  let ipcError;
1363
1602
  const pingPromise = probeDaemon(p.socket, DAEMON_PROBE_TIMEOUT_MS, true).catch(error => {
1364
1603
  ipcError = error;
1365
1604
  return null;
1366
1605
  });
1367
- const [ping, statusResponse, aidsResponse, agentsResponse, agentStatsResponse] = await Promise.all([
1606
+ const agentsPromise = process.env.EVOLCORE_SESSION_ID
1607
+ ? Promise.resolve(null)
1608
+ : ipcQuery(p.socket, { type: 'evolagent.list' }).catch(() => null);
1609
+ const [ping, statusResponse, aidsResponse, agentsResponse, agentStatsResponse, ecweb] = await Promise.all([
1368
1610
  pingPromise,
1369
1611
  ipcQuery(p.socket, { type: 'status' }).catch(() => null),
1370
1612
  ipcQuery(p.socket, { type: 'aun-aids' }).catch(() => null),
1371
- ipcQuery(p.socket, { type: 'evolagent.list' }).catch(() => null),
1613
+ agentsPromise,
1372
1614
  ipcQuery(p.socket, { type: 'agent-stats' }).catch(() => null),
1615
+ collectEcwebStatus(p),
1373
1616
  ]);
1617
+ const latencyMs = Date.now() - started;
1374
1618
  const now = Date.now();
1375
- const runningPid = ping?.pid ?? aliveMains[0]?.record.pid ?? null;
1376
- const mainRecord = runningPid ? aliveMains.find(instance => instance.record.pid === runningPid)?.record : undefined;
1619
+ const pid = ping?.pid ?? statusResponse?.pid ?? aliveMains[0]?.record.pid ?? null;
1620
+ const mainRecord = aliveMains.find(instance => instance.record.pid === pid)?.record;
1621
+ const processVisible = aliveMains.some(instance => instance.record.pid === pid);
1377
1622
  const statusAvailable = !!statusResponse;
1378
- const overallStatus = statusAvailable
1379
- ? 'running'
1380
- : platform.isWindows && ipcError instanceof IpcTransportError
1381
- && ['ENOENT', 'ECONNREFUSED'].includes(ipcError.code)
1382
- ? 'stopped'
1383
- : 'unknown';
1623
+ const transportStopped = !ipcError || (platform.isWindows && ipcError instanceof IpcTransportError
1624
+ && ['ENOENT', 'ECONNREFUSED'].includes(ipcError.code));
1625
+ const overallStatus = statusAvailable || ping ? 'running'
1626
+ : restartMonitors.length > 0 ? 'restarting' : pid ? 'unknown' : transportStopped ? 'stopped' : 'unknown';
1384
1627
  const todayStart = localDayStartMs(new Date(now));
1385
- const lastHourActivity = queryStatusActivity(p.root, now - 3_600_000, now);
1386
- const todayActivity = statusResponse?.activity?.today ?? queryStatusActivity(p.root, todayStart, now);
1387
- const daemonLastHourActivity = statusResponse?.activity?.lastHour;
1388
- const effectiveLastHourActivity = daemonLastHourActivity ?? lastHourActivity;
1389
- const agents = agentsResponse?.agents ?? [];
1390
- const agentStats = new Map((agentStatsResponse?.stats ?? []).map((item) => [item.aid, item]));
1628
+ const activity = {
1629
+ lastHour: statusResponse?.activity?.lastHour ?? queryStatusActivity(p.root, now - 3_600_000, now),
1630
+ today: statusResponse?.activity?.today ?? queryStatusActivity(p.root, todayStart, now),
1631
+ };
1391
1632
  const statusAgents = Array.isArray(statusResponse?.agents) ? statusResponse.agents : null;
1392
- const agentUsage = statusAgents
1393
- ? new Map()
1394
- : queryStatusActivityByAgent(p.root, todayStart, now, agents.map((agent) => String(agent.aid ?? agent.name ?? '')));
1633
+ const fallbackAgents = agentsResponse?.ok && Array.isArray(agentsResponse.agents) ? agentsResponse.agents : [];
1634
+ const aunSource = aidsResponse?.ok && Array.isArray(aidsResponse.aids) ? aidsResponse.aids : [];
1635
+ const stats = agentStatsResponse?.ok && Array.isArray(agentStatsResponse.stats) ? agentStatsResponse.stats : [];
1636
+ const agentItems = projectStatusAgentItems(p.root, now, statusAgents, fallbackAgents, stats, aunSource);
1395
1637
  const diagnostics = [];
1396
- if (!statusAvailable) {
1397
- diagnostics.push({ code: 'DAEMON_IPC_UNAVAILABLE', message: ipcError instanceof Error ? ipcError.message : 'daemon status unavailable' });
1398
- }
1399
- const agentItems = statusAgents ?? agents.map((agent) => {
1400
- const aid = String(agent.aid ?? agent.name ?? '');
1401
- const runtime = agentStats.get(aid);
1402
- const usage = agentUsage.get(aid) ?? queryStatusActivity(p.root, todayStart, now, aid);
1403
- return {
1404
- aid,
1405
- name: agent.name ?? aid,
1406
- status: agent.status ?? 'unknown',
1407
- baseagent: agent.baseagent ?? null,
1408
- model: agent.model ?? null,
1409
- effort: agent.effort ?? null,
1410
- queue: runtime ? { pending: runtime.queued ?? 0, processing: runtime.processing ?? 0 } : null,
1411
- usage: {
1412
- calls: usage.modelCalls,
1413
- tokens: usage.tokens,
1414
- cost: usage.cost,
1415
- },
1416
- };
1417
- });
1418
- const channels = Object.entries(statusResponse?.channels ?? {})
1419
- .filter(([, channel]) => channel?.channelType !== 'aun')
1420
- .map(([name, channel]) => ({
1421
- name,
1422
- type: channel?.channelType ?? name,
1423
- status: channel?.status ?? (channel?.connected ? 'connected' : 'disconnected'),
1424
- connected: channel?.connected ?? false,
1425
- }));
1426
- const aunItems = (aidsResponse?.aids ?? []).map((aid) => ({
1427
- aid: aid.aid,
1428
- channelName: aid.channelName,
1429
- status: aid.status ?? 'unknown',
1430
- connected: aid.status === 'connected',
1431
- queue: aid.queueStatus ? {
1432
- pending: aid.queueStatus.queued ?? 0,
1433
- processing: aid.queueStatus.processing ?? 0,
1434
- } : null,
1435
- reconnectCount: aid.reconnectCount ?? 0,
1436
- }));
1638
+ if (!statusAvailable)
1639
+ diagnostics.push({
1640
+ code: 'DAEMON_IPC_UNAVAILABLE',
1641
+ message: ipcError instanceof Error ? ipcError.message : 'daemon status unavailable',
1642
+ });
1643
+ if (aliveMains.length > 1)
1644
+ diagnostics.push({
1645
+ code: 'MULTIPLE_DAEMONS',
1646
+ message: `检测到 ${aliveMains.length} 个 main 实例同时运行: ${aliveMains.map(item => item.record.pid).join(', ')}`,
1647
+ });
1648
+ if (statusAgents === null && !agentsResponse?.ok)
1649
+ diagnostics.push({
1650
+ code: 'AGENT_STATUS_UNAVAILABLE', message: 'Agent 列表状态不可用',
1651
+ });
1437
1652
  const host = statusResponse?.host ?? readHostInfo(readLocalPackageVersion());
1438
- const ecwebEntry = readEcwebInstanceEntries(p)[0];
1439
- const ecweb = ecwebEntry
1440
- ? { source: 'instance-record', status: platform.isProcessRunning(ecwebEntry.record.pid) ? 'running' : 'unknown', port: ecwebEntry.record.port, url: `http://localhost:${ecwebEntry.record.port}` }
1441
- : { source: 'instance-record', status: 'stopped', port: null, url: null };
1442
- const triggerSummary = statusResponse?.triggers
1443
- ? { source: 'runtime+history', ...statusResponse.triggers }
1444
- : { source: 'unavailable', enabled: null, today: { calls: null, failures: null } };
1445
- const build = statusResponse?.build
1446
- ? { runtimeMode: statusResponse.build.runtimeMode, version: statusResponse.build.version ?? null }
1447
- : null;
1448
- const output = {
1653
+ const packageRoot = getPackageRoot();
1654
+ const runMode = statusResponse?.runMode ?? mainRecord?.runMode ?? null;
1655
+ return {
1449
1656
  schemaVersion: 1,
1450
1657
  generatedAt: new Date(now).toISOString(),
1451
1658
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1452
- overall: {
1453
- status: overallStatus,
1454
- degraded: !statusAvailable || statusResponse?.agentRuntime?.state === 'error',
1455
- },
1659
+ overall: { status: overallStatus, degraded: !statusAvailable || statusResponse?.agentRuntime?.state === 'error' },
1456
1660
  host,
1661
+ runtime: {
1662
+ packagePath: packageRoot, evolcoreHome: p.root,
1663
+ installationType: packageRoot.includes('node_modules') ? 'npm-global' : 'development-link',
1664
+ runMode,
1665
+ cliExecution: import.meta.url.includes('/dist/') ? 'dist' : 'source',
1666
+ daemonExecution: statusResponse?.build?.runtimeMode ?? null,
1667
+ processMetrics: readProcessMetrics(pid, processVisible),
1668
+ },
1669
+ versions: {
1670
+ evolcore: host?.evolcore?.version ?? readLocalPackageVersion(),
1671
+ ecweb: readEcwebPackageVersion(), fastaun: readFastaunVersion(),
1672
+ },
1457
1673
  daemon: {
1458
- pid: runningPid,
1459
- uptimeMs: ping?.uptime ?? statusResponse?.uptime ?? null,
1460
- ipc: { reachable: statusAvailable, latencyMs: Date.now() - started },
1461
- runMode: statusResponse?.runMode ?? mainRecord?.runMode ?? null,
1462
- build,
1674
+ pid, uptimeMs: statusResponse?.uptime ?? ping?.uptime ?? null,
1675
+ ipc: { reachable: statusAvailable, latencyMs },
1676
+ runMode,
1677
+ build: statusResponse?.build
1678
+ ? { runtimeMode: statusResponse.build.runtimeMode, version: statusResponse.build.version ?? null } : null,
1463
1679
  queue: statusResponse?.queue ?? { pending: null, processing: null },
1680
+ restartMonitorPids: restartMonitors.map(item => item.record.pid),
1464
1681
  },
1465
1682
  baseagents: statusResponse?.baseagents ?? { source: 'unavailable', items: [] },
1466
- activity: {
1467
- lastHour: statusActivityJson(effectiveLastHourActivity),
1468
- today: statusActivityJson(todayActivity),
1469
- },
1683
+ activity,
1470
1684
  agents: {
1471
- source: statusAvailable ? 'daemon+stats-db' : 'stats-db',
1685
+ source: statusAgents !== null || agentsResponse?.ok ? 'daemon+stats-db' : 'unavailable',
1686
+ registered: (statusAgents ?? fallbackAgents).length,
1472
1687
  items: agentItems,
1473
1688
  },
1474
- aun: { source: aidsResponse ? 'daemon' : 'unavailable', items: aunItems },
1475
- channels: { source: statusAvailable ? 'daemon' : 'unavailable', items: channels },
1689
+ aun: {
1690
+ source: aidsResponse?.ok ? 'daemon' : 'unavailable',
1691
+ items: aunSource.map((aid) => ({
1692
+ aid: aid.aid, channelName: aid.channelName, status: aid.status ?? 'unknown',
1693
+ connected: aid.status === 'connected',
1694
+ queue: aid.queueStatus ? { pending: aid.queueStatus.queued ?? 0, processing: aid.queueStatus.processing ?? 0 } : null,
1695
+ reconnectCount: aid.reconnectCount ?? 0,
1696
+ })),
1697
+ },
1698
+ channels: {
1699
+ source: statusAvailable ? 'daemon' : 'unavailable',
1700
+ items: Object.entries(statusResponse?.channels ?? {})
1701
+ .filter(([, channel]) => channel?.channelType !== 'aun')
1702
+ .map(([name, channel]) => ({
1703
+ name, type: channel?.channelType ?? name,
1704
+ status: channel?.status ?? (channel?.connected ? 'connected' : 'disconnected'),
1705
+ connected: channel?.connected ?? false,
1706
+ })),
1707
+ },
1476
1708
  controlAid: statusResponse?.controlAid ?? null,
1477
- triggers: triggerSummary,
1478
- ecweb,
1479
- diagnostics,
1709
+ triggers: statusResponse?.triggers
1710
+ ? { source: 'runtime+history', ...statusResponse.triggers }
1711
+ : { source: 'unavailable', enabled: null, today: { calls: null, failures: null } },
1712
+ proxy: statusResponse?.serviceProxy ?? { source: 'unavailable', items: [] },
1713
+ ecweb, diagnostics,
1480
1714
  };
1481
- console.log(JSON.stringify(output, null, 2));
1482
1715
  }
1483
- export async function cmdStatus(options = {}) {
1484
- if (options.format === 'json') {
1485
- await cmdStatusJson();
1486
- return;
1487
- }
1488
- const p = resolvePaths();
1489
- const status = scanInstances();
1490
- const aliveMains = status.mains.filter(m => m.alive);
1491
- const aliveRestartMonitors = status.restartMonitors.filter(m => m.alive);
1492
- // Start all read-only daemon queries together. On a busy Windows host each
1493
- // query can otherwise wait behind the same IPC/event-loop delay and make the
1494
- // total `ec status` time the sum of several individual timeouts.
1495
- let ipcFailure;
1496
- let agentsQueryFailure;
1497
- const pingPromise = probeDaemon(p.socket, DAEMON_PROBE_TIMEOUT_MS, true).catch(error => {
1498
- ipcFailure = error;
1499
- return null;
1500
- });
1501
- const statusPromise = ipcQuery(p.socket, { type: 'status' }).catch(() => null);
1502
- const aidsPromise = ipcQuery(p.socket, { type: 'aun-aids' }).catch(() => null);
1503
- const agentsPromise = process.env.EVOLCORE_SESSION_ID
1504
- ? Promise.resolve({ ok: false, error: 'per-agent listing requires a local control token' })
1505
- : ipcQuery(p.socket, { type: 'evolagent.list' }, 5_000).catch(error => {
1506
- agentsQueryFailure = error;
1507
- return null;
1508
- });
1509
- // Only the ping is needed to decide whether to show the live-daemon
1510
- // sections. The remaining responses continue in parallel while local
1511
- // process/session information is rendered.
1512
- const ping = await pingPromise;
1513
- const pid = ping?.pid ?? (aliveMains.length > 0 ? aliveMains[0].record.pid : null);
1514
- const processVisible = !!pid && aliveMains.some(entry => entry.record.pid === pid);
1515
- if (aliveMains.length > 1) {
1516
- console.log(`⚠ 检测到 ${aliveMains.length} 个 main 实例同时运行: ${aliveMains.map(m => m.record.pid).join(', ')}`);
1517
- console.log(' 这是异常状态,建议执行 ec restart 让所有实例统一退出');
1518
- console.log('');
1519
- }
1520
- if (pid) {
1521
- const mainRecord = aliveMains.find(m => m.record.pid === pid)?.record;
1522
- printStartupInfo({ pid, running: true, runMode: mainRecord?.runMode });
1523
- if (!ping) {
1524
- console.log('⚠ 仅确认 daemon PID 存活,IPC 不可用,不能据此判断服务健康。');
1525
- if (ipcFailure)
1526
- console.log(` ${ipcFailure instanceof Error ? ipcFailure.message : String(ipcFailure)}`);
1527
- }
1528
- console.log('');
1529
- console.log('📊 Process Info:');
1530
- if (processVisible) {
1531
- try {
1532
- const info = platform.getProcessInfo(pid);
1533
- if (info.uptime)
1534
- console.log(` Uptime: ${info.uptime}`);
1535
- if (info.cpu)
1536
- console.log(` CPU: ${info.cpu}%`);
1537
- if (info.memory) {
1538
- const memKB = parseInt(info.memory, 10);
1539
- const memStr = memKB >= 1024 ? `${(memKB / 1024).toFixed(0)} MB` : `${memKB} KB`;
1540
- console.log(` Memory: ${memStr}`);
1541
- }
1542
- }
1543
- catch { }
1544
- }
1545
- else {
1546
- console.log(' 宿主进程指标受 PID namespace 隔离,IPC 连接正常');
1547
- }
1548
- console.log(` EVOLCORE_HOME: ${resolveRoot()}`);
1549
- // Runtime statistics (read from sessions filesystem)
1550
- if (fs.existsSync(p.sessionsDir)) {
1551
- try {
1552
- const { chatDirPath, scanChatDirs, scanMetaFiles, readJsonFile, readLastJsonlLine } = await import('../core/session/session-fs-store.js');
1553
- const chatDirs = scanChatDirs(p.sessionsDir);
1554
- const allSessions = [];
1555
- for (const { dirPath } of chatDirs) {
1556
- const active = readJsonFile(path.join(dirPath, 'active.json'));
1557
- if (active)
1558
- allSessions.push({ ...active, isActive: true });
1559
- for (const metaFile of scanMetaFiles(dirPath)) {
1560
- const meta = readLastJsonlLine(path.join(dirPath, metaFile));
1561
- if (!meta)
1562
- continue;
1563
- // 跳过同 id 的(active.json 已经是它的最新版)
1564
- if (active && active.id === meta.id)
1565
- continue;
1566
- allSessions.push({ ...meta, isActive: false });
1567
- }
1568
- }
1569
- // 最近 5 个(按 updatedAt 倒排)
1570
- const recentSessions = [...allSessions].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 5);
1571
- // 检测 orphan:按物理 session 路由而非历史 meta 判定。保留的旧
1572
- // 实例副本在唯一的当前实例已存在时属于迁移来源,不应误报。
1573
- let orphanCount = 0;
1574
- try {
1575
- // When the daemon is reachable, use its loaded Agent view instead of
1576
- // reopening protected defaults.json and daemon.json from the CLI.
1577
- const [agentResponse, liveStatus] = await Promise.all([agentsPromise, statusPromise]);
1578
- if (!agentResponse?.ok || !Array.isArray(agentResponse.agents))
1579
- throw new Error('Agent list unavailable');
1580
- const configChannelNames = new Set();
1581
- const configuredByAgentType = new Map();
1582
- for (const cfg of agentResponse.agents) {
1583
- if (typeof cfg.aid !== 'string' || !cfg.aid)
1584
- continue;
1585
- // AUN 是从 agent 自身 AID 隐式派生的内建通道,不出现在 cfg.channels 里。
1586
- // 不补这条,所有 aun#<aid>#main 会话都会被误判成 orphan。
1587
- configChannelNames.add(`aun#${cfg.aid}#main`);
1588
- for (const channelKey of Array.isArray(cfg.channels) ? cfg.channels : []) {
1589
- if (typeof channelKey !== 'string')
1590
- continue;
1591
- configChannelNames.add(channelKey);
1592
- const [type, aid] = channelKey.split('#');
1593
- if (!type || !aid)
1594
- continue;
1595
- const identity = `${type}\0${aid}`;
1596
- configuredByAgentType.set(identity, [...(configuredByAgentType.get(identity) ?? []), channelKey]);
1597
- }
1598
- }
1599
- // The daemon control identity owns AUN transcripts but deliberately
1600
- // has no Agent config, so include it explicitly in route validity.
1601
- const controlAid = liveStatus?.controlAid?.aid;
1602
- if (typeof controlAid === 'string' && controlAid)
1603
- configChannelNames.add(`aun#${controlAid}#main`);
1604
- for (const chat of chatDirs) {
1605
- const channelKey = chat.channelKey;
1606
- if (!channelKey || configChannelNames.has(channelKey) || isNonAgentSessionChannel(channelKey))
1607
- continue;
1608
- const [type, aid] = channelKey.split('#');
1609
- const candidates = type && aid ? configuredByAgentType.get(`${type}\0${aid}`) : undefined;
1610
- if (candidates?.length === 1) {
1611
- const canonical = chatDirPath(p.sessionsDir, type, chat.channelId, type === 'aun' ? aid : undefined, candidates[0]);
1612
- if (canonical !== chat.dirPath && fs.existsSync(canonical))
1613
- continue;
1614
- }
1615
- orphanCount++;
1616
- }
1617
- }
1618
- catch { }
1619
- if (recentSessions.length > 0) {
1620
- console.log('');
1621
- console.log('📋 Recent Active Sessions:');
1622
- for (const s of recentSessions) {
1623
- const projectName = path.basename(s.projectPath);
1624
- const sessionType = isTopicThreadId(s.threadId) ? '话题会话' : '主会话';
1625
- const chatType = s.chatType === 'group' ? '群聊' : '单聊';
1626
- const sessionName = displaySessionTitle(s.name);
1627
- const timeAgo = formatTimeAgo(Date.now() - s.updatedAt);
1628
- const dot = s.isActive ? '•' : '○';
1629
- const agentSidLabel = s.agentSessionId ? ` [${s.agentSessionId}]` : '';
1630
- const agentType = s.baseagent || s.agentType;
1631
- if (!agentType) {
1632
- console.error(`[daemon-commands] baseagent is empty for session ${s.id}`);
1633
- }
1634
- const displayType = agentType || 'unknown';
1635
- console.log(` ${dot} [${displayType}] ${projectName} / ${sessionName} (${sessionType}, ${chatType})${agentSidLabel} - ${timeAgo}`);
1636
- }
1637
- }
1638
- if (orphanCount > 0) {
1639
- console.log('');
1640
- console.log(`⚠ Orphan sessions: ${orphanCount}`);
1641
- }
1642
- }
1643
- catch { }
1644
- }
1645
- }
1646
- else if (aliveRestartMonitors.length > 0) {
1647
- console.log(`🔄 EvolCore 正在重启,daemon 尚未就绪(monitor PID: ${aliveRestartMonitors.map(m => m.record.pid).join(', ')})`);
1648
- console.log(' 请稍后再次执行 ec status。');
1716
+ function renderStatusHeader(snapshot) {
1717
+ const { runtime, versions, daemon } = snapshot;
1718
+ const versionLine = `✓ EvolCore is running , v${versions.evolcore ?? '?'} (PID: ${daemon.pid})`
1719
+ + ` ec-web v${versions.ecweb ?? '?'} fastaun v${versions.fastaun ?? '?'}`;
1720
+ const useColor = !!process.stdout.isTTY && !process.env.NO_COLOR;
1721
+ console.log(useColor ? `\x1b[42;30;1m ${versionLine} \x1b[0m` : versionLine);
1722
+ console.log(` 包路径: ${runtime.packagePath}`);
1723
+ console.log(` EVOLCORE_HOME: ${runtime.evolcoreHome}`);
1724
+ const installType = runtime.installationType === 'npm-global' ? 'npm全局安装' : '开发仓(link)';
1725
+ const runMode = runtime.runMode === null ? '未知' : runtime.runMode === 'install' ? '安装模式' : '开发模式';
1726
+ console.log(` 安装类型: ${installType} 运行模式: ${runMode}`);
1727
+ const cliExecution = runtime.cliExecution === 'dist' ? '编译产物(dist)' : '源码(tsx)';
1728
+ const daemonExecution = runtime.daemonExecution === 'dist' ? '编译产物(dist)'
1729
+ : runtime.daemonExecution === 'source' ? '源码' : '未知';
1730
+ console.log(` CLI执行: ${cliExecution} Daemon执行: ${daemonExecution}`);
1731
+ }
1732
+ function renderStatusSnapshot(snapshot) {
1733
+ const hasStatus = snapshot.overall.status === 'running' || snapshot.daemon.pid !== null;
1734
+ if (snapshot.overall.status === 'running') {
1735
+ renderStatusHeader(snapshot);
1736
+ }
1737
+ else if (snapshot.overall.status === 'restarting') {
1738
+ console.log(`🔄 EvolCore 正在重启,daemon 尚未就绪(monitor PID: ${snapshot.daemon.restartMonitorPids.join(', ')})`);
1649
1739
  }
1650
1740
  else {
1651
- // With no live main/monitor, a missing Windows pipe is the normal stopped
1652
- // state. Preserve uncertainty for permissions, timeouts, unknown errors,
1653
- // and Unix callers that may be isolated from the daemon's PID namespace.
1654
- const stopped = !ipcFailure || (platform.isWindows && ipcFailure instanceof IpcTransportError
1655
- && ['ENOENT', 'ECONNREFUSED'].includes(ipcFailure.code));
1656
- console.log(stopped ? '⚠ EvolCore is not running' : '⚠ 无法确认 EvolCore 运行状态:IPC 不可用,且没有可见的存活 PID。');
1657
- if (!stopped && ipcFailure)
1658
- console.log(` ${ipcFailure instanceof Error ? ipcFailure.message : String(ipcFailure)}`);
1659
- }
1660
- // Session & Project statistics (从文件系统读)
1661
- if (fs.existsSync(p.sessionsDir)) {
1662
- console.log('');
1663
- console.log('📦 Sessions & Projects:');
1664
- try {
1665
- const { scanChatDirs, scanMetaFiles, readJsonFile, readLastJsonlLine } = await import('../core/session/session-fs-store.js');
1666
- const chatDirs = scanChatDirs(p.sessionsDir);
1667
- let totalSessions = 0;
1668
- let activeSessions = 0;
1669
- const channelIdSet = new Set();
1670
- const projectSet = new Set();
1671
- for (const { channelId, dirPath } of chatDirs) {
1672
- channelIdSet.add(channelId);
1673
- const active = readJsonFile(path.join(dirPath, 'active.json'));
1674
- if (active) {
1675
- activeSessions++;
1676
- projectSet.add(active.projectPath);
1677
- }
1678
- for (const metaFile of scanMetaFiles(dirPath)) {
1679
- const meta = readLastJsonlLine(path.join(dirPath, metaFile));
1680
- if (!meta)
1681
- continue;
1682
- totalSessions++;
1683
- projectSet.add(meta.projectPath);
1684
- }
1685
- }
1686
- console.log(` Total sessions: ${totalSessions} (active: ${activeSessions})`);
1687
- console.log(` Unique chats: ${channelIdSet.size}`);
1688
- console.log(` Projects: ${projectSet.size}`);
1689
- }
1690
- catch { }
1691
- }
1692
- // Channel status. A running daemon is authoritative and avoids reading
1693
- // protected config files from the CLI's potentially sandboxed process.
1694
- let agentsResponse = null;
1695
- let liveAgentRuntime = null;
1696
- if (pid) {
1697
- console.log('');
1698
- const [statusResponse, aidsResponse, agentResponse] = await Promise.all([
1699
- statusPromise,
1700
- aidsPromise,
1701
- agentsPromise,
1702
- ]);
1703
- agentsResponse = agentResponse;
1704
- liveAgentRuntime = statusResponse?.agentRuntime ?? null;
1705
- if (statusResponse) {
1706
- if (statusResponse.build) {
1707
- if (statusResponse.build.runtimeMode === 'source') {
1708
- console.log(` Build ID: runtime=source dist=${statusResponse.build.diskDistId || '?'}`);
1709
- console.log(' ℹ daemon 当前由源码入口运行,dist build ID 不参与一致性比较。');
1710
- }
1711
- else {
1712
- const runtimeBuildId = statusResponse.build.runtimeId || '?';
1713
- const diskDistBuildId = statusResponse.build.diskDistId || '?';
1714
- console.log(` Build ID: runtime=${runtimeBuildId} dist=${diskDistBuildId}`);
1715
- if (runtimeBuildId !== '?' && diskDistBuildId !== '?' && runtimeBuildId !== diskDistBuildId) {
1716
- console.log(' ⚠ 运行进程 build ID 与磁盘 dist 不一致;请重启 daemon 后再判断源码行为。');
1717
- }
1718
- }
1719
- }
1720
- else {
1721
- console.log(` Build ID: runtime=unavailable (daemon 未提供 build identity) dist=${computeBuildId(path.join(getPackageRoot(), 'dist')) ?? '?'}`);
1722
- console.log(' ⚠ 当前 daemon 未提供 build ID;请重启到包含 build identity 的版本后再判断源码行为。');
1723
- }
1724
- if (!statusResponse) {
1725
- const config = readStatusDefaultsConfig(p.defaultsConfig);
1726
- if (config) {
1727
- console.log('🔌 Channels (live status unavailable; configuration is stale):');
1728
- showConfigChannels(config);
1729
- }
1730
- else {
1731
- console.log('🔌 Channels: live status unavailable');
1732
- }
1733
- }
1734
- // 🔑 AUN AIDs 表格(详细 AUN 实例状态)
1735
- try {
1736
- if (aidsResponse?.ok && aidsResponse.aids?.length > 0) {
1737
- console.log('🔑 AUN AIDs:');
1738
- renderAunAidsTable(aidsResponse.aids);
1739
- }
1740
- }
1741
- catch { /* ignore */ }
1742
- // 控制 AID(daemon 进程身份)状态
1743
- if (statusResponse.controlAid) {
1744
- const state = statusResponse.controlAid.connected ? 'connected' : 'disconnected';
1745
- console.log(`control: ${statusResponse.controlAid.aid} [${state}]`);
1746
- }
1747
- else {
1748
- console.log('control: not configured');
1749
- }
1750
- if (statusResponse.stats) {
1751
- console.log('');
1752
- console.log('📊 Last hour:');
1753
- console.log(` Messages: ${statusResponse.stats.received} received, ${statusResponse.stats.completed} completed`);
1754
- if (statusResponse.stats.errors > 0)
1755
- console.log(` Errors: ${statusResponse.stats.errors}`);
1756
- if (statusResponse.stats.completed > 0)
1757
- console.log(` Avg response: ${(statusResponse.stats.avgResponseMs / 1000).toFixed(1)}s`);
1758
- }
1759
- }
1760
- else {
1761
- // IPC unreachable but PID exists — fall back to local config if readable.
1762
- const config = readStatusDefaultsConfig(p.defaultsConfig);
1763
- if (config) {
1764
- console.log('🔌 Channels (live status unavailable; configuration is stale):');
1765
- showConfigChannels(config);
1766
- }
1767
- }
1741
+ console.log(snapshot.overall.status === 'stopped' ? '⚠ EvolCore is not running'
1742
+ : '⚠ 无法确认 EvolCore 运行状态:IPC 不可用。');
1768
1743
  }
1769
- else if (fs.existsSync(p.defaultsConfig)) {
1770
- console.log('');
1771
- const config = readStatusDefaultsConfig(p.defaultsConfig);
1772
- if (config) {
1773
- console.log('🔌 Channel Configuration:');
1774
- showConfigChannels(config);
1775
- }
1744
+ for (const diagnostic of snapshot.diagnostics)
1745
+ console.log(` ⚠ ${diagnostic.message}`);
1746
+ if (hasStatus) {
1747
+ renderStatusOverview(snapshot);
1748
+ renderStatusAgents(snapshot.agents.items, snapshot.aun.items, snapshot.daemon.queue, snapshot.controlAid, snapshot.agents.registered);
1749
+ renderStatusServiceProxy(snapshot.proxy);
1776
1750
  }
1777
- // EvolAgent summary (via IPC, only when running)
1778
- if (pid) {
1779
- try {
1780
- const agentResult = agentsResponse;
1781
- if (agentResult?.ok && Array.isArray(agentResult.agents)) {
1782
- const agents = agentResult.agents;
1783
- console.log('');
1784
- console.log('🤖 EvolAgents (live status):');
1785
- if (agents.length === 0)
1786
- console.log(' (no agents loaded)');
1787
- for (const a of agents) {
1788
- const statusIcon = a.status === 'running' ? '●' : a.status === 'error' ? '✗' : a.status === 'disabled' ? '○' : '◌';
1789
- const channels = summarizeChannelFingerprints(a.channels || []);
1790
- const shortName = a.name.replace(/\.agentid\.pub$/, '');
1791
- console.log(` ${statusIcon} ${shortName.padEnd(20)} ${a.status.padEnd(10)} ${channels}`);
1792
- }
1793
- }
1794
- else {
1795
- const { EvolAgentRegistry } = await import('../core/evolagent-registry.js');
1796
- const diskRegistry = new EvolAgentRegistry(p.agentsDir);
1797
- diskRegistry.loadAll();
1798
- const agents = diskRegistry.list();
1799
- if (agents.length > 0) {
1800
- console.log('');
1801
- const detail = typeof agentResult?.error === 'string'
1802
- ? agentResult.error
1803
- : agentsQueryFailure instanceof Error ? agentsQueryFailure.message : 'IPC request failed';
1804
- const running = Number.isFinite(liveAgentRuntime?.runningAgents) ? liveAgentRuntime.runningAgents : null;
1805
- const runnable = Number.isFinite(liveAgentRuntime?.runnableAgents) ? liveAgentRuntime.runnableAgents : null;
1806
- if (running !== null && runnable !== null) {
1807
- console.log(`🤖 EvolAgents (live aggregate: ${running} running / ${runnable} runnable):`);
1808
- console.log(` Per-agent details unavailable (${detail}); following entries are stale configuration only:`);
1809
- }
1810
- else {
1811
- console.log(`🤖 EvolAgents (live status unavailable: ${detail}; stale configuration):`);
1812
- }
1813
- for (const a of agents) {
1814
- const diskStatus = a.status === 'disabled' || a.status === 'error' ? a.status : 'unknown';
1815
- const channels = summarizeChannelFingerprints(a.channels || []);
1816
- const shortName = a.name.replace(/\.agentid\.pub$/, '');
1817
- console.log(` ? ${shortName.padEnd(20)} ${`${diskStatus} (stale)`.padEnd(18)} ${channels}`);
1818
- }
1819
- }
1820
- }
1821
- }
1822
- catch {
1823
- // IPC query for agents failed — skip section
1824
- }
1825
- }
1826
- // ECWeb status(独立于 main 进程:ecweb 是单独 detached 进程)
1827
- await printEcwebStatus(p);
1751
+ renderEcwebStatus(snapshot.ecweb);
1828
1752
  }
1829
- /**
1830
- * 把 channel fingerprint 列表(`<type>#<selfAID>#<name>`)折叠成展示用摘要。
1831
- *
1832
- * 聚合规则:
1833
- * - 按 type 分组
1834
- * - 单实例:直接打 type(如 `aun`、`wechat`)
1835
- * - 多实例:`type×N (name1, name2, ...)`
1836
- * - 输出顺序保持首次出现的 type 顺序(aun 通常排第一,因为 channelInstanceNames 把它放头)
1837
- */
1838
- function summarizeChannelFingerprints(fingerprints) {
1839
- if (fingerprints.length === 0)
1840
- return '—';
1841
- const groups = new Map();
1842
- const order = [];
1843
- for (const fp of fingerprints) {
1844
- const parts = fp.split('#');
1845
- if (parts.length < 3) {
1846
- if (!groups.has(fp)) {
1847
- groups.set(fp, []);
1848
- order.push(fp);
1849
- }
1850
- continue;
1851
- }
1852
- const type = parts[0];
1853
- const name = parts[2];
1854
- if (!groups.has(type)) {
1855
- groups.set(type, []);
1856
- order.push(type);
1857
- }
1858
- groups.get(type).push(name);
1859
- }
1860
- return order.map(type => {
1861
- const names = groups.get(type);
1862
- if (names.length === 0)
1863
- return type;
1864
- if (names.length === 1)
1865
- return type;
1866
- return `${type}×${names.length} (${names.join(', ')})`;
1867
- }).join(', ');
1753
+ export async function cmdStatus(options = {}) {
1754
+ const snapshot = await collectStatusSnapshot();
1755
+ if (options.format === 'json')
1756
+ console.log(JSON.stringify(snapshot, null, 2));
1757
+ else
1758
+ renderStatusSnapshot(snapshot);
1868
1759
  }
1869
1760
  // Log line pattern: [timestamp] [LEVEL] [Module?] message
1870
1761
  const LOG_RE = /^(\[[^\]]+\]) (\[(?:INFO|WARN|ERROR|DEBUG)\]) ((?:\[[^\]]+\] )*)(.*)$/;
@@ -3060,13 +2951,9 @@ function readEcwebInstanceEntries(p) {
3060
2951
  continue;
3061
2952
  const filePath = path.join(p.instanceDir, file);
3062
2953
  try {
3063
- const raw = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
3064
- if (Number.isInteger(raw.pid) && raw.pid > 0) {
3065
- entries.push({
3066
- record: { pid: raw.pid, port: raw.port ?? 42705 },
3067
- filePath,
3068
- });
3069
- }
2954
+ const record = parseEcwebInstanceRecord(JSON.parse(fs.readFileSync(filePath, 'utf-8')), p.root, file);
2955
+ if (record)
2956
+ entries.push({ record, filePath });
3070
2957
  }
3071
2958
  catch { }
3072
2959
  }
@@ -3092,24 +2979,43 @@ function findAliveEcweb(p) {
3092
2979
  const alive = findAliveEcwebs(p);
3093
2980
  return alive[0] ?? null;
3094
2981
  }
3095
- /**
3096
- * 轻量 HTTP 就绪探测:ECWeb 的健康端点必须返回明确的服务标识。
3097
- * 不走 /api/pair-code(会触发配对码刷新副作用),也不依赖静态页面内容。
3098
- */
3099
- async function probeEcwebReady(port) {
2982
+ async function probeEcwebLiveness(port, record) {
3100
2983
  try {
3101
2984
  const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
3102
2985
  signal: AbortSignal.timeout(2000),
3103
2986
  });
3104
2987
  if (!res.ok)
3105
2988
  return false;
3106
- const body = await res.json();
3107
- return body.ok === true && body.service === 'ecweb';
2989
+ return matchesEcwebInstanceHealth(await res.json(), record);
3108
2990
  }
3109
2991
  catch {
3110
2992
  return false;
3111
2993
  }
3112
2994
  }
2995
+ async function probeEcwebReadiness(port) {
2996
+ try {
2997
+ const res = await fetch(`http://127.0.0.1:${port}/api/ready`, {
2998
+ signal: AbortSignal.timeout(2000),
2999
+ });
3000
+ const body = await res.json().catch(() => ({}));
3001
+ const ready = res.ok
3002
+ && body.ok === true
3003
+ && body.service === 'ecweb'
3004
+ && body.ready === true
3005
+ && body.daemonProtocolCompatible === true;
3006
+ if (ready)
3007
+ return { ready: true };
3008
+ return {
3009
+ ready: false,
3010
+ error: typeof body.daemonProtocolError === 'string'
3011
+ ? body.daemonProtocolError
3012
+ : `readiness endpoint returned HTTP ${res.status}`,
3013
+ };
3014
+ }
3015
+ catch (error) {
3016
+ return { ready: false, error: error instanceof Error ? error.message : String(error) };
3017
+ }
3018
+ }
3113
3019
  /**
3114
3020
  * Wait briefly for an already-launched ECWeb to become healthy. `ec start`,
3115
3021
  * restart-monitor, and the daemon can overlap by a few milliseconds; treating
@@ -3119,7 +3025,7 @@ async function waitForExistingEcweb(p, timeoutMs = 3_000) {
3119
3025
  const deadline = Date.now() + timeoutMs;
3120
3026
  do {
3121
3027
  for (const entry of findAliveEcwebs(p)) {
3122
- if (await probeEcwebReady(entry.port))
3028
+ if (await probeEcwebLiveness(entry.port, entry))
3123
3029
  return entry;
3124
3030
  }
3125
3031
  if (Date.now() >= deadline)
@@ -3130,32 +3036,32 @@ async function waitForExistingEcweb(p, timeoutMs = 3_000) {
3130
3036
  }
3131
3037
  /**
3132
3038
  * 输出 ECWeb 状态。判定口径:
3133
- * 1. HTTP 是否就绪——探测 ECWeb 专用 /api/health 端点。
3039
+ * 1. /api/health 判断进程是否存活,/api/ready 判断 daemon 协议是否就绪。
3134
3040
  * 2. 进程是否存活(instance/ 下的 pid 文件 + isProcessRunning)仅用于补充诊断;
3135
3041
  * 某些 CLI 运行在隔离 PID namespace 中,看不到宿主 ECWeb PID 是正常情况。
3136
3042
  */
3137
- async function printEcwebStatus(p) {
3043
+ async function collectEcwebStatus(p) {
3138
3044
  let externalUrl = null;
3045
+ let enabled = true;
3139
3046
  try {
3140
3047
  const cfg = loadDaemonConfig();
3141
- if (ecwebService(cfg.services)?.enabled === false) {
3142
- console.log('');
3143
- console.log('🔭 ECWeb: 已禁用 (daemon.json → services[name=ecweb].enabled: false)');
3144
- return;
3145
- }
3048
+ enabled = ecwebService(cfg.services)?.enabled !== false;
3146
3049
  externalUrl = resolveEcwebExternalUrl(cfg);
3147
3050
  }
3148
3051
  catch {
3149
- // Agent tool sandboxes may mask daemon.json. Instance and HTTP probes below
3150
- // still provide an authoritative runtime status without local config access.
3052
+ // Runtime and HTTP checks remain useful when config access is restricted.
3151
3053
  }
3054
+ if (!enabled)
3055
+ return { source: 'config', status: 'disabled', port: null, url: null, externalUrl };
3152
3056
  const entries = readEcwebInstanceEntries(p);
3153
3057
  // Probe before consulting PID visibility. The daemon and CLI can be in
3154
3058
  // different PID namespaces while sharing the host network namespace.
3155
- let readyEntry;
3059
+ let liveEntry;
3060
+ let readiness = null;
3156
3061
  for (const entry of entries) {
3157
- if (await probeEcwebReady(entry.record.port)) {
3158
- readyEntry = entry;
3062
+ if (await probeEcwebLiveness(entry.record.port, entry.record)) {
3063
+ liveEntry = entry;
3064
+ readiness = await probeEcwebReadiness(entry.record.port);
3159
3065
  break;
3160
3066
  }
3161
3067
  }
@@ -3167,9 +3073,9 @@ async function printEcwebStatus(p) {
3167
3073
  else {
3168
3074
  // A stale EC Web record must never be used to report the PID of an
3169
3075
  // unrelated process that later inherited the port.
3170
- // Keep a record whose dedicated health endpoint just proved live: the
3171
- // PID may be hidden by a namespace boundary rather than actually dead.
3172
- if (entry.filePath !== readyEntry?.filePath) {
3076
+ // Keep a record whose health endpoint just proved live: the PID may be
3077
+ // hidden by a namespace boundary rather than actually dead.
3078
+ if (entry.filePath !== liveEntry?.filePath) {
3173
3079
  try {
3174
3080
  fs.unlinkSync(entry.filePath);
3175
3081
  }
@@ -3177,52 +3083,106 @@ async function printEcwebStatus(p) {
3177
3083
  }
3178
3084
  }
3179
3085
  }
3180
- if (readyEntry) {
3181
- console.log('');
3182
- const pidVisible = aliveEntries.some(entry => entry.filePath === readyEntry.filePath);
3183
- const pidText = pidVisible ? `PID: ${readyEntry.record.pid}` : `PID: ${readyEntry.record.pid}(当前 namespace 不可见)`;
3184
- console.log(`🔭 ECWeb: 运行中 (${pidText}) http://localhost:${readyEntry.record.port}`);
3185
- if (externalUrl) {
3186
- console.log(` 外网访问: ${externalUrl}`);
3187
- console.log(` 命令行输入 ${MAIN_CLI_BIN} watch web/${WEB_CLI_BIN} 获取配对码`);
3188
- }
3189
- return;
3086
+ if (liveEntry) {
3087
+ const pidVisible = aliveEntries.some(entry => entry.filePath === liveEntry.filePath);
3088
+ return {
3089
+ source: 'health-check',
3090
+ status: readiness?.ready ? 'running' : 'process-not-ready',
3091
+ reason: readiness?.ready ? undefined : 'daemon-not-ready',
3092
+ readinessError: readiness?.ready ? undefined : readiness?.error,
3093
+ pid: liveEntry.record.pid,
3094
+ pidVisible,
3095
+ port: liveEntry.record.port,
3096
+ url: `http://localhost:${liveEntry.record.port}`,
3097
+ externalUrl,
3098
+ };
3190
3099
  }
3191
3100
  const occupiedPids = new Set();
3192
3101
  for (const entry of entries) {
3193
- for (const pid of platform.findProcessByPort(entry.record.port))
3194
- occupiedPids.add(pid);
3102
+ for (const processId of platform.findProcessByPort(entry.record.port))
3103
+ occupiedPids.add(processId);
3195
3104
  }
3196
- console.log('');
3197
3105
  if (aliveEntries.length > 0) {
3198
- const visibleEntry = aliveEntries[0];
3199
- console.log(`🔭 ECWeb: 进程存活 (PID: ${visibleEntry.record.pid}) 但 HTTP 未就绪 (端口 ${visibleEntry.record.port}),查看 logs/ecweb-daemon.log`);
3106
+ return { source: 'instance+process', status: 'process-not-ready', pid: aliveEntries[0].record.pid, port: aliveEntries[0].record.port, url: null, externalUrl };
3200
3107
  }
3201
- else if (occupiedPids.size > 0) {
3202
- console.log(`🔭 ECWeb: 端口仍被未登记进程占用 (PID: ${[...occupiedPids].join(', ')}),请先执行 ec restart`);
3108
+ if (occupiedPids.size > 0) {
3109
+ return { source: 'port-scan', status: 'port-occupied', pids: [...occupiedPids], port: entries[0]?.record.port ?? null, url: null, externalUrl };
3203
3110
  }
3204
- else if (entries.length > 0) {
3111
+ if (entries.length > 0) {
3112
+ return { source: 'instance-record', status: 'recorded-unavailable', port: entries[0].record.port, url: null, externalUrl };
3113
+ }
3114
+ return {
3115
+ source: 'daemon-config',
3116
+ status: externalUrl ? 'enabled-not-running' : 'stopped',
3117
+ port: null,
3118
+ url: null,
3119
+ externalUrl,
3120
+ };
3121
+ }
3122
+ function renderEcwebStatus(status) {
3123
+ console.log('');
3124
+ if (status.status === 'disabled') {
3125
+ console.log('🔭 ECWeb: 已禁用 (daemon.json → services[name=ecweb].enabled: false)');
3126
+ }
3127
+ else if (status.status === 'running') {
3128
+ const pidText = status.pidVisible
3129
+ ? `PID: ${status.pid}`
3130
+ : `PID: ${status.pid}(当前 namespace 不可见)`;
3131
+ console.log(`🔭 ECWeb: 运行中 (${pidText}) http://localhost:${status.port}`);
3132
+ if (status.externalUrl) {
3133
+ console.log(` 外网访问: ${status.externalUrl}`);
3134
+ console.log(` 命令行输入 ${MAIN_CLI_BIN} watch web/${WEB_CLI_BIN} 获取配对码`);
3135
+ }
3136
+ }
3137
+ else if (status.status === 'process-not-ready') {
3138
+ if (status.reason === 'daemon-not-ready') {
3139
+ const detail = status.readinessError ? `:${status.readinessError}` : '';
3140
+ console.log(`🔭 ECWeb: 进程存活 (PID: ${status.pid}) 但 daemon 未就绪 (端口 ${status.port})${detail}`);
3141
+ }
3142
+ else {
3143
+ console.log(`🔭 ECWeb: 进程存活 (PID: ${status.pid}) 但 HTTP 未响应 (端口 ${status.port}),查看 logs/ecweb-daemon.log`);
3144
+ }
3145
+ }
3146
+ else if (status.status === 'port-occupied') {
3147
+ console.log(`🔭 ECWeb: 端口仍被未登记进程占用 (PID: ${status.pids.join(', ')}),请先执行 ec restart`);
3148
+ }
3149
+ else if (status.status === 'recorded-unavailable') {
3205
3150
  console.log('🔭 ECWeb: instance 记录存在,但宿主 PID 不可见且 HTTP 未就绪');
3206
3151
  }
3207
- else if (externalUrl) {
3152
+ else if (status.status === 'enabled-not-running') {
3208
3153
  console.log('🔭 ECWeb: 已启用但未运行,查看 logs/ecweb-daemon.log');
3209
3154
  }
3210
3155
  else {
3211
3156
  console.log('🔭 ECWeb: 未运行');
3212
3157
  }
3213
3158
  }
3214
- function removeEcwebInstanceFiles(p) {
3159
+ function removeEcwebInstanceFiles(p, pid, expectedStartedAt) {
3160
+ if (expectedStartedAt === null)
3161
+ return;
3215
3162
  if (!fs.existsSync(p.instanceDir))
3216
3163
  return;
3217
3164
  for (const file of fs.readdirSync(p.instanceDir)) {
3218
3165
  if (!isEcwebInstanceFile(file))
3219
3166
  continue;
3167
+ if (!new RegExp(`^(?:ecweb|watch-web)-${pid}\\.json$`).test(file))
3168
+ continue;
3220
3169
  try {
3221
- fs.unlinkSync(path.join(p.instanceDir, file));
3170
+ const record = parseEcwebInstanceRecord(JSON.parse(fs.readFileSync(path.join(p.instanceDir, file), 'utf8')), p.root, file);
3171
+ if (record?.startedAt !== undefined && startTimeMatches(expectedStartedAt, record.startedAt)) {
3172
+ fs.unlinkSync(path.join(p.instanceDir, file));
3173
+ }
3222
3174
  }
3223
3175
  catch { }
3224
3176
  }
3225
3177
  }
3178
+ async function stopStartedEcweb(pid, expectedStartedAt) {
3179
+ const actualStartedAt = getProcessStartTime(pid);
3180
+ if (expectedStartedAt === null || actualStartedAt === null || !startTimeMatches(expectedStartedAt, actualStartedAt))
3181
+ return false;
3182
+ if (!platform.killProcess(pid, true))
3183
+ return false;
3184
+ return platform.waitForProcessExit(pid, 5_000);
3185
+ }
3226
3186
  /** 清理 EvolCore 登记的 codex app-server 孤儿进程,返回清理的进程数。 */
3227
3187
  export function stopCodexAppServerOrphans() {
3228
3188
  const entries = listCodexAppServerProcesses();
@@ -3256,22 +3216,38 @@ export function stopCodexAppServerOrphans() {
3256
3216
  }
3257
3217
  /** 若 ecweb 在运行则杀掉并确认 pid/端口都已释放。 */
3258
3218
  async function stopEcwebIfRunning(p) {
3259
- const alive = findAliveEcweb(p);
3260
3219
  const port = ecwebService(loadDaemonConfig().services)?.port ?? DEFAULT_ECWEB_PORT;
3261
- const pids = new Set([
3262
- ...(alive ? [alive.pid] : []),
3263
- ...platform.findProcessByPort(port),
3264
- ]);
3220
+ const entries = readEcwebInstanceEntries(p);
3221
+ const pids = new Set();
3222
+ const ports = new Set([port]);
3223
+ for (const entry of entries) {
3224
+ const { pid, startedAt } = entry.record;
3225
+ if (!platform.isProcessRunning(pid))
3226
+ continue;
3227
+ const actual = getProcessStartTime(pid);
3228
+ if (actual === null || startedAt === undefined) {
3229
+ throw new Error(`Cannot verify ECWeb process identity (PID: ${pid}); refusing to terminate it`);
3230
+ }
3231
+ if (!startTimeMatches(startedAt, actual))
3232
+ continue;
3233
+ pids.add(pid);
3234
+ ports.add(entry.record.port);
3235
+ }
3265
3236
  for (const pid of pids)
3266
3237
  platform.killProcess(pid, true);
3267
3238
  const exited = await Promise.all([...pids].map(pid => platform.waitForProcessExit(pid, 5_000)));
3268
- const portReleased = await waitForPortRelease(port, 5_000);
3269
- if (exited.some(result => !result) || !portReleased) {
3270
- throw new Error(`EC Web old process or port ${port} could not be released`);
3239
+ const released = await Promise.all([...ports].map(target => waitForPortRelease(target, 5_000)));
3240
+ if (exited.some(result => !result) || released.some(result => !result)) {
3241
+ throw new Error(`EC Web old process or port ${port} could not be released; unrelated listeners are not terminated`);
3271
3242
  }
3272
3243
  // 清理 pid 文件(仅 ecweb-<pid>.json / watch-web-<pid>.json,
3273
3244
  // 不碰 daemon-owned control-access-tokens.json 等非 pid 文件,否则会清空凭据库导致每次重启都要重新配对)
3274
- removeEcwebInstanceFiles(p);
3245
+ for (const entry of entries) {
3246
+ try {
3247
+ fs.unlinkSync(entry.filePath);
3248
+ }
3249
+ catch { }
3250
+ }
3275
3251
  return pids.size > 0;
3276
3252
  }
3277
3253
  async function waitForPortRelease(port, timeoutMs) {
@@ -3302,6 +3278,9 @@ export async function startEcwebIfEnabled(p, options = {}) {
3302
3278
  const existing = await waitForExistingEcweb(p);
3303
3279
  if (existing) {
3304
3280
  console.log(`✓ ECWeb 已在运行 (PID: ${existing.pid}) http://localhost:${existing.port}`);
3281
+ const readiness = await probeEcwebReadiness(existing.port);
3282
+ if (!readiness.ready)
3283
+ console.log(`⚠ ECWeb 进程存活但 daemon 未就绪: ${readiness.error || 'unknown'}`);
3305
3284
  if (externalUrl)
3306
3285
  console.log(` 外网访问: ${externalUrl}`);
3307
3286
  return true;
@@ -3345,6 +3324,7 @@ export async function startEcwebIfEnabled(p, options = {}) {
3345
3324
  return false;
3346
3325
  }
3347
3326
  let startedPid;
3327
+ let startedAt = null;
3348
3328
  try {
3349
3329
  const child = spawn(launch.command, launch.args, {
3350
3330
  detached: true,
@@ -3352,7 +3332,7 @@ export async function startEcwebIfEnabled(p, options = {}) {
3352
3332
  windowsHide: true,
3353
3333
  env: {
3354
3334
  ...process.env,
3355
- EVOLCORE_PACKAGE_ROOT: getPackageRoot(),
3335
+ EVOLCORE_HOME: p.root,
3356
3336
  },
3357
3337
  });
3358
3338
  child.unref();
@@ -3362,31 +3342,30 @@ export async function startEcwebIfEnabled(p, options = {}) {
3362
3342
  console.log('❌ ECWeb 启动失败(进程创建失败)');
3363
3343
  return false;
3364
3344
  }
3365
- fs.mkdirSync(p.instanceDir, { recursive: true });
3366
- const startedAt = getProcessStartTime(pid) ?? Date.now();
3367
- fs.writeFileSync(path.join(p.instanceDir, `ecweb-${pid}.json`), JSON.stringify({ pid, port, startedAt, startedAtIso: new Date(startedAt).toISOString() }, null, 2));
3368
- // 轮询端口确认 HTTP 服务真正就绪(spawn 成功 ≠ 端口绑定成功)。
3369
- // 配对码由 daemon 提供,daemon 尚未启动时不应把已经就绪的 ECWeb 杀掉。
3370
- let ready = false;
3345
+ startedAt = getProcessStartTime(pid);
3346
+ let processAlive = false;
3347
+ let readiness = null;
3371
3348
  let pair = null;
3372
- for (let i = 0; i < 20; i++) {
3373
- ready = await probeEcwebReady(port);
3374
- if (ready) {
3375
- pair = await fetchRemotePairingCode();
3349
+ for (let i = 0; i < 40; i++) {
3350
+ const registered = readEcwebInstanceEntries(p).find(entry => entry.record.pid === pid)?.record;
3351
+ processAlive = registered ? await probeEcwebLiveness(registered.port, registered) : false;
3352
+ if (processAlive) {
3353
+ readiness = await probeEcwebReadiness(port);
3354
+ if (readiness.ready)
3355
+ pair = await fetchRemotePairingCode();
3376
3356
  break;
3377
3357
  }
3378
3358
  await sleep(250);
3379
3359
  }
3380
- if (ready) {
3381
- const actualStartedAt = getProcessStartTime(pid);
3382
- if (actualStartedAt !== null) {
3383
- fs.writeFileSync(path.join(p.instanceDir, `ecweb-${pid}.json`), JSON.stringify({ pid, port, startedAt: actualStartedAt, startedAtIso: new Date(actualStartedAt).toISOString() }, null, 2));
3384
- }
3360
+ if (processAlive) {
3385
3361
  const actionLabel = wasRunning ? '已重启' : '启动成功';
3386
3362
  console.log(`✓ ECWeb ${actionLabel} (PID: ${pid}) http://localhost:${port}`);
3387
3363
  if (externalUrl)
3388
3364
  console.log(` 外网访问: ${externalUrl}`);
3389
- if (pair) {
3365
+ if (!readiness?.ready) {
3366
+ console.log(`⚠ ECWeb 进程存活但 daemon 未就绪: ${readiness?.error || 'unknown'}`);
3367
+ }
3368
+ else if (pair) {
3390
3369
  const mins = Math.max(0, Math.round((pair.expiresAt - Date.now()) / 60000));
3391
3370
  console.log(` 配对码: ${pair.code} (约 ${mins} 分钟内有效,仅可配对一次,已配对过的浏览器无需重新配对)`);
3392
3371
  }
@@ -3396,17 +3375,20 @@ export async function startEcwebIfEnabled(p, options = {}) {
3396
3375
  return true;
3397
3376
  }
3398
3377
  console.log(`❌ ECWeb 启动失败:端口 ${port} 未就绪(进程 PID ${pid} 可能已退出,查看 logs/watch-web.log)`);
3399
- platform.killProcess(pid, true);
3400
- await platform.waitForProcessExit(pid, 5_000);
3401
- removeEcwebInstanceFiles(p);
3378
+ if (!await stopStartedEcweb(pid, startedAt)) {
3379
+ console.log(`⚠ 无法确认 ECWeb PID ${pid} 仍为本次启动的进程,未发送终止信号`);
3380
+ }
3381
+ removeEcwebInstanceFiles(p, pid, startedAt);
3402
3382
  return false;
3403
3383
  }
3404
3384
  catch (err) {
3405
3385
  if (startedPid) {
3406
- platform.killProcess(startedPid, true);
3407
- await platform.waitForProcessExit(startedPid, 5_000);
3386
+ if (!await stopStartedEcweb(startedPid, startedAt)) {
3387
+ console.log(`⚠ 无法确认 ECWeb PID ${startedPid} 仍为本次启动的进程,未发送终止信号`);
3388
+ }
3408
3389
  }
3409
- removeEcwebInstanceFiles(p);
3390
+ if (startedPid)
3391
+ removeEcwebInstanceFiles(p, startedPid, startedAt);
3410
3392
  console.log(`⚠ ECWeb 启动失败: ${err instanceof Error ? err.message : String(err)}`);
3411
3393
  console.log(` command: ${launch.command}`);
3412
3394
  console.log(` args: ${JSON.stringify(launch.args)}`);
@@ -3676,7 +3658,7 @@ export async function cmdDiagnose(args = []) {
3676
3658
  const unregisteredPids = portPids.filter(pid => !recordedPids.has(pid));
3677
3659
  if (unregisteredPids.length > 0) {
3678
3660
  console.error(`[diagnose] ❌ EC Web 端口 ${port} 被未登记进程占用: PID ${unregisteredPids.join(', ')}`);
3679
- console.error('[diagnose] 请执行 ec restart 清理 EC Web 后再启动。');
3661
+ console.error('[diagnose] 请核实占用进程或修改 ECWeb 端口;不会自动结束未登记服务。');
3680
3662
  hasError = true;
3681
3663
  }
3682
3664
  else {