evolcore 0.0.41-test.0 → 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 (177) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +20 -43
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +84 -28
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/group/fs-download.js +39 -0
  9. package/dist/aun/group/identity.js +36 -21
  10. package/dist/aun/group/operations.js +5 -0
  11. package/dist/aun/msg/managed-operation.js +68 -7
  12. package/dist/aun/msg/p2p.js +5 -0
  13. package/dist/aun/service-proxy.js +36 -12
  14. package/dist/channels/aun.js +334 -20
  15. package/dist/channels/daemon.js +15 -1
  16. package/dist/cli/aun-commands.js +4 -20
  17. package/dist/cli/daemon-commands.js +678 -697
  18. package/dist/cli/fs-command.js +64 -2
  19. package/dist/cli/index.js +48 -4
  20. package/dist/cli/managed-command-guard.js +4 -0
  21. package/dist/cli/model.js +40 -40
  22. package/dist/cli/proxy-command.js +92 -0
  23. package/dist/cli/role.js +85 -0
  24. package/dist/config/access-policy.js +7 -2
  25. package/dist/config/boot-log.js +38 -1
  26. package/dist/config/config-field-policy.js +5 -32
  27. package/dist/config/config-manager.js +46 -39
  28. package/dist/config/config-operation-service.js +5 -19
  29. package/dist/config/contact-book-store.js +47 -21
  30. package/dist/config/contact-book.js +18 -12
  31. package/dist/config/contact-operation-service.js +3 -4
  32. package/dist/config/contact-request-service.js +11 -0
  33. package/dist/config/daemon-services.js +11 -0
  34. package/dist/config/gateway-config.js +88 -594
  35. package/dist/config/peer-role-resolver.js +13 -11
  36. package/dist/config/providers-config.js +12 -7
  37. package/dist/config/providers-import.js +3 -21
  38. package/dist/config/resolved-config-op.js +3 -0
  39. package/dist/config/role-command-service.js +166 -0
  40. package/dist/config/role-request-service.js +193 -0
  41. package/dist/config/schema-migration.js +686 -25
  42. package/dist/config-store.js +79 -3
  43. package/dist/contracts/ecweb-instance.js +41 -0
  44. package/dist/contracts/ecweb-service-protocol.js +3 -1
  45. package/dist/core/agent-runtime.js +1 -1
  46. package/dist/core/auth/agent-delegation.js +2 -1
  47. package/dist/core/auth/auth-gateway.js +1 -1
  48. package/dist/core/auth/authorization-audit.js +17 -6
  49. package/dist/core/auth/delegation-authorization.js +3 -1
  50. package/dist/core/auth/operation-authorizer.js +15 -0
  51. package/dist/core/auth/operation-catalog.js +31 -6
  52. package/dist/core/command/agent-control.js +3 -7
  53. package/dist/core/command/agent-storage-menu.js +5 -3
  54. package/dist/core/command/cli-intent-parser.js +2 -1
  55. package/dist/core/command/command-handler.js +48 -99
  56. package/dist/core/command/connect-menu.js +11 -3
  57. package/dist/core/command/data-root-resolver.js +5 -4
  58. package/dist/core/command/memory-slash.js +16 -8
  59. package/dist/core/command/menu-catalog.js +5 -6
  60. package/dist/core/command/menu-handler.js +49 -62
  61. package/dist/core/command/role-menu.js +147 -30
  62. package/dist/core/command/slash-handler.js +123 -254
  63. package/dist/core/daemon-control.js +8 -14
  64. package/dist/core/evolagent-registry.js +4 -4
  65. package/dist/core/evolagent.js +2 -2
  66. package/dist/core/inference/text-inference.js +31 -40
  67. package/dist/core/ipc-registration.js +6 -2
  68. package/dist/core/memory/consolidation-context.js +51 -5
  69. package/dist/core/memory/consolidation-ops-records.js +1 -1
  70. package/dist/core/memory/consolidation-trigger.js +189 -189
  71. package/dist/core/memory/consolidation.js +316 -29
  72. package/dist/core/memory/forget-log.js +96 -0
  73. package/dist/core/memory/index-manager.js +27 -5
  74. package/dist/core/memory/memory-admin.js +45 -5
  75. package/dist/core/memory/memory-writer.js +163 -18
  76. package/dist/core/memory/relation-idle-monitor.js +119 -58
  77. package/dist/core/memory/relation-sweep.js +44 -39
  78. package/dist/core/message/aun-ipc-sender.js +8 -2
  79. package/dist/core/message/im-renderer.js +7 -4
  80. package/dist/core/message/message-admission.js +89 -4
  81. package/dist/core/message/message-bridge.js +31 -18
  82. package/dist/core/message/response-engine.js +77 -8
  83. package/dist/core/model/catalog-service.js +4 -2
  84. package/dist/core/model/config-scope.js +24 -64
  85. package/dist/core/model/field-scope.js +1 -1
  86. package/dist/core/model/model-catalog.js +30 -41
  87. package/dist/core/model/model-diagnostics.js +4 -3
  88. package/dist/core/model/model-fallback.js +10 -7
  89. package/dist/core/model/model-permission.js +3 -2
  90. package/dist/core/ownership/owner-resolver.js +23 -21
  91. package/dist/core/permission/ec-command-parser.js +30 -2
  92. package/dist/core/permission/sandbox-runtime.js +18 -1
  93. package/dist/core/permission/tool-policy.js +14 -3
  94. package/dist/core/relation/peer-identity.js +64 -1
  95. package/dist/core/role/runtime-policy.js +72 -13
  96. package/dist/core/session/session-capsule.js +1 -1
  97. package/dist/core/session/session-idle-monitor.js +1 -1
  98. package/dist/core/session/session-manager.js +20 -0
  99. package/dist/core/session/session-renew.js +3 -3
  100. package/dist/core/skill/index-generator.js +15 -5
  101. package/dist/core/system-session/memory.js +6 -1
  102. package/dist/core/thread/thread-service.js +19 -6
  103. package/dist/directory/owner-directory-admission.js +95 -0
  104. package/dist/directory/owner-directory-authorization.js +309 -0
  105. package/dist/directory/owner-directory-cache.js +635 -0
  106. package/dist/eck/kit-renderer.js +2 -2
  107. package/dist/ecweb/basic-settings-service.js +33 -40
  108. package/dist/ecweb/message-context-service.js +110 -0
  109. package/dist/index.js +76 -14
  110. package/dist/ipc.js +170 -12
  111. package/dist/paths.js +4 -0
  112. package/dist/proxy/command.js +122 -0
  113. package/dist/proxy/ipc-service.js +68 -0
  114. package/dist/proxy/manager.js +485 -0
  115. package/dist/proxy/service-supervisor.js +603 -0
  116. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  117. package/dist/utils/cross-platform.js +14 -0
  118. package/dist/utils/ecweb-supervisor.js +258 -83
  119. package/dist/utils/error-utils.js +2 -2
  120. package/dist/utils/logger.js +24 -5
  121. package/dist/utils/package-version-info.js +4 -2
  122. package/kits/docs/channels/aun.md +9 -0
  123. package/kits/docs/evolcore/agent.md +1 -1
  124. package/kits/docs/evolcore/config.md +17 -6
  125. package/kits/docs/evolcore/contact.md +3 -0
  126. package/kits/docs/evolcore/fs.md +11 -0
  127. package/kits/docs/evolcore/memory-architecture.md +2 -2
  128. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  129. package/kits/docs/evolcore/memory.md +1 -1
  130. package/kits/docs/evolcore/menu-protocol.md +4 -0
  131. package/kits/docs/evolcore/model.md +23 -20
  132. package/kits/docs/evolcore/msg.md +4 -7
  133. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  134. package/kits/schemas/_meta.json +37 -4
  135. package/kits/schemas/agent-config.schema.13.json +8 -3
  136. package/kits/schemas/agent-config.schema.16.json +891 -0
  137. package/kits/schemas/daemon.schema.9.json +366 -0
  138. package/kits/schemas/defaults.schema.5.json +406 -127
  139. package/kits/schemas/relation-config.schema.11.json +260 -0
  140. package/kits/schemas/role-config.schema.1.json +7 -7
  141. package/kits/skills/.switches.json +3 -7
  142. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  143. package/kits/skills/ec-trigger/SKILL.md +13 -5
  144. package/kits/skills/personal-assistant/SKILL.md +176 -0
  145. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  147. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  148. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  149. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  150. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  151. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  152. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  153. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  154. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  155. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  156. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  157. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  158. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  159. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  160. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  161. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  162. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  163. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  164. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  165. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  166. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  167. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  168. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  169. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  170. package/kits/templates/memory-consolidation/forget.md +19 -6
  171. package/kits/templates/memory-consolidation/notes.md +1 -1
  172. package/kits/templates/memory-consolidation/profile.md +2 -2
  173. package/kits/templates/memory-consolidation/promote.md +20 -3
  174. package/kits/templates/roles/member.json +8 -1
  175. package/kits/templates/system-fragments/baseagent.md +2 -2
  176. package/kits/templates/system-fragments/memory.md +4 -4
  177. package/package.json +6 -2
@@ -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,517 +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
- // 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。');
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(', ')})`);
1649
1738
  }
1650
1739
  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
- }
1740
+ console.log(snapshot.overall.status === 'stopped' ? '⚠ EvolCore is not running'
1741
+ : '⚠ 无法确认 EvolCore 运行状态:IPC 不可用。');
1768
1742
  }
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
- }
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);
1776
1749
  }
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);
1750
+ renderEcwebStatus(snapshot.ecweb);
1828
1751
  }
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(', ');
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);
1868
1758
  }
1869
1759
  // Log line pattern: [timestamp] [LEVEL] [Module?] message
1870
1760
  const LOG_RE = /^(\[[^\]]+\]) (\[(?:INFO|WARN|ERROR|DEBUG)\]) ((?:\[[^\]]+\] )*)(.*)$/;
@@ -3060,13 +2950,9 @@ function readEcwebInstanceEntries(p) {
3060
2950
  continue;
3061
2951
  const filePath = path.join(p.instanceDir, file);
3062
2952
  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
- }
2953
+ const record = parseEcwebInstanceRecord(JSON.parse(fs.readFileSync(filePath, 'utf-8')), p.root, file);
2954
+ if (record)
2955
+ entries.push({ record, filePath });
3070
2956
  }
3071
2957
  catch { }
3072
2958
  }
@@ -3092,24 +2978,43 @@ function findAliveEcweb(p) {
3092
2978
  const alive = findAliveEcwebs(p);
3093
2979
  return alive[0] ?? null;
3094
2980
  }
3095
- /**
3096
- * 轻量 HTTP 就绪探测:ECWeb 的健康端点必须返回明确的服务标识。
3097
- * 不走 /api/pair-code(会触发配对码刷新副作用),也不依赖静态页面内容。
3098
- */
3099
- async function probeEcwebReady(port) {
2981
+ async function probeEcwebLiveness(port, record) {
3100
2982
  try {
3101
2983
  const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
3102
2984
  signal: AbortSignal.timeout(2000),
3103
2985
  });
3104
2986
  if (!res.ok)
3105
2987
  return false;
3106
- const body = await res.json();
3107
- return body.ok === true && body.service === 'ecweb';
2988
+ return matchesEcwebInstanceHealth(await res.json(), record);
3108
2989
  }
3109
2990
  catch {
3110
2991
  return false;
3111
2992
  }
3112
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
+ }
3113
3018
  /**
3114
3019
  * Wait briefly for an already-launched ECWeb to become healthy. `ec start`,
3115
3020
  * restart-monitor, and the daemon can overlap by a few milliseconds; treating
@@ -3119,7 +3024,7 @@ async function waitForExistingEcweb(p, timeoutMs = 3_000) {
3119
3024
  const deadline = Date.now() + timeoutMs;
3120
3025
  do {
3121
3026
  for (const entry of findAliveEcwebs(p)) {
3122
- if (await probeEcwebReady(entry.port))
3027
+ if (await probeEcwebLiveness(entry.port, entry))
3123
3028
  return entry;
3124
3029
  }
3125
3030
  if (Date.now() >= deadline)
@@ -3130,32 +3035,32 @@ async function waitForExistingEcweb(p, timeoutMs = 3_000) {
3130
3035
  }
3131
3036
  /**
3132
3037
  * 输出 ECWeb 状态。判定口径:
3133
- * 1. HTTP 是否就绪——探测 ECWeb 专用 /api/health 端点。
3038
+ * 1. /api/health 判断进程是否存活,/api/ready 判断 daemon 协议是否就绪。
3134
3039
  * 2. 进程是否存活(instance/ 下的 pid 文件 + isProcessRunning)仅用于补充诊断;
3135
3040
  * 某些 CLI 运行在隔离 PID namespace 中,看不到宿主 ECWeb PID 是正常情况。
3136
3041
  */
3137
- async function printEcwebStatus(p) {
3042
+ async function collectEcwebStatus(p) {
3138
3043
  let externalUrl = null;
3044
+ let enabled = true;
3139
3045
  try {
3140
3046
  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
- }
3047
+ enabled = ecwebService(cfg.services)?.enabled !== false;
3146
3048
  externalUrl = resolveEcwebExternalUrl(cfg);
3147
3049
  }
3148
3050
  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.
3051
+ // Runtime and HTTP checks remain useful when config access is restricted.
3151
3052
  }
3053
+ if (!enabled)
3054
+ return { source: 'config', status: 'disabled', port: null, url: null, externalUrl };
3152
3055
  const entries = readEcwebInstanceEntries(p);
3153
3056
  // Probe before consulting PID visibility. The daemon and CLI can be in
3154
3057
  // different PID namespaces while sharing the host network namespace.
3155
- let readyEntry;
3058
+ let liveEntry;
3059
+ let readiness = null;
3156
3060
  for (const entry of entries) {
3157
- if (await probeEcwebReady(entry.record.port)) {
3158
- readyEntry = entry;
3061
+ if (await probeEcwebLiveness(entry.record.port, entry.record)) {
3062
+ liveEntry = entry;
3063
+ readiness = await probeEcwebReadiness(entry.record.port);
3159
3064
  break;
3160
3065
  }
3161
3066
  }
@@ -3167,9 +3072,9 @@ async function printEcwebStatus(p) {
3167
3072
  else {
3168
3073
  // A stale EC Web record must never be used to report the PID of an
3169
3074
  // 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) {
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) {
3173
3078
  try {
3174
3079
  fs.unlinkSync(entry.filePath);
3175
3080
  }
@@ -3177,52 +3082,106 @@ async function printEcwebStatus(p) {
3177
3082
  }
3178
3083
  }
3179
3084
  }
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;
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
+ };
3190
3098
  }
3191
3099
  const occupiedPids = new Set();
3192
3100
  for (const entry of entries) {
3193
- for (const pid of platform.findProcessByPort(entry.record.port))
3194
- occupiedPids.add(pid);
3101
+ for (const processId of platform.findProcessByPort(entry.record.port))
3102
+ occupiedPids.add(processId);
3195
3103
  }
3196
- console.log('');
3197
3104
  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`);
3105
+ return { source: 'instance+process', status: 'process-not-ready', pid: aliveEntries[0].record.pid, port: aliveEntries[0].record.port, url: null, externalUrl };
3200
3106
  }
3201
- else if (occupiedPids.size > 0) {
3202
- 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 };
3203
3109
  }
3204
- 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') {
3205
3149
  console.log('🔭 ECWeb: instance 记录存在,但宿主 PID 不可见且 HTTP 未就绪');
3206
3150
  }
3207
- else if (externalUrl) {
3151
+ else if (status.status === 'enabled-not-running') {
3208
3152
  console.log('🔭 ECWeb: 已启用但未运行,查看 logs/ecweb-daemon.log');
3209
3153
  }
3210
3154
  else {
3211
3155
  console.log('🔭 ECWeb: 未运行');
3212
3156
  }
3213
3157
  }
3214
- function removeEcwebInstanceFiles(p) {
3158
+ function removeEcwebInstanceFiles(p, pid, expectedStartedAt) {
3159
+ if (expectedStartedAt === null)
3160
+ return;
3215
3161
  if (!fs.existsSync(p.instanceDir))
3216
3162
  return;
3217
3163
  for (const file of fs.readdirSync(p.instanceDir)) {
3218
3164
  if (!isEcwebInstanceFile(file))
3219
3165
  continue;
3166
+ if (!new RegExp(`^(?:ecweb|watch-web)-${pid}\\.json$`).test(file))
3167
+ continue;
3220
3168
  try {
3221
- 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
+ }
3222
3173
  }
3223
3174
  catch { }
3224
3175
  }
3225
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
+ }
3226
3185
  /** 清理 EvolCore 登记的 codex app-server 孤儿进程,返回清理的进程数。 */
3227
3186
  export function stopCodexAppServerOrphans() {
3228
3187
  const entries = listCodexAppServerProcesses();
@@ -3256,22 +3215,38 @@ export function stopCodexAppServerOrphans() {
3256
3215
  }
3257
3216
  /** 若 ecweb 在运行则杀掉并确认 pid/端口都已释放。 */
3258
3217
  async function stopEcwebIfRunning(p) {
3259
- const alive = findAliveEcweb(p);
3260
3218
  const port = ecwebService(loadDaemonConfig().services)?.port ?? DEFAULT_ECWEB_PORT;
3261
- const pids = new Set([
3262
- ...(alive ? [alive.pid] : []),
3263
- ...platform.findProcessByPort(port),
3264
- ]);
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
+ }
3265
3235
  for (const pid of pids)
3266
3236
  platform.killProcess(pid, true);
3267
3237
  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`);
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`);
3271
3241
  }
3272
3242
  // 清理 pid 文件(仅 ecweb-<pid>.json / watch-web-<pid>.json,
3273
3243
  // 不碰 daemon-owned control-access-tokens.json 等非 pid 文件,否则会清空凭据库导致每次重启都要重新配对)
3274
- removeEcwebInstanceFiles(p);
3244
+ for (const entry of entries) {
3245
+ try {
3246
+ fs.unlinkSync(entry.filePath);
3247
+ }
3248
+ catch { }
3249
+ }
3275
3250
  return pids.size > 0;
3276
3251
  }
3277
3252
  async function waitForPortRelease(port, timeoutMs) {
@@ -3302,6 +3277,9 @@ export async function startEcwebIfEnabled(p, options = {}) {
3302
3277
  const existing = await waitForExistingEcweb(p);
3303
3278
  if (existing) {
3304
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'}`);
3305
3283
  if (externalUrl)
3306
3284
  console.log(` 外网访问: ${externalUrl}`);
3307
3285
  return true;
@@ -3345,6 +3323,7 @@ export async function startEcwebIfEnabled(p, options = {}) {
3345
3323
  return false;
3346
3324
  }
3347
3325
  let startedPid;
3326
+ let startedAt = null;
3348
3327
  try {
3349
3328
  const child = spawn(launch.command, launch.args, {
3350
3329
  detached: true,
@@ -3352,7 +3331,7 @@ export async function startEcwebIfEnabled(p, options = {}) {
3352
3331
  windowsHide: true,
3353
3332
  env: {
3354
3333
  ...process.env,
3355
- EVOLCORE_PACKAGE_ROOT: getPackageRoot(),
3334
+ EVOLCORE_HOME: p.root,
3356
3335
  },
3357
3336
  });
3358
3337
  child.unref();
@@ -3362,31 +3341,30 @@ export async function startEcwebIfEnabled(p, options = {}) {
3362
3341
  console.log('❌ ECWeb 启动失败(进程创建失败)');
3363
3342
  return false;
3364
3343
  }
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;
3344
+ startedAt = getProcessStartTime(pid);
3345
+ let processAlive = false;
3346
+ let readiness = null;
3371
3347
  let pair = null;
3372
- for (let i = 0; i < 20; i++) {
3373
- ready = await probeEcwebReady(port);
3374
- if (ready) {
3375
- 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();
3376
3355
  break;
3377
3356
  }
3378
3357
  await sleep(250);
3379
3358
  }
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
- }
3359
+ if (processAlive) {
3385
3360
  const actionLabel = wasRunning ? '已重启' : '启动成功';
3386
3361
  console.log(`✓ ECWeb ${actionLabel} (PID: ${pid}) http://localhost:${port}`);
3387
3362
  if (externalUrl)
3388
3363
  console.log(` 外网访问: ${externalUrl}`);
3389
- if (pair) {
3364
+ if (!readiness?.ready) {
3365
+ console.log(`⚠ ECWeb 进程存活但 daemon 未就绪: ${readiness?.error || 'unknown'}`);
3366
+ }
3367
+ else if (pair) {
3390
3368
  const mins = Math.max(0, Math.round((pair.expiresAt - Date.now()) / 60000));
3391
3369
  console.log(` 配对码: ${pair.code} (约 ${mins} 分钟内有效,仅可配对一次,已配对过的浏览器无需重新配对)`);
3392
3370
  }
@@ -3396,17 +3374,20 @@ export async function startEcwebIfEnabled(p, options = {}) {
3396
3374
  return true;
3397
3375
  }
3398
3376
  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);
3377
+ if (!await stopStartedEcweb(pid, startedAt)) {
3378
+ console.log(`⚠ 无法确认 ECWeb PID ${pid} 仍为本次启动的进程,未发送终止信号`);
3379
+ }
3380
+ removeEcwebInstanceFiles(p, pid, startedAt);
3402
3381
  return false;
3403
3382
  }
3404
3383
  catch (err) {
3405
3384
  if (startedPid) {
3406
- platform.killProcess(startedPid, true);
3407
- await platform.waitForProcessExit(startedPid, 5_000);
3385
+ if (!await stopStartedEcweb(startedPid, startedAt)) {
3386
+ console.log(`⚠ 无法确认 ECWeb PID ${startedPid} 仍为本次启动的进程,未发送终止信号`);
3387
+ }
3408
3388
  }
3409
- removeEcwebInstanceFiles(p);
3389
+ if (startedPid)
3390
+ removeEcwebInstanceFiles(p, startedPid, startedAt);
3410
3391
  console.log(`⚠ ECWeb 启动失败: ${err instanceof Error ? err.message : String(err)}`);
3411
3392
  console.log(` command: ${launch.command}`);
3412
3393
  console.log(` args: ${JSON.stringify(launch.args)}`);
@@ -3676,7 +3657,7 @@ export async function cmdDiagnose(args = []) {
3676
3657
  const unregisteredPids = portPids.filter(pid => !recordedPids.has(pid));
3677
3658
  if (unregisteredPids.length > 0) {
3678
3659
  console.error(`[diagnose] ❌ EC Web 端口 ${port} 被未登记进程占用: PID ${unregisteredPids.join(', ')}`);
3679
- console.error('[diagnose] 请执行 ec restart 清理 EC Web 后再启动。');
3660
+ console.error('[diagnose] 请核实占用进程或修改 ECWeb 端口;不会自动结束未登记服务。');
3680
3661
  hasError = true;
3681
3662
  }
3682
3663
  else {