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