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,310 @@
1
+ /**
2
+ * 形态 B:宿主侧管理**常驻子进程**。
3
+ *
4
+ * 设计稿:`docs/services/resident-mode.md` §4.2、§4.4。
5
+ *
6
+ * ## 与形态 A 的根本差别
7
+ *
8
+ * 形态 A 里「超时 = 杀进程」,干净利落——因为进程就是这次调用。形态 B 里一个进程服务
9
+ * 所有调用,**无法只杀掉其中一个**。所以超时必须是两层(4.4):
10
+ *
11
+ * 1. **软超时**:到点立刻回错误、作废该 `callId`。迟到结果被丢弃,不串给后来的调用;
12
+ * 2. **硬超时**:连续 N 次软超时(或子进程退出/协议破坏)→ 杀掉整个常驻进程,
13
+ * 该包所有在途调用一起判失败。
14
+ *
15
+ * 只做 1 会留下「永远吞调用的黑洞」;只做 2 会让一个偶发慢调用杀掉整个包的进程。
16
+ *
17
+ * ## 为什么由 daemon 拼调用行
18
+ *
19
+ * 常驻脚本的每帧都要带 `callId` 与本次的 `EC_*` 等价字段,而这些每次调用都不同;
20
+ * 常驻进程的环境变量在启动时就冻结了。所以调用行由 daemon 拼好整行传下来,
21
+ * 本模块只负责写进去、读回来——宿主仍然不需要理解脚本语义。
22
+ */
23
+ import { spawn } from 'node:child_process';
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { FrameSplitter } from './protocol.js';
27
+ /** 软/硬超时的缺省策略。 */
28
+ export const RESIDENT_HARD_TIMEOUT_AFTER = 3;
29
+ /** 常驻子进程启动握手超时。 */
30
+ export const RESIDENT_START_TIMEOUT_MS = 10_000;
31
+ /** 常驻子进程输出上限(按行累计的粗保护)。 */
32
+ const RESIDENT_LINE_LIMIT_BYTES = 2 * 1024 * 1024;
33
+ /**
34
+ * 常驻子进程池。
35
+ *
36
+ * 一个宿主里可以有多个常驻进程(每个 `residentKey` 一个),因为不同 handler 可能
37
+ * 是不同的脚本、不同的 runtime。
38
+ */
39
+ export class ResidentHost {
40
+ deps;
41
+ processes = new Map();
42
+ /**
43
+ * 正在启动中的进程(按 key)。
44
+ *
45
+ * **必须有这个表**:并发调用会同时走到 `ensureProcess`,第二个看到 `existing` 存在
46
+ * 但还没 `ready`,会把它当成"要重启的旧进程"杀掉——结果是两个调用一起失败,
47
+ * 日志里出现 "terminated: restarting" 紧跟 "exited before ready",极难归因。
48
+ * 正确做法是共享同一个启动 Promise。
49
+ */
50
+ starting = new Map();
51
+ constructor(deps) {
52
+ this.deps = deps;
53
+ }
54
+ /** 当前存活的常驻进程数(观测用)。 */
55
+ get size() {
56
+ return this.processes.size;
57
+ }
58
+ /** 是否有该键的存活进程。 */
59
+ has(key) {
60
+ const proc = this.processes.get(key);
61
+ return !!proc && !proc.dead;
62
+ }
63
+ /**
64
+ * 投递一次调用。
65
+ *
66
+ * 进程不存在则先拉起并等 ready。**调用行由调用方传**(已序列化,含 callId)。
67
+ */
68
+ async call(input) {
69
+ const proc = await this.ensureProcess(input);
70
+ if (proc.dead) {
71
+ return {
72
+ outcome: 'error', durationMs: 0, timedOut: false,
73
+ hostError: { code: 'RESIDENT_UNAVAILABLE', message: `resident process for ${input.key} is not alive` },
74
+ };
75
+ }
76
+ const startedAt = Date.now();
77
+ // 调用级目录:本次独有,调用结束(拿到结果 / 超时 / 进程死)即删。
78
+ // 与 `workDir` 区分——后者是进程级、跨调用稳定,常驻脚本的缓存放那里。
79
+ const callDir = path.join(input.workDir, 'call', input.callId);
80
+ try {
81
+ fs.mkdirSync(callDir, { recursive: true });
82
+ }
83
+ catch (error) {
84
+ return {
85
+ outcome: 'error', durationMs: 0, timedOut: false,
86
+ hostError: { code: 'WORKDIR_UNAVAILABLE', message: error.message },
87
+ };
88
+ }
89
+ const dropCallDir = () => {
90
+ fs.rm(callDir, { recursive: true, force: true }, () => { });
91
+ };
92
+ return await new Promise(resolve => {
93
+ const timer = setTimeout(() => {
94
+ // 软超时:作废该 callId 并立刻回错误。进程**不杀**——迟到结果会被丢弃。
95
+ if (!proc.pending.has(input.callId))
96
+ return;
97
+ proc.pending.delete(input.callId);
98
+ proc.softTimeouts += 1;
99
+ const threshold = input.hardTimeoutAfter ?? RESIDENT_HARD_TIMEOUT_AFTER;
100
+ if (proc.softTimeouts >= threshold) {
101
+ // 硬超时:进程级失败。该包所有在途调用一起判失败。
102
+ this.kill(proc.key, `soft timeouts reached ${proc.softTimeouts}`);
103
+ }
104
+ dropCallDir();
105
+ resolve({
106
+ outcome: 'timeout',
107
+ durationMs: Date.now() - startedAt,
108
+ timedOut: true,
109
+ error: { code: 'TIMEOUT', message: `resident call timed out after ${input.softTimeoutMs}ms` },
110
+ });
111
+ }, input.softTimeoutMs);
112
+ timer.unref?.();
113
+ proc.pending.set(input.callId, { resolve, timer, startedAt });
114
+ try {
115
+ proc.child.stdin.write(`${input.line}\n`);
116
+ }
117
+ catch (error) {
118
+ clearTimeout(timer);
119
+ proc.pending.delete(input.callId);
120
+ dropCallDir();
121
+ resolve({
122
+ outcome: 'error', durationMs: Date.now() - startedAt, timedOut: false,
123
+ hostError: { code: 'RESIDENT_WRITE_FAILED', message: error.message },
124
+ });
125
+ }
126
+ });
127
+ }
128
+ /** 杀掉某个常驻进程;在途调用全部判失败。 */
129
+ kill(key, reason) {
130
+ const proc = this.processes.get(key);
131
+ if (!proc)
132
+ return;
133
+ this.processes.delete(key);
134
+ this.failAll(proc, { code: 'RESIDENT_RESTARTING', message: `resident process stopped: ${reason}` }, reason);
135
+ }
136
+ /** 全部杀掉(宿主退出前调用)。 */
137
+ killAll(reason) {
138
+ for (const key of [...this.processes.keys()])
139
+ this.kill(key, reason);
140
+ }
141
+ /** 清理某个进程的临时目录(宿主退出时统一做)。 */
142
+ failAll(proc, error, reason) {
143
+ proc.dead = true;
144
+ for (const [callId, pending] of proc.pending) {
145
+ clearTimeout(pending.timer);
146
+ pending.resolve({
147
+ outcome: 'error',
148
+ durationMs: Date.now() - pending.startedAt,
149
+ timedOut: false,
150
+ hostError: error,
151
+ });
152
+ proc.pending.delete(callId);
153
+ }
154
+ try {
155
+ proc.child.kill('SIGKILL');
156
+ }
157
+ catch { /* already gone */ }
158
+ fs.rm(proc.workDir, { recursive: true, force: true }, () => { });
159
+ this.deps.log(`resident process ${proc.key} terminated: ${reason}`);
160
+ }
161
+ async ensureProcess(input) {
162
+ const existing = this.processes.get(input.key);
163
+ if (existing && !existing.dead && existing.ready)
164
+ return existing;
165
+ // 已在启动中:等同一个 Promise,不要重复拉起。
166
+ const pendingStart = this.starting.get(input.key);
167
+ if (pendingStart)
168
+ return await pendingStart;
169
+ if (existing)
170
+ this.kill(input.key, 'restarting');
171
+ const startPromise = this.spawnProcess(input);
172
+ this.starting.set(input.key, startPromise);
173
+ try {
174
+ return await startPromise;
175
+ }
176
+ finally {
177
+ // 只清自己那一条:若期间已被别处替换,别误删新的。
178
+ if (this.starting.get(input.key) === startPromise)
179
+ this.starting.delete(input.key);
180
+ }
181
+ }
182
+ /** 真正拉起并等待握手。由 `ensureProcess` 保证同 key 只有一个在跑。 */
183
+ async spawnProcess(input) {
184
+ try {
185
+ fs.mkdirSync(input.workDir, { recursive: true });
186
+ }
187
+ catch (error) {
188
+ throw new Error(`resident workDir unavailable: ${error.message}`);
189
+ }
190
+ const child = spawn(input.runtime, [input.scriptPath, ...input.args], {
191
+ cwd: input.cwd,
192
+ env: { ...input.env, TMPDIR: input.workDir, TEMP: input.workDir, TMP: input.workDir },
193
+ stdio: ['pipe', 'pipe', 'pipe'],
194
+ windowsHide: true,
195
+ shell: false,
196
+ });
197
+ const proc = {
198
+ key: input.key,
199
+ child,
200
+ splitter: new FrameSplitter(RESIDENT_LINE_LIMIT_BYTES),
201
+ ready: false,
202
+ pending: new Map(),
203
+ softTimeouts: 0,
204
+ dead: false,
205
+ workDir: input.workDir,
206
+ };
207
+ this.processes.set(input.key, proc);
208
+ const readyPromise = new Promise((resolve, reject) => {
209
+ proc.readyResolve = resolve;
210
+ proc.readyReject = reject;
211
+ });
212
+ const startTimeoutMs = input.startTimeoutMs ?? RESIDENT_START_TIMEOUT_MS;
213
+ const startTimer = setTimeout(() => {
214
+ proc.readyReject?.(new Error(`resident process did not signal ready within ${startTimeoutMs}ms`));
215
+ }, startTimeoutMs);
216
+ startTimer.unref?.();
217
+ child.stdout?.setEncoding('utf8');
218
+ child.stdout?.on('data', (chunk) => {
219
+ for (const line of proc.splitter.push(chunk))
220
+ this.onLine(proc, line);
221
+ });
222
+ child.stderr?.setEncoding('utf8');
223
+ child.stderr?.on('data', (chunk) => {
224
+ for (const line of chunk.split('\n')) {
225
+ if (line.trim())
226
+ this.deps.log(`[resident ${input.key}] ${line}`);
227
+ }
228
+ });
229
+ child.on('error', error => {
230
+ proc.readyReject?.(error);
231
+ this.kill(input.key, `spawn error: ${error.message}`);
232
+ });
233
+ child.on('close', code => {
234
+ proc.readyReject?.(new Error(`resident process exited with code ${code} before ready`));
235
+ // 进程退出 = 该键所有在途调用失败。不能各自等软超时。
236
+ this.kill(input.key, `exited with code ${code}`);
237
+ });
238
+ try {
239
+ await readyPromise;
240
+ }
241
+ finally {
242
+ clearTimeout(startTimer);
243
+ }
244
+ proc.ready = true;
245
+ return proc;
246
+ }
247
+ /**
248
+ * 处理常驻子进程回的一行。
249
+ *
250
+ * 行格式与 daemon 侧的 result 语义一致:`{callId, outcome, data|error}`。
251
+ * 解析失败只丢弃并记日志——**不判死进程**(一次脏输出不该影响整个包)。
252
+ */
253
+ onLine(proc, line) {
254
+ if (!line.trim())
255
+ return;
256
+ let frame;
257
+ try {
258
+ const parsed = JSON.parse(line);
259
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
260
+ throw new Error('not an object');
261
+ frame = parsed;
262
+ }
263
+ catch {
264
+ this.deps.log(`[resident ${proc.key}] dropped non-JSON line`);
265
+ return;
266
+ }
267
+ // 握手:常驻脚本启动完成后必须发一条 ready,否则调用会误判成超时。
268
+ if (frame.t === 'ready' && !proc.ready) {
269
+ proc.readyResolve?.();
270
+ return;
271
+ }
272
+ const callId = typeof frame.callId === 'string' ? frame.callId : undefined;
273
+ if (!callId) {
274
+ this.deps.log(`[resident ${proc.key}] dropped line without callId`);
275
+ return;
276
+ }
277
+ const pending = proc.pending.get(callId);
278
+ if (!pending) {
279
+ // 未知 callId:软超时后迟到,或脚本写错了。丢弃,绝不猜归属。
280
+ this.deps.log(`[resident ${proc.key}] dropped result for unknown callId`);
281
+ return;
282
+ }
283
+ proc.pending.delete(callId);
284
+ clearTimeout(pending.timer);
285
+ // 收到正常结果说明进程是健康的:软超时计数清零。
286
+ proc.softTimeouts = 0;
287
+ // 调用级目录随本次调用结束一起删。进程级 `workDir` 不动。
288
+ fs.rm(path.join(proc.workDir, 'call', callId), { recursive: true, force: true }, () => { });
289
+ const outcome = frame.outcome;
290
+ const durationMs = Date.now() - pending.startedAt;
291
+ if (outcome === 'success') {
292
+ pending.resolve({ outcome: 'success', payload: frame.data, durationMs, timedOut: false });
293
+ return;
294
+ }
295
+ if (outcome === 'noop') {
296
+ pending.resolve({ outcome: 'noop', payload: undefined, durationMs, timedOut: false });
297
+ return;
298
+ }
299
+ const error = frame.error && typeof frame.error === 'object' ? frame.error : {};
300
+ pending.resolve({
301
+ outcome: outcome === 'timeout' ? 'timeout' : 'error',
302
+ durationMs,
303
+ timedOut: outcome === 'timeout',
304
+ error: {
305
+ code: typeof error.code === 'string' && error.code ? error.code : 'RESIDENT_FAILED',
306
+ message: typeof error.message === 'string' ? error.message : 'resident handler reported an error',
307
+ },
308
+ });
309
+ }
310
+ }
@@ -0,0 +1,386 @@
1
+ /**
2
+ * 服务常驻宿主的 daemon 侧客户端。
3
+ *
4
+ * 设计稿:`docs/services/resident-mode.md` §三、§5.2。
5
+ *
6
+ * 职责边界(与宿主程序刻意互补):
7
+ *
8
+ * - 本模块负责 **拉起、帧收发、callId 记账、单调用超时、退出处理**;
9
+ * - 宿主负责 **spawn 子进程、按 callId 回结果**;
10
+ * - `stdin` 契约 JSON 与环境变量由调用方(`script-runner`)算好后传进来,
11
+ * 结果里的 stdout/stderr 也原样返回给调用方去解析——**本模块不解析脚本输出语义**。
12
+ *
13
+ * ## 超时分两层,不要混
14
+ *
15
+ * - **宿主侧**(`CallFrame.timeoutMs`):真正的脚本超时,到点杀子进程并回 `timeout`。
16
+ * - **daemon 侧**(`timeoutMs + DAEMON_TIMEOUT_GRACE_MS`):只是保险丝,防宿主卡死导致
17
+ * 调用永不兑现。它必须**晚于**宿主侧到点,否则两边同时动手,日志里会出现
18
+ * 「脚本超时」与「宿主超时」两条互相矛盾的记录,且宿主那条 result 会被当成迟到帧丢弃。
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ import { randomUUID } from 'node:crypto';
22
+ import { FrameSplitter, decodeFrame, encodeFrame, } from './host/protocol.js';
23
+ import { ServiceError, errorMessage } from './types.js';
24
+ /**
25
+ * daemon 侧比宿主侧多等的余量。
26
+ *
27
+ * 足够覆盖「宿主收帧 → spawn → 到点杀进程 → 写回 result 帧」这段往返。
28
+ */
29
+ export const DAEMON_TIMEOUT_GRACE_MS = 5000;
30
+ /** 宿主启动就绪上限。冷态实测约 1.9 秒(含沙箱入场 + 探针),按 10 秒预算。 */
31
+ export const HOST_STARTUP_TIMEOUT_MS = 10_000;
32
+ /** 连续多少条无法解析的行判定宿主协议破坏。 */
33
+ export const HOST_PROTOCOL_BREAK_THRESHOLD = 20;
34
+ /**
35
+ * 保活参数(设计稿 3.4)。
36
+ *
37
+ * `intervalMs` 3 秒、`timeoutMs` 5 秒、连续 2 次失败才判死。
38
+ * 单次抖动不重启:宿主是事件驱动的,偶发一次 pong 迟到通常来自 GC 或磁盘抖动。
39
+ */
40
+ export const DEFAULT_KEEPALIVE = {
41
+ intervalMs: 3000,
42
+ timeoutMs: 5000,
43
+ failureThreshold: 2,
44
+ };
45
+ /** 调度层错误码。与 `QUEUE_FULL` / `DISPATCHER_CLOSED` 同类:不进幂等缓存。 */
46
+ export const SERVICES_HOST_STARTING = 'SERVICES_HOST_STARTING';
47
+ export const SERVICES_HOST_RESTARTING = 'SERVICES_HOST_RESTARTING';
48
+ export const SERVICES_HOST_UNAVAILABLE = 'SERVICES_HOST_UNAVAILABLE';
49
+ export const SERVICES_HOST_PROTOCOL = 'SERVICES_HOST_PROTOCOL';
50
+ /**
51
+ * 一个宿主进程的句柄。
52
+ *
53
+ * 生命周期:`start()` → 若干 `call()` → `close()`。一个实例对应一个宿主进程;
54
+ * 重启(P2)由上层丢弃旧实例、新建一个完成,本类不做退避。
55
+ */
56
+ export class ServiceHostClient {
57
+ deps;
58
+ child;
59
+ pending = new Map();
60
+ splitter = new FrameSplitter();
61
+ readyResolve;
62
+ readyReject;
63
+ ready = false;
64
+ closed = false;
65
+ badLineStreak = 0;
66
+ droppedUnknownResult = 0;
67
+ droppedBadLine = 0;
68
+ keepaliveTimer;
69
+ keepaliveSeq = 0;
70
+ lastPongAt = 0;
71
+ /** 最近一次宿主自省快照。 */
72
+ lastStats;
73
+ /**
74
+ * 宿主在 `ready` 帧里回报的程序版本。
75
+ *
76
+ * 只记录、不判断——「版本不一致要不要重启」是 daemon 的策略,客户端不该越界。
77
+ * 没有它,部署了新版宿主之后旧进程会一直跑到下次崩溃,运维无从发现。
78
+ */
79
+ programVersionValue;
80
+ /** 连续未收到 pong 的次数。收到任何一帧 pong 即清零。 */
81
+ missedPongs = 0;
82
+ keepalive;
83
+ constructor(deps) {
84
+ this.deps = deps;
85
+ this.keepalive = deps.keepalive ?? { ...DEFAULT_KEEPALIVE };
86
+ }
87
+ get isReady() {
88
+ return this.ready;
89
+ }
90
+ get stats() {
91
+ return {
92
+ inFlight: this.pending.size,
93
+ droppedUnknownResult: this.droppedUnknownResult,
94
+ droppedBadLine: this.droppedBadLine,
95
+ ready: this.ready,
96
+ ...(this.lastStats ? { stats: this.lastStats } : {}),
97
+ };
98
+ }
99
+ /** 拉起宿主并等到 `ready` 帧。超时或进程早退都抛 `SERVICES_HOST_STARTING`。 */
100
+ async start() {
101
+ if (this.child)
102
+ throw new ServiceError('HOST_ALREADY_STARTED', 'host client already started');
103
+ const spawnImpl = this.deps.spawnImpl ?? spawn;
104
+ const startupTimeoutMs = this.deps.startupTimeoutMs ?? HOST_STARTUP_TIMEOUT_MS;
105
+ const child = spawnImpl(this.deps.launch.command, this.deps.launch.args, {
106
+ cwd: this.deps.launch.cwd,
107
+ env: this.deps.launch.env,
108
+ stdio: ['pipe', 'pipe', 'pipe'],
109
+ windowsHide: true,
110
+ shell: false,
111
+ });
112
+ this.child = child;
113
+ const readyPromise = new Promise((resolve, reject) => {
114
+ this.readyResolve = resolve;
115
+ this.readyReject = reject;
116
+ });
117
+ const startupTimer = setTimeout(() => {
118
+ if (this.ready)
119
+ return;
120
+ this.readyReject?.(new ServiceError(SERVICES_HOST_STARTING, `host did not become ready within ${startupTimeoutMs}ms`));
121
+ }, startupTimeoutMs);
122
+ startupTimer.unref?.();
123
+ child.stdout?.setEncoding('utf8');
124
+ child.stdout?.on('data', (chunk) => this.onStdout(chunk));
125
+ child.stderr?.setEncoding('utf8');
126
+ child.stderr?.on('data', (chunk) => {
127
+ for (const line of chunk.split('\n')) {
128
+ if (line.trim())
129
+ this.deps.onHostLog?.(line);
130
+ }
131
+ });
132
+ child.on('error', error => this.onHostGone(error));
133
+ child.on('close', (code, signal) => this.onHostGone(new ServiceError(SERVICES_HOST_RESTARTING, `host exited (code=${code} signal=${signal})`)));
134
+ try {
135
+ await readyPromise;
136
+ }
137
+ finally {
138
+ clearTimeout(startupTimer);
139
+ }
140
+ this.startKeepalive();
141
+ }
142
+ /** 最近一次收到 pong 的时间(毫秒);供 status 观测。 */
143
+ get lastPongTimestamp() {
144
+ return this.lastPongAt;
145
+ }
146
+ /** 最近一次宿主自省快照;供泄漏判据与 status 使用。 */
147
+ get hostStats() {
148
+ return this.lastStats;
149
+ }
150
+ /** 宿主回报的程序版本;未就绪时为 undefined。 */
151
+ get programVersion() {
152
+ return this.programVersionValue;
153
+ }
154
+ /**
155
+ * 保活循环。
156
+ *
157
+ * 每 `intervalMs` 发一次 ping,并检查「上一条 ping 是否超时未答」。
158
+ * 连续 `failureThreshold` 次未答 → 判卡死,走 `onHostGone`(在途调用立即失败)。
159
+ *
160
+ * **必须与调用路径并发**:宿主是事件驱动的,一个慢调用不阻塞 pong;如果这里
161
+ * 观察到 pong 迟到,说明宿主事件循环被卡住或进程已经僵死。
162
+ */
163
+ startKeepalive() {
164
+ if (this.keepaliveTimer)
165
+ return;
166
+ const { intervalMs, timeoutMs, failureThreshold } = this.keepalive;
167
+ let awaitingSince = 0;
168
+ const timer = setInterval(() => {
169
+ if (this.closed || !this.ready)
170
+ return;
171
+ const now = Date.now();
172
+ if (awaitingSince !== 0 && now - awaitingSince >= timeoutMs) {
173
+ this.missedPongs += 1;
174
+ awaitingSince = 0;
175
+ if (this.missedPongs >= failureThreshold) {
176
+ this.onHostGone(new ServiceError(SERVICES_HOST_PROTOCOL, `host missed ${this.missedPongs} consecutive keepalive replies`));
177
+ return;
178
+ }
179
+ }
180
+ if (awaitingSince === 0) {
181
+ awaitingSince = now;
182
+ this.sendPing();
183
+ }
184
+ }, intervalMs);
185
+ timer.unref?.();
186
+ this.keepaliveTimer = timer;
187
+ }
188
+ sendPing() {
189
+ const child = this.child;
190
+ if (!child?.stdin?.writable)
191
+ return;
192
+ this.keepaliveSeq += 1;
193
+ try {
194
+ child.stdin.write(encodeFrame({ t: 'ping', seq: this.keepaliveSeq }));
195
+ }
196
+ catch {
197
+ // 写失败说明管道已断:退出事件会兜底。
198
+ }
199
+ }
200
+ /** 停掉保活循环(close / 宿主已失联时调用)。 */
201
+ stopKeepalive() {
202
+ if (this.keepaliveTimer) {
203
+ clearInterval(this.keepaliveTimer);
204
+ this.keepaliveTimer = undefined;
205
+ }
206
+ }
207
+ /**
208
+ * 投递一次调用。
209
+ *
210
+ * `callId` 在这里生成——**只在本段存在**,不进回复 payload、不进脚本可见的 `data`。
211
+ * 绝不复用 `request_id`:两个不同调用方可以撞同一个值。
212
+ */
213
+ async call(input) {
214
+ if (!this.ready)
215
+ throw new ServiceError(SERVICES_HOST_STARTING, 'host is not ready');
216
+ if (this.closed)
217
+ throw new ServiceError(SERVICES_HOST_RESTARTING, 'host client is closed');
218
+ const child = this.child;
219
+ if (!child?.stdin?.writable)
220
+ throw new ServiceError(SERVICES_HOST_RESTARTING, 'host stdin is not writable');
221
+ const callId = `svc-${randomUUID()}`;
222
+ const frame = {
223
+ t: 'call',
224
+ callId,
225
+ mode: input.mode ?? 'spawn',
226
+ runtime: input.runtime,
227
+ scriptPath: input.scriptPath,
228
+ args: input.args,
229
+ stdin: input.stdin,
230
+ env: input.env,
231
+ cwd: input.cwd,
232
+ workDir: input.workDir,
233
+ timeoutMs: input.timeoutMs,
234
+ ...(input.residentKey ? { residentKey: input.residentKey } : {}),
235
+ ...(input.residentLine ? { residentLine: input.residentLine(callId, input.workDir) } : {}),
236
+ ...(input.hardTimeoutAfter !== undefined ? { hardTimeoutAfter: input.hardTimeoutAfter } : {}),
237
+ ...(input.residentStartTimeoutMs !== undefined
238
+ ? { residentStartTimeoutMs: input.residentStartTimeoutMs } : {}),
239
+ };
240
+ return await new Promise((resolve, reject) => {
241
+ const timer = setTimeout(() => {
242
+ // 保险丝跳了:宿主没在预定时间内回帧。该调用作废,迟到帧会被当成未知 callId 丢弃。
243
+ this.pending.delete(callId);
244
+ reject(new ServiceError(SERVICES_HOST_RESTARTING, `host did not answer call within ${input.timeoutMs + DAEMON_TIMEOUT_GRACE_MS}ms`));
245
+ }, input.timeoutMs + DAEMON_TIMEOUT_GRACE_MS);
246
+ timer.unref?.();
247
+ this.pending.set(callId, { resolve, reject, timer, callId });
248
+ try {
249
+ child.stdin.write(encodeFrame(frame));
250
+ }
251
+ catch (error) {
252
+ clearTimeout(timer);
253
+ this.pending.delete(callId);
254
+ reject(new ServiceError(SERVICES_HOST_RESTARTING, `failed to write call frame: ${error.message}`));
255
+ }
256
+ });
257
+ }
258
+ /** 关闭:等当前帧写完再断开 stdin,宿主收到 EOF 会自杀。 */
259
+ async close() {
260
+ if (this.closed)
261
+ return;
262
+ this.closed = true;
263
+ this.stopKeepalive();
264
+ this.failAllPending(new ServiceError(SERVICES_HOST_RESTARTING, 'host client closed'));
265
+ const child = this.child;
266
+ if (!child)
267
+ return;
268
+ const exited = child.exitCode !== null || child.signalCode !== null ? Promise.resolve() : new Promise(resolve => {
269
+ const timer = setTimeout(() => { child.kill('SIGKILL'); }, 5500);
270
+ timer.unref?.();
271
+ child.once('close', () => { clearTimeout(timer); resolve(); });
272
+ });
273
+ try {
274
+ child.stdin?.end();
275
+ }
276
+ catch {
277
+ /* ignore */
278
+ }
279
+ await exited;
280
+ }
281
+ // ── 帧处理 ──────────────────────────────────────────────────────────
282
+ onStdout(chunk) {
283
+ for (const line of this.splitter.push(chunk)) {
284
+ const frame = decodeFrame(line);
285
+ if (!frame) {
286
+ this.droppedBadLine += 1;
287
+ this.badLineStreak += 1;
288
+ // 连续不可解析说明宿主在往 stdout 打非帧内容,属于协议破坏。
289
+ if (this.badLineStreak >= HOST_PROTOCOL_BREAK_THRESHOLD) {
290
+ this.onHostGone(new ServiceError(SERVICES_HOST_PROTOCOL, `host emitted ${this.badLineStreak} consecutive malformed lines`));
291
+ }
292
+ continue;
293
+ }
294
+ this.badLineStreak = 0;
295
+ this.onFrame(frame);
296
+ }
297
+ }
298
+ onFrame(frame) {
299
+ switch (frame.t) {
300
+ case 'ready':
301
+ this.programVersionValue = typeof frame.programVersion === 'string' ? frame.programVersion : undefined;
302
+ this.ready = true;
303
+ this.readyResolve?.();
304
+ this.readyResolve = undefined;
305
+ this.readyReject = undefined;
306
+ return;
307
+ case 'pong':
308
+ this.lastPongAt = Date.now();
309
+ this.missedPongs = 0;
310
+ return;
311
+ case 'log':
312
+ this.deps.onHostLog?.(`[${frame.level}] ${frame.message}`);
313
+ return;
314
+ case 'stats':
315
+ // 只存最新的:泄漏判据看的是当前水位,历史曲线由 daemon 侧的日志/台账负责。
316
+ this.lastStats = frame.stats;
317
+ this.deps.onHostStats?.(frame.stats);
318
+ return;
319
+ case 'result': {
320
+ const pending = this.pending.get(frame.callId);
321
+ if (!pending) {
322
+ // 未知 callId:软超时后迟到的结果、或伪造帧。丢弃并计数,绝不猜归属。
323
+ this.droppedUnknownResult += 1;
324
+ return;
325
+ }
326
+ this.pending.delete(frame.callId);
327
+ clearTimeout(pending.timer);
328
+ pending.resolve({
329
+ outcome: frame.outcome,
330
+ stdout: frame.stdout,
331
+ stderr: frame.stderr,
332
+ exitCode: frame.exitCode,
333
+ durationMs: frame.durationMs,
334
+ timedOut: frame.timedOut,
335
+ truncated: frame.truncated === true,
336
+ ...(frame.hostError ? { hostError: frame.hostError } : {}),
337
+ ...(frame.data !== undefined ? { data: frame.data } : {}),
338
+ ...(frame.scriptError ? { scriptError: frame.scriptError } : {}),
339
+ ...(frame.resident ? { resident: true } : {}),
340
+ });
341
+ return;
342
+ }
343
+ default:
344
+ return;
345
+ }
346
+ }
347
+ onHostGone(error) {
348
+ this.stopKeepalive();
349
+ if (this.closed) {
350
+ this.failAllPending(error);
351
+ return;
352
+ }
353
+ this.closed = true;
354
+ this.ready = false;
355
+ if (error instanceof ServiceError) {
356
+ try {
357
+ this.deps.onHostLost?.(error);
358
+ }
359
+ catch {
360
+ // 上层回调抛错不能影响「在途调用判失败」这件必须完成的事。
361
+ }
362
+ }
363
+ // 启动阶段用原始错误:那时还没有调用方,`SERVICES_HOST_STARTING` 更有信息量。
364
+ if (!this.ready)
365
+ this.readyReject?.(error);
366
+ this.readyReject = undefined;
367
+ /**
368
+ * **在途调用一律看 `SERVICES_HOST_RESTARTING`**,不暴露具体死因。
369
+ *
370
+ * 设计稿 9:`SERVICES_HOST_*` 是调度层状态,调用方只需知道「宿主换了,可以重试」。
371
+ * 把 `PROTOCOL` / `UNAVAILABLE` 这类内部码透给对端,等于把一个运维细节变成协议
372
+ * 的一部分——以后改判据就会破坏对端。具体死因走 `onHostLost` 给 daemon 记日志。
373
+ */
374
+ const callerError = new ServiceError(SERVICES_HOST_RESTARTING, `service host is gone: ${errorMessage(error)}`);
375
+ this.failAllPending(callerError);
376
+ // 残余缓冲里的半帧必须丢弃:不能与将来的帧拼接。
377
+ this.splitter.flush();
378
+ }
379
+ failAllPending(error) {
380
+ for (const [callId, pending] of this.pending) {
381
+ clearTimeout(pending.timer);
382
+ pending.reject(error);
383
+ this.pending.delete(callId);
384
+ }
385
+ }
386
+ }