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,138 @@
1
+ /**
2
+ * 向运行中的 Claude Code 会话投递一条消息。
3
+ *
4
+ * 走的是 Claude Code 自带的跨会话 inbox——和 `SendMessage` 工具同一条通道。
5
+ * 协议(从 claude.exe 内置示例提取并实测):
6
+ *
7
+ * 连接命名管道 → 写首行 auth → 写消息行 → 关闭
8
+ *
9
+ * {"type":"auth","token":"<32位hex>"}\n
10
+ * {"type":"user","msg_id":"<uuid>","from":"<地址>","message":{"role":"user","content":"<正文>"}}\n
11
+ *
12
+ * 首行必须在 firstLineDeadlineMs(30 秒)内写完,否则对端直接断开。
13
+ * 对端空闲时消息会开启新轮,忙时在工具调用之间读入;内容按纯文本处理,
14
+ * 斜杠命令不生效(解码时带 skipSlashCommands)。
15
+ */
16
+ import crypto from 'node:crypto';
17
+ import fs from 'node:fs';
18
+ import net from 'node:net';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { logger } from '../../utils/logger.js';
22
+ const SESSIONS_DIR = path.join(os.homedir(), '.claude', 'sessions');
23
+ /** 令牌文件名形如 `<pid>.<sha256>.key`。 */
24
+ const KEY_FILE_RE = /^(\d+)\.[0-9a-f]{64}\.key$/;
25
+ /** 对端只接受这三种前缀的地址形状。 */
26
+ const ADDRESS_RE = /^(?:uds|bridge|did):[A-Za-z0-9%:_/.\-]{1,200}$/;
27
+ /** 写完后留一点时间给对端读完,再断开。 */
28
+ const CLOSE_GRACE_MS = 200;
29
+ /**
30
+ * 读取会话的投递令牌。
31
+ *
32
+ * 令牌文件名里的 sha256 是 socket 路径的哈希,**不能从 pid 推导**,必须扫目录配对。
33
+ * 每次投递前现读,因为会话重启后令牌会换。
34
+ */
35
+ export function readInboxToken(session) {
36
+ let names;
37
+ try {
38
+ names = fs.readdirSync(SESSIONS_DIR);
39
+ }
40
+ catch (error) {
41
+ throw new Error(`会话目录不可读:${error.message}`);
42
+ }
43
+ const candidates = [];
44
+ for (const name of names) {
45
+ const match = KEY_FILE_RE.exec(name);
46
+ if (!match || Number(match[1]) !== session.pid)
47
+ continue;
48
+ const socketHash = crypto.createHash('sha256').update(session.socket).digest('hex');
49
+ if (!name.includes(socketHash))
50
+ continue;
51
+ const file = path.join(SESSIONS_DIR, name);
52
+ let parsed;
53
+ try {
54
+ parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ const token = parsed.peerToken;
60
+ if (typeof token !== 'string' || !/^[0-9a-f]{32}$/.test(token))
61
+ continue;
62
+ // 同 pid 的旧进程可能留下令牌文件,用进程创建时间排除
63
+ const keyProcStart = typeof parsed.procStart === 'string' ? parsed.procStart : undefined;
64
+ if (session.procStart && keyProcStart && keyProcStart !== session.procStart)
65
+ continue;
66
+ candidates.push({ mtime: fs.statSync(file).mtimeMs, token });
67
+ }
68
+ if (candidates.length === 0) {
69
+ throw new Error(`找不到 pid=${session.pid} 的投递令牌。可能原因:会话以 --bare 启动、受限模式、或版本过旧。`);
70
+ }
71
+ // 多个候选时取最新写入的
72
+ candidates.sort((a, b) => b.mtime - a.mtime);
73
+ return candidates[0].token;
74
+ }
75
+ /** 构造要写入管道的帧文本。 */
76
+ export function buildInboxFrames(token, text, options = {}) {
77
+ const auth = { type: 'auth', token };
78
+ const user = {
79
+ type: 'user',
80
+ msg_id: crypto.randomUUID(),
81
+ message: { role: 'user', content: text },
82
+ };
83
+ // from / from_name 只是「自称」,对端照着显示,不做身份验证
84
+ if (options.from && ADDRESS_RE.test(options.from)) {
85
+ user.from = options.from;
86
+ }
87
+ else if (options.from) {
88
+ logger.debug('[claude-gateway] from 地址形状不合法,已忽略:', options.from);
89
+ }
90
+ if (options.fromName) {
91
+ user.from_name = options.fromName;
92
+ }
93
+ return `${JSON.stringify(auth)}\n${JSON.stringify(user)}\n`;
94
+ }
95
+ /** 把一段文本写进命名管道(或 Unix 套接字),写完关闭。 */
96
+ function writeToSocket(socketPath, payload) {
97
+ return new Promise((resolve, reject) => {
98
+ const socket = net.connect(socketPath);
99
+ let settled = false;
100
+ const fail = (error) => {
101
+ if (settled)
102
+ return;
103
+ settled = true;
104
+ socket.destroy();
105
+ reject(error);
106
+ };
107
+ socket.once('error', fail);
108
+ socket.once('connect', () => {
109
+ socket.write(payload, 'utf-8', writeError => {
110
+ if (writeError) {
111
+ fail(writeError);
112
+ return;
113
+ }
114
+ // 给对端留时间读完再断开,否则可能被当成半截帧丢弃
115
+ setTimeout(() => {
116
+ if (settled)
117
+ return;
118
+ settled = true;
119
+ socket.end();
120
+ resolve();
121
+ }, CLOSE_GRACE_MS);
122
+ });
123
+ });
124
+ });
125
+ }
126
+ /**
127
+ * 投递一条消息到指定会话。
128
+ *
129
+ * @returns 投递是否已写入管道。**这不等于对方已处理**——只能确认字节写出去了。
130
+ */
131
+ export async function deliverToSession(session, text, options = {}) {
132
+ if (!session.socket) {
133
+ throw new Error(`会话 pid=${session.pid} 没有 messagingSocketPath`);
134
+ }
135
+ const token = readInboxToken(session);
136
+ const frames = buildInboxFrames(token, text, options);
137
+ await writeToSocket(session.socket, frames);
138
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Claude Code 会话网关:把本机 Claude Code 终端会话接进 evolcore。
3
+ *
4
+ * ## 分层
5
+ *
6
+ * - `sessions.ts` 枚举会话、区分归属、探测在线
7
+ * - `inbox.ts` 向会话投递消息
8
+ * - `transcript.ts` 跟读会话输出
9
+ * - `terminal.ts` 拉起离线会话
10
+ *
11
+ * ## 一个话题 = 一个 sessionId
12
+ *
13
+ * 话题绑定 Claude Code 的 sessionId(不是 pid,也不是 cwd)。会话进程不在时,
14
+ * 用 `claude --resume <sessionId>` 拉起即可接续上下文。因此:
15
+ *
16
+ * - **在线**:直接投递
17
+ * - **离线**:先问用户是否拉起,确认后拉起再投递
18
+ *
19
+ * ## 不要用这里去驱动 evolcore 自己的 agent
20
+ *
21
+ * evolcore 的 agent 由 `claude-runner.ts`(Agent SDK)负责。本网关的定位是
22
+ * 「接管 evolcore 管不到的那些、人或别的工具正在用的终端会话」。两者职责不重叠。
23
+ */
24
+ import { logger } from '../../utils/logger.js';
25
+ import { deliverToSession, readInboxToken } from './inbox.js';
26
+ import { isEvolcoreOwned, listClaudeSessions, findClaudeSession } from './sessions.js';
27
+ import { launchSession } from './terminal.js';
28
+ import { findTranscript, readTranscriptHistory, TranscriptTail } from './transcript.js';
29
+ import { findSessionCwd, listSessionsForMenu, resolveSessionSelection } from './listing.js';
30
+ export { isEvolcoreOwned, listClaudeSessions, findClaudeSession };
31
+ export { deliverToSession, readInboxToken };
32
+ export { findTranscript, readTranscriptHistory, TranscriptTail };
33
+ export { launchSession };
34
+ export { findSessionCwd, listSessionsForMenu, resolveSessionSelection };
35
+ /**
36
+ * 判断一个 sessionId 的当前状态。
37
+ *
38
+ * - `online`:进程在,管道能连
39
+ * - `offline`:找不到进程(需要拉起)
40
+ * - `unknown`:会话目录不可读等异常情况
41
+ */
42
+ export async function checkAvailability(sessionId) {
43
+ if (!sessionId)
44
+ return 'unknown';
45
+ try {
46
+ const session = await findClaudeSession({ sessionId }, { probe: true });
47
+ if (session?.online)
48
+ return 'online';
49
+ return 'offline';
50
+ }
51
+ catch (error) {
52
+ logger.debug('[claude-gateway] 检查会话状态失败:', error);
53
+ return 'unknown';
54
+ }
55
+ }
56
+ /**
57
+ * 确保会话在线:不在线则拉起。
58
+ *
59
+ * 注意这是**不询问用户**的版本。调用方如果需要在拉起前征求确认
60
+ * (比如 App 里弹「会话不在线,是否拉起」),应当先调 `checkAvailability`。
61
+ */
62
+ export async function ensureOnline(sessionId, options) {
63
+ const availability = await checkAvailability(sessionId);
64
+ if (availability === 'online') {
65
+ return { online: true, launched: false };
66
+ }
67
+ return launchSession({ ...options, sessionId });
68
+ }
69
+ /**
70
+ * 一个话题对端:绑定某个 sessionId,负责收发。
71
+ *
72
+ * 典型用法:
73
+ *
74
+ * ```ts
75
+ * const peer = new ClaudeCodePeer({ sessionId, cwd });
76
+ * await peer.send('你好', { from: 'did:aun:xxx', fromName: '老大' });
77
+ * for (;;) {
78
+ * for (const entry of peer.poll()) { ... }
79
+ * await sleep(350);
80
+ * }
81
+ * ```
82
+ */
83
+ export class ClaudeCodePeer {
84
+ binding;
85
+ tail;
86
+ closed = false;
87
+ constructor(binding) {
88
+ this.binding = binding;
89
+ this.tail = new TranscriptTail(findTranscript(binding.sessionId));
90
+ }
91
+ get sessionId() {
92
+ return this.binding.sessionId;
93
+ }
94
+ get cwd() {
95
+ return this.binding.cwd;
96
+ }
97
+ /** 投递一条消息。会话不在线时抛错,调用方应先 `ensureOnline`。 */
98
+ async send(text, options = {}) {
99
+ if (this.closed)
100
+ throw new Error('网关对端已关闭');
101
+ const session = await findClaudeSession({ sessionId: this.binding.sessionId }, { probe: false });
102
+ if (!session) {
103
+ throw new Error(`会话 ${this.binding.sessionId} 不在线`);
104
+ }
105
+ await deliverToSession(session, text, options);
106
+ // 会话可能是刚起的,转录还没建
107
+ this.tail.attach(this.binding.sessionId);
108
+ }
109
+ /** 读出自上次以来的新输出。 */
110
+ poll() {
111
+ if (this.closed)
112
+ return [];
113
+ if (!this.tail.path)
114
+ this.tail.attach(this.binding.sessionId);
115
+ return this.tail.poll();
116
+ }
117
+ /** 当前在线状态。 */
118
+ async availability() {
119
+ return checkAvailability(this.binding.sessionId);
120
+ }
121
+ /** 关闭跟读(不关闭对方的会话进程)。 */
122
+ close() {
123
+ this.closed = true;
124
+ }
125
+ }
@@ -0,0 +1,330 @@
1
+ /**
2
+ * 会话列表:给主会话展示「这台机器上有哪些 Claude Code 会话」。
3
+ *
4
+ * 两个来源合并:
5
+ *
6
+ * 1. **正在运行的**(`~/.claude/sessions/*.json`)——能直接投递,带 pid 与状态;
7
+ * 2. **历史会话**(SDK `listSessions()`)——不在跑,但转录还在,可以 `--resume` 拉起来。
8
+ *
9
+ * 同一个 sessionId 只出现一次:运行中的那条优先。
10
+ *
11
+ * 列表要能让用户"看到聊到哪了",所以每项都带最近一条消息的预览。
12
+ * 预览从转录尾部读,只读最后若干 KB,不整文件加载。
13
+ */
14
+ import fs from 'node:fs';
15
+ import { logger } from '../../utils/logger.js';
16
+ import { findTranscript, stripPeerWrapper } from './transcript.js';
17
+ import { listClaudeSessions } from './sessions.js';
18
+ import { listClaudeSdkSessions } from '../../core/session/adapters/claude-session-file-adapter.js';
19
+ import { buildCliSessionPreview } from '../../core/session/session-title.js';
20
+ /** 读取转录尾部时最多读多少字节,用来找最近一条消息。 */
21
+ const TAIL_BYTES = 64 * 1024;
22
+ /** 列表最多返回多少项。 */
23
+ const MAX_ITEMS = 30;
24
+ /** 预览最多保留多少字符。 */
25
+ const PREVIEW_CHARS = 80;
26
+ /** 从转录尾部取最近一条可展示的消息。 */
27
+ function readLastMessage(sessionId) {
28
+ const file = findTranscript(sessionId);
29
+ if (!file)
30
+ return undefined;
31
+ let chunk;
32
+ let truncated = false;
33
+ try {
34
+ const stat = fs.statSync(file);
35
+ const start = Math.max(0, stat.size - TAIL_BYTES);
36
+ truncated = start > 0;
37
+ const length = stat.size - start;
38
+ const buffer = Buffer.alloc(length);
39
+ const fd = fs.openSync(file, 'r');
40
+ try {
41
+ fs.readSync(fd, buffer, 0, length, start);
42
+ }
43
+ finally {
44
+ fs.closeSync(fd);
45
+ }
46
+ chunk = buffer.toString('utf-8');
47
+ }
48
+ catch (error) {
49
+ logger.debug('[ccagent] 读取转录尾部失败:', error.message);
50
+ return undefined;
51
+ }
52
+ const lines = chunk.split('\n');
53
+ // 第一行很可能是被截断的半行,丢掉
54
+ if (truncated)
55
+ lines.shift();
56
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
57
+ const line = lines[i].trim();
58
+ if (!line)
59
+ continue;
60
+ let raw;
61
+ try {
62
+ raw = JSON.parse(line);
63
+ }
64
+ catch {
65
+ continue;
66
+ }
67
+ if (raw.type !== 'user' && raw.type !== 'assistant')
68
+ continue;
69
+ const message = raw.message;
70
+ if (!message || typeof message !== 'object')
71
+ continue;
72
+ const content = message.content;
73
+ let text = '';
74
+ if (typeof content === 'string') {
75
+ text = content;
76
+ }
77
+ else if (Array.isArray(content)) {
78
+ text = content
79
+ .filter((block) => !!block && typeof block === 'object')
80
+ .filter(block => block.type === 'text')
81
+ .map(block => (typeof block.text === 'string' ? block.text : ''))
82
+ .join(' ');
83
+ }
84
+ text = stripPeerWrapper(text).replace(/\s+/g, ' ').trim();
85
+ if (!text)
86
+ continue;
87
+ const prefix = raw.type === 'assistant' ? '' : '你:';
88
+ const body = `${prefix}${text}`;
89
+ return body.length <= PREVIEW_CHARS ? body : `${body.slice(0, PREVIEW_CHARS)}…`;
90
+ }
91
+ return undefined;
92
+ }
93
+ /**
94
+ * 列出历史会话。
95
+ *
96
+ * SDK 不可用或调用失败时返回空数组——列表退化成"只有运行中的会话",
97
+ * 不影响主流程。
98
+ */
99
+ async function listHistory() {
100
+ try {
101
+ const sessions = await listClaudeSdkSessions({
102
+ limit: MAX_ITEMS,
103
+ // 排除 evolcore 自己起的无头会话,用户看的是自己开的终端会话
104
+ includeProgrammatic: false,
105
+ });
106
+ return sessions
107
+ .filter(s => typeof s.sessionId === 'string' && typeof s.lastModified === 'number')
108
+ .map(s => {
109
+ const title = s.customTitle?.trim()
110
+ || s.summary?.trim()
111
+ || (s.firstPrompt ? buildCliSessionPreview([s.firstPrompt], 'claude').title : '')
112
+ || s.sessionId.slice(0, 8);
113
+ return {
114
+ sessionId: s.sessionId,
115
+ title,
116
+ cwd: s.cwd ?? '',
117
+ lastModified: s.lastModified,
118
+ };
119
+ });
120
+ }
121
+ catch (error) {
122
+ logger.debug('[ccagent] 枚举历史会话失败:', error.message);
123
+ return [];
124
+ }
125
+ }
126
+ /**
127
+ * 列出用过的项目目录。
128
+ *
129
+ * Claude Code 本身没有「项目」这个实体,所以目录是从历史会话的 `cwd` 去重出来的:
130
+ * 用过哪些目录、每个目录里有多少会话、最近一次是什么时候。
131
+ *
132
+ * 排序按最近活动时间倒序——用户最可能选的是刚用过的那个。
133
+ */
134
+ export async function listProjectDirectories() {
135
+ const [running, history] = await Promise.all([
136
+ listClaudeSessions({ includeEvolcore: false, probe: false }),
137
+ listHistory(),
138
+ ]);
139
+ const byPath = new Map();
140
+ // 同一个会话可能在历史和运行列表里各出现一次,按 sessionId 去重
141
+ const seenSessions = new Set();
142
+ const add = (cwd, lastActive, sessionId, title) => {
143
+ const key = cwd.trim();
144
+ if (!key || seenSessions.has(sessionId))
145
+ return;
146
+ seenSessions.add(sessionId);
147
+ const existing = byPath.get(key);
148
+ if (existing) {
149
+ existing.sessionCount += 1;
150
+ if (lastActive > existing.lastActive) {
151
+ existing.lastActive = lastActive;
152
+ if (title)
153
+ existing.lastTitle = title;
154
+ }
155
+ return;
156
+ }
157
+ byPath.set(key, {
158
+ path: key,
159
+ sessionCount: 1,
160
+ lastActive,
161
+ ...(title ? { lastTitle: title } : {}),
162
+ });
163
+ };
164
+ // 历史优先:它的标题(自定义名或摘要)比运行中的自动名更有意义
165
+ for (const entry of history)
166
+ add(entry.cwd, entry.lastModified, entry.sessionId, entry.title);
167
+ for (const session of running)
168
+ add(session.cwd, session.startedAt, session.sessionId, session.name);
169
+ return [...byPath.values()].sort((a, b) => b.lastActive - a.lastActive);
170
+ }
171
+ /**
172
+ * 解析用户发来的一条消息,看它是不是在选择某个会话。
173
+ *
174
+ * 支持三种写法:
175
+ *
176
+ * - 完整 sessionId 或它的前 8 位以上前缀
177
+ * - 列表里的序号(1 based)
178
+ * - 会话显示名完全匹配
179
+ *
180
+ * @param content 用户原文
181
+ * @param lastListing 上一次展示给用户的列表,用来解析序号
182
+ */
183
+ export function resolveSessionSelection(content, lastListing) {
184
+ const text = content.trim();
185
+ if (!text || text.length > 200)
186
+ return undefined;
187
+ // 1. 纯数字 → 列表序号
188
+ if (/^\d{1,2}$/.test(text) && lastListing?.length) {
189
+ const index = Number(text) - 1;
190
+ if (index >= 0 && index < lastListing.length)
191
+ return lastListing[index];
192
+ return undefined;
193
+ }
194
+ // 2. sessionId 前缀
195
+ const normalized = text.toLowerCase();
196
+ if (/^[0-9a-f-]{8,36}$/.test(normalized) && lastListing?.length) {
197
+ const matches = lastListing.filter(item => item.sessionId.toLowerCase().startsWith(normalized));
198
+ if (matches.length === 1)
199
+ return matches[0];
200
+ if (matches.length > 1)
201
+ return 'ambiguous';
202
+ }
203
+ // 3. 显示名完全匹配
204
+ if (lastListing?.length) {
205
+ const exact = lastListing.filter(item => item.title === text);
206
+ if (exact.length === 1)
207
+ return exact[0];
208
+ if (exact.length > 1)
209
+ return 'ambiguous';
210
+ }
211
+ return undefined;
212
+ }
213
+ /**
214
+ * 解析用户消息,看他是不是在选一个项目目录(要开新会话)。
215
+ *
216
+ * 支持:
217
+ *
218
+ * - `new` / `新建` / `新会话` → 没有指定目录,回目录列表
219
+ * - `new 3` / `新建 3` → 选列表第 3 个目录
220
+ * - 直接发目录路径 → 选中它(必须存在于已知目录里,避免误开任意路径)
221
+ */
222
+ export function resolveDirectorySelection(content, directories) {
223
+ const text = content.trim();
224
+ if (!text)
225
+ return undefined;
226
+ // 「新建」类指令
227
+ const newMatch = /^(?:new|新建|新会话)(?:\s+(.+))?$/i.exec(text);
228
+ if (newMatch) {
229
+ const arg = newMatch[1]?.trim();
230
+ if (!arg)
231
+ return 'list';
232
+ // 序号
233
+ if (/^\d{1,2}$/.test(arg) && directories?.length) {
234
+ const index = Number(arg) - 1;
235
+ return index >= 0 && index < directories.length ? directories[index] : undefined;
236
+ }
237
+ // 路径
238
+ return matchDirectory(arg, directories);
239
+ }
240
+ // 用户直接发了个路径
241
+ if (/^[a-zA-Z]:[\\/]|^\//.test(text)) {
242
+ return matchDirectory(text, directories);
243
+ }
244
+ return undefined;
245
+ }
246
+ /** 按路径前缀匹配已知目录。 */
247
+ function matchDirectory(input, directories) {
248
+ if (!directories?.length)
249
+ return undefined;
250
+ const normalized = input.replace(/\//g, '\\').toLowerCase();
251
+ const exact = directories.filter(d => d.path.replace(/\//g, '\\').toLowerCase() === normalized);
252
+ if (exact.length === 1)
253
+ return exact[0];
254
+ if (exact.length > 1)
255
+ return 'ambiguous';
256
+ const prefix = directories.filter(d => d.path.replace(/\//g, '\\').toLowerCase().startsWith(normalized));
257
+ if (prefix.length === 1)
258
+ return prefix[0];
259
+ if (prefix.length > 1)
260
+ return 'ambiguous';
261
+ return undefined;
262
+ }
263
+ /**
264
+ * 查一个 sessionId 的工作目录。
265
+ *
266
+ * 运行中的会话直接给;不在跑的去历史里找;再不行看转录所在项目目录。
267
+ * 拉起终端需要这个目录,找不到就没法保证 `--resume` 能接上原上下文。
268
+ */
269
+ export async function findSessionCwd(sessionId) {
270
+ const running = await listClaudeSessions({ includeEvolcore: true, probe: false });
271
+ const hit = running.find(session => session.sessionId === sessionId);
272
+ if (hit?.cwd)
273
+ return hit.cwd;
274
+ try {
275
+ const sdk = await import('@anthropic-ai/claude-agent-sdk');
276
+ const info = await sdk.getSessionInfo(sessionId);
277
+ if (info?.cwd)
278
+ return info.cwd;
279
+ }
280
+ catch (error) {
281
+ logger.debug('[ccagent] 查询会话信息失败:', error.message);
282
+ }
283
+ return undefined;
284
+ }
285
+ /**
286
+ * 生成主会话的会话列表。
287
+ *
288
+ * 排序:运行中的在前,然后按最后活动时间倒序。
289
+ */
290
+ export async function listSessionsForMenu() {
291
+ const [running, history] = await Promise.all([
292
+ listClaudeSessions({ includeEvolcore: false, probe: true }),
293
+ listHistory(),
294
+ ]);
295
+ const byId = new Map();
296
+ // 先放历史,运行中的会覆盖同 ID 项
297
+ for (const entry of history) {
298
+ byId.set(entry.sessionId, {
299
+ sessionId: entry.sessionId,
300
+ title: entry.title,
301
+ online: false,
302
+ cwd: entry.cwd,
303
+ lastActive: entry.lastModified,
304
+ });
305
+ }
306
+ for (const session of running) {
307
+ byId.set(session.sessionId, {
308
+ sessionId: session.sessionId,
309
+ title: session.name,
310
+ online: true,
311
+ pid: session.pid,
312
+ status: session.status,
313
+ cwd: session.cwd,
314
+ lastActive: session.startedAt,
315
+ });
316
+ }
317
+ const items = [...byId.values()]
318
+ .sort((a, b) => {
319
+ if (a.online !== b.online)
320
+ return a.online ? -1 : 1;
321
+ return b.lastActive - a.lastActive;
322
+ })
323
+ .slice(0, MAX_ITEMS);
324
+ for (const item of items) {
325
+ const lastMessage = readLastMessage(item.sessionId);
326
+ if (lastMessage)
327
+ item.lastMessage = lastMessage;
328
+ }
329
+ return items;
330
+ }