vessel-agent 0.0.0-stage → 2.3.0-beta.2

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 (1095) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +466 -2
  3. package/README.zh-CN.md +476 -0
  4. package/apps/web/dist/Vela.png +0 -0
  5. package/apps/web/dist/Vessel.svg +24 -0
  6. package/apps/web/dist/apple-touch-icon.png +0 -0
  7. package/apps/web/dist/assets/ConfigView-BKdxb1s5.js +1 -0
  8. package/apps/web/dist/assets/DesignLabContent-CY5HfVn_.js +4 -0
  9. package/apps/web/dist/assets/DesignLabView-DTBWv5-E.js +1 -0
  10. package/apps/web/dist/assets/action-menu.preview-CpIL3tay.js +1 -0
  11. package/apps/web/dist/assets/agent-message.preview-CSYnJxgr.js +1 -0
  12. package/apps/web/dist/assets/assistant-text.preview-Bc2Is6sW.js +2 -0
  13. package/apps/web/dist/assets/badges.preview-DP0oPcs5.js +1 -0
  14. package/apps/web/dist/assets/buttons.preview-Y84aT4k3.js +1 -0
  15. package/apps/web/dist/assets/card-shell.preview-mwRwhVb8.js +1 -0
  16. package/apps/web/dist/assets/chip-tones.preview-dQ_6pwft.js +1 -0
  17. package/apps/web/dist/assets/composer-controls.preview-CBtJVrMo.js +1 -0
  18. package/apps/web/dist/assets/confirm-dialog.preview-BkNEtLld.js +1 -0
  19. package/apps/web/dist/assets/data-table.preview-DPZ7Pnn8.js +1 -0
  20. package/apps/web/dist/assets/depth-color.preview-CtCbAgCH.js +1 -0
  21. package/apps/web/dist/assets/entity-header.preview-BxPLNUSH.js +1 -0
  22. package/apps/web/dist/assets/env-card.preview-Bv4UlMjr.js +1 -0
  23. package/apps/web/dist/assets/failure-card.preview-DD3-RMju.js +1 -0
  24. package/apps/web/dist/assets/filter-popover.preview-D7Q7Kws8.js +1 -0
  25. package/apps/web/dist/assets/form.preview-D_Qltx-j.js +1 -0
  26. package/apps/web/dist/assets/index-ee36IO2F.js +600 -0
  27. package/apps/web/dist/assets/index-uU9N5oTa.css +1 -0
  28. package/apps/web/dist/assets/key-value.preview-B0gzxwtK.js +1 -0
  29. package/apps/web/dist/assets/mention-popover.preview-Duza1RgL.js +1 -0
  30. package/apps/web/dist/assets/message-fold.preview-Cx-CD3Y4.js +1 -0
  31. package/apps/web/dist/assets/modal-shell.preview-DYKwUk2S.js +1 -0
  32. package/apps/web/dist/assets/nav-item.preview-FTbsBQ2g.js +1 -0
  33. package/apps/web/dist/assets/nav-status-legend.preview-bS4LDFbd.js +1 -0
  34. package/apps/web/dist/assets/page-scaffold.preview-bzBFkjZ6.js +1 -0
  35. package/apps/web/dist/assets/plugin-ui-BxTydP3l.js +1 -0
  36. package/apps/web/dist/assets/projection-card.preview-BV0P-y8e.js +6 -0
  37. package/apps/web/dist/assets/queued.preview-zQqFe4Zr.js +1 -0
  38. package/apps/web/dist/assets/react-vendor-CUu194FT.js +9 -0
  39. package/apps/web/dist/assets/reasoning.preview-DtHXgW_8.js +2 -0
  40. package/apps/web/dist/assets/section.preview-A-PRm-rh.js +1 -0
  41. package/apps/web/dist/assets/sidebar-shell.preview-DFKMwNoo.js +1 -0
  42. package/apps/web/dist/assets/stat.preview-BzChSFLL.js +1 -0
  43. package/apps/web/dist/assets/states.preview-CyXZWnZ-.js +1 -0
  44. package/apps/web/dist/assets/status-icons.preview-DHdWwUis.js +1 -0
  45. package/apps/web/dist/assets/tabs.preview-CHbK1Two.js +1 -0
  46. package/apps/web/dist/assets/tool-card.preview-Z48fekTD.js +2 -0
  47. package/apps/web/dist/assets/toolbar.preview-Bl6hLYXX.js +1 -0
  48. package/apps/web/dist/assets/tooltip.preview-GKGTGfMP.js +1 -0
  49. package/apps/web/dist/assets/user-bubble.preview-CHYvio9z.js +1 -0
  50. package/apps/web/dist/assets/vendor/jsx-runtime.mjs +7 -0
  51. package/apps/web/dist/assets/vendor/plugin-sdk.mjs +12 -0
  52. package/apps/web/dist/assets/vendor/react-dom-client.mjs +6 -0
  53. package/apps/web/dist/assets/vendor/react-dom.mjs +11 -0
  54. package/apps/web/dist/assets/vendor/react.mjs +39 -0
  55. package/apps/web/dist/build.json +5 -0
  56. package/apps/web/dist/favicon.ico +0 -0
  57. package/apps/web/dist/index.html +24 -0
  58. package/package.json +70 -4
  59. package/packages/agent/package.json +32 -0
  60. package/packages/agent/src/address-display.ts +141 -0
  61. package/packages/agent/src/conversation-budget.ts +651 -0
  62. package/packages/agent/src/conversation-store.ts +351 -0
  63. package/packages/agent/src/distress.ts +161 -0
  64. package/packages/agent/src/env-info-scope.ts +153 -0
  65. package/packages/agent/src/error-text.ts +28 -0
  66. package/packages/agent/src/inbox-source.ts +73 -0
  67. package/packages/agent/src/inbox.ts +2335 -0
  68. package/packages/agent/src/index.ts +273 -0
  69. package/packages/agent/src/member-cwd.ts +128 -0
  70. package/packages/agent/src/member-ports.ts +162 -0
  71. package/packages/agent/src/refs.ts +51 -0
  72. package/packages/agent/src/registry.ts +741 -0
  73. package/packages/agent/src/runtime.ts +2501 -0
  74. package/packages/agent/src/self-card-delta.ts +428 -0
  75. package/packages/agent/src/service.ts +9212 -0
  76. package/packages/agent/src/snapshot.ts +614 -0
  77. package/packages/agent/src/team-address.ts +96 -0
  78. package/packages/agent/src/team-log.ts +487 -0
  79. package/packages/agent/src/team-service.ts +1966 -0
  80. package/packages/agent/src/team-slug.ts +167 -0
  81. package/packages/agent/src/team-store.ts +619 -0
  82. package/packages/agent/src/tool.ts +1306 -0
  83. package/packages/agent/src/types/budget.ts +168 -0
  84. package/packages/agent/src/types/constants.ts +17 -0
  85. package/packages/agent/src/types/dispatch.ts +133 -0
  86. package/packages/agent/src/types/events.ts +132 -0
  87. package/packages/agent/src/types/execution.ts +289 -0
  88. package/packages/agent/src/types/lifecycle.ts +372 -0
  89. package/packages/agent/src/types/member.ts +221 -0
  90. package/packages/agent/src/types/message.ts +113 -0
  91. package/packages/agent/src/types/results.ts +64 -0
  92. package/packages/agent/src/types/roster.ts +137 -0
  93. package/packages/agent/src/types/service.ts +702 -0
  94. package/packages/agent/src/types/session.ts +102 -0
  95. package/packages/agent/src/types/team.ts +558 -0
  96. package/packages/agent/src/types.ts +22 -0
  97. package/packages/agent/tsconfig.json +8 -0
  98. package/packages/config/package.json +32 -0
  99. package/packages/config/src/auth-origins.ts +85 -0
  100. package/packages/config/src/auth-strategies/avatar-ref.ts +40 -0
  101. package/packages/config/src/auth-strategies/gitee.ts +72 -0
  102. package/packages/config/src/auth-strategies/github.ts +64 -0
  103. package/packages/config/src/auth-strategies/index.ts +47 -0
  104. package/packages/config/src/auth-strategies/match.ts +82 -0
  105. package/packages/config/src/auth-strategies/microsoft.ts +100 -0
  106. package/packages/config/src/auth-strategies/oauth-exchange.ts +192 -0
  107. package/packages/config/src/auth-strategies/password.ts +34 -0
  108. package/packages/config/src/auth-strategies/registry.ts +105 -0
  109. package/packages/config/src/auth-strategies/shapes.ts +138 -0
  110. package/packages/config/src/auth-strategies/types.ts +190 -0
  111. package/packages/config/src/auth.ts +305 -0
  112. package/packages/config/src/config-lock.ts +328 -0
  113. package/packages/config/src/defaults.ts +271 -0
  114. package/packages/config/src/env-file.ts +175 -0
  115. package/packages/config/src/env-injection.ts +117 -0
  116. package/packages/config/src/explain.ts +283 -0
  117. package/packages/config/src/gateway.ts +107 -0
  118. package/packages/config/src/index.ts +253 -0
  119. package/packages/config/src/loader.ts +871 -0
  120. package/packages/config/src/model-migration.ts +534 -0
  121. package/packages/config/src/model-registry.ts +374 -0
  122. package/packages/config/src/models-disk.ts +72 -0
  123. package/packages/config/src/models-validation.ts +467 -0
  124. package/packages/config/src/node-registration.ts +583 -0
  125. package/packages/config/src/root-secret.ts +402 -0
  126. package/packages/config/src/secrets.ts +452 -0
  127. package/packages/config/src/sources.ts +82 -0
  128. package/packages/config/src/team-policy.ts +422 -0
  129. package/packages/config/src/types/agent.ts +263 -0
  130. package/packages/config/src/types/attention.ts +28 -0
  131. package/packages/config/src/types/auth.ts +126 -0
  132. package/packages/config/src/types/connect.ts +21 -0
  133. package/packages/config/src/types/hub.ts +59 -0
  134. package/packages/config/src/types/models.ts +153 -0
  135. package/packages/config/src/types/node.ts +202 -0
  136. package/packages/config/src/types/observability.ts +84 -0
  137. package/packages/config/src/types/root.ts +240 -0
  138. package/packages/config/src/types/runtime.ts +123 -0
  139. package/packages/config/src/types/security.ts +43 -0
  140. package/packages/config/src/types/serve.ts +34 -0
  141. package/packages/config/src/types/snapshot.ts +28 -0
  142. package/packages/config/src/types/team.ts +112 -0
  143. package/packages/config/src/types/ui.ts +179 -0
  144. package/packages/config/src/types.ts +22 -0
  145. package/packages/config/src/user-config.ts +175 -0
  146. package/packages/config/src/utils.ts +55 -0
  147. package/packages/config/src/validator/auth.ts +302 -0
  148. package/packages/config/src/validator/hub.ts +329 -0
  149. package/packages/config/src/validator/models.ts +1304 -0
  150. package/packages/config/src/validator/serve.ts +784 -0
  151. package/packages/config/src/validator/settings.ts +244 -0
  152. package/packages/config/src/validator/shared.ts +304 -0
  153. package/packages/config/src/validator/tenant-keys.ts +91 -0
  154. package/packages/config/src/validator/unknown-keys.ts +452 -0
  155. package/packages/config/src/validator.ts +1146 -0
  156. package/packages/config/tsconfig.json +8 -0
  157. package/packages/core/package.json +38 -0
  158. package/packages/core/src/context/anchor.ts +57 -0
  159. package/packages/core/src/context/archive-notice.ts +283 -0
  160. package/packages/core/src/context/cleared-tool-result.ts +262 -0
  161. package/packages/core/src/context/compaction-index.ts +381 -0
  162. package/packages/core/src/context/composition.ts +251 -0
  163. package/packages/core/src/context/context-manager.ts +1585 -0
  164. package/packages/core/src/context/context-notice.ts +218 -0
  165. package/packages/core/src/context/index.ts +220 -0
  166. package/packages/core/src/context/model-change-notice.ts +81 -0
  167. package/packages/core/src/context/projection-policy.ts +719 -0
  168. package/packages/core/src/context/prompt-context.ts +66 -0
  169. package/packages/core/src/context/read-side-mask.ts +63 -0
  170. package/packages/core/src/context/request-sequence.ts +423 -0
  171. package/packages/core/src/context/request-view.ts +256 -0
  172. package/packages/core/src/context/session-breaker.ts +100 -0
  173. package/packages/core/src/context/tool-result-whitelist.ts +135 -0
  174. package/packages/core/src/events/event-stream.ts +271 -0
  175. package/packages/core/src/events/file-event-store.ts +119 -0
  176. package/packages/core/src/events/index.ts +15 -0
  177. package/packages/core/src/events/replay.ts +82 -0
  178. package/packages/core/src/events/summarize-event.ts +135 -0
  179. package/packages/core/src/index.ts +475 -0
  180. package/packages/core/src/kernel/cancellation.ts +54 -0
  181. package/packages/core/src/kernel/event-bus.ts +65 -0
  182. package/packages/core/src/kernel/index.ts +32 -0
  183. package/packages/core/src/kernel/internal.ts +32 -0
  184. package/packages/core/src/kernel/scheduler.ts +406 -0
  185. package/packages/core/src/kernel/types.ts +269 -0
  186. package/packages/core/src/limits/index.ts +23 -0
  187. package/packages/core/src/limits/limit-checker.ts +270 -0
  188. package/packages/core/src/limits/limit-error.ts +29 -0
  189. package/packages/core/src/log-format.ts +722 -0
  190. package/packages/core/src/log-hub.ts +278 -0
  191. package/packages/core/src/logging.ts +64 -0
  192. package/packages/core/src/observability/index.ts +24 -0
  193. package/packages/core/src/observability/metrics.ts +279 -0
  194. package/packages/core/src/observability/read-trace.ts +163 -0
  195. package/packages/core/src/observability/rebuild-metrics.ts +37 -0
  196. package/packages/core/src/observability/trace-prune.ts +248 -0
  197. package/packages/core/src/observability/trace-recorder.ts +484 -0
  198. package/packages/core/src/observability/trace-redactor.ts +93 -0
  199. package/packages/core/src/pii/index.ts +88 -0
  200. package/packages/core/src/pii/notice.ts +156 -0
  201. package/packages/core/src/pii/reveal.ts +198 -0
  202. package/packages/core/src/pii/rules.ts +545 -0
  203. package/packages/core/src/pii/types.ts +140 -0
  204. package/packages/core/src/pii/vault.ts +764 -0
  205. package/packages/core/src/provider/errors.ts +41 -0
  206. package/packages/core/src/provider/index.ts +19 -0
  207. package/packages/core/src/provider/providers.ts +1011 -0
  208. package/packages/core/src/provider/request-extras.ts +285 -0
  209. package/packages/core/src/provider/stream-accumulator.ts +168 -0
  210. package/packages/core/src/provider/usage.ts +112 -0
  211. package/packages/core/src/runtime/error-envelope.ts +451 -0
  212. package/packages/core/src/runtime/error-summary.ts +174 -0
  213. package/packages/core/src/runtime/execution-unit.ts +6675 -0
  214. package/packages/core/src/runtime/guardrail-runner.ts +86 -0
  215. package/packages/core/src/runtime/hook-runner.ts +137 -0
  216. package/packages/core/src/runtime/index.ts +123 -0
  217. package/packages/core/src/runtime/permission-policy.ts +267 -0
  218. package/packages/core/src/runtime/plugin-host.ts +489 -0
  219. package/packages/core/src/runtime/plugin-install.ts +144 -0
  220. package/packages/core/src/runtime/policy/index.ts +21 -0
  221. package/packages/core/src/runtime/prompt-prefix-guard.ts +166 -0
  222. package/packages/core/src/runtime/provider-retry.ts +220 -0
  223. package/packages/core/src/runtime/resume-markers.ts +114 -0
  224. package/packages/core/src/runtime/resume-recovery.ts +164 -0
  225. package/packages/core/src/runtime/run-journal.ts +382 -0
  226. package/packages/core/src/runtime/run-timing.ts +217 -0
  227. package/packages/core/src/runtime/runtime.ts +349 -0
  228. package/packages/core/src/runtime/safepoint-pause.ts +29 -0
  229. package/packages/core/src/runtime/tool-attachment.ts +170 -0
  230. package/packages/core/src/runtime/tool-calling-loop.ts +1219 -0
  231. package/packages/core/src/runtime/tool-name.ts +215 -0
  232. package/packages/core/src/runtime/tool-pipeline.ts +459 -0
  233. package/packages/core/src/runtime/tool-provenance.ts +48 -0
  234. package/packages/core/src/runtime/tool-result-gate.ts +329 -0
  235. package/packages/core/src/session/atomic-write.ts +335 -0
  236. package/packages/core/src/session/compaction-index-derive.ts +173 -0
  237. package/packages/core/src/session/compaction-index-store.ts +161 -0
  238. package/packages/core/src/session/compaction-recall.ts +375 -0
  239. package/packages/core/src/session/delete-session.ts +198 -0
  240. package/packages/core/src/session/file-backend.ts +1311 -0
  241. package/packages/core/src/session/index.ts +118 -0
  242. package/packages/core/src/session/message-identity.ts +272 -0
  243. package/packages/core/src/session/project-messages.ts +908 -0
  244. package/packages/core/src/session/projection-cache.ts +254 -0
  245. package/packages/core/src/session/prune.ts +153 -0
  246. package/packages/core/src/session/run-record-store.ts +307 -0
  247. package/packages/core/src/session/session-index.ts +158 -0
  248. package/packages/core/src/session/session-log-dir.ts +39 -0
  249. package/packages/core/src/session/session-store.ts +266 -0
  250. package/packages/core/src/session/sqlite-backend.ts +391 -0
  251. package/packages/core/src/socket-inherit-guard.ts +188 -0
  252. package/packages/core/src/storage/metadata-sidecar.ts +124 -0
  253. package/packages/core/src/tenant/index.ts +13 -0
  254. package/packages/core/src/tenant/resolve-tenant.ts +19 -0
  255. package/packages/core/src/tenant/tenant-paths.ts +83 -0
  256. package/packages/core/src/timeline/archive-audit.ts +316 -0
  257. package/packages/core/src/timeline/archive-lock.ts +124 -0
  258. package/packages/core/src/timeline/blocks.ts +1639 -0
  259. package/packages/core/src/timeline/enum-stats.ts +34 -0
  260. package/packages/core/src/timeline/holes.ts +431 -0
  261. package/packages/core/src/timeline/index.ts +387 -0
  262. package/packages/core/src/timeline/legacy-format.ts +97 -0
  263. package/packages/core/src/timeline/read-port.ts +582 -0
  264. package/packages/core/src/timeline/types.ts +371 -0
  265. package/packages/core/src/timeline/wal.ts +2485 -0
  266. package/packages/core/src/timeline/writer.ts +2079 -0
  267. package/packages/core/src/timeout.ts +93 -0
  268. package/packages/core/src/transport/in-process.ts +86 -0
  269. package/packages/core/src/transport/index.ts +6 -0
  270. package/packages/core/src/types/context.ts +229 -0
  271. package/packages/core/src/types/env-cadence.ts +35 -0
  272. package/packages/core/src/types/error-registry.ts +343 -0
  273. package/packages/core/src/types/error.ts +107 -0
  274. package/packages/core/src/types/event.ts +496 -0
  275. package/packages/core/src/types/guardrail.ts +35 -0
  276. package/packages/core/src/types/hook.ts +122 -0
  277. package/packages/core/src/types/index.ts +28 -0
  278. package/packages/core/src/types/lease.ts +91 -0
  279. package/packages/core/src/types/limits.ts +112 -0
  280. package/packages/core/src/types/logging.ts +54 -0
  281. package/packages/core/src/types/member-port.ts +194 -0
  282. package/packages/core/src/types/plugin.ts +392 -0
  283. package/packages/core/src/types/projection-cache.ts +80 -0
  284. package/packages/core/src/types/projection.ts +100 -0
  285. package/packages/core/src/types/provider.ts +319 -0
  286. package/packages/core/src/types/run-journal.ts +178 -0
  287. package/packages/core/src/types/run-record-store.ts +128 -0
  288. package/packages/core/src/types/run.ts +140 -0
  289. package/packages/core/src/types/session.ts +328 -0
  290. package/packages/core/src/types/source-module.ts +68 -0
  291. package/packages/core/src/types/tenant.ts +41 -0
  292. package/packages/core/src/types/tool-name.ts +57 -0
  293. package/packages/core/src/types/tool.ts +122 -0
  294. package/packages/core/src/types/trace.ts +38 -0
  295. package/packages/core/src/types/vision.ts +219 -0
  296. package/packages/core/src/vision/blobs.ts +328 -0
  297. package/packages/core/src/vision/index.ts +73 -0
  298. package/packages/core/src/vision/ingest.ts +126 -0
  299. package/packages/core/src/vision/notice.ts +58 -0
  300. package/packages/core/src/vision/plan.ts +358 -0
  301. package/packages/core/src/vision/staging.ts +81 -0
  302. package/packages/core/tsconfig.json +8 -0
  303. package/packages/permission/package.json +31 -0
  304. package/packages/permission/src/index.ts +60 -0
  305. package/packages/plugin-sdk/package.json +21 -0
  306. package/packages/plugin-sdk/src/index.ts +478 -0
  307. package/packages/plugin-sdk/src/semver.ts +154 -0
  308. package/packages/plugin-ui/package.json +33 -0
  309. package/packages/plugin-ui/src/Badge.tsx +41 -0
  310. package/packages/plugin-ui/src/Button.tsx +84 -0
  311. package/packages/plugin-ui/src/ComposerAttachments.tsx +87 -0
  312. package/packages/plugin-ui/src/ComposerContextMeter.tsx +209 -0
  313. package/packages/plugin-ui/src/ComposerToolbar.tsx +233 -0
  314. package/packages/plugin-ui/src/CountBadge.tsx +57 -0
  315. package/packages/plugin-ui/src/DataTable.tsx +168 -0
  316. package/packages/plugin-ui/src/Field.tsx +543 -0
  317. package/packages/plugin-ui/src/KeyValueList.tsx +32 -0
  318. package/packages/plugin-ui/src/Page.tsx +39 -0
  319. package/packages/plugin-ui/src/Pager.tsx +63 -0
  320. package/packages/plugin-ui/src/SearchInput.tsx +33 -0
  321. package/packages/plugin-ui/src/Section.tsx +47 -0
  322. package/packages/plugin-ui/src/Stat.tsx +25 -0
  323. package/packages/plugin-ui/src/TableToolbar.tsx +27 -0
  324. package/packages/plugin-ui/src/Tabs.tsx +77 -0
  325. package/packages/plugin-ui/src/card-surface.ts +11 -0
  326. package/packages/plugin-ui/src/cn.ts +7 -0
  327. package/packages/plugin-ui/src/dom-globals.d.ts +124 -0
  328. package/packages/plugin-ui/src/host.ts +270 -0
  329. package/packages/plugin-ui/src/index.ts +26 -0
  330. package/packages/plugin-ui/src/styles.css +386 -0
  331. package/packages/plugin-ui/src/useStaleWhileRevalidate.ts +211 -0
  332. package/packages/serve/package.json +32 -0
  333. package/packages/serve/src/agent-control.ts +595 -0
  334. package/packages/serve/src/agents-registry.ts +409 -0
  335. package/packages/serve/src/auth/avatar.ts +352 -0
  336. package/packages/serve/src/auth/bootstrap.ts +184 -0
  337. package/packages/serve/src/auth/credentials.ts +275 -0
  338. package/packages/serve/src/auth/github-oauth.ts +33 -0
  339. package/packages/serve/src/auth/index.ts +121 -0
  340. package/packages/serve/src/auth/oauth.ts +394 -0
  341. package/packages/serve/src/auth/origins.ts +145 -0
  342. package/packages/serve/src/auth/password.ts +187 -0
  343. package/packages/serve/src/auth/ratelimit.ts +249 -0
  344. package/packages/serve/src/auth/routes.ts +1757 -0
  345. package/packages/serve/src/auth/session.ts +407 -0
  346. package/packages/serve/src/auth/totp.ts +183 -0
  347. package/packages/serve/src/backpressure.ts +91 -0
  348. package/packages/serve/src/durable.ts +216 -0
  349. package/packages/serve/src/evals.ts +140 -0
  350. package/packages/serve/src/event-buffer.ts +92 -0
  351. package/packages/serve/src/event-summary.ts +11 -0
  352. package/packages/serve/src/federation.ts +1100 -0
  353. package/packages/serve/src/feishu.ts +51 -0
  354. package/packages/serve/src/gateway/auth.ts +773 -0
  355. package/packages/serve/src/gateway/errors.ts +21 -0
  356. package/packages/serve/src/gateway/frames.ts +195 -0
  357. package/packages/serve/src/gateway/methods/admin.ts +530 -0
  358. package/packages/serve/src/gateway/methods/agents.ts +1727 -0
  359. package/packages/serve/src/gateway/methods/attachments.ts +354 -0
  360. package/packages/serve/src/gateway/methods/common.ts +50 -0
  361. package/packages/serve/src/gateway/methods/config.ts +883 -0
  362. package/packages/serve/src/gateway/methods/evals.ts +87 -0
  363. package/packages/serve/src/gateway/methods/feishu.ts +52 -0
  364. package/packages/serve/src/gateway/methods/fleet.ts +225 -0
  365. package/packages/serve/src/gateway/methods/images.ts +196 -0
  366. package/packages/serve/src/gateway/methods/interactions.ts +721 -0
  367. package/packages/serve/src/gateway/methods/jobs.ts +148 -0
  368. package/packages/serve/src/gateway/methods/kanban.ts +637 -0
  369. package/packages/serve/src/gateway/methods/mcp.ts +82 -0
  370. package/packages/serve/src/gateway/methods/observability.ts +264 -0
  371. package/packages/serve/src/gateway/methods/permissions.ts +397 -0
  372. package/packages/serve/src/gateway/methods/rpc-namespaces.ts +80 -0
  373. package/packages/serve/src/gateway/methods/runs.ts +434 -0
  374. package/packages/serve/src/gateway/methods/schemas.ts +1196 -0
  375. package/packages/serve/src/gateway/methods/sessions.ts +2568 -0
  376. package/packages/serve/src/gateway/methods/subscription.ts +515 -0
  377. package/packages/serve/src/gateway/methods/teams.ts +638 -0
  378. package/packages/serve/src/gateway/sse.ts +130 -0
  379. package/packages/serve/src/gateway/static.ts +66 -0
  380. package/packages/serve/src/gateway/timeline-protocol.ts +532 -0
  381. package/packages/serve/src/gateway.ts +4974 -0
  382. package/packages/serve/src/hub-control.ts +86 -0
  383. package/packages/serve/src/hub-frames.ts +435 -0
  384. package/packages/serve/src/hub-protocol.ts +182 -0
  385. package/packages/serve/src/index.ts +511 -0
  386. package/packages/serve/src/interactions-registry.ts +1362 -0
  387. package/packages/serve/src/interactions-store.ts +360 -0
  388. package/packages/serve/src/local.ts +48 -0
  389. package/packages/serve/src/log-event.ts +57 -0
  390. package/packages/serve/src/mcp.ts +73 -0
  391. package/packages/serve/src/metrics.ts +137 -0
  392. package/packages/serve/src/platform/auth.ts +146 -0
  393. package/packages/serve/src/platform/index.ts +54 -0
  394. package/packages/serve/src/platform/listen-guard.ts +68 -0
  395. package/packages/serve/src/platform/metrics.ts +123 -0
  396. package/packages/serve/src/platform/proxy-config.ts +368 -0
  397. package/packages/serve/src/platform/proxy-ws.ts +737 -0
  398. package/packages/serve/src/platform/proxy.ts +909 -0
  399. package/packages/serve/src/platform/registry.ts +130 -0
  400. package/packages/serve/src/platform/rpc.ts +445 -0
  401. package/packages/serve/src/platform/server.ts +1148 -0
  402. package/packages/serve/src/platform/types.ts +276 -0
  403. package/packages/serve/src/plugin-host/catalog.ts +212 -0
  404. package/packages/serve/src/plugin-host/child.ts +767 -0
  405. package/packages/serve/src/plugin-host/dto.ts +191 -0
  406. package/packages/serve/src/plugin-host/errors.ts +50 -0
  407. package/packages/serve/src/plugin-host/events.ts +114 -0
  408. package/packages/serve/src/plugin-host/expose.ts +142 -0
  409. package/packages/serve/src/plugin-host/http.ts +823 -0
  410. package/packages/serve/src/plugin-host/index.ts +170 -0
  411. package/packages/serve/src/plugin-host/manager.ts +2027 -0
  412. package/packages/serve/src/plugin-host/ndjson.ts +136 -0
  413. package/packages/serve/src/plugin-host/proxy.ts +358 -0
  414. package/packages/serve/src/plugin-host/registry.ts +208 -0
  415. package/packages/serve/src/plugin-host/static.ts +162 -0
  416. package/packages/serve/src/plugin-host/types.ts +529 -0
  417. package/packages/serve/src/plugin-host/ws-proxy.ts +431 -0
  418. package/packages/serve/src/prometheus.ts +98 -0
  419. package/packages/serve/src/protocol.ts +332 -0
  420. package/packages/serve/src/replay-budget.ts +481 -0
  421. package/packages/serve/src/rpc.ts +614 -0
  422. package/packages/serve/src/run-control.ts +106 -0
  423. package/packages/serve/src/session-search.ts +142 -0
  424. package/packages/serve/src/shutdown-step.ts +128 -0
  425. package/packages/serve/src/team-control.ts +282 -0
  426. package/packages/serve/src/tenant-event-hub.ts +194 -0
  427. package/packages/serve/src/tenant.ts +169 -0
  428. package/packages/serve/src/tool-events.ts +244 -0
  429. package/packages/tui/package.json +40 -0
  430. package/packages/tui/src/commands/agents-command.ts +402 -0
  431. package/packages/tui/src/commands/capabilities-command.ts +356 -0
  432. package/packages/tui/src/commands/commands.ts +1361 -0
  433. package/packages/tui/src/commands/config-command.ts +541 -0
  434. package/packages/tui/src/commands/context-command.ts +348 -0
  435. package/packages/tui/src/commands/cost-command.ts +66 -0
  436. package/packages/tui/src/commands/details-command.ts +47 -0
  437. package/packages/tui/src/commands/errors-command.ts +205 -0
  438. package/packages/tui/src/commands/export-command.ts +193 -0
  439. package/packages/tui/src/commands/feishu-command.ts +101 -0
  440. package/packages/tui/src/commands/mcp-command.ts +319 -0
  441. package/packages/tui/src/commands/metrics-command.ts +314 -0
  442. package/packages/tui/src/commands/permissions-command.ts +117 -0
  443. package/packages/tui/src/commands/runs-command.ts +421 -0
  444. package/packages/tui/src/commands/sessions-command.ts +367 -0
  445. package/packages/tui/src/commands/settings-command.ts +180 -0
  446. package/packages/tui/src/commands/status-command.ts +30 -0
  447. package/packages/tui/src/commands/trace-command.ts +382 -0
  448. package/packages/tui/src/components/AskUserDialog.tsx +663 -0
  449. package/packages/tui/src/components/BottomBar.tsx +44 -0
  450. package/packages/tui/src/components/ConfirmDialog.tsx +175 -0
  451. package/packages/tui/src/components/DataTable.tsx +99 -0
  452. package/packages/tui/src/components/DetailPanel.tsx +80 -0
  453. package/packages/tui/src/components/EmptyState.tsx +27 -0
  454. package/packages/tui/src/components/InlineAutocomplete.tsx +319 -0
  455. package/packages/tui/src/components/InteractiveViewHost.tsx +652 -0
  456. package/packages/tui/src/components/KeyHints.tsx +41 -0
  457. package/packages/tui/src/components/Markdown.tsx +489 -0
  458. package/packages/tui/src/components/PanelFrame.tsx +113 -0
  459. package/packages/tui/src/components/QueuePreview.tsx +113 -0
  460. package/packages/tui/src/components/QuickHelp.tsx +91 -0
  461. package/packages/tui/src/components/ReasoningBlock.tsx +42 -0
  462. package/packages/tui/src/components/SessionTable.tsx +523 -0
  463. package/packages/tui/src/components/SpinnerWithVerb.tsx +116 -0
  464. package/packages/tui/src/components/StateTracker.ts +102 -0
  465. package/packages/tui/src/components/StatusBar.tsx +315 -0
  466. package/packages/tui/src/components/StreamOutput.tsx +302 -0
  467. package/packages/tui/src/components/SubagentActivity.tsx +57 -0
  468. package/packages/tui/src/components/TextViewer.tsx +100 -0
  469. package/packages/tui/src/components/ToolDisplay.tsx +248 -0
  470. package/packages/tui/src/components/ToolTrail.tsx +104 -0
  471. package/packages/tui/src/components/UiItemView.tsx +460 -0
  472. package/packages/tui/src/components/UpdateBanner.tsx +48 -0
  473. package/packages/tui/src/components/indicator.ts +61 -0
  474. package/packages/tui/src/error-classifier.ts +255 -0
  475. package/packages/tui/src/i18n/index.ts +67 -0
  476. package/packages/tui/src/i18n/messages/en.ts +543 -0
  477. package/packages/tui/src/i18n/messages/zh-CN.ts +528 -0
  478. package/packages/tui/src/index.ts +335 -0
  479. package/packages/tui/src/renderer/ask-user.ts +431 -0
  480. package/packages/tui/src/renderer/notify-user.ts +184 -0
  481. package/packages/tui/src/renderer/stream-renderer.ts +149 -0
  482. package/packages/tui/src/renderer/tool-confirm.ts +47 -0
  483. package/packages/tui/src/repl/agent-registry.ts +747 -0
  484. package/packages/tui/src/repl/cache-metrics.ts +241 -0
  485. package/packages/tui/src/repl/clear-on-start.ts +28 -0
  486. package/packages/tui/src/repl/error-archive.ts +95 -0
  487. package/packages/tui/src/repl/error-log.ts +212 -0
  488. package/packages/tui/src/repl/ink-repl.tsx +1735 -0
  489. package/packages/tui/src/repl/layout.ts +303 -0
  490. package/packages/tui/src/repl/limit-info.ts +630 -0
  491. package/packages/tui/src/repl/permission-pending.ts +49 -0
  492. package/packages/tui/src/repl/project/ui-item.ts +1307 -0
  493. package/packages/tui/src/repl/queue-info.ts +109 -0
  494. package/packages/tui/src/repl/resume-picker.ts +24 -0
  495. package/packages/tui/src/repl/run-turn.ts +60 -0
  496. package/packages/tui/src/repl/runtime-counters.ts +91 -0
  497. package/packages/tui/src/repl/startup-header.ts +144 -0
  498. package/packages/tui/src/repl/startup-notice.ts +100 -0
  499. package/packages/tui/src/repl/status-format.ts +513 -0
  500. package/packages/tui/src/repl/status-metrics.ts +88 -0
  501. package/packages/tui/src/repl/status-snapshot.ts +454 -0
  502. package/packages/tui/src/repl/use-repl-state.ts +548 -0
  503. package/packages/tui/src/repl-context.ts +349 -0
  504. package/packages/tui/src/rich-renderer.ts +63 -0
  505. package/packages/tui/src/rpc-events.ts +161 -0
  506. package/packages/tui/src/rpc.ts +149 -0
  507. package/packages/tui/src/theme.ts +180 -0
  508. package/packages/tui/src/types/events.ts +284 -0
  509. package/packages/tui/src/utils/dialog.ts +35 -0
  510. package/packages/tui/src/utils/diff.ts +124 -0
  511. package/packages/tui/src/utils/display-labels.ts +56 -0
  512. package/packages/tui/src/utils/file-reference.ts +180 -0
  513. package/packages/tui/src/utils/git.ts +24 -0
  514. package/packages/tui/src/utils/sanitize-terminal-text.ts +109 -0
  515. package/packages/tui/src/utils/text-layout.ts +127 -0
  516. package/packages/tui/src/utils/time.ts +25 -0
  517. package/packages/tui/src/utils/tool-input-summary.ts +70 -0
  518. package/packages/tui/src/views/keys.ts +344 -0
  519. package/packages/tui/src/views/layout.ts +224 -0
  520. package/packages/tui/src/views/render-text.ts +154 -0
  521. package/packages/tui/src/views/selection.ts +57 -0
  522. package/packages/tui/src/views/session-picker.ts +215 -0
  523. package/packages/tui/src/views/tones.ts +24 -0
  524. package/packages/tui/src/views/types.ts +200 -0
  525. package/packages/tui/src/wizard/setup-wizard.ts +439 -0
  526. package/packages/tui/tsconfig.json +10 -0
  527. package/plugins/context/doc-subscription/package.json +32 -0
  528. package/plugins/context/doc-subscription/src/agent.ts +151 -0
  529. package/plugins/context/doc-subscription/src/auto-sub.ts +80 -0
  530. package/plugins/context/doc-subscription/src/config.ts +358 -0
  531. package/plugins/context/doc-subscription/src/diff.ts +107 -0
  532. package/plugins/context/doc-subscription/src/friend-edges.ts +118 -0
  533. package/plugins/context/doc-subscription/src/health.ts +163 -0
  534. package/plugins/context/doc-subscription/src/hook.ts +1222 -0
  535. package/plugins/context/doc-subscription/src/implicit.ts +84 -0
  536. package/plugins/context/doc-subscription/src/index.ts +288 -0
  537. package/plugins/context/doc-subscription/src/lifecycle-listener.ts +58 -0
  538. package/plugins/context/doc-subscription/src/lifecycle.ts +186 -0
  539. package/plugins/context/doc-subscription/src/mute.ts +39 -0
  540. package/plugins/context/doc-subscription/src/notice.ts +347 -0
  541. package/plugins/context/doc-subscription/src/script.ts +288 -0
  542. package/plugins/context/doc-subscription/src/sources.ts +187 -0
  543. package/plugins/context/doc-subscription/src/store.ts +748 -0
  544. package/plugins/context/doc-subscription/src/team-log.ts +155 -0
  545. package/plugins/context/doc-subscription/src/tool.ts +2132 -0
  546. package/plugins/context/skills/package.json +182 -0
  547. package/plugins/context/skills/src/config.ts +178 -0
  548. package/plugins/context/skills/src/frontmatter.ts +166 -0
  549. package/plugins/context/skills/src/index.ts +144 -0
  550. package/plugins/context/skills/src/rpc.ts +274 -0
  551. package/plugins/context/skills/src/scanner.ts +262 -0
  552. package/plugins/context/skills/src/service.ts +277 -0
  553. package/plugins/context/skills/src/store.ts +333 -0
  554. package/plugins/context/skills/src/tool.ts +354 -0
  555. package/plugins/context/skills/src/trust.ts +71 -0
  556. package/plugins/context/skills/src/types.ts +130 -0
  557. package/plugins/context/skills/src/watch.ts +83 -0
  558. package/plugins/context/skills/tsconfig.web.json +29 -0
  559. package/plugins/context/skills/vite.config.embed.ts +107 -0
  560. package/plugins/context/skills/vite.config.ts +121 -0
  561. package/plugins/context/skills/web/assets/skills-8su2cNqF.css +2 -0
  562. package/plugins/context/skills/web/assets/skills-BhiDTAac.js +10 -0
  563. package/plugins/context/skills/web/embed/index.css +3 -0
  564. package/plugins/context/skills/web/embed/index.mjs +4251 -0
  565. package/plugins/context/skills/web/skills.html +13 -0
  566. package/plugins/context/skills/web-src/App.tsx +47 -0
  567. package/plugins/context/skills/web-src/SkillsView.tsx +649 -0
  568. package/plugins/context/skills/web-src/embed.css +153 -0
  569. package/plugins/context/skills/web-src/embed.tsx +36 -0
  570. package/plugins/context/skills/web-src/env.d.ts +2 -0
  571. package/plugins/context/skills/web-src/i18n.ts +195 -0
  572. package/plugins/context/skills/web-src/main.tsx +14 -0
  573. package/plugins/context/skills/web-src/shared.tsx +226 -0
  574. package/plugins/context/skills/web-src/skills.html +12 -0
  575. package/plugins/context/skills/web-src/styles.css +62 -0
  576. package/plugins/context/skills/web-src/types.ts +85 -0
  577. package/plugins/context/thinking-intensity/package.json +201 -0
  578. package/plugins/context/thinking-intensity/src/index.ts +285 -0
  579. package/plugins/context/thinking-intensity/src/mapping.ts +175 -0
  580. package/plugins/context/thinking-intensity/src/state.ts +134 -0
  581. package/plugins/evals/harness/package.json +32 -0
  582. package/plugins/evals/harness/src/assertions.ts +99 -0
  583. package/plugins/evals/harness/src/errors.ts +23 -0
  584. package/plugins/evals/harness/src/index.ts +48 -0
  585. package/plugins/evals/harness/src/mock-provider.ts +64 -0
  586. package/plugins/evals/harness/src/plugin.ts +48 -0
  587. package/plugins/evals/harness/src/report.ts +66 -0
  588. package/plugins/evals/harness/src/runner.ts +417 -0
  589. package/plugins/evals/harness/src/suite.ts +352 -0
  590. package/plugins/evals/harness/src/types.ts +154 -0
  591. package/plugins/fleet/compose/README.md +40 -0
  592. package/plugins/fleet/compose/package.json +172 -0
  593. package/plugins/fleet/compose/src/cli.ts +347 -0
  594. package/plugins/fleet/compose/src/i18n.ts +99 -0
  595. package/plugins/fleet/compose/src/index.ts +3 -0
  596. package/plugins/fleet/compose/src/manifest.ts +194 -0
  597. package/plugins/im/feishu/FEISHU.md +142 -0
  598. package/plugins/im/feishu/package.json +33 -0
  599. package/plugins/im/feishu/src/channel.ts +360 -0
  600. package/plugins/im/feishu/src/config.ts +133 -0
  601. package/plugins/im/feishu/src/dedupe.ts +30 -0
  602. package/plugins/im/feishu/src/errors.ts +21 -0
  603. package/plugins/im/feishu/src/index.ts +47 -0
  604. package/plugins/im/feishu/src/messages.ts +41 -0
  605. package/plugins/im/feishu/src/queue.ts +71 -0
  606. package/plugins/im/feishu/src/runner.ts +356 -0
  607. package/plugins/im/feishu/src/sdk-transport.ts +220 -0
  608. package/plugins/im/feishu/src/text.ts +56 -0
  609. package/plugins/im/feishu/src/types.ts +150 -0
  610. package/plugins/marketplace/marketplace/package.json +166 -0
  611. package/plugins/marketplace/marketplace/registry-template/README.md +105 -0
  612. package/plugins/marketplace/marketplace/registry-template/index.sample.json +71 -0
  613. package/plugins/marketplace/marketplace/registry-template/validate.mjs +272 -0
  614. package/plugins/marketplace/marketplace/registry-template/validate.yml +35 -0
  615. package/plugins/marketplace/marketplace/src/config-lock.ts +325 -0
  616. package/plugins/marketplace/marketplace/src/config.ts +432 -0
  617. package/plugins/marketplace/marketplace/src/errors.ts +79 -0
  618. package/plugins/marketplace/marketplace/src/index.ts +364 -0
  619. package/plugins/marketplace/marketplace/src/install.ts +930 -0
  620. package/plugins/marketplace/marketplace/src/jobs.ts +155 -0
  621. package/plugins/marketplace/marketplace/src/registry.ts +508 -0
  622. package/plugins/marketplace/marketplace/src/semver.ts +162 -0
  623. package/plugins/marketplace/marketplace/src/settings.ts +108 -0
  624. package/plugins/marketplace/marketplace/src/tar.ts +269 -0
  625. package/plugins/marketplace/marketplace/tsconfig.ui.json +26 -0
  626. package/plugins/marketplace/marketplace/vite.config.ts +107 -0
  627. package/plugins/marketplace/marketplace/web/assets/index-B2V7bx73.css +2 -0
  628. package/plugins/marketplace/marketplace/web/assets/index-B4NAz59m.js +13 -0
  629. package/plugins/marketplace/marketplace/web/index.html +13 -0
  630. package/plugins/marketplace/marketplace/web-src/App.tsx +193 -0
  631. package/plugins/marketplace/marketplace/web-src/api.ts +153 -0
  632. package/plugins/marketplace/marketplace/web-src/catalog.ts +27 -0
  633. package/plugins/marketplace/marketplace/web-src/components/ConfirmDialog.tsx +96 -0
  634. package/plugins/marketplace/marketplace/web-src/components/InstalledTable.tsx +152 -0
  635. package/plugins/marketplace/marketplace/web-src/components/JobStatus.tsx +70 -0
  636. package/plugins/marketplace/marketplace/web-src/components/Permissions.tsx +116 -0
  637. package/plugins/marketplace/marketplace/web-src/components/RegistryBanners.tsx +22 -0
  638. package/plugins/marketplace/marketplace/web-src/components/RegistrySetup.tsx +69 -0
  639. package/plugins/marketplace/marketplace/web-src/components/States.tsx +97 -0
  640. package/plugins/marketplace/marketplace/web-src/i18n.ts +337 -0
  641. package/plugins/marketplace/marketplace/web-src/index.html +12 -0
  642. package/plugins/marketplace/marketplace/web-src/main.tsx +17 -0
  643. package/plugins/marketplace/marketplace/web-src/styles.css +37 -0
  644. package/plugins/marketplace/marketplace/web-src/types.ts +175 -0
  645. package/plugins/marketplace/marketplace/web-src/views/InstalledView.tsx +150 -0
  646. package/plugins/marketplace/marketplace/web-src/views/MarketplaceView.tsx +479 -0
  647. package/plugins/marketplace/marketplace/web-src/views/UpdatesView.tsx +207 -0
  648. package/plugins/marketplace/marketplace/web-src/vite-env.d.ts +1 -0
  649. package/plugins/mcp/client/package.json +31 -0
  650. package/plugins/mcp/client/src/config-validate.ts +37 -0
  651. package/plugins/mcp/client/src/http-transport.ts +369 -0
  652. package/plugins/mcp/client/src/index.ts +35 -0
  653. package/plugins/mcp/client/src/json-rpc.ts +104 -0
  654. package/plugins/mcp/client/src/logging.ts +51 -0
  655. package/plugins/mcp/client/src/naming.ts +36 -0
  656. package/plugins/mcp/client/src/plugin.ts +310 -0
  657. package/plugins/mcp/client/src/registration.ts +143 -0
  658. package/plugins/mcp/client/src/server-connection.ts +556 -0
  659. package/plugins/mcp/client/src/stdio-transport.ts +377 -0
  660. package/plugins/mcp/client/src/transport.ts +11 -0
  661. package/plugins/mcp/client/src/types.ts +147 -0
  662. package/plugins/media/media/package.json +33 -0
  663. package/plugins/media/media/src/binaries.ts +88 -0
  664. package/plugins/media/media/src/config.ts +184 -0
  665. package/plugins/media/media/src/exec.ts +172 -0
  666. package/plugins/media/media/src/index.ts +125 -0
  667. package/plugins/media/media/src/tool.ts +640 -0
  668. package/plugins/observability/hook-logging/package.json +31 -0
  669. package/plugins/observability/hook-logging/src/index.ts +286 -0
  670. package/plugins/observability/usage/package.json +163 -0
  671. package/plugins/observability/usage/src/aggregate.ts +919 -0
  672. package/plugins/observability/usage/src/index.ts +362 -0
  673. package/plugins/observability/usage/src/query.ts +322 -0
  674. package/plugins/observability/usage/src/store.ts +1455 -0
  675. package/plugins/observability/usage/src/worker-client.ts +263 -0
  676. package/plugins/observability/usage/src/worker.ts +87 -0
  677. package/plugins/observability/usage/tsconfig.web.json +29 -0
  678. package/plugins/observability/usage/vite.config.embed.ts +105 -0
  679. package/plugins/observability/usage/vite.config.ts +121 -0
  680. package/plugins/observability/usage/web/assets/main-DD4g5VDL.css +2 -0
  681. package/plugins/observability/usage/web/assets/main-DVmWaf73.js +10 -0
  682. package/plugins/observability/usage/web/embed/index.css +3 -0
  683. package/plugins/observability/usage/web/embed/index.mjs +4560 -0
  684. package/plugins/observability/usage/web/logs.html +13 -0
  685. package/plugins/observability/usage/web/usage.html +13 -0
  686. package/plugins/observability/usage/web-src/App.tsx +54 -0
  687. package/plugins/observability/usage/web-src/LogsView.tsx +505 -0
  688. package/plugins/observability/usage/web-src/ModelTable.tsx +102 -0
  689. package/plugins/observability/usage/web-src/UsageView.tsx +210 -0
  690. package/plugins/observability/usage/web-src/embed.css +96 -0
  691. package/plugins/observability/usage/web-src/embed.tsx +75 -0
  692. package/plugins/observability/usage/web-src/env.d.ts +2 -0
  693. package/plugins/observability/usage/web-src/format.ts +88 -0
  694. package/plugins/observability/usage/web-src/i18n.ts +261 -0
  695. package/plugins/observability/usage/web-src/logs.html +12 -0
  696. package/plugins/observability/usage/web-src/main.tsx +19 -0
  697. package/plugins/observability/usage/web-src/shared.tsx +187 -0
  698. package/plugins/observability/usage/web-src/styles.css +22 -0
  699. package/plugins/observability/usage/web-src/usage.html +12 -0
  700. package/plugins/provider/anthropic/package.json +31 -0
  701. package/plugins/provider/anthropic/src/index.ts +75 -0
  702. package/plugins/provider/anthropic/src/retry.ts +266 -0
  703. package/plugins/provider/anthropic/src/timeout.ts +84 -0
  704. package/plugins/provider/model-registry/package.json +167 -0
  705. package/plugins/provider/model-registry/src/connectivity.ts +123 -0
  706. package/plugins/provider/model-registry/src/credential-store.ts +219 -0
  707. package/plugins/provider/model-registry/src/index.ts +453 -0
  708. package/plugins/provider/model-registry/src/registry-store.ts +223 -0
  709. package/plugins/provider/model-registry/tsconfig.web.json +29 -0
  710. package/plugins/provider/model-registry/vite.config.embed.ts +105 -0
  711. package/plugins/provider/model-registry/vite.config.ts +122 -0
  712. package/plugins/provider/model-registry/web/assets/main-BofPzD0n.js +10 -0
  713. package/plugins/provider/model-registry/web/assets/main-DkpGgdsZ.css +2 -0
  714. package/plugins/provider/model-registry/web/credentials.html +13 -0
  715. package/plugins/provider/model-registry/web/embed/index.css +3 -0
  716. package/plugins/provider/model-registry/web/embed/index.mjs +4887 -0
  717. package/plugins/provider/model-registry/web/models.html +13 -0
  718. package/plugins/provider/model-registry/web-src/App.tsx +54 -0
  719. package/plugins/provider/model-registry/web-src/CredentialsView.tsx +357 -0
  720. package/plugins/provider/model-registry/web-src/ModelForm.tsx +489 -0
  721. package/plugins/provider/model-registry/web-src/ModelsView.tsx +383 -0
  722. package/plugins/provider/model-registry/web-src/credentials.html +12 -0
  723. package/plugins/provider/model-registry/web-src/embed.css +96 -0
  724. package/plugins/provider/model-registry/web-src/embed.tsx +43 -0
  725. package/plugins/provider/model-registry/web-src/env.d.ts +2 -0
  726. package/plugins/provider/model-registry/web-src/i18n.ts +323 -0
  727. package/plugins/provider/model-registry/web-src/main.tsx +21 -0
  728. package/plugins/provider/model-registry/web-src/models.html +12 -0
  729. package/plugins/provider/model-registry/web-src/shared.tsx +147 -0
  730. package/plugins/provider/model-registry/web-src/styles.css +22 -0
  731. package/plugins/provider/model-registry/web-src/types.ts +120 -0
  732. package/plugins/provider/openai/package.json +31 -0
  733. package/plugins/provider/openai/src/index.ts +104 -0
  734. package/plugins/provider/openai/src/retry.ts +266 -0
  735. package/plugins/provider/openai/src/timeout.ts +84 -0
  736. package/plugins/provider/openai/src/vision.ts +121 -0
  737. package/plugins/security/guardrail-pii/package.json +31 -0
  738. package/plugins/security/guardrail-pii/src/index.ts +285 -0
  739. package/plugins/security/guardrail-pii/src/rules.ts +197 -0
  740. package/plugins/security/redact-secrets/package.json +31 -0
  741. package/plugins/security/redact-secrets/src/index.ts +145 -0
  742. package/plugins/security/redact-secrets/src/redactor.ts +83 -0
  743. package/plugins/security/redact-secrets/src/rules.ts +137 -0
  744. package/plugins/security/tool-policy/package.json +31 -0
  745. package/plugins/security/tool-policy/src/index.ts +184 -0
  746. package/plugins/tools/basic-tools/package.json +32 -0
  747. package/plugins/tools/basic-tools/src/background-jobs.ts +356 -0
  748. package/plugins/tools/basic-tools/src/bash-source.ts +58 -0
  749. package/plugins/tools/basic-tools/src/call-scope.ts +80 -0
  750. package/plugins/tools/basic-tools/src/config.ts +130 -0
  751. package/plugins/tools/basic-tools/src/index.ts +202 -0
  752. package/plugins/tools/basic-tools/src/path-boundary.ts +258 -0
  753. package/plugins/tools/basic-tools/src/shared.ts +221 -0
  754. package/plugins/tools/basic-tools/src/text.ts +49 -0
  755. package/plugins/tools/basic-tools/src/tools/bash-async.ts +1830 -0
  756. package/plugins/tools/basic-tools/src/tools/bash-exec.ts +567 -0
  757. package/plugins/tools/basic-tools/src/tools/bash.ts +300 -0
  758. package/plugins/tools/basic-tools/src/tools/edit.ts +160 -0
  759. package/plugins/tools/basic-tools/src/tools/grep.ts +601 -0
  760. package/plugins/tools/basic-tools/src/tools/read.ts +151 -0
  761. package/plugins/tools/basic-tools/src/tools/write.ts +494 -0
  762. package/plugins/tools/basic-tools/src/write-coord.ts +291 -0
  763. package/plugins/tools/basic-tools/src/write-lock.ts +353 -0
  764. package/plugins/tools/engine-client/package.json +34 -0
  765. package/plugins/tools/engine-client/src/client.ts +276 -0
  766. package/plugins/tools/engine-client/src/forward.ts +164 -0
  767. package/plugins/tools/engine-client/src/index.ts +18 -0
  768. package/plugins/tools/engine-client/src/pending.ts +101 -0
  769. package/plugins/tools/engine-client/src/pool.ts +1173 -0
  770. package/plugins/tools/engine-client/src/protocol.ts +249 -0
  771. package/plugins/tools/engine-client/src/registry.ts +138 -0
  772. package/plugins/tools/file-refs/README.md +68 -0
  773. package/plugins/tools/file-refs/package.json +135 -0
  774. package/plugins/tools/file-refs/src/index.ts +24 -0
  775. package/plugins/tools/file-refs/tsconfig.web.json +27 -0
  776. package/plugins/tools/file-refs/vite.config.embed.ts +88 -0
  777. package/plugins/tools/file-refs/web/embed/index.css +3 -0
  778. package/plugins/tools/file-refs/web/embed/index.mjs +879 -0
  779. package/plugins/tools/file-refs/web-src/AttachSheet.tsx +613 -0
  780. package/plugins/tools/file-refs/web-src/FileRefCard.tsx +206 -0
  781. package/plugins/tools/file-refs/web-src/FileRefLinkCard.tsx +90 -0
  782. package/plugins/tools/file-refs/web-src/attach-handler.tsx +116 -0
  783. package/plugins/tools/file-refs/web-src/attach-paths.ts +69 -0
  784. package/plugins/tools/file-refs/web-src/drop-handler.ts +15 -0
  785. package/plugins/tools/file-refs/web-src/embed.css +518 -0
  786. package/plugins/tools/file-refs/web-src/embed.tsx +18 -0
  787. package/plugins/tools/file-refs/web-src/env.d.ts +2 -0
  788. package/plugins/tools/file-refs/web-src/i18n.ts +137 -0
  789. package/plugins/tools/file-refs/web-src/icons.tsx +122 -0
  790. package/plugins/tools/file-refs/web-src/staging.ts +120 -0
  791. package/plugins/tools/file-refs/web-src/thumbnail.tsx +36 -0
  792. package/plugins/tools/recall/package.json +31 -0
  793. package/plugins/tools/recall/src/config.ts +74 -0
  794. package/plugins/tools/recall/src/index.ts +151 -0
  795. package/plugins/tools/recall/src/tool.ts +307 -0
  796. package/plugins/tools/web-tools/README.md +330 -0
  797. package/plugins/tools/web-tools/package.json +184 -0
  798. package/plugins/tools/web-tools/src/backends.ts +61 -0
  799. package/plugins/tools/web-tools/src/budget.ts +80 -0
  800. package/plugins/tools/web-tools/src/cache.ts +94 -0
  801. package/plugins/tools/web-tools/src/config.ts +412 -0
  802. package/plugins/tools/web-tools/src/deepseek-client.ts +406 -0
  803. package/plugins/tools/web-tools/src/deepseek-fetch.ts +168 -0
  804. package/plugins/tools/web-tools/src/extract.ts +373 -0
  805. package/plugins/tools/web-tools/src/fetch/local.ts +36 -0
  806. package/plugins/tools/web-tools/src/fetch/provider.ts +56 -0
  807. package/plugins/tools/web-tools/src/http.ts +415 -0
  808. package/plugins/tools/web-tools/src/index.ts +649 -0
  809. package/plugins/tools/web-tools/src/limits.ts +388 -0
  810. package/plugins/tools/web-tools/src/provider-http.ts +102 -0
  811. package/plugins/tools/web-tools/src/render.ts +248 -0
  812. package/plugins/tools/web-tools/src/robots.ts +187 -0
  813. package/plugins/tools/web-tools/src/search/custom.ts +595 -0
  814. package/plugins/tools/web-tools/src/search/deepseek.ts +111 -0
  815. package/plugins/tools/web-tools/src/search/index.ts +725 -0
  816. package/plugins/tools/web-tools/src/search/provider.ts +200 -0
  817. package/plugins/tools/web-tools/src/search/serper.ts +157 -0
  818. package/plugins/tools/web-tools/src/search/tavily.ts +146 -0
  819. package/plugins/tools/web-tools/src/secrets.ts +87 -0
  820. package/plugins/tools/web-tools/src/ssrf.ts +287 -0
  821. package/plugins/tools/web-tools/src/types.ts +137 -0
  822. package/skills/code-writing.md +33 -0
  823. package/src/agent/agent-control.ts +409 -0
  824. package/src/agent/agent-owner-client.ts +150 -0
  825. package/src/agent/agent-owner-server.ts +689 -0
  826. package/src/agent/agent-service-wiring.ts +675 -0
  827. package/src/agent/agent-wiring.ts +48 -0
  828. package/src/agent/ask-answer-delivery.ts +215 -0
  829. package/src/agent/local-run-adapter.ts +335 -0
  830. package/src/agent/peer-notices.ts +459 -0
  831. package/src/agent/peer-source.ts +63 -0
  832. package/src/agent/self-card.ts +52 -0
  833. package/src/agent/team-human-delivery.ts +144 -0
  834. package/src/assembly/collect.ts +161 -0
  835. package/src/assembly/feature.ts +133 -0
  836. package/src/assembly/features/attachments.ts +38 -0
  837. package/src/assembly/features/fleet.ts +31 -0
  838. package/src/assembly/features/jobs.ts +32 -0
  839. package/src/assembly/features/kanban.ts +56 -0
  840. package/src/assembly/features/restart.ts +35 -0
  841. package/src/assembly/features/subscription.ts +32 -0
  842. package/src/assembly/features.ts +30 -0
  843. package/src/cli/agent-call.ts +107 -0
  844. package/src/cli/args.ts +551 -0
  845. package/src/cli/ask-channel.ts +447 -0
  846. package/src/cli/command-spec/agent.ts +306 -0
  847. package/src/cli/command-spec/config.ts +179 -0
  848. package/src/cli/command-spec/define.ts +86 -0
  849. package/src/cli/command-spec/federation.ts +333 -0
  850. package/src/cli/command-spec/flags.ts +668 -0
  851. package/src/cli/command-spec/gateway.ts +350 -0
  852. package/src/cli/command-spec/hub.ts +290 -0
  853. package/src/cli/command-spec/kanban.ts +134 -0
  854. package/src/cli/command-spec/misc.ts +1032 -0
  855. package/src/cli/command-spec/model.ts +338 -0
  856. package/src/cli/command-spec/node.ts +160 -0
  857. package/src/cli/command-spec/plugin.ts +148 -0
  858. package/src/cli/command-spec/shared.ts +86 -0
  859. package/src/cli/command-spec/team.ts +582 -0
  860. package/src/cli/command-spec/token.ts +111 -0
  861. package/src/cli/command-spec.ts +270 -0
  862. package/src/cli/command-support.ts +53 -0
  863. package/src/cli/commands/agent/agent-command.ts +279 -0
  864. package/src/cli/commands/agent/agent-inbox-command.ts +141 -0
  865. package/src/cli/commands/agent/agents-command.ts +145 -0
  866. package/src/cli/commands/attention.ts +896 -0
  867. package/src/cli/commands/cli-update.ts +283 -0
  868. package/src/cli/commands/completion-command.ts +29 -0
  869. package/src/cli/commands/config-command.ts +545 -0
  870. package/src/cli/commands/dev-command.ts +429 -0
  871. package/src/cli/commands/doctor-command.ts +873 -0
  872. package/src/cli/commands/doctor-fleet.ts +410 -0
  873. package/src/cli/commands/errors-command.ts +469 -0
  874. package/src/cli/commands/eval-command.ts +168 -0
  875. package/src/cli/commands/federation-pair.ts +426 -0
  876. package/src/cli/commands/federation-peer.ts +445 -0
  877. package/src/cli/commands/federation.ts +527 -0
  878. package/src/cli/commands/fleet/fleet-inventory.ts +222 -0
  879. package/src/cli/commands/fleet/fleet-status-command.ts +433 -0
  880. package/src/cli/commands/fleet/ps-command.ts +387 -0
  881. package/src/cli/commands/fleet/restart-command.ts +745 -0
  882. package/src/cli/commands/fleet/start-command.ts +176 -0
  883. package/src/cli/commands/fleet/status-command.ts +318 -0
  884. package/src/cli/commands/fleet/stop-command.ts +548 -0
  885. package/src/cli/commands/gateway/gateway-command.ts +4204 -0
  886. package/src/cli/commands/gateway/gateway-nodes-command.ts +401 -0
  887. package/src/cli/commands/hub-command.ts +1007 -0
  888. package/src/cli/commands/kanban-command.ts +204 -0
  889. package/src/cli/commands/logs-command.ts +148 -0
  890. package/src/cli/commands/migrate-command.ts +131 -0
  891. package/src/cli/commands/model.ts +427 -0
  892. package/src/cli/commands/node-command.ts +805 -0
  893. package/src/cli/commands/permission/permission-show-command.ts +189 -0
  894. package/src/cli/commands/plugin/plugin-cli-command.ts +831 -0
  895. package/src/cli/commands/plugin/plugin-cli-local.ts +267 -0
  896. package/src/cli/commands/plugin/plugin-command.ts +407 -0
  897. package/src/cli/commands/prune-command.ts +233 -0
  898. package/src/cli/commands/resume-command.ts +100 -0
  899. package/src/cli/commands/rpc-command.ts +226 -0
  900. package/src/cli/commands/session/session-status-command.ts +352 -0
  901. package/src/cli/commands/team-command.ts +722 -0
  902. package/src/cli/commands/token-command.ts +494 -0
  903. package/src/cli/commands/trace-command.ts +133 -0
  904. package/src/cli/completion-script.ts +627 -0
  905. package/src/cli/completion-spec.ts +101 -0
  906. package/src/cli/control-plane-target.ts +295 -0
  907. package/src/cli/control-plane-types.ts +189 -0
  908. package/src/cli/feishu-command.ts +45 -0
  909. package/src/cli/headless-runner.ts +354 -0
  910. package/src/cli/help-search.ts +320 -0
  911. package/src/cli/help.ts +489 -0
  912. package/src/cli/output.ts +141 -0
  913. package/src/cli/parse-engine.ts +701 -0
  914. package/src/cli/parse-validators.ts +155 -0
  915. package/src/cli/project.ts +355 -0
  916. package/src/cli/registry.ts +25 -0
  917. package/src/cli.ts +2272 -0
  918. package/src/config/cli-overrides.ts +74 -0
  919. package/src/config/config-error-format.ts +44 -0
  920. package/src/config/config-snapshot.ts +15 -0
  921. package/src/config/config-watch.ts +436 -0
  922. package/src/config/config-write-apply.ts +98 -0
  923. package/src/config/empty-response-settings.ts +49 -0
  924. package/src/config/hot-apply-appliers.ts +527 -0
  925. package/src/config/hot-apply-assembly.ts +317 -0
  926. package/src/config/legacy-tool-names.ts +48 -0
  927. package/src/config/permission-defaults.ts +26 -0
  928. package/src/config/ui-settings.ts +568 -0
  929. package/src/config/vision-settings.ts +98 -0
  930. package/src/data/attachment-ingest.ts +101 -0
  931. package/src/data/attachment-staging.ts +377 -0
  932. package/src/data/attachments-list.ts +240 -0
  933. package/src/data/auto-prune.ts +342 -0
  934. package/src/data/data-lock.ts +580 -0
  935. package/src/data/data-paths.ts +265 -0
  936. package/src/data/image-blob-gc.ts +341 -0
  937. package/src/data/migrate.ts +480 -0
  938. package/src/data/path-resolution.ts +172 -0
  939. package/src/data/permission-store.ts +322 -0
  940. package/src/data/prune-wiring.ts +1037 -0
  941. package/src/data/refs-notice-hook.ts +417 -0
  942. package/src/federation/attention-client.ts +196 -0
  943. package/src/federation/attention-nodes.ts +142 -0
  944. package/src/federation/federation-address.ts +276 -0
  945. package/src/federation/federation-client.ts +620 -0
  946. package/src/federation/federation-config.ts +222 -0
  947. package/src/federation/federation-outbox.ts +374 -0
  948. package/src/federation/federation-pair-store.ts +236 -0
  949. package/src/federation/federation-pairing.ts +176 -0
  950. package/src/federation/federation-peer-store.ts +145 -0
  951. package/src/federation/federation-secrets.ts +140 -0
  952. package/src/federation/federation-send-port.ts +436 -0
  953. package/src/gateway/clean-spawn.ts +260 -0
  954. package/src/gateway/daemon.ts +336 -0
  955. package/src/gateway/fleet-index.ts +262 -0
  956. package/src/gateway/gateway-banner.ts +199 -0
  957. package/src/gateway/gateway-config-control.ts +53 -0
  958. package/src/gateway/gateway-reload-wiring.ts +512 -0
  959. package/src/gateway/gateway-wiring.ts +113 -0
  960. package/src/gateway/handoff.ts +131 -0
  961. package/src/gateway/instance-lock.ts +244 -0
  962. package/src/gateway/interactions-dir.ts +27 -0
  963. package/src/gateway/node-listen.ts +123 -0
  964. package/src/gateway/node-registry.ts +401 -0
  965. package/src/gateway/node-supervisor.ts +2226 -0
  966. package/src/gateway/pid.ts +827 -0
  967. package/src/gateway/pool-supervisor.ts +1150 -0
  968. package/src/gateway/reload.ts +238 -0
  969. package/src/gateway/restart-stop-exemption.ts +43 -0
  970. package/src/gateway/self-restart.ts +147 -0
  971. package/src/gateway/serve-auth.ts +184 -0
  972. package/src/gateway/serve-config.ts +135 -0
  973. package/src/gateway/service.ts +361 -0
  974. package/src/gateway/shutdown-report.ts +47 -0
  975. package/src/gateway/shutdown-sequence.ts +70 -0
  976. package/src/gateway/stop-drain.ts +299 -0
  977. package/src/gateway/stop-nodes-marker.ts +151 -0
  978. package/src/gateway/transport-factory.ts +53 -0
  979. package/src/gateway/watchdog.ts +622 -0
  980. package/src/gateway/web-dist.ts +1155 -0
  981. package/src/hub/client-protocol.ts +43 -0
  982. package/src/hub/derive-origins.ts +193 -0
  983. package/src/hub/hub-wiring.ts +310 -0
  984. package/src/hub/inbound-control.ts +432 -0
  985. package/src/hub/join-policy.ts +75 -0
  986. package/src/hub/join-store.ts +243 -0
  987. package/src/hub/node-credential-store.ts +295 -0
  988. package/src/hub/node-state.ts +279 -0
  989. package/src/hub/node-url.ts +33 -0
  990. package/src/hub/outbound-client.ts +509 -0
  991. package/src/hub/outbound-wiring.ts +168 -0
  992. package/src/hub/pairing-code.ts +27 -0
  993. package/src/hub/registry.ts +575 -0
  994. package/src/hub/runtime.ts +599 -0
  995. package/src/hub/secret-store.ts +571 -0
  996. package/src/hub/server.ts +1032 -0
  997. package/src/hub/snapshot-policy.ts +67 -0
  998. package/src/hub/types.ts +258 -0
  999. package/src/i18n/index.ts +94 -0
  1000. package/src/i18n/messages/en.ts +1462 -0
  1001. package/src/i18n/messages/zh-CN.ts +1323 -0
  1002. package/src/mock/scenarios.ts +165 -0
  1003. package/src/node/node-auto-resume.ts +264 -0
  1004. package/src/node/node-drain.ts +520 -0
  1005. package/src/node/node-identity.ts +240 -0
  1006. package/src/node/node-resume.ts +511 -0
  1007. package/src/node/resume-scan.ts +97 -0
  1008. package/src/node/token-derive.ts +504 -0
  1009. package/src/observability/logging.ts +72 -0
  1010. package/src/observability/observability-wiring.ts +82 -0
  1011. package/src/observability/startup-timing.ts +151 -0
  1012. package/src/observability/trace-wiring.ts +250 -0
  1013. package/src/observability/usage-pricing.ts +80 -0
  1014. package/src/plugin/eval-wiring.ts +175 -0
  1015. package/src/plugin/feishu-wiring.ts +250 -0
  1016. package/src/plugin/mcp-wiring.ts +200 -0
  1017. package/src/plugin/plugin-config.ts +491 -0
  1018. package/src/plugin/plugin-host-assembly.ts +448 -0
  1019. package/src/plugin/plugin-lifecycle.ts +130 -0
  1020. package/src/plugin/plugin-loader.ts +788 -0
  1021. package/src/plugin/plugin-manifest.ts +1936 -0
  1022. package/src/plugin/plugin-selection.ts +200 -0
  1023. package/src/plugin/plugin-surface.ts +207 -0
  1024. package/src/plugin/plugin-watch.ts +114 -0
  1025. package/src/rpc/http-client.ts +579 -0
  1026. package/src/rpc/index.ts +34 -0
  1027. package/src/rpc/local-client.ts +55 -0
  1028. package/src/rpc/types.ts +125 -0
  1029. package/src/run/connect-run-wait.ts +544 -0
  1030. package/src/run/durable-wiring.ts +133 -0
  1031. package/src/run/lease-service.ts +510 -0
  1032. package/src/run/run-control.ts +160 -0
  1033. package/src/run/run-record-store-factory.ts +89 -0
  1034. package/src/runtime/agent-activity-watch.ts +335 -0
  1035. package/src/runtime/agent-assembly.ts +818 -0
  1036. package/src/runtime/agent-events-bridge.ts +86 -0
  1037. package/src/runtime/bash-job-delivery.ts +291 -0
  1038. package/src/runtime/bootstrap-connect.ts +644 -0
  1039. package/src/runtime/bootstrap-types.ts +303 -0
  1040. package/src/runtime/bootstrap.ts +1020 -0
  1041. package/src/runtime/bus-source.ts +62 -0
  1042. package/src/runtime/gc-assembly.ts +214 -0
  1043. package/src/runtime/local-rpc-surface.ts +301 -0
  1044. package/src/runtime/model-registry-wiring.ts +653 -0
  1045. package/src/runtime/node-health-watch.ts +484 -0
  1046. package/src/runtime/node-restart.ts +444 -0
  1047. package/src/runtime/process-handlers.ts +164 -0
  1048. package/src/runtime/provider-factory.ts +86 -0
  1049. package/src/runtime/reasoning.ts +47 -0
  1050. package/src/runtime/repl-context.ts +234 -0
  1051. package/src/runtime/runtime-notice-hook.ts +357 -0
  1052. package/src/runtime/runtime-notice.ts +273 -0
  1053. package/src/runtime/session-id.ts +15 -0
  1054. package/src/runtime/shutdown-sequence.ts +429 -0
  1055. package/src/runtime/subscription-mute-bridge.ts +99 -0
  1056. package/src/runtime/subscription-rpc-port.ts +597 -0
  1057. package/src/runtime/team-log-bridge.ts +46 -0
  1058. package/src/runtime/tenant-runtime-factory.ts +1838 -0
  1059. package/src/runtime/thinking-agent-bridge.ts +57 -0
  1060. package/src/runtime/tool-output-env.ts +80 -0
  1061. package/src/runtime/vessel-meta.ts +338 -0
  1062. package/src/session/context-composition.ts +147 -0
  1063. package/src/session/context-ratio-source.ts +165 -0
  1064. package/src/session/context-usage.ts +346 -0
  1065. package/src/session/image-delivery.ts +297 -0
  1066. package/src/session/session-control.ts +135 -0
  1067. package/src/session/session-events.ts +144 -0
  1068. package/src/session/session-factory.ts +73 -0
  1069. package/src/session/session-liveness.ts +405 -0
  1070. package/src/session/session-lock-runtime.ts +64 -0
  1071. package/src/session/session-lock.ts +399 -0
  1072. package/src/session/session-resume.ts +282 -0
  1073. package/src/session/system-context.ts +235 -0
  1074. package/src/session/timeline-dual-write.ts +2129 -0
  1075. package/src/session/timeline-session-log.ts +140 -0
  1076. package/src/shared/port-in-use.ts +27 -0
  1077. package/src/shared/socket-inherit-guard.ts +13 -0
  1078. package/src/shared/version.ts +38 -0
  1079. package/src/tools-engine/engine.ts +286 -0
  1080. package/src/tools-engine/entry.ts +757 -0
  1081. package/src/tools-engine/mcp-engine-wiring.ts +354 -0
  1082. package/src/tools-engine/mcp.ts +324 -0
  1083. package/src/tools-engine/supervisor.ts +234 -0
  1084. package/src/tools-engine/tools-list.ts +148 -0
  1085. package/src/tools-engine/validate.ts +395 -0
  1086. package/src/tools-engine/wiring.ts +88 -0
  1087. package/src/tools-engine/worker.ts +110 -0
  1088. package/src/update/background.ts +64 -0
  1089. package/src/update/cache.ts +70 -0
  1090. package/src/update/check.ts +138 -0
  1091. package/src/update/gateway-check.ts +231 -0
  1092. package/src/update/install-detect.ts +125 -0
  1093. package/src/update/manifest.ts +132 -0
  1094. package/src/update/semver.ts +70 -0
  1095. package/src/update/stage.ts +219 -0
@@ -0,0 +1,1838 @@
1
+ /**
2
+ * 每 tenant 执行面(0.5 A-6 / DECISION-010 §13.2)。
3
+ *
4
+ * `buildTenantRuntime()` 构造一个 tenant 的独立 bundle:
5
+ * config / provider / session / runStore / 共享 pluginHost + plugins /
6
+ * trace / metrics / redactor / sessionControl / feishu / MCP。
7
+ * Stage 4:bundle 不持长期 WorkingContext / ExecutionUnit;profile 注册到传入的
8
+ * per-node `Runtime`,`bundle.runtime` 是按 session 解析 EU 的门面。
9
+ *
10
+ * 一个 node 恰好构造一个 bundle(`--serve` 与本地模式共用),它是唯一执行面:
11
+ * 单 EventStream / SessionStore / PluginHost / MetricsControl / scheduler。
12
+ *
13
+ * @module vessel/tenant-runtime-factory
14
+ */
15
+
16
+ import { join } from 'node:path';
17
+ import { createInboxMemberBodyContribution, type ModelRefErrorInfo } from '@vessel-agent/agent';
18
+ import {
19
+ deriveSessionMeta,
20
+ FileProjectionCache,
21
+ isPlaceholderTitle,
22
+ } from '@vessel-agent/core/session';
23
+ import type { EngineClient } from '@vessel-agent/engine-client';
24
+ import {
25
+ type ConfigSources,
26
+ DEFAULT_TIMELINE_OPTIONS,
27
+ type DefaultModelIdentity,
28
+ type EnvInjectionConfig,
29
+ resolveEnvCadence,
30
+ resolveEnvChannel,
31
+ type VesselConfig,
32
+ } from '../../packages/config/src/index';
33
+ import {
34
+ alignMessageSeqs,
35
+ appendCompactionIndex,
36
+ appendCompactionStub,
37
+ buildCompactionIndexEntry,
38
+ type CompactionIndexEntry,
39
+ type ContextSummarizer,
40
+ createDefaultTraceRedactor,
41
+ createProjectionCursor,
42
+ createResumeMarkerRegistry,
43
+ createRunJournalFactory,
44
+ createSessionBreaker,
45
+ type EventStream,
46
+ estimateTokens,
47
+ extendProjection,
48
+ formatCompactionStub,
49
+ InProcessScheduler,
50
+ installPluginsIntoHost,
51
+ type LLMProvider,
52
+ type Logger,
53
+ MemoryPluginHost,
54
+ MemoryWorkingContext,
55
+ type Message,
56
+ noopLogger,
57
+ type Plugin,
58
+ type PluginHost,
59
+ type PluginSurfaceKind,
60
+ type ProjectionCursor,
61
+ type ResumeMarkerRegistryState,
62
+ type RunEvent,
63
+ type RunJournalFactory,
64
+ type RunnableAgent,
65
+ type RunRecordStore,
66
+ type Runtime,
67
+ type RuntimePermissionConfig,
68
+ type Scheduler,
69
+ type SessionStore,
70
+ sessionDirPath,
71
+ startDeadline,
72
+ type TenantPaths,
73
+ type TenantRuntimeProfile,
74
+ type TraceRedactor,
75
+ } from '../../packages/core/src/index';
76
+ import { TimelineEventLog } from '../../packages/core/src/timeline/read-port';
77
+ import {
78
+ type PluginHostManager,
79
+ runShutdownStep,
80
+ type ShutdownStepEmit,
81
+ } from '../../packages/serve/src/index';
82
+ import { ownerSelfCard } from '../agent/self-card';
83
+ import type { FeishuChannelLike, MetricsControlLike } from '../cli/control-plane-types';
84
+ import { emptyResponsePolicyOf } from '../config/empty-response-settings';
85
+ import { normalizeLegacyToolName } from '../config/legacy-tool-names';
86
+ import { DEFAULT_NEVER_AUTO_APPROVE } from '../config/permission-defaults';
87
+ import { visionSettingsOf } from '../config/vision-settings';
88
+ import { resolveDataDir } from '../data/data-paths';
89
+ import { resolveAgentCwd } from '../data/path-resolution';
90
+ import { reportShutdownFailure } from '../gateway/shutdown-report';
91
+ import type { MockScenarioName } from '../mock/scenarios';
92
+ import {
93
+ createEventStream,
94
+ createMetricsCollector,
95
+ disposeMetrics,
96
+ type MetricsFactory,
97
+ } from '../observability/observability-wiring';
98
+ import { noteStartup, noteStartupMax, timeStartup } from '../observability/startup-timing';
99
+ import {
100
+ composeTraceRedactors,
101
+ installTrace,
102
+ pruneTenantTrace,
103
+ type TraceControl,
104
+ type TraceRecorderFactory,
105
+ } from '../observability/trace-wiring';
106
+ import { createUsagePricing } from '../observability/usage-pricing';
107
+ import { createFeishuFromConfig, stopFeishuChannel } from '../plugin/feishu-wiring';
108
+ import { installMcp, type McpControl, type McpPluginLike } from '../plugin/mcp-wiring';
109
+ import {
110
+ buildPluginConfigMap,
111
+ declarativePluginEntries,
112
+ withPluginConfig,
113
+ } from '../plugin/plugin-config';
114
+ import { registerInProcessPluginEntries } from '../plugin/plugin-host-assembly';
115
+ import { type PluginDescriptor, PluginLoader } from '../plugin/plugin-loader';
116
+ import { resolvePluginSelection, warnExternalPluginsOnce } from '../plugin/plugin-selection';
117
+ import { FileLeaseService } from '../run/lease-service';
118
+ import { closeRunRecordStore, createRunRecordStore } from '../run/run-record-store-factory';
119
+ import { createSessionControl, type SessionControl } from '../session/session-control';
120
+ import { createSessionStore } from '../session/session-factory';
121
+ import { withSessionWriteLock } from '../session/session-lock-runtime';
122
+ import {
123
+ createTimelineDualWrite,
124
+ createTimelineLegacyBroadcastGate,
125
+ type TimelineDualWrite,
126
+ type TimelineLegacyBroadcastGate,
127
+ type TimelinePublication,
128
+ } from '../session/timeline-dual-write';
129
+ import { createTimelineSessionLog, type TimelineSessionLog } from '../session/timeline-session-log';
130
+ import { createMcpEngineFromConfig, type McpEngineShell } from '../tools-engine/mcp-engine-wiring';
131
+ import { syncBasicToolsEngineWiring, syncCallbackToolsEngineWiring } from '../tools-engine/wiring';
132
+ import { createProvider } from './provider-factory';
133
+ import { includeReasoningFor, liveIncludeReasoningFor } from './reasoning';
134
+
135
+ /** 构造一个 tenant 执行面的输入 */
136
+ export interface BuildTenantRuntimeOptions {
137
+ tenantId: string;
138
+ /**
139
+ * Stage 4:per-node Runtime。tenant profile 注册到它,per-session EU 经
140
+ * `getOrCreateExecutionUnit` 取得;bundle 不再自己构造 ExecutionUnit。
141
+ */
142
+ runtime: Runtime;
143
+ /** 已合并 tenant overlay 的配置 */
144
+ config: VesselConfig;
145
+ /**
146
+ * 活配置 env_injection getter(P2 热加载):EU 的 envCadence / envChannel 端口每请求
147
+ * 求值 ⇒ 热改 env_injection 下一请求生效(修启动快照冻结)。缺省 ⇒ 读 options.config
148
+ * 快照(旧 caller 零回归)。
149
+ */
150
+ getEnvInjection?: () => EnvInjectionConfig | undefined;
151
+ /**
152
+ * 活配置 getter(q-subscription-script,hot-gate 同族修复):doc-subscription 插件
153
+ * 安装配置注入 liveConfig(cadence / channel / scripts 每请求求值)。缺省 ⇒ 插件读
154
+ * install 快照(旧 caller 零回归)。
155
+ */
156
+ getLiveConfig?: () => VesselConfig | undefined;
157
+ tenantPaths: TenantPaths;
158
+ /** config.loaded 事件的来源(缺省空) */
159
+ configSources?: ConfigSources;
160
+ /** 用户/项目配置路径(config.get.paths) */
161
+ configPaths?: { user: string; project: string };
162
+ /** tenant overlay 命中的叶子键(config snapshot) */
163
+ tenantOverlayKeys?: string[];
164
+ /** session 写锁(0.15);缺省 memory 后端关闭,其余开启 */
165
+ sessionLocks?: boolean;
166
+ /**
167
+ * 是否安装 trace(本地写意图)。false 时不创建 trace / 不写 events。
168
+ * 默认 false:仅供 --serve 的只读执行面显式开启。
169
+ */
170
+ writeTrace?: boolean;
171
+ /** 启动前按 trace 保留策略 prune;默认 false(本地 bootstrap 自己处理) */
172
+ pruneTrace?: boolean;
173
+ useMock?: boolean;
174
+ /** mock 场景(仅 useMock);缺省时 provider-factory 走 MemoryLLMProvider */
175
+ mockScenario?: MockScenarioName;
176
+ headless?: boolean;
177
+ /**
178
+ * ask:交互 REPL、serve/gateway 与 headless(落盘后挂起)都注册。
179
+ * `ui.askUser: false` 可关闭(0.15)。
180
+ */
181
+ registerAskUser?: boolean;
182
+ loader?: PluginLoader;
183
+ nodeId: string;
184
+ /** host owner 的初始 sessionId;缺省随机 UUID(serve 每 tenant 独立) */
185
+ sessionId?: string;
186
+ metricsFactory?: MetricsFactory;
187
+ traceFactory?: TraceRecorderFactory;
188
+ /** 共享 / 注入的 ext redactor;缺省从 loader 加载 */
189
+ redactor?: TraceRedactor;
190
+ /** 诊断 logger(0.10 R2-14);缺省 noop,CLI / serve 注入 stderr logger */
191
+ logger?: Logger;
192
+ clock?: () => number;
193
+ loadMcpModule?: () => Promise<unknown | null>;
194
+ loadFeishuModule?: () => Promise<unknown | null>;
195
+ feishuTransport?: unknown;
196
+ /**
197
+ * 0.28 F2:渠道成员被 TTL 回收后复活所需的 Team id。
198
+ * Team 由 bootstrap 的 `createAgentServiceWiring` 在 bundle 之后才建出来,
199
+ * 所以这里是晚绑定 getter(与 localHuman / localMember 同口径);缺省不复活。
200
+ */
201
+ resolveFeishuTeamId?: () => string | undefined;
202
+ /**
203
+ * 0.28:飞书渠道执行面所需的 `AgentService`,同样是晚绑定 getter。
204
+ * bundle(含渠道)先于 `createAgentServiceWiring` 构造;渠道在 `start()` 时求值。
205
+ * 缺省时渠道 `start()` 保持显式失败(禁止静默降级)。
206
+ */
207
+ resolveFeishuService?: () => unknown;
208
+ /**
209
+ * tools-engine P2:engine-client(装配层注入)。installPluginsIntoHost 之后按白名单
210
+ * 就地换转发 handler + 喂注册表;缺省 = 不接线(in-process 直执行,库用法零变化)。
211
+ */
212
+ engineClient?: EngineClient;
213
+ }
214
+
215
+ /** 一个 tenant 的完整执行面 */
216
+ export interface TenantRuntimeBundle {
217
+ tenantId: string;
218
+ config: VesselConfig;
219
+ tenantPaths: TenantPaths;
220
+ configSources: ConfigSources;
221
+ configPaths?: { user: string; project: string };
222
+ tenantOverlayKeys: string[];
223
+ provider: LLMProvider;
224
+ providerName: string;
225
+ /** 启动时的 provider 模型快照(装配期一次性消费;热应用后的活值读 config / profile) */
226
+ providerModel: string;
227
+ /**
228
+ * 启动时的缺省模型身份 ref(第 6 修 SPAWN-02):宿主缺省 / spawn 继承用它,
229
+ * 展示面用 providerModel(wire)。热应用后的活值经 applyDefaultModel 下发。
230
+ */
231
+ providerModelRef: string;
232
+ providerBaseUrl: string;
233
+ /**
234
+ * 节点缺省模型热应用入口(P0-1 D4 批准;P1-w2d 泛化到 provider/models 全域,
235
+ * 装配层内部字段,不上 wire、不进 core)。原地改已注册 owner profile 的 `.model`:
236
+ * **新 EU** 创建时即用新值;live EU 的 model 是构造期只读快照(前缀不变量),
237
+ * 续接 run 仍用旧值,换模型须 rotate / 重启。`next` = 校验通过的重载配置:
238
+ * 提供时同步重建 registry 快照 + 清 provider 缓存(多厂商路由 / 凭证 / promptCache
239
+ * 随下一具 body/EU/run 生效);缺省时只改 profile.model(兼容旧调用点)。
240
+ * 不同步 `providerModel` 字段:它只在装配期被解构一次(bootstrap),无运行期消费者。
241
+ */
242
+ applyProviderModel: (model: string, next?: VesselConfig) => void;
243
+ /**
244
+ * P3 收紧(两面重构 §11.1):ModelRef 纯校验(gateway agents/sessions 参数闸)。
245
+ * 未命中注册表且无 legacy 透传 → 结构化错误(code/ref/message/candidates);
246
+ * mock 模式缺省。q-error-e2(§3.6):string 拍扁改结构化透传。
247
+ */
248
+ validateModelRefDetailed?: (ref: string) => ModelRefErrorInfo | undefined;
249
+ /**
250
+ * 缺省模型身份热应用预览(第 6 修 SPAWN-03):registry 存在时注入,
251
+ * config scope 用它按运行期同口径(legacyPresent 单向闸)解析 from/to 身份;
252
+ * mock 模式缺省(runner 回落只读保守口径)。
253
+ */
254
+ previewDefaultModel?: (next: VesselConfig) => DefaultModelIdentity | undefined;
255
+ /**
256
+ * P1-w2d(w1a 接缝):install 之后对 capabilityManifest 非空的 in-process 插件调
257
+ * `registerInProcessPlugin`,把 RPC / 贡献面登记进宿主 PluginRpcRegistry。
258
+ * 由装配层在 `createPluginHostManager` 之后调用(cli gateway / bootstrap local);
259
+ * generic 接线,不依赖具体插件包存在。`config` 用于 enabled / trust_ui 判定。
260
+ * 返回已登记插件的 `plugins.list` 基础行(name = descriptor.name,与 contributions
261
+ * 键 manifest.id 一致是契约 §1 承重):provider 类能力插件不在 bundle.plugins 里,
262
+ * 调用方须把这些行并入 base 列表并按 name 去重,否则贡献面没有行可合并。
263
+ */
264
+ registerInProcessPlugins: (
265
+ manager: PluginHostManager,
266
+ config: VesselConfig,
267
+ ) => Array<{ name: string; enabled: boolean }>;
268
+ /**
269
+ * 生命周期审计(q-plugin-lifecycle §6.1):install 期实际登记的注册面(插件名 → 种类集)。
270
+ * 真源 = 宿主注册行为;catalog / 热应用据此推导 per-capability 生命周期。
271
+ * provider / 工厂类不经 installPluginsIntoHost,缺省(推导按结构判据 restart)。
272
+ */
273
+ pluginSurfaces: ReadonlyMap<string, ReadonlySet<PluginSurfaceKind>>;
274
+ /** tenant 独立事件流(trace / metrics 只订阅它) */
275
+ events: EventStream;
276
+ /** runtime 事件出口;与 tenant 流同一实例 */
277
+ runtimeEvents: EventStream;
278
+ session: SessionStore;
279
+ pluginHost: PluginHost;
280
+ /**
281
+ * 0.27:每 tenant 唯一 `InProcessScheduler`(spec §5.1)。
282
+ * 装配层只在这里构造一次;`AgentService` 的所有执行都经它的 executor。
283
+ */
284
+ scheduler: Scheduler;
285
+ /**
286
+ * per-session 门面:每次 run/resume 按 session_id 解析本 tenant 的
287
+ * ExecutionUnit(Stage 4)。不再是一个长期存活的 EU 实例。
288
+ */
289
+ runtime: RunnableAgent;
290
+ /** ADR-098 C2:本 tenant 的租约服务;memory 后端 / 关闭 sessionLocks 时缺省 */
291
+ leaseService?: FileLeaseService;
292
+ /** 0.34 Stage 3:seeded create(seed=compact)压缩摘要器(与 tenant 上下文共用) */
293
+ summarizer?: ContextSummarizer;
294
+ /** 0.34 S4 / R7:按 session 取带熔断的摘要器(与 `summarizer` 同分桶) */
295
+ summarizerForSession?: (sessionId: string) => ContextSummarizer;
296
+ runStore?: RunRecordStore;
297
+ /**
298
+ * 0.52 S1a:进程退出时武装的续跑标记注册表。
299
+ *
300
+ * 退出路径把标记 arm 进来后,RunJournal 每次保存会话状态都会把它合并回去,
301
+ * 避免 settle 期间被打断 run 的终态保存把标记冲掉。
302
+ */
303
+ resumeMarkers: ResumeMarkerRegistryState;
304
+ /**
305
+ * 0.52 S1c:启动恢复要在「卡片被准入」之后清掉 `resume_after_restart`,
306
+ * 而标记的唯一写口是 RunJournal —— 装配层把工厂一起交出来,
307
+ * 启动侧只用 `transient({ runId: 'manual' }).saveSessionState()` 这一条。
308
+ */
309
+ journalFactory: RunJournalFactory;
310
+ /**
311
+ * 0.18:会话事件**唯一持久化端口**(0.54 stop-write:时间线实现,`events.ndjson` 不再写)。
312
+ *
313
+ * 需要「写 + 读」的几处(停摆会话终态 / 通知注入 / ask 恢复 / 种子消息 / 会话删除)拿它。
314
+ */
315
+ eventLog?: TimelineSessionLog;
316
+ /**
317
+ * 0.54 stop-write:会话事件的**只读口**(`TimelineEventLog`,类型上没有 `append`)。
318
+ *
319
+ * 读方(EU 历史投影 / idle 压缩 / 读回判定 / 两张卡 / `sessions.events` / `event_cursor`)
320
+ * 只拿它;写入只有 `journalFactory` 一条路。memory 后端或只读执行面 ⇒ 字段不存在。
321
+ */
322
+ timelineLog?: TimelineEventLog;
323
+ /**
324
+ * 0.54 A:会话 timeline 双写旁路(ADR-105 §11)。
325
+ *
326
+ * 缺省(`timeline.dual_write` 关 / 没有事件日志)⇒ 字段不存在 ⇒
327
+ * `sessions.get.event_cursor` **不带** timeline 四字段(不报假零)。
328
+ */
329
+ timelineDualWrite?: TimelineDualWrite;
330
+ trace?: TraceControl;
331
+ metrics?: MetricsControlLike;
332
+ /** 组合后的 redactor(core 默认 + ext);live hub / gateway 使用同一实例 */
333
+ redactor: TraceRedactor;
334
+ /** 0.18:未组合的 ext redactor;factory 透传给所有 tenant(缺省无 ext) */
335
+ extRedactor?: TraceRedactor;
336
+ sessionControl: SessionControl;
337
+ /** 本 bundle 使用的插件扫描器(0.12:`gateway.reload` 刷新缓存) */
338
+ pluginLoader: PluginLoader;
339
+ plugins: Plugin[];
340
+ mcpPlugin?: McpPluginLike;
341
+ mcp?: McpControl;
342
+ /** tools-engine P2 批次 2:engine 模式 host shell(bootstrap onReady 重启对账用)。 */
343
+ mcpShell?: McpEngineShell;
344
+ feishu?: FeishuChannelLike;
345
+ /**
346
+ * 幂等关闭。`drain: false` 用于调用方已先 `await gateway.stop()` 的场景:
347
+ * gateway 已完成 interrupt('shutdown') + 5s 等待,避免重复限时等待。
348
+ */
349
+ close(options?: { drain?: boolean }): Promise<void>;
350
+ }
351
+
352
+ function tenantSessionsDbPath(tenantRoot: string): string {
353
+ return join(tenantRoot, 'sessions.db');
354
+ }
355
+
356
+ /**
357
+ * C4(AI 命名):命名约束写在 system 提示词里,输出再经 `sanitizeGeneratedTitle` 清洗。
358
+ * 不新增配置键;模型 / 超时沿用当前 tenant provider。
359
+ */
360
+ const SESSION_TITLE_SYSTEM_PROMPT =
361
+ 'Give this conversation a title: 3-7 words, at most 40 characters. ' +
362
+ "Make it imperative and follow the user's language. " +
363
+ 'No quotes, no markdown, no trailing punctuation. Do not answer the question. ' +
364
+ 'Reply with the title only.';
365
+
366
+ /**
367
+ * C4:命名请求的完成预算(金丝雀终验 issue-②)。
368
+ *
369
+ * 此前是 64:reasoning 模型(deepseek-reasoner / 思考模式 qwen 等)的思维链与正文
370
+ * **共用** max_tokens 预算,64 token 全被思考耗尽 → `content` 为空 → 清洗得空串 →
371
+ * 静默放弃,会话永远卡在 Untitled。标题正文本身 ≤40 字符,2048 给思维链留足余量
372
+ * (与压缩 reduce 的 SUMMARIZER_REDUCE_MAX_TOKENS 同量级);即便仍被耗尽 / 超时,
373
+ * 下面还有派生标题兜底,不再静默放弃。
374
+ */
375
+ const SESSION_TITLE_MAX_TOKENS = 2048;
376
+ /**
377
+ * C4:命名请求的截止时间。命名是 run.completed 后的 fire-and-forget 补名,不阻塞
378
+ * run 终态;reasoning 模型首 token 延迟高,5s 经常不够(超时 = 又一条静默放弃路径),
379
+ * 放宽到与压缩摘要同口径的 15s。
380
+ */
381
+ const SESSION_TITLE_TIMEOUT_MS = 15_000;
382
+
383
+ /** 去掉首尾引号 / 反引号(含中英文引号) */
384
+ function stripWrappingQuotes(value: string): string {
385
+ return value
386
+ .replace(/^["'`“”‘’]+/, '')
387
+ .replace(/["'`“”‘’]+$/, '')
388
+ .trim();
389
+ }
390
+
391
+ /**
392
+ * C4:清洗 AI 生成的标题 —— trim → 去首尾引号 / 反引号 → 去 `Title:` 前缀
393
+ * → 折叠空白 → 去句末标点 → 按码点截 40。返回空串表示放弃(保留派生标题)。
394
+ *
395
+ * 入参容错:provider 可能给 undefined / null(无 content),一律当空串放弃,
396
+ * 绝不把非字符串值 stringify 成 'undefined' 落库。清洗后若仍是占位 / 脏值
397
+ * (空 / 'Untitled' / 'undefined' / 'null')同样放弃 —— 这些绝不能成为会话名。
398
+ */
399
+ export function sanitizeGeneratedTitle(raw: string | undefined | null): string {
400
+ if (typeof raw !== 'string') return '';
401
+ let title = stripWrappingQuotes(raw);
402
+ title = title.replace(/^title\s*[::]\s*/i, '').trim();
403
+ // `Title: "Foo"` 这类组合:去前缀后再剥一次引号。
404
+ title = stripWrappingQuotes(title);
405
+ title = title.replace(/\s+/g, ' ').trim();
406
+ title = title.replace(/[.,;:!?。,;:!?…]+$/u, '').trim();
407
+ const codePoints = Array.from(title);
408
+ title = (codePoints.length > 40 ? codePoints.slice(0, 40).join('') : title).trim();
409
+ return isPlaceholderTitle(title) ? '' : title;
410
+ }
411
+
412
+ /**
413
+ * C4:命名输入 —— 首条真实 user 消息(跳过 `vessel:` 注入与压缩摘要),
414
+ * 取前 500 码点;没有可用输入返回 undefined。
415
+ */
416
+ function firstUserInputForTitle(messages: Message[]): string | undefined {
417
+ for (const message of messages) {
418
+ if (message.role !== 'user') continue;
419
+ if (message.compaction_summary === true) continue;
420
+ if (message.name?.startsWith('vessel:') === true) continue;
421
+ const input = Array.from(message.content).slice(0, 500).join('').trim();
422
+ if (input !== '') return input;
423
+ }
424
+ return undefined;
425
+ }
426
+
427
+ /** 单条消息渲染上限(字符);超出只保留前缀,避免单条工具结果独占分块预算。 */
428
+ const SUMMARIZER_MAX_MESSAGE_CHARS = 12_000;
429
+ const SUMMARIZER_MAX_CHUNK_TOKENS = 48_000;
430
+ const SUMMARIZER_MIN_CHUNK_TOKENS = 2_000;
431
+ const SUMMARIZER_PARTIAL_MAX_TOKENS = 1024;
432
+ const SUMMARIZER_REDUCE_MAX_TOKENS = 2048;
433
+ /** C3:单次摘要请求的上限;超时由 provider 请求自身取消,不阻塞请求组装。 */
434
+ const SUMMARIZER_TIMEOUT_MS = 15_000;
435
+
436
+ /**
437
+ * 压缩摘要的固定段落,按此顺序输出。
438
+ *
439
+ * 为什么固定:压缩后模型只能看到一条 system 摘要,段落稳定才能快速定位
440
+ * 「正在做什么 / 卡在哪 / 关键值是多少」;部分摘要与 reduce 也沿用同一模板,
441
+ * 合并时不会因段落漂移丢信息。摘要文本本身原样进入摘要消息与
442
+ * `message.compaction` 事件,这里只约束模型输出,不做二次改写。
443
+ */
444
+ const SUMMARY_SECTIONS = [
445
+ '目标',
446
+ '当前用户要求(原话)',
447
+ '约束',
448
+ '已完成',
449
+ '进行中',
450
+ '阻塞',
451
+ '决策',
452
+ '相关文件',
453
+ '下一步',
454
+ '关键值',
455
+ ] as const;
456
+
457
+ /** 组装摘要提示:任务说明 + 固定段落 + 必须保留的事实。 */
458
+ function summaryPrompt(task: string): string {
459
+ return [
460
+ task,
461
+ 'Output only the summary. Use exactly these sections in this order, each as a markdown heading "## <section>"; write "(未提及)" under a section with no content:',
462
+ SUMMARY_SECTIONS.map((section) => `## ${section}`).join('\n'),
463
+ "Under 当前用户要求(原话), quote the user's most recent explicit request as close to their original wording as possible.",
464
+ 'Preserve decisions, file paths, tool names and results, and open tasks. Put concrete values (ids, counts, thresholds, paths, versions) under 关键值.',
465
+ ].join(' ');
466
+ }
467
+
468
+ const SUMMARY_SYSTEM_PROMPT = summaryPrompt('Summarize the conversation for context compaction.');
469
+ const PARTIAL_SYSTEM_PROMPT = summaryPrompt(
470
+ 'Summarize this part of a longer conversation for context compaction.',
471
+ );
472
+ const REDUCE_SYSTEM_PROMPT = summaryPrompt(
473
+ 'Combine the ordered partial summaries into one conversation summary for context compaction.',
474
+ );
475
+
476
+ /**
477
+ * 渲染一条消息。`reasoning_content` 不进入摘要(与事件流一致)。
478
+ * tool 结果与 assistant 的工具调用必须带上标识,否则摘要丢失工具名/参数。
479
+ */
480
+ function renderSummarizerMessage(message: Message): string {
481
+ const content = message.content ?? '';
482
+ let rendered: string;
483
+ if (message.role === 'tool') {
484
+ rendered = `[tool:${message.tool_call_id ?? ''}] ${content}`;
485
+ } else if (message.role === 'assistant') {
486
+ const calls = (message.tool_calls ?? []).map(
487
+ (call) => `[tool_call:${call.function?.name ?? ''}] ${call.function?.arguments ?? ''}`,
488
+ );
489
+ rendered = [`[assistant] ${content}`, ...calls].join('\n');
490
+ } else {
491
+ rendered = `[${message.role}] ${content}`;
492
+ }
493
+ return rendered.length > SUMMARIZER_MAX_MESSAGE_CHARS
494
+ ? `${rendered.slice(0, SUMMARIZER_MAX_MESSAGE_CHARS)}\n[truncated]`
495
+ : rendered;
496
+ }
497
+
498
+ /** 按渲染后文本的估算 token 分组;单条超出预算时独占一块。 */
499
+ function chunkSummarizerTranscript(rendered: string[], budget: number): string[][] {
500
+ const chunks: string[][] = [];
501
+ let current: string[] = [];
502
+ let currentTokens = 0;
503
+ for (const text of rendered) {
504
+ const tokens = estimateTokens(text);
505
+ if (current.length > 0 && currentTokens + tokens > budget) {
506
+ chunks.push(current);
507
+ current = [];
508
+ currentTokens = 0;
509
+ }
510
+ current.push(text);
511
+ currentTokens += tokens;
512
+ }
513
+ if (current.length > 0) chunks.push(current);
514
+ return chunks;
515
+ }
516
+
517
+ /** 截断到估算 token 预算(预算按 token,字符数不固定)。 */
518
+ function truncateToTokenBudget(text: string, maxTokens: number): string {
519
+ if (estimateTokens(text) <= maxTokens) return text;
520
+ let low = 0;
521
+ let high = text.length;
522
+ while (low < high) {
523
+ const mid = Math.ceil((low + high) / 2);
524
+ if (estimateTokens(text.slice(0, mid)) <= maxTokens) low = mid;
525
+ else high = mid - 1;
526
+ }
527
+ return text.slice(0, low);
528
+ }
529
+
530
+ /** C3:把当前窗口的已有摘要并入 system 提示,要求合并而非重写。 */
531
+ function withPreviousSummary(system: string, previous: string | undefined): string {
532
+ if (previous === undefined || previous.trim() === '') return system;
533
+ return `${system}\n\nMerge the existing summary; do not drop its facts.\n\nExisting summary:\n${previous}`;
534
+ }
535
+
536
+ /**
537
+ * 用当前 provider 生成真实上下文摘要(0.6.1 E3,0.14.4 分块)。
538
+ *
539
+ * 单块:一次摘要调用(输出预算见 C3;有旧摘要时合并)。
540
+ * 多块:每块一次部分摘要(≤1024),再 reduce 一次(同一输出预算,只在此合并旧摘要)。
541
+ * 分块失败写占位标记继续;reduce 失败拼接部分摘要;全部失败返回空串,
542
+ * 由 core 回退占位摘要。
543
+ */
544
+ export function createContextSummarizer(
545
+ resolve: () => { provider: LLMProvider; model: string },
546
+ ): ContextSummarizer {
547
+ const summarize = async (system: string, user: string, maxTokens: number): Promise<string> => {
548
+ // P1-w2d:消费与 EU 同一 resolveModel 结果(mock 为常量闭包)——默认模型热应用
549
+ // 后压缩跟随同一厂商,不加独立压缩模型字段(契约 §2.5)。
550
+ const { provider, model } = resolve();
551
+ // 0.64:摘要调用很可能发生在「只有这一次挂起的 await」的时刻(上下文压缩期间
552
+ // 没有别的定时器),`AbortSignal.timeout` 在这种空闲事件循环里可能不触发 ⇒ 挂死。
553
+ const deadline = startDeadline(SUMMARIZER_TIMEOUT_MS);
554
+ try {
555
+ const response = await provider.chat({
556
+ model,
557
+ messages: [
558
+ { role: 'system', content: system },
559
+ { role: 'user', content: user },
560
+ ],
561
+ max_tokens: maxTokens,
562
+ temperature: 0,
563
+ signal: deadline.signal,
564
+ });
565
+ return typeof response.content === 'string' ? response.content : '';
566
+ } finally {
567
+ deadline.dispose();
568
+ }
569
+ };
570
+
571
+ return async (messages, options) => {
572
+ const rendered = messages.map(renderSummarizerMessage);
573
+ const chunkBudget = Math.min(
574
+ SUMMARIZER_MAX_CHUNK_TOKENS,
575
+ Math.max(SUMMARIZER_MIN_CHUNK_TOKENS, Math.floor(options.maxTokens / 8)),
576
+ );
577
+ const chunks = chunkSummarizerTranscript(rendered, chunkBudget);
578
+ if (chunks.length === 0) return '';
579
+
580
+ // C3:输出预算随被移除内容的规模增长;无 removedTokens 时沿用旧上限。
581
+ const maxOutputTokens =
582
+ options.removedTokens !== undefined
583
+ ? Math.max(2048, Math.min(8192, Math.floor(options.removedTokens / 8)))
584
+ : Math.max(128, Math.min(options.maxTokens, SUMMARIZER_REDUCE_MAX_TOKENS));
585
+
586
+ if (chunks.length === 1) {
587
+ try {
588
+ return await summarize(
589
+ withPreviousSummary(SUMMARY_SYSTEM_PROMPT, options.previousSummary),
590
+ chunks[0]?.join('\n\n') ?? '',
591
+ maxOutputTokens,
592
+ );
593
+ } catch {
594
+ return '';
595
+ }
596
+ }
597
+
598
+ const partials: string[] = [];
599
+ let succeeded = 0;
600
+ for (const [index, chunk] of chunks.entries()) {
601
+ try {
602
+ partials.push(
603
+ await summarize(PARTIAL_SYSTEM_PROMPT, chunk.join('\n\n'), SUMMARIZER_PARTIAL_MAX_TOKENS),
604
+ );
605
+ succeeded += 1;
606
+ } catch {
607
+ partials.push(`[partial summary unavailable: chunk ${index + 1}]`);
608
+ }
609
+ }
610
+ if (succeeded === 0) return '';
611
+
612
+ const joined = partials.join('\n\n');
613
+ try {
614
+ return await summarize(
615
+ withPreviousSummary(REDUCE_SYSTEM_PROMPT, options.previousSummary),
616
+ joined,
617
+ maxOutputTokens,
618
+ );
619
+ } catch {
620
+ return truncateToTokenBudget(joined, maxOutputTokens);
621
+ }
622
+ };
623
+ }
624
+
625
+ /** 每 tenant 的上下文配置(含真实 summarizer);供 owner 与成员共用。 */
626
+ function contextConfigFor(config: VesselConfig, summarizer: ContextSummarizer | undefined) {
627
+ return {
628
+ maxTokens: config.context?.maxTokens,
629
+ maxMessages: config.context?.maxMessages,
630
+ autoCompact: config.context?.autoCompact,
631
+ compactThreshold: config.context?.compactThreshold,
632
+ // q-tool-result-whitelist:原样透传(undefined ⇒ core 内置默认;显式 [] ⇒ 关闭)。
633
+ ...(config.context?.toolResultWhitelist !== undefined
634
+ ? { toolResultWhitelist: config.context.toolResultWhitelist }
635
+ : {}),
636
+ ...(summarizer !== undefined ? { summarizer } : {}),
637
+ };
638
+ }
639
+
640
+ /**
641
+ * 0.8.2 Wave 2B1:runtime 共用的 resolved 权限配置。
642
+ *
643
+ * 老配置兼容:用户 YAML 的 `auto_approve` / `never_auto_approve` 里可能仍写着工具**旧名**
644
+ * (`ask_user` / `pii.reveal`)—— 统一由 `normalizeLegacyToolName` 换算成现行名。
645
+ *
646
+ * 表在 `src/legacy-tool-names.ts`(适配层),真源是 core 的
647
+ * `packages/core/src/runtime/tool-name.ts::TOOL_NAME_ALIASES`(注册表的别名解析与这里同源)。
648
+ * 不换算的后果正是 L-011 那类事故的另一面:注册侧改了、选择侧不认,而且没有报错,
649
+ * 用户当年选的「always / never」静默失效。
650
+ */
651
+ export function resolveRuntimePermission(
652
+ config: VesselConfig,
653
+ headless: boolean,
654
+ ): RuntimePermissionConfig {
655
+ return {
656
+ default: headless ? 'allow' : 'ask',
657
+ // E7:配置持久化的 always 规则 + 运行时始终免确认的 ask / notify(非阻塞、无副作用)。
658
+ autoApprove: [
659
+ ...new Set([
660
+ ...(config.permission?.autoApprove ?? []).map(normalizeLegacyToolName),
661
+ 'ask',
662
+ 'notify',
663
+ ]),
664
+ ],
665
+ // 0.27:配置级保险;用户显式配置时以其值为准(与 autoApprove 语义一致,不合并默认)。
666
+ // perm-F1:缺省名单单一真源 `DEFAULT_NEVER_AUTO_APPROVE`(含 pii_reveal)——
667
+ // 热应用(replaceRules 整体替换)从这里取缺省,必须与成员 wiring 同源。
668
+ neverAutoApprove: (config.permission?.neverAutoApprove ?? [...DEFAULT_NEVER_AUTO_APPROVE]).map(
669
+ normalizeLegacyToolName,
670
+ ),
671
+ };
672
+ }
673
+
674
+ /** `drainActiveRuns` 结果:无 run / 已终态 / 超时 / 运行时无 interrupt */
675
+ export type DrainOutcome = 'idle' | 'interrupted' | 'timeout' | 'unsupported';
676
+
677
+ export interface DrainActiveRunsOptions {
678
+ /** active run id 集合;run 终态事件由订阅方删除 */
679
+ activeRuns: Set<string>;
680
+ /** ExecutionUnit.interrupt */
681
+ interrupt?: (reason: 'shutdown') => void;
682
+ logger: Logger;
683
+ tenantId: string;
684
+ timeoutMs?: number;
685
+ /** 测试注入:等待下一次轮询 */
686
+ sleep?: (ms: number) => Promise<void>;
687
+ now?: () => number;
688
+ }
689
+
690
+ /**
691
+ * 0.10 R2-18:关闭前的软中断。调用方先 `interrupt('shutdown')`(checkpoint 落
692
+ * interrupted,可 `--resume-run`),再限时等待 active run 从集合中消失。
693
+ * 超时只 warning,不阻断关闭。
694
+ */
695
+ export async function drainActiveRuns(options: DrainActiveRunsOptions): Promise<DrainOutcome> {
696
+ if (options.activeRuns.size === 0) return 'idle';
697
+ if (!options.interrupt) {
698
+ options.logger.warn('shutdown drain: no interrupt hook for active runs', {
699
+ runs: options.activeRuns.size,
700
+ });
701
+ return 'unsupported';
702
+ }
703
+
704
+ options.interrupt('shutdown');
705
+
706
+ const timeoutMs = options.timeoutMs ?? 5000;
707
+ const sleep =
708
+ options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
709
+ const now = options.now ?? Date.now;
710
+ const deadline = now() + timeoutMs;
711
+
712
+ while (options.activeRuns.size > 0 && now() < deadline) {
713
+ await sleep(25);
714
+ }
715
+ if (options.activeRuns.size > 0) {
716
+ options.logger.warn('shutdown drain timed out', {
717
+ runs: [...options.activeRuns],
718
+ });
719
+ return 'timeout';
720
+ }
721
+ return 'interrupted';
722
+ }
723
+
724
+ /**
725
+ * 把一次 timeline 发布还原成事件流里的 `RunEvent`(ADR-105 §3 I2 的新发布点)。
726
+ *
727
+ * 形状与旧链路广播的事件同形(`type` / `run_id` / `ts` / `data`):UI 与订阅者不需要知道
728
+ * 这条事件是从哪条链路来的。**不写 `seq` 字段** —— `RunEvent.seq` 是 trace 的 run 内序号,
729
+ * timeline seq 是会话内持久序号,两者不是一套编号(ADR-105 §9 R7),混用会造出第二套 seq。
730
+ */
731
+ function publicationToRunEvent(publication: TimelinePublication): RunEvent {
732
+ const data = publication.data;
733
+ return {
734
+ type: publication.type,
735
+ run_id: publication.run_id,
736
+ ts: publication.ts,
737
+ data: (data === undefined || data === null ? {} : data) as RunEvent['data'],
738
+ };
739
+ }
740
+
741
+ /**
742
+ * 构造一个 tenant 的独立执行面。
743
+ * 失败时释放本函数获取的锁;调用方负责释放传入的锁。
744
+ */
745
+ export async function buildTenantRuntime(
746
+ options: BuildTenantRuntimeOptions,
747
+ ): Promise<TenantRuntimeBundle> {
748
+ const { tenantId, config, tenantPaths } = options;
749
+ const useMock = options.useMock ?? false;
750
+ const headless = options.headless ?? false;
751
+ const loader = options.loader ?? new PluginLoader();
752
+ const logger = options.logger ?? noopLogger;
753
+
754
+ const backend = config.session?.backend ?? 'file';
755
+ if (options.pruneTrace === true) {
756
+ try {
757
+ await pruneTenantTrace({ config, tenantPaths });
758
+ } catch (error) {
759
+ console.warn(
760
+ `⚠ Failed to prune trace for tenant "${tenantId}": ${
761
+ error instanceof Error ? error.message : error
762
+ }`,
763
+ );
764
+ }
765
+ }
766
+
767
+ // ADR-098 C2:SessionLease 接管 session 级写排他;memory 后端或无写意图时缺省
768
+ // 不创建(EU / 事件日志端口缺省为 no-op,行为等同现状)。
769
+ const leaseConfig = (config as { lease?: { ttlMs?: number; renewMs?: number } }).lease;
770
+ const sessionLocksEnabled = options.sessionLocks ?? backend !== 'memory';
771
+ const leaseService = sessionLocksEnabled
772
+ ? new FileLeaseService({
773
+ tenantDir: tenantPaths.root,
774
+ tenantId,
775
+ ...(leaseConfig?.ttlMs !== undefined ? { ttlMs: leaseConfig.ttlMs } : {}),
776
+ ...(leaseConfig?.renewMs !== undefined ? { renewMs: leaseConfig.renewMs } : {}),
777
+ logger,
778
+ })
779
+ : undefined;
780
+
781
+ const runStore = createRunRecordStore(config, {
782
+ tenantRunsDir: tenantPaths.runs_dir,
783
+ tenantId,
784
+ });
785
+ // §7.4 legacyPresent:provider.* 有非 default 层来源(与 registry-store 同口径)。
786
+ const legacyPresent = Object.entries(options.configSources ?? {}).some(
787
+ ([key, source]) => (key === 'provider' || key.startsWith('provider.')) && source !== 'default',
788
+ );
789
+ const resolvedProvider = await timeStartup(
790
+ 'runtime.provider',
791
+ // q-credential-hot-reload:活配置端口透传 registry wiring(reasoning-unify
792
+ // getLiveConfig 同族)⇒ legacy 链凭证热改下一请求生效,不依赖 applyConfig 差分。
793
+ createProvider(
794
+ config,
795
+ loader,
796
+ useMock,
797
+ options.mockScenario,
798
+ legacyPresent,
799
+ options.getLiveConfig,
800
+ ),
801
+ );
802
+ const { provider, providerName, providerModel, providerModelRef, providerBaseUrl, registry } =
803
+ resolvedProvider;
804
+ // 0.51:opt-in 计价;两面重构 §10.1 合并视图(entry.pricing 按 wire 名覆盖 pricing.models)。
805
+ const pricing = createUsagePricing(config.pricing, config.models?.entries);
806
+
807
+ // P1-w2d:summarizer 与 EU 消费同一 resolveModel(默认热应用后压缩跟随);
808
+ // mock 无 registry → 常量闭包,与今天逐字等价。
809
+ const summarizer = createContextSummarizer(
810
+ registry !== undefined
811
+ ? () => registry.resolveModel(undefined)
812
+ : () => ({ provider, model: providerModel }),
813
+ );
814
+ // R7:熔断按 session 分桶;owner / 成员共享同一份计数,`force` 由 core 传入。
815
+ const summarizerForSession =
816
+ summarizer !== undefined ? createSessionBreaker(summarizer) : undefined;
817
+ // 0.54 B(ADR-105 §3 I2 端到端):timeline 写入开启时,旧链路的广播**降级为发送缓冲**。
818
+ //
819
+ // 顺序有讲究:闸门必须在 `events` 第一次被交出去之前包好,否则早退的订阅者会拿到
820
+ // 未受控的流。显式 `dual_write: false`(0.54 cutover 起不再是默认)⇒ 不建闸门、不包流。
821
+ const timelineOptions = config.timeline ?? DEFAULT_TIMELINE_OPTIONS;
822
+ const writesEventLog = options.writeTrace === true && backend !== 'memory';
823
+ // 只有「真会装双写端口」时才装闸门:没有事件日志 / memory 后端 / 开关关 ⇒ 一个都不建。
824
+ const dualWriteActive = writesEventLog && timelineOptions.dualWrite === true;
825
+ const broadcastGate: TimelineLegacyBroadcastGate | undefined = dualWriteActive
826
+ ? createTimelineLegacyBroadcastGate({ logger })
827
+ : undefined;
828
+ const rawEvents = createEventStream(config);
829
+ const events: EventStream =
830
+ broadcastGate !== undefined ? broadcastGate.wrap(rawEvents) : rawEvents;
831
+ // 0.27(spec §5.1):每 tenant 唯一 scheduler,装配层只在此处构造。
832
+ // 所有 body / owner / 成员的执行都经它的 executor,不再有第二套队列。
833
+ // 未配置项沿用 core 缺省(无并发上限 / 队列 100 / per-body 串行),符合 spec §5.1「默认无上限」。
834
+ // 注意:`DEFAULT_SCHEDULER_OPTIONS.maxConcurrency` 仍是 1(0.2 遗留),这里**不用**它兜底。
835
+ const scheduler = new InProcessScheduler({
836
+ ...(config.scheduler?.maxConcurrency !== undefined
837
+ ? { maxConcurrency: config.scheduler.maxConcurrency }
838
+ : {}),
839
+ ...(config.scheduler?.maxQueueSize !== undefined
840
+ ? { maxQueueSize: config.scheduler.maxQueueSize }
841
+ : {}),
842
+ ...(config.scheduler?.perBodySerial !== undefined
843
+ ? { perBodySerial: config.scheduler.perBodySerial }
844
+ : {}),
845
+ events,
846
+ });
847
+
848
+ // 0.10 R2-18:只跟踪真实在跑的 run(包装 `ExecutionUnit.run/resume`),
849
+ // 不从事件推断——测试 / gateway 也会发布合成的 run.started,按事件跟踪会让
850
+ // shutdown 白等 5s。
851
+ const activeRuns = new Set<string>();
852
+ let activeRunSeq = 0;
853
+ const trackActive = <T>(promise: Promise<T>): Promise<T> => {
854
+ activeRunSeq += 1;
855
+ const token = `inflight-${activeRunSeq}`;
856
+ activeRuns.add(token);
857
+ void promise
858
+ .finally(() => {
859
+ activeRuns.delete(token);
860
+ })
861
+ .catch(() => {
862
+ // 原 promise 的拒绝由调用方处理;这里只为清理跟踪标记
863
+ });
864
+ return promise;
865
+ };
866
+
867
+ // 事件流由 cli 的 `createGatewayEventHub({ streams: [...] })` 直接消费,
868
+ // bundle 不再向 hub 注册(T3 单流)。
869
+ const session = createSessionStore(config.session, {
870
+ tenantSessionsDir: tenantPaths.sessions_dir,
871
+ tenantSessionsDbPath: tenantSessionsDbPath(tenantPaths.root),
872
+ tenantId,
873
+ });
874
+ // 0.54 stop-write:**会话事件的唯一持久化落点 = 时间线**。
875
+ //
876
+ // `sessions/<id>/events.ndjson` 从 0.54 起就不再被写;0.55 连它的读写代码一起删掉了
877
+ // (旧格式会话 = `legacy_session_unsupported`,见 `timeline/legacy-format.ts`),
878
+ // `SessionEventLog` 这份实现也不存在了。所以装配层没有任何旧日志对象可建。
879
+ //
880
+ // `timeline.dual_write` 开关同样没有意义:时间线是**唯一**落盘口,关掉它就是关掉
881
+ // 整个事件的持久化。显式写 `false` 的安装会拿到一条警告(不是静默降级)。
882
+ if (writesEventLog && timelineOptions.dualWrite === false) {
883
+ logger.warn('timeline.dual_write=false is ignored (timeline is the only durable event sink)', {
884
+ tenant_id: tenantId,
885
+ });
886
+ }
887
+ // 0.54(ADR-105 §3 I2):`onPublish` 是**唯一的对外发布出口** —— 写者在 WAL/块
888
+ // fsync 之后才回调它,所以「UI 能看见的事件」的可见性由 timeline 的持久化决定。
889
+ // `publicationGate` 把那条广播扣成发送缓冲:写者 fsync 之后才放行给 UI。
890
+ const timelineDualWrite: TimelineDualWrite | undefined = writesEventLog
891
+ ? createTimelineDualWrite({
892
+ sessionsDir: tenantPaths.sessions_dir,
893
+ dualWrite: true,
894
+ ...(timelineOptions.chunkFlushMs !== undefined
895
+ ? { chunkFlushMs: timelineOptions.chunkFlushMs }
896
+ : {}),
897
+ ...(timelineOptions.archiveIntervalMs !== undefined
898
+ ? { archiveIntervalMs: timelineOptions.archiveIntervalMs }
899
+ : {}),
900
+ // 发布点:写者 fsync 之后回调 ⇒ 发到**底层**事件流(不能回到闸门,否则自我循环)。
901
+ onPublish: (publication) => {
902
+ try {
903
+ rawEvents.publish(publicationToRunEvent(publication));
904
+ } catch {
905
+ // 发布通道失败不影响落盘(数据已 fsync;实现侧还会再兜一层指标)
906
+ }
907
+ },
908
+ ...(broadcastGate !== undefined ? { publicationGate: broadcastGate } : {}),
909
+ logger,
910
+ })
911
+ : undefined;
912
+ timelineDualWrite?.installExitFlush();
913
+ /**
914
+ * 0.54 stop-write:**读口**(没有 `append`)。
915
+ *
916
+ * 所有读链路(EU 的 `loadStoredHistory` / `archiveReadbackAvailability`、idle 压缩、
917
+ * `context_usage` / `system_context` 两张卡、`sessions.events`、`event_cursor`)从这里
918
+ * 读;写入只有 `journalFactory`(经时间线写者)。
919
+ *
920
+ * `settle` 接双写旁路的 `flushSession`:块级 WAL 的活动块在内存里,不等它封块就读会
921
+ * 少一段在飞 chunk。旧格式会话会抛 `legacy_session_unsupported` —— 读口自己吞掉并降级为
922
+ * 「直接读磁盘」,随后由 `read()` / `heads()` 自己把这条错误报给用户(不能当成空会话)。
923
+ */
924
+ const timelineLog: TimelineEventLog | undefined = writesEventLog
925
+ ? new TimelineEventLog({
926
+ dir: tenantPaths.sessions_dir,
927
+ logger,
928
+ ...(timelineDualWrite !== undefined
929
+ ? {
930
+ settle: async (sessionId?: string) => {
931
+ if (sessionId === undefined) return;
932
+ await timelineDualWrite.flushSession(sessionId);
933
+ },
934
+ }
935
+ : {}),
936
+ })
937
+ : undefined;
938
+ /**
939
+ * 0.54 stop-write:**唯一持久化端口**(读口 + 时间线写者拼起来的 `SessionEventLogPort`)。
940
+ *
941
+ * 需要写的几处(停摆会话终态 / 通知注入 / ask 恢复 / 种子消息 / 会话删除)拿它;
942
+ * EU 的读路径只拿上面那个没有 `append` 的读口 —— 权限差别在类型上。
943
+ */
944
+ const eventLog: TimelineSessionLog | undefined =
945
+ timelineLog !== undefined
946
+ ? createTimelineSessionLog({
947
+ read: timelineLog,
948
+ ...(timelineDualWrite !== undefined ? { dualWrite: timelineDualWrite } : {}),
949
+ })
950
+ : undefined;
951
+ const sessionControl = createSessionControl({
952
+ session,
953
+ paths: tenantPaths,
954
+ events,
955
+ ...(runStore ? { runStore } : {}),
956
+ ...(eventLog ? { eventLog } : {}),
957
+ });
958
+
959
+ // ── 插件 ──────────────────────────────────────
960
+ const declarativePlugins = declarativePluginEntries(config);
961
+ /** E1:插件名 → 安装配置(显式 plugins[].config 覆盖声明式条目) */
962
+ const pluginConfigs = buildPluginConfigMap(
963
+ config.plugins,
964
+ declarativePlugins,
965
+ resolveAgentCwd(config),
966
+ resolveDataDir(config),
967
+ config.envInjection,
968
+ options.getLiveConfig,
969
+ );
970
+ const pluginSelection = resolvePluginSelection(
971
+ loader,
972
+ config.plugins,
973
+ Boolean(process.env.VESSEL_DEBUG),
974
+ declarativePlugins,
975
+ );
976
+ // 默认集里的外部插件以完整进程权限运行:启动时告警一次(stderr)。
977
+ warnExternalPluginsOnce(pluginSelection.external);
978
+ const defaultPluginNames = pluginSelection.names;
979
+
980
+ const plugins: Plugin[] = [];
981
+ // P1-w2d:capabilityManifest 非空的 in-process 插件(非 provider 类;provider 类由
982
+ // wiring 收集)——install 后经 bundle.registerInProcessPlugins 登记 RPC / 贡献面。
983
+ const inProcessCapabilityPlugins: Array<{ descriptor: PluginDescriptor; plugin: Plugin }> = [];
984
+ const pluginLoadEvents: Array<{
985
+ type: 'plugin.loaded' | 'plugin.failed';
986
+ data: Record<string, unknown>;
987
+ }> = [];
988
+ for (const name of defaultPluginNames) {
989
+ const descriptor = loader.list().find((candidate) => candidate.name === name);
990
+ const category = descriptor?.category ?? 'unknown';
991
+ // 逐个插件计时(明细行里一条一个 key):插件全是动态 import,谁慢要能指名道姓。
992
+ const pluginStartedAt = performance.now();
993
+ const plugin = await loader.load(name);
994
+ noteStartup(`plugin.load.${name}`, performance.now() - pluginStartedAt);
995
+ noteStartupMax(`plugin.load.max`, performance.now() - pluginStartedAt);
996
+ if (plugin) {
997
+ // E1:配置在 install 时透传(host 路径直接传;非 host 路径见 ExecutionUnit)。
998
+ plugins.push(plugin);
999
+ // 收集原始 plugin(withPluginConfig 包装不透传 rpc);登记发生在 manager 创建后。
1000
+ if (descriptor?.mode === 'in-process' && descriptor.capabilityManifest !== undefined) {
1001
+ inProcessCapabilityPlugins.push({ descriptor, plugin });
1002
+ }
1003
+ pluginLoadEvents.push({
1004
+ type: 'plugin.loaded',
1005
+ data: {
1006
+ name: plugin.name,
1007
+ category,
1008
+ version: plugin.version ?? descriptor?.version ?? '',
1009
+ },
1010
+ });
1011
+ } else {
1012
+ pluginLoadEvents.push({
1013
+ type: 'plugin.failed',
1014
+ data: { name, category, reason: 'load_failed' },
1015
+ });
1016
+ }
1017
+ }
1018
+
1019
+ // 0.15:ui.askUser=false 按 tenant 关闭(overlay 生效);无客户端入口不会传 true。
1020
+ if (options.registerAskUser === true && config.ui?.askUser !== false) {
1021
+ const { createAskUserTool } = await import('../../packages/tui/src/renderer/ask-user');
1022
+ plugins.push({
1023
+ name: 'ask-user',
1024
+ version: '0.1.0',
1025
+ description: 'Ask-user interactive tool (ADR-029)',
1026
+ install(host) {
1027
+ host.registerTool(createAskUserTool());
1028
+ },
1029
+ });
1030
+ }
1031
+ // q-human-notify P1:notify 工具(「通知」形,fire-and-forget)。复用同一客户端入口信号
1032
+ // (registerAskUser),独立配置开关 ui.notify(镜像 ui.askUser,缺省 allow)。
1033
+ if (options.registerAskUser === true && config.ui?.notify !== false) {
1034
+ const { createNotifyUserTool } = await import('../../packages/tui/src/renderer/notify-user');
1035
+ plugins.push({
1036
+ name: 'notify-user',
1037
+ version: '0.1.0',
1038
+ description: 'Notify-user fire-and-forget tool (q-human-notify P1)',
1039
+ install(host) {
1040
+ host.registerTool(createNotifyUserTool());
1041
+ },
1042
+ });
1043
+ }
1044
+ // runtime 共用的 resolved 权限配置(0.8.2 Wave 2B1)。
1045
+ const permission = resolveRuntimePermission(config, headless);
1046
+
1047
+ // ── Runtime ───────────────────────────────────
1048
+ const limits = config.limits ?? {};
1049
+ const termination = {
1050
+ maxIterations: config.termination?.maxIterations,
1051
+ maxRuntimeSeconds: config.termination?.maxRuntimeSeconds,
1052
+ };
1053
+ // 0.50:默认 system 完全由用户掌握。未配置时为空串,不注入任何内置 base system
1054
+ // 文本;Self Card 仍由 composeRunSystemPrompt 生成。
1055
+ const systemPrompt = config.agent?.systemPrompt ?? '';
1056
+
1057
+ const contextFactory = () => new MemoryWorkingContext(contextConfigFor(config, summarizer));
1058
+
1059
+ // ── Stage 4:tenant 范围内只安装一次插件 ──────────
1060
+ // 插件安装原本在 ExecutionUnit 构造内;改成 per-session EU 后,同一 tenant 的
1061
+ // 多个 EU 共享一个 PluginHost,安装/init/dispose 只发生一次。
1062
+ const finalPluginHost = new MemoryPluginHost();
1063
+ const installedPlugins = await timeStartup(
1064
+ 'runtime.plugin-install',
1065
+ installPluginsIntoHost({
1066
+ host: finalPluginHost,
1067
+ plugins: plugins.map((plugin) => withPluginConfig(plugin, pluginConfigs[plugin.name])),
1068
+ publish: (event) => events.publish(event),
1069
+ logger,
1070
+ }),
1071
+ );
1072
+ noteStartup('plugin.count', installedPlugins.plugins.length);
1073
+ // 0.51 期 0:`inbox` 的成员面贡献(空壳,`tools()` 返回空数组 ⇒ 工具面与 0.50 逐字相同)。
1074
+ // 注册在 tenant 宿主上而不是 body 上,是因为 `MemberExecutionHost` 握的就是这一个宿主:
1075
+ // spawn 直接 `getMemberBodyContributions()` 读,零新增透传(报告 §3.2)。
1076
+ // 期 1 由 `plugins/inbox/inbox` 用自己的 install() 注册同名贡献,这里那行随之删掉。
1077
+ finalPluginHost.registerMemberBodyContribution(createInboxMemberBodyContribution());
1078
+
1079
+ // ── tools-engine P2:白名单转发接线(install 之后;seams 契约 §3.4)──────────
1080
+ // wireTool 就地换 handler(def 身份不变),不注册新工具 ⇒ spawn 顺序不变式不受影响
1081
+ // (vessel / agent 注册与 body spawn 都在其后)。boundary/config 用本次安装配置重建。
1082
+ // pushRegistry 失败只记日志:engine disabled 时工具 fail-closed,不静默回退 in-process。
1083
+ if (options.engineClient !== undefined) {
1084
+ syncBasicToolsEngineWiring(options.engineClient, finalPluginHost, pluginConfigs['basic-tools']);
1085
+ // 批次 3:ask(ask-user 插件)/ recall / pii_reveal(guardrail-pii 插件)恒 callback。
1086
+ syncCallbackToolsEngineWiring(options.engineClient, finalPluginHost);
1087
+ try {
1088
+ await options.engineClient.pushRegistry();
1089
+ } catch (error) {
1090
+ logger.warn('tools-engine registry push failed at assembly', {
1091
+ message: error instanceof Error ? error.message : String(error),
1092
+ });
1093
+ }
1094
+ }
1095
+
1096
+ // 铁律 1:持久端口只到 Runtime 工厂层;EU 经 journal 写入。
1097
+ // 成员 run 与 tenant run 共用同一工厂 → 成员 run 同样写 RunRecord。
1098
+ // 0.52 S1a:进程退出时武装的续跑标记(每 tenant 一份,与工厂同寿命)。
1099
+ // 装进工厂后,**任何一次**会话状态保存都会把标记合并回去(settle 期间终态保存不会
1100
+ // 把 drain 先写下的标记覆盖掉)。
1101
+ const resumeMarkers = createResumeMarkerRegistry();
1102
+ // 0.56 send-first:投影续算快照的落盘口(`sessions/<id>.projection.json`)。
1103
+ // 与事件日志同目录、与会话壳并列;它是**缓存**(写失败只记日志,读坏就当没有),
1104
+ // 但它是「重启后第一条消息不再整份读」的唯一依据,所以必须由装配层给到 EU。
1105
+ const projectionCache = new FileProjectionCache({
1106
+ dir: tenantPaths.sessions_dir,
1107
+ logger,
1108
+ });
1109
+ const journalFactory = createRunJournalFactory({
1110
+ ...(eventLog !== undefined ? { eventLog } : {}),
1111
+ session,
1112
+ ...(runStore !== undefined ? { runStore } : {}),
1113
+ ...(leaseService !== undefined
1114
+ ? { fenceOf: (kind, key) => leaseService.fenceOf(kind, key) }
1115
+ : {}),
1116
+ logger,
1117
+ resumeMarkers,
1118
+ projectionCache,
1119
+ ...(timelineDualWrite !== undefined ? { timelineDualWrite } : {}),
1120
+ });
1121
+
1122
+ // profile 提成 const 引用:core `registerProfile` 存的就是这个对象,`materializeOptions`
1123
+ // 在 **EU 创建时**读 `profile.model`。`provider.model` 热应用(P0-1 D4)只能**原地改**
1124
+ // 它的 `.model`(见 bundle.applyProviderModel)——同 tenant 重新注册不同 profile 会抛
1125
+ // `tenant_profile_conflict`。live EU 的 model 是构造期快照,改 profile 只影响新 EU。
1126
+ const ownerProfile: TenantRuntimeProfile = {
1127
+ tenantId,
1128
+ providerFactory: () => provider,
1129
+ model: providerModel,
1130
+ // P1-w2d(w1a D4 接缝):注入 resolveModel 后 materializeOptions 的 provider/model
1131
+ // 取解析结果(多厂商路由 + delegating wrapper);mock 无 registry → 不注入,
1132
+ // 走 legacy providerFactory() + model 路径,与今天逐字等价。
1133
+ ...(registry !== undefined ? { resolveModel: registry.resolveModel } : {}),
1134
+ // 插件已由装配层安装到共享 host;EU 不重复安装。
1135
+ plugins: [],
1136
+ pluginHostFactory: () => finalPluginHost,
1137
+ limits,
1138
+ termination,
1139
+ ...(pricing !== undefined ? { pricing } : {}),
1140
+ // 0.56:视觉的运行期设置(能力在 provider.vision 上,由 provider 插件挂)。
1141
+ // 没有 `enable` 这个键:支持即直通;`disabled` 是出事时的 kill switch(不是默认门)。
1142
+ ...(visionSettingsOf(config) !== undefined ? { vision: visionSettingsOf(config) } : {}),
1143
+ // q-empty-response:空响应兜底(nudge 重试)。缺省不注入 = core 内置缺省(启用、
1144
+ // 2 次);显式配置才覆盖。owner + 成员的新 EU 生效(与 vision 同快照语义)。
1145
+ ...(emptyResponsePolicyOf(config) !== undefined
1146
+ ? { emptyResponse: emptyResponsePolicyOf(config) }
1147
+ : {}),
1148
+ // 注入粒度框架:EU notice producer 的检测节奏 / 投递通道端口。P2:读 live getter
1149
+ // (缺省回退 config 快照)⇒ 热改 env_injection 下一请求生效。缺省配置走内置默认表
1150
+ // (全 request / model+ui)⇒ gate 恒放行、通道恒 model+ui,零回归。
1151
+ envCadence: (scope) =>
1152
+ resolveEnvCadence(scope, options.getEnvInjection?.() ?? config.envInjection),
1153
+ envChannel: (scope) =>
1154
+ resolveEnvChannel(scope, options.getEnvInjection?.() ?? config.envInjection),
1155
+ // 0.11.1:`ui.showReasoning` 显式 opt-in(默认 false,行为同 0.11.0)。
1156
+ // q-reasoning-truth-source-unify:静态值仅作兜底;活端口读 getLiveConfig
1157
+ // (envCadence/envChannel 热加载同族)⇒ 热改 ui.showReasoning 下一请求生效,
1158
+ // 免 restart 快照。单一真相源 = ui.showReasoning(frontend toggle 写它读它,
1159
+ // backend includeReasoning 读它;ADR-077 默认发射策略不动)。
1160
+ includeReasoning: includeReasoningFor(config),
1161
+ resolveIncludeReasoning: liveIncludeReasoningFor(options.getLiveConfig, config),
1162
+ context: {
1163
+ ...(config.context?.maxTokens !== undefined ? { maxTokens: config.context.maxTokens } : {}),
1164
+ ...(config.context?.autoCompact !== undefined
1165
+ ? { autoCompact: config.context.autoCompact }
1166
+ : {}),
1167
+ // q-tool-result-whitelist:构造期注入(重启生效);缺省 ⇒ core 内置默认。
1168
+ ...(config.context?.toolResultWhitelist !== undefined
1169
+ ? { toolResultWhitelist: config.context.toolResultWhitelist }
1170
+ : {}),
1171
+ // q-context-composition:构造期注入(重启生效);缺省 ⇒ EU 默认开。
1172
+ ...(config.context?.compositionRecord !== undefined
1173
+ ? { compositionRecord: config.context.compositionRecord }
1174
+ : {}),
1175
+ summarizer,
1176
+ },
1177
+ systemPrompt,
1178
+ permission,
1179
+ journalFactory,
1180
+ };
1181
+ options.runtime.registerProfile(ownerProfile);
1182
+
1183
+ // 0.15 E9:主 agent 的 Self Card(成员由 AgentService 注入)。
1184
+ const selfCard = ownerSelfCard(config, providerModel, {
1185
+ askUser: options.registerAskUser === true,
1186
+ });
1187
+
1188
+ /** 本 bundle 已服务过的 session(关闭时逐个 retire)。 */
1189
+ const servedSessionIds = new Set<string>();
1190
+
1191
+ const executionUnitFor = (sessionId: string) =>
1192
+ options.runtime.getOrCreateExecutionUnit({
1193
+ tenantId,
1194
+ sessionId,
1195
+ events,
1196
+ session,
1197
+ // 0.54 stop-write:EU 拿的是**只读口**(没有 `append`)—— 它只读历史、判读回、
1198
+ // 合并写 `index.json`;写入的唯一入口是 journal(经时间线写者)。
1199
+ ...(timelineLog !== undefined ? { eventLog: timelineLog } : {}),
1200
+ ...(leaseService !== undefined ? { leaseService } : {}),
1201
+ // 0.56 ctx-recall:压缩索引(`<sessionDir>/compactions.ndjson`)的落点。
1202
+ compactionIndexDir: tenantPaths.sessions_dir,
1203
+ pluginHost: finalPluginHost,
1204
+ plugins: [],
1205
+ // tenant EU 仍用完整 context 配置(maxMessages / compactThreshold 不进 profile 形状);
1206
+ // profile 的 `context` 只是成员路径的缺省值。
1207
+ contextFactory: () =>
1208
+ new MemoryWorkingContext(
1209
+ contextConfigFor(config, summarizerForSession?.(sessionId) ?? summarizer),
1210
+ ),
1211
+ overrides: { selfCard },
1212
+ });
1213
+
1214
+ /**
1215
+ * C6:idle session(无 live EU)的等价瞬态压缩路径。
1216
+ * 不启动 Run、不注入用户消息;从事件日志/缓存播种,压缩后经 transient journal
1217
+ * 写 `message.compaction` 与 SessionState,下一次 run/resume 直接读压缩后的缓存。
1218
+ */
1219
+ const compactIdleSession = async (
1220
+ sessionId: string,
1221
+ ): Promise<{ removed: number; remaining: number; messages: Message[] }> => {
1222
+ const state = await session.load(sessionId);
1223
+ if (state === null) throw new Error('compact_unavailable');
1224
+ const workingContext = new MemoryWorkingContext(
1225
+ contextConfigFor(config, summarizerForSession?.(sessionId) ?? summarizer),
1226
+ );
1227
+ workingContext.setSessionId(sessionId);
1228
+ let history: Message[] = state.messages ?? [];
1229
+ /** 0.56 ctx-recall:投影游标(压缩索引要按 seq 定位被替换的消息)。 */
1230
+ let projection: ProjectionCursor | undefined;
1231
+ if (timelineLog !== undefined) {
1232
+ await timelineLog.flush(sessionId);
1233
+ const stored = await timelineLog.read(sessionId);
1234
+ // 0.54:这条路径的产物会经 `saveSessionState` 写回 `SessionState.messages`
1235
+ // (见下面的 `journal.saveSessionState`),所以必须取原文视图,不能把清集替换的
1236
+ // 占位物化进盘上。模型视图由请求构建层按段冻结集合自己替换。
1237
+ // 0.56:用游标而不是 `projectMessages` —— 同一套折叠,但多一份与消息平行的 seq 记录
1238
+ // (压缩索引的区间来源,见 `ProjectionCursor.messageSeqs`)。
1239
+ if (stored.length > 0) {
1240
+ const cursor = createProjectionCursor({ applyClearedReplacements: false });
1241
+ extendProjection(cursor, stored);
1242
+ projection = cursor;
1243
+ history = cursor.messages;
1244
+ }
1245
+ }
1246
+ let prependedBaseSystem = false;
1247
+ if (
1248
+ !history.some(
1249
+ (message) => message.role === 'system' && message.compaction_summary !== true,
1250
+ ) &&
1251
+ systemPrompt !== ''
1252
+ ) {
1253
+ workingContext.add({ role: 'system', content: systemPrompt, timestamp: Date.now() });
1254
+ prependedBaseSystem = true;
1255
+ }
1256
+ for (const message of history) workingContext.add(message);
1257
+ /**
1258
+ * 与**窗口**逐位对齐的 seq(对不上 ⇒ `undefined`,索引如实记 unmapped)。
1259
+ *
1260
+ * 窗口前面可能补了一条基底 system(它不来自任何事件)⇒ 整份右移一位;
1261
+ * 对不齐就别用(错位的区间读出来是别人的历史)。
1262
+ */
1263
+ const aligned = alignMessageSeqs(
1264
+ history,
1265
+ projection?.messages ?? [],
1266
+ projection?.messageSeqs ?? [],
1267
+ );
1268
+ const windowLength = workingContext.messages.length;
1269
+ const windowSeqs =
1270
+ projection !== undefined && aligned.length + (prependedBaseSystem ? 1 : 0) === windowLength
1271
+ ? prependedBaseSystem
1272
+ ? [undefined, ...aligned]
1273
+ : aligned
1274
+ : [];
1275
+ const tokensBefore = workingContext.tokenCount;
1276
+ const removed = workingContext.compactAsync
1277
+ ? await workingContext.compactAsync()
1278
+ : workingContext.compact();
1279
+ const remaining = workingContext.messages.length;
1280
+ const messages = workingContext.messages;
1281
+ if (removed > 0) {
1282
+ const journal = journalFactory.transient({ runId: 'manual', events, sessionId });
1283
+ const report = workingContext.lastCompaction;
1284
+ const summary = [...messages]
1285
+ .reverse()
1286
+ .find((message) => message.role === 'system' && message.compaction_summary === true);
1287
+ const ts = summary?.timestamp ?? Date.now();
1288
+ // ── 0.56 ctx-recall:索引(这条 idle 路径与 EU 里的段起点压缩是同一个段边界,
1289
+ // 同样要能读回;否则「用户在两次 run 之间点压缩」就等于静默丢一条通道)。
1290
+ let compaction: CompactionIndexEntry | undefined;
1291
+ let nextCompactions: CompactionIndexEntry[] = state.compactions ?? [];
1292
+ if (summary !== undefined) {
1293
+ const indices = report?.removed_indices ?? [];
1294
+ const removedSeqs: (number | undefined)[] = [];
1295
+ for (let offset = 0; offset < removed; offset += 1) {
1296
+ const index = indices[offset];
1297
+ const aligned = index === undefined ? undefined : windowSeqs[index];
1298
+ removedSeqs.push(aligned);
1299
+ }
1300
+ const nextId =
1301
+ nextCompactions.reduce((max, entry) => Math.max(max, entry.compaction_id), 0) + 1;
1302
+ compaction = buildCompactionIndexEntry({
1303
+ compaction_id: nextId,
1304
+ at: ts,
1305
+ reason: 'manual',
1306
+ summary: summary.content,
1307
+ removedSeqs,
1308
+ tokens_before: tokensBefore,
1309
+ tokens_after: workingContext.tokenCount,
1310
+ });
1311
+ nextCompactions = [...nextCompactions, compaction];
1312
+ // stub 只在这里写一次;摘要正文从此冻结(重放逐字节一致)。
1313
+ appendCompactionStub(messages, formatCompactionStub(nextCompactions));
1314
+ }
1315
+ journal.appendFact({
1316
+ type: 'context.compacted',
1317
+ run_id: 'manual',
1318
+ data: {
1319
+ run_id: 'manual',
1320
+ session_id: sessionId,
1321
+ removed,
1322
+ remaining,
1323
+ reason: 'manual',
1324
+ ...(report?.degraded !== undefined ? { degraded: report.degraded } : {}),
1325
+ ...(compaction !== undefined ? { compaction } : {}),
1326
+ },
1327
+ ts,
1328
+ });
1329
+ if (summary !== undefined) {
1330
+ const cleared = report?.cleared_tool_call_ids ?? [];
1331
+ journal.appendFact({
1332
+ type: 'message.compaction',
1333
+ run_id: 'manual',
1334
+ data: {
1335
+ run_id: 'manual',
1336
+ session_id: sessionId,
1337
+ removed,
1338
+ remaining,
1339
+ kept: messages.filter((message) => message.role !== 'system').length,
1340
+ reason: 'manual',
1341
+ message: { ...summary, timestamp: ts },
1342
+ ...(cleared.length > 0 ? { cleared_tool_call_ids: cleared } : {}),
1343
+ ...(report?.degraded !== undefined ? { degraded: report.degraded } : {}),
1344
+ },
1345
+ ts,
1346
+ });
1347
+ }
1348
+ if (compaction !== undefined) {
1349
+ await appendCompactionIndex(
1350
+ sessionDirPath(tenantPaths.sessions_dir, sessionId),
1351
+ compaction,
1352
+ ).catch(() => false);
1353
+ }
1354
+ await journal.saveSessionState({
1355
+ ...state,
1356
+ messages,
1357
+ updated_at: Date.now(),
1358
+ ...(nextCompactions.length > 0 ? { compactions: nextCompactions } : {}),
1359
+ });
1360
+ }
1361
+ return { removed, remaining, messages };
1362
+ };
1363
+
1364
+ // Stage 4:bundle.runtime 是 per-session 门面,不再是单个长期存活的 EU。
1365
+ // `id` / `applyPermissionRules` 让既有热应用装配(按结构解析 live runtime)继续命中
1366
+ // 本 tenant 已建的 EU,不新增公开 RPC/事件。
1367
+ const executionFacade: RunnableAgent & {
1368
+ readonly id: string;
1369
+ applyPermissionRules(rules: RuntimePermissionConfig): void;
1370
+ /** C6:手动压缩;有 live EU 用 EU,idle session 走等价瞬态路径。 */
1371
+ compactContext?(
1372
+ sessionId: string,
1373
+ ): Promise<{ removed: number; remaining: number; messages?: Message[] }>;
1374
+ } = {
1375
+ id: `tenant:${tenantId}`,
1376
+ events,
1377
+ pluginHost: finalPluginHost,
1378
+ applyPermissionRules(rules) {
1379
+ for (const sessionId of servedSessionIds) {
1380
+ options.runtime.getExecutionUnit({ tenantId, sessionId })?.applyPermissionRules(rules);
1381
+ }
1382
+ },
1383
+ async compactContext(sessionId) {
1384
+ // C6:有 live EU(含成员 EU)走 EU;idle session 走等价瞬态路径,
1385
+ // 不为它新造 EU(避免 agentId 绑定冲突与目录残留)。
1386
+ const unit = options.runtime.getExecutionUnit({ tenantId, sessionId });
1387
+ if (unit !== undefined) return unit.compactContext(sessionId);
1388
+ return compactIdleSession(sessionId);
1389
+ },
1390
+ async run(input, sessionId, opts) {
1391
+ const targetSession = sessionId ?? options.sessionId ?? 'default';
1392
+ servedSessionIds.add(targetSession);
1393
+ const unit = await executionUnitFor(targetSession);
1394
+ return trackActive(unit.run(input, targetSession, opts));
1395
+ },
1396
+ async resumeRun(runId, opts) {
1397
+ if (runStore === undefined) throw new Error(`durable_disabled: ${runId}`);
1398
+ const record = await runStore.load(runId);
1399
+ if (record === null) throw new Error(`run_not_found: ${runId}`);
1400
+ servedSessionIds.add(record.session_id);
1401
+ const unit = await executionUnitFor(record.session_id);
1402
+ // 调用方负责按 agent_id 路由;门面只处理 tenant EU。
1403
+ return trackActive(unit.resumeRun(record, opts));
1404
+ },
1405
+ async resumeSession(sessionId, input, opts) {
1406
+ servedSessionIds.add(sessionId);
1407
+ const unit = await executionUnitFor(sessionId);
1408
+ return trackActive(unit.resumeSession(sessionId, input, opts));
1409
+ },
1410
+ async dispose() {
1411
+ // 生命周期归 ControlPlane(bundle.close 逐个 retire);门面不销毁共享 EU。
1412
+ },
1413
+ };
1414
+
1415
+ // 0.15:run/resumeRun 的跨进程写锁。memory 后端不落盘,无需锁。
1416
+ const lockedRuntime = withSessionWriteLock(executionFacade, {
1417
+ tenantDir: tenantPaths.root,
1418
+ enabled: options.sessionLocks ?? backend !== 'memory',
1419
+ });
1420
+
1421
+ // ── Trace ─────────────────────────────────────
1422
+ const extRedactor = options.redactor ?? (await loadRedactSecrets(loader));
1423
+ const redactor = composeTraceRedactors(createDefaultTraceRedactor(), extRedactor);
1424
+ const trace =
1425
+ options.writeTrace === true
1426
+ ? installTrace({
1427
+ events,
1428
+ config,
1429
+ tenantPaths,
1430
+ ...(extRedactor ? { redactor: extRedactor } : {}),
1431
+ ...(options.traceFactory ? { factory: options.traceFactory } : {}),
1432
+ })
1433
+ : undefined;
1434
+
1435
+ // asm 事件:不含值、不含密钥。
1436
+ try {
1437
+ const nowTs = options.clock ?? Date.now;
1438
+ events.publish({
1439
+ type: 'config.loaded',
1440
+ run_id: 'config',
1441
+ data: {
1442
+ sources: [...new Set(Object.values(options.configSources ?? {}))],
1443
+ keys: Object.keys(config),
1444
+ },
1445
+ ts: nowTs(),
1446
+ });
1447
+ for (const event of pluginLoadEvents) {
1448
+ events.publish({ type: event.type, run_id: 'plugins', data: event.data, ts: nowTs() });
1449
+ }
1450
+ } catch {
1451
+ // 事件投递失败不阻断启动
1452
+ }
1453
+
1454
+ // ── MCP ───────────────────────────────────────
1455
+ let mcpPlugin: McpPluginLike | undefined;
1456
+ let mcpControl: McpControl | undefined;
1457
+ let mcpShell: McpEngineShell | undefined;
1458
+ if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
1459
+ if (options.engineClient !== undefined) {
1460
+ // tools-engine P2 批次 2:连接/传输/pending 在 engine worker;host 壳 = 注册权威 +
1461
+ // 控制面代理(createMcpControl 单实现不变,cli applier/toggle 零改动)。
1462
+ const wiring = await createMcpEngineFromConfig({
1463
+ config,
1464
+ events,
1465
+ tenantId,
1466
+ loader,
1467
+ ...(options.loadMcpModule ? { loadModule: options.loadMcpModule } : {}),
1468
+ client: options.engineClient,
1469
+ host: finalPluginHost,
1470
+ logger,
1471
+ });
1472
+ if (wiring) {
1473
+ mcpPlugin = wiring.plugin;
1474
+ mcpControl = wiring.control;
1475
+ mcpShell = wiring.plugin;
1476
+ }
1477
+ } else {
1478
+ const wiring = await installMcp(
1479
+ {
1480
+ config,
1481
+ events,
1482
+ tenantId,
1483
+ loader,
1484
+ ...(options.loadMcpModule ? { loadModule: options.loadMcpModule } : {}),
1485
+ },
1486
+ finalPluginHost,
1487
+ );
1488
+ if (wiring) {
1489
+ mcpPlugin = wiring.plugin;
1490
+ mcpControl = wiring.control;
1491
+ }
1492
+ }
1493
+ }
1494
+
1495
+ // ── Feishu / Metrics ───────────────
1496
+ const feishuChannel = await createFeishuFromConfig({
1497
+ config,
1498
+ provider,
1499
+ model: providerModel,
1500
+ pluginHost: finalPluginHost,
1501
+ session,
1502
+ events,
1503
+ tenantId,
1504
+ env: {},
1505
+ ...(runStore ? { runStore } : {}),
1506
+ contextFactory,
1507
+ ...(options.feishuTransport !== undefined ? { transport: options.feishuTransport } : {}),
1508
+ ...(options.resolveFeishuTeamId !== undefined
1509
+ ? { resolveTeamId: options.resolveFeishuTeamId }
1510
+ : {}),
1511
+ ...(options.resolveFeishuService !== undefined
1512
+ ? { resolveService: options.resolveFeishuService }
1513
+ : {}),
1514
+ loader,
1515
+ ...(options.loadFeishuModule ? { loadModule: options.loadFeishuModule } : {}),
1516
+ });
1517
+
1518
+ const metrics = createMetricsCollector(events, config, options.metricsFactory);
1519
+
1520
+ // ── C4:AI 命名(ControlPlane 元数据写,与 sessions.rename 同一 save 路径) ──
1521
+ // 订阅本 tenant 事件流(含成员转发事件);fire-and-forget,失败只 warn,
1522
+ // 不阻塞 run 终态,也不写 SessionEventLog。
1523
+ const titleGenerationInFlight = new Set<string>();
1524
+ const generateSessionTitle = async (sessionId: string): Promise<void> => {
1525
+ try {
1526
+ const state = await session.load(sessionId);
1527
+ if (state === null) return;
1528
+ // 已确定命名(人工 rename / 创建时按成员身份命名 / 上一次 AI 命名)⇒ 自动
1529
+ // 命名永不覆盖。没有 marker 的是 legacy 数据,走下面的占位判定,无需迁移。
1530
+ if (state.title_source === 'manual' || state.title_source === 'generated') return;
1531
+ const messages = state.messages ?? [];
1532
+ const derivedTitle = deriveSessionMeta(messages).title;
1533
+ // 真实(非占位)且不等于当前派生标题 ⇒ 是 legacy 路径有意写下的名字,保留。
1534
+ // 占位标题(空 / 'Untitled' / 'undefined' / 'null')= 尚未命名 ⇒ 必须走 AI
1535
+ // 补名。此前这里把落壳的 'Untitled' 当成「已有名字」直接 return,导致空壳
1536
+ // 会话永远卡在 'Untitled'(用户报的 undefined / Untitled 根因之一)。
1537
+ if (!isPlaceholderTitle(state.title) && state.title !== derivedTitle) return;
1538
+ const input = firstUserInputForTitle(messages);
1539
+ if (input === undefined) return;
1540
+ // 0.64:AI 起标题是后台补的,触发时事件循环经常是空的 —— 用会真正触发的截止时间。
1541
+ const deadline = startDeadline(SESSION_TITLE_TIMEOUT_MS);
1542
+ let aiTitle = '';
1543
+ try {
1544
+ const response = await provider.chat({
1545
+ model: providerModel,
1546
+ messages: [
1547
+ { role: 'system', content: SESSION_TITLE_SYSTEM_PROMPT },
1548
+ { role: 'user', content: input },
1549
+ ],
1550
+ max_tokens: SESSION_TITLE_MAX_TOKENS,
1551
+ temperature: 0.2,
1552
+ signal: deadline.signal,
1553
+ });
1554
+ aiTitle = sanitizeGeneratedTitle(response.content);
1555
+ } catch (error) {
1556
+ // 失败不再静默放弃:warn 之后走下面的派生标题兜底。
1557
+ logger.warn('session title generation failed', {
1558
+ session_id: sessionId,
1559
+ error: error instanceof Error ? error.message : String(error),
1560
+ });
1561
+ } finally {
1562
+ deadline.dispose();
1563
+ }
1564
+ // 生成窗口内可能人工 rename / 已有另一次命名:写前重读,保住人工标题。
1565
+ const current = await session.load(sessionId);
1566
+ if (current === null) return;
1567
+ if (current.title_source === 'manual' || current.title_source === 'generated') return;
1568
+ const currentDerived = deriveSessionMeta(current.messages ?? []).title;
1569
+ if (!isPlaceholderTitle(current.title) && current.title !== currentDerived) return;
1570
+ // 兜底(金丝雀终验 issue-②):AI 无产出(reasoning 耗尽预算 / 超时 / 空响应)时
1571
+ // 用派生标题(首条用户话语截断,与读侧 deriveSessionMeta 同口径)补名,
1572
+ // 不再让会话静默卡在 Untitled。兜底标题**不标 generated**:它等于派生标题,
1573
+ // 下一次 run.completed 仍会通过上面的守卫,AI 命名可重试;人工标题不受影响。
1574
+ const title =
1575
+ aiTitle !== '' ? aiTitle : isPlaceholderTitle(currentDerived) ? '' : currentDerived;
1576
+ if (title === '') return;
1577
+ if (aiTitle === '') {
1578
+ logger.warn('session title generation produced no output; using derived title fallback', {
1579
+ session_id: sessionId,
1580
+ });
1581
+ }
1582
+ await session.save({
1583
+ ...current,
1584
+ title,
1585
+ ...(aiTitle !== '' ? { title_source: 'generated' as const } : {}),
1586
+ updated_at: Date.now(),
1587
+ });
1588
+ events.publish({
1589
+ type: 'session.titled',
1590
+ run_id: 'session',
1591
+ data: { session_id: sessionId, title },
1592
+ ts: Date.now(),
1593
+ });
1594
+ } catch (error) {
1595
+ logger.warn('session title generation failed', {
1596
+ session_id: sessionId,
1597
+ error: error instanceof Error ? error.message : String(error),
1598
+ });
1599
+ }
1600
+ };
1601
+ const unsubscribeTitles = events.subscribe((event) => {
1602
+ if (event.type !== 'run.completed') return;
1603
+ if (providerName === 'mock') return;
1604
+ const data = event.data as Record<string, unknown>;
1605
+ const sessionId = typeof data.session_id === 'string' ? data.session_id : undefined;
1606
+ if (sessionId === undefined) return;
1607
+ if (titleGenerationInFlight.has(sessionId)) return;
1608
+ titleGenerationInFlight.add(sessionId);
1609
+ void generateSessionTitle(sessionId).finally(() => {
1610
+ titleGenerationInFlight.delete(sessionId);
1611
+ });
1612
+ });
1613
+
1614
+ let closed = false;
1615
+ const SHUTDOWN_DRAIN_TIMEOUT_MS = 5000;
1616
+
1617
+ /** 关闭失败统一出口:logger.error + `shutdown.failed`(不阻断后续步骤) */
1618
+ const report = (step: string, error: unknown): void => {
1619
+ reportShutdownFailure({
1620
+ events,
1621
+ logger,
1622
+ step,
1623
+ error,
1624
+ tenantId,
1625
+ ...(options.clock ? { now: options.clock } : {}),
1626
+ });
1627
+ };
1628
+
1629
+ /**
1630
+ * 0.10 R2-18:有在跑 run 时先 `interrupt('shutdown')`(checkpoint 落 interrupted,
1631
+ * 可 `--resume-run`),限时等待终态;超时记录 warning 后继续关闭。
1632
+ */
1633
+ const drain = async (): Promise<void> => {
1634
+ try {
1635
+ await drainActiveRuns({
1636
+ activeRuns,
1637
+ logger,
1638
+ tenantId,
1639
+ timeoutMs: SHUTDOWN_DRAIN_TIMEOUT_MS,
1640
+ interrupt: (reason: 'shutdown') => {
1641
+ // Stage 4:每个 session 一个 EU;逐个软中断(checkpoint 落 interrupted)。
1642
+ for (const sessionId of servedSessionIds) {
1643
+ options.runtime.getExecutionUnit({ tenantId, sessionId })?.interrupt?.(reason);
1644
+ }
1645
+ },
1646
+ });
1647
+ } catch (error) {
1648
+ report('runtime.interrupt', error);
1649
+ }
1650
+ };
1651
+
1652
+ const close = async (closeOptions: { drain?: boolean } = {}): Promise<void> => {
1653
+ if (closed) return;
1654
+ closed = true;
1655
+
1656
+ // DR15-1:退出步永久进度日志(挂起时最后一条 start 即挂点;复验实证哪步慢)。
1657
+ const emit: ShutdownStepEmit = (level, event, fields) => {
1658
+ if (level === 'warn') logger.warn(event, fields);
1659
+ else logger.info(event, fields);
1660
+ };
1661
+
1662
+ // 先中断 / 等待在跑 run,再进入关闭顺序。
1663
+ // serve 路径已由 gateway.stop() 完成 drain,调用方传 drain:false 避免二次 5s。
1664
+ if (closeOptions.drain !== false) await drain();
1665
+
1666
+ // 关闭顺序:feishu → metrics → MCP → runtime → trace
1667
+ // → runStore → session。全部 await,异常逐段隔离,后续步骤仍会执行。
1668
+ // 0.9:MCP 是工厂式插件,不在 runtime 的 `plugins` 数组里,
1669
+ // `ExecutionUnit.dispose()` 触达不到;它的 dispose() 只是 close() 的
1670
+ // 幂等别名(ext 0.9),因此这里保留显式 close —— 不要为接 dispose
1671
+ // 而改安装顺序(DECISION-019 A)。
1672
+ await runShutdownStep(emit, 'bundle.feishu.stop', () =>
1673
+ stopFeishuChannel(feishuChannel, (error) => report('feishu.stop', error)),
1674
+ );
1675
+
1676
+ disposeMetrics(metrics);
1677
+
1678
+ const mcp = mcpPlugin;
1679
+ if (mcp) {
1680
+ try {
1681
+ await runShutdownStep(emit, 'bundle.mcp.close', () => mcp.close());
1682
+ } catch (error) {
1683
+ report('mcp.close', error);
1684
+ }
1685
+ }
1686
+
1687
+ // Stage 4:per-session EU 由 Runtime 目录持有;逐个 retire(dispose + 移出目录)。
1688
+ // retire 幂等;单条失败不阻断其余条目与后续关闭步骤。
1689
+ await runShutdownStep(emit, 'bundle.runtime.retire', async () => {
1690
+ for (const sessionId of servedSessionIds) {
1691
+ try {
1692
+ await options.runtime.retireExecutionUnit({ tenantId, sessionId });
1693
+ } catch (error) {
1694
+ report('runtime.retire', error);
1695
+ }
1696
+ }
1697
+ servedSessionIds.clear();
1698
+ });
1699
+
1700
+ // 插件在 EU 之外安装(tenant host 共享),随 bundle 关闭一起 dispose。
1701
+ try {
1702
+ await runShutdownStep(emit, 'bundle.plugin.dispose', () => installedPlugins.dispose());
1703
+ } catch (error) {
1704
+ report('runtime.plugin.dispose', error);
1705
+ }
1706
+
1707
+ if (trace) {
1708
+ await runShutdownStep(emit, 'bundle.trace.close', async () => {
1709
+ try {
1710
+ await trace.flush();
1711
+ } catch (error) {
1712
+ report('trace.flush', error);
1713
+ }
1714
+ try {
1715
+ await trace.close();
1716
+ } catch (error) {
1717
+ report('trace.close', error);
1718
+ }
1719
+ });
1720
+ }
1721
+
1722
+ await runShutdownStep(emit, 'bundle.runStore.close', () =>
1723
+ closeRunRecordStore(runStore, (error) => report('runStore.close', error)),
1724
+ );
1725
+
1726
+ if (timelineDualWrite !== undefined) {
1727
+ // 尽力而为:`closeAll` 自带 300ms 上限,关不掉也不拖住退出(数据在旧链路里)。
1728
+ try {
1729
+ await runShutdownStep(emit, 'bundle.timeline.close', () => timelineDualWrite.closeAll());
1730
+ } catch (error) {
1731
+ report('timelineDualWrite.close', error);
1732
+ }
1733
+ }
1734
+
1735
+ if (eventLog) {
1736
+ try {
1737
+ // 时间线写者有自己的关闭路径(`closeAll`,带 300ms 上限);这个端口没有额外句柄。
1738
+ await runShutdownStep(emit, 'bundle.eventLog.flush', async () => {
1739
+ await eventLog.flush?.();
1740
+ });
1741
+ } catch (error) {
1742
+ report('eventLog.flush', error);
1743
+ }
1744
+ }
1745
+
1746
+ try {
1747
+ session.close?.();
1748
+ } catch (error) {
1749
+ report('session.close', error);
1750
+ }
1751
+
1752
+ unsubscribeTitles();
1753
+ };
1754
+
1755
+ return {
1756
+ tenantId,
1757
+ config,
1758
+ tenantPaths,
1759
+ configSources: options.configSources ?? {},
1760
+ ...(options.configPaths ? { configPaths: options.configPaths } : {}),
1761
+ tenantOverlayKeys: options.tenantOverlayKeys ?? [],
1762
+ provider,
1763
+ providerName,
1764
+ providerModel,
1765
+ providerModelRef,
1766
+ providerBaseUrl,
1767
+ // 原地改引用(不能重新注册:同 tenant 不同 profile 会抛 tenant_profile_conflict)。
1768
+ // next 提供时同步重建 registry 快照 + 清缓存(P1-w2d 泛化;live EU 不动,下一具生效)。
1769
+ applyProviderModel: (model, next) => {
1770
+ ownerProfile.model = model;
1771
+ if (next !== undefined) registry?.applyConfig(next);
1772
+ },
1773
+ ...(registry !== undefined
1774
+ ? { validateModelRefDetailed: registry.validateModelRefDetailed }
1775
+ : {}),
1776
+ ...(registry !== undefined ? { previewDefaultModel: registry.previewDefaultModel } : {}),
1777
+ // provider 类能力插件(model-registry)由 wiring 收集;显式启用时 selection 的
1778
+ // 显式分支不排除 provider 类,同一插件会再进通用装载名单——两条路各持同一
1779
+ // descriptor/plugin(同 loader 缓存 + ESM 单实例)。去重单实现在装配层
1780
+ // registerInProcessPluginEntries(按 name 只登记一次,防 plugin_id_conflict 崩溃)。
1781
+ registerInProcessPlugins: (manager, pluginConfig) =>
1782
+ registerInProcessPluginEntries({
1783
+ manager,
1784
+ entries: [...inProcessCapabilityPlugins, ...(registry?.inProcessPlugins ?? [])],
1785
+ config: pluginConfig,
1786
+ }),
1787
+ pluginSurfaces: installedPlugins.surfaces,
1788
+ events,
1789
+ runtimeEvents: events,
1790
+ session,
1791
+ pluginHost: finalPluginHost,
1792
+ scheduler,
1793
+ runtime: lockedRuntime,
1794
+ ...(leaseService !== undefined ? { leaseService } : {}),
1795
+ summarizer,
1796
+ ...(summarizerForSession !== undefined ? { summarizerForSession } : {}),
1797
+ ...(runStore ? { runStore } : {}),
1798
+ resumeMarkers,
1799
+ journalFactory,
1800
+ ...(eventLog ? { eventLog } : {}),
1801
+ ...(timelineLog !== undefined ? { timelineLog } : {}),
1802
+ ...(timelineDualWrite !== undefined ? { timelineDualWrite } : {}),
1803
+ ...(trace ? { trace } : {}),
1804
+ ...(metrics ? { metrics } : {}),
1805
+ redactor,
1806
+ ...(extRedactor ? { extRedactor } : {}),
1807
+ sessionControl,
1808
+ pluginLoader: loader,
1809
+ plugins,
1810
+ ...(mcpPlugin ? { mcpPlugin } : {}),
1811
+ ...(mcpControl ? { mcp: mcpControl } : {}),
1812
+ ...(mcpShell ? { mcpShell } : {}),
1813
+ ...(feishuChannel ? { feishu: feishuChannel } : {}),
1814
+ close,
1815
+ };
1816
+ }
1817
+
1818
+ /** ext redact-secrets 的结构镜像 */
1819
+ interface RedactSecretsModuleLike {
1820
+ createTraceRedactor(config?: unknown): TraceRedactor;
1821
+ }
1822
+
1823
+ /** 动态加载 ext redactor;缺失只 warn,不阻断启动 */
1824
+ async function loadRedactSecrets(loader: PluginLoader): Promise<TraceRedactor | undefined> {
1825
+ try {
1826
+ const mod = (await loader.loadModule('redact-secrets')) as RedactSecretsModuleLike | null;
1827
+ if (!mod || typeof mod.createTraceRedactor !== 'function') {
1828
+ console.warn('⚠ redact-secrets unavailable; trace uses the core default redactor.');
1829
+ return undefined;
1830
+ }
1831
+ return mod.createTraceRedactor();
1832
+ } catch (error) {
1833
+ console.warn(
1834
+ `⚠ Failed to load redact-secrets: ${error instanceof Error ? error.message : String(error)}`,
1835
+ );
1836
+ return undefined;
1837
+ }
1838
+ }