evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -729,7 +729,7 @@ function queryPathOperands(analysis) {
729
729
  accessKind: command.accessKind ?? (operand.access === 'recursive' ? 'enumerate' : 'content'),
730
730
  }))));
731
731
  }
732
- const PROTECTED_BASENAME_LITERAL_RE = /^(?:daemon\.json|defaults\.json|config\.json|contact\.json|contact-operations\.jsonl|\.device_id|\.env|\.lock|daemon\.pid)$/i;
732
+ const PROTECTED_BASENAME_LITERAL_RE = /^(?:daemon\.json|defaults\.json|config\.json|contact\.json|contact-operations\.jsonl|\.device_id(?:\..+)?|\.env|\.lock|daemon\.pid)$/i;
733
733
  const SHELL_PATH_LITERAL_META_RE = /[\0\r\n$`*?\[\]{}<>|;&(),]/;
734
734
  /**
735
735
  * Extract literal operands immediately following an unquoted shell
@@ -2649,19 +2649,34 @@ export function evaluateToolPreflight(toolName, input, context) {
2649
2649
  policyCode: 'managed_ec_discovery_forbidden',
2650
2650
  };
2651
2651
  }
2652
- const parserOptions = {
2653
- verifyShellExecutable: process.platform === 'win32',
2652
+ const shellDialect = stringShellCarrier?.dialect
2653
+ ?? (hasCodexCmdCarrierEcIntent(input) ? 'cmd' : undefined);
2654
+ const hasPowerShellCarrierAssignment = stringShellCarrier?.dialect === 'powershell'
2655
+ && hasPowerShellCredentialAssignment(stringShellCarrier.command);
2656
+ const syntaxOptions = {
2654
2657
  managedTempDir: context.managedTempDir,
2658
+ posixShell: stringShellCarrier?.posixShell,
2659
+ ...(shellDialect ? { dialect: shellDialect } : {}),
2655
2660
  ...(context.sessionCredential
2656
2661
  ? { expectedCredentialToken: context.sessionCredential }
2657
2662
  : {}),
2658
2663
  };
2664
+ // Identify EC intent without granting privileges or probing the shell.
2665
+ // Non-EC commands continue through the ordinary path/approval policy.
2666
+ const ecIntent = hasPowerShellCarrierAssignment
2667
+ || classifyEvolcoreShellCommand(policyCommand, syntaxOptions).kind !== 'none';
2668
+ const parserOptions = {
2669
+ ...syntaxOptions,
2670
+ verifyShellExecutable: process.platform === 'win32' && ecIntent,
2671
+ };
2659
2672
  const parsedCodex = context.sessionId ? parseCodexToolCommand(input, parserOptions) : null;
2660
2673
  if (context.sessionId && parsedCodex && !parsedCodex.ok && parsedCodex.issue === 'untrusted-shell') {
2674
+ logger.warn('[ToolPolicy] EC shell trust validation failed', parsedCodex.shellTrustFailure);
2661
2675
  return {
2662
2676
  behavior: 'deny',
2663
2677
  input,
2664
- message: '🔒 Shell 可执行文件未通过 Windows Authenticode 签名校验,禁止进入 EvolCore EC 特权路径。',
2678
+ message: '🔒 Shell 信任校验失败,禁止进入 EvolCore EC 特权路径。'
2679
+ + (parsedCodex.shellTrustFailure ? ` ${parsedCodex.shellTrustFailure.message}` : ''),
2665
2680
  policyCode: 'ec_shell_untrusted_executable',
2666
2681
  };
2667
2682
  }
@@ -2674,10 +2689,6 @@ export function evaluateToolPreflight(toolName, input, context) {
2674
2689
  policyCode: 'delegation_token_unbound',
2675
2690
  };
2676
2691
  }
2677
- const shellDialect = stringShellCarrier?.dialect
2678
- ?? (hasCodexCmdCarrierEcIntent(input) ? 'cmd' : undefined);
2679
- const hasPowerShellCarrierAssignment = stringShellCarrier?.dialect === 'powershell'
2680
- && hasPowerShellCredentialAssignment(stringShellCarrier.command);
2681
2692
  const ecCommand = hasPowerShellCarrierAssignment && parsedCodex
2682
2693
  ? parsedCodex.ok && parsedCodex.argv[0] === 'ec'
2683
2694
  ? { kind: 'literal' }
@@ -2714,10 +2725,12 @@ export function evaluateToolPreflight(toolName, input, context) {
2714
2725
  }
2715
2726
  if (ecCommand.kind === 'composite') {
2716
2727
  if (ecCommand.issue === 'untrusted-shell') {
2728
+ logger.warn('[ToolPolicy] EC shell trust validation failed', ecCommand.shellTrustFailure);
2717
2729
  return {
2718
2730
  behavior: 'deny',
2719
2731
  input,
2720
- message: '🔒 Shell 可执行文件未通过 Windows Authenticode 签名校验,禁止进入 EvolCore EC 特权路径。',
2732
+ message: '🔒 Shell 信任校验失败,禁止进入 EvolCore EC 特权路径。'
2733
+ + (ecCommand.shellTrustFailure ? ` ${ecCommand.shellTrustFailure.message}` : ''),
2721
2734
  policyCode: 'ec_shell_untrusted_executable',
2722
2735
  };
2723
2736
  }
@@ -2748,7 +2761,10 @@ export function evaluateToolPreflight(toolName, input, context) {
2748
2761
  };
2749
2762
  }
2750
2763
  if (ecCommand.issue === 'unsupported-escape') {
2751
- return { behavior: 'deny', input, message: '🔒 EC 内联文本不支持 PowerShell `n;请使用字面量 \\n。', policyCode: 'ec_shell_unsupported_escape' };
2764
+ const message = shellDialect === 'powershell'
2765
+ ? '🔒 EC 内联文本不支持 PowerShell `n;请使用字面量 \\n。'
2766
+ : `🔒 ${literalShellParseRemedy({ issue: ecCommand.issue, dialect: 'posix' })}`;
2767
+ return { behavior: 'deny', input, message, policyCode: 'ec_shell_unsupported_escape' };
2752
2768
  }
2753
2769
  if (ecCommand.issue === 'lossy-cmd-shim') {
2754
2770
  return { behavior: 'deny', input, message: '🔒 PowerShell 调用 ec.cmd 会截断物理多行参数;请保持原有 ec ... 调用,由 PowerShell 原生 shim 无损传递。', policyCode: 'ec_shell_lossy_cmd_shim' };
@@ -90,6 +90,19 @@ export function parsePeerKey(key) {
90
90
  channelId: decodeURIComponent(key.slice(idx + 1)),
91
91
  };
92
92
  }
93
+ /** Normalize a bare AID or encoded relation key; strict callers also validate external selectors. */
94
+ export function normalizePeerKey(input, options = {}) {
95
+ const raw = (input || '').trim();
96
+ if (!raw)
97
+ throw new Error('Peer must not be empty');
98
+ const { channelType, channelId } = raw.includes('#')
99
+ ? parsePeerKey(raw) : { channelType: 'aun', channelId: raw };
100
+ if (!channelType || !channelId || (options.strict && (!/^[a-z][a-z0-9_-]*$/.test(channelType) || !channelId.trim()
101
+ || /[\x00-\x1f\x7f]/.test(channelId)
102
+ || (channelType === 'aun' && !isValidAid(channelId)))))
103
+ throw new Error('Invalid peer selector');
104
+ return formatPeerKey(channelType, channelId);
105
+ }
93
106
  /** Read type evidence without network access or any AID-shape fallback. */
94
107
  export function readAunPeerKind(selfAid, peerAid, options = {}) {
95
108
  if (!isValidAid(selfAid) || !isValidAid(peerAid)) {
@@ -11,6 +11,11 @@ import path from 'path';
11
11
  import fs from 'fs';
12
12
  import os from 'os';
13
13
  import { visitSessionHistory } from '../session-fs-store.js';
14
+ /** One SDK query seam for managed-session adapters and the local terminal gateway. */
15
+ export async function listClaudeSdkSessions(options) {
16
+ const { listSessions } = await import('@anthropic-ai/claude-agent-sdk');
17
+ return listSessions(options);
18
+ }
14
19
  export class ClaudeSessionFileAdapter {
15
20
  baseagent = 'claude';
16
21
  getSessionFilePath(projectPath, agentSessionId) {
@@ -206,8 +211,7 @@ export class ClaudeSessionFileAdapter {
206
211
  }
207
212
  async listSdkSessions(projectPath) {
208
213
  try {
209
- const { listSessions: sdkListSessions } = await import('@anthropic-ai/claude-agent-sdk');
210
- const sessions = await sdkListSessions({ dir: projectPath });
214
+ const sessions = await listClaudeSdkSessions({ dir: projectPath });
211
215
  return sessions.map(s => ({
212
216
  sessionId: s.sessionId,
213
217
  title: s.customTitle || undefined,
@@ -481,6 +481,10 @@ export class CodexSessionFileAdapter {
481
481
  this.dbInitialized = false;
482
482
  this.rolloutPathCache.clear();
483
483
  }
484
+ /** Locate an already bound rollout without requiring a CLI SQLite index row. */
485
+ findSessionFile(agentSessionId) {
486
+ return this.findRolloutFile(agentSessionId);
487
+ }
484
488
  /**
485
489
  * 从 rollout JSONL 读取第一条或最后一条 user_message
486
490
  */
@@ -10,6 +10,8 @@ import { sessionToFile, fileToSession, formatSessionKey, DEFAULT_THREAD_ID, norm
10
10
  import { tryParseChannelKey } from '../channel-loader.js';
11
11
  import { isMainSession, isMainSessionThreadId, isTopicSession, isTopicThreadId, mainTopicPeer, safeFormatMainTopicId, sessionLocalTopicId, sessionTopicThreadId, } from '../thread/topic-id.js';
12
12
  import { isSystemControlChannel } from '../system-channels.js';
13
+ import { sameThreadPeer } from '../thread/topic-id.js';
14
+ import { sanitizeIndexEntry } from '../thread/types.js';
13
15
  import path from 'path';
14
16
  import fs from 'fs';
15
17
  import os from 'os';
@@ -288,8 +290,17 @@ export class SessionManager {
288
290
  this.identityResolver = resolver;
289
291
  }
290
292
  registerFileAdapter(adapter) {
293
+ const previous = this.fileAdapters.get(adapter.baseagent);
291
294
  this.fileAdapters.set(adapter.baseagent, adapter);
292
295
  logger.debug(`[SessionManager] Registered file adapter: ${adapter.baseagent}`);
296
+ return () => {
297
+ if (this.fileAdapters.get(adapter.baseagent) !== adapter)
298
+ return;
299
+ if (previous)
300
+ this.fileAdapters.set(adapter.baseagent, previous);
301
+ else
302
+ this.fileAdapters.delete(adapter.baseagent);
303
+ };
293
304
  }
294
305
  setCapsuleTranscriptReader(reader) {
295
306
  this.capsuleTranscriptReader = reader;
@@ -1833,24 +1844,29 @@ export class SessionManager {
1833
1844
  try {
1834
1845
  const indexPath = agentThreadIndexPath(input.selfAid);
1835
1846
  const raw = readJsonFile(indexPath);
1836
- const index = raw && Array.isArray(raw.threads) ? raw : { version: 1, threads: [] };
1847
+ // 新索引按当前 schema 版本写(2:条目已归一)。读到旧版本时由
1848
+ // ThreadService.readIndex 负责迁移,这里只保证新建时不是旧版本。
1849
+ const index = raw && Array.isArray(raw.threads) ? raw : { version: 2, threads: [] };
1837
1850
  const existing = index.threads.find((t) => t.threadId === input.threadId
1838
- && String(t.peer ?? '').toLowerCase() === input.peer.toLowerCase());
1851
+ && (t.channelType ?? 'aun') === input.channelType && sameThreadPeer(t.peer, input.peer, input.channelType));
1839
1852
  if (existing) {
1840
1853
  existing.sessionId = existing.sessionId || input.sessionId;
1841
1854
  return;
1842
1855
  }
1843
- index.threads.push({
1856
+ const candidate = sanitizeIndexEntry({
1844
1857
  threadId: input.threadId,
1845
1858
  sessionId: input.sessionId,
1846
1859
  peer: input.peer,
1847
1860
  channelType: input.channelType,
1848
1861
  peerKind: input.peerKind,
1849
1862
  name: input.name || '话题会话',
1850
- topicStatus: input.topicStatus,
1863
+ topicStatus: normalizeTopicStatus(input.topicStatus),
1851
1864
  createdAt: input.now,
1852
1865
  lastActiveAt: input.now,
1853
1866
  });
1867
+ if (!candidate.ok)
1868
+ return;
1869
+ index.threads.push(candidate.entry);
1854
1870
  ensureDir(path.dirname(indexPath));
1855
1871
  atomicWriteJson(indexPath, index);
1856
1872
  }
@@ -2230,14 +2246,21 @@ export class SessionManager {
2230
2246
  * 入站的 `closed → active` 回退只经过这里),因此由本方法兜底同步索引,
2231
2247
  * 否则列表会一直显示旧状态直到 `rebuild-index`。
2232
2248
  */
2233
- async setTopicStatus(sessionId, status) {
2249
+ async setTopicStatus(sessionId, status, updatedAt) {
2234
2250
  const normalized = normalizeTopicStatus(status);
2235
2251
  const loaded = this.loadSessionForUpdate(sessionId);
2236
2252
  if (!loaded || !isTopicSession(loaded.current))
2237
2253
  return false;
2254
+ // 版本号:调用方(`ThreadService.statusThread`)会传入与索引同一次写入的版本,
2255
+ // 让两侧版本一致;只经过本方法的路径(菜单 action、入站回退)自己生成一个。
2256
+ const previous = Number(loaded.current.metadata?.topicStatusUpdatedAt ?? 0);
2257
+ if (updatedAt !== undefined && (!Number.isSafeInteger(updatedAt) || updatedAt <= previous))
2258
+ return false;
2259
+ const version = updatedAt ?? Math.max(Date.now(), previous + 1);
2238
2260
  loaded.current.topicStatus = normalized;
2261
+ loaded.current.metadata = { ...(loaded.current.metadata ?? {}), topicStatusUpdatedAt: version };
2239
2262
  this.persistSession(loaded.current, 'sync', { topicMutation: true });
2240
- this.syncTopicStatusToAgentIndex(loaded.current, normalized);
2263
+ this.syncTopicStatusToAgentIndex(loaded.current, normalized, version);
2241
2264
  return true;
2242
2265
  }
2243
2266
  /**
@@ -2247,7 +2270,7 @@ export class SessionManager {
2247
2270
  * 那里会补 name / peerKind / createdAt 等字段;这里若凭空插入条目,会得到一条
2248
2271
  * 缺字段的残条目。找不到条目(索引尚未建立)时静默跳过,等 rebuild-index 补齐。
2249
2272
  */
2250
- syncTopicStatusToAgentIndex(session, status) {
2273
+ syncTopicStatusToAgentIndex(session, status, updatedAt) {
2251
2274
  const selfAid = session.selfAID;
2252
2275
  const threadId = sessionTopicThreadId(session);
2253
2276
  // 与 upsertAgentThreadIndex 同口径:主会话、daemon 内部会话不是真实话题。
@@ -2266,11 +2289,25 @@ export class SessionManager {
2266
2289
  if (!raw || !Array.isArray(raw.threads))
2267
2290
  return;
2268
2291
  const entry = raw.threads.find((t) => t.threadId === threadId
2269
- && String(t.peer ?? '').toLowerCase() === peer.toLowerCase());
2270
- if (!entry || entry.topicStatus === status)
2292
+ && (t.channelType ?? 'aun') === (session.channelType ?? 'aun')
2293
+ && sameThreadPeer(t.peer, peer, session.channelType ?? 'aun'));
2294
+ if (!entry)
2295
+ return;
2296
+ // 版本闸门:索引里已有更新的状态时不许回写。没有这道闸,一份持有旧 Session
2297
+ // 对象的调用方(跨 await、或菜单侧并发的入站回退)会把刚归档的话题改回 active。
2298
+ const incoming = Number(updatedAt ?? 0) || Date.now();
2299
+ const existing = Number(entry.topicStatusUpdatedAt ?? 0);
2300
+ if (existing >= incoming)
2301
+ return;
2302
+ if (entry.topicStatus === status && existing === incoming)
2303
+ return;
2304
+ const checked = sanitizeIndexEntry({ ...entry, topicStatus: status });
2305
+ if (!checked.ok)
2271
2306
  return;
2307
+ Object.assign(entry, checked.entry);
2272
2308
  entry.topicStatus = status;
2273
- entry.lastActiveAt = Date.now();
2309
+ entry.topicStatusUpdatedAt = incoming;
2310
+ entry.lastActiveAt = Math.max(Number(entry.lastActiveAt ?? 0), incoming);
2274
2311
  atomicWriteJson(indexPath, raw);
2275
2312
  }
2276
2313
  catch (error) {
@@ -16,6 +16,22 @@ export function normalizeTopicStatus(value) {
16
16
  return 'active';
17
17
  throw new Error('topicStatus 必须是 active、closed 或 archived');
18
18
  }
19
+ /**
20
+ * 读取侧口径:不认识的旧值一律读作 `active`,不抛错。
21
+ *
22
+ * 与 `normalizeTopicStatus` 的区别只在未知值:那个用于**写入**(用户输入要拒绝),
23
+ * 这个用于**读取**(历史数据要能读出来)。索引与 session 文件里都存着旧版本的
24
+ * `pending` / `in_progress` / `completed`,直接比较原始值会把"同一个状态"判成
25
+ * stale,或者在 `--status active` 过滤里漏掉这些条目。
26
+ */
27
+ export function readTopicStatusLenient(value) {
28
+ try {
29
+ return normalizeTopicStatus(value);
30
+ }
31
+ catch {
32
+ return 'active';
33
+ }
34
+ }
19
35
  /** Resolve the public archived query flag while keeping omitted values backward compatible. */
20
36
  export function resolveTopicArchiveFilter(value) {
21
37
  if (value === undefined || value === false)
@@ -49,13 +49,12 @@ function generateOneIndex(indexDir, filename, skills, label, skillRoot) {
49
49
  技能目录 = 根目录 + "${path.sep}" + 技能名
50
50
  执行脚本时必须写完整绝对路径。
51
51
  `;
52
- // 技能条目(name + description),并附示例路径
52
+ // 技能条目(name + description)。头部已给出「技能目录 = 根目录 + 技能名」,
53
+ // 逐条再列一遍绝对路径是重复:14 个技能白占约 1.4 KB 每会话。
53
54
  const items = [];
54
55
  for (const skill of skills) {
55
56
  const desc = readSkillDescription(skill.skillDir);
56
57
  items.push(`- ${skill.name}\n ${desc || '(无描述)'}`);
57
- // 示例路径:用真实技能名,不是占位符
58
- items.push(` 示例(技能名为 ${skill.name}): ${path.join(skill.skillDir, 'SKILL.md')}`);
59
58
  }
60
59
  const content = header + '\n' + items.join('\n\n') + '\n';
61
60
  fs.writeFileSync(filePath, content, 'utf-8');
@@ -80,6 +80,9 @@ function readSwitchesFile(file) {
80
80
  locked: sw.locked !== undefined ? Boolean(sw.locked) : false,
81
81
  };
82
82
  }
83
+ // Preserve an old per-Agent/local override when the built-in skill was renamed.
84
+ if (!('ec-proxy' in result) && 'ec-service-proxy' in result)
85
+ result['ec-proxy'] = result['ec-service-proxy'];
83
86
  return result;
84
87
  }
85
88
  catch {
@@ -193,6 +193,7 @@ export class TaskRecoveryService {
193
193
  $schema_version: 3.1, id: trigger.triggerId, agentAid: session.selfAID, name: 'task-recovery',
194
194
  origin: { channelKey: message.channel, channelType, channelId: session.channelId,
195
195
  peerId, session: sessionTopicThreadId(session) ? 'thread' : 'main',
196
+ threadId: sessionTopicThreadId(session),
196
197
  delivery: session.chatType === 'group' ? { chatType: 'group', groupId: session.channelId } : { chatType: 'private' } },
197
198
  source: { type: 'once' }, execution: { type: 'target_session', prompt: TASK_RECOVERY_PROMPT },
198
199
  feedback: { strategy: 'origin' },
@@ -10,6 +10,7 @@ const OPTIONS = {
10
10
  show: [], history: ['--limit', '--before', '--after'],
11
11
  create: ['--name', '--status', '--group', '--private'], rename: [], status: [],
12
12
  delete: [], 'rebuild-index': ['--check', '--agent'], 'check-index': ['--agent'],
13
+ 'reconcile-status': ['--write', '--agent', '--check'],
13
14
  'summary-show': [], 'summary-set': ['--name', '--if-rev'], 'summary-log': [], 'summary-clear': [],
14
15
  };
15
16
  /**
@@ -76,7 +77,7 @@ export function resolveThreadCommandArgv(argv, context = {}) {
76
77
  const sort = text('--sort');
77
78
  if (sort !== undefined && sort !== 'recent' && sort !== 'created')
78
79
  throw new Error('Invalid sort order');
79
- const maximum = ['peers', 'rebuild-index', 'check-index'].includes(command) ? 0
80
+ const maximum = ['peers', 'rebuild-index', 'check-index', 'reconcile-status'].includes(command) ? 0
80
81
  : ['rename', 'status'].includes(command) ? 2 : command === 'summary-set' ? Infinity : 1;
81
82
  const minimum = maximum === 0 ? 0 : ['rename', 'status', 'summary-set'].includes(command) ? 2 : 1;
82
83
  if (positional.length < minimum || positional.length > maximum)
@@ -138,6 +139,8 @@ export function resolveThreadCommandArgv(argv, context = {}) {
138
139
  request.topicStatus = status;
139
140
  if (command === 'rebuild-index')
140
141
  request.dryRun = options.has('--check');
142
+ if (command === 'reconcile-status')
143
+ request.apply = options.has('--write');
141
144
  if (command === 'summary-set') {
142
145
  if (!text('--name')?.trim())
143
146
  throw new Error('Summary requires --name; use - to keep the current name');
@@ -53,7 +53,9 @@ export function createThreadOperationExecutor(dependencies) {
53
53
  permissionMode: grant.permissionMode, processOwners: dependencies.getProcessOwners(),
54
54
  ...trustedExecutionIdentityInput(grant),
55
55
  });
56
- const readOnly = ['list', 'list-peers', 'show', 'history', 'check-index', 'summary-show', 'summary-log'].includes(request.op);
56
+ const readOnly = ['list', 'list-peers', 'show', 'history', 'check-index', 'summary-show', 'summary-log',
57
+ // 不带 --write 的对账只报告,按只读对待;带 --write 时仍要过写权限闸门。
58
+ ...(request.op === 'reconcile-status' && request.apply !== true ? ['reconcile-status'] : [])].includes(request.op);
57
59
  // 话题数据是**本 agent 自己的**(`agents/<self>/data/threads/`),与当前
58
60
  // 所在的关系(私聊对端 / 群)无关。因此:
59
61
  // - 触发场景的 chatType 不能决定能否操作话题:在群里被要求联系第三方,
@@ -90,7 +92,7 @@ export function createThreadOperationExecutor(dependencies) {
90
92
  }
91
93
  if (grant && subject) {
92
94
  const relationOnly = subject.dataScope === 'relation';
93
- const globalOperation = ['list-peers', 'check-index', 'rebuild-index'].includes(request.op);
95
+ const globalOperation = ['list-peers', 'check-index', 'rebuild-index', 'reconcile-status'].includes(request.op);
94
96
  const decision = await authorizeOperation({
95
97
  source: 'agent-tool', subject,
96
98
  intent: { operation: `ec.thread.${request.op}`, scope: globalOperation && !(relationOnly && request.op === 'list-peers') ? 'agent' : 'relation', source: 'agent-tool', args: { self: request.selfAid, targetAgentAid: request.selfAid, peer: request.peer ?? currentPeer, peerKey: grant.peerKey } },
@@ -121,18 +121,24 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
121
121
  resp.indexWarning = indexWarning;
122
122
  return resp;
123
123
  }
124
+ case 'reconcile-status': {
125
+ // 逐条对齐「索引 ↔ 会话文件」的状态漂移,与全量 rebuild 区分开:
126
+ // 只改冲突字段,其余条目不动;默认只报告,--write 才落盘。
127
+ const result = threadService.reconcileStatus(selfAid, { apply: request.apply === true });
128
+ return { ok: true, result };
129
+ }
124
130
  case 'check-index': {
125
131
  const result = threadService.checkIndex(selfAid);
126
132
  let warning;
127
- if (result.missing > 0 && result.stale > 0) {
128
- warning = `索引异常:${result.missing} 条 session 文件缺失(数据问题),${result.stale} 条属性与文件不一致(写盘时序)`;
129
- }
130
- else if (result.missing > 0) {
131
- warning = `索引异常:${result.missing} 条 session 文件缺失,rebuild-index 后相关话题的 rename/status 改动将回退`;
132
- }
133
- else if (result.stale > 0) {
134
- warning = `索引轻微不一致:${result.stale} 条话题属性(name/status)与 session 文件最后一行不同步,rebuild-index 可修复`;
135
- }
133
+ const issues = [];
134
+ if (result.missing > 0)
135
+ issues.push(`${result.missing} 条 session 文件缺失(数据问题)`);
136
+ if (result.stale > 0)
137
+ issues.push(`${result.stale} 条属性与文件不一致(写盘时序)`);
138
+ if (result.selfPeer > 0)
139
+ issues.push(`${result.selfPeer} 条对端是本端自己的残缺话题(需删除)`);
140
+ if (issues.length > 0)
141
+ warning = `索引异常:${issues.join(',')}`;
136
142
  return { ok: true, result, indexWarning: warning };
137
143
  }
138
144
  case 'history': {
@@ -219,7 +225,16 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
219
225
  if (dryRun) {
220
226
  const { rebuilt } = result;
221
227
  const check = threadService.checkIndex(selfAid);
222
- return { ok: true, result: { rebuilt, missing: check.missing, missingIds: check.missingIds, dryRun: true } };
228
+ return {
229
+ ok: true,
230
+ result: {
231
+ rebuilt,
232
+ missing: check.missing, missingIds: check.missingIds,
233
+ stale: check.stale, staleIds: check.staleIds,
234
+ selfPeer: check.selfPeer, selfPeerIds: check.selfPeerIds,
235
+ dryRun: true,
236
+ },
237
+ };
223
238
  }
224
239
  return { ok: true, result };
225
240
  }