evolcore 0.0.43-test.7 → 0.0.43-test.8

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 (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
@@ -11,7 +11,7 @@ import { applyCachedPackageUpgrades, recordPackageUpgrade } from '../utils/packa
11
11
  import { acknowledgeUpgradeRestart, readUpgradeJob, updateUpgradeJob } from '../utils/upgrade-jobs.js';
12
12
  import { isValidAid } from '../aun/aid/validation.js';
13
13
  import { scanInstances, cleanupInstances, writeRestartMonitor, removeRestartMonitor, isRestartMonitorWinner, findOrphanProcesses, killOrphans, updateRestartMonitorPhase } from '../utils/instance-registry.js';
14
- import { CHANNEL_LOGS_ENV, MAIN_PACKAGE_NAME, RESTART_REQUEST_ID_ENV } from '../product.js';
14
+ import { CHANNEL_LOGS_ENV, MAIN_PACKAGE_NAME, RESTART_REQUEST_ID_ENV, TARGET_PACKAGE_ROOT_ENV } from '../product.js';
15
15
  import { readRestartRequest, updateRestartRequest, removeRestartRequest, shouldSuppressRealRestart } from '../utils/restart-safety.js';
16
16
  import { rotateStdoutLog } from '../utils/log-writer.js';
17
17
  import { applyDataMigration, finalizeDataMigration, planDataMigration, verifyDataMigration, } from '../core/data-migration.js';
@@ -88,7 +88,7 @@ async function finishSuccessfulRestart() {
88
88
  * exactly `getPackageRoot()` and behaviour is unchanged.
89
89
  */
90
90
  function targetPackageRoot() {
91
- return process.env.EVOLCORE_TARGET_PACKAGE_ROOT || getPackageRoot();
91
+ return process.env[TARGET_PACKAGE_ROOT_ENV] || getPackageRoot();
92
92
  }
93
93
  // 清理 Claude Code 环境变量,防止 SDK 认为是嵌套会话
94
94
  function cleanEnv() {
@@ -454,12 +454,18 @@ export async function cmdRestartMonitor() {
454
454
  // Apply only the preflight cache. There is no registry VERSION query after
455
455
  // shutdown (npm still downloads the exact cached package when needed).
456
456
  log('Applying cached version information...');
457
- // 升级会原地替换整包,先留一个可回退的产物副本。备份放 EVOLCORE_HOME 而非包目录:
458
- // Linux/macOS 的全局目录常常不可写,而 HOME 一定可写。
459
- upgradeBackup = await backupDistForUpgrade(p, log);
460
457
  [upgrade] = await applyCachedPackageUpgrades(undefined, {
461
458
  log,
462
459
  ...(upgradeJob ? { target: upgradeJob.target, distTag: upgradeJob.distTag, npmConfig: upgradeJob.npmConfig } : {}),
460
+ beforeInstall: async (name) => {
461
+ if (name !== MAIN_PACKAGE_NAME)
462
+ return;
463
+ // npm replaces package metadata, schemas and runtime files together.
464
+ upgradeBackup = await backupPackageForUpgrade(p, log);
465
+ if (!upgradeBackup && !fs.existsSync(path.join(targetPackageRoot(), 'src'))) {
466
+ throw new Error('Package backup unavailable; upgrade was not attempted');
467
+ }
468
+ },
463
469
  });
464
470
  }
465
471
  else {
@@ -473,12 +479,15 @@ export async function cmdRestartMonitor() {
473
479
  if (!distArtifactIsUsable(path.join(targetPackageRoot(), 'dist'))) {
474
480
  // npm 报成功但产物不完整:当作升级失败处理。
475
481
  log('❌ Upgrade left an incomplete dist/');
476
- if (await restoreDistBackup(upgradeBackup, log)) {
482
+ if (await restorePackageBackup(upgradeBackup, log)) {
477
483
  upgradeRolledBack = `升级到 ${upgrade.to} 后产物不完整,已回滚到 ${upgrade.from}`;
478
484
  await notifyDaemonOwners(p, `⚠️ ${upgradeRolledBack}`, log);
479
485
  }
480
486
  else {
481
487
  await notifyDaemonOwners(p, `❌ 升级到 ${upgrade.to} 后产物不完整,且回滚失败,请人工检查`, log);
488
+ markRestartOutcome(pendingFile, 'rollback-failed', 'Upgraded package is incomplete and rollback failed', log, hasCorrelatedRequest ? requestId : undefined);
489
+ cleanupPendingFile(pendingFile, log, hasCorrelatedRequest ? requestId : undefined);
490
+ process.exit(1);
482
491
  }
483
492
  }
484
493
  else {
@@ -498,11 +507,15 @@ export async function cmdRestartMonitor() {
498
507
  break;
499
508
  case 'failed':
500
509
  log(`⚠ Upgrade failed (${upgrade.from} → ${upgrade.to}): ${upgrade.error}`);
501
- // 安装可能中途失败并留下残缺目录,此时必须用备份恢复才敢继续启动。
502
- if (!distArtifactIsUsable(path.join(targetPackageRoot(), 'dist'))) {
503
- log('❌ Failed upgrade left an unusable dist/');
504
- if (await restoreDistBackup(upgradeBackup, log)) {
505
- upgradeRolledBack = `升级失败且产物受损,已回滚到 ${upgrade.from}`;
510
+ // Even when entry files exist, npm may have replaced schemas or only part of the dependency tree.
511
+ if (upgradeBackup) {
512
+ if (await restorePackageBackup(upgradeBackup, log)) {
513
+ upgradeRolledBack = `升级失败,已完整回滚到 ${upgrade.from}`;
514
+ }
515
+ else {
516
+ markRestartOutcome(pendingFile, 'rollback-failed', upgrade.error, log, hasCorrelatedRequest ? requestId : undefined);
517
+ cleanupPendingFile(pendingFile, log, hasCorrelatedRequest ? requestId : undefined);
518
+ process.exit(1);
506
519
  }
507
520
  }
508
521
  await notifyDaemonOwners(p, `⚠️ evolcore 升级失败,使用当前版本继续\n${upgrade.error ?? ''}`.trim(), log);
@@ -572,7 +585,7 @@ export async function cmdRestartMonitor() {
572
585
  await recordPackageUpgrade(MAIN_PACKAGE_NAME, {
573
586
  ...upgradeVersions, at: new Date().toISOString(), status: 'failed', error: 'Upgraded daemon failed its ready check',
574
587
  }, log);
575
- if (await restoreDistBackup(upgradeBackup, log)) {
588
+ if (await restorePackageBackup(upgradeBackup, log)) {
576
589
  await notifyDaemonOwners(p, `⚠️ 升级到 ${upgradeVersions.to} 后启动失败,正在回滚到 ${upgradeVersions.from} 重试...`, log);
577
590
  started = await spawnAndWaitReady(p, log, READY_TIMEOUT, trace);
578
591
  if (started) {
@@ -589,6 +602,14 @@ export async function cmdRestartMonitor() {
589
602
  }
590
603
  log('❌ Rolled-back version also failed to start');
591
604
  }
605
+ else {
606
+ const reason = 'Upgraded package failed its ready check and package rollback failed';
607
+ log(`❌ ${reason}`);
608
+ await notifyDaemonOwners(p, `❌ ${reason}`, log);
609
+ markRestartOutcome(pendingFile, 'rollback-failed', reason, log, hasCorrelatedRequest ? requestId : undefined);
610
+ cleanupPendingFile(pendingFile, log, hasCorrelatedRequest ? requestId : undefined);
611
+ process.exit(1);
612
+ }
592
613
  }
593
614
  // 新产物起不来:回退到上一份可用产物再试一次,比直接进 self-heal 快且确定。
594
615
  if (buildOutcome.status === 'built') {
@@ -1005,61 +1026,119 @@ async function revertToPreviousBuild(log) {
1005
1026
  return restored;
1006
1027
  }
1007
1028
  /**
1008
- * Copy the current dist/ aside so a bad upgrade can be undone.
1029
+ * Copy the installed package aside so a bad upgrade can be undone.
1009
1030
  *
1010
- * Unlike the build path — where dist/ is *moved* to dist.prev because it is
1011
- * about to be deleted anyway — an upgrade replaces dist/ in place, so the
1012
- * original must stay usable until npm succeeds. Hence a copy.
1031
+ * The restart monitor runs from a staging copy, allowing npm to replace the
1032
+ * installed package while a complete rollback copy stays available.
1013
1033
  *
1014
1034
  * The backup lives under EVOLCORE_HOME rather than in the package directory:
1015
1035
  * on Linux/macOS the global prefix is frequently root-owned, and a rollback
1016
1036
  * that cannot be written is worthless. Returns null when there is nothing to
1017
1037
  * back up or the copy failed — the caller then knows rollback is unavailable.
1018
1038
  */
1019
- async function backupDistForUpgrade(p, log) {
1020
- // Linked/source checkouts cannot be upgraded by npm. Copying dist/ here was
1021
- // pure restart overhead and made every source restart rewrite the artifact
1022
- // tree even when no build was needed.
1023
- if (fs.existsSync(path.join(targetPackageRoot(), 'src')))
1039
+ export async function backupPackageForUpgrade(p, log) {
1040
+ const packageRoot = targetPackageRoot();
1041
+ if (fs.existsSync(path.join(packageRoot, 'src')))
1024
1042
  return null;
1025
- const distDir = path.join(targetPackageRoot(), 'dist');
1043
+ const distDir = path.join(packageRoot, 'dist');
1026
1044
  if (!distArtifactIsUsable(distDir))
1027
1045
  return null;
1028
- const backupDir = path.join(p.root, 'data', 'package-backup', 'dist.prev');
1046
+ const backupDir = path.join(p.root, 'data', 'package-backup', 'package.prev');
1047
+ const suffix = `${process.pid}-${Date.now()}`;
1048
+ const stagedBackup = `${backupDir}.tmp-${suffix}`;
1049
+ const previousBackup = `${backupDir}.old-${suffix}`;
1050
+ let previousMoved = false;
1029
1051
  try {
1030
1052
  fs.mkdirSync(path.dirname(backupDir), { recursive: true });
1031
- fs.rmSync(backupDir, { recursive: true, force: true });
1032
- fs.cpSync(distDir, backupDir, { recursive: true });
1033
- log(`Backed up dist/ -> ${backupDir}`);
1053
+ fs.cpSync(packageRoot, stagedBackup, { recursive: true, dereference: true });
1054
+ if (!fs.existsSync(path.join(stagedBackup, 'package.json'))
1055
+ || !distArtifactIsUsable(path.join(stagedBackup, 'dist'))) {
1056
+ throw new Error('package backup is incomplete');
1057
+ }
1058
+ if (fs.existsSync(backupDir)) {
1059
+ fs.renameSync(backupDir, previousBackup);
1060
+ previousMoved = true;
1061
+ }
1062
+ fs.renameSync(stagedBackup, backupDir);
1063
+ if (previousMoved) {
1064
+ try {
1065
+ fs.rmSync(previousBackup, { recursive: true, force: true });
1066
+ }
1067
+ catch (error) {
1068
+ log(`WARN: could not remove previous package backup: ${error.message}`);
1069
+ }
1070
+ }
1071
+ log(`Backed up complete package -> ${backupDir}`);
1034
1072
  return backupDir;
1035
1073
  }
1036
1074
  catch (error) {
1037
- log(`WARN: could not back up dist/ before upgrade: ${error.message}`);
1075
+ try {
1076
+ fs.rmSync(stagedBackup, { recursive: true, force: true });
1077
+ }
1078
+ catch { }
1079
+ if (previousMoved && !fs.existsSync(backupDir) && fs.existsSync(previousBackup)) {
1080
+ try {
1081
+ fs.renameSync(previousBackup, backupDir);
1082
+ }
1083
+ catch { }
1084
+ }
1085
+ log(`WARN: could not back up package before upgrade: ${error.message}`);
1038
1086
  return null;
1039
1087
  }
1040
1088
  }
1041
- /** Restore a backup produced by backupDistForUpgrade. */
1042
- async function restoreDistBackup(backupDir, log) {
1089
+ /** Restore a complete package backup without leaving a partial installation at the target path. */
1090
+ export async function restorePackageBackup(backupDir, log) {
1043
1091
  if (!backupDir || !fs.existsSync(backupDir)) {
1044
- log('❌ No usable dist backup to restore from');
1092
+ log('❌ No usable package backup to restore from');
1093
+ return false;
1094
+ }
1095
+ if (!fs.existsSync(path.join(backupDir, 'package.json'))
1096
+ || !distArtifactIsUsable(path.join(backupDir, 'dist'))) {
1097
+ log('❌ Package backup is incomplete');
1045
1098
  return false;
1046
1099
  }
1047
- const distDir = path.join(targetPackageRoot(), 'dist');
1100
+ const packageRoot = targetPackageRoot();
1048
1101
  for (let attempt = 1; attempt <= 3; attempt++) {
1102
+ const suffix = `${process.pid}-${Date.now()}-${attempt}`;
1103
+ const stagedRestore = `${packageRoot}.restore-${suffix}`;
1104
+ const failedPackage = `${packageRoot}.failed-${suffix}`;
1049
1105
  try {
1050
- fs.rmSync(distDir, { recursive: true, force: true });
1051
- fs.cpSync(backupDir, distDir, { recursive: true });
1052
- log('↩ Restored dist/ from backup');
1106
+ fs.cpSync(backupDir, stagedRestore, { recursive: true, dereference: true });
1107
+ if (!distArtifactIsUsable(path.join(stagedRestore, 'dist'))) {
1108
+ throw new Error('restored package is incomplete');
1109
+ }
1110
+ if (fs.existsSync(packageRoot))
1111
+ fs.renameSync(packageRoot, failedPackage);
1112
+ try {
1113
+ fs.renameSync(stagedRestore, packageRoot);
1114
+ }
1115
+ catch (error) {
1116
+ if (!fs.existsSync(packageRoot) && fs.existsSync(failedPackage)) {
1117
+ fs.renameSync(failedPackage, packageRoot);
1118
+ }
1119
+ throw error;
1120
+ }
1121
+ try {
1122
+ fs.rmSync(failedPackage, { recursive: true, force: true });
1123
+ }
1124
+ catch (error) {
1125
+ log(`WARN: could not remove failed package: ${error.message}`);
1126
+ }
1127
+ log('↩ Restored complete package from backup');
1053
1128
  return true;
1054
1129
  }
1055
1130
  catch (error) {
1131
+ try {
1132
+ fs.rmSync(stagedRestore, { recursive: true, force: true });
1133
+ }
1134
+ catch { }
1056
1135
  const code = error.code;
1057
1136
  if (attempt < 3 && (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES')) {
1058
1137
  log(`restore failed (${code}), retry ${attempt}/2`);
1059
1138
  await sleep(attempt * 700);
1060
1139
  continue;
1061
1140
  }
1062
- log(`❌ Could not restore dist/: ${error.message}`);
1141
+ log(`❌ Could not restore package: ${error.message}`);
1063
1142
  return false;
1064
1143
  }
1065
1144
  }
@@ -1071,7 +1150,7 @@ function dropUpgradeBackup(backupDir, log) {
1071
1150
  return;
1072
1151
  try {
1073
1152
  fs.rmSync(backupDir, { recursive: true, force: true });
1074
- log('Removed upgrade backup (new version verified)');
1153
+ log('Removed package upgrade backup (new version verified)');
1075
1154
  }
1076
1155
  catch {
1077
1156
  log('WARN: could not remove upgrade backup');
@@ -5,7 +5,9 @@
5
5
  * 请求登记与应答落盘都在 daemon 的 AunRequestRegistry 里,CLI 被杀也不丢结果。
6
6
  */
7
7
  import fs from 'node:fs';
8
+ import path from 'node:path';
8
9
  import { ipcQuery } from '../ipc.js';
10
+ import { readDelegationCredential, hashCurrentDelegatedCommand } from '../core/auth/agent-delegation.js';
9
11
  import { resolvePaths } from '../paths.js';
10
12
  const HELP = `ec services — 服务路由运维
11
13
 
@@ -18,6 +20,14 @@ const HELP = `ec services — 服务路由运维
18
20
  ec services reload [<包名>] [--aid <aid>] 重载
19
21
  ec services enable / disable [--aid <aid>] 总闸
20
22
 
23
+ 安装与卸载(L 类目录只能由 daemon 代写):
24
+ ec services pack add <包名> --from <源目录> [--aid <aid>]
25
+ ec services pack remove <包名> [--aid <aid>] [--purge]
26
+
27
+ add 遇到已安装的包直接报错,先 remove 再装。
28
+ remove 默认把日志与台账归档到 <包>/logs/archive-<时间戳>/;--purge 连归档一起删。
29
+ ec services pack list [--aid <aid>]
30
+
21
31
  对端:
22
32
  ec services describe <aid> [--service <type>] 查对端可用服务
23
33
  ec services schema <aid> <type> 查某个服务的请求 schema
@@ -36,9 +46,16 @@ function readControlToken() {
36
46
  }
37
47
  }
38
48
  async function queryServices(argv, timeoutMs = 20_000) {
39
- const controlToken = readControlToken();
49
+ // 托管会话优先带 delegation 身份:daemon 要靠它判定 owner/admin/member,
50
+ // 只带 control token 会被当成"主机终端",任何角色都能管理。
51
+ const sessionId = process.env.EVOLCORE_SESSION_ID;
52
+ const delegationToken = sessionId ? readDelegationCredential() : undefined;
53
+ const controlToken = delegationToken ? undefined : readControlToken();
40
54
  try {
41
- const response = await ipcQuery(resolvePaths().socket, { type: 'services.op', argv, controlToken }, timeoutMs, { throwOnError: false });
55
+ const response = await ipcQuery(resolvePaths().socket, {
56
+ type: 'services.op', argv, controlToken,
57
+ ...(sessionId && delegationToken ? { sessionId, delegationToken, delegationCommandHash: hashCurrentDelegatedCommand() } : {}),
58
+ }, timeoutMs, { throwOnError: false });
42
59
  if (!response || typeof response !== 'object')
43
60
  return { transportError: 'invalid daemon response' };
44
61
  return { response };
@@ -54,8 +71,17 @@ function printResult(result, json) {
54
71
  }
55
72
  console.log(String(result));
56
73
  }
74
+ /** `--from` 在 CLI 侧 resolve:daemon 的 cwd 与调用方工作区不同。 */
75
+ function resolveFromPath(args) {
76
+ const index = args.indexOf('--from');
77
+ if (index < 0 || index + 1 >= args.length)
78
+ return args;
79
+ const next = [...args];
80
+ next[index + 1] = path.resolve(next[index + 1]);
81
+ return next;
82
+ }
57
83
  export async function runServicesCommand(argv) {
58
- const args = [...argv];
84
+ const args = resolveFromPath([...argv]);
59
85
  const json = args.includes('--format') && args[args.indexOf('--format') + 1] === 'json';
60
86
  if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
61
87
  console.log(HELP);
@@ -118,6 +118,68 @@ function printResult(data, jsonFormat, opts) {
118
118
  printItem(data, opts);
119
119
  }
120
120
  }
121
+ /**
122
+ * 空结果的成因诊断。分界线是「语法错误」(调用方已在前置校验里 exit 1)
123
+ * 与「语法合法但查不到」——后者一律 exit 0,但要说明是哪一种查不到。
124
+ */
125
+ function printEmptyThreadList(result, echoSelf) {
126
+ const peer = result.peer ?? '<peer>';
127
+ const self = echoSelf ? ` --self ${echoSelf}` : '';
128
+ if (result.indexState === 'corrupt') {
129
+ console.error('✗ 话题索引文件损坏,无法读取(数据文件仍在,重建索引不丢消息)');
130
+ console.error(' 先检查: ec thread rebuild-index --check');
131
+ console.error(' 修复: ec thread rebuild-index');
132
+ process.exitCode = 1;
133
+ return;
134
+ }
135
+ console.log(`0 条 · ${peer}`);
136
+ if (result.peerKnown === false) {
137
+ console.log(' 原因: 与该对端没有任何往来记录(索引和聊天日志中都没有)');
138
+ console.log(' 下一步: ec thread peers # 查看确实有话题记录的对端');
139
+ return;
140
+ }
141
+ if ((result.peerTopicCount ?? 0) > 0) {
142
+ const filters = [];
143
+ if (result.status)
144
+ filters.push(`--status ${result.status}`);
145
+ if (result.label)
146
+ filters.push(`--label "${result.label}"`);
147
+ if (result.unlabeled)
148
+ filters.push('--unlabeled');
149
+ console.log(` 原因: 该对端共 ${result.peerTopicCount} 个话题,均不匹配${filters.length ? ' ' + filters.join(' ') : '当前过滤条件'}`);
150
+ console.log(` 下一步: ec thread list ${peer}${self} # 去掉过滤条件`);
151
+ return;
152
+ }
153
+ if (result.hasMainChat) {
154
+ console.log(' 原因: 该对端只有主话题往来,没有独立话题;主话题不参与状态/标签过滤');
155
+ console.log(` 下一步: ec thread history ${peer}${self}`);
156
+ return;
157
+ }
158
+ if (result.indexState === 'missing') {
159
+ console.log(' 原因: 话题索引尚未建立');
160
+ console.log(' 下一步: ec thread rebuild-index');
161
+ return;
162
+ }
163
+ console.log(' 原因: 索引中没有该对端的话题,且没有主话题往来');
164
+ console.log(' 下一步: ec thread peers');
165
+ }
166
+ /**
167
+ * 对端标识的语法校验(存在性由 daemon 侧判断,这里只挡形态错误)。
168
+ * 合法:`alice.agentid.cn`、`aun#alice.agentid.cn`、非 AUN 渠道的 `ou_xxx`。
169
+ * 非法:空、含空白、`#` 之后为空。
170
+ */
171
+ function invalidPeerArg(raw) {
172
+ const trimmed = raw.trim();
173
+ if (!trimmed || /\s/.test(trimmed))
174
+ return true;
175
+ const tail = trimmed.includes('#') ? trimmed.slice(trimmed.lastIndexOf('#') + 1) : trimmed;
176
+ let decoded = tail;
177
+ try {
178
+ decoded = decodeURIComponent(tail);
179
+ }
180
+ catch { /* 解码失败不改变语法判断 */ }
181
+ return !decoded.trim();
182
+ }
121
183
  function printItem(item, opts) {
122
184
  if (typeof item !== 'object' || !item) {
123
185
  console.log(String(item));
@@ -195,6 +257,11 @@ function printItem(item, opts) {
195
257
  // ListThreadsResult
196
258
  if ('threads' in obj && Array.isArray(obj.threads)) {
197
259
  const result = obj;
260
+ // 空结果不裸打 0 条:区分「语法没错但查不到」的四种成因(见 B1 空探针)。
261
+ if (result.total === 0) {
262
+ printEmptyThreadList(result, opts?.echoSelf);
263
+ return;
264
+ }
198
265
  for (const t of result.threads)
199
266
  printItem(t);
200
267
  const shown = result.threads.length;
@@ -279,6 +346,13 @@ export async function runThreadCommand(args) {
279
346
  process.exitCode = 1;
280
347
  return;
281
348
  }
349
+ // 形态错属于「参数错误」,必须报错退出;查不到结果走空态诊断,两者不混。
350
+ if (invalidPeerArg(peer)) {
351
+ console.error(`✗ 对端标识无效: '${peer}'`);
352
+ console.error(' 应为裸 AID(如 alice.agentid.cn)或 <channel>#<peerId>');
353
+ process.exitCode = 1;
354
+ return;
355
+ }
282
356
  const statusVal = argValue(args, '--status');
283
357
  // B9: 枚举校验
284
358
  if (statusVal && !TOPIC_STATUSES.includes(statusVal)) {
@@ -374,6 +448,12 @@ export async function runThreadCommand(args) {
374
448
  process.exitCode = 1;
375
449
  return;
376
450
  }
451
+ if (invalidPeerArg(peer)) {
452
+ console.error(`✗ 对端标识无效: '${peer}'`);
453
+ console.error(' 应为裸 AID(如 alice.agentid.cn)或 <channel>#<peerId>');
454
+ process.exitCode = 1;
455
+ return;
456
+ }
377
457
  const name = argValue(args, '--name');
378
458
  if (!name) {
379
459
  console.error('✗ 必须指定 --name');
@@ -501,15 +581,19 @@ export async function runThreadCommand(args) {
501
581
  }
502
582
  const r = resp.result;
503
583
  if (dryRun) {
504
- if (r.missing === 0 && r.stale === 0) {
505
- console.log(`✓ 索引健康:共 ${r.rebuilt} 条话题,session 文件完整`);
584
+ // 两个计数都可能缺省(接口只回传有问题的维度),缺省按 0 处理,
585
+ // 否则健康状态也会落进「建议 rebuild」分支。
586
+ const missing = r.missing ?? 0;
587
+ const stale = r.stale ?? 0;
588
+ if (missing === 0 && stale === 0) {
589
+ console.log(`✓ 索引健康:共 ${r.rebuilt ?? r.total} 条话题,session 文件完整`);
506
590
  }
507
591
  else {
508
- if (r.missing > 0) {
509
- console.warn(`⚠ [严重] ${r.missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
592
+ if (missing > 0) {
593
+ console.warn(`⚠ [严重] ${missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
510
594
  }
511
- if (r.stale > 0) {
512
- console.warn(`⚠ [轻微] ${r.stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
595
+ if (stale > 0) {
596
+ console.warn(`⚠ [轻微] ${stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
513
597
  }
514
598
  console.warn(` 建议执行 ec thread rebuild-index 修复`);
515
599
  if (jsonFormat)
@@ -532,15 +616,17 @@ export async function runThreadCommand(args) {
532
616
  return;
533
617
  }
534
618
  const r = resp.result;
535
- if (r.missing === 0 && r.stale === 0) {
619
+ const missing = r.missing ?? 0;
620
+ const stale = r.stale ?? 0;
621
+ if (missing === 0 && stale === 0) {
536
622
  console.log(`✓ 索引健康:共 ${r.total} 条话题,session 文件完整`);
537
623
  }
538
624
  else {
539
- if (r.missing > 0) {
540
- console.warn(`⚠ [严重] ${r.missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
625
+ if (missing > 0) {
626
+ console.warn(`⚠ [严重] ${missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
541
627
  }
542
- if (r.stale > 0) {
543
- console.warn(`⚠ [轻微] ${r.stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
628
+ if (stale > 0) {
629
+ console.warn(`⚠ [轻微] ${stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
544
630
  }
545
631
  console.warn(` 建议执行 ec thread rebuild-index 修复`);
546
632
  if (jsonFormat)
@@ -15,7 +15,7 @@ import { logger } from '../utils/logger.js';
15
15
  import { autoMigrateIfNeeded } from '../config-store.js';
16
16
  import { ConfigTarget, initConfigManager, notifyConfigWrite } from './config-manager.js';
17
17
  import { ensureRoleConfigV4OnStartup, ensureRoleConfigV5OnStartup } from './role-migration-startup.js';
18
- import { ensureAccessPolicyMigrationOnStartup, ensureAgentModelProviderMigrationOnStartup, ensureAgentOnlyModelMigrationOnStartup, ensureAuxiliaryModelMigrationOnStartup, ensurePeerFileRenameOnStartup, ensurePublishedSchemaConsolidationMigrationOnStartup, ensureProviderServiceTypeMigrationOnStartup, ensureProviderIdentityMigrationOnStartup, ensureRelationConfigVersionMigrationOnStartup, invalidateMigrationReadCache, withMigrationReadCache, } from './schema-migration.js';
18
+ import { ensureAccessPolicyMigrationOnStartup, ensureAgentModelProviderMigrationOnStartup, ensureAgentOnlyModelMigrationOnStartup, ensureAuxiliaryModelMigrationOnStartup, ensurePeerFileRenameOnStartup, ensureStartupConfigCompatibilityMigrationOnStartup, ensureProviderServiceTypeMigrationOnStartup, ensureProviderIdentityMigrationOnStartup, ensureRelationConfigVersionMigrationOnStartup, invalidateMigrationReadCache, withMigrationReadCache, } from './schema-migration.js';
19
19
  import { ensureContactBookV2OnStartup } from './peer-book-v2-startup.js';
20
20
  import { synchronizeAllManagementPeersSync } from './peer-book-store.js';
21
21
  import { readInstalledEvolcoreVersion, readFastaunVersion } from '../utils/evolcore-version.js';
@@ -38,9 +38,9 @@ export async function prepareStartupConfig(recoverRoleMutations, onStep) {
38
38
  step('auxiliaryModel');
39
39
  // 任一迁移真的落盘后立刻丢弃缓存:这三个迁移改的是同一批 relation 配置,
40
40
  // 后一个迁移若沿用写盘前的旧文本做整文件覆盖,会把前一个的改动回滚掉。
41
- const { publishedSchemaConsolidationMigration, auxiliaryModelMigration, agentOnlyModelMigration, relationVersionMigration } = await withMigrationReadCache(async () => {
42
- const publishedSchemaConsolidation = await ensurePublishedSchemaConsolidationMigrationOnStartup();
43
- if (publishedSchemaConsolidation)
41
+ const { startupConfigCompatibilityMigration, auxiliaryModelMigration, agentOnlyModelMigration, relationVersionMigration } = await withMigrationReadCache(async () => {
42
+ const startupConfigCompatibility = await ensureStartupConfigCompatibilityMigrationOnStartup();
43
+ if (startupConfigCompatibility)
44
44
  invalidateMigrationReadCache();
45
45
  const auxiliary = await ensureAuxiliaryModelMigrationOnStartup();
46
46
  if (auxiliary)
@@ -52,15 +52,15 @@ export async function prepareStartupConfig(recoverRoleMutations, onStep) {
52
52
  if (relationVersion)
53
53
  invalidateMigrationReadCache();
54
54
  return {
55
- publishedSchemaConsolidationMigration: publishedSchemaConsolidation,
55
+ startupConfigCompatibilityMigration: startupConfigCompatibility,
56
56
  auxiliaryModelMigration: auxiliary,
57
57
  agentOnlyModelMigration: agentOnly,
58
58
  relationVersionMigration: relationVersion,
59
59
  };
60
60
  });
61
- if (publishedSchemaConsolidationMigration) {
62
- const message = `✓ Published schema consolidation applied automatically: ${publishedSchemaConsolidationMigration.changedFiles} file(s) restamped`
63
- + (publishedSchemaConsolidationMigration.backup ? `; backup: ${publishedSchemaConsolidationMigration.backup}` : '');
61
+ if (startupConfigCompatibilityMigration) {
62
+ const message = `✓ Startup config compatibility migration applied automatically: ${startupConfigCompatibilityMigration.changedFiles} file(s)`
63
+ + (startupConfigCompatibilityMigration.backup ? `; backup: ${startupConfigCompatibilityMigration.backup}` : '');
64
64
  logger.info(message);
65
65
  console.error(message);
66
66
  }
@@ -1601,26 +1601,44 @@ export async function ensureRelationConfigVersionMigrationOnStartup() {
1601
1601
  throw new ConfigError('RELATION_CONFIG_VERSION_MIGRATION_FAILED', `Automatic relation-config version migration failed: ${detail}`, { cause: error });
1602
1602
  }
1603
1603
  }
1604
- // ── Published schema consolidation: retired v20/v13 → v19/v12 ───────────────
1604
+ // ── Startup config compatibility: retired schemas and chat modes ────────────
1605
1605
  /**
1606
1606
  * The unpublished v20/v13 schemas only split the group-chatmode consolidation
1607
1607
  * from v19/v12. Once those files were removed, persisted configs created in
1608
1608
  * the short release window must be restamped before the contact-book startup
1609
- * gate decides they are an unknown future format.
1609
+ * gate decides they are an unknown future format. This pass also maps retired
1610
+ * `paactive` values in known schemas before startup validators inspect them.
1610
1611
  */
1611
1612
  const PUBLISHED_SCHEMA_CONSOLIDATIONS = [
1612
1613
  { logicalName: 'agent-config', from: 20, to: 19 },
1613
1614
  { logicalName: 'relation-config', from: 13, to: 12 },
1614
1615
  ];
1615
1616
  function restampPublishedSchemaConsolidation(value, file, consolidation) {
1616
- if (value.$schema_version !== consolidation.from)
1617
- return null;
1617
+ let next = value;
1618
+ let chatModeChanged = false;
1619
+ const schemaVersion = value.$schema_version;
1620
+ const currentSchemaVersion = currentVersion(consolidation.logicalName);
1621
+ const knownSchema = Number.isInteger(schemaVersion) && Number(schemaVersion) >= 1
1622
+ && (Number(schemaVersion) <= currentSchemaVersion || schemaVersion === consolidation.from);
1623
+ if (knownSchema && isRecord(value.chatmode)) {
1624
+ const chatmode = { ...value.chatmode };
1625
+ for (const scene of ['private', 'group', 'nothuman']) {
1626
+ if (chatmode[scene] !== 'paactive')
1627
+ continue;
1628
+ chatmode[scene] = 'proactive';
1629
+ chatModeChanged = true;
1630
+ }
1631
+ if (chatModeChanged)
1632
+ next = { ...value, chatmode };
1633
+ }
1634
+ if (schemaVersion !== consolidation.from)
1635
+ return chatModeChanged ? next : null;
1618
1636
  // A consolidation only applies while the source version is unpublished.
1619
1637
  // Once that version is current, its fields (for example agent-config.team)
1620
1638
  // must be retained instead of being validated against the older schema.
1621
- if (currentVersion(consolidation.logicalName) >= consolidation.from)
1622
- return null;
1623
- const next = { ...value, $schema_version: consolidation.to };
1639
+ if (currentSchemaVersion >= consolidation.from)
1640
+ return chatModeChanged ? next : null;
1641
+ next = { ...next, $schema_version: consolidation.to };
1624
1642
  const schema = loadSchema(consolidation.logicalName, consolidation.to);
1625
1643
  if (!schema.validate(next)) {
1626
1644
  const detail = (schema.validate.errors ?? [])
@@ -1631,12 +1649,13 @@ function restampPublishedSchemaConsolidation(value, file, consolidation) {
1631
1649
  }
1632
1650
  return next;
1633
1651
  }
1634
- function planPublishedSchemaConsolidationMigration(home) {
1652
+ function planStartupConfigCompatibilityMigration(home) {
1635
1653
  const changes = [];
1636
1654
  const summary = {
1637
1655
  agentsScanned: 0,
1638
1656
  relationsScanned: 0,
1639
- filesRestamped: 0,
1657
+ filesChanged: 0,
1658
+ filesWithChatModesNormalized: 0,
1640
1659
  };
1641
1660
  const agentsRoot = path.join(home, 'agents');
1642
1661
  if (!fs.existsSync(agentsRoot))
@@ -1661,7 +1680,10 @@ function planPublishedSchemaConsolidationMigration(home) {
1661
1680
  const next = restampPublishedSchemaConsolidation(parsed.value, agentFile, agentConsolidation);
1662
1681
  if (next) {
1663
1682
  changes.push({ file: agentFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1664
- summary.filesRestamped += 1;
1683
+ summary.filesChanged += 1;
1684
+ if (JSON.stringify(parsed.value.chatmode) !== JSON.stringify(next.chatmode)) {
1685
+ summary.filesWithChatModesNormalized += 1;
1686
+ }
1665
1687
  }
1666
1688
  }
1667
1689
  }
@@ -1680,19 +1702,22 @@ function planPublishedSchemaConsolidationMigration(home) {
1680
1702
  if (!next)
1681
1703
  continue;
1682
1704
  changes.push({ file: relationFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1683
- summary.filesRestamped += 1;
1705
+ summary.filesChanged += 1;
1706
+ if (JSON.stringify(parsed.value.chatmode) !== JSON.stringify(next.chatmode)) {
1707
+ summary.filesWithChatModesNormalized += 1;
1708
+ }
1684
1709
  }
1685
1710
  }
1686
1711
  return { home, changes, summary };
1687
1712
  }
1688
- export function runPublishedSchemaConsolidationMigration(options = {}) {
1713
+ export function runStartupConfigCompatibilityMigration(options = {}) {
1689
1714
  const id = 'published-schema-consolidation-v1';
1690
1715
  const home = path.resolve(options.home || resolvePaths().root);
1691
1716
  const release = acquireLock(home, id);
1692
1717
  try {
1693
1718
  assertDaemonStopped(home);
1694
1719
  recoverJournal(home, id);
1695
- const plan = planPublishedSchemaConsolidationMigration(home);
1720
+ const plan = planStartupConfigCompatibilityMigration(home);
1696
1721
  const backup = options.apply ? applyMigration(plan, id) : null;
1697
1722
  return {
1698
1723
  ok: true,
@@ -1707,10 +1732,10 @@ export function runPublishedSchemaConsolidationMigration(options = {}) {
1707
1732
  release();
1708
1733
  }
1709
1734
  }
1710
- export async function ensurePublishedSchemaConsolidationMigrationOnStartup() {
1735
+ export async function ensureStartupConfigCompatibilityMigrationOnStartup() {
1711
1736
  const home = resolvePaths().root;
1712
1737
  try {
1713
- const result = runPublishedSchemaConsolidationMigration({ home, apply: true });
1738
+ const result = runStartupConfigCompatibilityMigration({ home, apply: true });
1714
1739
  if (result.changedFiles === 0)
1715
1740
  return null;
1716
1741
  return {
@@ -1722,7 +1747,7 @@ export async function ensurePublishedSchemaConsolidationMigrationOnStartup() {
1722
1747
  }
1723
1748
  catch (error) {
1724
1749
  const detail = error instanceof Error ? error.message : String(error);
1725
- throw new ConfigError('PUBLISHED_SCHEMA_CONSOLIDATION_MIGRATION_FAILED', `Automatic published schema consolidation failed: ${detail}`, { cause: error });
1750
+ throw new ConfigError('STARTUP_CONFIG_COMPATIBILITY_MIGRATION_FAILED', `Automatic startup config compatibility migration failed: ${detail}`, { cause: error });
1726
1751
  }
1727
1752
  }
1728
1753
  // ── Agent 消息准入重写:v16 → v17 → v18 ──────────────────────────────────────