evolcore 0.0.49 → 0.0.51

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 (514) hide show
  1. package/CHANGELOG.md +103 -3
  2. package/bin/ec-build.mjs +60 -0
  3. package/bin/ecmsg.js +64 -57
  4. package/dist/ability/caller/authorization.js +21 -0
  5. package/dist/ability/caller/command.js +173 -0
  6. package/dist/ability/caller/contract.js +117 -0
  7. package/dist/ability/caller/credential-files.js +132 -0
  8. package/dist/ability/caller/daemon.js +183 -0
  9. package/dist/ability/caller/schema-view.js +157 -0
  10. package/dist/ability/caller/service.js +519 -0
  11. package/dist/ability/command-contract.js +5 -0
  12. package/dist/ability/daemon.js +5 -1
  13. package/dist/ability/interop-v1.js +156 -106
  14. package/dist/ability/management.js +1 -0
  15. package/dist/agent-template/jobs.js +79 -3
  16. package/dist/agent-template/runtime.js +459 -47
  17. package/dist/agent-template/service.js +1242 -198
  18. package/dist/agent-template/share.js +103 -0
  19. package/dist/agent-template/tool-runner.js +25 -0
  20. package/dist/agent-template/types.js +10 -2
  21. package/dist/agents/claude/availability.js +94 -0
  22. package/dist/agents/claude/capability-provider.js +154 -0
  23. package/dist/agents/claude/index.js +145 -0
  24. package/dist/agents/{claude-runner.js → claude/runner.js} +78 -166
  25. package/dist/agents/claude/session-file-adapter.js +246 -0
  26. package/dist/agents/codex/app-server-client.js +90 -10
  27. package/dist/agents/codex/availability.js +164 -0
  28. package/dist/agents/codex/capability-provider.js +138 -0
  29. package/dist/agents/codex/cli.js +38 -0
  30. package/dist/agents/codex/index.js +345 -0
  31. package/dist/agents/codex/mcp-elicitation.js +135 -0
  32. package/dist/agents/{codex-runner.js → codex/runner.js} +652 -383
  33. package/dist/agents/codex/session-file-adapter.js +834 -0
  34. package/dist/agents/dsh/availability.js +28 -0
  35. package/dist/agents/dsh/capability-provider.js +56 -0
  36. package/dist/agents/dsh/desktop-locations.ps1 +66 -0
  37. package/dist/agents/dsh/desktop-probe.cjs +37 -0
  38. package/dist/agents/dsh/index.js +98 -0
  39. package/dist/agents/dsh/installation.js +400 -0
  40. package/dist/agents/dsh/resources.js +755 -0
  41. package/dist/agents/dsh/runner.js +1183 -0
  42. package/dist/agents/dsh/runtime/README.md +243 -0
  43. package/dist/agents/dsh/runtime/authorization.js +23 -0
  44. package/dist/agents/dsh/runtime/bridge.js +837 -0
  45. package/dist/agents/dsh/runtime/config.js +271 -0
  46. package/dist/agents/dsh/runtime/entry.js +229 -0
  47. package/dist/agents/dsh/runtime/session-inspector.js +340 -0
  48. package/dist/agents/dsh/runtime/tool-policy.js +49 -0
  49. package/dist/agents/dsh/session-file-adapter.js +145 -0
  50. package/dist/agents/ecagent/index.js +215 -0
  51. package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
  52. package/dist/agents/ecagent/session-file-adapter.js +134 -0
  53. package/dist/agents/gemini/index.js +96 -0
  54. package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
  55. package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
  56. package/dist/aun/ability-device-routing.js +11 -17
  57. package/dist/aun/aid/agentmd.js +27 -1
  58. package/dist/aun/aid/control-aid.js +52 -32
  59. package/dist/aun/aid/managed-operation.js +6 -4
  60. package/dist/aun/group/invite-service.js +7 -37
  61. package/dist/aun/group/operations.js +6 -0
  62. package/dist/aun/menu/client.js +1 -1
  63. package/dist/aun/msg/history.js +1 -1
  64. package/dist/aun/msg/managed-operation.js +93 -21
  65. package/dist/aun/msg/mention-schema.js +1 -1
  66. package/dist/aun/msg/p2p.js +32 -4
  67. package/dist/aun/msg/upload.js +126 -3
  68. package/dist/aun/service-proxy.js +1 -1
  69. package/dist/aun/storage/index.js +242 -0
  70. package/dist/build-identity.json +1 -1
  71. package/dist/channels/aun.js +698 -213
  72. package/dist/channels/daemon.js +3 -2
  73. package/dist/channels/dingtalk.js +1 -1
  74. package/dist/channels/feishu.js +9 -9
  75. package/dist/channels/qqbot.js +1 -1
  76. package/dist/channels/wechat.js +2 -2
  77. package/dist/channels/wecom.js +1 -1
  78. package/dist/claude-gateway/agent-registration.js +389 -0
  79. package/dist/claude-gateway/binding.js +96 -0
  80. package/dist/claude-gateway/inbox.js +138 -0
  81. package/dist/claude-gateway/index.js +125 -0
  82. package/dist/claude-gateway/listing.js +330 -0
  83. package/dist/claude-gateway/router.js +328 -0
  84. package/dist/claude-gateway/sessions.js +128 -0
  85. package/dist/claude-gateway/terminal.js +250 -0
  86. package/dist/claude-gateway/transcript.js +272 -0
  87. package/dist/claude-gateway/types.js +14 -0
  88. package/dist/cli/ability-command.js +45 -0
  89. package/dist/cli/ability-output.js +182 -0
  90. package/dist/cli/agent-command.js +21 -2
  91. package/dist/cli/agent-create.js +197 -56
  92. package/dist/cli/agent-template.js +400 -27
  93. package/dist/cli/agent.js +105 -11
  94. package/dist/cli/aun-commands.js +237 -123
  95. package/dist/cli/bench.js +5 -2
  96. package/dist/cli/config.js +22 -6
  97. package/dist/cli/daemon-commands.js +283 -109
  98. package/dist/cli/data-command.js +1 -1
  99. package/dist/cli/debug-mode.js +9 -0
  100. package/dist/cli/directory.js +1 -2
  101. package/dist/cli/ecmsg-gateway.js +64 -26
  102. package/dist/cli/fs-command.js +67 -39
  103. package/dist/cli/index.js +45 -12
  104. package/dist/cli/init.js +161 -90
  105. package/dist/cli/managed-command-guard.js +3 -0
  106. package/dist/cli/menu-client.js +32 -7
  107. package/dist/cli/model.js +1 -1
  108. package/dist/cli/pay-command.js +30 -0
  109. package/dist/cli/provider-command.js +6 -2
  110. package/dist/cli/restart-monitor.js +4 -4
  111. package/dist/cli/services-command.js +35 -10
  112. package/dist/cli/skill-command.js +4 -4
  113. package/dist/cli/task-context.js +24 -14
  114. package/dist/cli/team-workspace-command.js +50 -52
  115. package/dist/cli/thread-command.js +81 -14
  116. package/dist/cli/trigger-command.js +47 -12
  117. package/dist/cli/watch-logs.js +2 -1
  118. package/dist/config/access-policy.js +16 -3
  119. package/dist/config/boot-log.js +3 -0
  120. package/dist/config/builtin-role-templates.js +1 -1
  121. package/dist/config/config-field-policy.js +26 -13
  122. package/dist/config/config-manager.js +113 -52
  123. package/dist/config/config-operation-service.js +22 -1
  124. package/dist/config/gateway-config.js +29 -44
  125. package/dist/config/invoke-ipc-service.js +1 -1
  126. package/dist/config/owner-config.js +5 -19
  127. package/dist/config/peer-book-store.js +2 -3
  128. package/dist/config/peer-book.js +2 -2
  129. package/dist/config/peer-role-resolver.js +3 -9
  130. package/dist/config/provider-identity-migration.js +24 -105
  131. package/dist/config/provider-ipc-service.js +13 -3
  132. package/dist/config/provider-local-sync.js +4 -1
  133. package/dist/config/provider-menu-request.js +21 -3
  134. package/dist/config/provider-templates.js +1 -1
  135. package/dist/config/providers-config.js +138 -31
  136. package/dist/config/providers-import.js +3 -3
  137. package/dist/config/providers-management.js +109 -118
  138. package/dist/config/resolved-config-op.js +1 -42
  139. package/dist/config/schema-migration.js +254 -15
  140. package/dist/config/schema-registry.js +53 -8
  141. package/dist/config-store.js +1343 -63
  142. package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -9
  143. package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
  144. package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
  145. package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +119 -25
  146. package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
  147. package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
  148. package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
  149. package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
  150. package/dist/core/auth/agent-delegation.js +15 -8
  151. package/dist/core/auth/delegation-authorization.js +28 -0
  152. package/dist/core/auth/operation-authorizer.js +20 -2
  153. package/dist/core/auth/operation-catalog.js +80 -8
  154. package/dist/core/baseagent/baseagent-availability.js +197 -0
  155. package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
  156. package/dist/core/baseagent/baseagent-config-shared.js +56 -0
  157. package/dist/core/baseagent/baseagent-identity.js +68 -0
  158. package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +89 -6
  159. package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
  160. package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
  161. package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
  162. package/dist/core/baseagent/baseagent.js +157 -0
  163. package/dist/{agents → core/baseagent}/runner-types.js +36 -4
  164. package/dist/core/capability/capability-manager.js +91 -33
  165. package/dist/core/capability/providers/claude-capability-provider.js +2 -154
  166. package/dist/core/capability/providers/codex-capability-provider.js +2 -136
  167. package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
  168. package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +21 -19
  169. package/dist/core/command/agent-control.js +80 -17
  170. package/dist/core/command/agent-template-menu.js +23 -10
  171. package/dist/core/command/agentmd-menu-request.js +19 -8
  172. package/dist/core/command/agentmd-menu.js +14 -5
  173. package/dist/core/command/cli-intent-parser.js +15 -0
  174. package/dist/core/command/command-handler.js +127 -57
  175. package/dist/core/command/context-policy-menu.js +122 -0
  176. package/dist/core/command/data-root-resolver.js +157 -20
  177. package/dist/core/command/memory-slash.js +6 -6
  178. package/dist/core/command/menu-catalog.js +95 -19
  179. package/dist/core/command/menu-file-path.js +70 -0
  180. package/dist/core/command/menu-handler.js +392 -93
  181. package/dist/core/command/menu-protocol.js +47 -8
  182. package/dist/core/command/menu-query-batch.js +9 -5
  183. package/dist/core/command/private-mention-menu.js +71 -0
  184. package/dist/core/command/provider-menu.js +7 -11
  185. package/dist/core/command/role-menu.js +1 -1
  186. package/dist/core/command/skill-slash.js +17 -5
  187. package/dist/core/command/slash-gate.js +2 -4
  188. package/dist/core/command/slash-handler.js +143 -121
  189. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  190. package/dist/core/command/team-workspace-team.js +3 -3
  191. package/dist/core/command/topic-slash.js +16 -10
  192. package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
  193. package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
  194. package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
  195. package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
  196. package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
  197. package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
  198. package/dist/core/file-integrity/store.js +1 -1
  199. package/dist/core/handoff/ipc-registration.js +3 -3
  200. package/dist/core/handoff/runtime.js +2 -2
  201. package/dist/{agents → core/inference}/request-identity.js +2 -2
  202. package/dist/core/inference/text-inference.js +4 -4
  203. package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
  204. package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
  205. package/dist/core/initialization/service.js +57 -9
  206. package/dist/core/invoke/executors/media.js +1 -1
  207. package/dist/core/invoke/executors/text.js +1 -1
  208. package/dist/core/memory/consolidation-context.js +3 -2
  209. package/dist/core/memory/consolidation-trigger.js +9 -3
  210. package/dist/core/memory/consolidation.js +39 -68
  211. package/dist/core/memory/memory-admin.js +6 -6
  212. package/dist/core/memory/memory-writer.js +1 -1
  213. package/dist/core/memory/relation-idle-monitor.js +1 -1
  214. package/dist/core/message/aun-ipc-sender.js +204 -88
  215. package/dist/core/message/aun-request-registry.js +44 -5
  216. package/dist/core/message/auto-mention-gate.js +1 -1
  217. package/dist/core/message/contact-admission.js +1 -1
  218. package/dist/core/message/im-renderer.js +19 -0
  219. package/dist/core/{interaction-router.js → message/interaction-router.js} +131 -1
  220. package/dist/core/message/items-formatter.js +5 -5
  221. package/dist/core/message/message-admission.js +1 -1
  222. package/dist/core/message/message-bridge.js +239 -59
  223. package/dist/core/message/message-log.js +8 -0
  224. package/dist/core/message/message-queue.js +88 -7
  225. package/dist/core/message/message-utils.js +1 -1
  226. package/dist/core/message/peer-mode.js +16 -5
  227. package/dist/core/message/response-engine.js +351 -152
  228. package/dist/core/message/send-options.js +44 -7
  229. package/dist/core/message/send-routing.js +55 -115
  230. package/dist/core/message/stream-idle-monitor.js +1 -1
  231. package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
  232. package/dist/core/model/catalog-service.js +29 -8
  233. package/dist/core/model/model-capabilities.js +88 -0
  234. package/dist/core/model/model-catalog.js +18 -7
  235. package/dist/core/model/model-diagnostics.js +4 -4
  236. package/dist/core/ownership/owner-resolver.js +107 -101
  237. package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -3
  238. package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
  239. package/dist/core/permission/approval-gateway.js +9 -18
  240. package/dist/core/permission/ec-command-parser.js +242 -82
  241. package/dist/core/permission/managed-file.js +234 -0
  242. package/dist/core/permission/protected-paths.js +120 -9
  243. package/dist/core/permission/sandbox-runtime.js +267 -3
  244. package/dist/core/permission/services-path-acl.js +9 -2
  245. package/dist/core/permission/session-path-grants.js +1 -1
  246. package/dist/core/permission/shell-environment.js +15 -1
  247. package/dist/core/permission/tool-policy.js +21 -9
  248. package/dist/core/plugin/plugin-lifecycle.js +442 -0
  249. package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
  250. package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
  251. package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
  252. package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
  253. package/dist/core/{background-session → session/background}/types.js +1 -1
  254. package/dist/core/session/session-file-health.js +2 -272
  255. package/dist/core/session/session-idle-monitor.js +1 -1
  256. package/dist/core/session/session-manager.js +76 -12
  257. package/dist/core/session/session-mapper.js +16 -0
  258. package/dist/core/session/session-terminal.js +185 -0
  259. package/dist/core/session/session-title.js +8 -11
  260. package/dist/core/{system-session → session/system}/memory.js +43 -9
  261. package/dist/core/{system-session → session/system}/registry.js +1 -1
  262. package/dist/core/{system-session → session/system}/types.js +1 -1
  263. package/dist/core/skill/index-generator.js +3 -3
  264. package/dist/core/skill/switch-resolver.js +3 -0
  265. package/dist/core/task/task-activity-store.js +112 -0
  266. package/dist/core/task/task-recovery-service.js +2 -2
  267. package/dist/core/thread/command-parser.js +4 -1
  268. package/dist/core/thread/ipc-operation.js +6 -4
  269. package/dist/core/thread/thread-operation.js +27 -11
  270. package/dist/core/thread/thread-route.js +5 -3
  271. package/dist/core/thread/thread-service.js +307 -58
  272. package/dist/core/thread/topic-id.js +52 -2
  273. package/dist/core/thread/types.js +15 -1
  274. package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
  275. package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
  276. package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
  277. package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
  278. package/dist/directory/{owner-directory-search.js → search.js} +50 -2
  279. package/dist/directory/{owner-directory-store.js → store.js} +2 -2
  280. package/dist/eck/kit-renderer.js +3 -2
  281. package/dist/eck/manifest-engine.js +64 -2
  282. package/dist/eck/message-renderer.js +35 -0
  283. package/dist/ecweb/basic-settings-service.js +12 -10
  284. package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
  285. package/dist/ecweb/dsh-native-service.js +413 -0
  286. package/dist/ecweb/providers-service.js +5 -3
  287. package/dist/ecweb/runtime/lifecycle.js +1 -1
  288. package/dist/ecweb/runtime/supervisor.js +1 -1
  289. package/dist/event-center/center-config.js +2 -2
  290. package/dist/event-center/dispatcher.js +1 -1
  291. package/dist/event-center/ipc-operation.js +12 -3
  292. package/dist/event-center/pack-loader.js +2 -2
  293. package/dist/event-center/registry.js +6 -6
  294. package/dist/event-center/runtime.js +2 -2
  295. package/dist/index.js +181 -77
  296. package/dist/ipc.js +161 -12
  297. package/dist/outputs/authorization.js +27 -0
  298. package/dist/outputs/events.js +10 -1
  299. package/dist/outputs/panel-cards.js +960 -0
  300. package/dist/paths.js +60 -1
  301. package/dist/pay/command.js +38 -0
  302. package/dist/pay/protocol.js +136 -0
  303. package/dist/pay/runtime.js +196 -0
  304. package/dist/pay/service.js +384 -0
  305. package/dist/pay/store.js +81 -0
  306. package/dist/response-system/engines/v1/proactive-flow.js +30 -3
  307. package/dist/services/dispatcher.js +25 -7
  308. package/dist/services/host/main.js +397 -0
  309. package/dist/services/host/protocol.js +125 -0
  310. package/dist/services/host/resident.js +347 -0
  311. package/dist/services/host-client.js +398 -0
  312. package/dist/services/host-deploy.js +180 -0
  313. package/dist/services/host-launch.js +117 -0
  314. package/dist/services/host-recycle.js +208 -0
  315. package/dist/services/host-runtime.js +841 -0
  316. package/dist/services/idempotency.js +44 -86
  317. package/dist/services/index-generator.js +4 -3
  318. package/dist/services/index.js +258 -36
  319. package/dist/services/ipc-operation.js +503 -78
  320. package/dist/services/pack-manager.js +2 -2
  321. package/dist/services/router.js +43 -3
  322. package/dist/services/script-runner.js +541 -100
  323. package/dist/services/service-payload.js +28 -1
  324. package/dist/services/validation.js +136 -5
  325. package/dist/stats/context-usage.js +110 -0
  326. package/dist/stats/model-resolver.js +103 -17
  327. package/dist/stats/query.js +5 -0
  328. package/dist/trigger/application-service.js +9 -6
  329. package/dist/trigger/authorization.js +36 -33
  330. package/dist/trigger/ipc-service.js +4 -4
  331. package/dist/trigger/local-files.js +8 -166
  332. package/dist/trigger/manager.js +2 -2
  333. package/dist/trigger/parser.js +48 -0
  334. package/dist/trigger/scheduler.js +35 -13
  335. package/dist/trigger/script-executor.js +21 -0
  336. package/dist/trigger/script-sandbox.js +77 -232
  337. package/dist/trigger/system-definitions.js +25 -0
  338. package/dist/trigger/validation.js +1 -1
  339. package/dist/utils/aid-bind.js +3 -0
  340. package/dist/utils/atomic-write.js +88 -1
  341. package/dist/utils/cross-platform.js +4 -42
  342. package/dist/utils/error-dict.json +22 -1
  343. package/dist/utils/error-utils.js +193 -6
  344. package/dist/utils/evolcore-version.js +2 -2
  345. package/dist/utils/host-info.js +74 -1
  346. package/dist/utils/logger.js +5 -3
  347. package/dist/utils/media-cache.js +284 -42
  348. package/dist/utils/restart-safety.js +14 -1
  349. package/dist/utils/startup-trace.js +20 -4
  350. package/dist/utils/system-memory.js +113 -25
  351. package/dist/utils/systemd-lifecycle.js +154 -0
  352. package/dist/utils/welcome.js +64 -20
  353. package/dist/utils/windows-shell-trust.js +7 -3
  354. package/ecagent/README.md +35 -0
  355. package/ecagent/dist/agent-loop.js +80 -30
  356. package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
  357. package/ecagent/dist/harness/env/nodejs.js +49 -20
  358. package/ecagent/dist/harness/messages.js +3 -2
  359. package/ecagent/dist/harness/types.d.ts +1 -0
  360. package/ecagent/dist/runtime/types.d.ts +2 -0
  361. package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
  362. package/ecagent/dist/runtime/utils/validation.js +42 -0
  363. package/ecagent/dist/types.d.ts +2 -0
  364. package/kits/docs/INDEX.md +3 -2
  365. 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
  366. package/kits/docs/channels/aun.md +1 -1
  367. package/kits/docs/channels/feishu.md +1 -1
  368. package/kits/docs/evolcore/INDEX.md +13 -9
  369. package/kits/docs/evolcore/agent-create.md +2 -0
  370. package/kits/docs/evolcore/agent.md +133 -11
  371. package/kits/docs/evolcore/aid.md +39 -6
  372. package/kits/docs/evolcore/config.md +95 -1
  373. package/kits/docs/evolcore/ctl.md +2 -1
  374. package/kits/docs/evolcore/ec-capabilities.md +7 -10
  375. package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
  376. package/kits/docs/evolcore/event.md +1 -1
  377. package/kits/docs/evolcore/fs.md +49 -3
  378. package/kits/docs/evolcore/group.md +5 -4
  379. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  380. package/kits/docs/evolcore/memory-tags.md +2 -0
  381. package/kits/docs/evolcore/menu-client.md +3 -3
  382. package/kits/docs/evolcore/menu-protocol.md +31 -2
  383. package/kits/docs/evolcore/model.md +12 -1
  384. package/kits/docs/evolcore/msg.md +96 -36
  385. package/kits/docs/evolcore/pay.md +22 -0
  386. package/kits/docs/evolcore/plugin.md +74 -0
  387. package/kits/docs/evolcore/provider.md +29 -2
  388. package/kits/docs/evolcore/rpc.md +2 -2
  389. package/kits/docs/evolcore/services.md +46 -18
  390. package/kits/docs/evolcore/skill.md +17 -1
  391. package/kits/docs/evolcore/stats.md +5 -0
  392. package/kits/docs/evolcore/storage.md +22 -0
  393. package/kits/docs/evolcore/thread-chain.md +20 -9
  394. package/kits/docs/evolcore/tool-authorization.md +14 -0
  395. package/kits/docs/evolcore/trigger.md +89 -13
  396. package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
  397. package/kits/docs/venues/feishu-group.md +3 -2
  398. package/kits/docs/venues/feishu-private.md +3 -2
  399. package/kits/rules/01-overview.md +11 -32
  400. package/kits/rules/02-navigation.md +20 -6
  401. package/kits/rules/06-channel.md +20 -4
  402. package/kits/schemas/_meta.json +42 -5
  403. package/kits/schemas/agent-config.schema.21.json +974 -0
  404. package/kits/schemas/agent-config.schema.22.json +977 -0
  405. package/kits/schemas/agent-config.schema.23.json +974 -0
  406. package/kits/schemas/agent-config.schema.24.json +986 -0
  407. package/kits/schemas/agent-config.schema.25.json +986 -0
  408. package/kits/schemas/daemon.schema.10.json +373 -0
  409. package/kits/schemas/daemon.schema.11.json +487 -0
  410. package/kits/schemas/daemon.schema.12.json +505 -0
  411. package/kits/schemas/daemon.schema.9.json +12 -0
  412. package/kits/schemas/defaults.schema.7.json +472 -0
  413. package/kits/schemas/defaults.schema.8.json +484 -0
  414. package/kits/schemas/providers.schema.1.json +1 -1
  415. package/kits/schemas/providers.schema.2.json +1 -1
  416. package/kits/schemas/providers.schema.3.json +26 -4
  417. package/kits/schemas/relation-config.schema.13.json +289 -0
  418. package/kits/skills/.switches.json +17 -1
  419. package/kits/skills/ability/SKILL.md +395 -33
  420. package/kits/skills/ability/STRUCTURE.md +338 -0
  421. package/kits/skills/ability/references/cli.md +208 -0
  422. package/kits/skills/ability/references/development.md +107 -37
  423. package/kits/skills/ability/references/management.md +106 -46
  424. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  425. package/kits/skills/agent-output-cards/SKILL.md +80 -37
  426. package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
  427. package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
  428. package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
  429. package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
  430. package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
  431. package/kits/skills/agent-output-cards/examples/surface.html +8 -0
  432. package/kits/skills/agent-template-project/SKILL.md +51 -0
  433. package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
  434. package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
  435. package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
  436. package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
  437. package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
  438. package/kits/skills/ec-group/SKILL.md +8 -6
  439. package/kits/skills/ec-group/TASK.md +186 -0
  440. package/kits/skills/ec-group/WORKLOG.md +180 -0
  441. package/kits/skills/ec-group-collaboration/SKILL.md +5 -5
  442. package/kits/skills/ec-identity/SKILL.md +9 -6
  443. package/kits/skills/ec-pay/SKILL.md +223 -0
  444. package/kits/skills/ec-provider/SKILL.md +6 -6
  445. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  446. package/kits/skills/ec-service-call/SKILL.md +138 -0
  447. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  448. package/kits/skills/ec-skill/SKILL.md +25 -9
  449. package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
  450. package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
  451. package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
  452. package/kits/skills/ec-trigger/SKILL.md +3 -3
  453. package/kits/skills/personal-assistant/SKILL.md +22 -22
  454. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
  455. package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
  456. package/kits/skills/thread-ops/SKILL.md +19 -9
  457. package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
  458. package/kits/skills/wechat-article-reader/SKILL.md +2 -2
  459. package/kits/templates/memory-consolidation/notes.md +2 -2
  460. package/kits/templates/memory-consolidation/workflow.md +46 -0
  461. package/kits/templates/system-fragments/channel.md +13 -4
  462. package/kits/templates/system-fragments/commands.md +5 -4
  463. package/kits/templates/system-fragments/personal-assistant.md +2 -2
  464. package/kits/templates/system-fragments/reply.md +15 -9
  465. package/kits/templates/system-fragments/session.md +2 -2
  466. package/kits/templates/system-fragments/thread.md +30 -127
  467. package/kits/templates/system-fragments/venue.md +16 -0
  468. package/package.json +7 -7
  469. package/scripts/agent-template/index.mjs +7 -1
  470. package/scripts/agent-template/inspect.mjs +99 -39
  471. package/scripts/agent-template/overlay.mjs +126 -2
  472. package/scripts/agent-template/shared/common.mjs +49 -5
  473. package/scripts/agent-template/shared/plan.mjs +4 -2
  474. package/scripts/agent-template/shared/service-packs.mjs +104 -0
  475. package/scripts/agent-template/shared/team-schema.json +468 -39
  476. package/scripts/agent-template/shared/template-contract.mjs +93 -51
  477. package/scripts/agent-template/shared/template-package.mjs +225 -44
  478. package/scripts/agent-template/shared/template-runtime.mjs +137 -15
  479. package/scripts/agent-template/shared/template.mjs +31 -8
  480. package/scripts/agent-template/team-pack.mjs +528 -56
  481. package/scripts/agent-template/team-preview.mjs +102 -9
  482. package/scripts/aid-batch/identity-batch.mjs +1 -1
  483. package/dist/agents/baseagent-availability.js +0 -152
  484. package/dist/agents/baseagent.js +0 -750
  485. package/dist/agents/codex/catalog.js +0 -80
  486. package/dist/agents/ecagent-plugin-lazy.js +0 -41
  487. package/dist/agents/tool-time-context.js +0 -55
  488. package/dist/core/legacy-rename.js +0 -41
  489. package/dist/core/plugin-lifecycle.js +0 -137
  490. package/dist/core/rate-window.js +0 -53
  491. package/dist/core/runner-reload-transaction.js +0 -60
  492. package/dist/core/runtime-lock.js +0 -90
  493. package/dist/core/soul.js +0 -66
  494. package/dist/core/system-session/grants.js +0 -40
  495. package/dist/directory/owner-directory-agentmd-sync.js +0 -89
  496. package/dist/directory/owner-directory-request-operation.js +0 -79
  497. package/dist/directory/owner-directory-text.js +0 -60
  498. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  499. package/kits/docs/evolcore/ability.md +0 -185
  500. package/kits/skills/ability/references/calling.md +0 -56
  501. package/kits/skills/ability/references/contract-checklist.md +0 -37
  502. package/kits/skills/ability/references/recovery.md +0 -27
  503. /package/dist/{core/capability/providers/gemini-capability-provider.js → agents/gemini/capability-provider.js} +0 -0
  504. /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
  505. /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
  506. /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
  507. /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
  508. /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
  509. /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
  510. /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
  511. /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
  512. /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
  513. /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
  514. /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
@@ -0,0 +1,841 @@
1
+ /**
2
+ * 宿主运行时:一个 agent 一个实例,负责把「部署 → 沙箱启动 → 脚本暂存 → 调用」串起来。
3
+ *
4
+ * 设计稿:`docs/services/resident-mode.md` §3.1、§3.2、§六。
5
+ *
6
+ * ## 为什么脚本也要暂存
7
+ *
8
+ * 沙箱身份对 `agents/<aid>/services` 整棵树是 EPERM(`agents/<aid>` 根的继承
9
+ * `DENY(R)`)。一次性模式下 daemon 每次把脚本复制到运行目录再 spawn;宿主模式下
10
+ * 宿主自己 spawn 子进程,所以**脚本必须提前复制到宿主可读的根**
11
+ * (`<runtimeRoot>/host/packs/<packId>/`),并由策略授 read(`extraReadRoots`)。
12
+ *
13
+ * 一个根覆盖全部包:策略条目数不随包数增长(Windows 侧有 20k 字符命令行上限)。
14
+ *
15
+ * ## 生命周期
16
+ *
17
+ * 懒启动:第一次调用才 `start()`。关闭:`close()` 断开 stdin,宿主收到 EOF 自杀。
18
+ * 重启退避、保活、自愈属于 P2/P3,本类只保证「启动一次、用到底、能关干净」。
19
+ */
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { deployHostProgram } from './host-deploy.js';
23
+ import { ServiceHostClient, SERVICES_HOST_STARTING } from './host-client.js';
24
+ import { HostRecycleController } from './host-recycle.js';
25
+ import { HOST_PROGRAM_VERSION } from './host/protocol.js';
26
+ import { buildHostLaunch } from './host-launch.js';
27
+ import { resolveRuntimePermissionMode } from '../core/role/runtime-policy.js';
28
+ import { runPrepareWithDeadline } from '../trigger/script-sandbox.js';
29
+ import { SCRIPTS_DIR } from './pack-manager.js';
30
+ import { sha256 } from '../trigger/validation.js';
31
+ import { preserveNodeModuleType, readScriptSnapshot, SNAPSHOT_SKIP_TOP_ENTRIES, stageScriptSnapshot, } from '../trigger/script-sandbox.js';
32
+ import { resolveRuntimeExecutable, inferRuntime } from './script-runner.js';
33
+ import { errorMessage, ServiceError } from './types.js';
34
+ /**
35
+ * 计划外重启的退避参数(设计稿 3.4)。
36
+ *
37
+ * - 间隔 1s 起、每次 ×2、上限 30s;
38
+ * - 连续稳定 60s 后复位到 1s(否则一次抖动之后永远停在 30s);
39
+ * - 15 分钟内重启 3 次为预算,超出转降级、不再无脑重启。
40
+ *
41
+ * 与 `src/config/daemon-services.ts` 的托管服务实例同口径(3 次 / 15 分钟),
42
+ * 但那套是「本地服务进程」,这里是「服务宿主」,语义相近、数值独立。
43
+ */
44
+ export const HOST_RESTART_BACKOFF_INITIAL_MS = 1000;
45
+ export const HOST_RESTART_BACKOFF_MAX_MS = 30_000;
46
+ export const HOST_RESTART_BACKOFF_FACTOR = 2;
47
+ export const HOST_RESTART_STABLE_RESET_MS = 60_000;
48
+ export const HOST_RESTART_BUDGET_ATTEMPTS = 3;
49
+ export const HOST_RESTART_BUDGET_WINDOW_MS = 15 * 60_000;
50
+ /**
51
+ * 空闲回收阈值(设计稿 3.8.3)。
52
+ *
53
+ * **与「自愈重启的空闲窗口」是两件事**,别看混:
54
+ *
55
+ * - 1 小时 = 进程销毁,下次调用重新付沙箱税;
56
+ * - 5 分钟(P3-3)= 只是等安静时刻把进程**换掉**,进程一直在,不付沙箱税。
57
+ *
58
+ * 阈值取 1 小时而不是 5 分钟,是为了让**稀疏流量**(比如每 6 分钟一次的定时调用)
59
+ * 不必每调用都付一次约 1 秒的沙箱入场税——那会把常驻模式的收益吃光。
60
+ */
61
+ export const HOST_IDLE_EXIT_MS = 60 * 60_000;
62
+ export const DEFAULT_RESTART_POLICY = {
63
+ initialMs: HOST_RESTART_BACKOFF_INITIAL_MS,
64
+ maxMs: HOST_RESTART_BACKOFF_MAX_MS,
65
+ factor: HOST_RESTART_BACKOFF_FACTOR,
66
+ stableResetMs: HOST_RESTART_STABLE_RESET_MS,
67
+ budgetAttempts: HOST_RESTART_BUDGET_ATTEMPTS,
68
+ budgetWindowMs: HOST_RESTART_BUDGET_WINDOW_MS,
69
+ };
70
+ /**
71
+ * 计划外重启的退避与预算。
72
+ *
73
+ * 抽成独立类而不是散在 `ServiceHostRuntime` 里,有两个理由:
74
+ *
75
+ * 1. **可测**:退避复位、预算窗口、降级三者互相牵连,单独测它们不需要真的起宿主;
76
+ * 2. **可读**:宿主运行时已经承担了部署/暂存/启动三件事,再塞时间逻辑就没人看得懂。
77
+ *
78
+ * 时间不自己取,由调用方传入(`nowMs`),这样测试不必等真实秒数。
79
+ */
80
+ export class HostRestartController {
81
+ policy;
82
+ backoffMs;
83
+ lastStartedAt = 0;
84
+ stamps = [];
85
+ degradedReason;
86
+ constructor(policy = DEFAULT_RESTART_POLICY) {
87
+ this.policy = policy;
88
+ this.backoffMs = policy.initialMs;
89
+ }
90
+ get degraded() {
91
+ return this.degradedReason;
92
+ }
93
+ get currentBackoffMs() {
94
+ return this.backoffMs;
95
+ }
96
+ /** 宿主成功启动时调用:记录起点,供「稳定复位」判据使用。 */
97
+ markStarted(nowMs) {
98
+ this.lastStartedAt = nowMs;
99
+ }
100
+ /**
101
+ * 宿主丢失时调用,返回「等待多少毫秒后重启」。
102
+ *
103
+ * 返回 `undefined` 表示**不要重启**:要么已降级(超预算),要么调用方已关闭。
104
+ * 降级后不会再恢复——恢复要人工介入(重载配置 / 重启宿主进程)。
105
+ */
106
+ onLost(nowMs, reason) {
107
+ if (this.degradedReason)
108
+ return undefined;
109
+ // 稳定复位:上次宿主活过了复位阈值,说明抖动已过去,退避从头开始。
110
+ if (this.lastStartedAt > 0 && nowMs - this.lastStartedAt >= this.policy.stableResetMs) {
111
+ this.backoffMs = this.policy.initialMs;
112
+ }
113
+ // 预算窗口:只统计窗口内的重启。
114
+ while (this.stamps.length > 0 && nowMs - this.stamps[0] > this.policy.budgetWindowMs) {
115
+ this.stamps.shift();
116
+ }
117
+ if (this.stamps.length >= this.policy.budgetAttempts) {
118
+ this.degradedReason = `${this.stamps.length} restarts within ${Math.round(this.policy.budgetWindowMs / 60000)}min (last: ${reason})`;
119
+ return undefined;
120
+ }
121
+ this.stamps.push(nowMs);
122
+ const delay = this.backoffMs;
123
+ this.backoffMs = Math.min(this.policy.maxMs, Math.round(this.backoffMs * this.policy.factor));
124
+ return delay;
125
+ }
126
+ }
127
+ export class ServiceHostRuntime {
128
+ deps;
129
+ activeCalls = 0;
130
+ policyKey;
131
+ sandboxAbsent;
132
+ cleanupHost;
133
+ client;
134
+ starting;
135
+ staged = new Map();
136
+ closed = false;
137
+ restarts;
138
+ restartTimer;
139
+ idleTimer;
140
+ idleExitMs;
141
+ recycle;
142
+ /** 最近一次自省快照。 */
143
+ latestStats;
144
+ /** 最近一次调用结束的时间,用于算「连续空闲多久」。 */
145
+ lastCallEndedAt = 0;
146
+ /** 计划内重启的校验定时器。 */
147
+ recycleTimer;
148
+ /** 计划内重启次数(观测)。 */
149
+ recycleCount = 0;
150
+ /** 因空闲而退出的次数(观测用)。 */
151
+ idleExits = 0;
152
+ /** 关闸时因有在途调用没能立刻收进程,等最后一次调用结束再收。 */
153
+ retirePending = false;
154
+ constructor(deps) {
155
+ this.deps = deps;
156
+ this.restarts = new HostRestartController({ ...DEFAULT_RESTART_POLICY, ...(deps.restartPolicy ?? {}) });
157
+ this.idleExitMs = deps.idleExitMs ?? HOST_IDLE_EXIT_MS;
158
+ this.recycle = new HostRecycleController(deps.recyclePolicy ?? {});
159
+ }
160
+ /** 是否已降级(超重启预算)。 */
161
+ get degraded() {
162
+ return this.restarts.degraded;
163
+ }
164
+ /** 当前退避等待(观测用)。 */
165
+ get currentBackoffMs() {
166
+ return this.restarts.currentBackoffMs;
167
+ }
168
+ /** 是否已经起过宿主(供 status 观测)。 */
169
+ get running() {
170
+ return this.client?.isReady === true;
171
+ }
172
+ /** 当前宿主客户端(未启动时 undefined)。 */
173
+ get currentClient() {
174
+ return this.client;
175
+ }
176
+ async run(input) {
177
+ this.activeCalls++;
178
+ try {
179
+ return await this.runCurrent(input);
180
+ }
181
+ finally {
182
+ this.activeCalls--;
183
+ if (this.retirePending && this.activeCalls === 0)
184
+ await this.retireIfIdle();
185
+ }
186
+ }
187
+ async runCurrent(input) {
188
+ if (this.closed)
189
+ throw new ServiceError(SERVICES_HOST_STARTING, 'host runtime is closed');
190
+ const degraded = this.restarts.degraded;
191
+ if (degraded) {
192
+ throw new ServiceError('SERVICES_HOST_UNAVAILABLE', `service host is degraded: ${degraded}`);
193
+ }
194
+ await this.ensureStarted(input.role);
195
+ if (this.closed)
196
+ throw new ServiceError('SERVICES_HOST_RESTARTING', 'host closed during startup');
197
+ if (input.deadlineAt !== undefined && Date.now() >= input.deadlineAt) {
198
+ throw new ServiceError('SERVICE_DEADLINE_EXCEEDED', 'request expired during host startup');
199
+ }
200
+ const client = this.client;
201
+ if (!client)
202
+ throw new ServiceError(SERVICES_HOST_STARTING, 'host client unavailable');
203
+ const runtime = input.handler.runtime ?? inferRuntime(input.handler.script);
204
+ const executable = resolveRuntimeExecutable(runtime);
205
+ const staged = this.stagedScript(input.pack, input.handler, executable);
206
+ const scriptPath = staged.scriptPath;
207
+ // 有调用就取消空闲倒计时:1 小时的判据是「连续无调用」,不是「累计无调用」。
208
+ this.cancelIdleExit();
209
+ if (this.recycleTimer) {
210
+ clearInterval(this.recycleTimer);
211
+ this.recycleTimer = undefined;
212
+ }
213
+ const resident = input.handler.mode === 'resident';
214
+ // 常驻进程按「包 + 脚本」隔离:同一包的同一脚本共用一个进程,
215
+ // 不同脚本各一个——它们可能是不同 runtime、不同状态。
216
+ const residentKey = `${input.pack.id}:${input.handler.script}`;
217
+ /**
218
+ * 常驻模式下临时目录必须**按常驻进程**(而不是按调用)分配。
219
+ *
220
+ * 原因:常驻子进程的 `TMPDIR` 在启动时冻结成这个目录。若每次调用换一个新目录,
221
+ * 那么第一次调用结束后它就被删了,而后续调用里进程的 `TMPDIR` 仍指向那个不存在的
222
+ * 路径——脚本写临时文件会 ENOENT,症状还很难归因。
223
+ */
224
+ const workDir = resident
225
+ ? path.join(this.requireRuntimeRoot(), 'host', 'work', input.pack.id, `resident-${sanitizeKey(residentKey)}`)
226
+ : path.join(this.requireRuntimeRoot(), 'host', 'work', input.pack.id, `call-${Date.now()}-${Math.random().toString(36).slice(2)}`);
227
+ try {
228
+ const result = await client.call({
229
+ runtime: executable,
230
+ scriptPath,
231
+ args: input.handler.args ?? [],
232
+ stdin: input.stdin,
233
+ // 与一次性沙箱路径同口径:真实包目录在沙箱里不可读(services/ 是 EPERM),
234
+ // EC_PACK_DIR 必须指向快照镜像,否则脚本按它拼出来的路径必然打不开。
235
+ env: { ...input.env, EC_PACK_DIR: staged.rootDir },
236
+ // cwd 沿用一次性路径的口径:沙箱下是 agent 工程目录。
237
+ cwd: this.deps.getProjectPath() ?? input.pack.dir,
238
+ workDir,
239
+ timeoutMs: resident
240
+ ? (input.handler.resident?.softTimeoutMs ?? input.timeoutMs)
241
+ : input.timeoutMs,
242
+ ...(resident && input.residentLine
243
+ ? {
244
+ mode: 'resident',
245
+ residentKey,
246
+ residentLine: input.residentLine,
247
+ ...(input.handler.resident?.hardTimeoutAfter !== undefined
248
+ ? { hardTimeoutAfter: input.handler.resident.hardTimeoutAfter }
249
+ : {}),
250
+ ...(input.handler.resident?.startTimeoutMs !== undefined
251
+ ? { residentStartTimeoutMs: input.handler.resident.startTimeoutMs }
252
+ : {}),
253
+ }
254
+ : {}),
255
+ });
256
+ return {
257
+ outcome: result.outcome,
258
+ ...(this.sandboxAbsent ? { sandboxAbsent: this.sandboxAbsent } : {}),
259
+ stdout: result.stdout,
260
+ stderr: result.stderr,
261
+ exitCode: result.exitCode,
262
+ timedOut: result.timedOut,
263
+ truncated: result.truncated,
264
+ ...(result.hostError ? { hostError: result.hostError } : {}),
265
+ ...(result.data !== undefined ? { data: result.data } : {}),
266
+ ...(result.scriptError ? { scriptError: result.scriptError } : {}),
267
+ ...(result.resident ? { resident: true } : {}),
268
+ };
269
+ }
270
+ finally {
271
+ // 宿主也删一次;这里再删是防宿主被强杀后残留(幂等)。
272
+ // **常驻模式不删**:那是常驻进程的 TMPDIR,跨调用复用,随进程退出一起清。
273
+ if (!resident) {
274
+ fs.rm(workDir, { recursive: true, force: true }, () => { });
275
+ }
276
+ this.lastCallEndedAt = Date.now();
277
+ // 关闸发生在调用途中的情况:retireIfIdle 当时拒绝收进程,这里补一刀。
278
+ // 收进程时不再排空闲定时器——否则 1 小时后那个定时器还会去 stopHost 一个
279
+ // 已经没了的 client,并给 idleExits 记一次假退出。
280
+ if (this.retirePending && (this.client?.stats.inFlight ?? 0) === 0) {
281
+ void this.retireIfIdle();
282
+ }
283
+ else {
284
+ this.scheduleIdleExit();
285
+ }
286
+ this.checkRecycle();
287
+ }
288
+ }
289
+ /**
290
+ * 自省快照到达时推进计划内重启判据。
291
+ *
292
+ * 采样由宿主自己上报(10 秒一次),所以这里不需要额外定时器去"读"宿主;
293
+ * 但两次采样之间可能发生空闲→繁忙的转换,所以调用结束时也会 `checkRecycle()`。
294
+ */
295
+ onHostStats(stats) {
296
+ this.latestStats = stats;
297
+ this.recycle.seedBaseline(toLeakSnapshot(stats));
298
+ this.checkRecycle();
299
+ }
300
+ /**
301
+ * 推进一次计划内重启判定。
302
+ *
303
+ * 判定分两层(设计稿 3.8.2):间隔/泄漏信号只负责"置位",真正重启要等连续空闲
304
+ * `idleWindowMs`。这里每来一次采样或每次调用结束都会被调用,所以判定足够及时。
305
+ */
306
+ checkRecycle() {
307
+ if (this.closed || !this.latestStats || this.restartTimer || this.starting)
308
+ return;
309
+ const now = Date.now();
310
+ const idleForMs = Math.max(0, now - this.lastCallEndedAt);
311
+ const decision = this.recycle.onTick(now, toLeakSnapshot(this.latestStats), idleForMs);
312
+ if (decision.action === 'pending') {
313
+ this.ensureRecycleTimer();
314
+ return;
315
+ }
316
+ if (decision.action !== 'recycle')
317
+ return;
318
+ this.recycleCount += 1;
319
+ this.deps.onHostRecycled?.(decision.reason);
320
+ // 计划内重启是**优雅**的:只收宿主,不置 closed,下次调用会懒启动新的。
321
+ void this.stopHost();
322
+ }
323
+ /**
324
+ * 置位后还没到空闲窗口时需要持续复查。
325
+ *
326
+ * 不能只靠「调用结束」触发:如果宿主此后完全空闲,就再也不会有人调 `checkRecycle`,
327
+ * 重启会永远等不到执行——这正是"该换了却一直不换"的隐蔽形态。
328
+ */
329
+ ensureRecycleTimer() {
330
+ if (this.recycleTimer)
331
+ return;
332
+ const timer = setInterval(() => {
333
+ if (this.closed) {
334
+ clearInterval(timer);
335
+ this.recycleTimer = undefined;
336
+ return;
337
+ }
338
+ this.checkRecycle();
339
+ if (!this.recycle.isPending) {
340
+ clearInterval(timer);
341
+ this.recycleTimer = undefined;
342
+ }
343
+ }, Math.max(1000, Math.min(30_000, HOST_IDLE_EXIT_MS / 120)));
344
+ timer.unref?.();
345
+ this.recycleTimer = timer;
346
+ }
347
+ /**
348
+ * 只收掉宿主进程,**保持运行时可用**。
349
+ *
350
+ * 与 `close()` 的区别是语义而非实现:空闲回收之后,下一次调用必须能懒启动回来。
351
+ * 如果把运行时置成 closed,空闲回收就成了"用过一小时就永久报废"——这是我在写
352
+ * 第一版时踩过的坑,测试里表现为第二次调用拿到 `host runtime is closed`。
353
+ */
354
+ async stopHost() {
355
+ const client = this.client;
356
+ this.client = undefined;
357
+ this.starting = undefined;
358
+ /**
359
+ * 自省快照必须一起清掉。
360
+ *
361
+ * 不清的话,新宿主起来到第一次 stats 帧之间(最长一个采样周期,10 秒),`status`
362
+ * 会把**旧进程**的 `uptimeMs` / `rss` / `callsCompleted` 贴在新 pid 底下——运维据此
363
+ * 判断「重启后是不是真换了进程」会得出相反的结论。
364
+ */
365
+ this.latestStats = undefined;
366
+ // 进程已经收了,关闸遗留的"待收"标记就该清掉。不清的话下一次调用结束后会
367
+ // 走 retire 分支而不排空闲定时器,导致宿主永不过期退出。
368
+ this.retirePending = false;
369
+ try {
370
+ await client?.close();
371
+ }
372
+ finally {
373
+ this.cleanupHost?.();
374
+ this.cleanupHost = undefined;
375
+ }
376
+ }
377
+ cancelRetirement() {
378
+ this.retirePending = false;
379
+ }
380
+ /**
381
+ * 关闸时释放宿主:**只在该宿主没有在途调用时**立刻收掉进程。
382
+ *
383
+ * 为什么要有这个方法:关闸只摘掉 runner 的引用(`setHostRuntime(undefined)`),
384
+ * 运行时对象与进程都还在。空等 1 小时空闲回收意味着「已经关了闸,进程还活着」,
385
+ * 而 `status` 这时报 `{enabled:false}` 又不带 `running`——运维看到的是一个骗人的
386
+ * 快照,并且真去查进程还能查到。
387
+ *
388
+ * 有在途调用时不强杀:那些调用已经派发出去了,杀掉等于把它们全判失败。交给
389
+ * 正常路径——最后一次调用结束后 `scheduleIdleExit()` 会按空闲窗口收尾。
390
+ */
391
+ async retireIfIdle() {
392
+ if (this.closed)
393
+ return false;
394
+ const client = this.client;
395
+ if (!client) {
396
+ if (this.starting || this.activeCalls > 0)
397
+ this.retirePending = true;
398
+ return false;
399
+ }
400
+ if (client.stats.inFlight > 0 || this.activeCalls > 0) {
401
+ // 记一笔:最后一次调用结束时会再试一次,不必等满空闲窗口。
402
+ this.retirePending = true;
403
+ return false;
404
+ }
405
+ this.retirePending = false;
406
+ this.cancelIdleExit();
407
+ if (this.recycleTimer) {
408
+ clearInterval(this.recycleTimer);
409
+ this.recycleTimer = undefined;
410
+ }
411
+ // 走 stopHost 而不是 close:保留「可以再懒启动回来」的能力,
412
+ // 之后重新开闸不需要重建运行时对象。
413
+ await this.stopHost();
414
+ return true;
415
+ }
416
+ /** 彻底关闭:此后 `run()` 一律拒绝。 */
417
+ async close() {
418
+ if (this.closed)
419
+ return;
420
+ this.closed = true;
421
+ if (this.restartTimer) {
422
+ clearTimeout(this.restartTimer);
423
+ this.restartTimer = undefined;
424
+ }
425
+ this.cancelIdleExit();
426
+ if (this.recycleTimer) {
427
+ clearInterval(this.recycleTimer);
428
+ this.recycleTimer = undefined;
429
+ }
430
+ try {
431
+ await this.starting;
432
+ }
433
+ catch { /* startup failure is already reported to the caller */ }
434
+ await this.stopHost();
435
+ }
436
+ // ── 内部 ────────────────────────────────────────────────────────────
437
+ async ensureStarted(role) {
438
+ const mode = this.deps.permissionMode?.(role) ?? resolveRuntimePermissionMode({ selfAid: this.deps.aid, role }).effectiveValue;
439
+ const policyKey = JSON.stringify([this.deps.getProjectPath(), mode, mode === 'bypass' && role === 'owner']);
440
+ if (this.client && this.policyKey !== policyKey) {
441
+ if (this.client.stats.inFlight)
442
+ throw new ServiceError('SERVICES_HOST_RESTARTING', 'host policy changed; waiting for active calls');
443
+ await this.stopHost();
444
+ }
445
+ if (this.client?.isReady)
446
+ return;
447
+ if (this.starting) {
448
+ await this.starting;
449
+ if (this.policyKey !== policyKey)
450
+ return this.ensureStarted(role);
451
+ return;
452
+ }
453
+ this.starting = (async () => {
454
+ const runtimeRoot = this.requireRuntimeRoot();
455
+ const projectPath = this.deps.getProjectPath();
456
+ if (!projectPath) {
457
+ throw new ServiceError('SCRIPT_SANDBOX_UNAVAILABLE', 'agent project path unavailable; host refused');
458
+ }
459
+ const deployed = deployHostProgram(runtimeRoot);
460
+ const permissionMode = mode;
461
+ // 包脚本快照根必须先存在:策略条目过滤掉不存在的路径,根不存在就等于没授 read。
462
+ const packsRoot = path.join(runtimeRoot, 'host', 'packs');
463
+ fs.mkdirSync(packsRoot, { recursive: true, mode: 0o700 });
464
+ // 宿主工作根必须在**启动前**存在:策略条目指向不存在的路径不会生效,
465
+ // 而宿主启动后再建已经来不及(它已经在沙箱里,建不出来)。
466
+ const hostWorkRoot = path.join(runtimeRoot, 'host', 'work');
467
+ fs.mkdirSync(hostWorkRoot, { recursive: true, mode: 0o700 });
468
+ const launch = await buildHostLaunch({
469
+ aid: this.deps.aid,
470
+ identity: this.deps.identity(),
471
+ programEntry: deployed.entry,
472
+ programDir: deployed.dir,
473
+ projectPath,
474
+ permissionMode,
475
+ role,
476
+ env: {
477
+ EVOLCORE_HOST_WORKDIR: path.join(runtimeRoot, 'host', 'work'),
478
+ // 采样周期:显式透传而不是靠宿主继承环境——`EVOLCORE_` 前缀在无沙箱路径里
479
+ // 会被清洗掉(那是给 daemon 自己的控制变量),宿主看不到。
480
+ ...(process.env.EVOLCORE_HOST_STATS_MS
481
+ ? { EVOLCORE_HOST_STATS_MS: process.env.EVOLCORE_HOST_STATS_MS }
482
+ : {}),
483
+ },
484
+ /**
485
+ * 宿主 spawn 常驻子进程时,Node 解析入口脚本要对**路径链上每一级祖先**
486
+ * 做 `realpathSync`/`lstat`(`Module._findPath` → `resolveMainPath`)。
487
+ * 只授 `<runtimeRoot>/host/packs` 会让它在 `runtimeRoot` 这一级就撞 EPERM:
488
+ *
489
+ * Error: EPERM: operation not permitted, lstat 'C:\Windows\Temp\ec-session-…'
490
+ * at Module._findPath (node:internal/modules/cjs/loader)
491
+ *
492
+ * 结果是常驻子进程起不来 → `RESIDENT_UNAVAILABLE: exited before ready` →
493
+ * 宿主被判崩溃重启三次后整体降级。实测补上祖先目录后同一次调用从
494
+ * 3060ms 降到 6ms。
495
+ *
496
+ * `host/` 与 `runtimeRoot` 是运行目录自身的两段祖先,不含任何用户数据;
497
+ * 真正的隔离边界在 `agents/`、`.evolcore/` 与其它 agent 目录的 DENY 条目上,
498
+ * 授这两段 read 不扩大可达面。
499
+ */
500
+ extraReadRoots: [runtimeRoot, path.join(runtimeRoot, 'host'), packsRoot],
501
+ extraWriteRoots: [hostWorkRoot],
502
+ });
503
+ const spec = {
504
+ command: launch.command,
505
+ args: launch.args,
506
+ cwd: launch.cwd,
507
+ env: launch.env,
508
+ };
509
+ // 探针:宿主启动的**唯一**证明沙箱生效的时机。与一次性路径不同,这里
510
+ // **不降级**——一次调用降级只影响一次,宿主降级是整个生命周期裸奔(设计稿 6.5)。
511
+ if (launch.prepare) {
512
+ try {
513
+ await runPrepareWithDeadline(launch.prepare);
514
+ }
515
+ catch (error) {
516
+ launch.cleanup?.();
517
+ throw new ServiceError('SCRIPT_SANDBOX_UNAVAILABLE', `service host sandbox proof failed; host start refused: ${errorMessage(error)}`);
518
+ }
519
+ }
520
+ const client = new ServiceHostClient({
521
+ launch: spec,
522
+ ...(this.deps.spawnImpl ? { spawnImpl: this.deps.spawnImpl } : {}),
523
+ ...(this.deps.onHostLog ? { onHostLog: this.deps.onHostLog } : {}),
524
+ // 宿主丢失(崩溃/卡死/协议破坏)→ 计划外重启,带退避与预算。
525
+ onHostLost: reason => this.handleHostLost(reason),
526
+ onHostStats: stats => this.onHostStats(stats),
527
+ });
528
+ try {
529
+ await client.start();
530
+ }
531
+ catch (error) {
532
+ await client.close();
533
+ launch.cleanup?.();
534
+ throw error;
535
+ }
536
+ this.client = client;
537
+ this.cleanupHost = launch.cleanup;
538
+ this.policyKey = policyKey;
539
+ this.sandboxAbsent = launch.sandboxAbsent;
540
+ const now = Date.now();
541
+ this.restarts.markStarted(now);
542
+ this.recycle.markStarted(now);
543
+ this.lastCallEndedAt = now;
544
+ })();
545
+ try {
546
+ await this.starting;
547
+ }
548
+ finally {
549
+ this.starting = undefined;
550
+ }
551
+ }
552
+ /**
553
+ * 安排空闲退出。
554
+ *
555
+ * 每次调用结束后重排一次:**只有连续 `idleExitMs` 无调用才退出**。这样稀疏流量
556
+ * (每 6 分钟一次)永远不会触发——那类包正是常驻模式最该服务的对象。
557
+ *
558
+ * 退出走 `close()` 而不是直接杀进程:让宿主收到 EOF 自行终止子进程,避免留孤儿。
559
+ */
560
+ scheduleIdleExit() {
561
+ this.cancelIdleExit();
562
+ if (this.recycleTimer) {
563
+ clearInterval(this.recycleTimer);
564
+ this.recycleTimer = undefined;
565
+ }
566
+ const timer = setTimeout(() => {
567
+ this.idleTimer = undefined;
568
+ // 重启等待期里不退出:那会让下次调用又付一次启动,且可能与重启打架。
569
+ if (this.closed || this.restartTimer || this.starting)
570
+ return;
571
+ this.idleExits += 1;
572
+ void this.stopHost();
573
+ }, this.idleExitMs);
574
+ timer.unref?.();
575
+ this.idleTimer = timer;
576
+ }
577
+ cancelIdleExit() {
578
+ if (this.idleTimer) {
579
+ clearTimeout(this.idleTimer);
580
+ this.idleTimer = undefined;
581
+ }
582
+ }
583
+ /**
584
+ * 热重载:检查已运行宿主是否还与「当前代码」一致,不一致就请求滚动重启。
585
+ *
586
+ * 三个输入都要看,漏一个就会出现「改了代码没生效」这类最难查的问题:
587
+ *
588
+ * 1. **宿主程序版本**:部署了新程序但旧进程还在跑,必须换;
589
+ * 2. **包脚本内容**:脚本改了(`pack.revision` 不变),旧进程可能已经 require 过旧模块;
590
+ * 3. **包集合**:包被卸载后宿主里可能还留着它的状态。
591
+ *
592
+ * 注意**只是请求**:真正的重启走空闲窗口(`requestRecycle`),所以热重载不会
593
+ * 把错误糊到调用方脸上。
594
+ */
595
+ reconcile(activePacks, activePackScriptFingerprints) {
596
+ if (this.closed)
597
+ return;
598
+ const client = this.client;
599
+ if (!client?.isReady)
600
+ return; // 还没起过:下次懒启动自然会用新代码
601
+ const runningVersion = client.programVersion;
602
+ if (runningVersion && runningVersion !== HOST_PROGRAM_VERSION) {
603
+ this.recycle.requestRecycle(Date.now(), `host program changed: running ${runningVersion}, expected ${HOST_PROGRAM_VERSION}`);
604
+ this.checkRecycle();
605
+ return;
606
+ }
607
+ // 脚本内容变了:只要有一个包的快照指纹与当前暂存记录不一致,就换一个宿主。
608
+ for (const [packId, fingerprint] of activePackScriptFingerprints ?? []) {
609
+ const staged = this.staged.get(packId);
610
+ if (staged && staged.revision !== fingerprint) {
611
+ this.recycle.requestRecycle(Date.now(), `package ${packId} scripts changed`);
612
+ this.checkRecycle();
613
+ return;
614
+ }
615
+ }
616
+ // 包被禁用/卸载:让宿主重启,清掉它可能持有的该包状态。
617
+ const activeIds = new Set(activePacks.map(pack => pack.id));
618
+ for (const stagedId of this.staged.keys()) {
619
+ if (!activeIds.has(stagedId)) {
620
+ this.recycle.requestRecycle(Date.now(), `package ${stagedId} removed or disabled`);
621
+ this.checkRecycle();
622
+ return;
623
+ }
624
+ }
625
+ }
626
+ /** 观测用:当前暂存指纹(热重载判据)。 */
627
+ stagedFingerprints() {
628
+ return new Map([...this.staged].map(([id, value]) => [id, value.revision]));
629
+ }
630
+ /** 因空闲退出的次数(观测用)。 */
631
+ get idleExitCount() {
632
+ return this.idleExits;
633
+ }
634
+ /**
635
+ * 运维观测快照。
636
+ *
637
+ * 字段按「判断宿主是否健康」的需要挑,不做大而全:没有这些数字,上面所有阈值都
638
+ * 调不了,也判断不了自适应是否真的生效。
639
+ */
640
+ status() {
641
+ const stats = this.latestStats;
642
+ return {
643
+ running: this.running,
644
+ idleExits: this.idleExits,
645
+ recycleCount: this.recycleCount,
646
+ backoffMs: this.restarts.currentBackoffMs,
647
+ ...(this.restarts.degraded ? { degraded: this.restarts.degraded } : {}),
648
+ // 泄漏判据相关
649
+ leakTier: this.recycle.currentTier,
650
+ leakIntervalMs: this.recycle.currentIntervalMs,
651
+ restarts24h: this.recycle.recycleCount24h,
652
+ pendingRecycle: this.recycle.isPending
653
+ ? { reason: this.recycle.pendingRestartReason }
654
+ : undefined,
655
+ ...(stats
656
+ ? {
657
+ uptimeMs: stats.uptimeMs,
658
+ rss: stats.rss,
659
+ handles: stats.handles,
660
+ idleCpuPercent: stats.idleCpuPercent,
661
+ inFlight: stats.inFlight,
662
+ callsCompleted: stats.callsCompleted,
663
+ }
664
+ : {}),
665
+ client: this.client?.stats,
666
+ };
667
+ }
668
+ /**
669
+ * 宿主丢失后的计划外重启。
670
+ *
671
+ * 三条必须同时成立才重启:未关闭、未降级、预算内。任一不成立就**不重启**——
672
+ * 一个每次启动就崩的包不应该被无限重启,那不是恢复而是刷屏。
673
+ *
674
+ * 退避复位用「这次宿主活了多久」判:稳定超过 `stableResetMs` 说明上次抖动过去了,
675
+ * 下次从 1s 重新开始。不复位的话一次抖动之后永远停在 30s。
676
+ */
677
+ handleHostLost(reason) {
678
+ if (this.closed)
679
+ return;
680
+ // 清掉旧引用:下次 ensureStarted 会重建。
681
+ this.client = undefined;
682
+ this.starting = undefined;
683
+ // 旧进程的自省快照在新宿主首次采样前就是错的:pid 已经换了,内存与运行时长还是旧的。
684
+ this.latestStats = undefined;
685
+ const delay = this.restarts.onLost(Date.now(), reason.message);
686
+ if (delay === undefined) {
687
+ const degraded = this.restarts.degraded;
688
+ if (degraded)
689
+ this.deps.onDegraded?.(degraded);
690
+ return;
691
+ }
692
+ if (this.restartTimer)
693
+ clearTimeout(this.restartTimer);
694
+ const timer = setTimeout(() => {
695
+ this.restartTimer = undefined;
696
+ // 预热:下次真实调用时宿主已就绪,调用方不必等启动。
697
+ void this.ensureStarted().catch(() => { });
698
+ }, delay);
699
+ timer.unref?.();
700
+ this.restartTimer = timer;
701
+ }
702
+ requireRuntimeRoot() {
703
+ const root = this.deps.getRuntimeRoot();
704
+ if (!root)
705
+ throw new ServiceError('SCRIPT_SANDBOX_UNAVAILABLE', 'service host runtime root unavailable');
706
+ return root;
707
+ }
708
+ /**
709
+ * 取得该包脚本在宿主可读根下的快照路径。
710
+ *
711
+ * ## 为什么不能只看 `pack.revision`
712
+ *
713
+ * `revision` 是 **`pack.json` 的内容哈希**,不含脚本字节。只按它做缓存键的话,
714
+ * 改完脚本 `revision` 不变 → 永远复用旧快照 → 热重载在宿主模式下完全失效,
715
+ * 而日志里看不出任何异常(这正是 P4-1 的隐藏难点)。
716
+ *
717
+ * ## 为什么也不能只看入口脚本
718
+ *
719
+ * 暂存是**整目录树**的(相对导入 `./lib/*.mjs` 要跟着走)。只哈希入口文件的话,
720
+ * 改了兄弟模块不会被发现。
721
+ *
722
+ * 所以键 = `pack.revision` + 脚本目录树的逐文件哈希。代价是每次调用前要把目录读一遍——
723
+ * 这是为了保证「暂存的永远等于源码上的」,比省这点 IO 重要得多。
724
+ */
725
+ stagedScript(pack, handler, executable) {
726
+ const relative = handler.script.slice(SCRIPTS_DIR.length + 1);
727
+ const sourcePath = path.join(pack.paths.scriptsDir, relative);
728
+ // 快照以包目录为根,入口在镜像里的相对位置就是「包目录 → 入口」那段路径
729
+ // (`scripts/nested/parent.mjs`),不是去掉 `scripts/` 之后的后半截。
730
+ // 按后半截拼会把入口指到 `<快照>/nested/parent.mjs`,文件实际在
731
+ // `<快照>/scripts/nested/parent.mjs`——沙箱一启动就是 ERR_MODULE_NOT_FOUND。
732
+ const stagedRelative = path.relative(pack.dir, sourcePath);
733
+ const fingerprint = this.fingerprintScripts(pack);
734
+ const cached = this.staged.get(pack.id);
735
+ if (cached && cached.revision === fingerprint) {
736
+ return { scriptPath: path.join(cached.dir, stagedRelative), rootDir: cached.dir };
737
+ }
738
+ const root = this.requireRuntimeRoot();
739
+ // 按指纹分目录:新旧快照可以并存,在途调用读完旧版本前不会被删掉。
740
+ const dir = path.join(root, 'host', 'packs', pack.id, fingerprint.slice(0, 16));
741
+ fs.rmSync(dir, { recursive: true, force: true });
742
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
743
+ const bytes = readScriptSnapshot(sourcePath, pack.dir);
744
+ // 以包目录为暂存根:`scripts/<子目录>/handler.mjs` 里 `../lib/x.mjs` 这种
745
+ // 跨目录引用,在宿主沙箱里必须和本地运行落到同一处。
746
+ const scriptPath = stageScriptSnapshot(sourcePath, pack.dir, bytes, dir, {
747
+ rootDir: pack.dir,
748
+ skipTopEntries: SNAPSHOT_SKIP_TOP_ENTRIES,
749
+ });
750
+ preserveNodeModuleType(executable, sourcePath, dir);
751
+ this.staged.set(pack.id, { revision: fingerprint, dir });
752
+ // 同一包只保留最新快照目录:旧目录里可能是上一次的代码,
753
+ // 留着既占空间又容易在排查时看错。
754
+ this.pruneSnapshots(pack.id, dir);
755
+ return { scriptPath, rootDir: dir };
756
+ }
757
+ /**
758
+ * 脚本目录树的指纹。
759
+ *
760
+ * 覆盖**整个脚本目录**(与 `stageScriptSnapshot` 的暂存范围一致):入口文件 + 兄弟模块。
761
+ * 只从入口所在目录往下走的话,`scripts/<子目录>/` 里的 handler 改 `scripts/lib/`
762
+ * 不会让缓存失效——快照永远停在旧代码上,而日志里看不出任何异常。
763
+ * 用相对路径 + 字节的稳定顺序拼接,避免 `readdir` 顺序影响结果。
764
+ * 读不出来的文件跳过——真正的存在性/越界校验由 `stageScriptSnapshot` 负责,
765
+ * 这里只求「内容变了能被发现」。
766
+ */
767
+ fingerprintScripts(pack) {
768
+ const scriptDir = path.resolve(pack.paths.scriptsDir);
769
+ const parts = [pack.revision];
770
+ const walk = (dir) => {
771
+ let entries;
772
+ try {
773
+ entries = fs.readdirSync(dir, { withFileTypes: true });
774
+ }
775
+ catch {
776
+ return;
777
+ }
778
+ entries.sort((left, right) => left.name.localeCompare(right.name));
779
+ for (const entry of entries) {
780
+ const full = path.join(dir, entry.name);
781
+ if (entry.isDirectory()) {
782
+ if (entry.name === 'node_modules' || entry.name === '.git')
783
+ continue;
784
+ parts.push(`d:${path.relative(scriptDir, full)}`);
785
+ walk(full);
786
+ }
787
+ else if (entry.isFile()) {
788
+ try {
789
+ parts.push(`f:${path.relative(scriptDir, full)}:${sha256(fs.readFileSync(full))}`);
790
+ }
791
+ catch {
792
+ // 读不到就跳过:不因为一个文件让整个服务不可用。
793
+ }
794
+ }
795
+ }
796
+ };
797
+ walk(scriptDir);
798
+ return sha256(parts.join('\n'));
799
+ }
800
+ /** 清掉同一包下其它快照目录(只保留当前指纹那个)。 */
801
+ pruneSnapshots(packId, keepDir) {
802
+ const root = this.deps.getRuntimeRoot();
803
+ if (!root)
804
+ return;
805
+ const parent = path.join(root, 'host', 'packs', packId);
806
+ let entries;
807
+ try {
808
+ entries = fs.readdirSync(parent);
809
+ }
810
+ catch {
811
+ return;
812
+ }
813
+ for (const name of entries) {
814
+ const full = path.join(parent, name);
815
+ if (path.resolve(full) === path.resolve(keepDir))
816
+ continue;
817
+ // 与在途调用有竞态:宿主已经打开的脚本不受删目录影响(fd 已持有),
818
+ // 而下次调用会重新暂存。删失败不致命。
819
+ try {
820
+ fs.rmSync(full, { recursive: true, force: true });
821
+ }
822
+ catch { /* ignore */ }
823
+ }
824
+ }
825
+ }
826
+ /** 把 `pack:script` 这类键转成安全的目录名(去掉分隔符与可疑字符)。 */
827
+ function sanitizeKey(key) {
828
+ return key.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80);
829
+ }
830
+ /** 观测用快照:把宿主的自省数据映射成泄漏判据需要的形状。 */
831
+ function toLeakSnapshot(stats) {
832
+ return {
833
+ rss: stats.rss,
834
+ handles: stats.handles,
835
+ idleCpuPercent: stats.idleCpuPercent,
836
+ inFlight: stats.inFlight,
837
+ };
838
+ }
839
+ export function hostRuntimeErrorMessage(error) {
840
+ return errorMessage(error);
841
+ }