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
@@ -0,0 +1,328 @@
1
+ /**
2
+ * 网关 agent 的消息路由器。
3
+ *
4
+ * 参照 `DiagnosticSessionRouter` 的形态:在 `message-bridge` 里对特定 AID 走一条
5
+ * 独立分支,**不进 baseagent、不跑模型**。收到的每条消息只做两件事——
6
+ *
7
+ * 1. 找出这条消息所属话题绑定的 Claude Code 会话;
8
+ * 2. 把正文投递过去,并把对方的输出原样回给消息来源。
9
+ *
10
+ * ## 与普通 agent 的区别
11
+ *
12
+ * 普通 agent 的消息最终进 `ResponseEngine` → 模型。网关 agent 的模型调用次数是 0:
13
+ * 它只是搬运。用户看到的回复来自那个 Claude Code 终端,不是 evolcore 的模型。
14
+ */
15
+ import { logger } from '../../utils/logger.js';
16
+ import { findThreadBySession, getBinding, listBindings, removeBinding, setBinding, } from './binding.js';
17
+ import { deliverToSession } from './inbox.js';
18
+ import { getCcAgentAid } from './agent-registration.js';
19
+ import { loadDaemonConfig } from '../../config-store.js';
20
+ import { currentContactBinding, sameContactBinding } from '../../core/message/contact-admission.js';
21
+ import { safeFormatMainTopicId, isMainTopicId, mainTopicPeer, sameThreadPeer } from '../../core/thread/topic-id.js';
22
+ import { TranscriptTail, findTranscript } from './transcript.js';
23
+ import { findClaudeSession, listClaudeSessions } from './sessions.js';
24
+ import { findSessionCwd, listProjectDirectories, listSessionsForMenu, resolveDirectorySelection, resolveSessionSelection, } from './listing.js';
25
+ import { launchSession } from './terminal.js';
26
+ import { checkAvailability, ensureOnline, ClaudeCodePeer } from './index.js';
27
+ /**
28
+ * 判断某个 AID 是不是本机的 ccagent。
29
+ *
30
+ * AID 记在 `daemon.json` 的 `ccAgent.aid`,每台机器可能不同,
31
+ * 所以不能写死常量。查不到配置就返回 false(退化成普通 agent 处理)。
32
+ */
33
+ export function isCcAgentAid(aid) {
34
+ if (!aid)
35
+ return false;
36
+ const configured = getCcAgentAid();
37
+ return configured !== undefined && configured === aid.trim();
38
+ }
39
+ /** 每个授权绑定范围上一次展示的列表,用来解析「回 3」这类序号选择。 */
40
+ const lastListingByAid = new Map();
41
+ /** 每个授权绑定范围上一次展示的目录列表,用来解析「new 2」这类选择。 */
42
+ const lastDirectoriesByAid = new Map();
43
+ const outputSubscriptions = new Map();
44
+ /** Follow only the bound terminal's new assistant text; never replay terminal history. */
45
+ function followOutput(key, sessionId, aid, input) {
46
+ if (!input.sendOutput || !input.authorize)
47
+ throw new Error('Gateway output authorization is unavailable');
48
+ if (outputSubscriptions.get(key)?.sessionId === sessionId)
49
+ return;
50
+ outputSubscriptions.get(key)?.close();
51
+ const tail = new TranscriptTail(findTranscript(sessionId));
52
+ let busy = false;
53
+ let activeUntil = Date.now() + 30 * 60_000;
54
+ const close = () => {
55
+ clearInterval(timer);
56
+ if (outputSubscriptions.get(key)?.close === close)
57
+ outputSubscriptions.delete(key);
58
+ };
59
+ const timer = setInterval(async () => {
60
+ if (busy)
61
+ return;
62
+ busy = true;
63
+ try {
64
+ if (Date.now() > activeUntil || loadDaemonConfig().ccAgent?.enabled !== true
65
+ || !sameContactBinding(input.ownerBinding, currentContactBinding(aid))
66
+ || getBinding(key)?.sessionId !== sessionId || !await input.authorize())
67
+ return close();
68
+ tail.attach(sessionId, true);
69
+ for (const entry of tail.poll()) {
70
+ if (entry.type !== 'assistant' || !entry.text)
71
+ continue;
72
+ if (!await input.authorize())
73
+ return close();
74
+ await input.sendOutput(entry.text);
75
+ activeUntil = Date.now() + 30 * 60_000;
76
+ }
77
+ }
78
+ catch (error) {
79
+ logger.warn('[claude-gateway] output delivery stopped:', error instanceof Error ? error.message : String(error));
80
+ close();
81
+ }
82
+ finally {
83
+ busy = false;
84
+ }
85
+ }, 500);
86
+ timer.unref?.();
87
+ outputSubscriptions.set(key, { sessionId, close });
88
+ }
89
+ export function stopGatewayOutputs() {
90
+ for (const subscription of [...outputSubscriptions.values()])
91
+ subscription.close();
92
+ }
93
+ /**
94
+ * 把一条入站消息路由到它所属的 Claude Code 会话。
95
+ *
96
+ * 已绑定会话离线时返回 `offline`;只有显式选择或新建会话才会拉起终端。
97
+ */
98
+ export async function routeToGateway(aid, input) {
99
+ if (loadDaemonConfig().ccAgent?.enabled !== true)
100
+ return { kind: 'error', message: 'Claude 网关未启用。请由宿主 Owner 显式启用 ccAgent.enabled。' };
101
+ if (!input.ownerBinding || !input.deviceId || !input.authorize || !input.sendOutput
102
+ || input.ownerBinding.owner_aid !== input.from || !await input.authorize()) {
103
+ return { kind: 'error', message: 'Claude 网关仅接受当前协议 Owner 的加密设备私聊。' };
104
+ }
105
+ const externalThreadId = input.threadId?.trim();
106
+ const main = safeFormatMainTopicId(aid, input.from);
107
+ if (externalThreadId && isMainTopicId(externalThreadId)
108
+ && !sameThreadPeer(mainTopicPeer(externalThreadId, aid), input.from)) {
109
+ return { kind: 'error', message: '主话题身份与当前双方不匹配' };
110
+ }
111
+ const threadId = JSON.stringify([aid, input.from, input.deviceId, input.ownerBinding.relation_version,
112
+ !externalThreadId || isMainTopicId(externalThreadId) ? main : externalThreadId]);
113
+ // 主会话先选择并绑定终端;绑定后的普通正文沿用该会话。
114
+ if (!externalThreadId || isMainTopicId(externalThreadId)) {
115
+ const bound = getBinding(threadId);
116
+ const command = input.content.trim();
117
+ if (!bound || /^(list|列表|会话|新建|new)(\s|$)/i.test(command)) {
118
+ return routeFromMainSession(threadId, input.content);
119
+ }
120
+ }
121
+ // 话题里也可以「新建」——在这个目录开新会话并绑定到当前话题。
122
+ // 放在绑定检查之前,这样未绑定的话题也能靠它完成第一次绑定。
123
+ const directoryPick = resolveDirectorySelection(input.content, lastDirectoriesByAid.get(threadId));
124
+ if (directoryPick === 'ambiguous') {
125
+ return { kind: 'launch_failed', message: '匹配到多个目录,请发更完整的路径。' };
126
+ }
127
+ if (directoryPick === 'list') {
128
+ const directories = await listProjectDirectories();
129
+ lastDirectoriesByAid.set(threadId, directories);
130
+ return { kind: 'directory_listing', directories };
131
+ }
132
+ if (directoryPick) {
133
+ return beginNewSession(aid, threadId, directoryPick.path);
134
+ }
135
+ const binding = getBinding(threadId);
136
+ if (!binding) {
137
+ // 未绑定且没给目录:先把可选目录给他,比一句"未绑定"有用
138
+ const directories = await listProjectDirectories();
139
+ lastDirectoriesByAid.set(threadId, directories);
140
+ return { kind: 'directory_listing', directories };
141
+ }
142
+ const session = await findClaudeSession({ sessionId: binding.sessionId }, { probe: true });
143
+ if (!session?.online) {
144
+ // 不在这里拉起:会话的开与关由用户在终端决定,网关只反映现状。
145
+ return { kind: 'offline', sessionId: binding.sessionId, title: binding.title };
146
+ }
147
+ try {
148
+ if (!await input.authorize())
149
+ return { kind: 'error', message: '网关授权已失效' };
150
+ followOutput(threadId, session.sessionId, aid, input);
151
+ await deliverToSession(session, input.content, {
152
+ from: toAddress(input.from),
153
+ fromName: input.fromName,
154
+ });
155
+ }
156
+ catch (error) {
157
+ logger.warn('[claude-gateway] 投递失败:', error.message);
158
+ return { kind: 'error', message: `投递到会话失败:${error.message}` };
159
+ }
160
+ return { kind: 'delivered', sessionId: session.sessionId, sessionName: session.name };
161
+ }
162
+ /**
163
+ * 在指定目录开一个新会话,并绑定到给定话题。
164
+ *
165
+ * 新会话的 sessionId 由 Claude Code 生成,拉起前无从得知,所以靠
166
+ * `launchSession` 轮询「该目录下拉起之后才出现的会话」反推。
167
+ * 认出来就立刻绑定——此后这个话题的消息都发往它。
168
+ *
169
+ * @param threadId 包含身份、设备、归属版本和话题的授权绑定键;空串不保存绑定。
170
+ */
171
+ async function beginNewSession(aid, threadId, cwd) {
172
+ const title = cwd.split(/[\\/]/).filter(Boolean).pop() ?? '新会话';
173
+ const result = await launchSession({ cwd, title });
174
+ if (!result.online) {
175
+ return { kind: 'launch_failed', message: result.error ?? '拉起新会话失败' };
176
+ }
177
+ const sessionId = result.sessionId;
178
+ if (!sessionId || !threadId) {
179
+ // 认不出 ID(窗口开了但没起来),或压根不需要绑定
180
+ return { kind: 'new_session', cwd, ...(sessionId ? { sessionId } : {}), bound: false };
181
+ }
182
+ const bound = bindTopic(aid, threadId, { sessionId, cwd }, title);
183
+ return {
184
+ kind: 'new_session',
185
+ cwd,
186
+ sessionId,
187
+ bound: bound.ok,
188
+ };
189
+ }
190
+ /**
191
+ * 主会话路由:用户要么在看列表,要么在指定一个会话。
192
+ *
193
+ * - 消息能解析成一个已有会话(序号 / sessionId 前缀 / 显示名)→ 检查窗口在不在,
194
+ * 不在就拉起。**拉起必然带 `--resume`**,这样终端里的消息流能看到历史对话。
195
+ * - 否则 → 回列表(并记住它,供下一次用序号选择)。
196
+ */
197
+ async function routeFromMainSession(aid, content) {
198
+ // 先看是不是「开新会话」类的指令,再看是不是选已有会话。
199
+ // 顺序不能反:`new 3` 里的 3 是目录序号,不是会话序号。
200
+ const directoryPick = resolveDirectorySelection(content, lastDirectoriesByAid.get(aid));
201
+ if (directoryPick === 'list') {
202
+ const directories = await listProjectDirectories();
203
+ lastDirectoriesByAid.set(aid, directories);
204
+ return { kind: 'directory_listing', directories };
205
+ }
206
+ if (directoryPick === 'ambiguous') {
207
+ return { kind: 'launch_failed', message: '匹配到多个目录,请发更完整的路径。' };
208
+ }
209
+ if (directoryPick) {
210
+ // 主会话新建终端后也保存授权绑定,供后续正文投递。
211
+ return beginNewSession(aid, aid, directoryPick.path);
212
+ }
213
+ const previous = lastListingByAid.get(aid);
214
+ const selected = resolveSessionSelection(content, previous);
215
+ if (selected === 'ambiguous') {
216
+ return { kind: 'launch_failed', message: '匹配到多个会话,请发更完整的会话 ID 或列表序号。' };
217
+ }
218
+ if (selected) {
219
+ // 已经在跑:不重复开窗,直接告诉用户
220
+ const running = await findClaudeSession({ sessionId: selected.sessionId }, { probe: true });
221
+ if (running?.online) {
222
+ const bound = bindTopic(aid, aid, running, selected.title);
223
+ if (!bound.ok)
224
+ return { kind: 'error', message: bound.error };
225
+ return {
226
+ kind: 'launched',
227
+ sessionId: selected.sessionId,
228
+ title: selected.title,
229
+ alreadyOnline: true,
230
+ };
231
+ }
232
+ // cwd 解析与可恢复性校验都在 launchSession 内部完成(唯一判定处),
233
+ // 这里只负责把已知的候选目录传下去。
234
+ const cwd = await findSessionCwd(selected.sessionId) ?? selected.cwd ?? '';
235
+ const result = await launchSession({
236
+ cwd,
237
+ sessionId: selected.sessionId,
238
+ title: selected.title,
239
+ windowName: `claude-${selected.sessionId.slice(0, 8)}`,
240
+ });
241
+ if (!result.online) {
242
+ return {
243
+ kind: 'launch_failed',
244
+ message: result.error ?? '窗口已开但会话未上线',
245
+ };
246
+ }
247
+ const bound = bindTopic(aid, aid, { sessionId: selected.sessionId, cwd }, selected.title);
248
+ if (!bound.ok)
249
+ return { kind: 'error', message: bound.error };
250
+ return {
251
+ kind: 'launched',
252
+ sessionId: selected.sessionId,
253
+ title: selected.title,
254
+ alreadyOnline: false,
255
+ };
256
+ }
257
+ // 没有指定会话:回列表,并记住它
258
+ const sessions = await listSessionsForMenu();
259
+ lastListingByAid.set(aid, sessions);
260
+ return { kind: 'listing', sessions };
261
+ }
262
+ /** 把任意 AID 收敛成对端能接受的地址形状。 */
263
+ function toAddress(aid) {
264
+ const trimmed = aid.trim();
265
+ if (!trimmed)
266
+ return '';
267
+ if (/^(?:uds|bridge|did):/.test(trimmed))
268
+ return trimmed;
269
+ // AUN 的 AID 本身就是域名形状,用 did 前缀包一层
270
+ return `did:aun:${trimmed}`;
271
+ }
272
+ /**
273
+ * 用户确认后拉起绑定的会话。
274
+ *
275
+ * 拉起来之后会把「会话已上线」这件事回给调用方,由调用方再决定要不要
276
+ * 把用户那条消息补投过去。
277
+ */
278
+ export async function launchBoundSession(aid, threadId, options = {}) {
279
+ const binding = getBinding(threadId);
280
+ if (!binding)
281
+ return { ok: false, error: '该话题尚未绑定会话' };
282
+ const result = await ensureOnline(binding.sessionId, {
283
+ cwd: binding.cwd,
284
+ title: binding.title ?? threadId.slice(0, 12),
285
+ windowName: `claude-${binding.sessionId.slice(0, 8)}`,
286
+ ...options,
287
+ });
288
+ if (!result.online) {
289
+ return { ok: false, error: result.error ?? '会话未能上线', sessionId: binding.sessionId };
290
+ }
291
+ return { ok: true, sessionId: binding.sessionId };
292
+ }
293
+ /**
294
+ * 把一个话题绑定到某个 Claude Code 会话。
295
+ *
296
+ * 一个 sessionId 只能被一个话题占用,否则两个话题的输出会串。
297
+ */
298
+ export function bindTopic(aid, threadId, session, title) {
299
+ if (!threadId.trim())
300
+ return { ok: false, error: '话题 ID 不能为空' };
301
+ const occupied = findThreadBySession(session.sessionId);
302
+ if (occupied && occupied !== threadId) {
303
+ return { ok: false, error: `该 Claude Code 会话已被话题 ${occupied} 占用` };
304
+ }
305
+ const binding = setBinding(threadId, {
306
+ sessionId: session.sessionId,
307
+ cwd: session.cwd,
308
+ title,
309
+ });
310
+ return { ok: true, binding };
311
+ }
312
+ /** 解绑。 */
313
+ export function unbindTopic(aid, threadId) {
314
+ return removeBinding(threadId);
315
+ }
316
+ /** 列出该 agent 的全部话题绑定及其实时状态。 */
317
+ export async function describeBindings(aid) {
318
+ const bindings = listBindings();
319
+ return Promise.all(bindings.map(async (entry) => ({
320
+ ...entry,
321
+ online: (await checkAvailability(entry.binding.sessionId)) === 'online',
322
+ })));
323
+ }
324
+ /** 可供绑定的会话列表(已排除 evolcore 自己的)。 */
325
+ export async function listBindableSessions() {
326
+ return listClaudeSessions({ includeEvolcore: false, probe: true });
327
+ }
328
+ export { ClaudeCodePeer };
@@ -0,0 +1,128 @@
1
+ /**
2
+ * 枚举本机 Claude Code 会话,并区分「用户自己的」与「evolcore 自己起的」。
3
+ *
4
+ * 数据源是 `~/.claude/sessions/*.json`:每个运行中的 Claude Code 进程写一份,
5
+ * 内含 pid、sessionId、cwd、messagingSocketPath 等。进程退出后文件会残留,
6
+ * 因此不能只看文件存在,必须探测管道。
7
+ */
8
+ import fs from 'node:fs';
9
+ import net from 'node:net';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { logger } from '../../utils/logger.js';
13
+ import { loadAllAgents } from '../../config-store.js';
14
+ const SESSIONS_DIR = path.join(os.homedir(), '.claude', 'sessions');
15
+ /** 探测管道连通的默认超时。管道不通时 Windows 很快返回,给足冗余即可。 */
16
+ const PROBE_TIMEOUT_MS = 800;
17
+ /**
18
+ * 判定一个会话是否由 evolcore 自己创建。
19
+ *
20
+ * 不能只看 cwd:用户完全可能在 evolcore 仓库目录下手开会话。
21
+ * evolcore 起的 Claude 跑在 agent 项目目录下(`.../evolcore-agents/<aid>/`),
22
+ * 这条路径特征比 cwd 本身更可靠。
23
+ */
24
+ export function isEvolcoreOwned(session) {
25
+ // Use actual Agent configuration instead of assuming one fixed workspace prefix.
26
+ const agents = loadAllAgents().agents;
27
+ if (agents.some(agent => {
28
+ const project = agent.projects?.defaultPath;
29
+ return typeof project === 'string' && path.resolve(project) === path.resolve(session.cwd);
30
+ }))
31
+ return true;
32
+ const normalized = session.cwd.replace(/\\/g, '/').toLowerCase();
33
+ return normalized.includes('/evolcore-agents/')
34
+ || normalized.includes('/evolcore/test-tmp/');
35
+ }
36
+ /** 探测命名管道/套接字是否可连。 */
37
+ export function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
38
+ return new Promise(resolve => {
39
+ if (!socketPath) {
40
+ resolve(false);
41
+ return;
42
+ }
43
+ let settled = false;
44
+ const done = (ok) => {
45
+ if (settled)
46
+ return;
47
+ settled = true;
48
+ socket.destroy();
49
+ resolve(ok);
50
+ };
51
+ const socket = net.connect(socketPath);
52
+ socket.setTimeout(timeoutMs);
53
+ socket.once('connect', () => done(true));
54
+ socket.once('error', () => done(false));
55
+ socket.once('timeout', () => done(false));
56
+ });
57
+ }
58
+ /** 读取单个会话元数据,字段缺失或格式不对返回 undefined。 */
59
+ function parseSessionFile(file) {
60
+ let raw;
61
+ try {
62
+ raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
63
+ }
64
+ catch {
65
+ return undefined;
66
+ }
67
+ const pid = raw.pid;
68
+ const socket = raw.messagingSocketPath;
69
+ const sessionId = raw.sessionId;
70
+ if (typeof pid !== 'number' || typeof socket !== 'string' || typeof sessionId !== 'string') {
71
+ return undefined;
72
+ }
73
+ return {
74
+ pid,
75
+ sessionId,
76
+ cwd: typeof raw.cwd === 'string' ? raw.cwd : '',
77
+ name: typeof raw.name === 'string' ? raw.name : `pid-${pid}`,
78
+ status: typeof raw.status === 'string' ? raw.status : 'unknown',
79
+ kind: typeof raw.kind === 'string' ? raw.kind : 'unknown',
80
+ procStart: typeof raw.procStart === 'string' ? raw.procStart : '',
81
+ startedAt: typeof raw.startedAt === 'number' ? raw.startedAt : 0,
82
+ socket,
83
+ online: false,
84
+ };
85
+ }
86
+ /**
87
+ * 枚举本机会话。
88
+ *
89
+ * @param includeEvolcore 是否包含 evolcore 自己创建的会话,默认 false
90
+ * @param probe 是否探测管道连通(会多花几百毫秒),默认 true
91
+ */
92
+ export async function listClaudeSessions(options = {}) {
93
+ const { includeEvolcore = false, probe = true } = options;
94
+ let files;
95
+ try {
96
+ files = fs.readdirSync(SESSIONS_DIR).filter(f => f.endsWith('.json'));
97
+ }
98
+ catch (error) {
99
+ logger.debug('[claude-gateway] 会话目录不可读:', error);
100
+ return [];
101
+ }
102
+ const sessions = [];
103
+ for (const file of files) {
104
+ const session = parseSessionFile(path.join(SESSIONS_DIR, file));
105
+ if (!session)
106
+ continue;
107
+ if (!includeEvolcore && isEvolcoreOwned(session))
108
+ continue;
109
+ sessions.push(session);
110
+ }
111
+ if (probe) {
112
+ await Promise.all(sessions.map(async (session) => {
113
+ session.online = await probeSocket(session.socket);
114
+ }));
115
+ // 只有探测过才按 online 过滤:不探测时 online 一律是 false,
116
+ // 过滤会把结果清空(曾导致「不探测」等价于「没有会话」)。
117
+ return sessions
118
+ .filter(session => session.online)
119
+ .sort((a, b) => b.startedAt - a.startedAt);
120
+ }
121
+ return sessions.sort((a, b) => b.startedAt - a.startedAt);
122
+ }
123
+ /** 按 sessionId 或 pid 找会话,找不到返回 undefined。 */
124
+ export async function findClaudeSession(target, options = {}) {
125
+ const sessions = await listClaudeSessions({ includeEvolcore: true, probe: options.probe });
126
+ return sessions.find(session => (target.sessionId !== undefined && session.sessionId === target.sessionId)
127
+ || (target.pid !== undefined && session.pid === target.pid));
128
+ }