@animalabs/agent-framework 0.26.2 → 0.28.0

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 (371) hide show
  1. package/README.md +99 -8
  2. package/dist/src/agent.d.ts +291 -23
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +596 -61
  5. package/dist/src/agent.js.map +1 -1
  6. package/dist/src/api/server.d.ts.map +1 -1
  7. package/dist/src/api/server.js +5 -4
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/auto-continue.d.ts +34 -0
  10. package/dist/src/auto-continue.d.ts.map +1 -0
  11. package/dist/src/auto-continue.js +36 -0
  12. package/dist/src/auto-continue.js.map +1 -0
  13. package/dist/src/code-execution/isolate/scripts.d.ts +11 -0
  14. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  15. package/dist/src/code-execution/isolate/scripts.js +5 -1
  16. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  17. package/dist/src/cut-off-round.d.ts +24 -0
  18. package/dist/src/cut-off-round.d.ts.map +1 -0
  19. package/dist/src/cut-off-round.js +87 -0
  20. package/dist/src/cut-off-round.js.map +1 -0
  21. package/dist/src/framework.d.ts +1038 -193
  22. package/dist/src/framework.d.ts.map +1 -1
  23. package/dist/src/framework.js +5967 -1514
  24. package/dist/src/framework.js.map +1 -1
  25. package/dist/src/gate/event-gate.d.ts +405 -46
  26. package/dist/src/gate/event-gate.d.ts.map +1 -1
  27. package/dist/src/gate/event-gate.js +2646 -399
  28. package/dist/src/gate/event-gate.js.map +1 -1
  29. package/dist/src/gate/index.d.ts +3 -2
  30. package/dist/src/gate/index.d.ts.map +1 -1
  31. package/dist/src/gate/index.js +2 -1
  32. package/dist/src/gate/index.js.map +1 -1
  33. package/dist/src/gate/recipe-reconcile.d.ts +103 -0
  34. package/dist/src/gate/recipe-reconcile.d.ts.map +1 -0
  35. package/dist/src/gate/recipe-reconcile.js +325 -0
  36. package/dist/src/gate/recipe-reconcile.js.map +1 -0
  37. package/dist/src/gate/reply-judge.d.ts +116 -0
  38. package/dist/src/gate/reply-judge.d.ts.map +1 -0
  39. package/dist/src/gate/reply-judge.js +467 -0
  40. package/dist/src/gate/reply-judge.js.map +1 -0
  41. package/dist/src/gate/types.d.ts +229 -8
  42. package/dist/src/gate/types.d.ts.map +1 -1
  43. package/dist/src/heartbeat/heartbeat.d.ts +184 -0
  44. package/dist/src/heartbeat/heartbeat.d.ts.map +1 -0
  45. package/dist/src/heartbeat/heartbeat.js +752 -0
  46. package/dist/src/heartbeat/heartbeat.js.map +1 -0
  47. package/dist/src/heartbeat/reminder-time.d.ts +5 -0
  48. package/dist/src/heartbeat/reminder-time.d.ts.map +1 -0
  49. package/dist/src/heartbeat/reminder-time.js +107 -0
  50. package/dist/src/heartbeat/reminder-time.js.map +1 -0
  51. package/dist/src/index.d.ts +10 -4
  52. package/dist/src/index.d.ts.map +1 -1
  53. package/dist/src/index.js +7 -2
  54. package/dist/src/index.js.map +1 -1
  55. package/dist/src/mcpl/capability-mask.d.ts.map +1 -1
  56. package/dist/src/mcpl/capability-mask.js +3 -2
  57. package/dist/src/mcpl/capability-mask.js.map +1 -1
  58. package/dist/src/mcpl/channel-registry.d.ts +433 -113
  59. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  60. package/dist/src/mcpl/channel-registry.js +1154 -435
  61. package/dist/src/mcpl/channel-registry.js.map +1 -1
  62. package/dist/src/mcpl/conversation-router.d.ts +16 -8
  63. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  64. package/dist/src/mcpl/conversation-router.js +29 -15
  65. package/dist/src/mcpl/conversation-router.js.map +1 -1
  66. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  67. package/dist/src/mcpl/convert-block.js +14 -2
  68. package/dist/src/mcpl/convert-block.js.map +1 -1
  69. package/dist/src/mcpl/hook-orchestrator.d.ts +7 -1
  70. package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
  71. package/dist/src/mcpl/hook-orchestrator.js +32 -7
  72. package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
  73. package/dist/src/mcpl/inbound-source.d.ts +26 -10
  74. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  75. package/dist/src/mcpl/inbound-source.js +40 -69
  76. package/dist/src/mcpl/inbound-source.js.map +1 -1
  77. package/dist/src/mcpl/index.d.ts +5 -1
  78. package/dist/src/mcpl/index.d.ts.map +1 -1
  79. package/dist/src/mcpl/index.js +4 -0
  80. package/dist/src/mcpl/index.js.map +1 -1
  81. package/dist/src/mcpl/inference-router.d.ts +14 -2
  82. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  83. package/dist/src/mcpl/inference-router.js +73 -28
  84. package/dist/src/mcpl/inference-router.js.map +1 -1
  85. package/dist/src/mcpl/prose-grammar.d.ts +4 -0
  86. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  87. package/dist/src/mcpl/prose-grammar.js +6 -0
  88. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  89. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  90. package/dist/src/mcpl/protocol-family.js +3 -0
  91. package/dist/src/mcpl/protocol-family.js.map +1 -1
  92. package/dist/src/mcpl/push-coalescer.d.ts +20 -2
  93. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  94. package/dist/src/mcpl/push-coalescer.js +33 -11
  95. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  96. package/dist/src/mcpl/reference-fetcher.d.ts +63 -42
  97. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  98. package/dist/src/mcpl/reference-fetcher.js +177 -145
  99. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  100. package/dist/src/mcpl/references.d.ts +380 -46
  101. package/dist/src/mcpl/references.d.ts.map +1 -1
  102. package/dist/src/mcpl/references.js +736 -77
  103. package/dist/src/mcpl/references.js.map +1 -1
  104. package/dist/src/mcpl/server-connection.d.ts +93 -4
  105. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  106. package/dist/src/mcpl/server-connection.js +176 -11
  107. package/dist/src/mcpl/server-connection.js.map +1 -1
  108. package/dist/src/mcpl/tags.d.ts +9 -2
  109. package/dist/src/mcpl/tags.d.ts.map +1 -1
  110. package/dist/src/mcpl/tags.js +12 -2
  111. package/dist/src/mcpl/tags.js.map +1 -1
  112. package/dist/src/mcpl/tool-lifecycle.d.ts +11 -0
  113. package/dist/src/mcpl/tool-lifecycle.d.ts.map +1 -1
  114. package/dist/src/mcpl/tool-lifecycle.js +21 -0
  115. package/dist/src/mcpl/tool-lifecycle.js.map +1 -1
  116. package/dist/src/mcpl/tool-presence.d.ts +311 -0
  117. package/dist/src/mcpl/tool-presence.d.ts.map +1 -0
  118. package/dist/src/mcpl/tool-presence.js +697 -0
  119. package/dist/src/mcpl/tool-presence.js.map +1 -0
  120. package/dist/src/mcpl/tool-result-normalize.d.ts +9 -3
  121. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  122. package/dist/src/mcpl/tool-result-normalize.js +14 -6
  123. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  124. package/dist/src/mcpl/tool-signature.d.ts +46 -0
  125. package/dist/src/mcpl/tool-signature.d.ts.map +1 -0
  126. package/dist/src/mcpl/tool-signature.js +321 -0
  127. package/dist/src/mcpl/tool-signature.js.map +1 -0
  128. package/dist/src/mcpl/toolset-host.d.ts +251 -0
  129. package/dist/src/mcpl/toolset-host.d.ts.map +1 -0
  130. package/dist/src/mcpl/toolset-host.js +720 -0
  131. package/dist/src/mcpl/toolset-host.js.map +1 -0
  132. package/dist/src/mcpl/toolsets-module.d.ts +83 -0
  133. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -0
  134. package/dist/src/mcpl/toolsets-module.js +523 -0
  135. package/dist/src/mcpl/toolsets-module.js.map +1 -0
  136. package/dist/src/mcpl/transport.d.ts +2 -2
  137. package/dist/src/mcpl/transport.d.ts.map +1 -1
  138. package/dist/src/mcpl/transport.js +3 -2
  139. package/dist/src/mcpl/transport.js.map +1 -1
  140. package/dist/src/mcpl/types.d.ts +24 -2
  141. package/dist/src/mcpl/types.d.ts.map +1 -1
  142. package/dist/src/mcpl/types.js.map +1 -1
  143. package/dist/src/mcpl/visible-content.d.ts +7 -9
  144. package/dist/src/mcpl/visible-content.d.ts.map +1 -1
  145. package/dist/src/mcpl/visible-content.js +21 -9
  146. package/dist/src/mcpl/visible-content.js.map +1 -1
  147. package/dist/src/module-registry.d.ts +27 -9
  148. package/dist/src/module-registry.d.ts.map +1 -1
  149. package/dist/src/module-registry.js +77 -17
  150. package/dist/src/module-registry.js.map +1 -1
  151. package/dist/src/modules/discord/index.js +1 -1
  152. package/dist/src/modules/discord/index.js.map +1 -1
  153. package/dist/src/modules/history/index.d.ts +2 -1
  154. package/dist/src/modules/history/index.d.ts.map +1 -1
  155. package/dist/src/modules/history/index.js +73 -28
  156. package/dist/src/modules/history/index.js.map +1 -1
  157. package/dist/src/modules/history/semantic.d.ts +108 -6
  158. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  159. package/dist/src/modules/history/semantic.js +273 -57
  160. package/dist/src/modules/history/semantic.js.map +1 -1
  161. package/dist/src/modules/workspace/answers.d.ts +22 -0
  162. package/dist/src/modules/workspace/answers.d.ts.map +1 -0
  163. package/dist/src/modules/workspace/answers.js +123 -0
  164. package/dist/src/modules/workspace/answers.js.map +1 -0
  165. package/dist/src/modules/workspace/branch-intent.d.ts +5 -3
  166. package/dist/src/modules/workspace/branch-intent.d.ts.map +1 -1
  167. package/dist/src/modules/workspace/branch-intent.js +6 -2
  168. package/dist/src/modules/workspace/branch-intent.js.map +1 -1
  169. package/dist/src/modules/workspace/direct-write.d.ts +184 -0
  170. package/dist/src/modules/workspace/direct-write.d.ts.map +1 -0
  171. package/dist/src/modules/workspace/direct-write.js +417 -0
  172. package/dist/src/modules/workspace/direct-write.js.map +1 -0
  173. package/dist/src/modules/workspace/disk-agreement.d.ts +33 -11
  174. package/dist/src/modules/workspace/disk-agreement.d.ts.map +1 -1
  175. package/dist/src/modules/workspace/disk-agreement.js +48 -17
  176. package/dist/src/modules/workspace/disk-agreement.js.map +1 -1
  177. package/dist/src/modules/workspace/edit-text.d.ts +27 -12
  178. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -1
  179. package/dist/src/modules/workspace/edit-text.js +61 -29
  180. package/dist/src/modules/workspace/edit-text.js.map +1 -1
  181. package/dist/src/modules/workspace/effects.d.ts +10 -0
  182. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  183. package/dist/src/modules/workspace/effects.js +21 -14
  184. package/dist/src/modules/workspace/effects.js.map +1 -1
  185. package/dist/src/modules/workspace/index.d.ts +308 -78
  186. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  187. package/dist/src/modules/workspace/index.js +2103 -720
  188. package/dist/src/modules/workspace/index.js.map +1 -1
  189. package/dist/src/modules/workspace/observe.d.ts +75 -63
  190. package/dist/src/modules/workspace/observe.d.ts.map +1 -1
  191. package/dist/src/modules/workspace/observe.js +366 -180
  192. package/dist/src/modules/workspace/observe.js.map +1 -1
  193. package/dist/src/modules/workspace/read-page.d.ts +41 -0
  194. package/dist/src/modules/workspace/read-page.d.ts.map +1 -0
  195. package/dist/src/modules/workspace/read-page.js +219 -0
  196. package/dist/src/modules/workspace/read-page.js.map +1 -0
  197. package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
  198. package/dist/src/modules/workspace/reconcile.js +26 -16
  199. package/dist/src/modules/workspace/reconcile.js.map +1 -1
  200. package/dist/src/modules/workspace/result-text.d.ts +68 -0
  201. package/dist/src/modules/workspace/result-text.d.ts.map +1 -0
  202. package/dist/src/modules/workspace/result-text.js +94 -0
  203. package/dist/src/modules/workspace/result-text.js.map +1 -0
  204. package/dist/src/modules/workspace/sync.d.ts +9 -0
  205. package/dist/src/modules/workspace/sync.d.ts.map +1 -1
  206. package/dist/src/modules/workspace/sync.js +14 -0
  207. package/dist/src/modules/workspace/sync.js.map +1 -1
  208. package/dist/src/modules/workspace/text.d.ts +29 -12
  209. package/dist/src/modules/workspace/text.d.ts.map +1 -1
  210. package/dist/src/modules/workspace/text.js +35 -33
  211. package/dist/src/modules/workspace/text.js.map +1 -1
  212. package/dist/src/modules/workspace/types.d.ts +137 -60
  213. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  214. package/dist/src/modules/workspace/types.js.map +1 -1
  215. package/dist/src/modules/workspace/watcher.d.ts.map +1 -1
  216. package/dist/src/modules/workspace/watcher.js +8 -3
  217. package/dist/src/modules/workspace/watcher.js.map +1 -1
  218. package/dist/src/prose-drafts.d.ts +4 -3
  219. package/dist/src/prose-drafts.d.ts.map +1 -1
  220. package/dist/src/prose-drafts.js +3 -2
  221. package/dist/src/prose-drafts.js.map +1 -1
  222. package/dist/src/reasoning-loss-notice.d.ts +23 -0
  223. package/dist/src/reasoning-loss-notice.d.ts.map +1 -0
  224. package/dist/src/reasoning-loss-notice.js +50 -0
  225. package/dist/src/reasoning-loss-notice.js.map +1 -0
  226. package/dist/src/reasoning-loss.d.ts +24 -0
  227. package/dist/src/reasoning-loss.d.ts.map +1 -0
  228. package/dist/src/reasoning-loss.js +102 -0
  229. package/dist/src/reasoning-loss.js.map +1 -0
  230. package/dist/src/send-tools.d.ts +3 -2
  231. package/dist/src/send-tools.d.ts.map +1 -1
  232. package/dist/src/send-tools.js +3 -2
  233. package/dist/src/send-tools.js.map +1 -1
  234. package/dist/src/sent-rows.d.ts +59 -0
  235. package/dist/src/sent-rows.d.ts.map +1 -0
  236. package/dist/src/sent-rows.js +145 -0
  237. package/dist/src/sent-rows.js.map +1 -0
  238. package/dist/src/silent-heartbeat.d.ts +17 -10
  239. package/dist/src/silent-heartbeat.d.ts.map +1 -1
  240. package/dist/src/silent-heartbeat.js.map +1 -1
  241. package/dist/src/stable-hash.d.ts +3 -0
  242. package/dist/src/stable-hash.d.ts.map +1 -0
  243. package/dist/src/stable-hash.js +15 -0
  244. package/dist/src/stable-hash.js.map +1 -0
  245. package/dist/src/stored-injections.d.ts +99 -0
  246. package/dist/src/stored-injections.d.ts.map +1 -0
  247. package/dist/src/stored-injections.js +106 -0
  248. package/dist/src/stored-injections.js.map +1 -0
  249. package/dist/src/text-as-stored.d.ts +4 -3
  250. package/dist/src/text-as-stored.d.ts.map +1 -1
  251. package/dist/src/text-as-stored.js +4 -3
  252. package/dist/src/text-as-stored.js.map +1 -1
  253. package/dist/src/thinking-drops.d.ts +74 -0
  254. package/dist/src/thinking-drops.d.ts.map +1 -0
  255. package/dist/src/thinking-drops.js +96 -0
  256. package/dist/src/thinking-drops.js.map +1 -0
  257. package/dist/src/tool-args.d.ts +12 -0
  258. package/dist/src/tool-args.d.ts.map +1 -1
  259. package/dist/src/tool-args.js +35 -1
  260. package/dist/src/tool-args.js.map +1 -1
  261. package/dist/src/tool-image-ledger.d.ts +9 -8
  262. package/dist/src/tool-image-ledger.d.ts.map +1 -1
  263. package/dist/src/tool-image-ledger.js +9 -8
  264. package/dist/src/tool-image-ledger.js.map +1 -1
  265. package/dist/src/tool-presentation.d.ts.map +1 -1
  266. package/dist/src/tool-presentation.js +3 -1
  267. package/dist/src/tool-presentation.js.map +1 -1
  268. package/dist/src/tool-result-guard.d.ts +12 -6
  269. package/dist/src/tool-result-guard.d.ts.map +1 -1
  270. package/dist/src/tool-result-guard.js +44 -17
  271. package/dist/src/tool-result-guard.js.map +1 -1
  272. package/dist/src/tool-result-history.d.ts +176 -24
  273. package/dist/src/tool-result-history.d.ts.map +1 -1
  274. package/dist/src/tool-result-history.js +411 -91
  275. package/dist/src/tool-result-history.js.map +1 -1
  276. package/dist/src/tune-out/coordinator.d.ts +17 -9
  277. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  278. package/dist/src/tune-out/coordinator.js +84 -37
  279. package/dist/src/tune-out/coordinator.js.map +1 -1
  280. package/dist/src/tune-out/tools.d.ts +4 -1
  281. package/dist/src/tune-out/tools.d.ts.map +1 -1
  282. package/dist/src/types/agent.d.ts +217 -7
  283. package/dist/src/types/agent.d.ts.map +1 -1
  284. package/dist/src/types/events.d.ts +33 -9
  285. package/dist/src/types/events.d.ts.map +1 -1
  286. package/dist/src/types/framework.d.ts +39 -3
  287. package/dist/src/types/framework.d.ts.map +1 -1
  288. package/dist/src/types/module.d.ts +95 -9
  289. package/dist/src/types/module.d.ts.map +1 -1
  290. package/dist/src/types/trace.d.ts +91 -3
  291. package/dist/src/types/trace.d.ts.map +1 -1
  292. package/package.json +5 -4
  293. package/src/agent.ts +661 -67
  294. package/src/api/server.ts +5 -4
  295. package/src/auto-continue.ts +43 -0
  296. package/src/code-execution/isolate/scripts.ts +11 -3
  297. package/src/cut-off-round.ts +98 -0
  298. package/src/framework.ts +6168 -1540
  299. package/src/gate/event-gate.ts +2895 -405
  300. package/src/gate/index.ts +10 -1
  301. package/src/gate/recipe-reconcile.ts +355 -0
  302. package/src/gate/reply-judge.ts +512 -0
  303. package/src/gate/types.ts +234 -9
  304. package/src/heartbeat/heartbeat.ts +804 -0
  305. package/src/heartbeat/reminder-time.ts +107 -0
  306. package/src/index.ts +11 -4
  307. package/src/mcpl/capability-mask.ts +3 -2
  308. package/src/mcpl/channel-registry.ts +1222 -468
  309. package/src/mcpl/conversation-router.ts +34 -16
  310. package/src/mcpl/convert-block.ts +14 -1
  311. package/src/mcpl/hook-orchestrator.ts +33 -6
  312. package/src/mcpl/inbound-source.ts +42 -69
  313. package/src/mcpl/index.ts +6 -1
  314. package/src/mcpl/inference-router.ts +79 -34
  315. package/src/mcpl/prose-grammar.ts +7 -0
  316. package/src/mcpl/protocol-family.ts +2 -0
  317. package/src/mcpl/push-coalescer.ts +51 -13
  318. package/src/mcpl/reference-fetcher.ts +201 -162
  319. package/src/mcpl/references.ts +851 -77
  320. package/src/mcpl/server-connection.ts +189 -11
  321. package/src/mcpl/tags.ts +13 -2
  322. package/src/mcpl/tool-lifecycle.ts +21 -0
  323. package/src/mcpl/tool-presence.ts +716 -0
  324. package/src/mcpl/tool-result-normalize.ts +18 -6
  325. package/src/mcpl/tool-signature.ts +316 -0
  326. package/src/mcpl/toolset-host.ts +727 -0
  327. package/src/mcpl/toolsets-module.ts +545 -0
  328. package/src/mcpl/transport.ts +3 -2
  329. package/src/mcpl/types.ts +25 -2
  330. package/src/mcpl/visible-content.ts +22 -9
  331. package/src/module-registry.ts +85 -26
  332. package/src/modules/discord/index.ts +1 -1
  333. package/src/modules/history/index.ts +70 -30
  334. package/src/modules/history/semantic.ts +308 -54
  335. package/src/modules/workspace/answers.ts +133 -0
  336. package/src/modules/workspace/branch-intent.ts +10 -5
  337. package/src/modules/workspace/direct-write.ts +460 -0
  338. package/src/modules/workspace/disk-agreement.ts +52 -21
  339. package/src/modules/workspace/edit-text.ts +84 -35
  340. package/src/modules/workspace/effects.ts +22 -13
  341. package/src/modules/workspace/index.ts +2142 -723
  342. package/src/modules/workspace/observe.ts +381 -177
  343. package/src/modules/workspace/read-page.ts +228 -0
  344. package/src/modules/workspace/reconcile.ts +27 -15
  345. package/src/modules/workspace/result-text.ts +121 -0
  346. package/src/modules/workspace/sync.ts +16 -0
  347. package/src/modules/workspace/text.ts +58 -32
  348. package/src/modules/workspace/types.ts +137 -60
  349. package/src/modules/workspace/watcher.ts +8 -3
  350. package/src/prose-drafts.ts +4 -3
  351. package/src/reasoning-loss-notice.ts +62 -0
  352. package/src/reasoning-loss.ts +120 -0
  353. package/src/send-tools.ts +3 -2
  354. package/src/sent-rows.ts +162 -0
  355. package/src/silent-heartbeat.ts +17 -10
  356. package/src/stable-hash.ts +14 -0
  357. package/src/stored-injections.ts +131 -0
  358. package/src/text-as-stored.ts +4 -3
  359. package/src/thinking-drops.ts +135 -0
  360. package/src/tool-args.ts +34 -1
  361. package/src/tool-image-ledger.ts +9 -8
  362. package/src/tool-presentation.ts +3 -1
  363. package/src/tool-result-guard.ts +45 -17
  364. package/src/tool-result-history.ts +471 -90
  365. package/src/tune-out/coordinator.ts +80 -37
  366. package/src/tune-out/tools.ts +4 -1
  367. package/src/types/agent.ts +220 -7
  368. package/src/types/events.ts +33 -9
  369. package/src/types/framework.ts +36 -3
  370. package/src/types/module.ts +91 -9
  371. package/src/types/trace.ts +94 -3
@@ -0,0 +1,727 @@
1
+ /**
2
+ * MCPL RFC-014, host side: per server, the controller that feeds the
3
+ * server's tool presence (tool-presence.ts) from what its connection reads,
4
+ * sends toolsets/open, close and list, recovers from a lost rev, and renders
5
+ * what changed; and the hub that holds every server's controller for the
6
+ * meta-tools (toolsets-module.ts) and for reminders.
7
+ *
8
+ * Hint changes apply as their message is read (RFC §6.1); a static↔dynamic
9
+ * move takes effect when a tools/list states it (§4.1), and the model's tool
10
+ * list shows it at its next rebuild; until then the tool is called at either
11
+ * place (§4.2). The connection's read tap hands
12
+ * the controller every result of a hinted request (awaited or not, while no
13
+ * more than 1,000 hinted requests await an answer), each tools/list whole, every push/event and every tools/hints, of the
14
+ * current transport, synchronously and in arrival order, before anything
15
+ * routes the message or anything read after it is handled.
16
+ * What a message's changes did to the model's view is kept by the object
17
+ * that carried them (`readChanges`), so whoever later handles that object
18
+ * (the tool result, the push, the meta-tool) renders it next to the content.
19
+ *
20
+ * Reminders (RFC §8.3): after each compile built to send, the hub reads
21
+ * which open toolsets' markers (`[server/toolset:instance]`) the request
22
+ * carried. A marker an agent has had in view, gone from a later request
23
+ * (compressed, or out of the window), makes a reminder due for that agent,
24
+ * which the toolsets module gathers at its next start as a stored
25
+ * `afterUser` injection.
26
+ */
27
+ import { McplRequestError, type McplServerConnection, type HintRead } from './server-connection.js';
28
+ import type { McplServerConfig } from './types.js';
29
+ import { isToolAllowed } from './tool-policy.js';
30
+ import { redactServerText } from './protocol-family.js';
31
+ import { logDetail, logValueRedacted } from './log-value.js';
32
+ import {
33
+ ToolPresence, emptyChange, isEmptyChange, keyOf,
34
+ type ChangeSet, type MetaToolNames, type Presence,
35
+ } from './tool-presence.js';
36
+ import type { HintedTool } from './tool-signature.js';
37
+
38
+ /** The meta-tools' module, whose tools are `toolsets--open` and so on. */
39
+ export const TOOLSETS_MODULE = 'toolsets';
40
+ export const META_TOOL_NAMES: MetaToolNames = {
41
+ open: `${TOOLSETS_MODULE}--open`,
42
+ act: `${TOOLSETS_MODULE}--act`,
43
+ look: `${TOOLSETS_MODULE}--look`,
44
+ close: `${TOOLSETS_MODULE}--close`,
45
+ };
46
+
47
+ /** How long an open or close is waited for. A late result still applies when it's read. */
48
+ export const TOOLSET_REQUEST_TIMEOUT_MS = 60_000;
49
+ /** A toolsets/list after a (re)connect or in a recovery. */
50
+ const LIST_TIMEOUT_MS = 15_000;
51
+ /** A toolsets/list that only refreshes titles for look. */
52
+ const REFRESH_TIMEOUT_MS = 5_000;
53
+ /** A burst of anomalies is one recovery. */
54
+ const RECOVERY_DEBOUNCE_MS = 200;
55
+
56
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
57
+ const metaHints = (res: Record<string, unknown>): unknown => (isObj(res._meta) ? res._meta['mcpl/hints'] : undefined);
58
+
59
+ export interface ToolsetHostDeps {
60
+ /** A standalone notice into the conversation: a tools/hints change, a late
61
+ * result's, a reconnect's adoption, a recovery's. `invite`: it suggests an
62
+ * open. The host applies its usual rules for events. */
63
+ notify(serverId: string, text: string, opts: { invite: boolean }): boolean;
64
+ /** Whether the server's changes may be put into the conversation unasked
65
+ * (its `pushEvents` grant): notices and reminders. */
66
+ canNotify(serverId: string): boolean;
67
+ /** The operator's log. */
68
+ log(line: string): void;
69
+ /** How a static tool is named in the tool list (`prefix--tool`). */
70
+ listedName(serverId: string, tool: string): string;
71
+ /** Where the model's published tool list last put a server's tool:
72
+ * offered in it (static), listed but not offered (dynamic), or undefined
73
+ * where it isn't published. RFC §4.2: until its move applies, a tool
74
+ * keeps working where it is. */
75
+ published?(serverId: string, tool: string): Presence | undefined;
76
+ }
77
+
78
+ /** One server's RFC-014 state and traffic. Lives as long as the server's
79
+ * configuration, across reconnects and the server's restarts (its `ended`
80
+ * ids and what the model was shown carry over), in memory only. */
81
+ export class ToolsetController {
82
+ readonly presence: ToolPresence;
83
+ private connection: McplServerConnection | null = null;
84
+ /** The transport epoch the presence's revs belong to. */
85
+ private epoch = -1;
86
+ /** What applying a message's hints changed, by the object that carried them. */
87
+ private readonly readChanges = new WeakMap<object, ChangeSet>();
88
+ /** Results whose change no one has taken yet, in the order they were read, with their method (tellUnlessClaimed). */
89
+ private readonly unclaimed = new Map<object, string>();
90
+ /** eventIds of pushes read on this transport (bounded): a repeat's hints are ignored (RFC §6.1). */
91
+ private seenEvents = new Set<string>();
92
+ private recoveryTimer: ReturnType<typeof setTimeout> | null = null;
93
+ private recovering = false;
94
+ private recoverAgain = false;
95
+
96
+ constructor(
97
+ readonly serverId: string,
98
+ private config: McplServerConfig,
99
+ private readonly deps: ToolsetHostDeps,
100
+ ) {
101
+ this.presence = new ToolPresence(
102
+ serverId,
103
+ META_TOOL_NAMES,
104
+ (tool) => isToolAllowed(tool, this.config),
105
+ (tool) => deps.listedName(serverId, tool),
106
+ (tool) => deps.published?.(serverId, tool),
107
+ );
108
+ }
109
+
110
+ private log(line: string): void {
111
+ this.deps.log(`${this.serverId}: ${line}`);
112
+ }
113
+
114
+ private field(value: unknown): string {
115
+ return logValueRedacted(value, (text) => redactServerText(text, this.config));
116
+ }
117
+
118
+ private failure(error: unknown): string {
119
+ return logDetail(redactServerText(error instanceof Error ? error.message : String(error), this.config));
120
+ }
121
+
122
+ /** A restart can bring a new configuration under the same id. */
123
+ setConfig(config: McplServerConfig): void {
124
+ this.config = config;
125
+ }
126
+
127
+ /** Tap this connection (a connect or a restart's new one). */
128
+ attach(connection: McplServerConnection): void {
129
+ if (this.connection !== connection) {
130
+ this.connection?.setReadTap(null);
131
+ // A new connection numbers its transports from 0 again.
132
+ this.epoch = -1;
133
+ }
134
+ this.connection = connection;
135
+ connection.setReadTap((read, epoch) => this.onRead(connection, read, epoch));
136
+ }
137
+
138
+ release(): void {
139
+ if (this.connection) this.detach(this.connection);
140
+ }
141
+
142
+ /** The server's connection is gone for good (disconnected, removed). */
143
+ detach(connection: McplServerConnection): void {
144
+ if (this.connection !== connection) return;
145
+ connection.setReadTap(null);
146
+ this.connection = null;
147
+ this.epoch = -1;
148
+ if (this.recoveryTimer) clearTimeout(this.recoveryTimer);
149
+ this.recoveryTimer = null;
150
+ // Nothing of it presents any more; what the agent was told (ended ids,
151
+ // definitions shown) is kept for a next connection.
152
+ this.presence.deactivate();
153
+ }
154
+
155
+ /** Whether the meta-tools speak for this server now. */
156
+ get presents(): boolean {
157
+ return this.presence.presents;
158
+ }
159
+
160
+ /** The live connection, for a request. */
161
+ private live(): McplServerConnection {
162
+ const c = this.connection;
163
+ if (!c || !c.isConnected) throw new McplRequestError(`${this.serverId} is not connected right now; try again later`, 'not-sent');
164
+ this.sync(c.transportEpoch, c);
165
+ return c;
166
+ }
167
+
168
+ /**
169
+ * A new transport: revs start over (RFC §6.1), and its advertisement says
170
+ * whether hints are in effect. Read from the connection, which holds the
171
+ * advertisement before its transport can deliver anything.
172
+ */
173
+ private sync(epoch: number, connection: McplServerConnection): void {
174
+ if (epoch === this.epoch) return;
175
+ this.epoch = epoch;
176
+ this.seenEvents = new Set();
177
+ this.presence.beginConnection(connection.toolsetDeclarations, true);
178
+ }
179
+
180
+ // ── RFC §6.1: apply on arrival ──
181
+
182
+ private onRead(connection: McplServerConnection, read: HintRead, epoch: number): void {
183
+ if (connection !== this.connection) return;
184
+ this.sync(epoch, connection);
185
+ if (read.kind === 'result') {
186
+ this.readResult(read.method, read.params, read.result as Record<string, unknown>, read.awaited, read.straddled === true);
187
+ return;
188
+ }
189
+ if (!this.presence.active || !isObj(read.params)) return;
190
+ const p = read.params;
191
+ if (read.kind === 'hints') {
192
+ const cs = this.applyHints(p, 'tools/hints');
193
+ // Carrier 3: a change with nothing to say, told on its own.
194
+ this.deliver(cs);
195
+ return;
196
+ }
197
+ if (p.hints === undefined) return;
198
+ // RFC §7: a push carrying hints is never coalesced; when its changes
199
+ // would apply is undefined, so they're ignored and the state re-read.
200
+ if (p.coalesce !== undefined && p.coalesce !== null) {
201
+ this.log(`push ${this.field(p.eventId ?? '')} carries hints and coalesce (RFC-014 §7 forbids it): its hints are ignored; recovering`);
202
+ this.scheduleRecovery();
203
+ return;
204
+ }
205
+ // RFC §6.1: never retried, so a seen eventId is a duplicate whose hints applied once.
206
+ const eventId = typeof p.eventId === 'string' || typeof p.eventId === 'number' ? String(p.eventId) : '';
207
+ if (eventId) {
208
+ if (this.seenEvents.has(eventId)) {
209
+ this.log(`push ${this.field(eventId)} was read before: its hints are ignored`);
210
+ return;
211
+ }
212
+ this.seenEvents.add(eventId);
213
+ if (this.seenEvents.size > 1000) this.seenEvents.delete(this.seenEvents.values().next().value!);
214
+ }
215
+ // Applied now, before (and whatever) the host decides about the push.
216
+ const cs = this.applyHints(p.hints, 'push');
217
+ this.readChanges.set(p, cs);
218
+ this.tellUnlessClaimed(p, cs, 'push/event');
219
+ }
220
+
221
+ private readResult(method: string, params: Record<string, unknown>, res: Record<string, unknown>, awaited: boolean, straddled: boolean): void {
222
+ let cs: ChangeSet;
223
+ switch (method) {
224
+ case 'tools/list': {
225
+ if (!Array.isArray(res.tools)) return;
226
+ cs = this.readToolList(res.tools as HintedTool[], res);
227
+ if (straddled && !this.recovering) {
228
+ this.log('tools/list pages carried different revs, so its earlier pages are older than changes read between them: recovering');
229
+ this.scheduleRecovery();
230
+ }
231
+ this.deliver(cs);
232
+ return;
233
+ }
234
+ case 'toolsets/list':
235
+ cs = this.readToolsetList(res);
236
+ break;
237
+ case 'toolsets/open': {
238
+ if (!this.presence.active) return;
239
+ cs = this.applyHints(metaHints(res), 'toolsets/open');
240
+ const before = this.presence.view();
241
+ const toolset = typeof res.toolset === 'string' ? res.toolset : String(params.toolset ?? '');
242
+ const instance = typeof res.instance === 'string' && res.instance ? res.instance : typeof params.instance === 'string' ? params.instance : undefined;
243
+ this.presence.noteOpened(toolset, instance, typeof res.title === 'string' && res.title ? res.title : undefined);
244
+ cs.changes.push(...this.presence.diff(before, this.presence.view()).changes);
245
+ break;
246
+ }
247
+ case 'toolsets/close': {
248
+ if (!this.presence.active) return;
249
+ // RFC §5.2: the hint changes the close caused ride in its result, like an open's.
250
+ cs = this.applyHints(metaHints(res), 'toolsets/close');
251
+ const before = this.presence.view();
252
+ this.presence.noteClosed(String(params.toolset ?? ''), typeof params.instance === 'string' ? params.instance : undefined);
253
+ cs.changes.push(...this.presence.diff(before, this.presence.view()).changes);
254
+ break;
255
+ }
256
+ default:
257
+ if (!this.presence.active) return;
258
+ cs = this.applyHints(metaHints(res), method);
259
+ }
260
+ if (awaited) {
261
+ this.readChanges.set(res, cs);
262
+ this.tellUnlessClaimed(res, cs, method);
263
+ } else {
264
+ // RFC §6.1: a result nobody waits for any more (it timed out) applies
265
+ // all the same, and its change is told on its own.
266
+ this.log(`late ${method} result read: its hint changes applied`);
267
+ this.deliver(cs);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * The one apply path (RFC §6.1) for a HintChanges from any carrier, as its
273
+ * message is read. Revs are consecutive: anything but the last + 1 means a
274
+ * message was lost or misordered, and the host recovers.
275
+ */
276
+ private applyHints(h: unknown, source: string): ChangeSet {
277
+ if (h === undefined || !this.presence.active) return emptyChange();
278
+ const before = this.presence.view();
279
+ const last = this.field(this.presence.rev);
280
+ const r = this.presence.apply(h);
281
+ const rev = this.field((h as { rev?: unknown } | null)?.rev);
282
+ if (r.behind) {
283
+ this.log(`hint change rev ${rev} (${source}) is not after rev ${last}: ignored; recovering from tools/list and toolsets/list`);
284
+ this.scheduleRecovery();
285
+ } else if (r.skipped) {
286
+ this.log(`hint change rev ${rev} (${source}) after rev ${last}: a rev was lost; applied, and recovering from tools/list and toolsets/list`);
287
+ this.scheduleRecovery();
288
+ } else if (!r.applied) {
289
+ this.log(`a malformed hint change (${source}) was ignored`);
290
+ }
291
+ if (r.unlisted) {
292
+ this.log(`hint change rev ${rev} (${source}) names a tool tools/list hasn't listed: recovering from tools/list and toolsets/list`);
293
+ this.scheduleRecovery();
294
+ }
295
+ const cs = this.presence.diff(before, this.presence.view());
296
+ cs.suggest.push(...r.suggest);
297
+ return cs;
298
+ }
299
+
300
+ /** tools/list, as read: definitions and presence as of its `mcpl/rev`, which takes no rev of its own (RFC §4.1). */
301
+ private readToolList(tools: HintedTool[], last: Record<string, unknown>): ChangeSet {
302
+ const before = this.presence.view();
303
+ this.presence.setTools(tools);
304
+ if (this.presence.active && this.presence.noteListRev(isObj(last._meta) ? last._meta['mcpl/rev'] : undefined)) {
305
+ this.log(`tools/list was written after rev ${this.field(isObj(last._meta) ? last._meta['mcpl/rev'] : '')}, past the last rev read: a message was lost; recovering`);
306
+ this.scheduleRecovery();
307
+ }
308
+ return this.presence.diff(before, this.presence.view());
309
+ }
310
+
311
+ /** toolsets/list, as read: a full statement of dynamic-tool state under its own rev (RFC §5.3, §6.1). */
312
+ private readToolsetList(res: Record<string, unknown>): ChangeSet {
313
+ if (!this.presence.active) return emptyChange();
314
+ if (!Array.isArray(res.open)) {
315
+ this.log('a toolsets/list result with no open list was ignored');
316
+ return emptyChange();
317
+ }
318
+ const before = this.presence.view();
319
+ const { lost, ended, suggest, skipped, unlisted } = this.presence.adopt(res);
320
+ if (skipped && !this.recovering) {
321
+ // Per-instance state is restated in full; what else was lost (presence) comes from tools/list.
322
+ this.log('toolsets/list skipped a rev: re-reading tools/list');
323
+ this.scheduleRecovery();
324
+ }
325
+ if (unlisted && !this.recovering) {
326
+ this.log('toolsets/list names a tool tools/list hasn\'t listed: re-reading tools/list');
327
+ this.scheduleRecovery();
328
+ }
329
+ const cs = this.presence.diff(before, this.presence.view());
330
+ cs.suggest.push(...suggest);
331
+ // A lost toolset gets its note, not also a "closed" line.
332
+ cs.changes = cs.changes.filter((c) => !lost.some((o) => keyOf(o.toolset, o.instance) === c.key));
333
+ const told = this.presence.adoptionNotes(lost, ended);
334
+ cs.notes.push(...told.notes);
335
+ if (told.ended.length) cs.ended = [...(cs.ended ?? []), ...told.ended];
336
+ return cs;
337
+ }
338
+
339
+ /** A change with nothing else to ride on, told as a notice, after every result's change still unclaimed. */
340
+ private deliver(cs: ChangeSet): void {
341
+ this.tellUnclaimed();
342
+ this.notice(cs);
343
+ }
344
+
345
+ /**
346
+ * Unclaimed carriers' changes, told as notices in the order they were read,
347
+ * through `upTo` when given. When no notice can be written, a push keeps its
348
+ * change for the framework's push path, which takes it when the push gets
349
+ * there; a result's is dropped, whether or not its caller is still to
350
+ * resume.
351
+ */
352
+ private tellUnclaimed(upTo?: object): void {
353
+ for (const [res, method] of [...this.unclaimed]) {
354
+ this.unclaimed.delete(res);
355
+ const cs = this.readChanges.get(res) ?? emptyChange();
356
+ const sent = this.notice(cs);
357
+ if (sent !== 'refused' || method !== 'push/event') this.readChanges.delete(res);
358
+ if (sent === 'told') this.log(`${method}'s tool change wasn't shown with it: told as a notice`);
359
+ if (res === upTo) return;
360
+ }
361
+ }
362
+
363
+ /** Whether a notice was written, there was nothing left to tell (`empty`), or one couldn't be written (`refused`). */
364
+ private notice(cs: ChangeSet): 'told' | 'empty' | 'refused' {
365
+ if (isEmptyChange(cs)) return 'empty';
366
+ const text = this.presence.render(cs, { mark: false });
367
+ if (!text) return 'empty';
368
+ if (!this.deps.notify(this.serverId, text, { invite: cs.suggest.some((s) => s.action === 'open') })) return 'refused';
369
+ this.presence.markTold(cs.ended);
370
+ this.presence.markShown(cs);
371
+ return 'told';
372
+ }
373
+
374
+ /**
375
+ * A dynamic tool called by its namespaced name, as if it were listed (a
376
+ * model imitating an earlier call, a module): refused, so every call into
377
+ * a toolset goes through act, which knows its instance and gates closed
378
+ * groups (RFC §5.4, §5.5). Null for any other tool, including one the tool
379
+ * list last published or the server's latest tools/list puts as static
380
+ * (shownAs: RFC §4.2, until its move applies).
381
+ */
382
+ dynamicCallRefusal(tool: string, calledAs: string): string | null {
383
+ if (!this.presence.active || !this.presence.tool(tool) || this.presence.shownAs(tool, 'static')) return null;
384
+ return `There's no tool "${calledAs}" in your tool list, so nothing ran: ${tool} is a dynamic tool of ${this.serverId}, ` +
385
+ `called with ${META_TOOL_NAMES.act} {server:"${this.serverId}", tool:"${tool}", args}. ${this.presence.toolStatus(tool)}.`;
386
+ }
387
+
388
+ /**
389
+ * An awaited result's change is told by whoever renders that result, when
390
+ * the result goes to the agent: the model's own call of a tool (its tool
391
+ * result), a meta-tool. One no one renders by the time the awaiting code has
392
+ * run (the next macrotask), such as the result of a call the framework makes
393
+ * itself (a reaction, a send, an accounted side effect), is told as a notice
394
+ * instead, as a standalone tools/hints is (RFC §6.1: every change reaches the
395
+ * agent once), or dropped as tellUnclaimed says when none can be written.
396
+ */
397
+ private tellUnlessClaimed(res: object, cs: ChangeSet, method: string): void {
398
+ if (isEmptyChange(cs)) return;
399
+ this.unclaimed.set(res, method);
400
+ setImmediate(() => {
401
+ if (this.unclaimed.has(res)) this.tellUnclaimed(res);
402
+ });
403
+ }
404
+
405
+
406
+ /**
407
+ * The change a carrier's hints made (a tool result, a push's params), taken
408
+ * by a caller that shows it to an agent with the carrier: it isn't told as a
409
+ * notice, and the caller says when it has reached an agent (told). Call it
410
+ * synchronously as the carrier is read, before the next macrotask, when an
411
+ * unclaimed carrier's change goes out as a notice instead (tellUnclaimed
412
+ * says what happens when none can be written). A change already gone that
413
+ * way is empty here. Unclaimed carriers read before this one
414
+ * are told first, as notices, so no later change is shown before them.
415
+ */
416
+ takeChange(carrier: unknown): ChangeSet {
417
+ if (!isObj(carrier)) return emptyChange();
418
+ if (this.unclaimed.has(carrier)) {
419
+ let before: object | undefined;
420
+ for (const res of this.unclaimed.keys()) {
421
+ if (res === carrier) break;
422
+ before = res;
423
+ }
424
+ if (before) this.tellUnclaimed(before);
425
+ }
426
+ this.unclaimed.delete(carrier);
427
+ return this.readChanges.get(carrier) ?? emptyChange();
428
+ }
429
+
430
+ /** A change its taker showed to an agent: its ended records count as told, and the definitions it describes as shown, unless the taker showed it without its blocks (`blocksShown: false`). */
431
+ told(cs: ChangeSet): void {
432
+ this.presence.markTold(cs.ended);
433
+ if (cs.blocksShown !== false) this.presence.markShown(cs);
434
+ }
435
+
436
+ /** A change its taker couldn't show, told as a notice instead, or dropped when none can be written. */
437
+ tell(cs: ChangeSet): void {
438
+ this.notice(cs);
439
+ }
440
+
441
+ private changeOf(carrier: object): ChangeSet {
442
+ return this.readChanges.get(carrier) ?? emptyChange();
443
+ }
444
+
445
+ // ── recovery (RFC §6.1) ──
446
+
447
+ private scheduleRecovery(): void {
448
+ if (!this.presence.active) return;
449
+ if (this.recovering) {
450
+ this.recoverAgain = true;
451
+ return;
452
+ }
453
+ if (this.recoveryTimer) return;
454
+ this.recoveryTimer = setTimeout(() => {
455
+ this.recoveryTimer = null;
456
+ void this.recover();
457
+ }, RECOVERY_DEBOUNCE_MS);
458
+ this.recoveryTimer.unref?.();
459
+ }
460
+
461
+ /**
462
+ * Recovering: re-read tools/list (presence, declared definitions), then
463
+ * toolsets/list (dynamic-tool state in full), so every tool the statement
464
+ * names is already known, unless tools/list failed: a tool the last list
465
+ * lacks then stays unknown until a later change or list starts a recovery.
466
+ * Each applies where it's read. What
467
+ * changed is told. (stdio and WebSocket deliver in order, so no early rev is
468
+ * held.)
469
+ */
470
+ private async recover(): Promise<void> {
471
+ const connection = this.connection;
472
+ if (!connection || !connection.isConnected) return;
473
+ this.recovering = true;
474
+ try {
475
+ await this.ownToolList(connection);
476
+ // RFC §6.1: toolsets/list after tools/list, so every tool it names is known, unless tools/list failed.
477
+ if (connection !== this.connection) return;
478
+ const lists = await this.ownToolsetList(connection, LIST_TIMEOUT_MS, 'recovery');
479
+ if (connection !== this.connection) return;
480
+ this.deliver(lists);
481
+ } finally {
482
+ this.recovering = false;
483
+ if (this.recoverAgain) {
484
+ this.recoverAgain = false;
485
+ this.scheduleRecovery();
486
+ }
487
+ }
488
+ }
489
+
490
+ /** The tap applies the list and tells its change as it's read. */
491
+ private async ownToolList(connection: McplServerConnection): Promise<void> {
492
+ try {
493
+ await connection.sendToolsList();
494
+ } catch (error) {
495
+ this.log(`tools/list failed: ${this.failure(error)}`);
496
+ }
497
+ }
498
+
499
+ private async ownToolsetList(connection: McplServerConnection, timeoutMs: number, why: string): Promise<ChangeSet> {
500
+ try {
501
+ const r = await connection.sendToolsetsList(timeoutMs);
502
+ return this.takeChange(r);
503
+ } catch (error) {
504
+ this.log(`toolsets/list (${why}) failed: ${this.failure(error)}`);
505
+ return emptyChange();
506
+ }
507
+ }
508
+
509
+ /**
510
+ * After every (re)connect, once its policy has settled (RFC §5.3): tools/list
511
+ * then toolsets/list, the truth. What the server reports open is adopted
512
+ * (a game kept across the reconnect); what the host believed open and it
513
+ * doesn't report is closed, never re-opened here, since opening can start a
514
+ * new game. What ended meanwhile is told, each `ended` id once.
515
+ */
516
+ async connected(connection: McplServerConnection): Promise<void> {
517
+ if (connection !== this.connection || !connection.isConnected) return;
518
+ this.sync(connection.transportEpoch, connection);
519
+ if (!this.presence.active) return;
520
+ const epoch = connection.transportEpoch;
521
+ await this.ownToolList(connection);
522
+ if (connection !== this.connection || connection.transportEpoch !== epoch) return;
523
+ const lists = await this.ownToolsetList(connection, LIST_TIMEOUT_MS, 'after connecting');
524
+ if (connection !== this.connection || connection.transportEpoch !== epoch) return;
525
+ this.deliver(lists);
526
+ }
527
+
528
+ /**
529
+ * Re-read what the server holds open (titles, visibility) without telling
530
+ * it, for look. Returns what the re-read changed, taken from the notice it
531
+ * would otherwise get when `shown` (its result reaches an agent): look then
532
+ * either shows it (told) or hands it back (tell). Otherwise the change is
533
+ * left to its notice, and returned to be shown to the caller alone. Null
534
+ * when nothing was read.
535
+ */
536
+ async refreshOpen(opts: { shown: boolean }): Promise<ChangeSet | null> {
537
+ if (!this.presence.active) return null;
538
+ const connection = this.connection;
539
+ if (!connection || !connection.isConnected) return null;
540
+ try {
541
+ const r = await connection.sendToolsetsList(REFRESH_TIMEOUT_MS);
542
+ if (!isObj(r)) return null;
543
+ return opts.shown ? this.takeChange(r) : this.changeOf(r);
544
+ } catch (error) {
545
+ this.log(`toolsets/list (look) failed: ${this.failure(error)}`);
546
+ return null;
547
+ }
548
+ }
549
+
550
+ // ── the host's acts ──
551
+
552
+ /** toolsets/open (RFC §5.2). The server's refusal rejects. Its change is
553
+ * taken when `shown` (its result reaches an agent), else left to its
554
+ * notice and returned for the caller alone; close's is the same. */
555
+ async open(toolset: string, instance: string | undefined, options: Record<string, unknown> | undefined, opts: { shown: boolean }): Promise<{
556
+ key: string; title?: string; content: unknown[]; change: ChangeSet; adopted: boolean;
557
+ }> {
558
+ const connection = this.live();
559
+ const r = await connection.sendToolsetsOpen({ toolset, ...(instance ? { instance } : {}), ...(options ? { options } : {}) }, TOOLSET_REQUEST_TIMEOUT_MS);
560
+ const res = isObj(r) ? r : {};
561
+ const inst = typeof res.instance === 'string' && res.instance ? res.instance : instance;
562
+ // RFC §5.2: a proposed name is used as given or the open refused.
563
+ if (instance && inst !== instance) this.log(`proposed instance ${this.field(instance)} came back as ${this.field(inst)} (RFC-014 §5.2 forbids renaming): using the server's`);
564
+ const key = keyOf(toolset, this.presence.declared[toolset]?.instances ? inst : undefined);
565
+ const title = typeof res.title === 'string' && res.title ? res.title : this.presence.openRecords().find((o) => keyOf(o.toolset, o.instance) === key)?.title;
566
+ return {
567
+ key,
568
+ ...(title ? { title } : {}),
569
+ content: Array.isArray(res.content) ? res.content : [],
570
+ change: opts.shown ? this.takeChange(res) : this.changeOf(res),
571
+ adopted: res.adopted === true,
572
+ };
573
+ }
574
+
575
+ /** toolsets/close (RFC §5.2). */
576
+ async close(toolset: string, instance: string | undefined, opts: { shown: boolean }): Promise<{ content: unknown[]; change: ChangeSet }> {
577
+ const connection = this.live();
578
+ const r = await connection.sendToolsetsClose({ toolset, ...(instance ? { instance } : {}) }, TOOLSET_REQUEST_TIMEOUT_MS);
579
+ const res = isObj(r) ? r : {};
580
+ return { content: Array.isArray(res.content) ? res.content : [], change: opts.shown ? this.takeChange(res) : this.changeOf(res) };
581
+ }
582
+
583
+ /** Open or close an undeclared group (RFC §5.4): the host's own act; the server isn't told. */
584
+ setGroupOpen(group: string, open: boolean): ChangeSet {
585
+ const before = this.presence.view();
586
+ if (open) this.presence.openGroup(group);
587
+ else this.presence.closeGroup(group);
588
+ return this.presence.diff(before, this.presence.view());
589
+ }
590
+
591
+ /**
592
+ * A manifest re-fetch (RFC §5.1): the `toolsets` domain's declarations, as
593
+ * the server sent them. A toolset removed ends its instances; a server
594
+ * that withdraws toolHints is hint-less from then on. What changed is told.
595
+ */
596
+ manifestChanged(declarations: Record<string, unknown> | null): void {
597
+ const before = this.presence.view();
598
+ const wasActive = this.presence.active;
599
+ if (!declarations || declarations.toolHints !== true) {
600
+ if (!wasActive) return;
601
+ this.presence.deactivate();
602
+ this.log('the server withdrew toolHints: every tool is static from now on');
603
+ const cs = this.presence.diff(before, this.presence.view());
604
+ cs.notes.push(`${this.serverId} no longer presents toolsets: its tools are called directly now, by name, not through ${META_TOOL_NAMES.act}.`);
605
+ this.deliver(cs);
606
+ return;
607
+ }
608
+ if (!wasActive) {
609
+ // Hints that arrive by a manifest change take effect at the next
610
+ // connection's handshake: revs belong to a connection's first message.
611
+ this.log('the server now advertises toolHints: in effect from its next connection');
612
+ return;
613
+ }
614
+ this.presence.setManifest(declarations);
615
+ this.deliver(this.presence.diff(before, this.presence.view()));
616
+ }
617
+
618
+ /** At a rebuild of the model's tool list (RFC §4.2), tell where the tools it moved went: `moves`, those still pending, or every one pending. A move a list has undone since the rebuild listed the server isn't told; the next rebuild publishes the undoing. */
619
+ applyMoves(moves?: Array<{ name: string; to: Presence }>): void {
620
+ const moved = this.presence.applyMoves(moves);
621
+ if (!moved.length) return;
622
+ const cs = emptyChange();
623
+ cs.notes.push(...moved.map(({ name, to }) => to === 'dynamic'
624
+ ? `${name} left your tool list: it's announced when available, and called with ${META_TOOL_NAMES.act} {server:"${this.serverId}", tool:"${name}", args}.`
625
+ : `${name} is in your tool list now, as ${this.deps.listedName(this.serverId, name)}.`));
626
+ this.deliver(cs);
627
+ }
628
+ }
629
+
630
+ /** Every server's controller, for the meta-tools and reminders. */
631
+ export class ToolsetHub {
632
+ private readonly controllers = new Map<string, ToolsetController>();
633
+ /** Per agent: the markers it has had in view (seen), and whether a reminder is due. */
634
+ private readonly seen = new Map<string, Set<string>>();
635
+ private readonly due = new Set<string>();
636
+
637
+ constructor(private readonly deps: ToolsetHostDeps) {}
638
+
639
+ /** The controller for a server, made at its first connect. */
640
+ controllerFor(config: McplServerConfig): ToolsetController {
641
+ let c = this.controllers.get(config.id);
642
+ if (!c) {
643
+ c = new ToolsetController(config.id, config, this.deps);
644
+ this.controllers.set(config.id, c);
645
+ } else {
646
+ c.setConfig(config);
647
+ }
648
+ return c;
649
+ }
650
+
651
+ get(serverId: string): ToolsetController | undefined {
652
+ return this.controllers.get(serverId);
653
+ }
654
+
655
+ /** A server's configuration went (removed): its controller lets go of the
656
+ * connection it holds, and is forgotten, so a server added later under
657
+ * the same id starts from nothing. */
658
+ forget(serverId: string): void {
659
+ this.controllers.get(serverId)?.release();
660
+ this.controllers.delete(serverId);
661
+ }
662
+
663
+ all(): ToolsetController[] {
664
+ return [...this.controllers.values()];
665
+ }
666
+
667
+ /** The servers the meta-tools speak for now. */
668
+ presenting(): ToolsetController[] {
669
+ return this.all().filter((c) => c.presents);
670
+ }
671
+
672
+ /** Every open key's marker, across servers. */
673
+ private openMarkers(): string[] {
674
+ return this.all().flatMap((c) => (c.presence.active ? c.presence.openKeys().map((k) => c.presence.label(k)) : []));
675
+ }
676
+
677
+ /**
678
+ * A compile built to send for `agentName` (RFC §8.3): which open toolsets'
679
+ * announcements the request carries. One the agent has had in view and the
680
+ * request no longer carries (compressed, or out of the window) makes a
681
+ * reminder due.
682
+ */
683
+ observeCompile(agentName: string, messages: readonly unknown[]): void {
684
+ const open = this.openMarkers();
685
+ if (open.length === 0) {
686
+ this.seen.delete(agentName);
687
+ this.due.delete(agentName);
688
+ return;
689
+ }
690
+ const text = compiledText(messages);
691
+ const seen = this.seen.get(agentName) ?? new Set<string>();
692
+ let missing = false;
693
+ for (const marker of open) {
694
+ if (text.includes(marker)) seen.add(marker);
695
+ else if (seen.has(marker)) missing = true;
696
+ }
697
+ for (const marker of [...seen]) if (!open.includes(marker)) seen.delete(marker);
698
+ this.seen.set(agentName, seen);
699
+ // Due until a request carries every marker the agent has seen again: a
700
+ // gather that doesn't send (a preview) leaves it due for the next start.
701
+ if (missing) this.due.add(agentName);
702
+ else this.due.delete(agentName);
703
+ }
704
+
705
+ /** The reminder due for `agentName`, or null when none is. */
706
+ reminderFor(agentName: string): string | null {
707
+ if (!this.due.has(agentName)) return null;
708
+ const parts = this.presenting().filter((c) => this.deps.canNotify(c.serverId)).map((c) => c.presence.reminder()).filter((r): r is string => !!r);
709
+ if (parts.length === 0) return null;
710
+ return `Open toolsets (a reminder: their earlier announcements have left your context):\n${parts.join('\n')}`;
711
+ }
712
+ }
713
+
714
+ /** The text a compiled request carries, for marker search: text blocks and tool results' text, at any depth. */
715
+ function compiledText(messages: readonly unknown[]): string {
716
+ const out: string[] = [];
717
+ const walk = (v: unknown, depth: number): void => {
718
+ if (depth > 6) return;
719
+ if (typeof v === 'string') { out.push(v); return; }
720
+ if (Array.isArray(v)) { for (const x of v) walk(x, depth + 1); return; }
721
+ if (!isObj(v)) return;
722
+ if (typeof v.text === 'string') out.push(v.text);
723
+ if (v.content !== undefined) walk(v.content, depth + 1);
724
+ };
725
+ for (const m of messages) walk(isObj(m) ? m.content : undefined, 0);
726
+ return out.join('\n');
727
+ }