evolcore 0.0.49 → 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 (250) hide show
  1. package/CHANGELOG.md +64 -1
  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 +280 -6
  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 +4 -1
  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 +29 -1
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +537 -189
  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/ecmsg-gateway.js +11 -9
  54. package/dist/cli/index.js +23 -4
  55. package/dist/cli/init.js +39 -63
  56. package/dist/cli/managed-command-guard.js +1 -0
  57. package/dist/cli/menu-client.js +32 -7
  58. package/dist/cli/pay-command.js +30 -0
  59. package/dist/cli/provider-command.js +6 -2
  60. package/dist/cli/restart-monitor.js +2 -2
  61. package/dist/cli/services-command.js +11 -9
  62. package/dist/cli/thread-command.js +78 -12
  63. package/dist/config/access-policy.js +16 -3
  64. package/dist/config/config-field-policy.js +17 -8
  65. package/dist/config/config-manager.js +86 -46
  66. package/dist/config/config-operation-service.js +22 -1
  67. package/dist/config/gateway-config.js +9 -8
  68. package/dist/config/owner-config.js +0 -16
  69. package/dist/config/peer-role-resolver.js +1 -7
  70. package/dist/config/providers-config.js +99 -16
  71. package/dist/config/providers-management.js +35 -19
  72. package/dist/config/resolved-config-op.js +1 -42
  73. package/dist/config/schema-migration.js +78 -5
  74. package/dist/config/schema-registry.js +52 -7
  75. package/dist/config-store.js +1309 -17
  76. package/dist/core/agent-application-service.js +220 -1
  77. package/dist/core/agent-ipc-registration.js +19 -2
  78. package/dist/core/agent-reload-coordinator.js +5 -0
  79. package/dist/core/agent-runtime.js +198 -54
  80. package/dist/core/auth/agent-delegation.js +14 -0
  81. package/dist/core/auth/operation-authorizer.js +16 -1
  82. package/dist/core/auth/operation-catalog.js +50 -7
  83. package/dist/core/baseagent-loader.js +30 -3
  84. package/dist/core/capability/capability-manager.js +16 -7
  85. package/dist/core/channel-runtime.js +4 -2
  86. package/dist/core/command/agent-control.js +20 -2
  87. package/dist/core/command/agent-template-menu.js +4 -3
  88. package/dist/core/command/cli-intent-parser.js +15 -0
  89. package/dist/core/command/menu-catalog.js +20 -4
  90. package/dist/core/command/menu-file-path.js +70 -0
  91. package/dist/core/command/menu-handler.js +91 -72
  92. package/dist/core/command/menu-protocol.js +5 -0
  93. package/dist/core/command/menu-query-batch.js +2 -2
  94. package/dist/core/command/private-mention-menu.js +71 -0
  95. package/dist/core/command/slash-handler.js +17 -26
  96. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  97. package/dist/core/command/topic-slash.js +7 -1
  98. package/dist/core/daemon-bootstrap.js +0 -4
  99. package/dist/core/daemon-control.js +2 -1
  100. package/dist/core/daemon-lifecycle.js +13 -5
  101. package/dist/core/evolagent-registry.js +12 -7
  102. package/dist/core/handoff/runtime.js +1 -1
  103. package/dist/core/host-snapshot.js +8 -3
  104. package/dist/core/initialization/service.js +3 -0
  105. package/dist/core/interaction-router.js +130 -0
  106. package/dist/core/ipc-registration.js +4 -0
  107. package/dist/core/memory/consolidation-context.js +2 -1
  108. package/dist/core/memory/consolidation.js +35 -64
  109. package/dist/core/message/aun-ipc-sender.js +98 -21
  110. package/dist/core/message/aun-request-registry.js +31 -0
  111. package/dist/core/message/message-bridge.js +105 -6
  112. package/dist/core/message/message-log.js +8 -0
  113. package/dist/core/message/message-queue.js +5 -3
  114. package/dist/core/message/peer-mode.js +15 -4
  115. package/dist/core/message/response-engine.js +23 -8
  116. package/dist/core/message/send-options.js +37 -3
  117. package/dist/core/message/send-routing.js +11 -7
  118. package/dist/core/model/model-catalog.js +5 -5
  119. package/dist/core/ownership/owner-resolver.js +12 -86
  120. package/dist/core/pack-auth.js +4 -0
  121. package/dist/core/permission/ec-command-parser.js +182 -58
  122. package/dist/core/permission/protected-paths.js +64 -9
  123. package/dist/core/permission/services-path-acl.js +9 -2
  124. package/dist/core/permission/tool-policy.js +21 -9
  125. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  126. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  127. package/dist/core/session/session-manager.js +47 -10
  128. package/dist/core/session/session-mapper.js +16 -0
  129. package/dist/core/skill/index-generator.js +2 -3
  130. package/dist/core/skill/switch-resolver.js +3 -0
  131. package/dist/core/thread/command-parser.js +4 -1
  132. package/dist/core/thread/ipc-operation.js +4 -2
  133. package/dist/core/thread/thread-operation.js +25 -10
  134. package/dist/core/thread/thread-service.js +294 -55
  135. package/dist/core/thread/topic-id.js +52 -2
  136. package/dist/core/thread/types.js +15 -1
  137. package/dist/eck/kit-renderer.js +2 -1
  138. package/dist/ecweb/basic-settings-service.js +5 -9
  139. package/dist/ecweb/providers-service.js +4 -2
  140. package/dist/index.js +116 -41
  141. package/dist/ipc.js +58 -2
  142. package/dist/paths.js +48 -1
  143. package/dist/pay/command.js +38 -0
  144. package/dist/pay/protocol.js +136 -0
  145. package/dist/pay/runtime.js +188 -0
  146. package/dist/pay/service.js +384 -0
  147. package/dist/pay/store.js +81 -0
  148. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  149. package/dist/services/dispatcher.js +23 -5
  150. package/dist/services/host/main.js +388 -0
  151. package/dist/services/host/protocol.js +118 -0
  152. package/dist/services/host/resident.js +310 -0
  153. package/dist/services/host-client.js +386 -0
  154. package/dist/services/host-deploy.js +180 -0
  155. package/dist/services/host-launch.js +117 -0
  156. package/dist/services/host-recycle.js +203 -0
  157. package/dist/services/host-runtime.js +802 -0
  158. package/dist/services/idempotency.js +44 -86
  159. package/dist/services/index-generator.js +4 -3
  160. package/dist/services/index.js +176 -18
  161. package/dist/services/ipc-operation.js +204 -44
  162. package/dist/services/script-runner.js +515 -83
  163. package/dist/services/validation.js +109 -4
  164. package/dist/trigger/application-service.js +6 -4
  165. package/dist/trigger/local-files.js +19 -9
  166. package/dist/trigger/scheduler.js +22 -12
  167. package/dist/trigger/script-sandbox.js +51 -20
  168. package/dist/utils/aid-bind.js +3 -0
  169. package/dist/utils/evolcore-version.js +2 -2
  170. package/dist/utils/host-info.js +73 -0
  171. package/dist/utils/logger.js +2 -2
  172. package/dist/utils/media-cache.js +190 -43
  173. package/dist/utils/restart-safety.js +14 -1
  174. package/dist/utils/system-memory.js +113 -25
  175. package/dist/utils/systemd-lifecycle.js +154 -0
  176. package/dist/utils/windows-shell-trust.js +7 -3
  177. package/kits/docs/INDEX.md +3 -2
  178. 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
  179. package/kits/docs/channels/aun.md +1 -1
  180. package/kits/docs/evolcore/INDEX.md +7 -6
  181. package/kits/docs/evolcore/agent.md +36 -1
  182. package/kits/docs/evolcore/aid.md +20 -3
  183. package/kits/docs/evolcore/config.md +1 -1
  184. package/kits/docs/evolcore/group.md +2 -1
  185. package/kits/docs/evolcore/memory-tags.md +2 -0
  186. package/kits/docs/evolcore/menu-client.md +3 -3
  187. package/kits/docs/evolcore/menu-protocol.md +7 -0
  188. package/kits/docs/evolcore/model.md +3 -0
  189. package/kits/docs/evolcore/msg.md +68 -10
  190. package/kits/docs/evolcore/pay.md +34 -0
  191. package/kits/docs/evolcore/provider.md +21 -0
  192. package/kits/docs/evolcore/services.md +46 -18
  193. package/kits/docs/evolcore/thread-chain.md +2 -0
  194. package/kits/docs/evolcore/tool-authorization.md +10 -0
  195. package/kits/rules/01-overview.md +11 -32
  196. package/kits/rules/02-navigation.md +7 -0
  197. package/kits/rules/06-channel.md +3 -3
  198. package/kits/schemas/_meta.json +38 -5
  199. package/kits/schemas/agent-config.schema.21.json +974 -0
  200. package/kits/schemas/agent-config.schema.22.json +977 -0
  201. package/kits/schemas/agent-config.schema.23.json +958 -0
  202. package/kits/schemas/daemon.schema.10.json +373 -0
  203. package/kits/schemas/daemon.schema.9.json +12 -0
  204. package/kits/schemas/defaults.schema.7.json +472 -0
  205. package/kits/schemas/providers.schema.3.json +18 -2
  206. package/kits/schemas/relation-config.schema.13.json +289 -0
  207. package/kits/skills/.switches.json +13 -1
  208. package/kits/skills/ability/SKILL.md +229 -34
  209. package/kits/skills/ability/STRUCTURE.md +333 -0
  210. package/kits/skills/ability/references/cli.md +208 -0
  211. package/kits/skills/ability/references/development.md +107 -37
  212. package/kits/skills/ability/references/management.md +106 -46
  213. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  214. package/kits/skills/agent-output-cards/SKILL.md +12 -5
  215. package/kits/skills/ec-group/SKILL.md +8 -6
  216. package/kits/skills/ec-group/TASK.md +186 -0
  217. package/kits/skills/ec-group/WORKLOG.md +180 -0
  218. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  219. package/kits/skills/ec-pay/SKILL.md +101 -0
  220. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  221. package/kits/skills/ec-provider/SKILL.md +1 -1
  222. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  223. package/kits/skills/ec-service-call/SKILL.md +135 -0
  224. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  225. package/kits/skills/ec-trigger/SKILL.md +1 -1
  226. package/kits/templates/memory-consolidation/notes.md +2 -2
  227. package/kits/templates/memory-consolidation/workflow.md +46 -0
  228. package/kits/templates/system-fragments/channel.md +13 -4
  229. package/kits/templates/system-fragments/commands.md +4 -3
  230. package/kits/templates/system-fragments/reply.md +1 -0
  231. package/kits/templates/system-fragments/session.md +1 -1
  232. package/kits/templates/system-fragments/thread.md +27 -129
  233. package/kits/templates/system-fragments/venue.md +16 -0
  234. package/package.json +4 -5
  235. package/scripts/agent-template/inspect.mjs +37 -23
  236. package/scripts/agent-template/overlay.mjs +20 -2
  237. package/scripts/agent-template/shared/common.mjs +16 -4
  238. package/scripts/agent-template/shared/team-schema.json +20 -4
  239. package/scripts/agent-template/shared/template-contract.mjs +53 -13
  240. package/scripts/agent-template/shared/template-package.mjs +90 -26
  241. package/scripts/agent-template/shared/template-runtime.mjs +111 -1
  242. package/scripts/agent-template/shared/template.mjs +65 -7
  243. package/scripts/agent-template/team-pack.mjs +89 -33
  244. package/scripts/agent-template/team-preview.mjs +249 -5
  245. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  246. package/kits/docs/evolcore/ability.md +0 -185
  247. package/kits/skills/ability/references/calling.md +0 -56
  248. package/kits/skills/ability/references/contract-checklist.md +0 -37
  249. package/kits/skills/ability/references/recovery.md +0 -27
  250. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -0,0 +1,388 @@
1
+ /**
2
+ * 服务常驻宿主程序。
3
+ *
4
+ * 设计稿:`docs/services/resident-mode.md` §三、§4.1、§五。
5
+ *
6
+ * 由 daemon 以 `node <program>/main.js` 拉起(在沙箱内),之后长期存活。
7
+ * 一个 agent 一个实例,服务该 agent 的全部服务包。
8
+ *
9
+ * ## 只做四件事
10
+ *
11
+ * 1. 从 stdin 读换行分隔的帧;
12
+ * 2. `call` 帧 → 异步 spawn 一个子进程,按 `callId` 记账,**不阻塞**接收下一帧;
13
+ * 3. 子进程结束 / 超时 → 写一条 `result` 帧;
14
+ * 4. `ping` → 立刻回 `pong`;stdin EOF → 终止全部子进程并在 5 秒内退出。
15
+ *
16
+ * ## 刻意不做的事
17
+ *
18
+ * - **不解析脚本 stdout 的语义**。末行 JSON、`[[NOOP]]`、`HANDLER_PROTOCOL` 判定全部留在
19
+ * daemon 侧(`script-runner`),与一次性路径共用一份实现。宿主只搬运原始文本。
20
+ * - **不认识 `EC_*`**。环境变量由 daemon 算好整个传下来。
21
+ * - **不做业务级重试**。失败就是失败,重试是调用方的事。
22
+ *
23
+ * ## 硬约束
24
+ *
25
+ * - **不许有同步阻塞 I/O**:一旦阻塞事件循环,保活 ping 就会排队,daemon 会把一个健康的
26
+ * 宿主判成卡死并重启(连带杀掉在途调用)。所以本文件里没有任何 `*Sync` 调用。
27
+ * - **stdout 只写帧**,任何诊断信息走 stderr。
28
+ */
29
+ import { spawn } from 'node:child_process';
30
+ import fs from 'node:fs';
31
+ import path from 'node:path';
32
+ import { CHILD_OUTPUT_LIMIT_BYTES, FrameSplitter, HOST_PROGRAM_VERSION, encodeFrame, decodeFrame, } from './protocol.js';
33
+ import { ResidentHost, RESIDENT_HARD_TIMEOUT_AFTER } from './resident.js';
34
+ /** 收到 EOF 后的自毁期限。防某个卡住的子进程把宿主拖住不退。 */
35
+ const EOF_SELF_DESTRUCT_MS = 5000;
36
+ /**
37
+ * 自省采样周期。
38
+ *
39
+ * 10 秒足够让 daemon 在「泄漏已经明显」时及时介入,又不会让长跑宿主产生可观测的
40
+ * 额外开销(一次采样是三个同步 API,微秒级)。
41
+ */
42
+ const STATS_INTERVAL_MS = 10_000;
43
+ /**
44
+ * 采样周期的运行时覆盖。
45
+ *
46
+ * 只为两件事存在:运维现场调参与自动化测试(等 10 秒一次的采样在测试里不可接受)。
47
+ * 非法值静默回落到默认——采样周期配错不该让宿主起不来。
48
+ */
49
+ function statsIntervalMs() {
50
+ const raw = Number(process.env.EVOLCORE_HOST_STATS_MS);
51
+ return Number.isFinite(raw) && raw >= 100 ? Math.min(raw, 600_000) : STATS_INTERVAL_MS;
52
+ }
53
+ /** 统计口径。 */
54
+ let callsCompleted = 0;
55
+ const inFlight = new Map();
56
+ let shuttingDown = false;
57
+ /** 形态 B 的常驻子进程池(每个 residentKey 一个进程)。 */
58
+ const resident = new ResidentHost({ log: message => logToStderr(message) });
59
+ /** 写一帧到 stdout。只在这里碰 stdout,别处一律 stderr。 */
60
+ function writeFrame(frame) {
61
+ if (shuttingDown && frame.t !== 'result')
62
+ return;
63
+ try {
64
+ process.stdout.write(encodeFrame(frame));
65
+ }
66
+ catch {
67
+ // stdout 已关闭(daemon 退出了):没什么可做的,自毁定时器会收尾。
68
+ }
69
+ }
70
+ function logToStderr(message) {
71
+ try {
72
+ process.stderr.write(`[host] ${message}\n`);
73
+ }
74
+ catch {
75
+ /* ignore */
76
+ }
77
+ }
78
+ /** 杀掉子进程。Windows 上没有进程组信号,用 kill 逐个尽力而为。 */
79
+ function killChild(child) {
80
+ try {
81
+ if (child.pid) {
82
+ child.kill('SIGKILL');
83
+ }
84
+ }
85
+ catch {
86
+ /* already gone */
87
+ }
88
+ }
89
+ /**
90
+ * 逐块累积输出,超过上限就标记并杀进程。
91
+ *
92
+ * 与 `script-runner` 的口径一致:**超限是失败,不是截断**(截断会让脚本以为成功)。
93
+ */
94
+ function accumulate(state, chunk) {
95
+ if (state.truncated)
96
+ return;
97
+ state.bytes += chunk.length;
98
+ if (state.bytes > CHILD_OUTPUT_LIMIT_BYTES) {
99
+ state.truncated = true;
100
+ killChild(state.child);
101
+ return;
102
+ }
103
+ const text = chunk.toString('utf8');
104
+ // 只保留前 1 MiB:即使超限,也要回传已收集的部分做 preview。
105
+ if (state.stdout.length < CHILD_OUTPUT_LIMIT_BYTES)
106
+ state.stdout += text;
107
+ }
108
+ function settle(callId, exitCode, spawnError) {
109
+ const state = inFlight.get(callId);
110
+ if (!state || state.settled)
111
+ return;
112
+ state.settled = true;
113
+ clearTimeout(state.timer);
114
+ inFlight.delete(callId);
115
+ const durationMs = Date.now() - state.startedAt;
116
+ callsCompleted += 1;
117
+ const frame = {
118
+ t: 'result',
119
+ callId,
120
+ outcome: 'success',
121
+ stdout: state.stdout,
122
+ stderr: state.stderr,
123
+ exitCode,
124
+ durationMs,
125
+ timedOut: state.timedOut,
126
+ };
127
+ if (spawnError) {
128
+ frame.outcome = 'error';
129
+ frame.hostError = { code: 'SCRIPT_SPAWN_ERROR', message: spawnError.message };
130
+ }
131
+ else if (state.timedOut) {
132
+ frame.outcome = 'timeout';
133
+ }
134
+ else if (state.truncated) {
135
+ frame.outcome = 'error';
136
+ frame.truncated = true;
137
+ frame.hostError = { code: 'SCRIPT_OUTPUT_LIMIT', message: `output exceeded ${CHILD_OUTPUT_LIMIT_BYTES} bytes` };
138
+ }
139
+ else if (exitCode !== 0) {
140
+ frame.outcome = 'error';
141
+ }
142
+ writeFrame(frame);
143
+ // 临时目录删除不能阻塞主流程:失败的清理只记日志(下次启动会扫残留)。
144
+ fs.rm(state.workDir, { recursive: true, force: true }, error => {
145
+ if (error)
146
+ logToStderr(`workDir cleanup failed for ${callId}: ${error.message}`);
147
+ });
148
+ }
149
+ function handleCall(frame) {
150
+ if (shuttingDown)
151
+ return;
152
+ if (frame.mode === 'resident') {
153
+ void handleResidentCall(frame);
154
+ return;
155
+ }
156
+ let child;
157
+ try {
158
+ // 每个调用一个独立临时目录,落在 daemon 给的 workDir 下(它是策略里唯一可写的路径)。
159
+ fs.mkdirSync(frame.workDir, { recursive: true });
160
+ }
161
+ catch (error) {
162
+ writeFrame({
163
+ t: 'result', callId: frame.callId, outcome: 'error',
164
+ stdout: '', stderr: '', exitCode: 0, durationMs: 0, timedOut: false,
165
+ hostError: { code: 'WORKDIR_UNAVAILABLE', message: error.message },
166
+ });
167
+ return;
168
+ }
169
+ try {
170
+ child = spawn(frame.runtime, [frame.scriptPath, ...frame.args], {
171
+ cwd: frame.cwd,
172
+ env: {
173
+ ...frame.env,
174
+ // 临时目录三件套指向本次调用自己的目录。
175
+ TMPDIR: frame.workDir, TEMP: frame.workDir, TMP: frame.workDir,
176
+ },
177
+ stdio: ['pipe', 'pipe', 'pipe'],
178
+ windowsHide: true,
179
+ shell: false,
180
+ });
181
+ }
182
+ catch (error) {
183
+ fs.rm(frame.workDir, { recursive: true, force: true }, () => { });
184
+ writeFrame({
185
+ t: 'result', callId: frame.callId, outcome: 'error',
186
+ stdout: '', stderr: '', exitCode: 0, durationMs: 0, timedOut: false,
187
+ hostError: { code: 'SCRIPT_SPAWN_ERROR', message: error.message },
188
+ });
189
+ return;
190
+ }
191
+ const state = {
192
+ child,
193
+ timer: setTimeout(() => {
194
+ state.timedOut = true;
195
+ killChild(child);
196
+ }, frame.timeoutMs),
197
+ startedAt: Date.now(),
198
+ stdout: '',
199
+ stderr: '',
200
+ bytes: 0,
201
+ truncated: false,
202
+ timedOut: false,
203
+ settled: false,
204
+ workDir: frame.workDir,
205
+ };
206
+ state.timer.unref?.();
207
+ inFlight.set(frame.callId, state);
208
+ child.stdout?.on('data', (chunk) => accumulate(state, chunk));
209
+ child.stderr?.on('data', (chunk) => {
210
+ if (state.stderr.length < CHILD_OUTPUT_LIMIT_BYTES / 4)
211
+ state.stderr += chunk.toString('utf8');
212
+ });
213
+ child.on('error', error => settle(frame.callId, -1, error));
214
+ child.on('close', code => settle(frame.callId, typeof code === 'number' ? code : -1));
215
+ // 契约 JSON 已在 daemon 侧序列化好;写失败(进程早退)由 close 兜底。
216
+ try {
217
+ child.stdin?.on('error', () => { });
218
+ child.stdin?.end(frame.stdin);
219
+ }
220
+ catch {
221
+ /* ignore */
222
+ }
223
+ }
224
+ /**
225
+ * 形态 B 的一次调用。
226
+ *
227
+ * 调用行由 daemon 拼好传下来(含 `callId` 与本次 `EC_*` 等价字段),这里只负责投递
228
+ * 与把结果映射成统一的 ResultFrame——与形态 A 共用同一套 daemon 侧判定。
229
+ */
230
+ async function handleResidentCall(frame) {
231
+ const startedAt = Date.now();
232
+ const key = frame.residentKey ?? `${frame.scriptPath}`;
233
+ try {
234
+ const result = await resident.call({
235
+ key,
236
+ runtime: frame.runtime,
237
+ scriptPath: frame.scriptPath,
238
+ args: frame.args,
239
+ env: frame.env,
240
+ cwd: frame.cwd,
241
+ workDir: frame.workDir,
242
+ line: frame.residentLine ?? '',
243
+ callId: frame.callId,
244
+ softTimeoutMs: frame.timeoutMs,
245
+ hardTimeoutAfter: frame.hardTimeoutAfter ?? RESIDENT_HARD_TIMEOUT_AFTER,
246
+ ...(frame.residentStartTimeoutMs ? { startTimeoutMs: frame.residentStartTimeoutMs } : {}),
247
+ });
248
+ const resultFrame = {
249
+ t: 'result',
250
+ callId: frame.callId,
251
+ outcome: result.outcome === 'timeout' ? 'timeout' : result.outcome,
252
+ // 形态 B 不走 stdout 文本:脚本回的就是结构化正文,宿主已经解析过。
253
+ stdout: '',
254
+ stderr: '',
255
+ exitCode: 0,
256
+ durationMs: result.durationMs,
257
+ timedOut: result.timedOut,
258
+ resident: true,
259
+ ...(result.payload !== undefined ? { data: result.payload } : {}),
260
+ // 脚本自己报的业务错误(`outcome:error` + error 字段)不是宿主故障,
261
+ // 不能塞进 `hostError`——那会让 daemon 判成「脚本没起来」。
262
+ ...(result.hostError ? { hostError: result.hostError } : {}),
263
+ ...(!result.hostError && result.error && result.outcome !== 'success'
264
+ ? { scriptError: result.error }
265
+ : {}),
266
+ };
267
+ writeFrame(resultFrame);
268
+ }
269
+ catch (error) {
270
+ writeFrame({
271
+ t: 'result', callId: frame.callId, outcome: 'error',
272
+ stdout: '', stderr: '', exitCode: 0, durationMs: Date.now() - startedAt, timedOut: false,
273
+ resident: true,
274
+ hostError: { code: 'RESIDENT_UNAVAILABLE', message: error.message },
275
+ });
276
+ }
277
+ }
278
+ function shutdown(reason) {
279
+ if (shuttingDown)
280
+ return;
281
+ shuttingDown = true;
282
+ logToStderr(`shutting down: ${reason}`);
283
+ resident.killAll('host shutting down');
284
+ for (const [callId, state] of inFlight) {
285
+ killChild(state.child);
286
+ settle(callId, -1);
287
+ }
288
+ // 自毁兜底:即使某个子进程杀不掉也不拖住进程。
289
+ const timer = setTimeout(() => process.exit(0), EOF_SELF_DESTRUCT_MS);
290
+ timer.unref?.();
291
+ process.exit(0);
292
+ }
293
+ function main() {
294
+ // 启动时清理上一次被强杀留下的临时目录(宿主可能整进程被 kill,来不及删)。
295
+ try {
296
+ const parent = process.env.EVOLCORE_HOST_WORKDIR;
297
+ if (parent) {
298
+ const callsRoot = path.join(parent, 'services-call');
299
+ if (fs.existsSync(callsRoot)) {
300
+ for (const entry of fs.readdirSync(callsRoot)) {
301
+ fs.rmSync(path.join(callsRoot, entry), { recursive: true, force: true });
302
+ }
303
+ }
304
+ }
305
+ }
306
+ catch (error) {
307
+ logToStderr(`stale workDir sweep failed: ${error.message}`);
308
+ }
309
+ writeFrame({ t: 'ready', programVersion: HOST_PROGRAM_VERSION, pid: process.pid });
310
+ /**
311
+ * 自省采样。
312
+ *
313
+ * 三项指标各有分工(设计稿 3.8.2):
314
+ * - `rss`:**粗粒度**,GC 会让它来回跳,所以判据要看「超基线 2 倍」而不是绝对值;
315
+ * - `handles`:**最灵敏**的泄漏信号——`getActiveResourcesInfo` 数的是活跃句柄,
316
+ * 没清的定时器/没关的 socket 会立刻反映出来,且不会像 rss 那样抖;
317
+ * - `idleCpuPercent`:空闲时应当接近 0;明显大于 0 说明有空转定时器或轮询。
318
+ *
319
+ * CPU 用「两次采样之间的增量 / 经过时间」,所以第一轮没有基准、跳过。
320
+ */
321
+ /**
322
+ * CPU 度量窗口。
323
+ *
324
+ * **不能拿采样间隔当窗口**:间隔短于 1 秒时,一次 GC 或一次定时器抖动就能让
325
+ * 单次读数虚高到 10%以上,把健康的空闲宿主判成"空转定时器"。
326
+ * 所以固定用不少于 1 秒的窗口,采样间隔再短也不缩窗口。
327
+ */
328
+ const CPU_WINDOW_MS = Math.max(1000, statsIntervalMs());
329
+ let lastCpu = process.cpuUsage();
330
+ let lastSampleAt = Date.now();
331
+ const statsTimer = setInterval(() => {
332
+ if (shuttingDown)
333
+ return;
334
+ const now = Date.now();
335
+ const elapsedMs = now - lastSampleAt;
336
+ // 窗口不足就不出数:宁可少报一次,也不报一个不准的数字。
337
+ if (elapsedMs < CPU_WINDOW_MS)
338
+ return;
339
+ const cpu = process.cpuUsage(lastCpu);
340
+ lastCpu = process.cpuUsage();
341
+ lastSampleAt = now;
342
+ const cpuMs = (cpu.user + cpu.system) / 1000;
343
+ writeFrame({
344
+ t: 'stats',
345
+ stats: {
346
+ uptimeMs: Math.round(process.uptime() * 1000),
347
+ rss: process.memoryUsage().rss,
348
+ handles: process.getActiveResourcesInfo().length,
349
+ idleCpuPercent: Math.round(Math.min(100, (cpuMs / elapsedMs) * 100) * 10) / 10,
350
+ inFlight: inFlight.size,
351
+ callsCompleted,
352
+ },
353
+ });
354
+ }, Math.min(statsIntervalMs(), 1000));
355
+ statsTimer.unref?.();
356
+ const splitter = new FrameSplitter();
357
+ process.stdin.setEncoding('utf8');
358
+ process.stdin.on('data', (chunk) => {
359
+ for (const line of splitter.push(chunk)) {
360
+ const frame = decodeFrame(line);
361
+ if (!frame) {
362
+ logToStderr('dropped a line that is not a frame');
363
+ continue;
364
+ }
365
+ if (frame.t === 'ping') {
366
+ // 必须同步立刻回:这是保活判据,任何排队都会被 daemon 判成卡死。
367
+ writeFrame({ t: 'pong', seq: frame.seq });
368
+ }
369
+ else if (frame.t === 'call') {
370
+ handleCall(frame);
371
+ }
372
+ else {
373
+ logToStderr(`ignored frame type ${frame.t}`);
374
+ }
375
+ }
376
+ });
377
+ process.stdin.on('end', () => shutdown('stdin EOF'));
378
+ process.stdin.on('error', () => shutdown('stdin error'));
379
+ // 进程级兜底:任何未捕获异常都不能让宿主静默消失——先回报再退,daemon 才好重启。
380
+ process.on('uncaughtException', error => {
381
+ logToStderr(`uncaughtException: ${error.stack ?? error.message}`);
382
+ shutdown('uncaughtException');
383
+ });
384
+ process.on('unhandledRejection', error => {
385
+ logToStderr(`unhandledRejection: ${String(error)}`);
386
+ });
387
+ }
388
+ main();
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 常驻宿主模式的帧协议:daemon ↔ 宿主之间**换行分隔 JSON**(JSON Lines)。
3
+ *
4
+ * 设计稿:`docs/services/resident-mode.md` §五。
5
+ *
6
+ * ## 为什么是 JSON Lines
7
+ *
8
+ * `JSON.stringify` 的出口不会产生裸换行(字符串里的 `\n` 已被转义成 `\\n`),所以
9
+ * 「一行一帧」天然无歧义,不需要长度前缀或分隔符协商。代价是任何**非帧**输出都会破坏
10
+ * 流,因此约定:**宿主 stdout 只写帧,日志一律走 stderr**。
11
+ *
12
+ * ## 分工(重要)
13
+ *
14
+ * 本协议刻意让宿主"哑":
15
+ *
16
+ * - `call` 帧里的 `stdin` 是**已经序列化好的契约 JSON 字符串**,宿主原样写进子进程 stdin,
17
+ * 不解析、不改造。`EC_*` 环境变量同理,由 daemon 算好后整个 `env` 传下来。
18
+ * 这样宿主不认识任何业务语义,宿主升级不会改变调用行为。
19
+ * - `result` 帧回传**原始 stdout/stderr 文本**,末行 JSON 解析、`[[NOOP]]` 判定、
20
+ * 1 MB 截断全部留在 daemon 侧(`script-runner`),与一次性路径共用同一份实现。
21
+ * 如果宿主也解析一遍,两条路径的判定就必然漂移。
22
+ */
23
+ /** 单帧上限。超过即判该帧非法;**不因此杀宿主**(宿主是长跑进程)。 */
24
+ export const HOST_FRAME_LIMIT_BYTES = 2 * 1024 * 1024;
25
+ /** 子进程 stdout/stderr 合计上限,与 `script-runner` 的 1 MiB 同口径。 */
26
+ export const CHILD_OUTPUT_LIMIT_BYTES = 1024 * 1024;
27
+ /** 序列化成一帧(含换行)。 */
28
+ export function encodeFrame(frame) {
29
+ return `${JSON.stringify(frame)}\n`;
30
+ }
31
+ /**
32
+ * 解析一行。
33
+ *
34
+ * 返回 `undefined` 表示**这一行不是合法帧**(空行、非 JSON、非对象、缺 `t`、`t` 不认识)。
35
+ * 调用方必须能容忍这种行:宿主可能写了半行、也可能被打上了第三方库的调试输出,
36
+ * 任何一次都**不该**判死宿主——连续多次才判协议破坏(由调用方计数)。
37
+ */
38
+ export function decodeFrame(line) {
39
+ const text = line.trim();
40
+ if (!text)
41
+ return undefined;
42
+ let value;
43
+ try {
44
+ value = JSON.parse(text);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ if (!value || typeof value !== 'object' || Array.isArray(value))
50
+ return undefined;
51
+ const record = value;
52
+ const type = record.t;
53
+ if (type !== 'ping' && type !== 'pong' && type !== 'call'
54
+ && type !== 'result' && type !== 'ready' && type !== 'log' && type !== 'stats') {
55
+ return undefined;
56
+ }
57
+ return record;
58
+ }
59
+ /**
60
+ * 增量帧切分器。
61
+ *
62
+ * 换行分隔的流式解析不能假设「一次 data 事件正好一行」:管道会任意切块。这个类维护
63
+ * 一个残buffer,只在见到 `\n` 时吐出一行。
64
+ *
65
+ * **超长行的处理**:超过 `HOST_FRAME_LIMIT_BYTES` 仍未见换行,说明对端在写一条非法
66
+ * 巨型帧——直接丢弃到下一个换行,并回一个 `undefined` + 计数,而不是无限堆内存。
67
+ */
68
+ export class FrameSplitter {
69
+ limitBytes;
70
+ buffer = '';
71
+ overflowing = false;
72
+ /** 因超长被丢弃的行数,宿主与 daemon 两侧都可以读它做告警。 */
73
+ droppedForSize = 0;
74
+ constructor(limitBytes = HOST_FRAME_LIMIT_BYTES) {
75
+ this.limitBytes = limitBytes;
76
+ }
77
+ /**
78
+ * 投喂一段文本,返回其中完整的行。
79
+ *
80
+ * 返回的数组里**只包含已确认完整的行**;末尾不完整的一段留在内部 buffer 里等下一次。
81
+ */
82
+ push(chunk) {
83
+ this.buffer += chunk;
84
+ const lines = [];
85
+ let index;
86
+ while ((index = this.buffer.indexOf('\n')) >= 0) {
87
+ const line = this.buffer.slice(0, index);
88
+ this.buffer = this.buffer.slice(index + 1);
89
+ if (this.overflowing) {
90
+ // 这一行的前半段已因超长被丢弃,整行作废。
91
+ this.overflowing = false;
92
+ continue;
93
+ }
94
+ lines.push(line);
95
+ }
96
+ if (!this.overflowing && this.buffer.length > this.limitBytes) {
97
+ this.droppedForSize += 1;
98
+ this.overflowing = true;
99
+ this.buffer = '';
100
+ }
101
+ else if (this.overflowing) {
102
+ this.buffer = '';
103
+ }
104
+ return lines;
105
+ }
106
+ /** 流结束时取出残余(无换行结尾的最后一行)。 */
107
+ flush() {
108
+ const rest = this.buffer;
109
+ this.buffer = '';
110
+ if (this.overflowing) {
111
+ this.overflowing = false;
112
+ return [];
113
+ }
114
+ return rest ? [rest] : [];
115
+ }
116
+ }
117
+ /** 宿主程序版本。部署路径用它做目录名,ready 帧用它让 daemon 判断是否需要重启。 */
118
+ export const HOST_PROGRAM_VERSION = '1';