@animalabs/agent-framework 0.26.2 → 0.27.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 (276) hide show
  1. package/README.md +56 -6
  2. package/dist/src/agent.d.ts +263 -22
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +531 -54
  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 +1 -2
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/auto-continue.d.ts +33 -0
  10. package/dist/src/auto-continue.d.ts.map +1 -0
  11. package/dist/src/auto-continue.js +35 -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/framework.d.ts +759 -129
  18. package/dist/src/framework.d.ts.map +1 -1
  19. package/dist/src/framework.js +3482 -928
  20. package/dist/src/framework.js.map +1 -1
  21. package/dist/src/gate/event-gate.d.ts +309 -46
  22. package/dist/src/gate/event-gate.d.ts.map +1 -1
  23. package/dist/src/gate/event-gate.js +2117 -395
  24. package/dist/src/gate/event-gate.js.map +1 -1
  25. package/dist/src/gate/index.d.ts +2 -2
  26. package/dist/src/gate/index.d.ts.map +1 -1
  27. package/dist/src/gate/index.js +1 -1
  28. package/dist/src/gate/index.js.map +1 -1
  29. package/dist/src/gate/recipe-reconcile.d.ts +103 -0
  30. package/dist/src/gate/recipe-reconcile.d.ts.map +1 -0
  31. package/dist/src/gate/recipe-reconcile.js +325 -0
  32. package/dist/src/gate/recipe-reconcile.js.map +1 -0
  33. package/dist/src/gate/types.d.ts +68 -8
  34. package/dist/src/gate/types.d.ts.map +1 -1
  35. package/dist/src/index.d.ts +6 -4
  36. package/dist/src/index.d.ts.map +1 -1
  37. package/dist/src/index.js +5 -2
  38. package/dist/src/index.js.map +1 -1
  39. package/dist/src/mcpl/channel-registry.d.ts +433 -113
  40. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  41. package/dist/src/mcpl/channel-registry.js +1152 -434
  42. package/dist/src/mcpl/channel-registry.js.map +1 -1
  43. package/dist/src/mcpl/conversation-router.d.ts +16 -8
  44. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  45. package/dist/src/mcpl/conversation-router.js +29 -15
  46. package/dist/src/mcpl/conversation-router.js.map +1 -1
  47. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  48. package/dist/src/mcpl/convert-block.js +14 -2
  49. package/dist/src/mcpl/convert-block.js.map +1 -1
  50. package/dist/src/mcpl/hook-orchestrator.d.ts +7 -1
  51. package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
  52. package/dist/src/mcpl/hook-orchestrator.js +32 -7
  53. package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
  54. package/dist/src/mcpl/index.d.ts +5 -1
  55. package/dist/src/mcpl/index.d.ts.map +1 -1
  56. package/dist/src/mcpl/index.js +4 -0
  57. package/dist/src/mcpl/index.js.map +1 -1
  58. package/dist/src/mcpl/inference-router.d.ts +14 -2
  59. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  60. package/dist/src/mcpl/inference-router.js +73 -28
  61. package/dist/src/mcpl/inference-router.js.map +1 -1
  62. package/dist/src/mcpl/prose-grammar.d.ts +4 -0
  63. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  64. package/dist/src/mcpl/prose-grammar.js +6 -0
  65. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  66. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  67. package/dist/src/mcpl/protocol-family.js +3 -0
  68. package/dist/src/mcpl/protocol-family.js.map +1 -1
  69. package/dist/src/mcpl/push-coalescer.d.ts +20 -2
  70. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  71. package/dist/src/mcpl/push-coalescer.js +33 -11
  72. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  73. package/dist/src/mcpl/reference-fetcher.d.ts +63 -42
  74. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  75. package/dist/src/mcpl/reference-fetcher.js +177 -145
  76. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  77. package/dist/src/mcpl/references.d.ts +380 -46
  78. package/dist/src/mcpl/references.d.ts.map +1 -1
  79. package/dist/src/mcpl/references.js +736 -77
  80. package/dist/src/mcpl/references.js.map +1 -1
  81. package/dist/src/mcpl/server-connection.d.ts +82 -3
  82. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  83. package/dist/src/mcpl/server-connection.js +132 -7
  84. package/dist/src/mcpl/server-connection.js.map +1 -1
  85. package/dist/src/mcpl/tool-lifecycle.d.ts +11 -0
  86. package/dist/src/mcpl/tool-lifecycle.d.ts.map +1 -1
  87. package/dist/src/mcpl/tool-lifecycle.js +21 -0
  88. package/dist/src/mcpl/tool-lifecycle.js.map +1 -1
  89. package/dist/src/mcpl/tool-presence.d.ts +259 -0
  90. package/dist/src/mcpl/tool-presence.d.ts.map +1 -0
  91. package/dist/src/mcpl/tool-presence.js +628 -0
  92. package/dist/src/mcpl/tool-presence.js.map +1 -0
  93. package/dist/src/mcpl/tool-result-normalize.d.ts +9 -3
  94. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  95. package/dist/src/mcpl/tool-result-normalize.js +14 -6
  96. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  97. package/dist/src/mcpl/tool-signature.d.ts +39 -0
  98. package/dist/src/mcpl/tool-signature.d.ts.map +1 -0
  99. package/dist/src/mcpl/tool-signature.js +292 -0
  100. package/dist/src/mcpl/tool-signature.js.map +1 -0
  101. package/dist/src/mcpl/toolset-host.d.ts +200 -0
  102. package/dist/src/mcpl/toolset-host.d.ts.map +1 -0
  103. package/dist/src/mcpl/toolset-host.js +621 -0
  104. package/dist/src/mcpl/toolset-host.js.map +1 -0
  105. package/dist/src/mcpl/toolsets-module.d.ts +80 -0
  106. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -0
  107. package/dist/src/mcpl/toolsets-module.js +431 -0
  108. package/dist/src/mcpl/toolsets-module.js.map +1 -0
  109. package/dist/src/mcpl/transport.d.ts +2 -2
  110. package/dist/src/mcpl/transport.d.ts.map +1 -1
  111. package/dist/src/mcpl/transport.js +3 -2
  112. package/dist/src/mcpl/transport.js.map +1 -1
  113. package/dist/src/mcpl/types.d.ts +21 -1
  114. package/dist/src/mcpl/types.d.ts.map +1 -1
  115. package/dist/src/mcpl/types.js.map +1 -1
  116. package/dist/src/mcpl/visible-content.d.ts +7 -9
  117. package/dist/src/mcpl/visible-content.d.ts.map +1 -1
  118. package/dist/src/mcpl/visible-content.js +21 -9
  119. package/dist/src/mcpl/visible-content.js.map +1 -1
  120. package/dist/src/module-registry.d.ts +23 -8
  121. package/dist/src/module-registry.d.ts.map +1 -1
  122. package/dist/src/module-registry.js +68 -15
  123. package/dist/src/module-registry.js.map +1 -1
  124. package/dist/src/modules/discord/index.js +1 -1
  125. package/dist/src/modules/discord/index.js.map +1 -1
  126. package/dist/src/modules/history/index.d.ts +2 -1
  127. package/dist/src/modules/history/index.d.ts.map +1 -1
  128. package/dist/src/modules/history/index.js +51 -17
  129. package/dist/src/modules/history/index.js.map +1 -1
  130. package/dist/src/modules/history/semantic.d.ts +108 -6
  131. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  132. package/dist/src/modules/history/semantic.js +273 -57
  133. package/dist/src/modules/history/semantic.js.map +1 -1
  134. package/dist/src/modules/workspace/direct-write.d.ts +181 -0
  135. package/dist/src/modules/workspace/direct-write.d.ts.map +1 -0
  136. package/dist/src/modules/workspace/direct-write.js +384 -0
  137. package/dist/src/modules/workspace/direct-write.js.map +1 -0
  138. package/dist/src/modules/workspace/edit-text.d.ts +26 -12
  139. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -1
  140. package/dist/src/modules/workspace/edit-text.js +58 -28
  141. package/dist/src/modules/workspace/edit-text.js.map +1 -1
  142. package/dist/src/modules/workspace/effects.d.ts +10 -0
  143. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  144. package/dist/src/modules/workspace/effects.js +1 -1
  145. package/dist/src/modules/workspace/effects.js.map +1 -1
  146. package/dist/src/modules/workspace/index.d.ts +246 -27
  147. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  148. package/dist/src/modules/workspace/index.js +1216 -236
  149. package/dist/src/modules/workspace/index.js.map +1 -1
  150. package/dist/src/modules/workspace/read-page.d.ts +41 -0
  151. package/dist/src/modules/workspace/read-page.d.ts.map +1 -0
  152. package/dist/src/modules/workspace/read-page.js +213 -0
  153. package/dist/src/modules/workspace/read-page.js.map +1 -0
  154. package/dist/src/modules/workspace/result-text.d.ts +67 -0
  155. package/dist/src/modules/workspace/result-text.d.ts.map +1 -0
  156. package/dist/src/modules/workspace/result-text.js +94 -0
  157. package/dist/src/modules/workspace/result-text.js.map +1 -0
  158. package/dist/src/modules/workspace/text.d.ts +29 -12
  159. package/dist/src/modules/workspace/text.d.ts.map +1 -1
  160. package/dist/src/modules/workspace/text.js +35 -33
  161. package/dist/src/modules/workspace/text.js.map +1 -1
  162. package/dist/src/modules/workspace/types.d.ts +41 -17
  163. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  164. package/dist/src/modules/workspace/types.js.map +1 -1
  165. package/dist/src/sent-rows.d.ts +59 -0
  166. package/dist/src/sent-rows.d.ts.map +1 -0
  167. package/dist/src/sent-rows.js +145 -0
  168. package/dist/src/sent-rows.js.map +1 -0
  169. package/dist/src/silent-heartbeat.d.ts +17 -10
  170. package/dist/src/silent-heartbeat.d.ts.map +1 -1
  171. package/dist/src/silent-heartbeat.js.map +1 -1
  172. package/dist/src/stable-hash.d.ts +3 -0
  173. package/dist/src/stable-hash.d.ts.map +1 -0
  174. package/dist/src/stable-hash.js +15 -0
  175. package/dist/src/stable-hash.js.map +1 -0
  176. package/dist/src/stored-injections.d.ts +99 -0
  177. package/dist/src/stored-injections.d.ts.map +1 -0
  178. package/dist/src/stored-injections.js +106 -0
  179. package/dist/src/stored-injections.js.map +1 -0
  180. package/dist/src/text-as-stored.d.ts +4 -3
  181. package/dist/src/text-as-stored.d.ts.map +1 -1
  182. package/dist/src/text-as-stored.js +4 -3
  183. package/dist/src/text-as-stored.js.map +1 -1
  184. package/dist/src/thinking-drops.d.ts +81 -0
  185. package/dist/src/thinking-drops.d.ts.map +1 -0
  186. package/dist/src/thinking-drops.js +103 -0
  187. package/dist/src/thinking-drops.js.map +1 -0
  188. package/dist/src/tool-image-ledger.d.ts +9 -8
  189. package/dist/src/tool-image-ledger.d.ts.map +1 -1
  190. package/dist/src/tool-image-ledger.js +9 -8
  191. package/dist/src/tool-image-ledger.js.map +1 -1
  192. package/dist/src/tool-presentation.d.ts.map +1 -1
  193. package/dist/src/tool-presentation.js +3 -1
  194. package/dist/src/tool-presentation.js.map +1 -1
  195. package/dist/src/tool-result-guard.d.ts +4 -2
  196. package/dist/src/tool-result-guard.d.ts.map +1 -1
  197. package/dist/src/tool-result-guard.js +21 -6
  198. package/dist/src/tool-result-guard.js.map +1 -1
  199. package/dist/src/tool-result-history.d.ts +176 -24
  200. package/dist/src/tool-result-history.d.ts.map +1 -1
  201. package/dist/src/tool-result-history.js +411 -91
  202. package/dist/src/tool-result-history.js.map +1 -1
  203. package/dist/src/tune-out/coordinator.d.ts +17 -9
  204. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  205. package/dist/src/tune-out/coordinator.js +84 -37
  206. package/dist/src/tune-out/coordinator.js.map +1 -1
  207. package/dist/src/types/agent.d.ts +186 -7
  208. package/dist/src/types/agent.d.ts.map +1 -1
  209. package/dist/src/types/events.d.ts +15 -1
  210. package/dist/src/types/events.d.ts.map +1 -1
  211. package/dist/src/types/framework.d.ts +24 -3
  212. package/dist/src/types/framework.d.ts.map +1 -1
  213. package/dist/src/types/module.d.ts +90 -7
  214. package/dist/src/types/module.d.ts.map +1 -1
  215. package/dist/src/types/trace.d.ts +57 -2
  216. package/dist/src/types/trace.d.ts.map +1 -1
  217. package/package.json +4 -3
  218. package/src/agent.ts +593 -60
  219. package/src/api/server.ts +1 -2
  220. package/src/auto-continue.ts +42 -0
  221. package/src/code-execution/isolate/scripts.ts +11 -3
  222. package/src/framework.ts +3601 -967
  223. package/src/gate/event-gate.ts +2315 -389
  224. package/src/gate/index.ts +2 -1
  225. package/src/gate/recipe-reconcile.ts +355 -0
  226. package/src/gate/types.ts +70 -8
  227. package/src/index.ts +7 -4
  228. package/src/mcpl/channel-registry.ts +1220 -467
  229. package/src/mcpl/conversation-router.ts +34 -16
  230. package/src/mcpl/convert-block.ts +14 -1
  231. package/src/mcpl/hook-orchestrator.ts +33 -6
  232. package/src/mcpl/index.ts +6 -1
  233. package/src/mcpl/inference-router.ts +79 -34
  234. package/src/mcpl/prose-grammar.ts +7 -0
  235. package/src/mcpl/protocol-family.ts +2 -0
  236. package/src/mcpl/push-coalescer.ts +51 -13
  237. package/src/mcpl/reference-fetcher.ts +201 -162
  238. package/src/mcpl/references.ts +851 -77
  239. package/src/mcpl/server-connection.ts +145 -7
  240. package/src/mcpl/tool-lifecycle.ts +21 -0
  241. package/src/mcpl/tool-presence.ts +650 -0
  242. package/src/mcpl/tool-result-normalize.ts +18 -6
  243. package/src/mcpl/tool-signature.ts +285 -0
  244. package/src/mcpl/toolset-host.ts +637 -0
  245. package/src/mcpl/toolsets-module.ts +451 -0
  246. package/src/mcpl/transport.ts +3 -2
  247. package/src/mcpl/types.ts +22 -1
  248. package/src/mcpl/visible-content.ts +22 -9
  249. package/src/module-registry.ts +77 -24
  250. package/src/modules/discord/index.ts +1 -1
  251. package/src/modules/history/index.ts +48 -18
  252. package/src/modules/history/semantic.ts +308 -54
  253. package/src/modules/workspace/direct-write.ts +425 -0
  254. package/src/modules/workspace/edit-text.ts +82 -35
  255. package/src/modules/workspace/effects.ts +1 -1
  256. package/src/modules/workspace/index.ts +1274 -241
  257. package/src/modules/workspace/read-page.ts +222 -0
  258. package/src/modules/workspace/result-text.ts +119 -0
  259. package/src/modules/workspace/text.ts +58 -32
  260. package/src/modules/workspace/types.ts +41 -17
  261. package/src/sent-rows.ts +162 -0
  262. package/src/silent-heartbeat.ts +17 -10
  263. package/src/stable-hash.ts +14 -0
  264. package/src/stored-injections.ts +131 -0
  265. package/src/text-as-stored.ts +4 -3
  266. package/src/thinking-drops.ts +141 -0
  267. package/src/tool-image-ledger.ts +9 -8
  268. package/src/tool-presentation.ts +3 -1
  269. package/src/tool-result-guard.ts +19 -6
  270. package/src/tool-result-history.ts +471 -90
  271. package/src/tune-out/coordinator.ts +80 -37
  272. package/src/types/agent.ts +189 -7
  273. package/src/types/events.ts +15 -1
  274. package/src/types/framework.ts +21 -3
  275. package/src/types/module.ts +86 -7
  276. package/src/types/trace.ts +58 -2
@@ -0,0 +1,628 @@
1
+ /**
2
+ * MCPL RFC-014 (tool presence, toolsets and surfaces): one server's tool
3
+ * presence as the host keeps it.
4
+ *
5
+ * The server's tool list stays its whole truth (RFC §2 principle 1); hints say
6
+ * which tools are static (the API tool list, as before) and which are dynamic
7
+ * (announced in the conversation as they come and go, and called through the
8
+ * host's `act`). Per server this keeps:
9
+ *
10
+ * - the tool definitions (tools/list) and the toolset declarations (manifest);
11
+ * - which declared toolsets and instances are open (toolsets/open results,
12
+ * toolsets/list, hint `toolsets` entries), and which undeclared groups the
13
+ * host opened itself (RFC §5.4: the server is never told);
14
+ * - the server's visibility statements per instance, and definition
15
+ * overrides, from hint changes applied in `rev` order, each at most once.
16
+ * One apply path serves every carrier: a call's, an open's or a close's
17
+ * result, a push's `hints`, a standalone `tools/hints`. `tools/list`
18
+ * (`mcpl/rev`) and `toolsets/list` are statements later changes build on;
19
+ * - which definitions the model has been shown, so a tool's first sentence
20
+ * is said once.
21
+ *
22
+ * Every mutation is bracketed by view() snapshots, and diff() turns the
23
+ * difference into what the model reads. Nothing here does I/O: the
24
+ * controller (toolset-host.ts) feeds it what the connection read.
25
+ *
26
+ * Ported from mcpl-cc-bridge's presence.ts, the reference host.
27
+ */
28
+ import { objectSignature, renderToolLines, toolDigest } from './tool-signature.js';
29
+ /** Toolset-less dynamic tools live under this key: always "open", visible per the server. */
30
+ export const NO_TOOLSET = '';
31
+ export const keyOf = (toolset, instance) => `${toolset}\u0000${instance ?? ''}`;
32
+ export const splitKey = (key) => {
33
+ const [toolset, instance] = key.split('\u0000');
34
+ return { toolset: toolset ?? '', ...(instance ? { instance } : {}) };
35
+ };
36
+ export const emptyChange = () => ({ changes: [], suggest: [], notes: [] });
37
+ export const isEmptyChange = (c) => !c.changes.length && !c.suggest.length && !c.notes.length;
38
+ export const joinChanges = (...sets) => ({
39
+ changes: sets.flatMap((s) => s.changes),
40
+ suggest: sets.flatMap((s) => s.suggest),
41
+ notes: sets.flatMap((s) => s.notes),
42
+ });
43
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
44
+ const arr = (v) => (Array.isArray(v) ? v : []);
45
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
46
+ /** The fields a hint definition may change (RFC §6.1); `name` and all of `_meta` are ignored. */
47
+ export function overrideOf(d) {
48
+ return {
49
+ ...(typeof d.description === 'string' ? { description: d.description } : {}),
50
+ ...(isObj(d.inputSchema) ? { inputSchema: d.inputSchema } : {}),
51
+ ...(isObj(d.annotations) ? { annotations: d.annotations } : {}),
52
+ };
53
+ }
54
+ export class ToolPresence {
55
+ server;
56
+ names;
57
+ allowed;
58
+ listedName;
59
+ /** Hints are in effect on the current connection: the host advertised toolHints and the server did too. */
60
+ active = false;
61
+ declared = {};
62
+ surface = null;
63
+ /** The last rev read on this connection (RFC §6.1); 0 at each connect. */
64
+ rev = 0;
65
+ tools = new Map();
66
+ open = new Map();
67
+ groups = new Set();
68
+ visible = new Map();
69
+ /** Definition overrides from hints: per key (an instance's own, or a toolset's), per tool. */
70
+ defs = new Map();
71
+ /** `ended` ids told to the agent: once per id, across reconnects (RFC §5.3). */
72
+ toldEnded = new Set();
73
+ pendingMoves = new Map();
74
+ moved = new Map();
75
+ /** Digests of definitions the model has been shown with their first sentence. */
76
+ shown = new Set();
77
+ constructor(server,
78
+ /** The meta-tools' names, for the hints rendered text gives. */
79
+ names,
80
+ /** The host's tool policy (enabledTools/disabledTools): a tool it refuses is as if unlisted. */
81
+ allowed = () => true,
82
+ /** How a static tool is named in the API tool list, for `look`. */
83
+ listedName = (tool) => tool) {
84
+ this.server = server;
85
+ this.names = names;
86
+ this.allowed = allowed;
87
+ this.listedName = listedName;
88
+ }
89
+ // ── connection lifecycle ──
90
+ /** A new connection: revs start over; hints count only when both sides advertised toolHints. */
91
+ beginConnection(mcpl, hostHints) {
92
+ this.rev = 0;
93
+ // RFC §6.1: hint _meta and tools/hints from a server that did not advertise toolHints are ignored.
94
+ const active = hostHints && !!mcpl && mcpl.toolHints === true;
95
+ if (!active) {
96
+ if (this.active)
97
+ this.deactivate();
98
+ return;
99
+ }
100
+ this.active = true;
101
+ this.setManifest(mcpl);
102
+ }
103
+ /** Toolset declarations and the surface hint, from initialize or a manifest re-fetch. */
104
+ setManifest(mcpl) {
105
+ const prev = this.declared;
106
+ const decl = {};
107
+ if (mcpl && isObj(mcpl.toolsets)) {
108
+ for (const [name, d] of Object.entries(mcpl.toolsets)) {
109
+ if (!isObj(d) || !name)
110
+ continue;
111
+ decl[name] = {
112
+ ...(str(d.title) ? { title: str(d.title) } : {}),
113
+ ...(str(d.summary) ? { summary: str(d.summary) } : {}),
114
+ default: d.default === 'open' ? 'open' : 'closed',
115
+ ...(d.instances === true ? { instances: true } : {}),
116
+ ...(isObj(d.options) ? { options: d.options } : {}),
117
+ };
118
+ }
119
+ }
120
+ this.declared = decl;
121
+ this.surface = mcpl && isObj(mcpl.surface) ? { title: str(mcpl.surface.title), summary: str(mcpl.surface.summary) } : null;
122
+ // RFC §5.1: removing a toolset, or turning its instances on or off, ends
123
+ // its open instances; one that becomes undeclared starts closed under the
124
+ // host's gating.
125
+ for (const [k, r] of [...this.open]) {
126
+ if (!decl[r.toolset] || !!decl[r.toolset].instances !== !!prev[r.toolset]?.instances)
127
+ this.dropKey(k);
128
+ }
129
+ for (const name of Object.keys(prev)) {
130
+ if (decl[name])
131
+ continue;
132
+ this.groups.delete(name);
133
+ for (const k of new Set([...this.visible.keys(), ...this.defs.keys()]))
134
+ if (splitKey(k).toolset === name)
135
+ this.dropKey(k);
136
+ }
137
+ }
138
+ /** RFC §5.1: a server that withdraws toolHints is hint-less from then on: every tool static, nothing dynamic presented. */
139
+ deactivate() {
140
+ this.active = false;
141
+ this.declared = {};
142
+ this.surface = null;
143
+ this.open.clear();
144
+ this.groups.clear();
145
+ this.visible.clear();
146
+ this.defs.clear();
147
+ this.pendingMoves.clear();
148
+ this.moved.clear();
149
+ }
150
+ /** tools/list: every definition, visible or not (RFC §4.1). A tool the host's policy refuses is left out. */
151
+ setTools(list) {
152
+ this.tools = new Map(list
153
+ .filter((t) => isObj(t) && typeof t.name === 'string' && this.allowed(t.name))
154
+ .map((t) => [t.name, t]));
155
+ for (const set of this.visible.values())
156
+ for (const n of [...set])
157
+ if (!this.tools.has(n))
158
+ set.delete(n);
159
+ // The list's `mcpl/visible` is the server's word only where nothing else
160
+ // speaks: toolset-less dynamic tools and undeclared groups. For a declared
161
+ // toolset it's an aggregate ("visible in some open instance"); per-instance
162
+ // state comes from toolsets/list and hint changes (RFC §4.1, §5.3).
163
+ for (const t of this.tools.values()) {
164
+ if (this.presenceOf(t.name) !== 'dynamic')
165
+ continue;
166
+ const ts = this.toolsetOf(t.name);
167
+ if (ts && this.isDeclared(ts))
168
+ continue;
169
+ this.setVisible(keyOf(ts ?? NO_TOOLSET), t.name, t._meta?.['mcpl/visible'] !== false);
170
+ }
171
+ }
172
+ // ── reading ──
173
+ /** Whether the meta-tools speak for this server: hints in effect and something dynamic. */
174
+ get presents() {
175
+ if (!this.active)
176
+ return false;
177
+ if (Object.keys(this.declared).length)
178
+ return true;
179
+ for (const n of this.tools.keys())
180
+ if (this.presenceOf(n) === 'dynamic')
181
+ return true;
182
+ return false;
183
+ }
184
+ get allTools() {
185
+ return [...this.tools.values()];
186
+ }
187
+ tool(name) {
188
+ return this.tools.get(name);
189
+ }
190
+ toolsetOf(name) {
191
+ const m = this.tools.get(name)?._meta;
192
+ return m && typeof m['mcpl/toolset'] === 'string' && m['mcpl/toolset'] ? m['mcpl/toolset'] : undefined;
193
+ }
194
+ /** static unless hinted dynamic; a toolset wins over any "static" (RFC §4.1); a move applies only at a boundary (applyMoves). */
195
+ presenceOf(name) {
196
+ if (!this.active)
197
+ return 'static';
198
+ if (this.toolsetOf(name))
199
+ return 'dynamic';
200
+ const moved = this.moved.get(name);
201
+ if (moved)
202
+ return moved;
203
+ return this.tools.get(name)?._meta?.['mcpl/presence'] === 'dynamic' ? 'dynamic' : 'static';
204
+ }
205
+ isDeclared(toolset) {
206
+ return Object.hasOwn(this.declared, toolset);
207
+ }
208
+ /** Undeclared toolset names the server's tools are tagged with (RFC §5.4). */
209
+ get undeclaredGroups() {
210
+ const out = new Set();
211
+ for (const n of this.tools.keys()) {
212
+ const ts = this.toolsetOf(n);
213
+ if (ts && !this.isDeclared(ts))
214
+ out.add(ts);
215
+ }
216
+ return [...out];
217
+ }
218
+ openRecords(toolset) {
219
+ return [...this.open.values()].filter((r) => toolset === undefined || r.toolset === toolset);
220
+ }
221
+ isOpen(toolset, instance) {
222
+ return this.isDeclared(toolset) ? this.open.has(keyOf(toolset, instance)) : this.groups.has(toolset);
223
+ }
224
+ get openGroups() {
225
+ return [...this.groups];
226
+ }
227
+ /**
228
+ * The definition the model sees, and the host checks arguments against, for
229
+ * `name` in `key`: the instance's own (a hint definition with `instance`),
230
+ * else the toolset's (one without), else the listed one (RFC §6.1).
231
+ */
232
+ defOf(key, name) {
233
+ const listed = this.tools.get(name);
234
+ const { toolset } = splitKey(key);
235
+ const o = this.defs.get(key)?.get(name) ?? (toolset ? this.defs.get(keyOf(toolset))?.get(name) : undefined);
236
+ return o ? { ...listed, ...o } : listed;
237
+ }
238
+ view() {
239
+ const v = new Map();
240
+ for (const [key, r] of this.open)
241
+ v.set(key, { title: r.title, tools: new Map() });
242
+ for (const g of this.groups)
243
+ if (!this.isDeclared(g))
244
+ v.set(keyOf(g), { tools: new Map() });
245
+ for (const name of this.tools.keys()) {
246
+ if (this.presenceOf(name) !== 'dynamic')
247
+ continue;
248
+ const ts = this.toolsetOf(name);
249
+ if (ts && this.isDeclared(ts)) {
250
+ for (const [key, r] of this.open)
251
+ if (r.toolset === ts && this.visible.get(key)?.has(name))
252
+ v.get(key).tools.set(name, this.defOf(key, name));
253
+ }
254
+ else if (ts) {
255
+ // Two controllers (RFC §4.1, §5.4): the host has the group open AND the server says visible.
256
+ const key = keyOf(ts);
257
+ if (this.groups.has(ts) && this.visible.get(key)?.has(name))
258
+ v.get(key).tools.set(name, this.defOf(key, name));
259
+ }
260
+ else {
261
+ const key = keyOf(NO_TOOLSET);
262
+ if (this.visible.get(key)?.has(name)) {
263
+ if (!v.has(key))
264
+ v.set(key, { tools: new Map() });
265
+ v.get(key).tools.set(name, this.defOf(key, name));
266
+ }
267
+ }
268
+ }
269
+ return v;
270
+ }
271
+ diff(before, after) {
272
+ const out = emptyChange();
273
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
274
+ const b = before.get(key);
275
+ const a = after.get(key);
276
+ const isGroupKey = splitKey(key).toolset !== NO_TOOLSET;
277
+ const appeared = [];
278
+ const redefined = [];
279
+ for (const [n, d] of a?.tools ?? []) {
280
+ const was = b?.tools.get(n);
281
+ if (!was)
282
+ appeared.push(d);
283
+ else if (toolDigest(was) !== toolDigest(d))
284
+ redefined.push(d);
285
+ }
286
+ const gone = [...(b?.tools.keys() ?? [])].filter((n) => !a?.tools.has(n));
287
+ const opened = isGroupKey && !b && !!a;
288
+ const closed = isGroupKey && !!b && !a;
289
+ const retitled = !!a && !!b && !!a.title && a.title !== b.title;
290
+ if (!appeared.length && !redefined.length && !gone.length && !opened && !closed && !retitled)
291
+ continue;
292
+ out.changes.push({ key, ...splitKey(key), title: a?.title ?? b?.title, opened, closed, retitled, appeared, gone, redefined, now: [...(a?.tools.values() ?? [])] });
293
+ }
294
+ return out;
295
+ }
296
+ // ── the one apply path ──
297
+ /** Apply a HintChanges (RFC §6.1) from any of its carriers, as it is read (see ApplyOutcome). */
298
+ apply(h) {
299
+ const none = { applied: false, skipped: false, behind: false, suggest: [] };
300
+ if (!isObj(h) || typeof h.rev !== 'number' || !Number.isFinite(h.rev))
301
+ return none;
302
+ if (h.rev <= this.rev)
303
+ return { ...none, behind: true };
304
+ const skipped = h.rev !== this.rev + 1;
305
+ this.rev = h.rev;
306
+ return { ...none, applied: true, skipped, suggest: this.applyBody(h) };
307
+ }
308
+ /**
309
+ * tools/list's `_meta["mcpl/rev"]` (RFC §4.1): the last rev the server had
310
+ * sent when it wrote the list, which takes none itself. Read in order it
311
+ * equals the last rev read; a higher one means a message was lost (true).
312
+ */
313
+ noteListRev(rev) {
314
+ if (typeof rev !== 'number' || !Number.isFinite(rev))
315
+ return false;
316
+ const lost = rev > this.rev;
317
+ this.rev = Math.max(this.rev, rev);
318
+ return lost;
319
+ }
320
+ applyBody(h) {
321
+ for (const e of arr(h.toolsets)) {
322
+ if (!isObj(e) || !str(e.toolset) || !this.isDeclared(e.toolset))
323
+ continue; // undeclared toolsets are host-local
324
+ const ts = e.toolset;
325
+ const withInstances = !!this.declared[ts].instances;
326
+ const instance = withInstances ? str(e.instance) : undefined;
327
+ if (withInstances && !instance)
328
+ continue; // an instance-less statement about a toolset with instances names nothing
329
+ const key = keyOf(ts, instance);
330
+ // "open" opens, confirms, or (with a new title) retitles (RFC §6.1);
331
+ // it may come from another connection of the same principal (§5.6).
332
+ if (e.state === 'open')
333
+ this.open.set(key, { toolset: ts, ...(instance ? { instance } : {}), title: str(e.title) ?? this.open.get(key)?.title });
334
+ else if (e.state === 'closed')
335
+ this.dropKey(key);
336
+ }
337
+ for (const e of arr(h.tools)) {
338
+ if (!isObj(e) || !str(e.name) || !this.tools.has(e.name))
339
+ continue;
340
+ const name = e.name;
341
+ // A toolset's tool is dynamic whatever a hint says (RFC §4.1).
342
+ if ((e.presence === 'static' || e.presence === 'dynamic') && !this.toolsetOf(name)) {
343
+ // RFC §4.2: a move applies at a boundary the host chooses; until then the tool stays where it is.
344
+ if (e.presence !== this.presenceOf(name))
345
+ this.pendingMoves.set(name, e.presence);
346
+ else
347
+ this.pendingMoves.delete(name);
348
+ }
349
+ if (isObj(e.definition) && this.presenceOf(name) === 'dynamic') {
350
+ const key = this.defKeyFor(name, str(e.instance));
351
+ if (key !== null) {
352
+ if (!this.defs.has(key))
353
+ this.defs.set(key, new Map());
354
+ this.defs.get(key).set(name, overrideOf(e.definition));
355
+ }
356
+ }
357
+ if (typeof e.visible === 'boolean')
358
+ for (const key of this.keysFor(name, str(e.instance)))
359
+ this.setVisible(key, name, e.visible);
360
+ }
361
+ const suggest = [];
362
+ for (const s of arr(h.suggest)) {
363
+ if (!isObj(s) || !str(s.toolset) || (s.action !== 'open' && s.action !== 'close'))
364
+ continue;
365
+ suggest.push({ toolset: s.toolset, ...(str(s.instance) ? { instance: str(s.instance) } : {}), action: s.action, reason: str(s.reason) ?? '' });
366
+ }
367
+ return suggest;
368
+ }
369
+ /**
370
+ * Where a definition lands (RFC §6.1): with `instance`, that instance's own;
371
+ * without, the toolset's (for a toolset without instances, its only one's).
372
+ */
373
+ defKeyFor(name, instance) {
374
+ const ts = this.toolsetOf(name);
375
+ if (!ts)
376
+ return keyOf(NO_TOOLSET);
377
+ return keyOf(ts, this.declared[ts]?.instances ? instance : undefined);
378
+ }
379
+ /** Where a visibility statement lands. For a toolset with instances, `instance` is required; a statement without one is ignored. */
380
+ keysFor(name, instance) {
381
+ const ts = this.toolsetOf(name);
382
+ if (!ts)
383
+ return [keyOf(NO_TOOLSET)];
384
+ const decl = this.declared[ts];
385
+ if (!decl?.instances)
386
+ return [keyOf(ts)];
387
+ return instance ? [keyOf(ts, instance)] : [];
388
+ }
389
+ setVisible(key, name, on) {
390
+ let s = this.visible.get(key);
391
+ if (!s)
392
+ this.visible.set(key, (s = new Set()));
393
+ if (on)
394
+ s.add(name);
395
+ else
396
+ s.delete(name);
397
+ }
398
+ dropKey(key) {
399
+ this.open.delete(key);
400
+ this.visible.delete(key);
401
+ this.defs.delete(key);
402
+ }
403
+ /** The result of a toolsets/open: the instance is open whatever its hints say. */
404
+ noteOpened(toolset, instance, title) {
405
+ if (!this.isDeclared(toolset))
406
+ return;
407
+ const withInstances = !!this.declared[toolset].instances;
408
+ if (withInstances && !instance)
409
+ return;
410
+ const key = keyOf(toolset, withInstances ? instance : undefined);
411
+ this.open.set(key, { toolset, ...(withInstances && instance ? { instance } : {}), title: title ?? this.open.get(key)?.title });
412
+ }
413
+ /** toolsets/close succeeded: closed, whatever the hints said. */
414
+ noteClosed(toolset, instance) {
415
+ this.dropKey(keyOf(toolset, this.declared[toolset]?.instances ? instance : undefined));
416
+ }
417
+ /**
418
+ * toolsets/list (RFC §5.3): what the principal has open, with the full hint
419
+ * state of its dynamic tools, the truth for declared toolsets and dynamic
420
+ * tools outside them. Anything the host believed open and the server doesn't
421
+ * report is closed, never re-opened here: opening can start a new game.
422
+ * Returns what was lost, what the server says ended while no connection was
423
+ * told, its suggestions, and whether its rev skipped one.
424
+ */
425
+ adopt(result) {
426
+ const had = [...this.open.values()];
427
+ // A full statement: a dynamic tool not stated visible is invisible.
428
+ // Undeclared groups stay as the host has them open or closed.
429
+ for (const k of new Set([...this.open.keys(), ...this.visible.keys(), ...this.defs.keys()])) {
430
+ if (this.isDeclared(splitKey(k).toolset))
431
+ this.dropKey(k);
432
+ else {
433
+ this.visible.delete(k);
434
+ this.defs.delete(k);
435
+ }
436
+ }
437
+ const r = isObj(result) ? result : {};
438
+ for (const o of arr(r.open)) {
439
+ if (!isObj(o) || !str(o.toolset))
440
+ continue;
441
+ this.noteOpened(o.toolset, str(o.instance), str(o.title));
442
+ }
443
+ let suggest = [];
444
+ let skipped = false;
445
+ const h = isObj(r._meta) ? r._meta['mcpl/hints'] : undefined;
446
+ if (isObj(h)) {
447
+ suggest = this.applyBody(h);
448
+ // Its own rev, at its place in order (RFC §6.1).
449
+ if (typeof h.rev === 'number' && Number.isFinite(h.rev)) {
450
+ skipped = h.rev !== this.rev + 1;
451
+ this.rev = Math.max(this.rev, h.rev);
452
+ }
453
+ }
454
+ const ended = [];
455
+ for (const e of arr(r.ended)) {
456
+ if (!isObj(e) || !str(e.toolset))
457
+ continue;
458
+ ended.push({ ...(str(e.id) ? { id: str(e.id) } : {}), toolset: e.toolset, ...(str(e.instance) ? { instance: str(e.instance) } : {}), reason: str(e.reason) ?? '' });
459
+ }
460
+ return { lost: had.filter((o) => !this.open.has(keyOf(o.toolset, o.instance))), ended, suggest, skipped };
461
+ }
462
+ /**
463
+ * What the agent should hear about an adoption: what ended while it was
464
+ * away, each `ended` id once however often the server repeats it (RFC
465
+ * §5.3), and what is closed now.
466
+ */
467
+ adoptionNotes(lost, ended) {
468
+ const notes = [];
469
+ const endedKeys = new Set(ended.map((e) => keyOf(e.toolset, e.instance)));
470
+ for (const e of ended) {
471
+ if (e.id) {
472
+ if (this.toldEnded.has(e.id))
473
+ continue;
474
+ this.toldEnded.add(e.id);
475
+ }
476
+ notes.push(`${this.label(keyOf(e.toolset, e.instance))} ended${e.reason ? `: ${e.reason}` : ''}.`);
477
+ }
478
+ for (const o of lost) {
479
+ if (endedKeys.has(keyOf(o.toolset, o.instance)))
480
+ continue;
481
+ notes.push(`${this.label(keyOf(o.toolset, o.instance))} is closed: ${this.server} no longer has it open. ${this.openHint(o.toolset)} starts a new one.`);
482
+ }
483
+ return notes;
484
+ }
485
+ // ── host-made opens of undeclared groups (RFC §5.4) ──
486
+ openGroup(g) {
487
+ this.groups.add(g);
488
+ }
489
+ closeGroup(g) {
490
+ this.groups.delete(g);
491
+ }
492
+ // ── boundaries ──
493
+ /** Apply pending static↔dynamic moves (RFC §4.2) at a boundary the host chooses. Returns what moved. */
494
+ applyMoves() {
495
+ const out = [];
496
+ for (const [name, to] of this.pendingMoves) {
497
+ if (!this.tools.has(name))
498
+ continue;
499
+ this.moved.set(name, to);
500
+ out.push({ name, to });
501
+ }
502
+ this.pendingMoves.clear();
503
+ return out;
504
+ }
505
+ // ── rendering ──
506
+ /** The marker a key's announcements begin with, `[server/toolset:instance]`, which a reminder looks for. */
507
+ label(key) {
508
+ const { toolset, instance } = splitKey(key);
509
+ return `[${this.server}${toolset ? `/${toolset}` : ''}${instance ? `:${instance}` : ''}]`;
510
+ }
511
+ callHint(key) {
512
+ const { instance } = splitKey(key);
513
+ return `${this.names.act} {server:"${this.server}"${instance ? `, instance:"${instance}"` : ''}, tool, args}`;
514
+ }
515
+ closeHint(key) {
516
+ const { toolset, instance } = splitKey(key);
517
+ if (!toolset)
518
+ return null;
519
+ return `${this.names.close} {server:"${this.server}", toolset:"${toolset}"${instance ? `, instance:"${instance}"` : ''}}`;
520
+ }
521
+ openHint(toolset, instance) {
522
+ return `${this.names.open} {server:"${this.server}", toolset:"${toolset}"${instance ? `, instance:"${instance}"` : ''}}`;
523
+ }
524
+ /** The tool block for one key: its label, how to call, and the visible tools (new or changed ones described). */
525
+ toolBlock(key, tools, opts = {}) {
526
+ const head = opts.headed === false ? '' : `${this.label(key)}${opts.title ? ` ${opts.title}` : ''} `;
527
+ if (!tools.length)
528
+ return [`${head}no tools available right now.`];
529
+ return [`${head}tools now — ${this.callHint(key)}:`, ...renderToolLines(tools, this.shown, { describeAll: opts.describeAll })];
530
+ }
531
+ /** What the model reads for a change set. `bare`: a key whose header the caller already printed. */
532
+ render(cs, opts = {}) {
533
+ const lines = [];
534
+ for (const c of cs.changes) {
535
+ const bare = opts.bare === c.key;
536
+ if (c.closed) {
537
+ lines.push(`${this.label(c.key)} closed.${c.gone.length ? ` Now unavailable: ${c.gone.join(', ')}.` : ''}`);
538
+ continue;
539
+ }
540
+ const title = (c.opened || c.retitled) && !bare ? c.title : undefined;
541
+ const setChanged = c.opened || c.appeared.length > 0 || c.redefined.length > 0 || c.gone.length > 0;
542
+ if (setChanged)
543
+ lines.push(...this.toolBlock(c.key, c.now, { headed: !bare, title }));
544
+ else if (title)
545
+ lines.push(`${this.label(c.key)} ${title}`);
546
+ if (c.gone.length)
547
+ lines.push(`now unavailable: ${c.gone.join(', ')}`);
548
+ if (c.opened && !bare) {
549
+ const close = this.closeHint(c.key);
550
+ if (close)
551
+ lines.push(`${close} closes it.`);
552
+ }
553
+ }
554
+ for (const s of cs.suggest)
555
+ lines.push(this.renderSuggestion(s));
556
+ lines.push(...cs.notes);
557
+ return lines.join('\n');
558
+ }
559
+ /** RFC §6.2: a suggestion is shown, never acted on. */
560
+ renderSuggestion(s) {
561
+ const what = `${s.toolset}${s.instance ? `:${s.instance}` : ''}`;
562
+ const how = s.action === 'open' ? this.openHint(s.toolset, s.instance) : this.closeHint(keyOf(s.toolset, s.instance));
563
+ return `${this.server} suggests ${s.action === 'open' ? 'opening' : 'closing'} ${what}${s.reason ? `: ${s.reason}` : ''} — ${how} if you want to (nothing was done).`;
564
+ }
565
+ /** The keys a reminder restates: every open key of this server's view. */
566
+ openKeys() {
567
+ return [...this.view().keys()];
568
+ }
569
+ /** RFC §8.3 reminder: what is open, its current tools (described), how to call and close it. Null when nothing is open. */
570
+ reminder() {
571
+ const v = this.view();
572
+ if (!v.size)
573
+ return null;
574
+ const lines = [];
575
+ for (const [key, e] of v) {
576
+ lines.push(...this.toolBlock(key, [...e.tools.values()], { describeAll: true, title: e.title }));
577
+ const close = this.closeHint(key);
578
+ if (close)
579
+ lines.push(` ${close} closes it.`);
580
+ }
581
+ return lines.join('\n');
582
+ }
583
+ /** look naming this server: what is open (with tools) and what can be opened. */
584
+ catalog() {
585
+ const lines = [];
586
+ lines.push(this.surface ? `${this.server} — ${[this.surface.title, this.surface.summary].filter(Boolean).join(': ')}` : this.server);
587
+ const v = this.view();
588
+ if (v.size) {
589
+ for (const [key, e] of v) {
590
+ lines.push(...this.toolBlock(key, [...e.tools.values()], { describeAll: true, title: e.title }).map((l) => ` ${l}`));
591
+ const close = this.closeHint(key);
592
+ if (close)
593
+ lines.push(` ${close} closes it.`);
594
+ }
595
+ }
596
+ else {
597
+ lines.push(' nothing open');
598
+ }
599
+ const openable = [];
600
+ for (const [name, d] of Object.entries(this.declared)) {
601
+ if (!d.instances && this.isOpen(name))
602
+ continue;
603
+ openable.push(` ${name}${d.title ? ` — ${d.title}` : ''}${d.summary ? `: ${d.summary}` : ''}` +
604
+ (d.instances ? ' (several can be open at once; name each with instance)' : '') +
605
+ (d.options ? ` · options ${objectSignature(d.options)}` : ''));
606
+ }
607
+ for (const g of this.undeclaredGroups) {
608
+ if (this.groups.has(g))
609
+ continue;
610
+ const names = this.allTools.filter((t) => this.toolsetOf(t.name) === g).map((t) => t.name);
611
+ openable.push(` ${g}: ${names.join(', ')}`);
612
+ }
613
+ if (openable.length)
614
+ lines.push(`can open — ${this.names.open} {server:"${this.server}", toolset, instance?, options?}:`, ...openable);
615
+ return lines.join('\n');
616
+ }
617
+ /** Where a tool can be called from now, for `look` naming it. */
618
+ toolStatus(tool) {
619
+ if (this.presenceOf(tool) === 'static')
620
+ return `static — in your tool list as ${this.listedName(tool)}`;
621
+ const where = [...this.view().entries()].filter(([, e]) => e.tools.has(tool)).map(([k]) => k);
622
+ const ts = this.toolsetOf(tool);
623
+ return where.length
624
+ ? `available now in ${where.map((k) => this.label(k)).join(', ')} — ${this.names.act} {server:"${this.server}", tool:"${tool}"${where.length > 1 ? ', instance' : ''}, args}`
625
+ : `not available right now${ts ? ` (toolset ${ts})` : ''}`;
626
+ }
627
+ }
628
+ //# sourceMappingURL=tool-presence.js.map