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,2132 @@
1
+ /**
2
+ * @vessel-agent/doc-subscription - `subscribe` 工具
3
+ * @module @vessel-agent/doc-subscription/tool
4
+ *
5
+ * 显式订阅:add / remove / list / inspect / prune。只接受具体文件(无 glob、无目录),
6
+ * 权限与路径边界在 handler 内复用 read 工具的同一条 `evaluatePath` 判定。
7
+ *
8
+ * - BeforeLlm 发短通知;有 read 引用的条目可带 line-level diff 明细行(hook.ts),
9
+ * 其余正文只在模型显式 `inspect` 时返回。
10
+ * - `inspect` 成功才推进 `seen_rev`;失败 / 超限不推进。
11
+ * - 工具不写日志,不主动把正文写进 trace;正文随工具结果进入上下文。
12
+ * - 自动订阅入口:autoSubscribePath(edit/write,Phase 1)与 readSubscribePath
13
+ * (read line-level,蜂群协作增强);origin 升级梯 manual > edit > read。
14
+ */
15
+
16
+ import { createHash } from 'node:crypto';
17
+ import { readFile, stat } from 'node:fs/promises';
18
+ import * as path from 'node:path';
19
+ import {
20
+ canonicalPath,
21
+ DEFAULT_READ_LIMIT,
22
+ evaluatePath,
23
+ type PathBoundary,
24
+ splitLines,
25
+ } from '@vessel-agent/basic-tools';
26
+ import type { ToolContext, ToolDefinition } from '@vessel-agent/core';
27
+ import {
28
+ agentSignature,
29
+ agentSubscriptionKey,
30
+ describeAgentRev,
31
+ isValidAgentTarget,
32
+ readAgentSnapshot,
33
+ } from './agent.js';
34
+ import { type DocSubscriptionConfig, isValidScriptName, resolveInput } from './config.js';
35
+ import { unifiedDiff } from './diff.js';
36
+ import type { AgentRegistryState } from './friend-edges.js';
37
+ import {
38
+ describeHealthRev,
39
+ healthSignature,
40
+ healthSubscriptionKey,
41
+ isValidHealthTarget,
42
+ readHealthSnapshot,
43
+ } from './health.js';
44
+ import { evaluateTargetDeath, observeEntry, type TargetDeathKind } from './hook.js';
45
+ import {
46
+ BUS_SUBSCRIPTION_SCOPES,
47
+ busSubscriptionKey,
48
+ implicitSubscriptionKey,
49
+ isValidBusScope,
50
+ isValidImplicitTarget,
51
+ isValidTeamLogTarget,
52
+ SOURCE_LEVEL_IMPLICIT_SOURCES,
53
+ teamLogSubscriptionKey,
54
+ } from './implicit.js';
55
+ import { type ScriptRunner, scriptFlightKey, scriptSubscriptionKey } from './script.js';
56
+ import {
57
+ type ChangeOrigin,
58
+ type ReadRef,
59
+ type SessionSubscriptionState,
60
+ type SubscriptionEntry,
61
+ type SubscriptionStore,
62
+ subscriptionId,
63
+ tierOf,
64
+ } from './store.js';
65
+ import { describeTeamLogRev, observeTeamLogEntry, type TeamLogPort } from './team-log.js';
66
+
67
+ // tier 派生单源在 store.ts(entry 类型拥有者;B2 迁居,收养过滤共用);
68
+ // re-export 保 B1 既有 import 面(bulk 过滤 / RPC port)不变。
69
+ export { tierOf } from './store.js';
70
+
71
+ /** 与 read 工具同口径 */
72
+ export const MAX_SUBSCRIBE_BYTES = 8 * 1024 * 1024;
73
+
74
+ /** 工具依赖 */
75
+ export interface SubscribeToolDeps {
76
+ boundary: PathBoundary;
77
+ store: SubscriptionStore;
78
+ config: DocSubscriptionConfig;
79
+ /**
80
+ * live 配置 getter(q-subscription-script;q-doc-subscription-hot-gate 扩到自动订阅入口):
81
+ * allowlist / 调度 / cwd / maxFullBytes / stateDir 热改即时生效;缺省回落 install 快照。
82
+ */
83
+ liveConfig?: () => DocSubscriptionConfig;
84
+ /** script 执行器(inspect 诊断 peek 用);缺省 ⇒ 无在飞诊断 */
85
+ runner?: ScriptRunner;
86
+ /** team-log 源端口(q-sub-unify-p2 M6,装配注入);缺省 ⇒ 不可订(fail-closed) */
87
+ teamLog?: TeamLogPort;
88
+ /**
89
+ * 注册态读(q-subscription-lifecycle B3 N2,装配经 agentEvents 端口注入):
90
+ * S3 remove / §14 prune 的死亡事实单源 evaluateTargetDeath 消费(registry-missing
91
+ * 判据,§6.1);缺省 ⇒ 无此判据(零回归)。与 BeforeLlmHookDeps 同形(结构兼容)。
92
+ */
93
+ registryStateOf?: (
94
+ memberId: string,
95
+ ) => Promise<AgentRegistryState | undefined> | AgentRegistryState | undefined;
96
+ }
97
+
98
+ /** add 的单个路径结果 */
99
+ export interface AddOutcome {
100
+ entry?: SubscriptionEntry;
101
+ input: string;
102
+ reason?: string;
103
+ }
104
+
105
+ /** inspect 的结果 */
106
+ interface InspectOutcome {
107
+ output: string;
108
+ changed: boolean;
109
+ }
110
+
111
+ /** 类型守卫:值是否为对象记录 */
112
+ function isRecord(value: unknown): value is Record<string, unknown> {
113
+ return typeof value === 'object' && value !== null;
114
+ }
115
+
116
+ /**
117
+ * live 配置求值(hot-gate 同族修复,q-doc-subscription-hot-gate):getter 缺省 / 抛错 ⇒
118
+ * 回落 install 快照。工具 handler 与自动订阅入口(autoSubscribePath / readSubscribePath)
119
+ * 共用同一口径 —— 热改 cwd / maxFullBytes / stateDir / allowlist 在两条路都即时生效。
120
+ */
121
+ export function liveConfigOf(deps: SubscribeToolDeps): DocSubscriptionConfig {
122
+ if (deps.liveConfig === undefined) return deps.config;
123
+ try {
124
+ return deps.liveConfig();
125
+ } catch {
126
+ return deps.config;
127
+ }
128
+ }
129
+
130
+ /** XML 属性值转义(& < > ") */
131
+ function escapeXmlAttr(value: string): string {
132
+ return value
133
+ .replace(/&/g, '&amp;')
134
+ .replace(/</g, '&lt;')
135
+ .replace(/>/g, '&gt;')
136
+ .replace(/"/g, '&quot;');
137
+ }
138
+
139
+ /** 内容 hash */
140
+ function sha256Hex(buffer: Buffer): string {
141
+ return createHash('sha256').update(buffer).digest('hex');
142
+ }
143
+
144
+ /** 显式拒绝的敏感文件名 / 后缀(不依赖内容 redactor) */
145
+ function isSensitiveBasename(basename: string): boolean {
146
+ const lower = basename.toLowerCase();
147
+ if (lower === '.env' || lower.startsWith('.env.')) return true;
148
+ if (lower.endsWith('.pem') || lower.endsWith('.key')) return true;
149
+ if (lower === 'id_rsa' || lower === 'id_ed25519') return true;
150
+ if (lower.startsWith('credentials')) return true;
151
+ if (lower === '.netrc') return true;
152
+ return false;
153
+ }
154
+
155
+ /** 通配符 / 花括号模式:订阅只接受具体文件 */
156
+ function hasWildcard(input: string): boolean {
157
+ return /[*?[\]{}]/.test(input);
158
+ }
159
+
160
+ /**
161
+ * 校验并构造条目;失败返回 reason(稳定错误码)。
162
+ * 导出供控制面 RPC add 复用(q-subscription-control:校验单源,不造第二套)。
163
+ */
164
+ export async function prepareEntry(
165
+ input: string,
166
+ deps: SubscribeToolDeps,
167
+ existing: SubscriptionEntry | undefined,
168
+ ): Promise<AddOutcome> {
169
+ const trimmed = input.trim();
170
+ if (trimmed === '') return { input, reason: 'empty' };
171
+ if (hasWildcard(trimmed)) return { input, reason: 'wildcard' };
172
+
173
+ const absolute = resolveInput(deps.config, trimmed);
174
+ const canonical = canonicalPath(absolute);
175
+
176
+ const decision = evaluatePath(canonical, deps.boundary);
177
+ if (decision === 'deny') return { input, reason: 'path_denied' };
178
+ if (decision === 'ask') return { input, reason: 'path_outside_allowed_roots' };
179
+
180
+ let info: Awaited<ReturnType<typeof stat>>;
181
+ try {
182
+ info = await stat(canonical);
183
+ } catch {
184
+ return { input, reason: 'not_found' };
185
+ }
186
+ if (info.isDirectory()) return { input, reason: 'not_a_file' };
187
+ if (!info.isFile()) return { input, reason: 'not_a_file' };
188
+ if (info.size > MAX_SUBSCRIBE_BYTES) return { input, reason: 'too_large' };
189
+ if (isSensitiveBasename(path.basename(canonical))) return { input, reason: 'sensitive' };
190
+
191
+ return {
192
+ input: trimmed,
193
+ entry: {
194
+ id: subscriptionId(canonical),
195
+ path: canonical,
196
+ input: trimmed,
197
+ // 重复 add 保留已有游标,避免无谓重通知 / 重新全量。
198
+ rev: existing?.rev ?? '',
199
+ notified_rev: existing?.notified_rev ?? '',
200
+ seen_rev: existing?.seen_rev ?? '',
201
+ size: info.size,
202
+ mtime_ms: info.mtimeMs,
203
+ notified_at: existing?.notified_at ?? 0,
204
+ seen_at: existing?.seen_at ?? 0,
205
+ // origin/reads 像 snapshot 一样携带 existing:重复订阅不丢引用计数;
206
+ // 来源升级由各入口决定(manual add 恒 manual / edit-write 升 edit / read 只在新建时置 read)。
207
+ origin: existing?.origin ?? 'manual',
208
+ reads: existing?.reads ?? [],
209
+ ...(existing?.snapshot !== undefined ? { snapshot: existing.snapshot } : {}),
210
+ // last_writer 像 snapshot 一样携带 existing:重复订阅 / read 追加不丢来源归因。
211
+ ...(existing?.last_writer !== undefined ? { last_writer: existing.last_writer } : {}),
212
+ },
213
+ };
214
+ }
215
+
216
+ /** 解析 add 的输入路径列表(path + paths,保持顺序) */
217
+ function collectAddInputs(args: Record<string, unknown>): string[] {
218
+ const inputs: string[] = [];
219
+ const single = args.path;
220
+ if (typeof single === 'string' && single.trim() !== '') inputs.push(single);
221
+ const multiple = args.paths;
222
+ if (Array.isArray(multiple)) {
223
+ for (const item of multiple) {
224
+ if (typeof item === 'string') inputs.push(item);
225
+ }
226
+ }
227
+ return inputs;
228
+ }
229
+
230
+ /** 格式化为删除结果(S3:死目标经 evaluateTargetDeath 单源求值 ⇒ 真删,含 friend 块)。 */
231
+ async function formatRemove(
232
+ state: SessionSubscriptionState,
233
+ args: Record<string, unknown>,
234
+ resolve: (input: string) => string,
235
+ deps: SubscribeToolDeps,
236
+ ): Promise<string> {
237
+ const id = typeof args.id === 'string' && args.id.trim() !== '' ? args.id.trim() : undefined;
238
+ const rawPath =
239
+ typeof args.path === 'string' && args.path.trim() !== '' ? args.path.trim() : undefined;
240
+ const rawNode =
241
+ typeof args.node === 'string' && args.node.trim() !== '' ? args.node.trim() : undefined;
242
+ const rawName =
243
+ typeof args.name === 'string' && args.name.trim() !== '' ? args.name.trim() : undefined;
244
+ const rawTarget =
245
+ typeof args.target === 'string' && args.target.trim() !== '' ? args.target.trim() : undefined;
246
+
247
+ if (
248
+ id === undefined &&
249
+ rawPath === undefined &&
250
+ rawNode === undefined &&
251
+ rawName === undefined &&
252
+ rawTarget === undefined
253
+ ) {
254
+ return '错误:remove 需要 path、node、target、name 或 id。';
255
+ }
256
+
257
+ let key: string | undefined;
258
+ if (id !== undefined) {
259
+ key = Object.keys(state.subscriptions).find(
260
+ (candidate) => state.subscriptions[candidate]?.id === id,
261
+ );
262
+ if (key === undefined) return `not_found: id=${id}`;
263
+ } else if (rawNode !== undefined) {
264
+ key = healthSubscriptionKey(rawNode);
265
+ } else if (rawTarget !== undefined) {
266
+ key = agentSubscriptionKey(rawTarget);
267
+ } else if (rawName !== undefined) {
268
+ key = scriptSubscriptionKey(rawName);
269
+ } else if (rawPath !== undefined) {
270
+ key = canonicalPath(resolve(rawPath));
271
+ }
272
+
273
+ if (key === undefined || state.subscriptions[key] === undefined) {
274
+ return `not_found: ${rawPath ?? rawNode ?? rawTarget ?? rawName ?? id}`;
275
+ }
276
+ // S3 死亡事实单源求值(调用方评估传入纯决策,不第二套判据);快照缺失/stat 失败不判死。
277
+ const target = state.subscriptions[key];
278
+ const death = target !== undefined ? await evaluateTargetDeath(target, deps) : undefined;
279
+ const outcome = removeSubscriptionEntry(state, key, death);
280
+ if (outcome === 'already_muted') return `muted: ${key} (already)`;
281
+ if (outcome === 'muted') return `muted: ${key}`;
282
+ return `removed: ${key}`;
283
+ }
284
+
285
+ /**
286
+ * 删除一条订阅的纯决策(q-subscription-control 导出:控制面 RPC remove 复用,
287
+ * 与工具面 formatRemove 同口径单源)。原地改 state:
288
+ * - **死目标(death 非 undefined,S3)⇒ 真删**(含 friend/implicit agent 块——死亡终结
289
+ * D-4 保留语义;死亡事实由调用方经 evaluateTargetDeath 单源求值传入,本函数不第二套判据);
290
+ * - 活 agent 条目带 friend / origin implicit ⇒ 写 muted 保留(取关≠删好友,M5 D-4,逐字不动);
291
+ * - 隐式静音账本(inbox/bash-job/bus)⇒ mute 幂等(D3;bulk 也不真删,静音意图永不 prune);
292
+ * - 其余显式条目 ⇒ 删除(P1 现态语义)。
293
+ * 调用方负责落盘;'not_found' 时 state 不动。death 缺省(旧 caller)⇒ 活目标语义零回归。
294
+ */
295
+ export function removeSubscriptionEntry(
296
+ state: SessionSubscriptionState,
297
+ key: string,
298
+ death?: TargetDeathKind,
299
+ ): 'removed' | 'muted' | 'already_muted' | 'not_found' {
300
+ const entry = state.subscriptions[key];
301
+ if (entry === undefined) return 'not_found';
302
+ if (death === undefined) {
303
+ const source = entry.source ?? 'file';
304
+ // 隐式静音账本(inbox/bash-job/bus):remove=mute(D3 lazy default-on;条目只在
305
+ // muted 时物化 ⇒ 恒 already_muted 幂等)。bulk 裸全清也不真删账本(静音意图永不 prune)。
306
+ if (source === 'inbox' || source === 'bash-job' || source === 'bus') {
307
+ if (entry.muted === true) return 'already_muted';
308
+ entry.muted = true;
309
+ return 'muted';
310
+ }
311
+ if (source === 'agent' && (entry.friend !== undefined || entry.origin === 'implicit')) {
312
+ if (entry.muted === true) return 'already_muted';
313
+ entry.muted = true;
314
+ return 'muted';
315
+ }
316
+ }
317
+ delete state.subscriptions[key];
318
+ return 'removed';
319
+ }
320
+
321
+ /** bulk remove / prune 过滤器(设计 §14:组合选条目;缺省全不过滤 = 裸全清,须 confirm 闸)。 */
322
+ export interface SubscriptionBulkFilter {
323
+ /** 源类型(file/agent/health/script/team-log/inbox/bash-job/bus) */
324
+ source?: string;
325
+ /** tier(auto/persistent,origin 派生投影) */
326
+ tier?: 'auto' | 'persistent';
327
+ /** 路径/目标前缀 */
328
+ prefix?: string;
329
+ /** 只选死目标(死亡判据 evaluateTargetDeath 单源,fail-closed) */
330
+ deadOnly?: boolean;
331
+ }
332
+
333
+ /** bulk 逐条结果(reuse formatRemove outcome 词表 removed/muted,additive preserved 计数)。 */
334
+ export interface SubscriptionBulkOutcome {
335
+ removed: number;
336
+ muted: number;
337
+ preserved: number;
338
+ /** 有界清单(L-073:≤ BULK_ENTRIES_MAX 条;计数恒完整) */
339
+ entries: Array<{ key: string; outcome: 'removed' | 'muted' }>;
340
+ truncated: boolean;
341
+ }
342
+
343
+ /** bulk 清单有界上限(L-073 表层原则;计数不受截断影响) */
344
+ export const BULK_ENTRIES_MAX = 50;
345
+
346
+ /** 过滤器是否命中(纯函数;death 由调用方单源求值传入)。 */
347
+ export function matchesBulkFilter(
348
+ entry: SubscriptionEntry,
349
+ filter: SubscriptionBulkFilter,
350
+ death: TargetDeathKind | undefined,
351
+ ): boolean {
352
+ if (filter.source !== undefined && (entry.source ?? 'file') !== filter.source) return false;
353
+ if (filter.tier !== undefined && tierOf(entry) !== filter.tier) return false;
354
+ if (filter.prefix !== undefined && !entry.path.startsWith(filter.prefix)) return false;
355
+ if (filter.deadOnly === true && death === undefined) return false;
356
+ return true;
357
+ }
358
+
359
+ /**
360
+ * bulk 逐条删除(设计 §14.1 单源):一次调用内循环调 removeSubscriptionEntry 同一纯决策
361
+ * (活 agent friend/implicit ⇒ mute 保 D-4;死目标 ⇒ 真删 S3;显式活条目 ⇒ 真删现态)。
362
+ * 调用方把整段挂进 store.mutate per-session 串行链 ⇒ 原子落盘。
363
+ * 本函数不触 runner(预览复用同函数跑 state 副本,零副作用);script disarm 由调用方
364
+ * 经 disarmRemovedScripts 在落盘后执行。
365
+ */
366
+ export async function runBulkRemove(
367
+ state: SessionSubscriptionState,
368
+ filter: SubscriptionBulkFilter,
369
+ deps: SubscribeToolDeps,
370
+ ): Promise<SubscriptionBulkOutcome> {
371
+ const outcome: SubscriptionBulkOutcome = {
372
+ removed: 0,
373
+ muted: 0,
374
+ preserved: 0,
375
+ entries: [],
376
+ truncated: false,
377
+ };
378
+ for (const [key, entry] of Object.entries(state.subscriptions)) {
379
+ const death = await evaluateTargetDeath(entry, deps);
380
+ if (!matchesBulkFilter(entry, filter, death)) {
381
+ outcome.preserved += 1;
382
+ continue;
383
+ }
384
+ const result = removeSubscriptionEntry(state, key, death);
385
+ if (result === 'removed') {
386
+ outcome.removed += 1;
387
+ if (outcome.entries.length < BULK_ENTRIES_MAX) {
388
+ outcome.entries.push({ key, outcome: 'removed' });
389
+ } else outcome.truncated = true;
390
+ } else if (result === 'muted' || result === 'already_muted') {
391
+ outcome.muted += 1;
392
+ if (outcome.entries.length < BULK_ENTRIES_MAX) {
393
+ outcome.entries.push({ key, outcome: 'muted' });
394
+ } else outcome.truncated = true;
395
+ } else {
396
+ outcome.preserved += 1;
397
+ }
398
+ }
399
+ return outcome;
400
+ }
401
+
402
+ /** bulk 落盘后 script disarm(与单条 remove 同口径;在飞进程不杀,受各自超时闸约束)。 */
403
+ export function disarmRemovedScripts(
404
+ outcome: SubscriptionBulkOutcome,
405
+ deps: SubscribeToolDeps,
406
+ sessionId: string,
407
+ ): void {
408
+ for (const item of outcome.entries) {
409
+ if (item.outcome === 'removed' && item.key.startsWith('script:')) {
410
+ deps.runner?.disarmInterval(scriptFlightKey(sessionId, item.key.slice('script:'.length)));
411
+ }
412
+ }
413
+ }
414
+
415
+ /** bulk 结果格式化(工具面;预览/执行同形,additive 计数 + 有界清单)。 */
416
+ export function formatBulkOutcome(outcome: SubscriptionBulkOutcome, preview: boolean): string {
417
+ const lines = [
418
+ `${preview ? 'preview (not executed)' : 'bulk'}: removed=${outcome.removed} muted=${outcome.muted} preserved=${outcome.preserved}`,
419
+ ];
420
+ for (const item of outcome.entries) lines.push(` ${item.outcome}: ${item.key}`);
421
+ if (outcome.truncated)
422
+ lines.push(` … entries list truncated at ${BULK_ENTRIES_MAX} (counts complete)`);
423
+ if (preview) {
424
+ lines.push(
425
+ 'confirm:true required to execute (bare full clear includes live explicit entries).',
426
+ );
427
+ }
428
+ return lines.join('\n');
429
+ }
430
+
431
+ /** bulk 过滤器解析(工具 args / RPC params 同形状单源);非法值返回错误文案。 */
432
+ export function parseBulkFilter(args: Record<string, unknown>): SubscriptionBulkFilter | string {
433
+ const filter: SubscriptionBulkFilter = {};
434
+ if (typeof args.source === 'string' && args.source.trim() !== '') {
435
+ const source = args.source.trim();
436
+ if (
437
+ source !== 'file' &&
438
+ source !== 'health' &&
439
+ source !== 'script' &&
440
+ source !== 'agent' &&
441
+ source !== 'inbox' &&
442
+ source !== 'bash-job' &&
443
+ source !== 'bus' &&
444
+ source !== 'team-log'
445
+ ) {
446
+ return '错误:source 必须是 file / health / script / agent / inbox / bash-job / bus / team-log。';
447
+ }
448
+ filter.source = source;
449
+ }
450
+ if (args.tier !== undefined) {
451
+ if (args.tier !== 'auto' && args.tier !== 'persistent') {
452
+ return '错误:tier 必须是 auto / persistent。';
453
+ }
454
+ filter.tier = args.tier;
455
+ }
456
+ if (typeof args.prefix === 'string' && args.prefix !== '') filter.prefix = args.prefix;
457
+ if (args.dead_only === true) filter.deadOnly = true;
458
+ return filter;
459
+ }
460
+
461
+ /**
462
+ * 隐式源 remove = 静音(q-sub-unify-p2 M5,§4.4,D3):无条目=on,muted 才物化
463
+ * 条目(origin implicit)。幂等:已 muted 不重复写盘。bus 按 scope 词校验。
464
+ */
465
+ async function muteImplicitSource(
466
+ state: SessionSubscriptionState,
467
+ source: 'inbox' | 'bash-job' | 'bus',
468
+ args: Record<string, unknown>,
469
+ deps: SubscribeToolDeps,
470
+ ): Promise<string> {
471
+ let target: string;
472
+ let key: string;
473
+ if (source === 'bus') {
474
+ const raw = typeof args.target === 'string' ? args.target.trim() : '';
475
+ if (!isValidBusScope(raw)) {
476
+ return '错误:source:bus remove 需要 target 为 scope 词(config/permission/tools/mcp/update)。';
477
+ }
478
+ target = raw;
479
+ key = busSubscriptionKey(raw);
480
+ } else {
481
+ const raw =
482
+ typeof args.target === 'string' && args.target.trim() !== '' ? args.target.trim() : '*';
483
+ if (!isValidImplicitTarget(raw)) return `错误:source:${source} target 恒 '*'。`;
484
+ target = raw;
485
+ key = implicitSubscriptionKey(source);
486
+ }
487
+ const existing = state.subscriptions[key];
488
+ if (existing?.muted === true) return `muted: ${key} (already)`;
489
+ state.subscriptions[key] = {
490
+ ...(existing ?? {
491
+ id: subscriptionId(key),
492
+ path: target,
493
+ input: target,
494
+ source,
495
+ rev: '',
496
+ notified_rev: '',
497
+ seen_rev: '',
498
+ size: 0,
499
+ mtime_ms: 0,
500
+ notified_at: 0,
501
+ seen_at: 0,
502
+ origin: 'implicit' as const,
503
+ reads: [],
504
+ }),
505
+ muted: true,
506
+ };
507
+ try {
508
+ await deps.store.save(state);
509
+ } catch {
510
+ return '错误:保存订阅状态失败。';
511
+ }
512
+ return `muted: ${key}`;
513
+ }
514
+
515
+ /**
516
+ * 隐式源 add = 复订(q-sub-unify-p2 M5,§4.4,D3):muted 条目删除恢复无条目=on
517
+ * 静息态(零物化);本就无条目 ⇒ 默认开,不写盘。
518
+ */
519
+ async function unmuteImplicitSource(
520
+ state: SessionSubscriptionState,
521
+ source: 'inbox' | 'bash-job' | 'bus',
522
+ args: Record<string, unknown>,
523
+ deps: SubscribeToolDeps,
524
+ ): Promise<string> {
525
+ let key: string;
526
+ if (source === 'bus') {
527
+ const raw = typeof args.target === 'string' ? args.target.trim() : '';
528
+ if (!isValidBusScope(raw)) {
529
+ return '错误:source:bus add 需要 target 为 scope 词(config/permission/tools/mcp/update)。';
530
+ }
531
+ key = busSubscriptionKey(raw);
532
+ } else {
533
+ const raw =
534
+ typeof args.target === 'string' && args.target.trim() !== '' ? args.target.trim() : '*';
535
+ if (!isValidImplicitTarget(raw)) return `错误:source:${source} target 恒 '*'。`;
536
+ key = implicitSubscriptionKey(source);
537
+ }
538
+ const existing = state.subscriptions[key];
539
+ if (existing === undefined || existing.muted !== true) return `on: ${key} (default)`;
540
+ delete state.subscriptions[key];
541
+ try {
542
+ await deps.store.save(state);
543
+ } catch {
544
+ return '错误:保存订阅状态失败。';
545
+ }
546
+ return `unmuted: ${key}`;
547
+ }
548
+
549
+ /** rev 的展示形态 */
550
+ function describeRev(rev: string): string {
551
+ if (rev === '') return 'never';
552
+ if (rev === 'deleted') return 'deleted';
553
+ if (rev === 'empty') return 'empty';
554
+ if (rev.startsWith('too_large:')) return 'too_large';
555
+ if (rev.startsWith('binary:'))
556
+ return `binary:${rev.slice('binary:'.length, 'binary:'.length + 12)}`;
557
+ return `sha256:${rev.slice(0, 12)}`;
558
+ }
559
+
560
+ /** 格式化 list;显示 changed(未通知)/ unread(未 inspect) */
561
+ function formatList(state: SessionSubscriptionState): string {
562
+ const entries = Object.values(state.subscriptions).sort((a, b) =>
563
+ a.path < b.path ? -1 : a.path > b.path ? 1 : 0,
564
+ );
565
+ const lines = entries.length === 0 ? ['no subscriptions'] : [`subscribed ${entries.length}:`];
566
+ for (const entry of entries) {
567
+ const changeLabel =
568
+ entry.rev === '' ? 'pending' : entry.rev !== entry.notified_rev ? 'changed' : 'notified';
569
+ // tier 分账标注(B2,设计 §2/§5):每条 additive tier=auto|persistent(origin 派生单源)。
570
+ const tierLabel = `tier=${tierOf(entry)}`;
571
+ // 隐式源条目(q-sub-unify-p2 M5,additive):只在 muted 时物化,独立展示行。
572
+ if (entry.source === 'inbox' || entry.source === 'bash-job' || entry.source === 'bus') {
573
+ lines.push(` ${entry.path} id=${entry.id} source=${entry.source} muted ${tierLabel}`);
574
+ continue;
575
+ }
576
+ // health 条目(additive):独立展示行(B2 起各源行尾 additive tier 标注)。
577
+ if (entry.source === 'health') {
578
+ lines.push(
579
+ ` ${entry.path} id=${entry.id} source=health rev=${describeHealthRev(entry.rev)} ${changeLabel} ${tierLabel}`,
580
+ );
581
+ continue;
582
+ }
583
+ // agent 条目(q-sub-unify-p1,additive):活动签名展示行;muted/friend 标记 additive。
584
+ if (entry.source === 'agent') {
585
+ const marks = `${entry.muted === true ? ' muted' : ''}${entry.friend !== undefined ? ` friend=${entry.friend.origin}` : ''}`;
586
+ lines.push(
587
+ ` ${entry.path} id=${entry.id} source=agent rev=${describeAgentRev(entry.rev)}${marks} ${changeLabel} ${tierLabel}`,
588
+ );
589
+ continue;
590
+ }
591
+ // team-log 条目(q-sub-unify-p2 M6,additive):offset 游标展示行。
592
+ if (entry.source === 'team-log') {
593
+ const marks = entry.muted === true ? ' muted' : '';
594
+ lines.push(
595
+ ` ${entry.path} id=${entry.id} source=team-log rev=${describeTeamLogRev(entry.rev)}${marks} ${changeLabel} ${tierLabel}`,
596
+ );
597
+ continue;
598
+ }
599
+ // script 条目(additive):执行事实行(last_exit / last_run)。
600
+ if (entry.source === 'script') {
601
+ const facts = entry.script;
602
+ const exitLabel =
603
+ facts === undefined
604
+ ? 'never_run'
605
+ : facts.last_exit === null
606
+ ? facts.last_error !== undefined
607
+ ? 'failed'
608
+ : 'running'
609
+ : String(facts.last_exit);
610
+ const lastRun =
611
+ facts !== undefined && facts.last_started_at > 0
612
+ ? new Date(facts.last_started_at).toISOString()
613
+ : 'never';
614
+ lines.push(
615
+ ` ${entry.path} id=${entry.id} source=script rev=${describeRev(entry.rev)} ` +
616
+ `last_exit=${exitLabel} last_run=${lastRun} ${changeLabel} ${tierLabel}`,
617
+ );
618
+ continue;
619
+ }
620
+ const unread = entry.seen_rev === '' || entry.seen_rev !== entry.rev;
621
+ lines.push(
622
+ ` ${entry.path} id=${entry.id} rev=${describeRev(entry.rev)} ` +
623
+ `seen=${describeRev(entry.seen_rev)} bytes=${entry.size} ` +
624
+ `${changeLabel} ${unread ? 'unread' : 'read'} ${tierLabel}`,
625
+ );
626
+ }
627
+ // q-sub-unify-p2 M5(§8 P2 项 3):隐式源默认开/已静音投影(纯读注册表,不物化)。
628
+ lines.push(...implicitSourceProjection(state));
629
+ return lines.join('\n');
630
+ }
631
+
632
+ /** 隐式固定推送源状态投影(lazy default-on D3:无条目=on;muted 条目才显式落盘) */
633
+ function implicitSourceProjection(state: SessionSubscriptionState): string[] {
634
+ const muted = (key: string): boolean => state.subscriptions[key]?.muted === true;
635
+ const lines = ['implicit fixed-push sources (default on; remove=mute, add=unmute):'];
636
+ for (const source of SOURCE_LEVEL_IMPLICIT_SOURCES) {
637
+ lines.push(` ${source}:* ${muted(implicitSubscriptionKey(source)) ? 'muted' : 'on'}`);
638
+ }
639
+ const mutedScopes = BUS_SUBSCRIPTION_SCOPES.filter((scope) => muted(busSubscriptionKey(scope)));
640
+ lines.push(
641
+ ` bus ${mutedScopes.length === 0 ? 'on (all scopes)' : `muted: ${mutedScopes.join(',')}`}`,
642
+ );
643
+ return lines;
644
+ }
645
+
646
+ /** 找到 inspect 的条目 key;id 优先于 node / path */
647
+ function resolveKey(
648
+ state: SessionSubscriptionState,
649
+ args: Record<string, unknown>,
650
+ deps: SubscribeToolDeps,
651
+ ): string | undefined {
652
+ const id = typeof args.id === 'string' && args.id.trim() !== '' ? args.id.trim() : undefined;
653
+ if (id !== undefined) {
654
+ return Object.keys(state.subscriptions).find(
655
+ (candidate) => state.subscriptions[candidate]?.id === id,
656
+ );
657
+ }
658
+ const rawNode =
659
+ typeof args.node === 'string' && args.node.trim() !== '' ? args.node.trim() : undefined;
660
+ if (rawNode !== undefined) return healthSubscriptionKey(rawNode);
661
+ const rawTarget =
662
+ typeof args.target === 'string' && args.target.trim() !== '' ? args.target.trim() : undefined;
663
+ if (rawTarget !== undefined) return agentSubscriptionKey(rawTarget);
664
+ const rawName =
665
+ typeof args.name === 'string' && args.name.trim() !== '' ? args.name.trim() : undefined;
666
+ if (rawName !== undefined) return scriptSubscriptionKey(rawName);
667
+ const rawPath =
668
+ typeof args.path === 'string' && args.path.trim() !== '' ? args.path.trim() : undefined;
669
+ if (rawPath === undefined) return undefined;
670
+ return canonicalPath(resolveInput(deps.config, rawPath));
671
+ }
672
+
673
+ /** inspect 的 XML 信封 */
674
+ function inspectEnvelope(
675
+ entry: SubscriptionEntry,
676
+ attrs: Record<string, string>,
677
+ body: string,
678
+ ): string {
679
+ const attrText = [
680
+ `path="${escapeXmlAttr(entry.path)}"`,
681
+ `id="${escapeXmlAttr(entry.id)}"`,
682
+ ...Object.entries(attrs).map(([key, value]) => `${key}="${escapeXmlAttr(value)}"`),
683
+ ].join(' ');
684
+ return `<subscription-inspect ${attrText}>\n${body}\n</subscription-inspect>`;
685
+ }
686
+
687
+ /**
688
+ * 显式读取订阅正文:首次 / 无快照给全文,之后给 diff。
689
+ * 只有成功返回正文才推进 seen_rev;失败 / 超限只更新观察值。
690
+ */
691
+ async function inspectSubscription(
692
+ state: SessionSubscriptionState,
693
+ args: Record<string, unknown>,
694
+ deps: SubscribeToolDeps,
695
+ now: number,
696
+ ): Promise<InspectOutcome> {
697
+ const key = resolveKey(state, args, deps);
698
+ if (key === undefined || state.subscriptions[key] === undefined) {
699
+ return { output: 'not_found: inspect 需要已订阅的 path 或 id。', changed: false };
700
+ }
701
+ const entry = state.subscriptions[key];
702
+ if (entry === undefined) return { output: 'not_found', changed: false };
703
+
704
+ if (evaluatePath(entry.path, deps.boundary) !== 'allow') {
705
+ return { output: 'path_denied: 路径已不在允许边界内。', changed: false };
706
+ }
707
+
708
+ let info: Awaited<ReturnType<typeof stat>> | undefined;
709
+ try {
710
+ info = await stat(entry.path);
711
+ } catch {
712
+ info = undefined;
713
+ }
714
+
715
+ if (info === undefined || info.isDirectory()) {
716
+ if (entry.seen_rev === 'deleted') {
717
+ return {
718
+ output: inspectEnvelope(entry, { status: 'deleted', change: 'none' }, 'File is deleted.'),
719
+ changed: false,
720
+ };
721
+ }
722
+ const next: SubscriptionEntry = {
723
+ ...entry,
724
+ rev: 'deleted',
725
+ notified_rev: 'deleted',
726
+ seen_rev: 'deleted',
727
+ size: 0,
728
+ mtime_ms: 0,
729
+ seen_at: now,
730
+ };
731
+ delete next.snapshot;
732
+ state.subscriptions[key] = next;
733
+ return {
734
+ output: inspectEnvelope(entry, { status: 'deleted', rev: 'deleted' }, 'File was deleted.'),
735
+ changed: true,
736
+ };
737
+ }
738
+
739
+ if (!info.isFile()) {
740
+ return { output: 'not_a_file: 订阅路径不是普通文件。', changed: false };
741
+ }
742
+ if (info.size > MAX_SUBSCRIBE_BYTES) {
743
+ return {
744
+ output: inspectEnvelope(
745
+ entry,
746
+ { status: 'too_large', bytes: String(info.size) },
747
+ 'File is too large; use bash to inspect it.',
748
+ ),
749
+ changed: false,
750
+ };
751
+ }
752
+
753
+ let buffer: Buffer;
754
+ try {
755
+ buffer = await readFile(entry.path);
756
+ } catch {
757
+ return { output: 'read_failed: 无法读取文件。', changed: false };
758
+ }
759
+
760
+ if (buffer.includes(0)) {
761
+ return {
762
+ output: inspectEnvelope(
763
+ entry,
764
+ { status: 'binary' },
765
+ 'File is binary; use bash to inspect it.',
766
+ ),
767
+ changed: false,
768
+ };
769
+ }
770
+
771
+ const hash = sha256Hex(buffer);
772
+ const text = buffer.toString('utf-8');
773
+
774
+ // 已看过同一版:不重复返回正文。
775
+ if (entry.seen_rev === hash) {
776
+ state.subscriptions[key] = {
777
+ ...entry,
778
+ rev: hash,
779
+ notified_rev: hash,
780
+ size: buffer.byteLength,
781
+ mtime_ms: info.mtimeMs,
782
+ };
783
+ return {
784
+ output: inspectEnvelope(
785
+ entry,
786
+ { rev: `sha256:${hash}`, change: 'none' },
787
+ 'No changes since the last inspect.',
788
+ ),
789
+ changed: true,
790
+ };
791
+ }
792
+
793
+ const baseAttrs = { rev: `sha256:${hash}` };
794
+
795
+ // 第一次(或没有快照):给全文;超限则降级。
796
+ if (entry.snapshot === undefined) {
797
+ if (buffer.byteLength > deps.config.maxFullBytes) {
798
+ state.subscriptions[key] = {
799
+ ...entry,
800
+ rev: hash,
801
+ size: buffer.byteLength,
802
+ mtime_ms: info.mtimeMs,
803
+ };
804
+ return {
805
+ output: inspectEnvelope(
806
+ entry,
807
+ { ...baseAttrs, status: 'too_large' },
808
+ `File is ${buffer.byteLength} bytes; use read to view it.`,
809
+ ),
810
+ changed: true,
811
+ };
812
+ }
813
+ const next: SubscriptionEntry = {
814
+ ...entry,
815
+ rev: hash,
816
+ notified_rev: hash,
817
+ seen_rev: hash,
818
+ size: buffer.byteLength,
819
+ mtime_ms: info.mtimeMs,
820
+ seen_at: now,
821
+ snapshot: text,
822
+ };
823
+ state.subscriptions[key] = next;
824
+ return {
825
+ output: inspectEnvelope(entry, { ...baseAttrs, change: 'full' }, text),
826
+ changed: true,
827
+ };
828
+ }
829
+
830
+ const diff = unifiedDiff(entry.snapshot, text, {
831
+ maxBytes: deps.config.maxDiffBytes,
832
+ maxLines: deps.config.maxDiffLines,
833
+ });
834
+ if (diff.truncated) {
835
+ // 不推进 seen_rev / notified_rev;下一次仍可按需 inspect 或 read。
836
+ state.subscriptions[key] = {
837
+ ...entry,
838
+ rev: hash,
839
+ size: buffer.byteLength,
840
+ mtime_ms: info.mtimeMs,
841
+ };
842
+ return {
843
+ output: inspectEnvelope(
844
+ entry,
845
+ { ...baseAttrs, change: 'diff_omitted' },
846
+ `Diff exceeded limits (${diff.bytes} bytes / ${diff.lines} lines); use read to view it.`,
847
+ ),
848
+ changed: true,
849
+ };
850
+ }
851
+
852
+ const next: SubscriptionEntry = {
853
+ ...entry,
854
+ rev: hash,
855
+ notified_rev: hash,
856
+ seen_rev: hash,
857
+ size: buffer.byteLength,
858
+ mtime_ms: info.mtimeMs,
859
+ seen_at: now,
860
+ };
861
+ if (buffer.byteLength <= deps.config.maxFullBytes) {
862
+ next.snapshot = text;
863
+ } else {
864
+ delete next.snapshot;
865
+ }
866
+ state.subscriptions[key] = next;
867
+ return {
868
+ output: inspectEnvelope(entry, { ...baseAttrs, change: 'diff' }, diff.text),
869
+ changed: true,
870
+ };
871
+ }
872
+
873
+ /**
874
+ * 校验并构造 team-log 条目(q-sub-unify-p2 M6;q-subscription-control 导出:
875
+ * 控制面 RPC add 复用,与工具面同口径单源)。canRead fail-closed 只订本 team;
876
+ * add 设基线 = 当前文件 size(不补历史);重复 add 保留已有游标。
877
+ */
878
+ export async function prepareTeamLogEntry(
879
+ input: string,
880
+ port: TeamLogPort,
881
+ sessionId: string,
882
+ existing: SubscriptionEntry | undefined,
883
+ ): Promise<AddOutcome> {
884
+ const target = input.trim();
885
+ if (target === '') return { input, reason: 'empty' };
886
+ if (!isValidTeamLogTarget(target)) return { input, reason: 'invalid_team_target' };
887
+ if (!(await port.canRead(target, sessionId))) return { input: target, reason: 'not_your_team' };
888
+ const filePath = port.pathFor(target);
889
+ if (filePath === undefined) return { input: target, reason: 'team_log_unavailable' };
890
+ let baseline = 0;
891
+ try {
892
+ baseline = (await stat(filePath)).size;
893
+ } catch {
894
+ // 日志尚未创建 ⇒ 基线 0(首条追加即通知)。
895
+ }
896
+ const key = teamLogSubscriptionKey(target);
897
+ return {
898
+ input: target,
899
+ entry: {
900
+ id: subscriptionId(key),
901
+ path: target,
902
+ input: target,
903
+ source: 'team-log',
904
+ rev: existing?.rev ?? `${baseline}:`,
905
+ notified_rev: existing?.notified_rev ?? `${baseline}:`,
906
+ seen_rev: existing?.seen_rev ?? '',
907
+ size: 0,
908
+ mtime_ms: existing?.mtime_ms ?? 0,
909
+ notified_at: existing?.notified_at ?? 0,
910
+ seen_at: existing?.seen_at ?? 0,
911
+ origin: existing?.origin ?? 'manual',
912
+ reads: [],
913
+ ...(existing?.friend !== undefined ? { friend: existing.friend } : {}),
914
+ },
915
+ };
916
+ }
917
+
918
+ /** 解析 health add 的输入目标列表(node + nodes,保持顺序) */
919
+ function collectNodeInputs(args: Record<string, unknown>): string[] {
920
+ const inputs: string[] = [];
921
+ const single = args.node;
922
+ if (typeof single === 'string' && single.trim() !== '') inputs.push(single);
923
+ const multiple = args.nodes;
924
+ if (Array.isArray(multiple)) {
925
+ for (const item of multiple) {
926
+ if (typeof item === 'string') inputs.push(item);
927
+ }
928
+ }
929
+ return inputs;
930
+ }
931
+
932
+ /**
933
+ * 校验并构造 health 条目(q-health-subscription)。
934
+ * 基线:快照文件已在 ⇒ rev = notified_rev = 当前签名(订阅时的状态不出卡,与文件
935
+ * manual add 同语义);快照缺失(watcher 尚未探测)⇒ rev='',首次观察通知当前状态
936
+ * (health 的「首次通知」是基线确立,文件的首次全文在 inspect,口径差异有意)。
937
+ * 重复 add 保留已有游标(避免无谓重通知)。
938
+ */
939
+ export async function prepareHealthEntry(
940
+ input: string,
941
+ deps: SubscribeToolDeps,
942
+ existing: SubscriptionEntry | undefined,
943
+ ): Promise<AddOutcome> {
944
+ const trimmed = input.trim();
945
+ if (trimmed === '') return { input, reason: 'empty' };
946
+ if (!isValidHealthTarget(trimmed)) return { input, reason: 'invalid_node_target' };
947
+
948
+ const snapshot = await readHealthSnapshot(deps.config.stateDir, trimmed);
949
+ const baseline = snapshot !== undefined ? healthSignature(snapshot) : '';
950
+ return {
951
+ input: trimmed,
952
+ entry: {
953
+ id: subscriptionId(trimmed),
954
+ path: trimmed,
955
+ input: trimmed,
956
+ source: 'health',
957
+ rev: existing?.rev ?? baseline,
958
+ notified_rev: existing?.notified_rev ?? baseline,
959
+ seen_rev: existing?.seen_rev ?? '',
960
+ size: 0,
961
+ mtime_ms: snapshot?.checked_at ?? 0,
962
+ notified_at: existing?.notified_at ?? 0,
963
+ seen_at: existing?.seen_at ?? 0,
964
+ origin: 'manual',
965
+ reads: [],
966
+ },
967
+ };
968
+ }
969
+
970
+ /** health inspect 的 XML 信封(与文件 inspect 同族;target 替代 path 属性) */
971
+ function healthInspectEnvelope(
972
+ entry: SubscriptionEntry,
973
+ attrs: Record<string, string>,
974
+ body: string,
975
+ ): string {
976
+ const attrText = [
977
+ `node="${escapeXmlAttr(entry.path)}"`,
978
+ `id="${escapeXmlAttr(entry.id)}"`,
979
+ ...Object.entries(attrs).map(([key, value]) => `${key}="${escapeXmlAttr(value)}"`),
980
+ ].join(' ');
981
+ return `<subscription-inspect ${attrText}>\n${body}\n</subscription-inspect>`;
982
+ }
983
+
984
+ /**
985
+ * 显式读取 health 订阅快照:返回宿主最近一次探测的事实(reachable / version /
986
+ * started_at / node_id / name / checked_at / error)。成功返回才推进 seen_rev
987
+ * (与文件 inspect 同口径);快照缺失不推进任何游标。
988
+ */
989
+ async function inspectHealth(
990
+ state: SessionSubscriptionState,
991
+ args: Record<string, unknown>,
992
+ deps: SubscribeToolDeps,
993
+ now: number,
994
+ ): Promise<InspectOutcome> {
995
+ const key = resolveKey(state, args, deps);
996
+ if (key === undefined || state.subscriptions[key] === undefined) {
997
+ return { output: 'not_found: inspect 需要已订阅的 node 或 id。', changed: false };
998
+ }
999
+ const entry = state.subscriptions[key];
1000
+ if (entry === undefined) return { output: 'not_found', changed: false };
1001
+
1002
+ const snapshot = await readHealthSnapshot(deps.config.stateDir, entry.path);
1003
+ if (snapshot === undefined) {
1004
+ return {
1005
+ output: healthInspectEnvelope(
1006
+ entry,
1007
+ { status: 'no_snapshot' },
1008
+ 'No health snapshot yet; the host health watcher has not probed this node.',
1009
+ ),
1010
+ changed: false,
1011
+ };
1012
+ }
1013
+
1014
+ const rev = healthSignature(snapshot);
1015
+ const attrs: Record<string, string> = {
1016
+ rev,
1017
+ status: snapshot.reachable ? 'up' : 'down',
1018
+ change: entry.seen_rev === rev ? 'none' : 'full',
1019
+ };
1020
+ if (snapshot.version !== undefined) attrs.version = snapshot.version;
1021
+ if (snapshot.started_at !== undefined) attrs.started_at = String(snapshot.started_at);
1022
+ if (snapshot.node_id !== undefined) attrs.node_id = snapshot.node_id;
1023
+ if (snapshot.name !== undefined) attrs.name = snapshot.name;
1024
+ if (snapshot.error !== undefined) attrs.error = snapshot.error;
1025
+
1026
+ const lines: string[] = [
1027
+ `target: ${snapshot.target}`,
1028
+ `reachable: ${snapshot.reachable ? 'yes' : 'no'}`,
1029
+ ];
1030
+ if (snapshot.node_id !== undefined) lines.push(`node_id: ${snapshot.node_id}`);
1031
+ if (snapshot.name !== undefined) lines.push(`name: ${snapshot.name}`);
1032
+ if (snapshot.version !== undefined) lines.push(`version: ${snapshot.version}`);
1033
+ if (snapshot.started_at !== undefined) {
1034
+ lines.push(
1035
+ `started_at: ${snapshot.started_at} (${new Date(snapshot.started_at).toISOString()})`,
1036
+ );
1037
+ }
1038
+ if (snapshot.pid !== undefined) lines.push(`pid: ${snapshot.pid}`);
1039
+ if (snapshot.via !== undefined) lines.push(`via: ${snapshot.via}`);
1040
+ lines.push(`checked_at: ${snapshot.checked_at} (${new Date(snapshot.checked_at).toISOString()})`);
1041
+ if (snapshot.error !== undefined) lines.push(`error: ${snapshot.error}`);
1042
+
1043
+ state.subscriptions[key] = {
1044
+ ...entry,
1045
+ rev,
1046
+ notified_rev: rev,
1047
+ seen_rev: rev,
1048
+ mtime_ms: snapshot.checked_at,
1049
+ seen_at: now,
1050
+ notified_at: entry.notified_rev === rev ? entry.notified_at : now,
1051
+ };
1052
+ return { output: healthInspectEnvelope(entry, attrs, lines.join('\n')), changed: true };
1053
+ }
1054
+
1055
+ /** 解析 agent add 的输入目标列表(target + targets,保持顺序;q-sub-unify-p1) */
1056
+ function collectAgentInputs(args: Record<string, unknown>): string[] {
1057
+ const inputs: string[] = [];
1058
+ const single = args.target;
1059
+ if (typeof single === 'string' && single.trim() !== '') inputs.push(single);
1060
+ const multiple = args.targets;
1061
+ if (Array.isArray(multiple)) {
1062
+ for (const item of multiple) {
1063
+ if (typeof item === 'string') inputs.push(item);
1064
+ }
1065
+ }
1066
+ return inputs;
1067
+ }
1068
+
1069
+ /**
1070
+ * 校验并构造 agent 条目(q-sub-unify-p1,照抄 prepareHealthEntry)。
1071
+ * 基线:快照已在 ⇒ rev = notified_rev = 当前签名;快照缺失(watcher 尚未落 /
1072
+ * private fail-closed)⇒ rev='',首次观察通知当前状态。重复 add 保留已有游标。
1073
+ * 已有 friend 块 / muted / origin 保留(好友边是成员级事实,不被手动 add 覆盖)。
1074
+ */
1075
+ export async function prepareAgentEntry(
1076
+ input: string,
1077
+ deps: SubscribeToolDeps,
1078
+ existing: SubscriptionEntry | undefined,
1079
+ ): Promise<AddOutcome> {
1080
+ const trimmed = input.trim();
1081
+ if (trimmed === '') return { input, reason: 'empty' };
1082
+ if (!isValidAgentTarget(trimmed)) return { input, reason: 'invalid_agent_target' };
1083
+
1084
+ const snapshot = await readAgentSnapshot(deps.config.stateDir, trimmed);
1085
+ const baseline = snapshot !== undefined ? agentSignature(snapshot) : '';
1086
+ return {
1087
+ input: trimmed,
1088
+ entry: {
1089
+ id: subscriptionId(trimmed),
1090
+ path: trimmed,
1091
+ input: trimmed,
1092
+ source: 'agent',
1093
+ rev: existing?.rev ?? baseline,
1094
+ notified_rev: existing?.notified_rev ?? baseline,
1095
+ seen_rev: existing?.seen_rev ?? '',
1096
+ size: 0,
1097
+ mtime_ms: snapshot?.checked_at ?? 0,
1098
+ notified_at: existing?.notified_at ?? 0,
1099
+ seen_at: existing?.seen_at ?? 0,
1100
+ origin: existing?.origin ?? 'manual',
1101
+ reads: [],
1102
+ // q-sub-unify-p2 M5(D-4):add = 复订 ⇒ 清 muted(取关的逆操作;
1103
+ // friend 边保留——取关≠删好友,复订≠重建好友)。
1104
+ ...(existing?.friend !== undefined ? { friend: existing.friend } : {}),
1105
+ },
1106
+ };
1107
+ }
1108
+
1109
+ /** agent inspect 的 XML 信封(与 health inspect 同族;target 替代 node 属性) */
1110
+ function agentInspectEnvelope(
1111
+ entry: SubscriptionEntry,
1112
+ attrs: Record<string, string>,
1113
+ body: string,
1114
+ ): string {
1115
+ const attrText = [
1116
+ `agent="${escapeXmlAttr(entry.path)}"`,
1117
+ `id="${escapeXmlAttr(entry.id)}"`,
1118
+ ...Object.entries(attrs).map(([key, value]) => `${key}="${escapeXmlAttr(value)}"`),
1119
+ ].join(' ');
1120
+ return `<subscription-inspect ${attrText}>\n${body}\n</subscription-inspect>`;
1121
+ }
1122
+
1123
+ /**
1124
+ * team-log inspect(q-sub-unify-p2 M6):有界尾窗口回放近期条目(≤8MiB / ≤50 条素材),
1125
+ * 只推进 seen_rev 读标记,不动 notified_rev 通知游标。端口缺省 / 文件缺失 ⇒ 无观察。
1126
+ */
1127
+ async function inspectTeamLog(
1128
+ state: SessionSubscriptionState,
1129
+ args: Record<string, unknown>,
1130
+ deps: SubscribeToolDeps,
1131
+ sessionId: string,
1132
+ now: number,
1133
+ ): Promise<InspectOutcome> {
1134
+ const id = typeof args.id === 'string' && args.id.trim() !== '' ? args.id.trim() : undefined;
1135
+ const rawTarget =
1136
+ typeof args.target === 'string' && args.target.trim() !== '' ? args.target.trim() : undefined;
1137
+ const key =
1138
+ id !== undefined
1139
+ ? Object.keys(state.subscriptions).find((k) => state.subscriptions[k]?.id === id)
1140
+ : rawTarget !== undefined
1141
+ ? teamLogSubscriptionKey(rawTarget)
1142
+ : undefined;
1143
+ const entry = key !== undefined ? state.subscriptions[key] : undefined;
1144
+ if (key === undefined || entry === undefined || entry.source !== 'team-log') {
1145
+ return { output: 'not_found: inspect 需要已订阅的 team-log 或 id。', changed: false };
1146
+ }
1147
+ let observation: Awaited<ReturnType<typeof observeTeamLogEntry>>;
1148
+ try {
1149
+ observation = await observeTeamLogEntry({ ...entry, rev: '0:' }, deps.teamLog, sessionId);
1150
+ } catch {
1151
+ observation = undefined;
1152
+ }
1153
+ if (observation === undefined) {
1154
+ return { output: 'no observation: team-log 端口 / 文件不可用。', changed: false };
1155
+ }
1156
+ const lines = observation.entries.map(
1157
+ (item) =>
1158
+ ` <entry from="${escapeXmlAttr(item.from)}" kind="${item.kind}" ` +
1159
+ `ts="${new Date(item.ts).toISOString()}" /> ${item.preview}`,
1160
+ );
1161
+ if (observation.truncated) lines.push(' … older entries skipped (8MiB window)');
1162
+ const body = lines.length > 0 ? lines.join('\n') : ' (no entries yet)';
1163
+ const output =
1164
+ `<subscription-inspect teamlog="${escapeXmlAttr(entry.path)}" id="${escapeXmlAttr(entry.id)}" ` +
1165
+ `entries="${observation.entries.length}">\n${body}\n</subscription-inspect>`;
1166
+ state.subscriptions[key] = { ...entry, seen_rev: entry.rev, seen_at: now };
1167
+ return { output, changed: true };
1168
+ }
1169
+
1170
+ /**
1171
+ * 显式读取 agent 订阅快照:返回宿主最近一次折叠的活动事实(state / presence /
1172
+ * role / last_run_ts / name / team_id / checked_at)。成功返回才推进 seen_rev;
1173
+ * 快照缺失不推进任何游标(照抄 inspectHealth)。
1174
+ */
1175
+ async function inspectAgent(
1176
+ state: SessionSubscriptionState,
1177
+ args: Record<string, unknown>,
1178
+ deps: SubscribeToolDeps,
1179
+ now: number,
1180
+ ): Promise<InspectOutcome> {
1181
+ const key = resolveKey(state, args, deps);
1182
+ if (key === undefined || state.subscriptions[key] === undefined) {
1183
+ return { output: 'not_found: inspect 需要已订阅的 agent 或 id。', changed: false };
1184
+ }
1185
+ const entry = state.subscriptions[key];
1186
+ if (entry === undefined) return { output: 'not_found', changed: false };
1187
+
1188
+ const snapshot = await readAgentSnapshot(deps.config.stateDir, entry.path);
1189
+ if (snapshot === undefined) {
1190
+ return {
1191
+ output: agentInspectEnvelope(
1192
+ entry,
1193
+ { status: 'no_snapshot' },
1194
+ 'No activity snapshot yet; the host agent watcher has not observed this member (private members never produce snapshots).',
1195
+ ),
1196
+ changed: false,
1197
+ };
1198
+ }
1199
+
1200
+ const rev = agentSignature(snapshot);
1201
+ const attrs: Record<string, string> = {
1202
+ rev,
1203
+ state: snapshot.state ?? '-',
1204
+ change: entry.seen_rev === rev ? 'none' : 'full',
1205
+ };
1206
+ if (snapshot.presence !== undefined) attrs.presence = snapshot.presence;
1207
+ if (snapshot.role !== undefined) attrs.role = snapshot.role;
1208
+ if (snapshot.last_run_ts !== undefined) attrs.last_run_ts = String(snapshot.last_run_ts);
1209
+ if (snapshot.name !== undefined) attrs.name = snapshot.name;
1210
+ if (snapshot.team_id !== undefined) attrs.team_id = snapshot.team_id;
1211
+
1212
+ const lines: string[] = [`target: ${snapshot.target}`];
1213
+ if (snapshot.name !== undefined) lines.push(`name: ${snapshot.name}`);
1214
+ if (snapshot.team_id !== undefined) lines.push(`team_id: ${snapshot.team_id}`);
1215
+ if (snapshot.visibility !== undefined) lines.push(`visibility: ${snapshot.visibility}`);
1216
+ lines.push(`state: ${snapshot.state ?? '-'}`);
1217
+ lines.push(`presence: ${snapshot.presence ?? '-'}`);
1218
+ lines.push(`role: ${snapshot.role ?? '-'}`);
1219
+ if (snapshot.last_run_ts !== undefined) {
1220
+ lines.push(
1221
+ `last_run_ts: ${snapshot.last_run_ts} (${new Date(snapshot.last_run_ts).toISOString()})`,
1222
+ );
1223
+ }
1224
+ if (snapshot.last_event_type !== undefined)
1225
+ lines.push(`last_event_type: ${snapshot.last_event_type}`);
1226
+ if (snapshot.via !== undefined) lines.push(`via: ${snapshot.via}`);
1227
+ lines.push(`checked_at: ${snapshot.checked_at} (${new Date(snapshot.checked_at).toISOString()})`);
1228
+ if (entry.friend !== undefined) {
1229
+ lines.push(
1230
+ `friend: origin=${entry.friend.origin} since=${entry.friend.since}${entry.friend.nick !== undefined ? ` nick=${entry.friend.nick}` : ''}`,
1231
+ );
1232
+ }
1233
+
1234
+ state.subscriptions[key] = {
1235
+ ...entry,
1236
+ rev,
1237
+ notified_rev: rev,
1238
+ seen_rev: rev,
1239
+ mtime_ms: snapshot.checked_at,
1240
+ seen_at: now,
1241
+ notified_at: entry.notified_rev === rev ? entry.notified_at : now,
1242
+ };
1243
+ return { output: agentInspectEnvelope(entry, attrs, lines.join('\n')), changed: true };
1244
+ }
1245
+
1246
+ /** 解析 script add 的输入名列表(name + names,保持顺序) */
1247
+ function collectNameInputs(args: Record<string, unknown>): string[] {
1248
+ const inputs: string[] = [];
1249
+ const single = args.name;
1250
+ if (typeof single === 'string' && single.trim() !== '') inputs.push(single);
1251
+ const multiple = args.names;
1252
+ if (Array.isArray(multiple)) {
1253
+ for (const item of multiple) {
1254
+ if (typeof item === 'string') inputs.push(item);
1255
+ }
1256
+ }
1257
+ return inputs;
1258
+ }
1259
+
1260
+ /**
1261
+ * 校验并构造 script 条目(q-subscription-script,设计 §2.7 fail-closed):
1262
+ * 名字必须合法且在 **live allowlist**(用户配置 plugins.doc-subscription.config.scripts)
1263
+ * 里 —— 模型只能按名订阅已声明的脚本,不能注入 / 修改命令。
1264
+ * 基线:rev=''(首次成功输出全量投递,裁点 2:存量问题立刻可见;不同于 file/health
1265
+ * 的订阅时基线抑制)。重复 add 保留已有游标 / snapshot / 执行事实。
1266
+ */
1267
+ export function prepareScriptEntry(
1268
+ input: string,
1269
+ config: DocSubscriptionConfig,
1270
+ existing: SubscriptionEntry | undefined,
1271
+ ): AddOutcome {
1272
+ const trimmed = input.trim();
1273
+ if (trimmed === '') return { input, reason: 'empty' };
1274
+ if (!isValidScriptName(trimmed)) return { input, reason: 'invalid_script_name' };
1275
+ if (!config.scripts.some((spec) => spec.name === trimmed)) {
1276
+ return { input, reason: 'not_in_allowlist' };
1277
+ }
1278
+ return {
1279
+ input: trimmed,
1280
+ entry: {
1281
+ id: subscriptionId(trimmed),
1282
+ path: trimmed,
1283
+ input: trimmed,
1284
+ source: 'script',
1285
+ rev: existing?.rev ?? '',
1286
+ notified_rev: existing?.notified_rev ?? '',
1287
+ seen_rev: existing?.seen_rev ?? '',
1288
+ size: existing?.size ?? 0,
1289
+ mtime_ms: existing?.mtime_ms ?? 0,
1290
+ notified_at: existing?.notified_at ?? 0,
1291
+ seen_at: existing?.seen_at ?? 0,
1292
+ origin: 'manual',
1293
+ reads: [],
1294
+ ...(existing?.snapshot !== undefined ? { snapshot: existing.snapshot } : {}),
1295
+ ...(existing?.script !== undefined ? { script: existing.script } : {}),
1296
+ },
1297
+ };
1298
+ }
1299
+
1300
+ /** script inspect 的 XML 信封(与 file / health 同族;name 替代 path 属性) */
1301
+ function scriptInspectEnvelope(
1302
+ entry: SubscriptionEntry,
1303
+ attrs: Record<string, string>,
1304
+ body: string,
1305
+ ): string {
1306
+ const attrText = [
1307
+ `name="${escapeXmlAttr(entry.path)}"`,
1308
+ `id="${escapeXmlAttr(entry.id)}"`,
1309
+ ...Object.entries(attrs).map(([key, value]) => `${key}="${escapeXmlAttr(value)}"`),
1310
+ ].join(' ');
1311
+ return `<subscription-inspect ${attrText}>\n${body}\n</subscription-inspect>`;
1312
+ }
1313
+
1314
+ /**
1315
+ * 显式读取 script 订阅:返回最近一次成功 stdout 全文(设计 §2.6:通知只带 diff /
1316
+ * 摘要,全文在 inspect)+ 执行事实(last_exit / duration / schedule / output)。
1317
+ * 成功返回才推进 seen_rev(与 file / health 同口径);无输出不推进。
1318
+ * 命令本体来自 live allowlist(只读展示;模型不能经工具修改)。
1319
+ */
1320
+ function inspectScript(
1321
+ state: SessionSubscriptionState,
1322
+ args: Record<string, unknown>,
1323
+ deps: SubscribeToolDeps,
1324
+ config: DocSubscriptionConfig,
1325
+ now: number,
1326
+ ): InspectOutcome {
1327
+ const key = resolveKey(state, args, deps);
1328
+ if (key === undefined || state.subscriptions[key] === undefined) {
1329
+ return { output: 'not_found: inspect 需要已订阅的 name 或 id。', changed: false };
1330
+ }
1331
+ const entry = state.subscriptions[key];
1332
+ if (entry === undefined || entry.source !== 'script') {
1333
+ return { output: 'not_found', changed: false };
1334
+ }
1335
+ const spec = config.scripts.find((candidate) => candidate.name === entry.path);
1336
+ const facts = entry.script;
1337
+ const attrs: Record<string, string> = {
1338
+ rev:
1339
+ entry.rev === ''
1340
+ ? 'never'
1341
+ : entry.rev === 'empty'
1342
+ ? 'empty'
1343
+ : `sha256:${entry.rev.slice(0, 12)}`,
1344
+ exit:
1345
+ facts === undefined
1346
+ ? 'never_run'
1347
+ : facts.last_exit === null
1348
+ ? facts.last_error !== undefined
1349
+ ? 'failed'
1350
+ : 'running'
1351
+ : String(facts.last_exit),
1352
+ };
1353
+ if (spec !== undefined) {
1354
+ attrs.schedule =
1355
+ typeof spec.schedule === 'object'
1356
+ ? `interval:${spec.schedule.intervalSeconds}s`
1357
+ : spec.schedule;
1358
+ attrs.output = spec.output;
1359
+ } else {
1360
+ attrs.status = 'not_in_allowlist';
1361
+ }
1362
+
1363
+ const factLines: string[] = [];
1364
+ if (facts !== undefined) {
1365
+ const exitText =
1366
+ facts.last_exit === null
1367
+ ? facts.last_error !== undefined
1368
+ ? 'failed'
1369
+ : 'running'
1370
+ : String(facts.last_exit);
1371
+ factLines.push(`last_exit: ${exitText}`);
1372
+ factLines.push(`last_duration_ms: ${facts.last_duration_ms}`);
1373
+ if (facts.last_started_at > 0) {
1374
+ factLines.push(
1375
+ `last_started_at: ${facts.last_started_at} (${new Date(facts.last_started_at).toISOString()})`,
1376
+ );
1377
+ }
1378
+ if (facts.last_error !== undefined) factLines.push(`last_error: ${facts.last_error}`);
1379
+ }
1380
+ if (spec !== undefined) factLines.push(`command: ${JSON.stringify(spec.command)}`);
1381
+ const inFlight = deps.runner?.isInFlight(scriptFlightKey(state.session_id, entry.path)) ?? false;
1382
+ if (inFlight) factLines.push('status: running (a new execution is in flight)');
1383
+
1384
+ // 无全文可给:从未完成 / 空输出 / 超 maxFullBytes 未存 snapshot。
1385
+ if (entry.snapshot === undefined) {
1386
+ const body =
1387
+ entry.rev === 'empty'
1388
+ ? 'Script produced no output (empty = no issues).'
1389
+ : entry.rev === ''
1390
+ ? 'No output yet; the script has not completed a run.'
1391
+ : `Output is ${entry.size} bytes (over the full-content limit); use bash to run the script directly.`;
1392
+ return {
1393
+ output: scriptInspectEnvelope(entry, attrs, [...factLines, body].join('\n')),
1394
+ changed: false,
1395
+ };
1396
+ }
1397
+
1398
+ state.subscriptions[key] = { ...entry, seen_rev: entry.rev, seen_at: now };
1399
+ const body = [...factLines, '', entry.snapshot].join('\n');
1400
+ return {
1401
+ output: scriptInspectEnvelope(entry, { ...attrs, change: 'full' }, body),
1402
+ changed: true,
1403
+ };
1404
+ }
1405
+
1406
+ /** 构造 subscribe 工具 */
1407
+ export function createSubscribeTool(deps: SubscribeToolDeps): ToolDefinition {
1408
+ return {
1409
+ name: 'subscribe',
1410
+ description:
1411
+ 'Manage per-session subscriptions. add/remove/list/inspect concrete files; ' +
1412
+ 'changes produce a short notice, and inspect returns the diff (full content on first read). ' +
1413
+ 'edit/write auto-subscribe the files they touch (subscribe:false on those tools opts out); ' +
1414
+ 'read does NOT auto-subscribe by default (subscribe:true on read opts in). ' +
1415
+ "Entries carry a tier derived from origin: auto (read/edit, the current body's working set — " +
1416
+ 'dropped on rotate, re-attached on the next edit/write) vs persistent (manual/implicit — ' +
1417
+ 'kept across rotate). list shows tier per entry. ' +
1418
+ 'source:"health" subscribes a node\'s health instead of a file: node is a local node_id ' +
1419
+ 'or a federation address <principal>@<node_id>:<team_id>; reachability flips, version ' +
1420
+ 'changes and restarts (started_at) produce a health notice, inspect returns the snapshot. ' +
1421
+ 'source:"script" subscribes a detection script declared in the user config allowlist ' +
1422
+ '(plugins.doc-subscription.config.scripts): name must match a declared script (you cannot ' +
1423
+ 'add or change commands); its stdout changes produce a script notice (empty output = no ' +
1424
+ 'notice), inspect returns the latest full output. ' +
1425
+ 'source:"agent" subscribes a member\'s activity instead of a file: target is a local ' +
1426
+ 'agent_id or a federation address <principal>@<node_id>:<team_id>; state/presence flips, ' +
1427
+ 'role changes and run completions produce an agent notice, inspect returns the activity ' +
1428
+ 'snapshot (private members never produce snapshots). ' +
1429
+ 'use remove to clear subscriptions you no longer need (e.g. when switching tasks); ' +
1430
+ 'remove on a dead target (deleted file / closed agent / agent confirmed missing from the ' +
1431
+ 'registry) truly deletes it (including friend ' +
1432
+ 'edges), while remove on a live agent friend/implicit entry only mutes it. ' +
1433
+ 'action "prune" clears all dead-target subscriptions of this session in one call ' +
1434
+ '(including manual dead entries). remove without a single target accepts bulk filters ' +
1435
+ '(source/tier/prefix/dead_only); a bare full clear (no target, no filter) returns a ' +
1436
+ 'preview unless confirm:true is passed.',
1437
+ inputSchema: {
1438
+ type: 'object',
1439
+ properties: {
1440
+ action: {
1441
+ type: 'string',
1442
+ enum: ['add', 'remove', 'list', 'inspect', 'prune'],
1443
+ description: 'add | remove | list | inspect | prune (default list)',
1444
+ },
1445
+ source: {
1446
+ type: 'string',
1447
+ enum: ['file', 'health', 'script', 'agent', 'inbox', 'bash-job', 'bus', 'team-log'],
1448
+ description:
1449
+ 'Subscription source type (default file). inbox/bash-job/bus are implicit fixed-push ' +
1450
+ 'sources (default on): remove = mute reminders, add = unmute. bus target = scope word ' +
1451
+ '(config/permission/tools/mcp/update); inbox/bash-job target = "*".',
1452
+ },
1453
+ path: { type: 'string', description: 'Single file path (add / remove / inspect)' },
1454
+ paths: {
1455
+ type: 'array',
1456
+ items: { type: 'string' },
1457
+ description: 'Multiple file paths (add only)',
1458
+ },
1459
+ node: {
1460
+ type: 'string',
1461
+ description:
1462
+ 'Single node target (source:health add / remove / inspect): local node_id or <principal>@<node_id>:<team_id>',
1463
+ },
1464
+ nodes: {
1465
+ type: 'array',
1466
+ items: { type: 'string' },
1467
+ description: 'Multiple node targets (source:health add only)',
1468
+ },
1469
+ target: {
1470
+ type: 'string',
1471
+ description:
1472
+ 'Single agent target (source:agent add / remove / inspect): local agent_id or <principal>@<node_id>:<team_id>',
1473
+ },
1474
+ targets: {
1475
+ type: 'array',
1476
+ items: { type: 'string' },
1477
+ description: 'Multiple agent targets (source:agent add only)',
1478
+ },
1479
+ name: {
1480
+ type: 'string',
1481
+ description:
1482
+ 'Single script name (source:script add / remove / inspect): must be declared in the user config allowlist',
1483
+ },
1484
+ names: {
1485
+ type: 'array',
1486
+ items: { type: 'string' },
1487
+ description: 'Multiple script names (source:script add only)',
1488
+ },
1489
+ id: { type: 'string', description: 'Subscription id (remove / inspect)' },
1490
+ tier: {
1491
+ type: 'string',
1492
+ enum: ['auto', 'persistent'],
1493
+ description:
1494
+ 'Bulk remove filter: tier derived from origin (auto = read/edit auto-subscribed; ' +
1495
+ 'persistent = manual/implicit). Combinable with source/prefix/dead_only.',
1496
+ },
1497
+ prefix: {
1498
+ type: 'string',
1499
+ description: 'Bulk remove filter: path/target prefix match.',
1500
+ },
1501
+ dead_only: {
1502
+ type: 'boolean',
1503
+ description:
1504
+ 'Bulk remove filter: only dead targets (deleted files / closed agents / agents ' +
1505
+ 'confirmed missing from the registry / delisted scripts; fail-closed: a missing ' +
1506
+ 'snapshot or a registry read failure is NOT dead).',
1507
+ },
1508
+ confirm: {
1509
+ type: 'boolean',
1510
+ description:
1511
+ 'Required to execute a bare full clear (remove with no target and no filter). ' +
1512
+ 'Without it, remove returns a preview (counts + entries) and does not execute.',
1513
+ },
1514
+ },
1515
+ },
1516
+ display: { label: 'Subscribe', kind: 'generic' },
1517
+ // 校验全部在 handler;工具不写日志
1518
+ checkPermission: async () => 'allow',
1519
+ handler: async (args: unknown, ctx: ToolContext): Promise<string> => {
1520
+ if (!isRecord(args)) return '错误:subscribe 需要 { action }';
1521
+ // 零参 peek 范式(对齐 skills/recall):缺省 action = list,只读计数不消费。
1522
+ const action = args.action ?? 'list';
1523
+ if (
1524
+ action !== 'add' &&
1525
+ action !== 'remove' &&
1526
+ action !== 'list' &&
1527
+ action !== 'inspect' &&
1528
+ action !== 'prune'
1529
+ ) {
1530
+ return '错误:action 必须是 add / remove / list / inspect / prune。';
1531
+ }
1532
+
1533
+ const sessionId = ctx.session_id ?? 'default';
1534
+ // live 配置(q-subscription-script):allowlist / 调度每次调用求值,热改即时生效。
1535
+ const config = liveConfigOf(deps);
1536
+ const effectiveDeps: SubscribeToolDeps = { ...deps, config };
1537
+ let state: SessionSubscriptionState;
1538
+ try {
1539
+ state = await deps.store.load(sessionId);
1540
+ } catch {
1541
+ return '错误:读取订阅状态失败。';
1542
+ }
1543
+
1544
+ if (action === 'list') return formatList(state);
1545
+
1546
+ if (action === 'inspect') {
1547
+ // health / script 源(additive):按条目 source 分派;file 路径逐字节不变。
1548
+ const inspectKey = resolveKey(state, args, effectiveDeps);
1549
+ const inspectSource =
1550
+ inspectKey !== undefined ? state.subscriptions[inspectKey]?.source : undefined;
1551
+ const outcome =
1552
+ inspectSource === 'health'
1553
+ ? await inspectHealth(state, args, effectiveDeps, Date.now())
1554
+ : inspectSource === 'agent'
1555
+ ? await inspectAgent(state, args, effectiveDeps, Date.now())
1556
+ : inspectSource === 'team-log'
1557
+ ? await inspectTeamLog(state, args, effectiveDeps, sessionId, Date.now())
1558
+ : inspectSource === 'script'
1559
+ ? inspectScript(state, args, effectiveDeps, config, Date.now())
1560
+ : await inspectSubscription(state, args, effectiveDeps, Date.now());
1561
+ if (outcome.changed) {
1562
+ try {
1563
+ await deps.store.save(state);
1564
+ } catch {
1565
+ return '错误:保存订阅状态失败。';
1566
+ }
1567
+ }
1568
+ return outcome.output;
1569
+ }
1570
+
1571
+ if (action === 'remove') {
1572
+ // q-sub-unify-p2 M6:team-log 显式订阅 ⇒ remove 删除条目(P1 语义;id 路径走 formatRemove)。
1573
+ if (args.source === 'team-log' && typeof args.target === 'string') {
1574
+ const raw = args.target.trim();
1575
+ const key = raw !== '' ? teamLogSubscriptionKey(raw) : undefined;
1576
+ if (key === undefined || state.subscriptions[key] === undefined) {
1577
+ return `not_found: ${raw}`;
1578
+ }
1579
+ delete state.subscriptions[key];
1580
+ try {
1581
+ await deps.store.save(state);
1582
+ } catch {
1583
+ return '错误:保存订阅状态失败。';
1584
+ }
1585
+ return `removed: ${key}`;
1586
+ }
1587
+ // q-sub-unify-p2 M5(§4.4):隐式源 remove = 写 muted(退订提醒;lazy
1588
+ // default-on D3——无条目=on,静音才落条目)。bus 按 scope 词,inbox/bash-job 源级 '*'。
1589
+ const removeSource = args.source;
1590
+ if (removeSource === 'inbox' || removeSource === 'bash-job' || removeSource === 'bus') {
1591
+ return await muteImplicitSource(state, removeSource, args, deps);
1592
+ }
1593
+ const hasSingleSelector =
1594
+ (typeof args.path === 'string' && args.path.trim() !== '') ||
1595
+ (typeof args.node === 'string' && args.node.trim() !== '') ||
1596
+ (typeof args.target === 'string' && args.target.trim() !== '') ||
1597
+ (typeof args.name === 'string' && args.name.trim() !== '') ||
1598
+ (typeof args.id === 'string' && args.id.trim() !== '');
1599
+ if (hasSingleSelector) {
1600
+ const result = await formatRemove(
1601
+ state,
1602
+ args,
1603
+ (input) => resolveInput(config, input),
1604
+ effectiveDeps,
1605
+ );
1606
+ if (result.startsWith('removed:') || result.startsWith('muted:')) {
1607
+ // script 源 remove ⇒ disarm interval 真 timer(q-subscription-script-p1;
1608
+ // 在飞进程不杀,受各自超时闸约束,结果丢一次可接受——订阅已删不再 drain)。
1609
+ const removedKey = result.slice('removed: '.length);
1610
+ if (removedKey.startsWith('script:')) {
1611
+ deps.runner?.disarmInterval(
1612
+ scriptFlightKey(sessionId, removedKey.slice('script:'.length)),
1613
+ );
1614
+ }
1615
+ try {
1616
+ await deps.store.save(state);
1617
+ } catch {
1618
+ return '错误:保存订阅状态失败。';
1619
+ }
1620
+ }
1621
+ return result;
1622
+ }
1623
+ // 无单目标 ⇒ bulk 过滤 / 裸全清(下方与 prune 共用单源路径)。
1624
+ }
1625
+
1626
+ // §14 bulk-prune(q-subscription-lifecycle B1,S7):prune = dead-only 一键清
1627
+ // (含 manual 死条目 = S3 逃生口批量版,手动动作非自动 prune);remove 无单目标 ⇒
1628
+ // 过滤 bulk(source/tier/prefix/dead_only);裸全清(无过滤)缺省预览不执行,
1629
+ // confirm:true 才执行。逐条语义复用 removeSubscriptionEntry 单源;一次 store.mutate
1630
+ // per-session 串行链内循环原子落盘。
1631
+ if (action === 'remove' || action === 'prune') {
1632
+ const parsed = action === 'prune' ? { deadOnly: true } : parseBulkFilter(args);
1633
+ if (typeof parsed === 'string') return parsed;
1634
+ const filter = parsed;
1635
+ const bareFullClear =
1636
+ action === 'remove' &&
1637
+ filter.source === undefined &&
1638
+ filter.tier === undefined &&
1639
+ filter.prefix === undefined &&
1640
+ filter.deadOnly !== true;
1641
+ if (bareFullClear && args.confirm !== true) {
1642
+ // 预览:同一决策函数跑 state 副本(零副作用不写盘);二次意图表达后才执行。
1643
+ const preview = await runBulkRemove(structuredClone(state), filter, effectiveDeps);
1644
+ return formatBulkOutcome(preview, true);
1645
+ }
1646
+ let outcome: SubscriptionBulkOutcome = {
1647
+ removed: 0,
1648
+ muted: 0,
1649
+ preserved: 0,
1650
+ entries: [],
1651
+ truncated: false,
1652
+ };
1653
+ try {
1654
+ await deps.store.mutate(sessionId, async (fresh) => {
1655
+ outcome = await runBulkRemove(fresh, filter, effectiveDeps);
1656
+ return outcome.removed > 0 || outcome.muted > 0 ? fresh : undefined;
1657
+ });
1658
+ } catch {
1659
+ return '错误:保存订阅状态失败。';
1660
+ }
1661
+ disarmRemovedScripts(outcome, deps, sessionId);
1662
+ return formatBulkOutcome(outcome, false);
1663
+ }
1664
+
1665
+ // add:source 泛化(q-health-subscription / q-subscription-script / q-sub-unify-p1)——
1666
+ // 缺省 'file'(零回归);'health' 走 node/nodes;'script' 走 name/names;'agent' 走 target/targets。
1667
+ const source = args.source ?? 'file';
1668
+ if (
1669
+ source !== 'file' &&
1670
+ source !== 'health' &&
1671
+ source !== 'script' &&
1672
+ source !== 'agent' &&
1673
+ source !== 'inbox' &&
1674
+ source !== 'bash-job' &&
1675
+ source !== 'bus' &&
1676
+ source !== 'team-log'
1677
+ ) {
1678
+ return '错误:source 必须是 file / health / script / agent / inbox / bash-job / bus / team-log。';
1679
+ }
1680
+
1681
+ // q-sub-unify-p2 M6:team-log 活动订阅(显式条目,offset 游标;canRead fail-closed
1682
+ // 只订本 team;端口缺省 ⇒ 不可订)。add 设基线 = 当前文件 size(不补历史)。
1683
+ if (source === 'team-log') {
1684
+ const inputs = collectAgentInputs(args);
1685
+ if (inputs.length === 0) return '错误:source:team-log add 需要 target 或 targets。';
1686
+ const port = deps.teamLog;
1687
+ if (port === undefined) return '错误:team-log 端口未装配,无法订阅。';
1688
+ const added: SubscriptionEntry[] = [];
1689
+ const rejected: Array<{ input: string; reason: string }> = [];
1690
+ const seen = new Set<string>();
1691
+ for (const input of inputs) {
1692
+ const target = input.trim();
1693
+ if (seen.has(target)) continue;
1694
+ seen.add(target);
1695
+ const key = teamLogSubscriptionKey(target);
1696
+ const outcome = await prepareTeamLogEntry(
1697
+ target,
1698
+ port,
1699
+ sessionId,
1700
+ state.subscriptions[key],
1701
+ );
1702
+ if (outcome.entry === undefined) {
1703
+ rejected.push({ input: outcome.input, reason: outcome.reason ?? 'invalid' });
1704
+ continue;
1705
+ }
1706
+ state.subscriptions[key] = outcome.entry;
1707
+ added.push(outcome.entry);
1708
+ }
1709
+ if (added.length > 0) {
1710
+ try {
1711
+ await deps.store.save(state);
1712
+ } catch {
1713
+ return '错误:保存订阅状态失败。';
1714
+ }
1715
+ }
1716
+ const lines: string[] = [];
1717
+ if (added.length > 0) {
1718
+ lines.push(`added ${added.length}:`);
1719
+ for (const entry of added) lines.push(` ${entry.path} (team-log)`);
1720
+ lines.push(
1721
+ 'New team log entries will produce a short notice; ' +
1722
+ 'use action "inspect" to view recent entries.',
1723
+ );
1724
+ }
1725
+ if (rejected.length > 0) {
1726
+ lines.push(`rejected ${rejected.length}:`);
1727
+ for (const item of rejected) lines.push(` ${item.reason}: ${item.input}`);
1728
+ }
1729
+ return lines.join('\n');
1730
+ }
1731
+
1732
+ // q-sub-unify-p2 M5(§4.4):隐式源 add = 清 muted(复订;lazy D3——解静音
1733
+ // 删除条目恢复无条目=on 静息态,零物化)。
1734
+ if (source === 'inbox' || source === 'bash-job' || source === 'bus') {
1735
+ return await unmuteImplicitSource(state, source, args, deps);
1736
+ }
1737
+
1738
+ if (source === 'agent') {
1739
+ const inputs = collectAgentInputs(args);
1740
+ if (inputs.length === 0) return '错误:source:agent add 需要 target 或 targets。';
1741
+ const added: SubscriptionEntry[] = [];
1742
+ const rejected: Array<{ input: string; reason: string }> = [];
1743
+ const seen = new Set<string>();
1744
+ for (const input of inputs) {
1745
+ const target = input.trim();
1746
+ if (seen.has(target)) continue;
1747
+ seen.add(target);
1748
+ const key = agentSubscriptionKey(target);
1749
+ const outcome = await prepareAgentEntry(target, deps, state.subscriptions[key]);
1750
+ if (outcome.entry === undefined) {
1751
+ rejected.push({ input: outcome.input, reason: outcome.reason ?? 'invalid' });
1752
+ continue;
1753
+ }
1754
+ state.subscriptions[key] = outcome.entry;
1755
+ added.push(outcome.entry);
1756
+ }
1757
+ if (added.length > 0) {
1758
+ try {
1759
+ await deps.store.save(state);
1760
+ } catch {
1761
+ return '错误:保存订阅状态失败。';
1762
+ }
1763
+ }
1764
+ const lines: string[] = [];
1765
+ if (added.length > 0) {
1766
+ lines.push(`added ${added.length}:`);
1767
+ for (const entry of added) {
1768
+ const friendMark = entry.friend !== undefined ? ` (friend=${entry.friend.origin})` : '';
1769
+ lines.push(` ${entry.path} (agent)${friendMark}`);
1770
+ }
1771
+ lines.push(
1772
+ 'Activity changes (state / presence / role / run completion) will produce a short notice; ' +
1773
+ 'use action "inspect" to view the activity snapshot.',
1774
+ );
1775
+ }
1776
+ if (rejected.length > 0) {
1777
+ lines.push(`rejected ${rejected.length}:`);
1778
+ for (const item of rejected) lines.push(` ${item.reason}: ${item.input}`);
1779
+ }
1780
+ return lines.join('\n');
1781
+ }
1782
+
1783
+ if (source === 'script') {
1784
+ const inputs = collectNameInputs(args);
1785
+ if (inputs.length === 0) return '错误:source:script add 需要 name 或 names。';
1786
+ const added: SubscriptionEntry[] = [];
1787
+ const rejected: Array<{ input: string; reason: string }> = [];
1788
+ const seen = new Set<string>();
1789
+ for (const input of inputs) {
1790
+ const name = input.trim();
1791
+ if (seen.has(name)) continue;
1792
+ seen.add(name);
1793
+ const key = scriptSubscriptionKey(name);
1794
+ const outcome = prepareScriptEntry(name, config, state.subscriptions[key]);
1795
+ if (outcome.entry === undefined) {
1796
+ rejected.push({ input: outcome.input, reason: outcome.reason ?? 'invalid' });
1797
+ continue;
1798
+ }
1799
+ state.subscriptions[key] = outcome.entry;
1800
+ added.push(outcome.entry);
1801
+ }
1802
+ if (added.length > 0) {
1803
+ try {
1804
+ await deps.store.save(state);
1805
+ } catch {
1806
+ return '错误:保存订阅状态失败。';
1807
+ }
1808
+ }
1809
+ const lines: string[] = [];
1810
+ if (added.length > 0) {
1811
+ lines.push(`added ${added.length}:`);
1812
+ for (const entry of added) lines.push(` ${entry.path} (script)`);
1813
+ lines.push(
1814
+ 'Script output changes will produce a short notice (empty output = no notice); ' +
1815
+ 'use action "inspect" to view the latest full output.',
1816
+ );
1817
+ }
1818
+ if (rejected.length > 0) {
1819
+ lines.push(`rejected ${rejected.length}:`);
1820
+ for (const item of rejected) lines.push(` ${item.reason}: ${item.input}`);
1821
+ lines.push(
1822
+ 'not_in_allowlist: only scripts declared in plugins.doc-subscription.config.scripts ' +
1823
+ 'can be subscribed; ask the user to declare the script in config.',
1824
+ );
1825
+ }
1826
+ return lines.join('\n');
1827
+ }
1828
+
1829
+ if (source === 'health') {
1830
+ const inputs = collectNodeInputs(args);
1831
+ if (inputs.length === 0) return '错误:source:health add 需要 node 或 nodes。';
1832
+ const added: SubscriptionEntry[] = [];
1833
+ const rejected: Array<{ input: string; reason: string }> = [];
1834
+ const seen = new Set<string>();
1835
+ for (const input of inputs) {
1836
+ const target = input.trim();
1837
+ if (seen.has(target)) continue;
1838
+ seen.add(target);
1839
+ const key = healthSubscriptionKey(target);
1840
+ // live deps(hot-gate 残留修复):stateDir 热改后基线快照读新目录,与 inspect 同口径。
1841
+ const outcome = await prepareHealthEntry(target, effectiveDeps, state.subscriptions[key]);
1842
+ if (outcome.entry === undefined) {
1843
+ rejected.push({ input: outcome.input, reason: outcome.reason ?? 'invalid' });
1844
+ continue;
1845
+ }
1846
+ state.subscriptions[key] = outcome.entry;
1847
+ added.push(outcome.entry);
1848
+ }
1849
+ if (added.length > 0) {
1850
+ try {
1851
+ await deps.store.save(state);
1852
+ } catch {
1853
+ return '错误:保存订阅状态失败。';
1854
+ }
1855
+ }
1856
+ const lines: string[] = [];
1857
+ if (added.length > 0) {
1858
+ lines.push(`added ${added.length}:`);
1859
+ for (const entry of added) lines.push(` ${entry.path} (health)`);
1860
+ lines.push(
1861
+ 'Health changes (reachability / version / restart) will produce a short notice; ' +
1862
+ 'use action "inspect" to view the snapshot.',
1863
+ );
1864
+ }
1865
+ if (rejected.length > 0) {
1866
+ lines.push(`rejected ${rejected.length}:`);
1867
+ for (const item of rejected) lines.push(` ${item.reason}: ${item.input}`);
1868
+ }
1869
+ return lines.join('\n');
1870
+ }
1871
+
1872
+ // add(file)
1873
+ const inputs = collectAddInputs(args);
1874
+ if (inputs.length === 0) return '错误:add 需要 path 或 paths。';
1875
+
1876
+ const added: SubscriptionEntry[] = [];
1877
+ const rejected: Array<{ input: string; reason: string }> = [];
1878
+ const seen = new Set<string>();
1879
+
1880
+ for (const input of inputs) {
1881
+ const existingCanonical = canonicalPath(resolveInput(config, input.trim()));
1882
+ if (seen.has(existingCanonical)) continue;
1883
+ seen.add(existingCanonical);
1884
+
1885
+ // live deps(hot-gate 残留修复):cwd 热改后条目解析与上方 dedup 键同一份活配置,
1886
+ // 不再「dedup 用 live、落盘用快照」分裂出两条不同 canonical 的重复条目。
1887
+ const outcome = await prepareEntry(
1888
+ input,
1889
+ effectiveDeps,
1890
+ state.subscriptions[existingCanonical] ?? undefined,
1891
+ );
1892
+ if (outcome.entry === undefined) {
1893
+ rejected.push({ input: outcome.input, reason: outcome.reason ?? 'invalid' });
1894
+ continue;
1895
+ }
1896
+ // manual add 恒置 'manual'(升级梯顶端:永不自过期);reads 引用计数保留。
1897
+ outcome.entry.origin = 'manual';
1898
+ state.subscriptions[outcome.entry.path] = outcome.entry;
1899
+ added.push(outcome.entry);
1900
+ }
1901
+
1902
+ if (added.length > 0) {
1903
+ try {
1904
+ await deps.store.save(state);
1905
+ } catch {
1906
+ return '错误:保存订阅状态失败。';
1907
+ }
1908
+ }
1909
+
1910
+ const lines: string[] = [];
1911
+ if (added.length > 0) {
1912
+ lines.push(`added ${added.length}:`);
1913
+ for (const entry of added) lines.push(` ${entry.path}`);
1914
+ lines.push('Changes will produce a short notice; use action "inspect" to view them.');
1915
+ }
1916
+ if (rejected.length > 0) {
1917
+ lines.push(`rejected ${rejected.length}:`);
1918
+ for (const item of rejected) lines.push(` ${item.reason}: ${item.input}`);
1919
+ }
1920
+ return lines.join('\n');
1921
+ },
1922
+ };
1923
+ }
1924
+
1925
+ /**
1926
+ * 自动订阅入口(edit/write AfterTool hook 用,蜂群 Phase 1 第二重保险)。
1927
+ * 复用 prepareEntry(边界 / 大小 / 敏感判定与手动 add 同口径);成功后把当前观察记为
1928
+ * **基线**(rev = notified_rev):自己刚做的改动不出卡,只有他人再改(rev 不同)才通知。
1929
+ * seen_rev 保持 ''(模型尚未 inspect)。任何拒绝(deny / 越界 / 不存在 / 过大 / 敏感)静默跳过。
1930
+ * 返回是否写入了状态(无变化不写盘)。
1931
+ */
1932
+ /**
1933
+ * edit/write 来源事实(AfterTool hook 从 HookContext 取,设计 §2.2)。
1934
+ * 缺省(旧 caller / 装配未填)⇒ 不标 last_writer、cwd 回退 config.cwd(现状基线,零回归)。
1935
+ */
1936
+ export interface WriteOrigin {
1937
+ tool: 'edit' | 'write';
1938
+ /** 成员 id(HookContext.agent_id);缺省 ⇒ last_writer.member_id 缺省,抑制回退 session_id 判等 */
1939
+ member_id?: string;
1940
+ /** 成员实际 cwd(HookContext.cwd);缺省回退 config.cwd(现状) */
1941
+ cwd?: string;
1942
+ }
1943
+
1944
+ /** last_writer 实质判等:ts 只作诊断不参与(同 rev/成员/工具/session ⇒ 抑制语义相同) */
1945
+ function sameOrigin(a: ChangeOrigin | undefined, b: ChangeOrigin | undefined): boolean {
1946
+ if (a === undefined || b === undefined) return a === b;
1947
+ return (
1948
+ a.rev === b.rev &&
1949
+ a.member_id === b.member_id &&
1950
+ a.tool === b.tool &&
1951
+ a.session_id === b.session_id
1952
+ );
1953
+ }
1954
+
1955
+ export async function autoSubscribePath(
1956
+ deps: SubscribeToolDeps,
1957
+ sessionId: string,
1958
+ rawPath: string,
1959
+ origin?: WriteOrigin,
1960
+ ): Promise<boolean> {
1961
+ const trimmed = rawPath.trim();
1962
+ if (trimmed === '') return false;
1963
+ // live 配置(hot-gate 残留修复):自动订阅与手动 add 同口径读活配置(cwd / maxFullBytes
1964
+ // 热改即时生效);洞1 修复不变:成员实际 cwd 优先(HookContext.cwd),缺省回退活 config.cwd。
1965
+ const base = liveConfigOf(deps);
1966
+ const config = origin?.cwd !== undefined ? { ...base, cwd: origin.cwd } : base;
1967
+ const effectiveDeps: SubscribeToolDeps = { ...deps, config };
1968
+ const canonical = canonicalPath(resolveInput(config, trimmed));
1969
+ let wrote = false;
1970
+ // 原子读改写(设计 §2.2 修洞 3):load→改→save 整段在 per-session 串行链内,并发批不丢更新。
1971
+ await deps.store.mutate(
1972
+ sessionId,
1973
+ async (state) => {
1974
+ const existing = state.subscriptions[canonical] ?? undefined;
1975
+ const outcome = await prepareEntry(trimmed, effectiveDeps, existing);
1976
+ if (outcome.entry === undefined) return undefined;
1977
+ const entry = outcome.entry;
1978
+ // 升级梯 manual > edit > read:manual 不降级;read 条目被 edit/write 触碰升为 'edit'
1979
+ // (清除后不再自过期);新建置 'edit'。
1980
+ entry.origin = existing?.origin === 'manual' ? 'manual' : 'edit';
1981
+
1982
+ const observation = await observeEntry(entry, effectiveDeps);
1983
+ if (observation !== undefined) {
1984
+ entry.rev = observation.rev;
1985
+ entry.size = observation.size;
1986
+ entry.mtime_ms = observation.mtime_ms;
1987
+ // 基线抑制:该 rev 视为「已通知」,自己刚做的改动不出卡;他人再改时 BeforeLlm 才通知。
1988
+ entry.notified_rev = observation.rev;
1989
+ entry.notified_at = Date.now();
1990
+ // 来源标记(设计 §2.2):基线化同时记 last_writer;origin 缺省(旧 caller)不标。
1991
+ if (origin !== undefined) {
1992
+ entry.last_writer = {
1993
+ session_id: sessionId,
1994
+ ...(origin.member_id !== undefined ? { member_id: origin.member_id } : {}),
1995
+ tool: origin.tool,
1996
+ ts: Date.now(),
1997
+ rev: observation.rev,
1998
+ };
1999
+ }
2000
+ }
2001
+
2002
+ if (
2003
+ existing !== undefined &&
2004
+ existing.rev === entry.rev &&
2005
+ existing.notified_rev === entry.notified_rev &&
2006
+ existing.seen_rev === entry.seen_rev &&
2007
+ existing.size === entry.size &&
2008
+ existing.mtime_ms === entry.mtime_ms &&
2009
+ // origin 升级(read → edit)也算变化;reads 原样携带不改,无需比较。
2010
+ existing.origin === entry.origin &&
2011
+ // last_writer 实质判等(ts 除外):同来源同内容重触不写盘。
2012
+ sameOrigin(existing.last_writer, entry.last_writer)
2013
+ ) {
2014
+ return undefined; // 无变化不写盘
2015
+ }
2016
+ state.subscriptions[entry.path] = entry;
2017
+ wrote = true;
2018
+ return state;
2019
+ // 成员指针(§2.6):edit/write 落盘同步更新(origin.member_id 可得时)。
2020
+ },
2021
+ origin?.member_id,
2022
+ );
2023
+ return wrote;
2024
+ }
2025
+
2026
+ /** 从记录读取有限数字(镜像 basic-tools readNumber:非有限数字 ⇒ undefined ⇒ 走缺省) */
2027
+ function readRequestNumber(record: Record<string, unknown>, key: string): number | undefined {
2028
+ const value = record[key];
2029
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
2030
+ }
2031
+
2032
+ /**
2033
+ * read 自动订阅入口(line-level,蜂群协作增强;AfterTool hook 用)。
2034
+ *
2035
+ * 口径(CONTRACT-swarm-subscribe §0/§2):
2036
+ * - **attempt-based + 自然成功近似**:offset/limit 校验镜像 read 工具,clamp 校验天然滤掉
2037
+ * 失败 read(不存在 / 目录 / 二进制 / 超 8MiB / offset>total / 非法 offset、limit ⇒ 不订阅)。
2038
+ * - **clamp 范围 = 请求范围 ∩ 文件实际行数**,是实际返回范围的超集(token 闸只裁不增)⇒
2039
+ * 只会多通知不会漏通知。诚实标注:clamp 用 AfterTool 时刻的文件行数,read 执行与 hook
2040
+ * 之间文件被改有小竞态,由观察期内容锚重定位兜底。
2041
+ * - 行切分用 basic-tools 导出的 splitLines(与 read 工具行号逐字同源)。
2042
+ * - 已有条目:只追加 ReadRef,**不动 rev/notified_rev/seen_rev 任何游标**(保留待发通知;
2043
+ * ref.text = 当前内容 ⇒ 范围级天然基线抑制)。
2044
+ * - 新条目:prepareEntry 全套边界/敏感校验 + origin='read' + 基线抑制(notified_rev=当前
2045
+ * 观察 rev,autoSubscribePath 同款);seen_rev=''。
2046
+ * - best-effort:任何失败静默跳过;无变化不写盘。
2047
+ * - 相对路径按成员实际 cwd 归一化(HookContext.cwd,P1 修洞1);装配未填时回退 config.cwd(现状)。
2048
+ * 返回是否写入了状态。
2049
+ */
2050
+ export async function readSubscribePath(
2051
+ deps: SubscribeToolDeps,
2052
+ sessionId: string,
2053
+ args: Record<string, unknown>,
2054
+ cwd?: string,
2055
+ memberId?: string,
2056
+ ): Promise<boolean> {
2057
+ const rawPath = typeof args.path === 'string' ? args.path.trim() : '';
2058
+ if (rawPath === '') return false;
2059
+
2060
+ // offset/limit 校验镜像 read(basic-tools readFileSlice):非法 ⇒ 该 read 本身已失败,不订阅。
2061
+ const offset = readRequestNumber(args, 'offset') ?? 1;
2062
+ if (!Number.isInteger(offset) || offset < 1) return false;
2063
+ const limit = readRequestNumber(args, 'limit') ?? DEFAULT_READ_LIMIT;
2064
+ if (!Number.isInteger(limit) || limit < 1) return false;
2065
+
2066
+ // live 配置(hot-gate 残留修复):与 autoSubscribePath / 手动 add 同口径读活配置;
2067
+ // 洞1 修复不变:成员实际 cwd 优先(HookContext.cwd),缺省回退活 config.cwd。
2068
+ const base = liveConfigOf(deps);
2069
+ const config = cwd !== undefined ? { ...base, cwd } : base;
2070
+ const canonical = canonicalPath(resolveInput(config, rawPath));
2071
+ // 边界前置(observeEntry / prepareEntry 同口径):deny/ask 的 read 本身已失败,不订阅;
2072
+ // 也避免热应用收紧边界后仍把已拒路径的字节读进引用。
2073
+ if (evaluatePath(canonical, deps.boundary) !== 'allow') return false;
2074
+
2075
+ let info: Awaited<ReturnType<typeof stat>>;
2076
+ try {
2077
+ info = await stat(canonical);
2078
+ } catch {
2079
+ return false;
2080
+ }
2081
+ if (!info.isFile()) return false;
2082
+ if (info.size > MAX_SUBSCRIBE_BYTES) return false;
2083
+ let buffer: Buffer;
2084
+ try {
2085
+ buffer = await readFile(canonical);
2086
+ } catch {
2087
+ return false;
2088
+ }
2089
+ if (buffer.includes(0)) return false;
2090
+
2091
+ const lines = splitLines(buffer.toString('utf-8'));
2092
+ const total = lines.length;
2093
+ if (offset > total) return false; // 含空文件(total=0)
2094
+ const slice = lines.slice(offset - 1, offset - 1 + limit);
2095
+ const ref: ReadRef = { offset, limit, start: offset, end: offset - 1 + slice.length };
2096
+ const rangeText = slice.join('\n');
2097
+ // 仅当字节数 ≤ maxFullBytes 才存 text;存不下 ⇒ 无 text 的 ref(仍计引用,观察时整文件兜底)。
2098
+ if (Buffer.byteLength(rangeText, 'utf-8') <= config.maxFullBytes) ref.text = rangeText;
2099
+
2100
+ // 原子读改写(设计 §2.2 修洞 3):read 只追加引用 / 新建条目,不记 last_writer(read 非编辑)。
2101
+ let wrote = false;
2102
+ await deps.store.mutate(
2103
+ sessionId,
2104
+ async (state) => {
2105
+ const existing = state.subscriptions[canonical];
2106
+ if (existing !== undefined) {
2107
+ existing.reads.push(ref);
2108
+ wrote = true;
2109
+ return state;
2110
+ }
2111
+
2112
+ const outcome = await prepareEntry(rawPath, { ...deps, config }, undefined);
2113
+ if (outcome.entry === undefined) return undefined;
2114
+ const entry = outcome.entry;
2115
+ entry.origin = 'read';
2116
+ entry.reads = [ref];
2117
+ // 基线抑制:订阅时的观察视为「已通知」,read 本身不出卡;他人再改才通知。
2118
+ // rev 直接用刚读 buffer 的 hash(与 observeEntry 同口径),避免二次整文件读。
2119
+ entry.rev = sha256Hex(buffer);
2120
+ entry.notified_rev = entry.rev;
2121
+ entry.notified_at = Date.now();
2122
+ entry.size = buffer.byteLength;
2123
+ entry.mtime_ms = info.mtimeMs;
2124
+ state.subscriptions[entry.path] = entry;
2125
+ wrote = true;
2126
+ return state;
2127
+ // 成员指针(§2.6):read 订阅落盘同步更新(memberId 可得时;read 不记 last_writer)。
2128
+ },
2129
+ memberId,
2130
+ );
2131
+ return wrote;
2132
+ }