evolcore 0.0.40 → 0.0.41-test.1

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