@hashgraphonline/conversational-agent 0.2.215 → 0.2.217

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 (310) hide show
  1. package/cli/readme.md +181 -0
  2. package/dist/cjs/index.cjs +1 -1
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs/index.d.ts +1 -0
  5. package/dist/cjs/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
  6. package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
  7. package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
  8. package/dist/cjs/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
  9. package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
  10. package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
  11. package/dist/cjs/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
  12. package/dist/cjs/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
  13. package/dist/cjs/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
  14. package/dist/cjs/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
  15. package/dist/cjs/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
  16. package/dist/cjs/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
  17. package/dist/cjs/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
  18. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
  19. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
  20. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
  21. package/dist/cjs/plugins/community/swarm/config.d.ts +6 -0
  22. package/dist/cjs/plugins/community/swarm/constants.d.ts +8 -0
  23. package/dist/cjs/plugins/community/swarm/index.d.ts +2 -0
  24. package/dist/cjs/plugins/community/swarm/model.d.ts +23 -0
  25. package/dist/cjs/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
  26. package/dist/cjs/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
  27. package/dist/cjs/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
  28. package/dist/cjs/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
  29. package/dist/cjs/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
  30. package/dist/cjs/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
  31. package/dist/cjs/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
  32. package/dist/cjs/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
  33. package/dist/cjs/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
  34. package/dist/cjs/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
  35. package/dist/cjs/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
  36. package/dist/cjs/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
  37. package/dist/cjs/plugins/community/swarm/utils.d.ts +22 -0
  38. package/dist/cjs/plugins/index.d.ts +1 -0
  39. package/dist/esm/index.js +33 -31
  40. package/dist/esm/index.js.map +1 -1
  41. package/dist/esm/index10.js +13 -677
  42. package/dist/esm/index10.js.map +1 -1
  43. package/dist/esm/index11.js +601 -234
  44. package/dist/esm/index11.js.map +1 -1
  45. package/dist/esm/index12.js +296 -136
  46. package/dist/esm/index12.js.map +1 -1
  47. package/dist/esm/index13.js +127 -235
  48. package/dist/esm/index13.js.map +1 -1
  49. package/dist/esm/index14.js +247 -84
  50. package/dist/esm/index14.js.map +1 -1
  51. package/dist/esm/index15.js +81 -159
  52. package/dist/esm/index15.js.map +1 -1
  53. package/dist/esm/index16.js +155 -229
  54. package/dist/esm/index16.js.map +1 -1
  55. package/dist/esm/index17.js +238 -140
  56. package/dist/esm/index17.js.map +1 -1
  57. package/dist/esm/index18.js +139 -493
  58. package/dist/esm/index18.js.map +1 -1
  59. package/dist/esm/index19.js +479 -91
  60. package/dist/esm/index19.js.map +1 -1
  61. package/dist/esm/index20.js +88 -147
  62. package/dist/esm/index20.js.map +1 -1
  63. package/dist/esm/index21.js +127 -666
  64. package/dist/esm/index21.js.map +1 -1
  65. package/dist/esm/index22.js +698 -44
  66. package/dist/esm/index22.js.map +1 -1
  67. package/dist/esm/index23.js +45 -304
  68. package/dist/esm/index23.js.map +1 -1
  69. package/dist/esm/index24.js +303 -153
  70. package/dist/esm/index24.js.map +1 -1
  71. package/dist/esm/index25.js +150 -117
  72. package/dist/esm/index25.js.map +1 -1
  73. package/dist/esm/index26.js +154 -18
  74. package/dist/esm/index26.js.map +1 -1
  75. package/dist/esm/index27.js +18 -22
  76. package/dist/esm/index27.js.map +1 -1
  77. package/dist/esm/index28.js +15 -74
  78. package/dist/esm/index28.js.map +1 -1
  79. package/dist/esm/index29.js +70 -295
  80. package/dist/esm/index29.js.map +1 -1
  81. package/dist/esm/index30.js +279 -100
  82. package/dist/esm/index30.js.map +1 -1
  83. package/dist/esm/index31.js +86 -922
  84. package/dist/esm/index31.js.map +1 -1
  85. package/dist/esm/index32.js +904 -189
  86. package/dist/esm/index32.js.map +1 -1
  87. package/dist/esm/index33.js +185 -1169
  88. package/dist/esm/index33.js.map +1 -1
  89. package/dist/esm/index34.js +1218 -112
  90. package/dist/esm/index34.js.map +1 -1
  91. package/dist/esm/index35.js +111 -99
  92. package/dist/esm/index35.js.map +1 -1
  93. package/dist/esm/index36.js +113 -8
  94. package/dist/esm/index36.js.map +1 -1
  95. package/dist/esm/index37.js +8 -45
  96. package/dist/esm/index37.js.map +1 -1
  97. package/dist/esm/index38.js +41 -102
  98. package/dist/esm/index38.js.map +1 -1
  99. package/dist/esm/index39.js +96 -55
  100. package/dist/esm/index39.js.map +1 -1
  101. package/dist/esm/index4.js +1 -1
  102. package/dist/esm/index40.js +58 -71
  103. package/dist/esm/index40.js.map +1 -1
  104. package/dist/esm/index41.js +79 -21
  105. package/dist/esm/index41.js.map +1 -1
  106. package/dist/esm/index42.js +21 -5
  107. package/dist/esm/index42.js.map +1 -1
  108. package/dist/esm/index43.js +4 -11
  109. package/dist/esm/index43.js.map +1 -1
  110. package/dist/esm/index44.js +12 -322
  111. package/dist/esm/index44.js.map +1 -1
  112. package/dist/esm/index45.js +280 -142
  113. package/dist/esm/index45.js.map +1 -1
  114. package/dist/esm/index46.js +181 -24
  115. package/dist/esm/index46.js.map +1 -1
  116. package/dist/esm/index48.js +67 -85
  117. package/dist/esm/index48.js.map +1 -1
  118. package/dist/esm/index49.js +75 -0
  119. package/dist/esm/index49.js.map +1 -0
  120. package/dist/esm/index5.js +2 -2
  121. package/dist/esm/index50.js +57 -0
  122. package/dist/esm/index50.js.map +1 -0
  123. package/dist/esm/index51.js +103 -0
  124. package/dist/esm/index51.js.map +1 -0
  125. package/dist/esm/index52.js +79 -0
  126. package/dist/esm/index52.js.map +1 -0
  127. package/dist/esm/index53.js +75 -0
  128. package/dist/esm/index53.js.map +1 -0
  129. package/dist/esm/index54.js +124 -0
  130. package/dist/esm/index54.js.map +1 -0
  131. package/dist/esm/index55.js +58 -0
  132. package/dist/esm/index55.js.map +1 -0
  133. package/dist/esm/index56.js +83 -0
  134. package/dist/esm/index56.js.map +1 -0
  135. package/dist/esm/index57.js +100 -0
  136. package/dist/esm/index57.js.map +1 -0
  137. package/dist/esm/index58.js +118 -0
  138. package/dist/esm/index58.js.map +1 -0
  139. package/dist/esm/index59.js +108 -0
  140. package/dist/esm/index59.js.map +1 -0
  141. package/dist/esm/index6.js +132 -833
  142. package/dist/esm/index6.js.map +1 -1
  143. package/dist/esm/index60.js +30 -0
  144. package/dist/esm/index60.js.map +1 -0
  145. package/dist/esm/index61.js +98 -0
  146. package/dist/esm/index61.js.map +1 -0
  147. package/dist/esm/index62.js +131 -0
  148. package/dist/esm/index62.js.map +1 -0
  149. package/dist/esm/index63.js +19 -0
  150. package/dist/esm/index63.js.map +1 -0
  151. package/dist/esm/index7.js +826 -75
  152. package/dist/esm/index7.js.map +1 -1
  153. package/dist/esm/index8.js +91 -13
  154. package/dist/esm/index8.js.map +1 -1
  155. package/dist/esm/index9.js +13 -17
  156. package/dist/esm/index9.js.map +1 -1
  157. package/dist/types/index.d.ts +1 -0
  158. package/dist/types/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
  159. package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
  160. package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
  161. package/dist/types/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
  162. package/dist/types/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
  163. package/dist/types/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
  164. package/dist/types/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
  165. package/dist/types/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
  166. package/dist/types/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
  167. package/dist/types/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
  168. package/dist/types/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
  169. package/dist/types/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
  170. package/dist/types/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
  171. package/dist/types/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
  172. package/dist/types/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
  173. package/dist/types/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
  174. package/dist/types/plugins/community/swarm/config.d.ts +6 -0
  175. package/dist/types/plugins/community/swarm/constants.d.ts +8 -0
  176. package/dist/types/plugins/community/swarm/index.d.ts +2 -0
  177. package/dist/types/plugins/community/swarm/model.d.ts +23 -0
  178. package/dist/types/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
  179. package/dist/types/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
  180. package/dist/types/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
  181. package/dist/types/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
  182. package/dist/types/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
  183. package/dist/types/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
  184. package/dist/types/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
  185. package/dist/types/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
  186. package/dist/types/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
  187. package/dist/types/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
  188. package/dist/types/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
  189. package/dist/types/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
  190. package/dist/types/plugins/community/swarm/utils.d.ts +22 -0
  191. package/dist/types/plugins/index.d.ts +1 -0
  192. package/package.json +37 -27
  193. package/src/index.ts +1 -0
  194. package/src/plugins/community/swarm/README.md +279 -0
  195. package/src/plugins/community/swarm/SwarmPlugin.ts +178 -0
  196. package/src/plugins/community/swarm/__tests__/SwarmPlugin.mocks.ts +105 -0
  197. package/src/plugins/community/swarm/__tests__/SwarmPlugin.test.ts +93 -0
  198. package/src/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.ts +152 -0
  199. package/src/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.ts +93 -0
  200. package/src/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.ts +163 -0
  201. package/src/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.ts +132 -0
  202. package/src/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.ts +83 -0
  203. package/src/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.ts +219 -0
  204. package/src/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.ts +169 -0
  205. package/src/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.ts +133 -0
  206. package/src/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.ts +67 -0
  207. package/src/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.ts +148 -0
  208. package/src/plugins/community/swarm/__tests__/tools/UploadDataTool.test.ts +125 -0
  209. package/src/plugins/community/swarm/__tests__/tools/UploadFileTool.test.ts +194 -0
  210. package/src/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.ts +118 -0
  211. package/src/plugins/community/swarm/config.ts +6 -0
  212. package/src/plugins/community/swarm/constants.ts +12 -0
  213. package/src/plugins/community/swarm/index.ts +2 -0
  214. package/src/plugins/community/swarm/model.ts +23 -0
  215. package/src/plugins/community/swarm/tools/CreatePostageStampTool.ts +137 -0
  216. package/src/plugins/community/swarm/tools/DownloadDataTool.ts +79 -0
  217. package/src/plugins/community/swarm/tools/DownloadFilesTool.ts +155 -0
  218. package/src/plugins/community/swarm/tools/ExtendPostageStampTool.ts +112 -0
  219. package/src/plugins/community/swarm/tools/GetPostageStampTool.ts +92 -0
  220. package/src/plugins/community/swarm/tools/ListPostageStampsTool.ts +124 -0
  221. package/src/plugins/community/swarm/tools/QueryUploadProgressTool.ts +109 -0
  222. package/src/plugins/community/swarm/tools/ReadFeedTool.ts +110 -0
  223. package/src/plugins/community/swarm/tools/UpdateFeedTool.ts +149 -0
  224. package/src/plugins/community/swarm/tools/UploadDataTool.ts +109 -0
  225. package/src/plugins/community/swarm/tools/UploadFileTool.ts +163 -0
  226. package/src/plugins/community/swarm/tools/UploadFolderTool.ts +150 -0
  227. package/src/plugins/community/swarm/utils.ts +172 -0
  228. package/src/plugins/index.ts +1 -0
  229. package/cli/dist/CLIApp.d.ts +0 -11
  230. package/cli/dist/CLIApp.d.ts.map +0 -1
  231. package/cli/dist/CLIApp.js +0 -128
  232. package/cli/dist/CLIApp.js.map +0 -1
  233. package/cli/dist/LocalConversationalAgent.d.ts +0 -37
  234. package/cli/dist/LocalConversationalAgent.js +0 -58
  235. package/cli/dist/app.d.ts +0 -18
  236. package/cli/dist/app.d.ts.map +0 -1
  237. package/cli/dist/app.js +0 -14
  238. package/cli/dist/app.js.map +0 -1
  239. package/cli/dist/cli.d.ts +0 -3
  240. package/cli/dist/cli.d.ts.map +0 -1
  241. package/cli/dist/cli.js +0 -87
  242. package/cli/dist/cli.js.map +0 -1
  243. package/cli/dist/components/AppContainer.d.ts +0 -16
  244. package/cli/dist/components/AppContainer.js +0 -24
  245. package/cli/dist/components/AppScreens.d.ts +0 -2
  246. package/cli/dist/components/AppScreens.js +0 -259
  247. package/cli/dist/components/ChatScreen.d.ts +0 -21
  248. package/cli/dist/components/ChatScreen.d.ts.map +0 -1
  249. package/cli/dist/components/ChatScreen.js +0 -40
  250. package/cli/dist/components/ChatScreen.js.map +0 -1
  251. package/cli/dist/components/DebugLoadingScreen.d.ts +0 -5
  252. package/cli/dist/components/DebugLoadingScreen.js +0 -31
  253. package/cli/dist/components/LoadingScreen.d.ts +0 -3
  254. package/cli/dist/components/LoadingScreen.d.ts.map +0 -1
  255. package/cli/dist/components/LoadingScreen.js +0 -17
  256. package/cli/dist/components/LoadingScreen.js.map +0 -1
  257. package/cli/dist/components/LoadingScreenDebug.d.ts +0 -5
  258. package/cli/dist/components/LoadingScreenDebug.js +0 -27
  259. package/cli/dist/components/MCPConfigScreen.d.ts +0 -28
  260. package/cli/dist/components/MCPConfigScreen.d.ts.map +0 -1
  261. package/cli/dist/components/MCPConfigScreen.js +0 -186
  262. package/cli/dist/components/MCPConfigScreen.js.map +0 -1
  263. package/cli/dist/components/ScreenRouter.d.ts +0 -13
  264. package/cli/dist/components/ScreenRouter.d.ts.map +0 -1
  265. package/cli/dist/components/ScreenRouter.js +0 -23
  266. package/cli/dist/components/ScreenRouter.js.map +0 -1
  267. package/cli/dist/components/SetupScreen.d.ts +0 -16
  268. package/cli/dist/components/SetupScreen.d.ts.map +0 -1
  269. package/cli/dist/components/SetupScreen.js +0 -67
  270. package/cli/dist/components/SetupScreen.js.map +0 -1
  271. package/cli/dist/components/SingleLoadingScreen.d.ts +0 -5
  272. package/cli/dist/components/SingleLoadingScreen.js +0 -27
  273. package/cli/dist/components/StatusBadge.d.ts +0 -10
  274. package/cli/dist/components/StatusBadge.d.ts.map +0 -1
  275. package/cli/dist/components/StatusBadge.js +0 -24
  276. package/cli/dist/components/StatusBadge.js.map +0 -1
  277. package/cli/dist/components/TerminalWindow.d.ts +0 -9
  278. package/cli/dist/components/TerminalWindow.d.ts.map +0 -1
  279. package/cli/dist/components/TerminalWindow.js +0 -19
  280. package/cli/dist/components/TerminalWindow.js.map +0 -1
  281. package/cli/dist/components/WelcomeScreen.d.ts +0 -12
  282. package/cli/dist/components/WelcomeScreen.d.ts.map +0 -1
  283. package/cli/dist/components/WelcomeScreen.js +0 -47
  284. package/cli/dist/components/WelcomeScreen.js.map +0 -1
  285. package/cli/dist/context/AppContext.d.ts +0 -68
  286. package/cli/dist/context/AppContext.js +0 -363
  287. package/cli/dist/headless-runner.d.ts +0 -17
  288. package/cli/dist/headless-runner.d.ts.map +0 -1
  289. package/cli/dist/headless-runner.js +0 -128
  290. package/cli/dist/headless-runner.js.map +0 -1
  291. package/cli/dist/hooks/useInitializeAgent.d.ts +0 -19
  292. package/cli/dist/hooks/useInitializeAgent.d.ts.map +0 -1
  293. package/cli/dist/hooks/useInitializeAgent.js +0 -29
  294. package/cli/dist/hooks/useInitializeAgent.js.map +0 -1
  295. package/cli/dist/hooks/useStableState.d.ts +0 -38
  296. package/cli/dist/hooks/useStableState.d.ts.map +0 -1
  297. package/cli/dist/hooks/useStableState.js +0 -69
  298. package/cli/dist/hooks/useStableState.js.map +0 -1
  299. package/cli/dist/managers/AgentManager.d.ts +0 -58
  300. package/cli/dist/managers/AgentManager.d.ts.map +0 -1
  301. package/cli/dist/managers/AgentManager.js +0 -121
  302. package/cli/dist/managers/AgentManager.js.map +0 -1
  303. package/cli/dist/managers/ConfigManager.d.ts +0 -54
  304. package/cli/dist/managers/ConfigManager.d.ts.map +0 -1
  305. package/cli/dist/managers/ConfigManager.js +0 -188
  306. package/cli/dist/managers/ConfigManager.js.map +0 -1
  307. package/cli/dist/types.d.ts +0 -52
  308. package/cli/dist/types.d.ts.map +0 -1
  309. package/cli/dist/types.js +0 -34
  310. package/cli/dist/types.js.map +0 -1
@@ -1,722 +1,183 @@
1
- import { ReferenceIdGenerator } from "./index22.js";
2
- import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index46.js";
3
- const _ContentStorage = class _ContentStorage {
4
- constructor(maxStorage = _ContentStorage.DEFAULT_MAX_STORAGE, referenceConfig) {
1
+ import { TokenCounter } from "./index20.js";
2
+ const _MemoryWindow = class _MemoryWindow {
3
+ constructor(maxTokens = _MemoryWindow.DEFAULT_MAX_TOKENS, reserveTokens = _MemoryWindow.DEFAULT_RESERVE_TOKENS, tokenCounter) {
5
4
  this.messages = [];
6
- this.idCounter = 0;
7
- this.contentStore = /* @__PURE__ */ new Map();
8
- this.maxStorage = maxStorage;
9
- this.referenceConfig = {
10
- ...DEFAULT_CONTENT_REFERENCE_CONFIG,
11
- ...referenceConfig
12
- };
13
- this.referenceStats = {
14
- activeReferences: 0,
15
- totalStorageBytes: 0,
16
- recentlyCleanedUp: 0,
17
- totalResolutions: 0,
18
- failedResolutions: 0,
19
- averageContentSize: 0,
20
- storageUtilization: 0,
21
- performanceMetrics: {
22
- averageCreationTimeMs: 0,
23
- averageResolutionTimeMs: 0,
24
- averageCleanupTimeMs: 0,
25
- creationTimes: [],
26
- resolutionTimes: [],
27
- cleanupTimes: []
28
- }
29
- };
30
- if (this.referenceConfig.enableAutoCleanup) {
31
- this.startReferenceCleanupTimer();
32
- }
33
- }
34
- /**
35
- * Store messages in the content storage
36
- * Automatically drops oldest messages if storage limit is exceeded
37
- * @param messages - Messages to store
38
- * @returns Result indicating how many messages were stored and dropped
39
- */
40
- storeMessages(messages) {
41
- if (messages.length === 0) {
42
- return { stored: 0, dropped: 0 };
43
- }
44
- const now = /* @__PURE__ */ new Date();
45
- let dropped = 0;
46
- const storedMessages = messages.map((message) => ({
47
- message,
48
- storedAt: now,
49
- id: this.generateId()
50
- }));
51
- this.messages.push(...storedMessages);
52
- while (this.messages.length > this.maxStorage) {
53
- this.messages.shift();
54
- dropped++;
5
+ this.systemPrompt = "";
6
+ this.systemPromptTokens = 0;
7
+ if (reserveTokens >= maxTokens) {
8
+ throw new Error("Reserve tokens must be less than max tokens");
9
+ }
10
+ this.maxTokens = maxTokens;
11
+ this.reserveTokens = reserveTokens;
12
+ this.tokenCounter = tokenCounter || new TokenCounter();
13
+ }
14
+ /**
15
+ * Add a message to the memory window, pruning old messages if necessary
16
+ * @param message - The message to add
17
+ * @returns Result of the add operation including any pruned messages
18
+ */
19
+ addMessage(message) {
20
+ this.tokenCounter.countMessageTokens(message);
21
+ this.messages.push(message);
22
+ const currentTokens = this.getCurrentTokenCount();
23
+ const availableTokens = this.maxTokens - this.reserveTokens;
24
+ let prunedMessages = [];
25
+ if (currentTokens > availableTokens) {
26
+ this.messages.pop();
27
+ prunedMessages = this.pruneToFit();
28
+ this.messages.push(message);
55
29
  }
56
30
  return {
57
- stored: storedMessages.length,
58
- dropped
31
+ added: true,
32
+ prunedMessages,
33
+ currentTokenCount: this.getCurrentTokenCount(),
34
+ remainingCapacity: this.getRemainingTokenCapacity()
59
35
  };
60
36
  }
61
37
  /**
62
- * Get the most recent messages from storage
63
- * @param count - Number of recent messages to retrieve
64
- * @returns Array of recent messages in chronological order
38
+ * Prune old messages to fit within token limits
39
+ * Removes messages in pairs to maintain conversational flow
40
+ * @returns Array of pruned messages
65
41
  */
66
- getRecentMessages(count) {
67
- if (count <= 0 || this.messages.length === 0) {
68
- return [];
42
+ pruneToFit() {
43
+ const prunedMessages = [];
44
+ const targetTokens = this.maxTokens - this.reserveTokens;
45
+ while (this.getCurrentTokenCount() > targetTokens && this.messages.length > 0) {
46
+ const batchSize = Math.min(
47
+ _MemoryWindow.PRUNING_BATCH_SIZE,
48
+ this.messages.length
49
+ );
50
+ for (let i = 0; i < batchSize; i++) {
51
+ const prunedMessage = this.messages.shift();
52
+ if (prunedMessage) {
53
+ prunedMessages.push(prunedMessage);
54
+ }
55
+ }
56
+ if (prunedMessages.length > 1e3) {
57
+ break;
58
+ }
69
59
  }
70
- const startIndex = Math.max(0, this.messages.length - count);
71
- return this.messages.slice(startIndex).map((stored) => stored.message);
60
+ return prunedMessages;
72
61
  }
73
62
  /**
74
- * Search for messages containing specific text or patterns
75
- * @param query - Search term or regex pattern
76
- * @param options - Search configuration options
77
- * @returns Array of matching messages
63
+ * Get current token count including system prompt and messages
64
+ * @returns Current token count
78
65
  */
79
- searchMessages(query, options = {}) {
80
- if (!query || this.messages.length === 0) {
81
- return [];
82
- }
83
- const { caseSensitive = false, limit, useRegex = false } = options;
84
- let matches = [];
85
- if (useRegex) {
86
- try {
87
- const regex = new RegExp(query, caseSensitive ? "g" : "gi");
88
- matches = this.messages.filter((stored) => regex.test(stored.message.content)).map((stored) => stored.message);
89
- } catch {
90
- return [];
91
- }
92
- } else {
93
- const searchTerm = caseSensitive ? query : query.toLowerCase();
94
- matches = this.messages.filter((stored) => {
95
- const content = stored.message.content;
96
- const searchContent = caseSensitive ? content : content.toLowerCase();
97
- return searchContent.includes(searchTerm);
98
- }).map((stored) => stored.message);
99
- }
100
- return limit ? matches.slice(0, limit) : matches;
66
+ getCurrentTokenCount() {
67
+ const messageTokens = this.tokenCounter.countMessagesTokens(this.messages);
68
+ return this.systemPromptTokens + messageTokens;
101
69
  }
102
70
  /**
103
- * Get messages from a specific time range
104
- * @param startTime - Start of time range (inclusive)
105
- * @param endTime - End of time range (inclusive)
106
- * @returns Array of messages within the time range
71
+ * Get remaining token capacity before hitting the reserve limit
72
+ * @returns Remaining tokens that can be used
107
73
  */
108
- getMessagesFromTimeRange(startTime, endTime) {
109
- if (startTime > endTime || this.messages.length === 0) {
110
- return [];
111
- }
112
- return this.messages.filter(
113
- (stored) => stored.storedAt >= startTime && stored.storedAt <= endTime
114
- ).map((stored) => stored.message);
74
+ getRemainingTokenCapacity() {
75
+ return Math.max(0, this.maxTokens - this.getCurrentTokenCount());
115
76
  }
116
77
  /**
117
- * Get storage statistics and usage information
118
- * @returns Current storage statistics
78
+ * Check if a message can be added without exceeding limits
79
+ * @param message - The message to check
80
+ * @returns True if message can be added within reserve limits
119
81
  */
120
- getStorageStats() {
121
- const totalMessages = this.messages.length;
122
- const usagePercentage = totalMessages > 0 ? Math.round(totalMessages / this.maxStorage * 100) : 0;
123
- let oldestMessageTime;
124
- let newestMessageTime;
125
- if (totalMessages > 0) {
126
- oldestMessageTime = this.messages[0].storedAt;
127
- newestMessageTime = this.messages[totalMessages - 1].storedAt;
82
+ canAddMessage(message) {
83
+ const messageTokens = this.tokenCounter.countMessageTokens(message);
84
+ const currentTokens = this.getCurrentTokenCount();
85
+ const wouldExceedReserve = currentTokens + messageTokens > this.maxTokens - this.reserveTokens;
86
+ if (messageTokens > this.maxTokens) {
87
+ return false;
128
88
  }
129
- return {
130
- totalMessages,
131
- maxStorageLimit: this.maxStorage,
132
- usagePercentage,
133
- oldestMessageTime,
134
- newestMessageTime
135
- };
89
+ return !wouldExceedReserve || this.messages.length > 0;
136
90
  }
137
91
  /**
138
- * Clear all stored messages
92
+ * Get all messages in the memory window
93
+ * @returns Copy of current messages array
139
94
  */
140
- clear() {
141
- this.messages = [];
142
- this.idCounter = 0;
95
+ getMessages() {
96
+ return [...this.messages];
143
97
  }
144
98
  /**
145
- * Get total number of stored messages
146
- * @returns Number of messages currently in storage
99
+ * Clear all messages from the memory window
147
100
  */
148
- getTotalStoredMessages() {
149
- return this.messages.length;
101
+ clear() {
102
+ this.messages = [];
150
103
  }
151
104
  /**
152
- * Update the maximum storage limit
153
- * @param newLimit - New maximum storage limit
105
+ * Set the system prompt and update token calculations
106
+ * @param systemPrompt - The system prompt text
154
107
  */
155
- updateStorageLimit(newLimit) {
156
- if (newLimit <= 0) {
157
- throw new Error("Storage limit must be greater than 0");
158
- }
159
- this.maxStorage = newLimit;
160
- while (this.messages.length > this.maxStorage) {
161
- this.messages.shift();
162
- }
108
+ setSystemPrompt(systemPrompt) {
109
+ this.systemPrompt = systemPrompt;
110
+ this.systemPromptTokens = this.tokenCounter.estimateSystemPromptTokens(systemPrompt);
163
111
  }
164
112
  /**
165
- * Get messages by message type
166
- * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)
167
- * @param limit - Maximum number of messages to return
168
- * @returns Array of messages of the specified type
113
+ * Get the current system prompt
114
+ * @returns Current system prompt
169
115
  */
170
- getMessagesByType(messageType, limit) {
171
- const filtered = this.messages.filter((stored) => stored.message._getType() === messageType).map((stored) => stored.message);
172
- return limit ? filtered.slice(0, limit) : filtered;
116
+ getSystemPrompt() {
117
+ return this.systemPrompt;
173
118
  }
174
119
  /**
175
- * Get the current storage configuration
176
- * @returns Storage configuration object
120
+ * Get current configuration
121
+ * @returns Memory window configuration
177
122
  */
178
123
  getConfig() {
179
124
  return {
180
- maxStorage: this.maxStorage,
181
- currentUsage: this.messages.length,
182
- utilizationPercentage: this.messages.length / this.maxStorage * 100
125
+ maxTokens: this.maxTokens,
126
+ reserveTokens: this.reserveTokens,
127
+ currentTokens: this.getCurrentTokenCount(),
128
+ messageCount: this.messages.length,
129
+ systemPromptTokens: this.systemPromptTokens
183
130
  };
184
131
  }
185
132
  /**
186
- * Generate a unique ID for stored messages
187
- * @returns Unique string identifier
188
- */
189
- generateId() {
190
- return `msg_${++this.idCounter}_${Date.now()}`;
191
- }
192
- /**
193
- * Get messages stored within the last N minutes
194
- * @param minutes - Number of minutes to look back
195
- * @returns Array of messages from the last N minutes
196
- */
197
- getRecentMessagesByTime(minutes) {
198
- if (minutes <= 0 || this.messages.length === 0) {
199
- return [];
200
- }
201
- const cutoffTime = new Date(Date.now() - minutes * 60 * 1e3);
202
- return this.messages.filter((stored) => stored.storedAt >= cutoffTime).map((stored) => stored.message);
203
- }
204
- /**
205
- * Export messages to a JSON-serializable format
206
- * @returns Serializable representation of stored messages
133
+ * Update token limits
134
+ * @param maxTokens - New maximum token limit
135
+ * @param reserveTokens - New reserve token amount
207
136
  */
208
- exportMessages() {
209
- return this.messages.map((stored) => ({
210
- content: typeof stored.message.content === "string" ? stored.message.content : JSON.stringify(stored.message.content),
211
- type: stored.message._getType(),
212
- storedAt: stored.storedAt.toISOString(),
213
- id: stored.id
214
- }));
215
- }
216
- /**
217
- * Determine if content should be stored as a reference based on size
218
- */
219
- shouldUseReference(content) {
220
- const size = Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content, "utf8");
221
- return size > this.referenceConfig.sizeThresholdBytes;
222
- }
223
- /**
224
- * Store content and return a reference if it exceeds the size threshold
225
- * Otherwise returns null to indicate direct content should be used
226
- *
227
- * Special case: Image files are ALWAYS stored as references regardless of size
228
- * because they need special handling for inscription tools
229
- */
230
- async storeContentIfLarge(content, metadata) {
231
- const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8");
232
- const isImageFile = this.isImageContent(
233
- metadata.mimeType,
234
- metadata.fileName
235
- );
236
- if (!isImageFile && !this.shouldUseReference(buffer)) {
237
- return null;
238
- }
239
- const storeMetadata = {
240
- contentType: metadata.contentType || this.detectContentType(buffer, metadata.mimeType),
241
- sizeBytes: buffer.length,
242
- source: metadata.source,
243
- tags: []
244
- };
245
- if (metadata.mimeType !== void 0) {
246
- storeMetadata.mimeType = metadata.mimeType;
247
- }
248
- if (metadata.mcpToolName !== void 0) {
249
- storeMetadata.mcpToolName = metadata.mcpToolName;
137
+ updateLimits(maxTokens, reserveTokens) {
138
+ if (reserveTokens !== void 0 && reserveTokens >= maxTokens) {
139
+ throw new Error("Reserve tokens must be less than max tokens");
250
140
  }
251
- if (metadata.fileName !== void 0) {
252
- storeMetadata.fileName = metadata.fileName;
141
+ this.maxTokens = maxTokens;
142
+ if (reserveTokens !== void 0) {
143
+ this.reserveTokens = reserveTokens;
253
144
  }
254
- if (metadata.tags !== void 0) {
255
- storeMetadata.tags = metadata.tags;
145
+ if (this.getCurrentTokenCount() > this.maxTokens - this.reserveTokens) {
146
+ this.pruneToFit();
256
147
  }
257
- if (metadata.customMetadata !== void 0) {
258
- storeMetadata.customMetadata = metadata.customMetadata;
259
- }
260
- return await this.storeContent(buffer, storeMetadata);
261
148
  }
262
149
  /**
263
- * Store content and return a reference (implements ContentReferenceStore)
150
+ * Get statistics about the memory window
151
+ * @returns Memory usage statistics
264
152
  */
265
- async storeContent(content, metadata) {
266
- const startTime = Date.now();
267
- try {
268
- const now = /* @__PURE__ */ new Date();
269
- const referenceId = ReferenceIdGenerator.generateId(content);
270
- const fullMetadata = {
271
- ...metadata,
272
- createdAt: now,
273
- lastAccessedAt: now,
274
- accessCount: 0
275
- };
276
- const storedContent = {
277
- content,
278
- metadata: fullMetadata,
279
- state: "active"
280
- };
281
- const expirationTime = this.calculateExpirationTime(metadata.source);
282
- if (expirationTime !== void 0) {
283
- storedContent.expiresAt = expirationTime;
284
- }
285
- this.contentStore.set(referenceId, storedContent);
286
- this.updateStatsAfterStore(content.length);
287
- await this.enforceReferenceStorageLimits();
288
- const preview = this.createContentPreview(
289
- content,
290
- fullMetadata.contentType
291
- );
292
- const referenceMetadata = {
293
- contentType: fullMetadata.contentType,
294
- sizeBytes: fullMetadata.sizeBytes,
295
- source: fullMetadata.source
296
- };
297
- if (fullMetadata.fileName !== void 0) {
298
- referenceMetadata.fileName = fullMetadata.fileName;
299
- }
300
- if (fullMetadata.mimeType !== void 0) {
301
- referenceMetadata.mimeType = fullMetadata.mimeType;
302
- }
303
- const reference = {
304
- referenceId,
305
- state: "active",
306
- preview,
307
- metadata: referenceMetadata,
308
- createdAt: now,
309
- format: "ref://{id}"
310
- };
311
- const duration = Date.now() - startTime;
312
- this.recordPerformanceMetric("creation", duration);
313
- return reference;
314
- } catch (error) {
315
- const duration = Date.now() - startTime;
316
- this.recordPerformanceMetric("creation", duration);
317
- throw new ContentReferenceError(
318
- `Failed to store content: ${error instanceof Error ? error.message : "Unknown error"}`,
319
- "system_error",
320
- void 0,
321
- ["Try again", "Check storage limits", "Contact administrator"]
322
- );
323
- }
324
- }
325
- /**
326
- * Resolve a reference to its content (implements ContentReferenceStore)
327
- */
328
- async resolveReference(referenceId) {
329
- const startTime = Date.now();
330
- try {
331
- if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {
332
- this.referenceStats.failedResolutions++;
333
- return {
334
- success: false,
335
- error: "Invalid reference ID format",
336
- errorType: "not_found",
337
- suggestedActions: [
338
- "Check the reference ID format",
339
- "Ensure the reference ID is complete"
340
- ]
341
- };
342
- }
343
- const storedContent = this.contentStore.get(referenceId);
344
- if (!storedContent) {
345
- this.referenceStats.failedResolutions++;
346
- return {
347
- success: false,
348
- error: "Reference not found",
349
- errorType: "not_found",
350
- suggestedActions: [
351
- "Verify the reference ID",
352
- "Check if the content has expired",
353
- "Request fresh content"
354
- ]
355
- };
356
- }
357
- if (storedContent.expiresAt && storedContent.expiresAt < /* @__PURE__ */ new Date()) {
358
- storedContent.state = "expired";
359
- this.referenceStats.failedResolutions++;
360
- return {
361
- success: false,
362
- error: "Reference has expired",
363
- errorType: "expired",
364
- suggestedActions: [
365
- "Request fresh content",
366
- "Use alternative content source"
367
- ]
368
- };
369
- }
370
- if (storedContent.state !== "active") {
371
- this.referenceStats.failedResolutions++;
372
- return {
373
- success: false,
374
- error: `Reference is ${storedContent.state}`,
375
- errorType: storedContent.state === "expired" ? "expired" : "corrupted",
376
- suggestedActions: [
377
- "Request fresh content",
378
- "Check reference validity"
379
- ]
380
- };
381
- }
382
- storedContent.metadata.lastAccessedAt = /* @__PURE__ */ new Date();
383
- storedContent.metadata.accessCount++;
384
- this.referenceStats.totalResolutions++;
385
- const duration = Date.now() - startTime;
386
- this.recordPerformanceMetric("resolution", duration);
387
- return {
388
- success: true,
389
- content: storedContent.content,
390
- metadata: storedContent.metadata
391
- };
392
- } catch (error) {
393
- const duration = Date.now() - startTime;
394
- this.recordPerformanceMetric("resolution", duration);
395
- this.referenceStats.failedResolutions++;
396
- return {
397
- success: false,
398
- error: `System error resolving reference: ${error instanceof Error ? error.message : "Unknown error"}`,
399
- errorType: "system_error",
400
- suggestedActions: ["Try again", "Contact administrator"]
401
- };
402
- }
403
- }
404
- /**
405
- * Check if a reference exists and is valid
406
- */
407
- async hasReference(referenceId) {
408
- if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {
409
- return false;
410
- }
411
- const storedContent = this.contentStore.get(referenceId);
412
- if (!storedContent) {
413
- return false;
414
- }
415
- if (storedContent.expiresAt && storedContent.expiresAt < /* @__PURE__ */ new Date()) {
416
- storedContent.state = "expired";
417
- return false;
418
- }
419
- return storedContent.state === "active";
420
- }
421
- /**
422
- * Mark a reference for cleanup
423
- */
424
- async cleanupReference(referenceId) {
425
- const storedContent = this.contentStore.get(referenceId);
426
- if (!storedContent) {
427
- return false;
428
- }
429
- this.referenceStats.totalStorageBytes -= storedContent.content.length;
430
- this.referenceStats.activeReferences--;
431
- this.referenceStats.recentlyCleanedUp++;
432
- this.contentStore.delete(referenceId);
433
- return true;
434
- }
435
- /**
436
- * Get current reference storage statistics (implements ContentReferenceStore)
437
- */
438
- async getStats() {
439
- this.updateReferenceStorageStats();
153
+ getStats() {
154
+ const currentTokens = this.getCurrentTokenCount();
155
+ const capacity = this.maxTokens;
156
+ const usagePercentage = currentTokens / capacity * 100;
440
157
  return {
441
- ...this.referenceStats,
442
- performanceMetrics: {
443
- averageCreationTimeMs: this.calculateAverage(
444
- this.referenceStats.performanceMetrics.creationTimes
445
- ),
446
- averageResolutionTimeMs: this.calculateAverage(
447
- this.referenceStats.performanceMetrics.resolutionTimes
448
- ),
449
- averageCleanupTimeMs: this.calculateAverage(
450
- this.referenceStats.performanceMetrics.cleanupTimes
451
- )
452
- }
158
+ totalMessages: this.messages.length,
159
+ currentTokens,
160
+ maxTokens: capacity,
161
+ reserveTokens: this.reserveTokens,
162
+ systemPromptTokens: this.systemPromptTokens,
163
+ usagePercentage: Math.round(usagePercentage * 100) / 100,
164
+ remainingCapacity: this.getRemainingTokenCapacity(),
165
+ canAcceptMore: this.getRemainingTokenCapacity() > this.reserveTokens
453
166
  };
454
167
  }
455
168
  /**
456
- * Update reference configuration
169
+ * Clean up resources
457
170
  */
458
- async updateConfig(config) {
459
- this.referenceConfig = { ...this.referenceConfig, ...config };
460
- if (this.cleanupTimer) {
461
- clearInterval(this.cleanupTimer);
462
- delete this.cleanupTimer;
463
- }
464
- if (this.referenceConfig.enableAutoCleanup) {
465
- this.startReferenceCleanupTimer();
466
- }
467
- }
468
- /**
469
- * Perform cleanup based on current policies (implements ContentReferenceStore)
470
- */
471
- async performCleanup() {
472
- const startTime = Date.now();
473
- const errors = [];
474
- let cleanedUp = 0;
475
- try {
476
- const now = /* @__PURE__ */ new Date();
477
- const toCleanup = [];
478
- for (const [referenceId, storedContent] of this.contentStore.entries()) {
479
- let shouldCleanup = false;
480
- if (storedContent.expiresAt && storedContent.expiresAt < now) {
481
- shouldCleanup = true;
482
- storedContent.state = "expired";
483
- }
484
- const ageMs = now.getTime() - storedContent.metadata.createdAt.getTime();
485
- const policy = this.getCleanupPolicy(storedContent.metadata.source);
486
- if (ageMs > policy.maxAgeMs) {
487
- shouldCleanup = true;
488
- }
489
- if (storedContent.state === "cleanup_pending") {
490
- shouldCleanup = true;
491
- }
492
- if (shouldCleanup) {
493
- toCleanup.push(referenceId);
494
- }
495
- }
496
- toCleanup.sort((a, b) => {
497
- const aContent = this.contentStore.get(a);
498
- const bContent = this.contentStore.get(b);
499
- const aPriority = this.getCleanupPolicy(
500
- aContent.metadata.source
501
- ).priority;
502
- const bPriority = this.getCleanupPolicy(
503
- bContent.metadata.source
504
- ).priority;
505
- return bPriority - aPriority;
506
- });
507
- for (const referenceId of toCleanup) {
508
- try {
509
- const success = await this.cleanupReference(referenceId);
510
- if (success) {
511
- cleanedUp++;
512
- }
513
- } catch (error) {
514
- errors.push(
515
- `Failed to cleanup ${referenceId}: ${error instanceof Error ? error.message : "Unknown error"}`
516
- );
517
- }
518
- }
519
- if (this.contentStore.size > this.referenceConfig.maxReferences) {
520
- const sortedByAge = Array.from(this.contentStore.entries()).sort(
521
- ([, a], [, b]) => a.metadata.lastAccessedAt.getTime() - b.metadata.lastAccessedAt.getTime()
522
- );
523
- const excessCount = this.contentStore.size - this.referenceConfig.maxReferences;
524
- for (let i = 0; i < excessCount && i < sortedByAge.length; i++) {
525
- const [referenceId] = sortedByAge[i];
526
- try {
527
- const success = await this.cleanupReference(referenceId);
528
- if (success) {
529
- cleanedUp++;
530
- }
531
- } catch (error) {
532
- errors.push(
533
- `Failed to cleanup excess reference ${referenceId}: ${error instanceof Error ? error.message : "Unknown error"}`
534
- );
535
- }
536
- }
537
- }
538
- const duration = Date.now() - startTime;
539
- this.recordPerformanceMetric("cleanup", duration);
540
- return { cleanedUp, errors };
541
- } catch (error) {
542
- const duration = Date.now() - startTime;
543
- this.recordPerformanceMetric("cleanup", duration);
544
- const errorMessage = `Cleanup process failed: ${error instanceof Error ? error.message : "Unknown error"}`;
545
- errors.push(errorMessage);
546
- return { cleanedUp, errors };
547
- }
548
- }
549
- /**
550
- * Get reference configuration for debugging
551
- */
552
- getReferenceConfig() {
553
- return { ...this.referenceConfig };
554
- }
555
- async enforceReferenceStorageLimits() {
556
- if (this.contentStore.size >= this.referenceConfig.maxReferences) {
557
- await this.performCleanup();
558
- }
559
- if (this.referenceStats.totalStorageBytes >= this.referenceConfig.maxTotalStorageBytes) {
560
- await this.performCleanup();
561
- }
562
- }
563
- calculateExpirationTime(source) {
564
- const policy = this.getCleanupPolicy(source);
565
- return new Date(Date.now() + policy.maxAgeMs);
566
- }
567
- getCleanupPolicy(source) {
568
- switch (source) {
569
- case "mcp_tool":
570
- return this.referenceConfig.cleanupPolicies.recent;
571
- case "user_upload":
572
- return this.referenceConfig.cleanupPolicies.userContent;
573
- case "agent_generated":
574
- return this.referenceConfig.cleanupPolicies.agentGenerated;
575
- default:
576
- return this.referenceConfig.cleanupPolicies.default;
577
- }
578
- }
579
- detectContentType(content, mimeType) {
580
- if (mimeType) {
581
- if (mimeType === "text/html") return "html";
582
- if (mimeType === "text/markdown") return "markdown";
583
- if (mimeType === "application/json") return "json";
584
- if (mimeType.startsWith("text/")) return "text";
585
- return "binary";
586
- }
587
- const contentStr = content.toString(
588
- "utf8",
589
- 0,
590
- Math.min(content.length, 1e3)
591
- );
592
- if (contentStr.startsWith("{") || contentStr.startsWith("[")) return "json";
593
- if (contentStr.includes("<html>") || contentStr.includes("<!DOCTYPE"))
594
- return "html";
595
- if (contentStr.includes("#") && contentStr.includes("\n"))
596
- return "markdown";
597
- return "text";
598
- }
599
- createContentPreview(content, contentType) {
600
- const maxLength = 200;
601
- let preview = content.toString(
602
- "utf8",
603
- 0,
604
- Math.min(content.length, maxLength * 2)
605
- );
606
- if (contentType === "html") {
607
- preview = preview.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
608
- } else if (contentType === "json") {
609
- try {
610
- const parsed = JSON.parse(preview);
611
- preview = JSON.stringify(parsed, null, 0);
612
- } catch {
613
- }
614
- }
615
- preview = preview.trim();
616
- if (preview.length > maxLength) {
617
- preview = preview.substring(0, maxLength) + "...";
618
- }
619
- return preview || "[Binary content]";
620
- }
621
- updateStatsAfterStore(sizeBytes) {
622
- this.referenceStats.activeReferences++;
623
- this.referenceStats.totalStorageBytes += sizeBytes;
624
- this.updateReferenceStorageStats();
625
- }
626
- updateReferenceStorageStats() {
627
- if (this.referenceStats.activeReferences > 0) {
628
- this.referenceStats.averageContentSize = this.referenceStats.totalStorageBytes / this.referenceStats.activeReferences;
629
- }
630
- this.referenceStats.storageUtilization = this.referenceStats.totalStorageBytes / this.referenceConfig.maxTotalStorageBytes * 100;
631
- let mostAccessedId;
632
- let maxAccess = 0;
633
- for (const [referenceId, storedContent] of this.contentStore.entries()) {
634
- if (storedContent.metadata.accessCount > maxAccess) {
635
- maxAccess = storedContent.metadata.accessCount;
636
- mostAccessedId = referenceId;
637
- }
638
- }
639
- if (mostAccessedId !== void 0) {
640
- this.referenceStats.mostAccessedReferenceId = mostAccessedId;
641
- } else {
642
- delete this.referenceStats.mostAccessedReferenceId;
643
- }
644
- }
645
- /**
646
- * Check if content is an image file based on MIME type or filename
647
- */
648
- isImageContent(mimeType, fileName) {
649
- if (mimeType && mimeType.startsWith("image/")) {
650
- return true;
651
- }
652
- if (fileName) {
653
- const lowerFileName = fileName.toLowerCase();
654
- const imageExtensions = [
655
- ".png",
656
- ".jpg",
657
- ".jpeg",
658
- ".gif",
659
- ".bmp",
660
- ".webp",
661
- ".svg",
662
- ".tiff",
663
- ".ico"
664
- ];
665
- return imageExtensions.some((ext) => lowerFileName.endsWith(ext));
666
- }
667
- return false;
668
- }
669
- recordPerformanceMetric(type, timeMs) {
670
- const metrics = this.referenceStats.performanceMetrics;
671
- const maxRecords = 100;
672
- switch (type) {
673
- case "creation":
674
- metrics.creationTimes.push(timeMs);
675
- if (metrics.creationTimes.length > maxRecords) {
676
- metrics.creationTimes.shift();
677
- }
678
- break;
679
- case "resolution":
680
- metrics.resolutionTimes.push(timeMs);
681
- if (metrics.resolutionTimes.length > maxRecords) {
682
- metrics.resolutionTimes.shift();
683
- }
684
- break;
685
- case "cleanup":
686
- metrics.cleanupTimes.push(timeMs);
687
- if (metrics.cleanupTimes.length > maxRecords) {
688
- metrics.cleanupTimes.shift();
689
- }
690
- break;
691
- }
692
- }
693
- calculateAverage(times) {
694
- if (times.length === 0) return 0;
695
- return times.reduce((sum, time) => sum + time, 0) / times.length;
696
- }
697
- startReferenceCleanupTimer() {
698
- this.cleanupTimer = setInterval(async () => {
699
- try {
700
- await this.performCleanup();
701
- } catch {
702
- }
703
- }, this.referenceConfig.cleanupIntervalMs);
704
- }
705
- /**
706
- * Clean up resources (enhanced to include reference cleanup)
707
- */
708
- async dispose() {
709
- if (this.cleanupTimer) {
710
- clearInterval(this.cleanupTimer);
711
- delete this.cleanupTimer;
712
- }
713
- this.contentStore.clear();
171
+ dispose() {
714
172
  this.clear();
173
+ this.tokenCounter.dispose();
715
174
  }
716
175
  };
717
- _ContentStorage.DEFAULT_MAX_STORAGE = 1e3;
718
- let ContentStorage = _ContentStorage;
176
+ _MemoryWindow.DEFAULT_MAX_TOKENS = 8e3;
177
+ _MemoryWindow.DEFAULT_RESERVE_TOKENS = 1e3;
178
+ _MemoryWindow.PRUNING_BATCH_SIZE = 2;
179
+ let MemoryWindow = _MemoryWindow;
719
180
  export {
720
- ContentStorage
181
+ MemoryWindow
721
182
  };
722
183
  //# sourceMappingURL=index21.js.map