@agentmemory/agentmemory 0.9.30 → 0.9.31

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 (331) hide show
  1. package/.env.example +39 -33
  2. package/AGENTS.md +8 -8
  3. package/README.md +173 -558
  4. package/dist/.env.example +39 -33
  5. package/dist/cli.d.mts.map +1 -1
  6. package/dist/cli.mjs +1741 -966
  7. package/dist/cli.mjs.map +1 -1
  8. package/dist/compression-recovery-CnhLQC6N.mjs +5912 -0
  9. package/dist/compression-recovery-CnhLQC6N.mjs.map +1 -0
  10. package/dist/{connect-B4_ca6BD.mjs → connect-BSLIAMpw.mjs} +874 -267
  11. package/dist/connect-BSLIAMpw.mjs.map +1 -0
  12. package/dist/hooks/_capture.d.mts +5 -2
  13. package/dist/hooks/_capture.d.mts.map +1 -1
  14. package/dist/hooks/_capture.mjs +55 -19
  15. package/dist/hooks/_capture.mjs.map +1 -1
  16. package/dist/hooks/notification.mjs +20 -6
  17. package/dist/hooks/notification.mjs.map +1 -1
  18. package/dist/hooks/post-commit.mjs +25 -5
  19. package/dist/hooks/post-commit.mjs.map +1 -1
  20. package/dist/hooks/post-tool-failure.mjs +12 -4
  21. package/dist/hooks/post-tool-failure.mjs.map +1 -1
  22. package/dist/hooks/post-tool-use.mjs +12 -4
  23. package/dist/hooks/post-tool-use.mjs.map +1 -1
  24. package/dist/hooks/pre-compact.mjs +37 -10
  25. package/dist/hooks/pre-compact.mjs.map +1 -1
  26. package/dist/hooks/pre-tool-use.mjs +25 -5
  27. package/dist/hooks/pre-tool-use.mjs.map +1 -1
  28. package/dist/hooks/prompt-submit.mjs +12 -4
  29. package/dist/hooks/prompt-submit.mjs.map +1 -1
  30. package/dist/hooks/session-end.mjs +47 -16
  31. package/dist/hooks/session-end.mjs.map +1 -1
  32. package/dist/hooks/session-start.mjs +37 -10
  33. package/dist/hooks/session-start.mjs.map +1 -1
  34. package/dist/hooks/stop.mjs +74 -72
  35. package/dist/hooks/stop.mjs.map +1 -1
  36. package/dist/hooks/subagent-start.mjs +13 -5
  37. package/dist/hooks/subagent-start.mjs.map +1 -1
  38. package/dist/hooks/subagent-stop.mjs +18 -6
  39. package/dist/hooks/subagent-stop.mjs.map +1 -1
  40. package/dist/hooks/task-completed.mjs +13 -5
  41. package/dist/hooks/task-completed.mjs.map +1 -1
  42. package/dist/{image-refs-T_urbwHM.mjs → image-refs-Cyta4Lf9.mjs} +2 -2
  43. package/dist/{image-refs-T_urbwHM.mjs.map → image-refs-Cyta4Lf9.mjs.map} +1 -1
  44. package/dist/index.mjs +8539 -4203
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/integrations/dsh.d.mts +55 -0
  47. package/dist/integrations/dsh.d.mts.map +1 -0
  48. package/dist/integrations/dsh.mjs +1145 -0
  49. package/dist/integrations/dsh.mjs.map +1 -0
  50. package/dist/{keyed-mutex-DchXsyfP.mjs → keyed-mutex-DCUh7PG-.mjs} +58 -9
  51. package/dist/keyed-mutex-DCUh7PG-.mjs.map +1 -0
  52. package/dist/{secret-store-BnY3A50C.mjs → secret-store-D9GwO0xp.mjs} +535 -434
  53. package/dist/secret-store-D9GwO0xp.mjs.map +1 -0
  54. package/dist/session-arguments-zxsbbd8y.mjs +113 -0
  55. package/dist/session-arguments-zxsbbd8y.mjs.map +1 -0
  56. package/dist/{src-Jsq9LCeH.mjs → src-DaMtDzt_.mjs} +4087 -3788
  57. package/dist/src-DaMtDzt_.mjs.map +1 -0
  58. package/dist/{standalone-DKCdrf1d.mjs → standalone-BlqshyZ5.mjs} +213 -56
  59. package/dist/standalone-BlqshyZ5.mjs.map +1 -0
  60. package/dist/standalone.d.mts +1 -1
  61. package/dist/standalone.d.mts.map +1 -1
  62. package/dist/standalone.mjs +626 -73
  63. package/dist/standalone.mjs.map +1 -1
  64. package/dist/viewer/index.html +288 -140
  65. package/integrations/hermes/README.md +84 -0
  66. package/integrations/hermes/__init__.py +669 -0
  67. package/integrations/hermes/plugin.yaml +27 -0
  68. package/integrations/omp/LICENSE +190 -0
  69. package/integrations/omp/README.md +76 -0
  70. package/integrations/omp/capture.ts +1 -0
  71. package/integrations/omp/dist/index.mjs +1450 -0
  72. package/integrations/omp/index.ts +488 -0
  73. package/integrations/omp/package.json +13 -0
  74. package/integrations/omp/security.ts +67 -0
  75. package/integrations/omp/skills/agentmemory-agents/REFERENCE.md +32 -0
  76. package/integrations/omp/skills/agentmemory-agents/SKILL.md +48 -0
  77. package/integrations/omp/skills/agentmemory-agents/TROUBLESHOOTING.md +70 -0
  78. package/integrations/omp/skills/agentmemory-architecture/SKILL.md +33 -0
  79. package/integrations/omp/skills/agentmemory-architecture/TROUBLESHOOTING.md +70 -0
  80. package/integrations/omp/skills/agentmemory-config/REFERENCE.md +90 -0
  81. package/integrations/omp/skills/agentmemory-config/SKILL.md +78 -0
  82. package/integrations/omp/skills/agentmemory-config/TROUBLESHOOTING.md +70 -0
  83. package/integrations/omp/skills/agentmemory-hooks/REFERENCE.md +20 -0
  84. package/integrations/omp/skills/agentmemory-hooks/SKILL.md +49 -0
  85. package/integrations/omp/skills/agentmemory-hooks/TROUBLESHOOTING.md +70 -0
  86. package/integrations/omp/skills/agentmemory-mcp-tools/REFERENCE.md +66 -0
  87. package/integrations/omp/skills/agentmemory-mcp-tools/SKILL.md +42 -0
  88. package/integrations/omp/skills/agentmemory-mcp-tools/TROUBLESHOOTING.md +70 -0
  89. package/integrations/omp/skills/agentmemory-rest-api/REFERENCE.md +158 -0
  90. package/integrations/omp/skills/agentmemory-rest-api/SKILL.md +49 -0
  91. package/integrations/omp/skills/agentmemory-rest-api/TROUBLESHOOTING.md +70 -0
  92. package/integrations/omp/skills/commit-context/EXAMPLES.md +71 -0
  93. package/integrations/omp/skills/commit-context/SKILL.md +64 -0
  94. package/integrations/omp/skills/commit-context/TROUBLESHOOTING.md +70 -0
  95. package/integrations/omp/skills/commit-history/EXAMPLES.md +71 -0
  96. package/integrations/omp/skills/commit-history/SKILL.md +62 -0
  97. package/integrations/omp/skills/commit-history/TROUBLESHOOTING.md +70 -0
  98. package/integrations/omp/skills/forget/EXAMPLES.md +40 -0
  99. package/integrations/omp/skills/forget/SKILL.md +73 -0
  100. package/integrations/omp/skills/forget/TROUBLESHOOTING.md +70 -0
  101. package/integrations/omp/skills/handoff/EXAMPLES.md +57 -0
  102. package/integrations/omp/skills/handoff/SKILL.md +75 -0
  103. package/integrations/omp/skills/handoff/TROUBLESHOOTING.md +70 -0
  104. package/integrations/omp/skills/lesson/SKILL.md +64 -0
  105. package/integrations/omp/skills/lesson/TROUBLESHOOTING.md +70 -0
  106. package/integrations/omp/skills/memory-discipline/SKILL.md +65 -0
  107. package/integrations/omp/skills/memory-discipline/TROUBLESHOOTING.md +70 -0
  108. package/integrations/omp/skills/recall/EXAMPLES.md +74 -0
  109. package/integrations/omp/skills/recall/SKILL.md +74 -0
  110. package/integrations/omp/skills/recall/TROUBLESHOOTING.md +70 -0
  111. package/integrations/omp/skills/recap/EXAMPLES.md +62 -0
  112. package/integrations/omp/skills/recap/SKILL.md +68 -0
  113. package/integrations/omp/skills/recap/TROUBLESHOOTING.md +70 -0
  114. package/integrations/omp/skills/remember/EXAMPLES.md +67 -0
  115. package/integrations/omp/skills/remember/SKILL.md +66 -0
  116. package/integrations/omp/skills/remember/TROUBLESHOOTING.md +70 -0
  117. package/integrations/omp/skills/session-history/EXAMPLES.md +59 -0
  118. package/integrations/omp/skills/session-history/SKILL.md +67 -0
  119. package/integrations/omp/skills/session-history/TROUBLESHOOTING.md +70 -0
  120. package/integrations/omp/skills/write-agentmemory-skill/SKILL.md +41 -0
  121. package/integrations/omp/skills/write-agentmemory-skill/TROUBLESHOOTING.md +70 -0
  122. package/integrations/openclaw/LICENSE +190 -0
  123. package/integrations/openclaw/README.md +88 -0
  124. package/integrations/openclaw/openclaw.plugin.json +71 -0
  125. package/integrations/openclaw/package.json +38 -0
  126. package/integrations/openclaw/plugin.mjs +425 -0
  127. package/integrations/openclaw/plugin.yaml +26 -0
  128. package/integrations/openclaw/skills/agentmemory-agents/REFERENCE.md +32 -0
  129. package/integrations/openclaw/skills/agentmemory-agents/SKILL.md +48 -0
  130. package/integrations/openclaw/skills/agentmemory-agents/TROUBLESHOOTING.md +70 -0
  131. package/integrations/openclaw/skills/agentmemory-architecture/SKILL.md +33 -0
  132. package/integrations/openclaw/skills/agentmemory-architecture/TROUBLESHOOTING.md +70 -0
  133. package/integrations/openclaw/skills/agentmemory-config/REFERENCE.md +90 -0
  134. package/integrations/openclaw/skills/agentmemory-config/SKILL.md +78 -0
  135. package/integrations/openclaw/skills/agentmemory-config/TROUBLESHOOTING.md +70 -0
  136. package/integrations/openclaw/skills/agentmemory-hooks/REFERENCE.md +20 -0
  137. package/integrations/openclaw/skills/agentmemory-hooks/SKILL.md +49 -0
  138. package/integrations/openclaw/skills/agentmemory-hooks/TROUBLESHOOTING.md +70 -0
  139. package/integrations/openclaw/skills/agentmemory-mcp-tools/REFERENCE.md +66 -0
  140. package/integrations/openclaw/skills/agentmemory-mcp-tools/SKILL.md +42 -0
  141. package/integrations/openclaw/skills/agentmemory-mcp-tools/TROUBLESHOOTING.md +70 -0
  142. package/integrations/openclaw/skills/agentmemory-rest-api/REFERENCE.md +158 -0
  143. package/integrations/openclaw/skills/agentmemory-rest-api/SKILL.md +49 -0
  144. package/integrations/openclaw/skills/agentmemory-rest-api/TROUBLESHOOTING.md +70 -0
  145. package/integrations/openclaw/skills/commit-context/EXAMPLES.md +71 -0
  146. package/integrations/openclaw/skills/commit-context/SKILL.md +64 -0
  147. package/integrations/openclaw/skills/commit-context/TROUBLESHOOTING.md +70 -0
  148. package/integrations/openclaw/skills/commit-history/EXAMPLES.md +71 -0
  149. package/integrations/openclaw/skills/commit-history/SKILL.md +62 -0
  150. package/integrations/openclaw/skills/commit-history/TROUBLESHOOTING.md +70 -0
  151. package/integrations/openclaw/skills/forget/EXAMPLES.md +40 -0
  152. package/integrations/openclaw/skills/forget/SKILL.md +73 -0
  153. package/integrations/openclaw/skills/forget/TROUBLESHOOTING.md +70 -0
  154. package/integrations/openclaw/skills/handoff/EXAMPLES.md +57 -0
  155. package/integrations/openclaw/skills/handoff/SKILL.md +75 -0
  156. package/integrations/openclaw/skills/handoff/TROUBLESHOOTING.md +70 -0
  157. package/integrations/openclaw/skills/lesson/SKILL.md +64 -0
  158. package/integrations/openclaw/skills/lesson/TROUBLESHOOTING.md +70 -0
  159. package/integrations/openclaw/skills/memory-discipline/SKILL.md +65 -0
  160. package/integrations/openclaw/skills/memory-discipline/TROUBLESHOOTING.md +70 -0
  161. package/integrations/openclaw/skills/recall/EXAMPLES.md +74 -0
  162. package/integrations/openclaw/skills/recall/SKILL.md +74 -0
  163. package/integrations/openclaw/skills/recall/TROUBLESHOOTING.md +70 -0
  164. package/integrations/openclaw/skills/recap/EXAMPLES.md +62 -0
  165. package/integrations/openclaw/skills/recap/SKILL.md +68 -0
  166. package/integrations/openclaw/skills/recap/TROUBLESHOOTING.md +70 -0
  167. package/integrations/openclaw/skills/remember/EXAMPLES.md +67 -0
  168. package/integrations/openclaw/skills/remember/SKILL.md +66 -0
  169. package/integrations/openclaw/skills/remember/TROUBLESHOOTING.md +70 -0
  170. package/integrations/openclaw/skills/session-history/EXAMPLES.md +59 -0
  171. package/integrations/openclaw/skills/session-history/SKILL.md +67 -0
  172. package/integrations/openclaw/skills/session-history/TROUBLESHOOTING.md +70 -0
  173. package/integrations/openclaw/skills/write-agentmemory-skill/SKILL.md +41 -0
  174. package/integrations/openclaw/skills/write-agentmemory-skill/TROUBLESHOOTING.md +70 -0
  175. package/integrations/pi/LICENSE +190 -0
  176. package/integrations/pi/README.md +45 -51
  177. package/integrations/pi/dist/index.mjs +1379 -0
  178. package/integrations/pi/index.ts +138 -171
  179. package/integrations/pi/package.json +16 -6
  180. package/integrations/pi/security.ts +6 -26
  181. package/integrations/pi/skills/agentmemory-agents/REFERENCE.md +32 -0
  182. package/integrations/pi/skills/agentmemory-agents/SKILL.md +48 -0
  183. package/integrations/pi/skills/agentmemory-agents/TROUBLESHOOTING.md +70 -0
  184. package/integrations/pi/skills/agentmemory-architecture/SKILL.md +33 -0
  185. package/integrations/pi/skills/agentmemory-architecture/TROUBLESHOOTING.md +70 -0
  186. package/integrations/pi/skills/agentmemory-config/REFERENCE.md +90 -0
  187. package/integrations/pi/skills/agentmemory-config/SKILL.md +78 -0
  188. package/integrations/pi/skills/agentmemory-config/TROUBLESHOOTING.md +70 -0
  189. package/integrations/pi/skills/agentmemory-hooks/REFERENCE.md +20 -0
  190. package/integrations/pi/skills/agentmemory-hooks/SKILL.md +49 -0
  191. package/integrations/pi/skills/agentmemory-hooks/TROUBLESHOOTING.md +70 -0
  192. package/integrations/pi/skills/agentmemory-mcp-tools/REFERENCE.md +66 -0
  193. package/integrations/pi/skills/agentmemory-mcp-tools/SKILL.md +42 -0
  194. package/integrations/pi/skills/agentmemory-mcp-tools/TROUBLESHOOTING.md +70 -0
  195. package/integrations/pi/skills/agentmemory-rest-api/REFERENCE.md +158 -0
  196. package/integrations/pi/skills/agentmemory-rest-api/SKILL.md +49 -0
  197. package/integrations/pi/skills/agentmemory-rest-api/TROUBLESHOOTING.md +70 -0
  198. package/integrations/pi/skills/commit-context/EXAMPLES.md +71 -0
  199. package/integrations/pi/skills/commit-context/SKILL.md +64 -0
  200. package/integrations/pi/skills/commit-context/TROUBLESHOOTING.md +70 -0
  201. package/integrations/pi/skills/commit-history/EXAMPLES.md +71 -0
  202. package/integrations/pi/skills/commit-history/SKILL.md +62 -0
  203. package/integrations/pi/skills/commit-history/TROUBLESHOOTING.md +70 -0
  204. package/integrations/pi/skills/forget/EXAMPLES.md +40 -0
  205. package/integrations/pi/skills/forget/SKILL.md +73 -0
  206. package/integrations/pi/skills/forget/TROUBLESHOOTING.md +70 -0
  207. package/integrations/pi/skills/handoff/EXAMPLES.md +57 -0
  208. package/integrations/pi/skills/handoff/SKILL.md +75 -0
  209. package/integrations/pi/skills/handoff/TROUBLESHOOTING.md +70 -0
  210. package/integrations/pi/skills/lesson/SKILL.md +64 -0
  211. package/integrations/pi/skills/lesson/TROUBLESHOOTING.md +70 -0
  212. package/integrations/pi/skills/memory-discipline/SKILL.md +65 -0
  213. package/integrations/pi/skills/memory-discipline/TROUBLESHOOTING.md +70 -0
  214. package/integrations/pi/skills/recall/EXAMPLES.md +74 -0
  215. package/integrations/pi/skills/recall/SKILL.md +74 -0
  216. package/integrations/pi/skills/recall/TROUBLESHOOTING.md +70 -0
  217. package/integrations/pi/skills/recap/EXAMPLES.md +62 -0
  218. package/integrations/pi/skills/recap/SKILL.md +68 -0
  219. package/integrations/pi/skills/recap/TROUBLESHOOTING.md +70 -0
  220. package/integrations/pi/skills/remember/EXAMPLES.md +67 -0
  221. package/integrations/pi/skills/remember/SKILL.md +66 -0
  222. package/integrations/pi/skills/remember/TROUBLESHOOTING.md +70 -0
  223. package/integrations/pi/skills/session-history/EXAMPLES.md +59 -0
  224. package/integrations/pi/skills/session-history/SKILL.md +67 -0
  225. package/integrations/pi/skills/session-history/TROUBLESHOOTING.md +70 -0
  226. package/integrations/pi/skills/write-agentmemory-skill/SKILL.md +41 -0
  227. package/integrations/pi/skills/write-agentmemory-skill/TROUBLESHOOTING.md +70 -0
  228. package/package.json +32 -11
  229. package/plugin/.claude-plugin/plugin.json +1 -1
  230. package/plugin/.codex-plugin/plugin.json +4 -3
  231. package/plugin/.devin-plugin/plugin.json +5 -3
  232. package/plugin/cursor/hooks.json +23 -8
  233. package/plugin/hooks.json +67 -0
  234. package/plugin/opencode/README.md +1 -1
  235. package/plugin/opencode/agentmemory-capture.ts +25 -11
  236. package/plugin/opencode/plugin.json +1 -1
  237. package/plugin/plugin.json +1 -1
  238. package/plugin/scripts/_capture.d.mts +5 -2
  239. package/plugin/scripts/_capture.d.mts.map +1 -1
  240. package/plugin/scripts/_capture.mjs +55 -19
  241. package/plugin/scripts/_capture.mjs.map +1 -1
  242. package/plugin/scripts/cursor/run-detached.d.mts +1 -0
  243. package/plugin/scripts/cursor/run-detached.mjs +786 -0
  244. package/plugin/scripts/cursor/run-detached.mjs.map +1 -0
  245. package/plugin/scripts/cursor/run-hook.d.mts +1 -0
  246. package/plugin/scripts/cursor/run-hook.mjs +704 -0
  247. package/plugin/scripts/cursor/run-hook.mjs.map +1 -0
  248. package/plugin/scripts/notification.mjs +20 -6
  249. package/plugin/scripts/notification.mjs.map +1 -1
  250. package/plugin/scripts/plugin-bridge.mjs +37 -6
  251. package/plugin/scripts/post-commit.mjs +25 -5
  252. package/plugin/scripts/post-commit.mjs.map +1 -1
  253. package/plugin/scripts/post-tool-failure.mjs +12 -4
  254. package/plugin/scripts/post-tool-failure.mjs.map +1 -1
  255. package/plugin/scripts/post-tool-use.mjs +12 -4
  256. package/plugin/scripts/post-tool-use.mjs.map +1 -1
  257. package/plugin/scripts/pre-compact.mjs +37 -10
  258. package/plugin/scripts/pre-compact.mjs.map +1 -1
  259. package/plugin/scripts/pre-tool-use.mjs +25 -5
  260. package/plugin/scripts/pre-tool-use.mjs.map +1 -1
  261. package/plugin/scripts/prompt-submit.mjs +12 -4
  262. package/plugin/scripts/prompt-submit.mjs.map +1 -1
  263. package/plugin/scripts/session-end.mjs +47 -16
  264. package/plugin/scripts/session-end.mjs.map +1 -1
  265. package/plugin/scripts/session-start.mjs +37 -10
  266. package/plugin/scripts/session-start.mjs.map +1 -1
  267. package/plugin/scripts/stop.mjs +74 -72
  268. package/plugin/scripts/stop.mjs.map +1 -1
  269. package/plugin/scripts/subagent-start.mjs +13 -5
  270. package/plugin/scripts/subagent-start.mjs.map +1 -1
  271. package/plugin/scripts/subagent-stop.mjs +18 -6
  272. package/plugin/scripts/subagent-stop.mjs.map +1 -1
  273. package/plugin/scripts/task-completed.mjs +13 -5
  274. package/plugin/scripts/task-completed.mjs.map +1 -1
  275. package/plugin/skills/_shared/TROUBLESHOOTING.md +21 -7
  276. package/plugin/skills/agentmemory-agents/REFERENCE.md +7 -6
  277. package/plugin/skills/agentmemory-agents/SKILL.md +19 -5
  278. package/plugin/skills/agentmemory-agents/TROUBLESHOOTING.md +70 -0
  279. package/plugin/skills/agentmemory-architecture/SKILL.md +4 -4
  280. package/plugin/skills/agentmemory-architecture/TROUBLESHOOTING.md +70 -0
  281. package/plugin/skills/agentmemory-config/REFERENCE.md +12 -15
  282. package/plugin/skills/agentmemory-config/SKILL.md +7 -3
  283. package/plugin/skills/agentmemory-config/TROUBLESHOOTING.md +70 -0
  284. package/plugin/skills/agentmemory-hooks/SKILL.md +15 -5
  285. package/plugin/skills/agentmemory-hooks/TROUBLESHOOTING.md +70 -0
  286. package/plugin/skills/agentmemory-mcp-tools/REFERENCE.md +4 -4
  287. package/plugin/skills/agentmemory-mcp-tools/SKILL.md +6 -3
  288. package/plugin/skills/agentmemory-mcp-tools/TROUBLESHOOTING.md +70 -0
  289. package/plugin/skills/agentmemory-rest-api/REFERENCE.md +9 -1
  290. package/plugin/skills/agentmemory-rest-api/SKILL.md +12 -6
  291. package/plugin/skills/agentmemory-rest-api/TROUBLESHOOTING.md +70 -0
  292. package/plugin/skills/commit-context/SKILL.md +1 -1
  293. package/plugin/skills/commit-context/TROUBLESHOOTING.md +70 -0
  294. package/plugin/skills/commit-history/SKILL.md +1 -1
  295. package/plugin/skills/commit-history/TROUBLESHOOTING.md +70 -0
  296. package/plugin/skills/forget/EXAMPLES.md +19 -54
  297. package/plugin/skills/forget/SKILL.md +16 -12
  298. package/plugin/skills/forget/TROUBLESHOOTING.md +70 -0
  299. package/plugin/skills/handoff/EXAMPLES.md +5 -4
  300. package/plugin/skills/handoff/SKILL.md +10 -5
  301. package/plugin/skills/handoff/TROUBLESHOOTING.md +70 -0
  302. package/plugin/skills/lesson/SKILL.md +1 -1
  303. package/plugin/skills/lesson/TROUBLESHOOTING.md +70 -0
  304. package/plugin/skills/memory-discipline/SKILL.md +1 -1
  305. package/plugin/skills/memory-discipline/TROUBLESHOOTING.md +70 -0
  306. package/plugin/skills/recall/SKILL.md +18 -7
  307. package/plugin/skills/recall/TROUBLESHOOTING.md +70 -0
  308. package/plugin/skills/recap/EXAMPLES.md +5 -3
  309. package/plugin/skills/recap/SKILL.md +11 -6
  310. package/plugin/skills/recap/TROUBLESHOOTING.md +70 -0
  311. package/plugin/skills/remember/EXAMPLES.md +3 -3
  312. package/plugin/skills/remember/SKILL.md +1 -1
  313. package/plugin/skills/remember/TROUBLESHOOTING.md +70 -0
  314. package/plugin/skills/session-history/EXAMPLES.md +2 -2
  315. package/plugin/skills/session-history/SKILL.md +10 -4
  316. package/plugin/skills/session-history/TROUBLESHOOTING.md +70 -0
  317. package/plugin/skills/write-agentmemory-skill/SKILL.md +2 -1
  318. package/plugin/skills/write-agentmemory-skill/TROUBLESHOOTING.md +70 -0
  319. package/dist/connect-B4_ca6BD.mjs.map +0 -1
  320. package/dist/docker-compose.yml +0 -73
  321. package/dist/iii-config.docker.yaml +0 -53
  322. package/dist/iii-config.yaml +0 -63
  323. package/dist/keyed-mutex-DchXsyfP.mjs.map +0 -1
  324. package/dist/secret-store-BnY3A50C.mjs.map +0 -1
  325. package/dist/src-Jsq9LCeH.mjs.map +0 -1
  326. package/dist/standalone-DKCdrf1d.mjs.map +0 -1
  327. package/dist/status-IRz7ta8-.mjs +0 -2344
  328. package/dist/status-IRz7ta8-.mjs.map +0 -1
  329. package/docker-compose.yml +0 -73
  330. package/iii-config.docker.yaml +0 -53
  331. package/iii-config.yaml +0 -63
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-store-D9GwO0xp.mjs","names":[],"sources":["../src/config.ts","../src/cli/engine-launch.ts","../src/cli/engine-config.ts","../src/logger.ts","../src/version.ts","../src/mcp/tools-registry.ts","../src/functions/audit.ts","../src/state/search-layer.ts","../src/state/memory-utils.ts","../src/functions/recall-response.ts","../src/secret-store.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport pc from \"picocolors\";\nimport type {\n AgentMemoryConfig,\n ProviderConfig,\n EmbeddingConfig,\n FallbackConfig,\n ClaudeBridgeConfig,\n TeamConfig,\n} from \"./types.js\";\n\n// Import-side ceiling for observations in a single session (enforced by mem::import).\n// This is independent of MAX_OBS_PER_SESSION, which controls runtime writes.\nexport const MAX_IMPORT_OBS_PER_SESSION = 5_000;\n\nfunction safeParseInt(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const parsed = parseInt(value, 10);\n return Number.isNaN(parsed) ? fallback : parsed;\n}\n\nconst DATA_DIR = process.env[\"AGENTMEMORY_DATA_DIR\"] || join(homedir(), \".agentmemory\");\nconst ENV_FILE = process.env[\"AGENTMEMORY_ENV_FILE\"] || join(homedir(), \".agentmemory\", \".env\");\n\nlet warnPremiumModelShown = false;\nlet providerNoticeShown = false;\nlet obsCapImportCeilingWarned = false;\n\nfunction writeProviderNoticeOnce(text: string): void {\n if (providerNoticeShown) return;\n providerNoticeShown = true;\n process.stderr.write(text);\n}\n\n// Parsed ~/.agentmemory/.env, memoized for the process lifetime. getMergedEnv()\n// runs on every config getter (~20 of them), so without this cache a single\n// request would readFileSync + reparse the file dozens of times. The file is\n// boot-static, so read it from disk once and reuse the result. Tests that\n// mutate the file between cases reset the module (clearing this via reload) or\n// call __resetEnvFileCache().\nlet envFileCache: Record<string, string> | undefined;\n\nfunction loadEnvFile(): Record<string, string> {\n if (envFileCache) return envFileCache;\n if (!existsSync(ENV_FILE)) {\n envFileCache = {};\n return envFileCache;\n }\n envFileCache = parseEnvContent(readFileSync(ENV_FILE, \"utf-8\"));\n return envFileCache;\n}\n\nexport function parseEnvContent(content: string): Record<string, string> {\n const vars: Record<string, string> = {};\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx === -1) continue;\n const key = trimmed.slice(0, eqIdx).trim();\n let val = trimmed.slice(eqIdx + 1).trim();\n const quoteChar = val[0] === '\"' || val[0] === \"'\" ? val[0] : \"\";\n if (quoteChar) {\n const closeIdx = val.indexOf(quoteChar, 1);\n if (closeIdx !== -1) val = val.slice(1, closeIdx);\n } else {\n const hashIdx = val.indexOf(\" #\");\n if (hashIdx !== -1) val = val.slice(0, hashIdx).trim();\n }\n vars[key] = val;\n }\n return vars;\n}\n\n// Test hook: clears the memoized .env so the next loadEnvFile() re-reads disk\n// within the same module instance. vi.resetModules() reloads this module and\n// resets the cache on its own; this exists for tests that mutate the file\n// without a module reload.\nexport function __resetEnvFileCache(): void {\n envFileCache = undefined;\n}\n\nfunction hasRealValue(v: string | undefined): v is string {\n return typeof v === \"string\" && v.trim().length > 0;\n}\n\n// Hydrate ~/.agentmemory/.env into process.env at boot. loadEnvFile() is\n// otherwise only consumed via getMergedEnv(), which the many modules that\n// read raw process.env[\"X\"] never call — so .env-only values were silently\n// ignored by them. Copy the file's vars into process.env, but only when the\n// key is currently unset so a real process.env value still wins (this\n// preserves the {...fileEnv, ...process.env} precedence getMergedEnv uses).\nexport function hydrateProcessEnvFromFile(): Record<string, string | undefined> {\n const beforeHydration = { ...process.env };\n for (const [k, v] of Object.entries(loadEnvFile())) {\n if (process.env[k] === undefined) process.env[k] = v;\n }\n return beforeHydration;\n}\n\n// Warn once when a configured model is in the premium tier and likely to burn\n// money on background compression. Captured workload data shows ~$5/35h on\n// claude-sonnet-4 vs ~$0.46/35h on deepseek-v4-pro for the same compression\n// mix. Heuristic match avoids hard-coding a pricing table.\nfunction warnIfPremiumModel(env: Record<string, string>, envName: string, model: string): void {\n if (\n warnPremiumModelShown ||\n !/sonnet|opus|gpt-5\\.\\d+-sol|gpt-4o(?!.*mini)|gpt-4-turbo/i.test(model) ||\n env[\"AGENTMEMORY_SUPPRESS_COST_WARNING\"] === \"1\" ||\n env[\"AGENTMEMORY_SUPPRESS_COST_WARNING\"] === \"true\"\n ) {\n return;\n }\n warnPremiumModelShown = true;\n process.stderr.write(\n `[agentmemory] ${envName}=${model} is in the premium tier. ` +\n `Background compression on this model can cost $5+/day under active use. ` +\n `Cheaper alternatives with comparable quality for memory compression: ` +\n `deepseek/deepseek-v4-flash-0731, deepseek/deepseek-v4-pro, qwen/qwen3-coder. ` +\n `See README \"Cost-aware model selection\" for the full table. ` +\n `Set AGENTMEMORY_SUPPRESS_COST_WARNING=1 to silence.\\n`,\n );\n}\n\nfunction detectProvider(env: Record<string, string>): ProviderConfig {\n const maxTokens = parseInt(env[\"MAX_TOKENS\"] || \"4096\", 10);\n\n // OpenAI-compatible: supports OpenAI, DeepSeek, SiliconFlow, Azure, vLLM, LM Studio\n if (hasRealValue(env[\"OPENAI_API_KEY\"]) && env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\") {\n const model = env[\"OPENAI_MODEL\"] || \"gpt-5.6-luna\";\n warnIfPremiumModel(env, \"OPENAI_MODEL\", model);\n return {\n provider: \"openai\",\n model,\n maxTokens,\n baseURL: env[\"OPENAI_BASE_URL\"],\n };\n }\n\n // MiniMax: Anthropic-compatible API, requires raw fetch to avoid SDK stainless headers\n if (hasRealValue(env[\"MINIMAX_API_KEY\"])) {\n return {\n provider: \"minimax\",\n model: env[\"MINIMAX_MODEL\"] || \"MiniMax-M3\",\n maxTokens,\n };\n }\n\n if (hasRealValue(env[\"ANTHROPIC_API_KEY\"])) {\n return {\n provider: \"anthropic\",\n model: env[\"ANTHROPIC_MODEL\"] || \"claude-sonnet-5\",\n maxTokens,\n baseURL: env[\"ANTHROPIC_BASE_URL\"],\n };\n }\n if (hasRealValue(env[\"GEMINI_API_KEY\"]) || hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n if (!hasRealValue(env[\"GEMINI_API_KEY\"]) && hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n process.stderr.write(\n \"[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. \" +\n \"Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\\n\",\n );\n }\n return {\n provider: \"gemini\",\n model: env[\"GEMINI_MODEL\"] || \"gemini-3.7-flash\",\n maxTokens,\n };\n }\n if (hasRealValue(env[\"OPENROUTER_API_KEY\"])) {\n const model = env[\"OPENROUTER_MODEL\"] || \"anthropic/claude-sonnet-5\";\n warnIfPremiumModel(env, \"OPENROUTER_MODEL\", model);\n return {\n provider: \"openrouter\",\n model,\n maxTokens,\n };\n }\n\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n if (!allowAgentSdk) {\n writeProviderNoticeOnce(\n pc.dim(\n \"[agentmemory] No LLM provider key set — running zero-LLM: no LLM compression or summaries; search uses BM25 plus any configured embedding provider. \" +\n \"Set EMBEDDING_PROVIDER=local for on-device semantic embeddings if none is configured. \" +\n \"Set ANTHROPIC_API_KEY (or GEMINI/OPENAI/OPENROUTER/MINIMAX) in ~/.agentmemory/.env for LLM compression and summaries. \" +\n \"Agent-SDK fallback stays off by default to avoid a Stop-hook recursion loop; opt in with AGENTMEMORY_AUTO_COMPRESS=true + AGENTMEMORY_ALLOW_AGENT_SDK=true.\\n\",\n ),\n );\n return {\n provider: \"noop\",\n model: \"noop\",\n maxTokens,\n };\n }\n\n writeProviderNoticeOnce(\n \"[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. \" +\n \"This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook \" +\n \"recursion loop. A SDK-child env marker is set to block re-entry, \" +\n \"but prefer setting a real API key in ~/.agentmemory/.env instead.\\n\",\n );\n return {\n provider: \"agent-sdk\",\n model: \"claude-sonnet-5\",\n maxTokens,\n };\n}\n\nexport function loadConfig(): AgentMemoryConfig {\n const env = getMergedEnv();\n\n const provider = detectProvider(env);\n\n // REST is the anchor; viewer and engine ports derive from it unless individually overridden.\n const restPort = parseInt(env[\"III_REST_PORT\"] || \"3111\", 10) || 3111;\n const viewerPort =\n parseInt(env[\"III_VIEWER_PORT\"] || \"\", 10) || restPort + 2;\n const engineUrl =\n env[\"III_ENGINE_URL\"] ||\n env[\"III_URL\"] ||\n `ws://localhost:${\n parseInt(env[\"III_ENGINE_PORT\"] || \"\", 10) || restPort + 46023\n }`;\n\n const maxObservationsPerSession = safeParseInt(env[\"MAX_OBS_PER_SESSION\"], 500);\n if (\n !obsCapImportCeilingWarned &&\n (maxObservationsPerSession === 0 || maxObservationsPerSession > MAX_IMPORT_OBS_PER_SESSION)\n ) {\n obsCapImportCeilingWarned = true;\n const capDesc = maxObservationsPerSession === 0 ? \"uncapped (0)\" : String(maxObservationsPerSession);\n process.stderr.write(\n `[agentmemory] WARNING: MAX_OBS_PER_SESSION is ${capDesc}, above the ` +\n `${MAX_IMPORT_OBS_PER_SESSION}-per-session import ceiling (MAX_IMPORT_OBS_PER_SESSION). ` +\n `Sessions past that ceiling make every mem::export -> mem::import restore fail wholesale. ` +\n `Keep MAX_OBS_PER_SESSION at or below ${MAX_IMPORT_OBS_PER_SESSION} if you rely on export/import backups.\\n`,\n );\n }\n\n return {\n engineUrl,\n restPort,\n viewerPort,\n provider,\n tokenBudget: safeParseInt(env[\"TOKEN_BUDGET\"], 2000),\n maxObservationsPerSession,\n compressionModel: provider.model,\n dataDir: DATA_DIR,\n };\n}\n\nfunction getMergedEnv(\n overrides?: Record<string, string>,\n): Record<string, string> {\n const fileEnv = loadEnvFile();\n return { ...fileEnv, ...process.env, ...overrides } as Record<string, string>;\n}\n\nexport function getEnvVar(key: string): string | undefined {\n return getMergedEnv()[key];\n}\n\nexport function isSessionSweepEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_SESSION_SWEEP_ENABLED\"] !== \"false\";\n}\n\nexport function getSessionSweepStaleHours(): number {\n const raw = getMergedEnv()[\"AGENTMEMORY_SESSION_SWEEP_STALE_HOURS\"];\n if (!raw || !/^\\d+$/.test(raw.trim())) return 24;\n const parsed = parseInt(raw.trim(), 10);\n return parsed > 0 ? parsed : 24;\n}\n\nexport function getFinalizeIdleMs(): number {\n const raw = getMergedEnv()[\"AGENTMEMORY_FINALIZE_IDLE_MS\"];\n if (!raw || !/^\\d+$/.test(raw.trim())) return 120000;\n return parseInt(raw.trim(), 10);\n}\n\nexport function isGraphCompactOnBootEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_GRAPH_COMPACT_ON_BOOT\"] !== \"false\";\n}\n\nexport function isDropStaleIndexEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_DROP_STALE_INDEX\"] === \"true\";\n}\n\nconst VALID_STATE_BACKENDS = new Set([\"file\", \"redis\"]);\n\nexport function getStateBackend(): \"file\" | \"redis\" {\n const raw = (getMergedEnv()[\"AGENTMEMORY_STATE_BACKEND\"] || \"\")\n .trim()\n .toLowerCase();\n if (!raw) return \"file\";\n if (!VALID_STATE_BACKENDS.has(raw)) {\n throw new Error(\n `AGENTMEMORY_STATE_BACKEND=\"${raw}\" is not a recognized state backend. Use \"file\" (the default) or \"redis\", or unset it to keep the default file store.`,\n );\n }\n return raw as \"file\" | \"redis\";\n}\n\nexport function getRedisUrl(): string | undefined {\n const value = getMergedEnv()[\"AGENTMEMORY_REDIS_URL\"];\n return hasRealValue(value) ? value.trim() : undefined;\n}\n\nexport function getAuditRetentionMonths(): number {\n return safeParseInt(getMergedEnv()[\"AGENTMEMORY_AUDIT_RETENTION_MONTHS\"], 0);\n}\n\nexport function getAuditMigrateMaxBytes(): number {\n return safeParseInt(\n getMergedEnv()[\"AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES\"],\n 32 * 1024 * 1024,\n );\n}\n\nexport function detectLlmProviderKind(\n env: Record<string, string | undefined> = getMergedEnv(),\n): \"llm\" | \"noop\" {\n if (\n hasRealValue(env[\"ANTHROPIC_API_KEY\"]) ||\n hasRealValue(env[\"GEMINI_API_KEY\"]) ||\n hasRealValue(env[\"GOOGLE_API_KEY\"]) ||\n hasRealValue(env[\"OPENROUTER_API_KEY\"]) ||\n hasRealValue(env[\"MINIMAX_API_KEY\"]) ||\n (hasRealValue(env[\"OPENAI_API_KEY\"]) &&\n env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\") ||\n env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\"\n ) {\n return \"llm\";\n }\n return \"noop\";\n}\n\nexport function describeLlmRoute(provider: ProviderConfig): string | null {\n if (provider.provider === \"noop\") return null;\n const parts = [provider.provider, provider.model];\n if (provider.baseURL) {\n try {\n parts.push(new URL(provider.baseURL).host);\n } catch {\n parts.push(\"custom base URL\");\n }\n }\n return parts.join(\" · \");\n}\n\nexport function loadEmbeddingConfig(): EmbeddingConfig {\n const env = getMergedEnv();\n let bm25Weight = parseFloat(env[\"BM25_WEIGHT\"] || \"0.4\");\n let vectorWeight = parseFloat(env[\"VECTOR_WEIGHT\"] || \"0.6\");\n bm25Weight =\n isNaN(bm25Weight) || bm25Weight < 0 ? 0.4 : Math.min(bm25Weight, 1);\n vectorWeight =\n isNaN(vectorWeight) || vectorWeight < 0 ? 0.6 : Math.min(vectorWeight, 1);\n return {\n provider: env[\"EMBEDDING_PROVIDER\"] || undefined,\n bm25Weight,\n vectorWeight,\n };\n}\n\nexport function detectEmbeddingProvider(\n env?: Record<string, string>,\n): string | null {\n const source = env ?? getMergedEnv();\n const forced = source[\"EMBEDDING_PROVIDER\"];\n if (forced) return forced;\n\n if (source[\"GEMINI_API_KEY\"]) return \"gemini\";\n if (source[\"OPENAI_API_KEY\"] || source[\"OPENAI_EMBEDDING_API_KEY\"]) return \"openai\";\n if (source[\"VOYAGE_API_KEY\"]) return \"voyage\";\n if (source[\"COHERE_API_KEY\"]) return \"cohere\";\n if (source[\"OPENROUTER_API_KEY\"]) return \"openrouter\";\n return null;\n}\n\nexport function loadClaudeBridgeConfig(): ClaudeBridgeConfig {\n const env = getMergedEnv();\n const enabled = env[\"CLAUDE_MEMORY_BRIDGE\"] === \"true\";\n const projectPath = env[\"CLAUDE_PROJECT_PATH\"] || \"\";\n const lineBudget = safeParseInt(env[\"CLAUDE_MEMORY_LINE_BUDGET\"], 200);\n let memoryFilePath = \"\";\n if (enabled && projectPath) {\n // Claude Code stores project memory at\n // ~/.claude/projects/<slug>/memory/MEMORY.md\n // where <slug> is the project path with `/` and `\\` swapped for `-`.\n // The leading `-` from an absolute POSIX path is preserved (Claude\n // Code keeps it; stripping it produced a slug Claude never reads).\n // The `memory/` subdirectory holds MEMORY.md (the index) plus one\n // per-topic `.md` file per memory (verified against Claude Code 2.x).\n const safePath = projectPath.replace(/[/\\\\]/g, \"-\");\n memoryFilePath = join(\n homedir(),\n \".claude\",\n \"projects\",\n safePath,\n \"memory\",\n \"MEMORY.md\",\n );\n }\n return { enabled, projectPath, memoryFilePath, lineBudget };\n}\n\nexport function loadTeamConfig(): TeamConfig | null {\n const env = getMergedEnv();\n const teamId = env[\"TEAM_ID\"];\n const userId = env[\"USER_ID\"];\n if (!teamId || !userId) return null;\n const mode = env[\"TEAM_MODE\"] === \"shared\" ? \"shared\" : \"private\";\n return { teamId, userId, mode };\n}\n\n// optional AGENT_ID env for multi-agent memory isolation.\n// Returns null when unset so memory stays unscoped (legacy behavior).\n// Trimmed + length-capped to keep KV writes well-formed.\n//\n// Filtering is gated by AGENTMEMORY_AGENT_SCOPE:\n// \"shared\" (default) — tag everything, do not filter recall paths\n// \"isolated\" — tag everything AND filter recall paths\nexport function loadAgentScope(): {\n agentId: string;\n mode: \"shared\" | \"isolated\";\n} | null {\n const env = getMergedEnv();\n const raw = env[\"AGENT_ID\"];\n if (!raw) return null;\n const agentId = raw.trim().slice(0, 128);\n if (!agentId) return null;\n const mode = env[\"AGENTMEMORY_AGENT_SCOPE\"] === \"isolated\"\n ? \"isolated\"\n : \"shared\";\n return { agentId, mode };\n}\n\nexport function getAgentId(): string | undefined {\n return loadAgentScope()?.agentId;\n}\n\n// True only when AGENT_ID is set AND scope=isolated. Recall paths\n// consult this to decide whether to filter.\nexport function isAgentScopeIsolated(): boolean {\n return loadAgentScope()?.mode === \"isolated\";\n}\n\n// Floor for the git-snapshot timer. A zero/negative SNAPSHOT_INTERVAL would\n// make setInterval fire on roughly every event-loop tick, saturating the\n// worker with back-to-back full-state snapshots + git commits. Anything below\n// this floor is treated as a misconfiguration and falls back to the default.\nconst SNAPSHOT_INTERVAL_DEFAULT_SECONDS = 3600;\nconst MIN_SNAPSHOT_INTERVAL_SECONDS = 1;\n\nexport function loadSnapshotConfig(): {\n enabled: boolean;\n interval: number;\n dir: string;\n} {\n const env = getMergedEnv();\n const rawInterval = safeParseInt(\n env[\"SNAPSHOT_INTERVAL\"],\n SNAPSHOT_INTERVAL_DEFAULT_SECONDS,\n );\n const interval =\n rawInterval >= MIN_SNAPSHOT_INTERVAL_SECONDS\n ? rawInterval\n : SNAPSHOT_INTERVAL_DEFAULT_SECONDS;\n return {\n enabled: env[\"SNAPSHOT_ENABLED\"] === \"true\",\n interval,\n dir: env[\"SNAPSHOT_DIR\"] || join(homedir(), \".agentmemory\", \"snapshots\"),\n };\n}\n\nexport function isGraphExtractionEnabled(): boolean {\n return getMergedEnv()[\"GRAPH_EXTRACTION_ENABLED\"] === \"true\";\n}\n\nexport function getGraphBatchSize(): number {\n return safeParseInt(getMergedEnv()[\"GRAPH_EXTRACTION_BATCH_SIZE\"], 10);\n}\n\n// window for the smart-search followup-rate diagnostic. A second\n// search arriving within this many seconds (with disjoint results)\n// counts as a \"follow-up\" — a directional signal that the first result\n// set didn't satisfy. Long values overcount (legitimate refinement\n// looks like a follow-up); short values undercount.\nconst FOLLOWUP_WINDOW_DEFAULT_SECONDS = 30;\n\nexport function getFollowupWindowSeconds(): number {\n return safeParseInt(\n getMergedEnv()[\"AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS\"],\n FOLLOWUP_WINDOW_DEFAULT_SECONDS,\n );\n}\n\nexport function isConsolidationEnabled(): boolean {\n const env = getMergedEnv();\n const explicit = env[\"CONSOLIDATION_ENABLED\"];\n if (explicit === \"false\" || explicit === \"0\") return false;\n if (explicit === \"true\" || explicit === \"1\") return true;\n if ((env[\"AGENTMEMORY_PROVIDER\"] || \"\").toLowerCase() === \"noop\") return false;\n return detectLlmProviderKind(env) === \"llm\";\n}\n\n// Per-observation LLM compression is OFF by default as of 0.8.8.\n// When disabled, observations are captured and indexed via a synthetic\n// (zero-LLM) compression path so recall/search still works. Users who want\n// richer LLM-generated summaries can set AGENTMEMORY_AUTO_COMPRESS=true in\n// ~/.agentmemory/.env — but should expect their Claude API token usage to\n// climb proportionally with session tool-use frequency.\nexport function isAutoCompressEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_AUTO_COMPRESS\"] === \"true\";\n}\n\n// Hook-level context injection into Claude Code's conversation is OFF by\n// default as of 0.8.10. When disabled, pre-tool-use and\n// session-start hooks still POST observations for background capture, but\n// never write context to stdout — so Claude Code doesn't inject an extra\n// ~4000-char blob into every tool turn. 0.8.8 stopped the agentmemory-side\n// Claude calls (via ANTHROPIC_API_KEY); this stops the Claude Code-side\n// token burn where every tool call silently grew the model input window.\n// Users who want the in-conversation context injection explicitly opt in\n// with AGENTMEMORY_INJECT_CONTEXT=true and get a loud startup warning.\nexport function isContextInjectionEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_INJECT_CONTEXT\"] === \"true\";\n}\n\nexport const CONSOLIDATION_INTERVAL_DEFAULT_MS = 7200000;\n\nexport function getConsolidationIntervalMs(): number {\n const raw = parseInt(process.env.CONSOLIDATION_INTERVAL_MS || String(CONSOLIDATION_INTERVAL_DEFAULT_MS), 10);\n return Number.isFinite(raw) && raw > 0 ? raw : CONSOLIDATION_INTERVAL_DEFAULT_MS;\n}\n\nexport function getConsolidationDecayDays(): number {\n return safeParseInt(getMergedEnv()[\"CONSOLIDATION_DECAY_DAYS\"], 30);\n}\n\n// Cooldown between corpus consolidations triggered by session stop. The Stop\n// hook fires per agent turn and posts /session/end, so without this every turn\n// would kick a full LLM semantic-merge + reflect + crystallize. Debounced to at\n// most once per window. Set to 0 to disable the debounce (consolidate on every\n// stop). Default 5 minutes.\nconst CONSOLIDATION_COOLDOWN_DEFAULT_MS = 300000;\n\nexport function getConsolidationCooldownMs(): number {\n const raw = safeParseInt(\n getMergedEnv()[\"AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS\"],\n CONSOLIDATION_COOLDOWN_DEFAULT_MS,\n );\n return raw >= 0 ? raw : CONSOLIDATION_COOLDOWN_DEFAULT_MS;\n}\n\nexport const INDEX_SAVE_INTERVAL_DEFAULT_MS = 600_000;\n\nexport function getIndexSaveIntervalMs(): number {\n const raw = safeParseInt(\n getMergedEnv()[\"AGENTMEMORY_INDEX_SAVE_INTERVAL_MS\"],\n INDEX_SAVE_INTERVAL_DEFAULT_MS,\n );\n return raw > 0 ? raw : INDEX_SAVE_INTERVAL_DEFAULT_MS;\n}\n\nexport const STATE_SAVE_INTERVAL_DEFAULT_MS = 2000;\nexport const STATE_SAVE_INTERVAL_MIN_MS = 100;\nexport const STATE_SAVE_INTERVAL_MAX_MS = 3_600_000;\n\nexport function getStateSaveIntervalMs(): number {\n const value = getMergedEnv()[\"AGENTMEMORY_STATE_SAVE_INTERVAL_MS\"];\n if (value === undefined || value.trim() === \"\") return STATE_SAVE_INTERVAL_DEFAULT_MS;\n if (!/^\\d+$/.test(value.trim())) return STATE_SAVE_INTERVAL_DEFAULT_MS;\n const raw = Number(value);\n return Number.isSafeInteger(raw) && raw >= STATE_SAVE_INTERVAL_MIN_MS && raw <= STATE_SAVE_INTERVAL_MAX_MS\n ? raw\n : STATE_SAVE_INTERVAL_DEFAULT_MS;\n}\n\nexport const VECTOR_BUCKET_SIZE_DEFAULT = 500;\n\nexport function getVectorBucketSize(): number {\n const raw = safeParseInt(getMergedEnv()[\"AGENTMEMORY_VECTOR_BUCKET_SIZE\"], VECTOR_BUCKET_SIZE_DEFAULT);\n return raw > 0 ? raw : VECTOR_BUCKET_SIZE_DEFAULT;\n}\n\nexport const VECTOR_BACKFILL_MAX_DEFAULT = 500;\n\nexport function getVectorBackfillMax(): number {\n const raw = safeParseInt(getMergedEnv()[\"AGENTMEMORY_VECTOR_BACKFILL_MAX\"], VECTOR_BACKFILL_MAX_DEFAULT);\n return raw > 0 ? raw : VECTOR_BACKFILL_MAX_DEFAULT;\n}\n\nexport function isVectorBackfillAllEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_VECTOR_BACKFILL\"] === \"all\";\n}\n\nexport function isStandaloneMcp(): boolean {\n return getMergedEnv()[\"STANDALONE_MCP\"] === \"true\";\n}\n\nexport function getStandalonePersistPath(): string {\n const env = getMergedEnv();\n return (\n env[\"STANDALONE_PERSIST_PATH\"] ||\n join(homedir(), \".agentmemory\", \"standalone.json\")\n );\n}\n\nconst VALID_PROVIDERS = new Set([\n \"anthropic\",\n \"gemini\",\n \"openrouter\",\n \"agent-sdk\",\n \"minimax\",\n \"openai\",\n]);\n\nexport function loadFallbackConfig(): FallbackConfig {\n const env = getMergedEnv();\n const raw = env[\"FALLBACK_PROVIDERS\"] || \"\";\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n const providers = raw\n .split(\",\")\n .map((p) => p.trim())\n .filter(\n (p): p is FallbackConfig[\"providers\"][number] =>\n Boolean(p) && VALID_PROVIDERS.has(p),\n )\n .filter((p) => {\n // Honor the same safety gate as detectProvider: agent-sdk is only\n // permitted as a fallback target when the user has explicitly opted\n // in. Without this filter, a user could set FALLBACK_PROVIDERS=agent-sdk\n // and re-introduce the Stop-hook recursion loop even though\n // detectProvider() returned the noop provider.\n if (p === \"agent-sdk\" && !allowAgentSdk) {\n process.stderr.write(\n \"[agentmemory] Ignoring FALLBACK_PROVIDERS entry 'agent-sdk' \" +\n \"(AGENTMEMORY_ALLOW_AGENT_SDK is not 'true'). The agent-sdk \" +\n \"fallback can spawn Claude Agent SDK child sessions that trigger \" +\n \"the Stop-hook recursion loop. Opt in explicitly \" +\n \"with AGENTMEMORY_ALLOW_AGENT_SDK=true if this is intentional.\\n\",\n );\n return false;\n }\n return true;\n });\n return { providers };\n}\n","import { join } from \"node:path\";\n\nexport function runtimeConfigPath(dataDir: string): string {\n return join(dataDir, \"iii-config.runtime.yaml\");\n}\n\nconst CREDENTIAL_URL_PATTERN = /:\\/\\/[^@\\s/]*@/g;\n\nexport function redactCredentialUrls(text: string): string {\n return text.replace(CREDENTIAL_URL_PATTERN, \"://***@\");\n}\n","import { join } from \"node:path\";\n\nexport const ENGINE_DEFAULT_SAVE_INTERVAL_MS = 5000;\nexport const AGENTMEMORY_STATE_SAVE_INTERVAL_MS = 2000;\nexport const ENGINE_FLUSH_MARGIN_MS = 1500;\n\nexport function engineFlushWaitMs(\n stateBackend: \"file\" | \"redis\",\n configTexts: readonly string[],\n): number {\n if (stateBackend === \"redis\") return 0;\n return engineSaveIntervalMs(configTexts) + ENGINE_FLUSH_MARGIN_MS;\n}\n\nexport function captureDurableAfterMs(\n stateBackend: \"file\" | \"redis\",\n configTexts: readonly string[],\n): number {\n if (stateBackend === \"redis\") return ENGINE_FLUSH_MARGIN_MS;\n return engineSaveIntervalMs(configTexts) + ENGINE_FLUSH_MARGIN_MS;\n}\n\nexport function engineSaveIntervalMs(configTexts: readonly string[], env: NodeJS.ProcessEnv = process.env): number {\n const intervals: number[] = [];\n for (const text of configTexts) {\n const explicit: number[] = [];\n for (const match of text.matchAll(/save_interval_ms:\\s*[\"']?(\\d+|\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-(\\d+))?\\})/g)) {\n const raw = match[2] ? env[match[2]] || match[3] : match[1];\n if (raw && /^\\d+$/.test(raw) && Number.isSafeInteger(Number(raw))) explicit.push(Number(raw));\n }\n intervals.push(...explicit);\n const fileStores = text.match(/store_method:\\s*file_based/g)?.length ?? 0;\n if (fileStores > explicit.length) intervals.push(ENGINE_DEFAULT_SAVE_INTERVAL_MS);\n }\n return intervals.length > 0 ? Math.max(...intervals) : ENGINE_DEFAULT_SAVE_INTERVAL_MS;\n}\n\nexport function engineStateConfigPaths(engineCwd: string, runtimePath: string): string[] {\n return [...new Set([\n join(engineCwd, \"compose\", \"worker-compose.yaml\"),\n join(engineCwd, \"compose\", \"config\", \"state.yaml\"),\n join(engineCwd, \"worker-compose.runtime.yaml\"),\n join(engineCwd, \"config\", \"state.yaml\"),\n runtimePath,\n ])];\n}\n","type Fields = Record<string, unknown> | undefined;\n\nfunction fmt(level: string, msg: string, fields: Fields): string {\n if (!fields || Object.keys(fields).length === 0) {\n return `[agentmemory] ${level} ${msg}`;\n }\n try {\n return `[agentmemory] ${level} ${msg} ${JSON.stringify(fields)}`;\n } catch {\n // Fields contained a circular reference or a BigInt — fall back\n // to the plain message so a log line never throws.\n return `[agentmemory] ${level} ${msg}`;\n }\n}\n\nfunction emit(level: string, msg: string, fields: Fields): void {\n try {\n const line = fmt(level, msg, fields) + \"\\n\";\n if (level === \"error\" || process.env[\"AGENTMEMORY_MCP_STDIO__\"] === \"1\") {\n process.stderr.write(line);\n }\n else process.stdout.write(line);\n } catch {\n // stdout or stderr is unavailable in some test/worker contexts — swallow\n // so no log line can ever crash a handler.\n }\n}\n\nexport const logger = {\n info(msg: string, fields?: Fields): void {\n emit(\"info\", msg, fields);\n },\n warn(msg: string, fields?: Fields): void {\n emit(\"warn\", msg, fields);\n },\n error(msg: string, fields?: Fields): void {\n emit(\"error\", msg, fields);\n },\n};\n\n// ---------- boot log ----------\n//\n// `bootLog` is for the one-shot status lines that every register-*\n// function used to dump via `console.log` during engine startup. On a\n// fresh install that's ~25 lines of `[agentmemory] X enabled` noise\n// before the user can see a prompt. In quiet mode (default), each\n// line is captured into a buffer and discarded; the CLI surfaces a\n// single compressed summary instead. In verbose mode (set by\n// `--verbose` or `AGENTMEMORY_VERBOSE=1`) the lines pass straight\n// through to stderr exactly like the old console.log calls.\n\nlet bootVerbose =\n process.env[\"AGENTMEMORY_VERBOSE\"] === \"1\" ||\n process.env[\"AGENTMEMORY_VERBOSE\"] === \"true\";\n\nconst bootBuffer: string[] = [];\n\nexport function setBootVerbose(enabled: boolean): void {\n bootVerbose = enabled;\n}\n\nexport function isBootVerbose(): boolean {\n return bootVerbose;\n}\n\nexport function bootLog(msg: string): void {\n if (bootVerbose) {\n try {\n process.stderr.write(`[agentmemory] ${msg}\\n`);\n } catch {\n // stderr unavailable — drop.\n }\n return;\n }\n if (bootBuffer.length < 500) bootBuffer.push(msg);\n}\n\nexport function bootWarn(msg: string): void {\n // Warnings always surface; they're rare and the user needs to see\n // them even when the rest of the boot log is suppressed.\n try {\n process.stderr.write(`[agentmemory] warn ${msg}\\n`);\n } catch {}\n}\n\nexport function getBootBuffer(): readonly string[] {\n return bootBuffer;\n}\n","export const VERSION = \"0.9.31\";\nexport const III_PINNED_VERSION = \"0.25.0\";\n","export type McpToolDef = {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, { type: string; description: string; enum?: string[] }>;\n required?: string[];\n };\n};\n\nexport const CORE_TOOLS: McpToolDef[] = [\n {\n name: \"memory_recall\",\n description:\n \"Search stored memories and session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (keywords, file names, concepts)\",\n },\n limit: {\n type: \"number\",\n description: \"Max results to return (default 10)\",\n },\n format: {\n type: \"string\",\n description: \"Result format: full, compact, or narrative (default full)\",\n },\n token_budget: {\n type: \"number\",\n description: \"Optional estimated content token budget; response includes truncation and recovery metadata\",\n },\n targetLayer: {\n type: \"string\",\n enum: [\"all\", \"memory\", \"observation\"],\n description: \"Search all indexed layers (default), durable memories, or raw observations before ranking\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n cwd: { type: \"string\", description: \"Filter by session working directory\" },\n agentId: { type: \"string\", description: \"Filter by owning agent; '*' reads across agents\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_compress_file\",\n description:\n \"Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"Path to the markdown file to compress\",\n },\n },\n required: [\"filePath\"],\n },\n },\n {\n name: \"memory_save\",\n description:\n \"Explicitly save an important insight, decision, or pattern to long-term memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The insight or decision to remember\",\n },\n type: {\n type: \"string\",\n description:\n \"Memory type: pattern, preference, architecture, bug, workflow, or fact\",\n },\n concepts: {\n type: \"string\",\n description: \"Comma-separated key concepts\",\n },\n files: {\n type: \"string\",\n description: \"Comma-separated relevant file paths\",\n },\n project: {\n type: \"string\",\n description:\n \"Stable canonical project identifier this memory belongs to (e.g. a slug, \" +\n \"UUID, or registry key). Must match the value used when the session was \" +\n \"started. Do not use filesystem paths or ad-hoc display names — those \" +\n \"change across machines and will silently break project scoping.\",\n },\n agentId: {\n type: \"string\",\n description:\n \"Agent identity to scope this memory to. When set, agent-scoped recall \" +\n \"and search only surface it for the same agentId. Omit for shared memory.\",\n },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_file_history\",\n description: \"Get past observations about specific files.\",\n inputSchema: {\n type: \"object\",\n properties: {\n files: { type: \"string\", description: \"Comma-separated file paths\" },\n sessionId: {\n type: \"string\",\n description: \"Current session ID to exclude\",\n },\n },\n required: [\"files\"],\n },\n },\n {\n name: \"memory_patterns\",\n description: \"Detect recurring patterns across sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path to analyze\" },\n limit: {\n type: \"integer\",\n description:\n \"Most recent sessions to scan (default 50, max 500)\",\n },\n },\n },\n },\n {\n name: \"memory_sessions\",\n description:\n \"List recent sessions with status, observation counts, summaries and a continuation cursor. Filters apply before pagination; retain them when requesting the next page.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Exact project identifier used when sessions were started\" },\n agentId: { type: \"string\", description: \"Filter by owning agent; '*' reads across agents\" },\n limit: { type: \"integer\", description: \"Page size (default 20, max 100)\" },\n cursor: { type: \"string\", description: \"nextCursor from the previous page; omit for the first page\" },\n },\n },\n },\n {\n name: \"memory_smart_search\",\n description: \"Hybrid semantic+keyword search with progressive disclosure. Pass query to search, or expandIds to recover full results.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n expandIds: {\n type: \"string\",\n description: \"Comma-separated memory or observation IDs to expand; query is optional when provided\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n targetLayer: {\n type: \"string\",\n enum: [\"all\", \"memory\", \"observation\"],\n description: \"Search all indexed layers (default), durable memories, or raw observations before ranking\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n agentId: { type: \"string\", description: \"Filter by owning agent; '*' reads across agents\" },\n includeLessons: { type: \"boolean\", description: \"Include lesson matches when targetLayer is all (default true)\" },\n },\n },\n },\n {\n name: \"memory_vision_search\",\n description:\n \"Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true.\",\n inputSchema: {\n type: \"object\",\n properties: {\n queryText: { type: \"string\", description: \"Text query (e.g. 'login form with error banner')\" },\n queryImageRef: { type: \"string\", description: \"Absolute path to a stored image to match against\" },\n queryImageBase64: { type: \"string\", description: \"Raw base64 image bytes or data URL\" },\n topK: { type: \"number\", description: \"Max results (default 10, max 50)\" },\n sessionId: { type: \"string\", description: \"Filter to a single session\" },\n },\n },\n },\n {\n name: \"memory_timeline\",\n description: \"Chronological observations around an anchor point.\",\n inputSchema: {\n type: \"object\",\n properties: {\n anchor: {\n type: \"string\",\n description: \"Anchor point: ISO date or keyword\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n before: {\n type: \"number\",\n description: \"Observations before anchor (default 5)\",\n },\n after: {\n type: \"number\",\n description: \"Observations after anchor (default 5)\",\n },\n },\n required: [\"anchor\"],\n },\n },\n {\n name: \"memory_profile\",\n description: \"User/project profile with top concepts and file patterns.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path\" },\n refresh: {\n type: \"string\",\n description: \"Set to 'true' to force rebuild\",\n },\n },\n required: [\"project\"],\n },\n },\n {\n name: \"memory_export\",\n description:\n \"Export memory data as JSON. Past the transport size limit the export is refused, so use the paging arguments on a large store.\",\n inputSchema: {\n type: \"object\",\n properties: {\n maxSessions: {\n type: \"number\",\n description: \"Sessions per page (with their observations)\",\n },\n offset: { type: \"number\", description: \"Session offset\" },\n collectionLimit: {\n type: \"number\",\n description:\n \"Rows per page for memories, summaries, graphNodes, lessons and the other top-level collections; access logs follow the memories on the page. Sessions and their observations are paged only by maxSessions and offset, so pass collections to leave them out of each page\",\n },\n collectionOffset: {\n type: \"number\",\n description: \"Row offset for the top-level collections\",\n },\n collections: {\n type: \"string\",\n description:\n \"Comma-separated collections to return, e.g. memories,lessons. Sessions and their observations come back only when the list names sessions, access logs only together with memories. Unknown names are ignored. Omit for everything. A paged or selected export cannot be imported with strategy replace.\",\n },\n },\n },\n },\n {\n name: \"memory_relations\",\n description: \"Query the memory relationship graph.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: {\n type: \"string\",\n description: \"Memory ID to find relations for\",\n },\n maxHops: {\n type: \"number\",\n description: \"Max traversal depth (default 2)\",\n },\n minConfidence: {\n type: \"number\",\n description: \"Min confidence (0-1, default 0)\",\n },\n },\n required: [\"memoryId\"],\n },\n },\n {\n name: \"memory_commit_lookup\",\n description:\n \"Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sha: { type: \"string\", description: \"Full git commit SHA\" },\n },\n required: [\"sha\"],\n },\n },\n {\n name: \"memory_commits\",\n description:\n \"List recent commits linked to agent sessions, optionally filtered by branch or repo.\",\n inputSchema: {\n type: \"object\",\n properties: {\n branch: { type: \"string\", description: \"Filter by branch name\" },\n repo: { type: \"string\", description: \"Filter by remote URL\" },\n limit: { type: \"number\", description: \"Max results (default 100, max 500)\" },\n },\n },\n },\n];\n\nexport const V040_TOOLS: McpToolDef[] = [\n {\n name: \"memory_claude_bridge_sync\",\n description:\n \"Sync memory state to/from Claude Code's native MEMORY.md file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n description:\n \"'read' to import from MEMORY.md, 'write' to export to MEMORY.md\",\n },\n },\n required: [\"direction\"],\n },\n },\n {\n name: \"memory_graph_query\",\n description: \"Query the knowledge graph for entities and relationships.\",\n inputSchema: {\n type: \"object\",\n properties: {\n startNodeId: {\n type: \"string\",\n description: \"Starting node ID for traversal\",\n },\n nodeType: { type: \"string\", description: \"Filter by node type\" },\n maxDepth: {\n type: \"number\",\n description: \"Max BFS depth (default 3, max 5)\",\n },\n query: { type: \"string\", description: \"Search nodes by name\" },\n },\n },\n },\n {\n name: \"memory_consolidate\",\n description:\n \"Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tier: {\n type: \"string\",\n description: \"Target tier: episodic, semantic, or procedural\",\n },\n },\n },\n },\n {\n name: \"memory_team_share\",\n description: \"Share a memory or observation with team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n itemId: {\n type: \"string\",\n description: \"ID of memory or observation to share\",\n },\n itemType: {\n type: \"string\",\n description: \"Type: observation, memory, or pattern\",\n },\n },\n required: [\"itemId\", \"itemType\"],\n },\n },\n {\n name: \"memory_team_feed\",\n description: \"Get recent shared items from all team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"number\", description: \"Max items (default 20)\" },\n },\n },\n },\n {\n name: \"memory_audit\",\n description: \"View the audit trail of memory operations.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: { type: \"string\", description: \"Filter by operation type\" },\n limit: { type: \"number\", description: \"Max entries (default 50)\" },\n },\n },\n },\n {\n name: \"memory_governance_delete\",\n description: \"Delete specific memories with audit trail.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryIds: {\n type: \"string\",\n description: \"Comma-separated memory IDs to delete\",\n },\n reason: { type: \"string\", description: \"Reason for deletion\" },\n },\n required: [\"memoryIds\"],\n },\n },\n {\n name: \"memory_snapshot_create\",\n description: \"Create a git-versioned snapshot of current memory state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n message: { type: \"string\", description: \"Snapshot description\" },\n },\n },\n },\n];\n\nexport const V050_TOOLS: McpToolDef[] = [\n {\n name: \"memory_action_create\",\n description:\n \"Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Action title\" },\n description: {\n type: \"string\",\n description: \"Detailed description of the work\",\n },\n priority: {\n type: \"number\",\n description: \"Priority 1-10 (10 highest)\",\n },\n project: { type: \"string\", description: \"Project path\" },\n tags: {\n type: \"string\",\n description: \"Comma-separated tags\",\n },\n parentId: {\n type: \"string\",\n description: \"Parent action ID for hierarchical actions\",\n },\n requires: {\n type: \"string\",\n description:\n \"Comma-separated action IDs that must complete before this\",\n },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_action_update\",\n description:\n \"Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID to update\" },\n status: {\n type: \"string\",\n description: \"New status: pending, active, done, blocked, cancelled\",\n },\n result: {\n type: \"string\",\n description: \"Outcome description (when completing)\",\n },\n priority: { type: \"number\", description: \"New priority 1-10\" },\n },\n required: [\"actionId\"],\n },\n },\n {\n name: \"memory_frontier\",\n description:\n \"Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: {\n type: \"string\",\n description: \"Agent ID to check lease conflicts\",\n },\n limit: { type: \"number\", description: \"Max results (default 20)\" },\n },\n },\n },\n {\n name: \"memory_next\",\n description:\n \"Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: { type: \"string\", description: \"Current agent ID\" },\n },\n },\n },\n {\n name: \"memory_lease\",\n description:\n \"Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID\" },\n agentId: { type: \"string\", description: \"Agent claiming the action\" },\n operation: {\n type: \"string\",\n description: \"acquire, release, or renew\",\n },\n result: {\n type: \"string\",\n description: \"Result when releasing (marks action done)\",\n },\n ttlMs: {\n type: \"number\",\n description: \"Lease duration in ms (default 10min, max 1hr)\",\n },\n },\n required: [\"actionId\", \"agentId\", \"operation\"],\n },\n },\n {\n name: \"memory_routine_run\",\n description:\n \"Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n routineId: { type: \"string\", description: \"Routine template ID\" },\n project: { type: \"string\", description: \"Project context\" },\n initiatedBy: { type: \"string\", description: \"Agent starting the run\" },\n },\n required: [\"routineId\"],\n },\n },\n {\n name: \"memory_signal_send\",\n description:\n \"Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: { type: \"string\", description: \"Sender agent ID\" },\n to: {\n type: \"string\",\n description: \"Recipient agent ID (omit for broadcast)\",\n },\n content: { type: \"string\", description: \"Message content\" },\n type: {\n type: \"string\",\n description: \"Message type: info, request, response, alert, handoff\",\n },\n replyTo: {\n type: \"string\",\n description: \"Signal ID to reply to (auto-threads)\",\n },\n },\n required: [\"from\", \"content\"],\n },\n },\n {\n name: \"memory_signal_read\",\n description:\n \"Read messages for an agent. Marks delivered messages as read.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\", description: \"Agent to read messages for\" },\n unreadOnly: {\n type: \"string\",\n description: \"Set to 'true' for unread only\",\n },\n threadId: {\n type: \"string\",\n description: \"Filter by conversation thread\",\n },\n limit: { type: \"number\", description: \"Max messages (default 50)\" },\n },\n required: [\"agentId\"],\n },\n },\n {\n name: \"memory_checkpoint\",\n description:\n \"Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: {\n type: \"string\",\n description: \"create, resolve, or list\",\n },\n name: { type: \"string\", description: \"Checkpoint name (for create)\" },\n checkpointId: {\n type: \"string\",\n description: \"Checkpoint ID (for resolve)\",\n },\n status: {\n type: \"string\",\n description: \"passed or failed (for resolve)\",\n },\n type: {\n type: \"string\",\n description: \"Checkpoint type: ci, approval, deploy, external, timer\",\n },\n linkedActionIds: {\n type: \"string\",\n description:\n \"Comma-separated action IDs this checkpoint gates (for create)\",\n },\n },\n required: [\"operation\"],\n },\n },\n {\n name: \"memory_mesh_sync\",\n description:\n \"Sync memories and actions with peer agentmemory instances for multi-agent collaboration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n peerId: {\n type: \"string\",\n description: \"Specific peer ID (omit for all)\",\n },\n direction: {\n type: \"string\",\n description: \"push, pull, or both (default both)\",\n },\n },\n },\n },\n];\n\nexport const V051_TOOLS: McpToolDef[] = [\n {\n name: \"memory_sentinel_create\",\n description:\n \"Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Sentinel name\" },\n type: {\n type: \"string\",\n description: \"Type: webhook, timer, threshold, pattern, approval, custom\",\n },\n config: {\n type: \"string\",\n description: \"JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})\",\n },\n linkedActionIds: {\n type: \"string\",\n description: \"Comma-separated action IDs to gate\",\n },\n expiresInMs: { type: \"number\", description: \"Auto-expire after ms\" },\n },\n required: [\"name\", \"type\"],\n },\n },\n {\n name: \"memory_sentinel_trigger\",\n description:\n \"Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sentinelId: { type: \"string\", description: \"Sentinel ID to trigger\" },\n result: { type: \"string\", description: \"JSON result payload\" },\n },\n required: [\"sentinelId\"],\n },\n },\n {\n name: \"memory_sketch_create\",\n description:\n \"Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Sketch title\" },\n description: { type: \"string\", description: \"What this sketch explores\" },\n expiresInMs: { type: \"number\", description: \"TTL in ms (default 1 hour)\" },\n project: { type: \"string\", description: \"Project context\" },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_sketch_promote\",\n description:\n \"Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sketchId: { type: \"string\", description: \"Sketch ID to promote\" },\n project: { type: \"string\", description: \"Override project for promoted actions\" },\n },\n required: [\"sketchId\"],\n },\n },\n {\n name: \"memory_crystallize\",\n description:\n \"Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionIds: {\n type: \"string\",\n description: \"Comma-separated completed action IDs to crystallize\",\n },\n project: { type: \"string\", description: \"Project context\" },\n sessionId: { type: \"string\", description: \"Session context\" },\n },\n required: [\"actionIds\"],\n },\n },\n {\n name: \"memory_diagnose\",\n description:\n \"Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to check (default all)\",\n },\n },\n },\n },\n {\n name: \"memory_heal\",\n description:\n \"Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to heal (default all)\",\n },\n dryRun: {\n type: \"string\",\n description: \"Set to 'true' for dry run (report but don't fix)\",\n },\n },\n },\n },\n {\n name: \"memory_facet_tag\",\n description:\n \"Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: { type: \"string\", description: \"ID of the target to tag\" },\n targetType: {\n type: \"string\",\n description: \"Type: action, memory, or observation\",\n },\n dimension: { type: \"string\", description: \"Tag dimension (e.g., priority, team, status)\" },\n value: { type: \"string\", description: \"Tag value (e.g., urgent, backend, reviewed)\" },\n },\n required: [\"targetId\", \"targetType\", \"dimension\", \"value\"],\n },\n },\n {\n name: \"memory_facet_query\",\n description:\n \"Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.\",\n inputSchema: {\n type: \"object\",\n properties: {\n matchAll: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (AND logic)\",\n },\n matchAny: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (OR logic)\",\n },\n targetType: {\n type: \"string\",\n description: \"Filter by type: action, memory, or observation\",\n },\n },\n },\n },\n];\n\nexport const V061_TOOLS: McpToolDef[] = [\n {\n name: \"memory_verify\",\n description:\n \"Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Memory ID or observation ID to verify\",\n },\n },\n required: [\"id\"],\n },\n },\n];\n\nexport const V070_TOOLS: McpToolDef[] = [\n {\n name: \"memory_lesson_save\",\n description:\n \"Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The lesson learned (what worked, what to avoid, when to use X approach)\",\n },\n context: {\n type: \"string\",\n description: \"When/where this lesson applies\",\n },\n confidence: {\n type: \"number\",\n description: \"Initial confidence 0.0-1.0 (default 0.5)\",\n },\n project: { type: \"string\", description: \"Project this lesson is about\" },\n tags: { type: \"string\", description: \"Comma-separated tags\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_lesson_recall\",\n description:\n \"Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0.1)\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_lesson_delete\",\n description:\n \"Soft-delete a lesson by id. Deleted lessons are excluded from recall and list; re-saving the same content creates a fresh lesson.\",\n inputSchema: {\n type: \"object\",\n properties: {\n lessonId: { type: \"string\", description: \"The lesson id (lsn_...)\" },\n },\n required: [\"lessonId\"],\n },\n },\n {\n name: \"memory_obsidian_export\",\n description:\n \"Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n vaultDir: {\n type: \"string\",\n description: \"Output directory (default ~/.agentmemory/vault/)\",\n },\n types: {\n type: \"string\",\n description: \"Comma-separated types to export: memories,lessons,crystals,sessions (default all)\",\n },\n },\n },\n },\n];\n\nexport const V073_TOOLS: McpToolDef[] = [\n {\n name: \"memory_reflect\",\n description:\n \"Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n maxClusters: {\n type: \"number\",\n description: \"Max concept clusters to process (default 10, max 20)\",\n },\n },\n },\n },\n {\n name: \"memory_insight_list\",\n description:\n \"List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0)\",\n },\n limit: { type: \"number\", description: \"Max results (default 50)\" },\n },\n },\n },\n];\n\nexport const V010_SLOTS_TOOLS: McpToolDef[] = [\n {\n name: \"memory_slot_list\",\n description:\n \"List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_slot_get\",\n description: \"Read a single slot by label.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label (e.g. 'persona', 'pending_items')\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_create\",\n description: \"Create a new slot. Reject if a slot with the same label already exists.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label — lowercase, starts with letter, [a-z0-9_]\" },\n content: { type: \"string\", description: \"Initial content (default empty)\" },\n sizeLimit: { type: \"number\", description: \"Max chars (default 2000, hard cap 20000)\" },\n description: { type: \"string\", description: \"What this slot is for\" },\n pinned: { type: \"string\", description: \"'false' to exclude from context injection; default true\" },\n scope: { type: \"string\", description: \"'project' (default) or 'global' (shared across projects)\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_append\",\n description:\n \"Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n text: { type: \"string\", description: \"Text to append\" },\n },\n required: [\"label\", \"text\"],\n },\n },\n {\n name: \"memory_slot_replace\",\n description: \"Replace slot content in place. Fails if content exceeds sizeLimit.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n content: { type: \"string\", description: \"New full content\" },\n },\n required: [\"label\", \"content\"],\n },\n },\n {\n name: \"memory_slot_delete\",\n description: \"Delete a slot. Seeded default slots can be deleted unless marked readOnly.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n },\n required: [\"label\"],\n },\n },\n];\n\nexport const ESSENTIAL_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_consolidate\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_diagnose\",\n \"memory_lesson_save\",\n \"memory_reflect\",\n]);\n\nexport function getAllTools(): McpToolDef[] {\n return [\n ...CORE_TOOLS,\n ...V040_TOOLS,\n ...V050_TOOLS,\n ...V051_TOOLS,\n ...V061_TOOLS,\n ...V070_TOOLS,\n ...V073_TOOLS,\n ...V010_SLOTS_TOOLS,\n ];\n}\n\n// default switched from \"core\" (8 essential tools) to \"all\"\n// (full 54-tool surface). README and plugin manifests have always\n// advertised 54 tools \"in proxy mode\"; the old default left OpenCode /\n// Claude Code users seeing 8 with no indication the other tools existed.\n// Users who want the lean essentials can still set AGENTMEMORY_TOOLS=core.\nexport function getVisibleTools(): McpToolDef[] {\n const mode = process.env[\"AGENTMEMORY_TOOLS\"] || \"all\";\n if (mode === \"core\") return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));\n return getAllTools();\n}\n","import { stat, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AuditEntry, AuditMigrationState, AuditQueryResult } from \"../types.js\";\nimport { KV, generateId } from \"../state/schema.js\";\nimport type { StateKV } from \"../state/kv.js\";\nimport { logger } from \"../logger.js\";\nimport { withKeyedLock } from \"../state/keyed-mutex.js\";\nimport { getEnvVar, getAuditMigrateMaxBytes } from \"../config.js\";\nimport { runtimeConfigPath } from \"../cli/engine-launch.js\";\nimport { ENGINE_DEFAULT_SAVE_INTERVAL_MS, engineSaveIntervalMs, engineStateConfigPaths } from \"../cli/engine-config.js\";\n\nconst AUDIT_MIGRATE_FUNCTION_ID = \"mem::audit-migrate\";\nconst AUDIT_MIGRATION_COPY_CONCURRENCY = 32;\nconst AUDIT_MIGRATION_DELETE_CONCURRENCY = 8;\nconst AUDIT_MONTHS_LOCK = KV.auditMonths;\nconst AUDIT_MIGRATION_LOCK = \"mem:audit:migration-lock\";\nexport const AUDIT_MIGRATION_STATE_KEY = \"migration\";\nconst AUDIT_MIGRATION_DELETE_WAIT_INTERVALS = 2;\nconst STATE_STORE_DIR_NAME = \"state_store.db\";\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction encodeStateIndexSegment(index: string): string {\n let out = \"\";\n for (const byte of Buffer.from(index, \"utf8\")) {\n const ch = String.fromCharCode(byte);\n out += /^[A-Za-z0-9\\-_.]$/.test(ch)\n ? ch\n : `%${byte.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n return out;\n}\n\nfunction legacyAuditStateFilePath(dataDir: string): string {\n return join(dataDir, STATE_STORE_DIR_NAME, `${encodeStateIndexSegment(KV.audit)}.bin`);\n}\n\nexport type LegacyAuditProbe =\n | { safe: true; empty: true }\n | { safe: true; empty: false; sizeBytes: number }\n | { safe: false; reason: \"too-large\"; sizeBytes: number }\n | { safe: false; reason: \"unreadable\" };\n\nexport async function probeLegacyAuditFile(): Promise<LegacyAuditProbe> {\n const dataDir = getEnvVar(\"AGENTMEMORY_DATA_DIR\");\n if (!dataDir) return { safe: false, reason: \"unreadable\" };\n\n const storeDir = join(dataDir, STATE_STORE_DIR_NAME);\n try {\n await stat(storeDir);\n } catch {\n return { safe: false, reason: \"unreadable\" };\n }\n\n let fileStat;\n try {\n fileStat = await stat(legacyAuditStateFilePath(dataDir));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { safe: true, empty: true };\n }\n return { safe: false, reason: \"unreadable\" };\n }\n\n if (fileStat.size > getAuditMigrateMaxBytes()) {\n return { safe: false, reason: \"too-large\", sizeBytes: fileStat.size };\n }\n return { safe: true, empty: false, sizeBytes: fileStat.size };\n}\n\nexport async function probeLegacyAuditScope(kv: StateKV): Promise<LegacyAuditProbe> {\n let rows: AuditEntry[];\n try {\n rows = await kv.list<AuditEntry>(KV.audit);\n } catch {\n return { safe: false, reason: \"unreadable\" };\n }\n if (!Array.isArray(rows) || rows.length === 0) return { safe: true, empty: true };\n const sizeBytes = Buffer.byteLength(JSON.stringify(rows), \"utf8\");\n if (sizeBytes > getAuditMigrateMaxBytes()) {\n return { safe: false, reason: \"too-large\", sizeBytes };\n }\n return { safe: true, empty: false, sizeBytes };\n}\n\nasync function auditMigrationDeleteDelayMs(): Promise<number> {\n const dataDir = getEnvVar(\"AGENTMEMORY_DATA_DIR\");\n if (!dataDir) return ENGINE_DEFAULT_SAVE_INTERVAL_MS * AUDIT_MIGRATION_DELETE_WAIT_INTERVALS;\n const configTexts: string[] = [];\n for (const path of engineStateConfigPaths(dataDir, runtimeConfigPath(dataDir))) {\n try {\n configTexts.push(await readFile(path, \"utf-8\"));\n } catch {}\n }\n return engineSaveIntervalMs(configTexts) * AUDIT_MIGRATION_DELETE_WAIT_INTERVALS;\n}\n\nasync function readAuditMigrationState(kv: StateKV): Promise<AuditMigrationState | null> {\n return kv.get<AuditMigrationState>(KV.auditMonths, AUDIT_MIGRATION_STATE_KEY);\n}\n\nasync function writeAuditMigrationState(\n kv: StateKV,\n state: AuditMigrationState,\n): Promise<void> {\n await kv.set(KV.auditMonths, AUDIT_MIGRATION_STATE_KEY, state);\n}\n\nexport function auditMonthOf(timestamp: string): string {\n const parsed = new Date(timestamp);\n const iso = Number.isNaN(parsed.getTime())\n ? new Date().toISOString()\n : parsed.toISOString();\n return iso.slice(0, 7);\n}\n\nfunction monthStartMs(month: string): number {\n const [year, mon] = month.split(\"-\").map(Number);\n return Date.UTC(year, mon - 1, 1);\n}\n\nfunction monthEndMs(month: string): number {\n const [year, mon] = month.split(\"-\").map(Number);\n return Date.UTC(year, mon, 1) - 1;\n}\n\nfunction monthNMonthsAgo(count: number): string {\n const now = new Date();\n const cutoff = new Date(\n Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - count, 1),\n );\n return cutoff.toISOString().slice(0, 7);\n}\n\nasync function readAuditMonthIndex(kv: StateKV): Promise<string[]> {\n const index = await kv.get<{ months: string[] }>(KV.auditMonths, \"index\");\n return index?.months ?? [];\n}\n\nasync function markAuditMonth(kv: StateKV, month: string): Promise<void> {\n await withKeyedLock(AUDIT_MONTHS_LOCK, async () => {\n const months = await readAuditMonthIndex(kv);\n if (months.includes(month)) return;\n const next = [...months, month].sort();\n await kv.set(KV.auditMonths, \"index\", { months: next });\n });\n}\n\nexport async function listAuditMonthsDesc(kv: StateKV): Promise<string[]> {\n const months = await readAuditMonthIndex(kv);\n return [...months].sort().reverse();\n}\n\nlet auditRecordedListener: ((entry: AuditEntry) => void) | null = null;\n\nexport function setAuditRecordedListener(listener: ((entry: AuditEntry) => void) | null): void {\n auditRecordedListener = listener;\n}\n\nexport async function recordAudit(\n kv: StateKV,\n operation: AuditEntry[\"operation\"],\n functionId: string,\n targetIds: string[],\n details: Record<string, unknown> = {},\n qualityScore?: number,\n userId?: string,\n): Promise<AuditEntry> {\n const entry: AuditEntry = {\n id: generateId(\"aud\"),\n timestamp: new Date().toISOString(),\n operation,\n userId,\n functionId,\n targetIds,\n details,\n qualityScore,\n };\n const month = auditMonthOf(entry.timestamp);\n await kv.set(KV.auditMonth(month), entry.id, entry);\n await markAuditMonth(kv, month);\n try {\n auditRecordedListener?.(entry);\n } catch {}\n return entry;\n}\n\nexport async function safeAudit(\n kv: StateKV,\n operation: AuditEntry[\"operation\"],\n functionId: string,\n targetIds: string[],\n details: Record<string, unknown> = {},\n qualityScore?: number,\n userId?: string,\n): Promise<void> {\n try {\n await recordAudit(kv, operation, functionId, targetIds, details, qualityScore, userId);\n } catch (err) {\n try {\n logger.warn(\"audit write failed\", {\n functionId,\n operation,\n targetIds,\n error: err instanceof Error ? err.message : String(err),\n });\n } catch {}\n }\n}\n\nexport async function queryAudit(\n kv: StateKV,\n filter?: {\n operation?: AuditEntry[\"operation\"];\n dateFrom?: string;\n dateTo?: string;\n query?: string;\n limit?: number;\n },\n): Promise<AuditQueryResult> {\n const limit = filter?.limit || 100;\n\n let fromMs: number | undefined;\n if (filter?.dateFrom) {\n fromMs = new Date(filter.dateFrom).getTime();\n if (Number.isNaN(fromMs)) {\n throw new Error(`Invalid dateFrom: ${filter.dateFrom}`);\n }\n }\n const query = filter?.query?.trim().toLowerCase();\n\n let toMs: number | undefined;\n if (filter?.dateTo) {\n toMs = new Date(filter.dateTo).getTime();\n if (Number.isNaN(toMs)) {\n throw new Error(`Invalid dateTo: ${filter.dateTo}`);\n }\n }\n\n const matches = (entry: AuditEntry): boolean => {\n if (filter?.operation && entry.operation !== filter.operation) return false;\n const t = new Date(entry.timestamp).getTime();\n if (fromMs !== undefined && t < fromMs) return false;\n if (toMs !== undefined && t > toMs) return false;\n if (\n query &&\n ![entry.functionId, ...(entry.targetIds || [])].some((v) =>\n String(v || \"\").toLowerCase().includes(query),\n )\n ) {\n return false;\n }\n return true;\n };\n\n const seenIds = new Set<string>();\n const collected: AuditEntry[] = [];\n const addIfNew = (row: AuditEntry): void => {\n if (seenIds.has(row.id)) return;\n seenIds.add(row.id);\n if (matches(row)) collected.push(row);\n };\n\n const months = await listAuditMonthsDesc(kv);\n for (const month of months) {\n if (collected.length >= limit) break;\n if (toMs !== undefined && monthStartMs(month) > toMs) continue;\n if (fromMs !== undefined && monthEndMs(month) < fromMs) break;\n const rows = await kv.list<AuditEntry>(KV.auditMonth(month));\n for (const row of rows) addIfNew(row);\n }\n\n let legacyFrozen = false;\n let legacyFrozenBytes: number | undefined;\n\n if (collected.length < limit) {\n const migrationState = await readAuditMigrationState(kv);\n if (migrationState?.safeToListLegacy) {\n const legacyRows = await kv.list<AuditEntry>(KV.audit);\n for (const row of legacyRows) addIfNew(row);\n } else if (migrationState?.status === \"too-large\" || migrationState?.status === \"unreadable\") {\n legacyFrozen = true;\n legacyFrozenBytes = migrationState.legacySizeBytes;\n }\n }\n\n collected.sort(\n (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),\n );\n return {\n entries: collected.slice(0, limit),\n legacyFrozen,\n legacyFrozenBytes,\n };\n}\n\nasync function inParallel<T>(\n items: T[],\n concurrency: number,\n work: (item: T) => Promise<void>,\n): Promise<void> {\n let next = 0;\n const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next++];\n await work(item);\n }\n });\n await Promise.all(runners);\n}\n\nexport interface AuditMigrationDeps {\n probe?: () => Promise<LegacyAuditProbe>;\n deleteDelayMs?: () => Promise<number>;\n}\n\nexport async function startAuditMigration(\n kv: StateKV,\n deps: AuditMigrationDeps = {},\n): Promise<void> {\n const onRedis = kv.backend === \"redis\";\n const runProbe =\n deps.probe ?? (onRedis ? () => probeLegacyAuditScope(kv) : probeLegacyAuditFile);\n const runDeleteDelayMs =\n deps.deleteDelayMs ?? (onRedis ? async () => 0 : auditMigrationDeleteDelayMs);\n\n const marker = await readAuditMigrationState(kv);\n if (marker?.status === \"done\") return;\n\n const probe = await runProbe();\n\n if (probe.safe && probe.empty) {\n await writeAuditMigrationState(kv, {\n status: \"done\",\n safeToListLegacy: true,\n legacySizeBytes: 0,\n migrated: marker?.migrated ?? 0,\n purged: marker?.purged ?? 0,\n summaryWritten: marker?.summaryWritten ?? true,\n checkedAt: new Date().toISOString(),\n });\n return;\n }\n\n if (!probe.safe) {\n await writeAuditMigrationState(kv, {\n status: probe.reason,\n safeToListLegacy: false,\n legacySizeBytes: probe.reason === \"too-large\" ? probe.sizeBytes : marker?.legacySizeBytes,\n migrated: marker?.migrated ?? 0,\n purged: marker?.purged ?? 0,\n summaryWritten: marker?.summaryWritten ?? false,\n checkedAt: new Date().toISOString(),\n });\n logger.warn(\"legacy audit log left frozen; migration only reads it locally and under a size cap\", {\n reason: probe.reason,\n sizeBytes: probe.reason === \"too-large\" ? probe.sizeBytes : undefined,\n });\n return;\n }\n\n let migrated = marker?.migrated ?? 0;\n let purged = marker?.purged ?? 0;\n\n if (marker?.status !== \"copied\") {\n let legacy: AuditEntry[];\n try {\n legacy = await kv.list<AuditEntry>(KV.audit);\n } catch (err) {\n logger.warn(\"audit migration could not read the legacy audit log\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n if (legacy.length === 0) {\n await writeAuditMigrationState(kv, {\n status: \"done\",\n safeToListLegacy: true,\n legacySizeBytes: 0,\n migrated,\n purged,\n summaryWritten: marker?.summaryWritten ?? true,\n checkedAt: new Date().toISOString(),\n });\n return;\n }\n\n const seen = new Set<string>();\n const deduped = legacy.filter((entry) => {\n if (seen.has(entry.id)) return false;\n seen.add(entry.id);\n return true;\n });\n const kept = deduped.filter((entry) => entry.operation !== \"index_persist\");\n purged = deduped.length - kept.length;\n migrated = kept.length;\n\n try {\n const months = new Set<string>();\n await inParallel(kept, AUDIT_MIGRATION_COPY_CONCURRENCY, async (entry) => {\n const month = auditMonthOf(entry.timestamp);\n await kv.set(KV.auditMonth(month), entry.id, entry);\n months.add(month);\n });\n for (const month of months) await markAuditMonth(kv, month);\n } catch (err) {\n logger.warn(\n \"audit migration stopped before finishing the copy pass; it resumes on the next boot\",\n { error: err instanceof Error ? err.message : String(err) },\n );\n return;\n }\n\n await writeAuditMigrationState(kv, {\n status: \"copied\",\n safeToListLegacy: false,\n legacySizeBytes: probe.sizeBytes,\n migrated,\n purged,\n summaryWritten: false,\n checkedAt: new Date().toISOString(),\n });\n }\n\n await sleep(await runDeleteDelayMs());\n\n let remaining: AuditEntry[];\n try {\n remaining = await kv.list<AuditEntry>(KV.audit);\n } catch (err) {\n logger.warn(\n \"audit migration could not re-read the legacy audit log before deleting; it resumes on the next boot\",\n { error: err instanceof Error ? err.message : String(err) },\n );\n return;\n }\n\n try {\n await inParallel(\n remaining.slice().reverse(),\n AUDIT_MIGRATION_DELETE_CONCURRENCY,\n async (entry) => {\n await kv.delete(KV.audit, entry.id);\n },\n );\n } catch (err) {\n logger.warn(\n \"audit migration stopped before finishing the delete pass; it resumes on the next boot\",\n { error: err instanceof Error ? err.message : String(err) },\n );\n return;\n }\n\n await withKeyedLock(AUDIT_MIGRATION_LOCK, async () => {\n const current = await readAuditMigrationState(kv);\n if (current?.summaryWritten) return;\n if (purged > 0) {\n await safeAudit(kv, \"audit_migrate\", AUDIT_MIGRATE_FUNCTION_ID, [], {\n reason: \"index_persist rows predate opt-in auditing\",\n purged,\n migrated,\n });\n }\n await writeAuditMigrationState(kv, {\n status: \"done\",\n safeToListLegacy: true,\n legacySizeBytes: 0,\n migrated,\n purged,\n summaryWritten: true,\n checkedAt: new Date().toISOString(),\n });\n });\n\n logger.info(\"audit log moved to monthly scopes\", { migrated, purged });\n}\n\nexport async function runAuditRetentionSweep(\n kv: StateKV,\n retentionMonths: number,\n): Promise<{ droppedMonths: string[]; droppedRows: number }> {\n if (!Number.isFinite(retentionMonths) || retentionMonths <= 0) {\n return { droppedMonths: [], droppedRows: 0 };\n }\n\n const months = await readAuditMonthIndex(kv);\n const cutoff = monthNMonthsAgo(retentionMonths);\n const toDrop = months.filter((month) => month < cutoff).sort();\n if (toDrop.length === 0) {\n return { droppedMonths: [], droppedRows: 0 };\n }\n\n let droppedRows = 0;\n for (const month of toDrop) {\n const rows = await kv.list<AuditEntry>(KV.auditMonth(month));\n for (const row of rows.slice().reverse()) {\n await kv.delete(KV.auditMonth(month), row.id);\n droppedRows++;\n }\n }\n\n await withKeyedLock(AUDIT_MONTHS_LOCK, async () => {\n const current = await readAuditMonthIndex(kv);\n const remaining = current.filter((month) => !toDrop.includes(month)).sort();\n await kv.set(KV.auditMonths, \"index\", { months: remaining });\n });\n\n return { droppedMonths: toDrop, droppedRows };\n}\n","export type SearchLayer = \"all\" | \"memory\" | \"observation\";\nexport type SearchResultLayer = \"memory\" | \"observation\" | \"lesson\" | \"insight\";\nexport type SearchLayerResolver = (obsId: string, sessionId: string) => SearchResultLayer | undefined;\n\nexport function isSearchLayer(value: unknown): value is SearchLayer {\n return value === \"all\" || value === \"memory\" || value === \"observation\";\n}\n\nexport function isSearchResultLayer(value: unknown): value is SearchResultLayer {\n return value === \"memory\" || value === \"observation\" || value === \"lesson\" || value === \"insight\";\n}\n\nexport function getSearchResultLayer(obsId: string, sessionId: string): SearchResultLayer {\n if (obsId.startsWith(\"mem_\")) return \"memory\";\n if (sessionId === \"lesson\" || obsId.startsWith(\"lsn_\")) return \"lesson\";\n if (sessionId === \"insight\" || obsId.startsWith(\"ins_\")) return \"insight\";\n return \"observation\";\n}\n\nexport function matchesSearchLayer(\n obsId: string,\n sessionId: string,\n targetLayer: SearchLayer = \"all\",\n layer?: SearchResultLayer,\n): boolean {\n return targetLayer === \"all\" || (layer ?? getSearchResultLayer(obsId, sessionId)) === targetLayer;\n}\n","import type { CompressedObservation, Lesson, Memory } from \"../types.js\";\n\n// Wraps a Memory record in the CompressedObservation shape that\n// SearchIndex / VectorIndex / enrichment paths consume. Memories share\n// the same searchable fields as observations (title + content +\n// concepts + files); type is normalized to \"decision\" so memories stay\n// distinguishable in result metadata without colliding with observation\n// enums (file_read, command_run, …). The synthetic sessionId\n// (\"memory\" or memory.sessionIds[0]) is what enrich-side fallbacks key\n// off of when looking up the source record in KV.memories.\nexport function memoryToObservation(memory: Memory): CompressedObservation {\n return {\n id: memory.id,\n sessionId: memory.sessionIds?.[0] ?? \"memory\",\n timestamp: memory.createdAt,\n type: \"decision\",\n title: memory.title,\n facts: [memory.content],\n narrative: memory.content,\n concepts: memory.concepts,\n files: memory.files,\n importance: memory.strength,\n // Carry the owning agent through so agent-scoped search filters see\n // memories, not just raw observations. Dropping it made every memory\n // invisible to any agentId-scoped query.\n ...(memory.agentId ? { agentId: memory.agentId } : {}),\n };\n}\n\n// Same adapter for lessons, kept beside memoryToObservation so a new\n// CompressedObservation field has one obvious place to be threaded\n// through both record kinds.\nexport function lessonToObservation(l: Lesson): CompressedObservation {\n return {\n id: l.id,\n sessionId: \"lesson\",\n timestamp: l.createdAt,\n type: \"decision\",\n title: l.content.slice(0, 120),\n facts: [l.content],\n narrative: l.context || \"\",\n concepts: l.tags,\n files: [],\n importance: l.confidence,\n };\n}\n","import type { CompactSearchResult, SearchResult } from \"../types.js\";\n\nexport type RecallFormat = \"full\" | \"compact\" | \"narrative\";\n\ntype ClippedResult = { content_truncated?: true };\ntype FullResult = SearchResult & ClippedResult;\ntype CompactResult = CompactSearchResult & ClippedResult;\ntype NarrativeResult = Omit<CompactResult, \"type\"> & { narrative: string };\ntype RecallResult = FullResult | CompactResult | NarrativeResult;\n\ninterface RecallMetadata {\n tokens_used: number;\n tokens_budget?: number;\n truncated: boolean;\n matched_count: number;\n excluded_by_budget: number;\n excluded_results: Array<{ obsId: string; sessionId: string; title: string }>;\n excluded_results_truncated: boolean;\n minimum_budget?: number;\n}\n\nexport type RecallResponse = RecallMetadata & (\n | { format: \"full\"; results: FullResult[] }\n | { format: \"compact\"; results: CompactResult[] }\n | { format: \"narrative\"; results: NarrativeResult[]; text: string }\n);\n\nfunction estimateTokens(value: unknown): number {\n return Math.max(1, Math.ceil(JSON.stringify(value).length / 3));\n}\n\nfunction prefix(text: string, length: number): string {\n let end = Math.min(length, text.length);\n if (end > 0 && end < text.length && /[\\uD800-\\uDBFF]/.test(text[end - 1])) end--;\n return text.slice(0, end);\n}\n\nfunction fitText<T>(text: string, budget: number, makeResult: (text: string) => T): T {\n let low = 0;\n let high = text.length;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (estimateTokens(makeResult(prefix(text, middle))) <= budget) low = middle;\n else high = middle - 1;\n }\n return makeResult(prefix(text, low));\n}\n\nfunction formatResult(result: SearchResult, format: RecallFormat): RecallResult {\n if (format === \"full\") return result;\n const observation = result.observation;\n const compact: CompactResult = {\n obsId: observation.id,\n sessionId: result.sessionId,\n title: observation.title,\n type: observation.type,\n score: result.score,\n timestamp: observation.timestamp,\n ...(result.layer !== undefined && { layer: result.layer }),\n };\n if (format === \"compact\") return compact;\n const { type: _type, ...narrative } = compact;\n return { ...narrative, narrative: observation.narrative };\n}\n\nfunction clipResult(\n result: SearchResult,\n format: RecallFormat,\n budget: number,\n): { result?: RecallResult; minimum: number } {\n const observation = result.observation;\n const layer = result.layer !== undefined ? { layer: result.layer } : {};\n if (format === \"compact\") {\n const base: CompactResult = {\n obsId: observation.id,\n sessionId: result.sessionId,\n title: \"\",\n type: observation.type,\n score: result.score,\n timestamp: observation.timestamp,\n ...layer,\n content_truncated: true,\n };\n const minimum = estimateTokens(base);\n if (minimum > budget) return { minimum };\n return {\n result: fitText(observation.title, budget, (title) => ({ ...base, title })),\n minimum,\n };\n }\n\n const makeResult = (title: string, narrative: string): FullResult | NarrativeResult => {\n if (format === \"narrative\") {\n return {\n obsId: observation.id,\n sessionId: result.sessionId,\n title,\n narrative,\n score: result.score,\n timestamp: observation.timestamp,\n ...layer,\n content_truncated: true,\n };\n }\n return {\n observation: {\n id: observation.id,\n sessionId: observation.sessionId,\n timestamp: observation.timestamp,\n type: observation.type,\n title,\n facts: [],\n narrative,\n concepts: [],\n files: [],\n importance: observation.importance,\n ...(observation.confidence !== undefined && { confidence: observation.confidence }),\n ...(observation.agentId !== undefined && { agentId: observation.agentId }),\n ...(observation.origin && {\n origin: { channel: observation.origin.channel, capturedAt: observation.origin.capturedAt },\n }),\n },\n score: result.score,\n sessionId: result.sessionId,\n ...layer,\n content_truncated: true,\n };\n };\n const minimum = estimateTokens(makeResult(\"\", \"\"));\n if (minimum > budget) return { minimum };\n\n const titleResult = fitText(prefix(observation.title, 120), budget, (title) => makeResult(title, \"\"));\n const title = \"observation\" in titleResult ? titleResult.observation.title : titleResult.title;\n const narrative = observation.narrative || observation.facts.join(\"\\n\");\n return {\n result: fitText(narrative, budget, (text) => makeResult(title, text)),\n minimum,\n };\n}\n\nexport function buildRecallResponse(\n results: SearchResult[],\n format: RecallFormat,\n tokenBudget?: number,\n): RecallResponse {\n const selected: RecallResult[] = [];\n let used = 0;\n let clipped = false;\n let minimumBudget: number | undefined;\n for (const result of results) {\n const formatted = formatResult(result, format);\n const tokens = estimateTokens(formatted);\n if (tokenBudget === undefined || used + tokens <= tokenBudget) {\n selected.push(formatted);\n used += tokens;\n continue;\n }\n if (selected.length === 0) {\n const preview = clipResult(result, format, tokenBudget);\n if (preview.result) {\n selected.push(preview.result);\n used = estimateTokens(preview.result);\n clipped = true;\n continue;\n } else {\n minimumBudget = Math.min(preview.minimum, tokens);\n }\n }\n break;\n }\n\n const excluded = results.slice(selected.length);\n const metadata: RecallMetadata = {\n tokens_used: used,\n tokens_budget: tokenBudget,\n truncated: clipped || excluded.length > 0,\n matched_count: results.length,\n excluded_by_budget: excluded.length,\n excluded_results: excluded.slice(0, 10).map((result) => ({\n obsId: result.observation.id,\n sessionId: result.sessionId,\n title: prefix(result.observation.title, 120),\n })),\n excluded_results_truncated: excluded.length > 10,\n ...(minimumBudget !== undefined && { minimum_budget: minimumBudget }),\n };\n if (format === \"narrative\") {\n const narrativeResults = selected as NarrativeResult[];\n return {\n ...metadata,\n format,\n results: narrativeResults,\n text: narrativeResults.map((result, index) => `${index + 1}. ${result.title}\\n${result.narrative}`).join(\"\\n\\n\"),\n };\n }\n if (format === \"compact\") return { ...metadata, format, results: selected as CompactResult[] };\n return { ...metadata, format, results: selected as FullResult[] };\n}\n","import {\n chmodSync,\n closeSync,\n linkSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst SECRET_KEY = \"AGENTMEMORY_SECRET\";\n\nexport function agentmemoryHomeDir(): string {\n return process.env[\"AGENTMEMORY_DATA_DIR\"] || join(homedir(), \".agentmemory\");\n}\n\nexport function secretFilePath(): string {\n return join(agentmemoryHomeDir(), \"secret\");\n}\n\nfunction usable(value: string | undefined): string {\n if (typeof value !== \"string\") return \"\";\n const trimmed = value.trim();\n if (!trimmed) return \"\";\n if (trimmed.startsWith(\"${\") && trimmed.endsWith(\"}\")) return \"\";\n return trimmed;\n}\n\nfunction unquote(value: string): string {\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length > 1) {\n const close = value.indexOf(quote, 1);\n if (close !== -1) return value.slice(1, close);\n }\n const hash = value.indexOf(\" #\");\n return hash === -1 ? value : value.slice(0, hash).trim();\n}\n\nexport function readEnvFileSecret(): string {\n let content: unknown;\n try {\n content = readFileSync(process.env[\"AGENTMEMORY_ENV_FILE\"] || join(homedir(), \".agentmemory\", \".env\"), \"utf-8\");\n } catch {\n return \"\";\n }\n if (typeof content !== \"string\") return \"\";\n let found = \"\";\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).replace(/^export\\s+/, \"\").trim();\n if (key !== SECRET_KEY) continue;\n found = usable(unquote(trimmed.slice(eq + 1).trim()));\n }\n return found;\n}\n\nfunction readSecretFile(path: string): string {\n try {\n return usable(readFileSync(path, \"utf-8\"));\n } catch {\n return \"\";\n }\n}\n\nfunction legacyDataDirSecretPaths(env: NodeJS.ProcessEnv = process.env): string[] {\n const dataDir = env[\"AGENTMEMORY_DATA_DIR\"];\n if (!dataDir) return [];\n const paths = [join(dataDir, \"secret\"), join(dataDir, \".hmac\"), join(dataDir, \"..\", \".hmac\")];\n return [...new Set(paths.filter((path) => path !== secretFilePath()))];\n}\n\nexport function readStoredSecret(env: NodeJS.ProcessEnv = process.env): string {\n const canonicalPath = canonicalSecretPath();\n const localPath = secretFilePath();\n const legacyPaths = legacyDataDirSecretPaths(env);\n return readSecretFile(canonicalPath) ||\n (localPath === canonicalPath ? \"\" : readSecretFile(localPath)) ||\n legacyPaths.map(readSecretFile).find(Boolean) || \"\";\n}\n\nexport function explicitSecret(env: NodeJS.ProcessEnv = process.env): string {\n return usable(env[SECRET_KEY]) || readEnvFileSecret();\n}\n\nexport function isLoopbackUrl(url: string): boolean {\n let hostname: string;\n try {\n hostname = new URL(url).hostname.toLowerCase();\n } catch {\n return false;\n }\n const bare = hostname.replace(/^\\[|\\]$/g, \"\");\n return bare === \"localhost\" || bare === \"::1\" || /^127(?:\\.\\d{1,3}){3}$/.test(bare);\n}\n\nexport function resolveClientSecret(\n baseUrl: string,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n const fromEnv = usable(env[SECRET_KEY]);\n if (fromEnv) return fromEnv;\n if (env.AGENTMEMORY_CREDENTIAL_MODE === \"explicit\") return \"\";\n if (!isLoopbackUrl(baseUrl)) return \"\";\n return readEnvFileSecret() || readStoredSecret(env);\n}\n\nfunction canonicalSecretPath(): string {\n return join(homedir(), \".agentmemory\", \"secret\");\n}\n\nfunction writeSecretFile(path: string, secret: string): void {\n mkdirSync(join(path, \"..\"), { recursive: true, mode: 0o700 });\n const staging = `${path}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n const fd = openSync(staging, \"wx\", 0o600);\n try {\n writeSync(fd, `${secret}\\n`);\n } finally {\n closeSync(fd);\n }\n try {\n chmodSync(staging, 0o600);\n renameSync(staging, path);\n chmodSync(path, 0o600);\n } finally {\n try { unlinkSync(staging); } catch {}\n }\n}\n\nfunction writeSecretIfAbsent(path: string, secret: string): string {\n mkdirSync(join(path, \"..\"), { recursive: true, mode: 0o700 });\n const staging = `${path}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n const fd = openSync(staging, \"wx\", 0o600);\n try {\n writeSync(fd, `${secret}\\n`);\n } finally {\n closeSync(fd);\n }\n try {\n chmodSync(staging, 0o600);\n linkSync(staging, path);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n } finally {\n try { unlinkSync(staging); } catch {}\n }\n const stored = readSecretFile(path);\n if (!stored) throw new Error(`Could not read stored API secret at ${path}.`);\n return stored;\n}\n\nexport function ensureServerSecret(env: NodeJS.ProcessEnv = process.env): {\n secret: string;\n source: \"env\" | \"file\" | \"generated\";\n} {\n const configured = explicitSecret(env);\n if (configured) return { secret: configured, source: \"env\" };\n\n const localPath = secretFilePath();\n const canonicalPath = canonicalSecretPath();\n const canonical = localPath === canonicalPath ? \"\" : readSecretFile(canonicalPath);\n if (canonical) {\n if (localPath !== canonicalPath && readSecretFile(localPath) !== canonical) {\n writeSecretFile(localPath, canonical);\n }\n return { secret: canonical, source: \"file\" };\n }\n\n const legacy = readSecretFile(localPath) || legacyDataDirSecretPaths(env).map(readSecretFile).find(Boolean) || \"\";\n const candidate = legacy || randomBytes(32).toString(\"hex\");\n const localSecret = writeSecretIfAbsent(localPath, candidate);\n const secret = localPath === canonicalPath\n ? localSecret\n : writeSecretIfAbsent(canonicalPath, localSecret);\n if (localPath !== canonicalPath && localSecret !== secret) writeSecretFile(localPath, secret);\n return { secret, source: legacy ? \"file\" : \"generated\" };\n}\n\nexport function bearerHeaders(\n baseUrl: string,\n env: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const secret = resolveClientSecret(baseUrl, env);\n return secret ? { Authorization: `Bearer ${secret}` } : {};\n}\n"],"mappings":";;;;;;;;AAeA,MAAa,6BAA6B;AAE1C,SAAS,aAAa,OAA2B,UAA0B;AACzE,KAAI,CAAC,MAAO,QAAO;CACnB,MAAM,SAAS,SAAS,OAAO,GAAG;AAClC,QAAO,OAAO,MAAM,OAAO,GAAG,WAAW;;AAG3C,MAAM,WAAW,QAAQ,IAAI,2BAA2B,KAAK,SAAS,EAAE,eAAe;AACvF,MAAM,WAAW,QAAQ,IAAI,2BAA2B,KAAK,SAAS,EAAE,gBAAgB,OAAO;AAE/F,IAAI,wBAAwB;AAC5B,IAAI,sBAAsB;AAC1B,IAAI,4BAA4B;AAEhC,SAAS,wBAAwB,MAAoB;AACnD,KAAI,oBAAqB;AACzB,uBAAsB;AACtB,SAAQ,OAAO,MAAM,KAAK;;AAS5B,IAAI;AAEJ,SAAS,cAAsC;AAC7C,KAAI,aAAc,QAAO;AACzB,KAAI,CAAC,WAAW,SAAS,EAAE;AACzB,iBAAe,EAAE;AACjB,SAAO;;AAET,gBAAe,gBAAgB,aAAa,UAAU,QAAQ,CAAC;AAC/D,QAAO;;AAGT,SAAgB,gBAAgB,SAAyC;CACvE,MAAM,OAA+B,EAAE;AACvC,MAAK,MAAM,QAAQ,QAAQ,MAAM,KAAK,EAAE;EACtC,MAAM,UAAU,KAAK,MAA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;IAC5F;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,UAAU;IACR,MAAM;IACN,aAAa;IACd,EACF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,MAAM;KACJ,MAAM;KACN,aACE;KACH;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aACE;KAIH;IACD,SAAS;KACP,MAAM;KACN,aACE;KAEH;IACF;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAA8B;IACpE,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KAAE,MAAM;KAAU,aAAa;KAA2B;IACnE,OAAO;KACL,MAAM;KACN,aACE;KACH;IACF;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KAAE,MAAM;KAAU,aAAa;KAA4D;IACpG,SAAS;KAAE,MAAM;KAAU,aAAa;KAAmD;IAC3F,OAAO;KAAE,MAAM;KAAW,aAAa;KAAmC;IAC1E,QAAQ;KAAE,MAAM;KAAU,aAAa;KAA8D;IACtG;GACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAAgB;IACtD,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAA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ACF;GACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,KAAK;IAAE,MAAM;IAAU,aAAa;IAAuB,EAC5D;GACD,UAAU,CAAC,MAAM;GAClB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,QAAQ;KAAE,MAAM;KAAU,aAAa;KAAyB;IAChE,MAAM;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC7D,OAAO;KAAE,MAAM;KAAU,aAAa;KAAsC;IAC7E;GACF;EACF;CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,WAAW;IACT,MAAM;IACN,aACE;IACH,EACF;GACD,UAAU,CAAC,YAAY;GACxB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,aAAa;KACX,MAAM;KACN,aAAa;KACd;IACD,UAAU;KAAE,MAAM;KAAU,aAAa;KAAuB;IAChE,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC/D;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACd,EACF;GACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,UAA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EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,CACtC;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY,EACV,IAAI;GACF,MAAM;GACN,aAAa;GACd,EACF;EACD,UAAU,CAAC,KAAK;EACjB;CACF,CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAgC;IACxE,MAAM;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC9D;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAAgB;IACtD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAqB;IAC7D,eAAe;KACb,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAA4B;IACnE;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,UAAU;IAAE,MAAM;IAAU,aAAa;IAA2B,EACrE;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,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Param(params, name) {
2
+ const raw = params?.[name];
3
+ const value = Array.isArray(raw) ? raw[0] : raw;
4
+ if (typeof value !== "string") return void 0;
5
+ const trimmed = value.trim();
6
+ return trimmed.length > 0 ? trimmed : void 0;
7
+ }
8
+ function parseListQuery(params) {
9
+ const rawLimit = firstParam(params, "limit");
10
+ const parsedLimit = rawLimit === void 0 ? NaN : Number(rawLimit);
11
+ return {
12
+ limit: Number.isFinite(parsedLimit) && parsedLimit >= 1 ? Math.min(Math.floor(parsedLimit), 500) : void 0,
13
+ cursor: firstParam(params, "cursor"),
14
+ project: firstParam(params, "project"),
15
+ type: firstParam(params, "type"),
16
+ status: firstParam(params, "status"),
17
+ q: firstParam(params, "q")
18
+ };
19
+ }
20
+ function encodeCursor(position) {
21
+ return Buffer.from(JSON.stringify(position), "utf-8").toString("base64url");
22
+ }
23
+ function decodeCursor(cursor) {
24
+ if (!cursor) return null;
25
+ try {
26
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf-8"));
27
+ if (!parsed || typeof parsed !== "object") return null;
28
+ const position = {};
29
+ if (typeof parsed.key === "string") position.key = parsed.key;
30
+ if (typeof parsed.id === "string") position.id = parsed.id;
31
+ if (Number.isInteger(parsed.offset) && parsed.offset >= 0) position.offset = parsed.offset;
32
+ return position;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ function compareDesc(aKey, aId, bKey, bId) {
38
+ if (aKey !== bKey) return aKey < bKey ? 1 : -1;
39
+ if (aId === bId) return 0;
40
+ return aId < bId ? 1 : -1;
41
+ }
42
+ function sortByKeyDesc(items, keyOf, idOf) {
43
+ return items.sort((a, b) => compareDesc(keyOf(a), idOf(a), keyOf(b), idOf(b)));
44
+ }
45
+ function pageAfterCursor(sortedDesc, keyOf, idOf, cursor, limit) {
46
+ const position = decodeCursor(cursor);
47
+ let start = 0;
48
+ if (position?.key !== void 0 && position.id !== void 0) {
49
+ const { key, id } = position;
50
+ start = sortedDesc.findIndex((item) => compareDesc(keyOf(item), idOf(item), key, id) > 0);
51
+ if (start < 0) start = sortedDesc.length;
52
+ }
53
+ const page = sortedDesc.slice(start, start + limit);
54
+ const last = page[page.length - 1];
55
+ return {
56
+ page,
57
+ nextCursor: last !== void 0 && start + limit < sortedDesc.length ? encodeCursor({
58
+ key: keyOf(last),
59
+ id: idOf(last)
60
+ }) : null
61
+ };
62
+ }
63
+ function pageByOffset(ordered, cursor, limit) {
64
+ const start = decodeCursor(cursor)?.offset ?? 0;
65
+ return {
66
+ page: ordered.slice(start, start + limit),
67
+ nextCursor: start + limit < ordered.length ? encodeCursor({ offset: start + limit }) : null
68
+ };
69
+ }
70
+ function matchesText(q, ...fields) {
71
+ if (!q) return true;
72
+ const needle = q.toLowerCase();
73
+ return fields.some((field) => typeof field === "string" && field.toLowerCase().includes(needle));
74
+ }
75
+ //#endregion
76
+ //#region src/mcp/search-arguments.ts
77
+ function parseSearchExpansionIds(value) {
78
+ return (typeof value === "string" ? value.split(",") : Array.isArray(value) ? value : []).flatMap((entry) => {
79
+ if (typeof entry === "string") return entry.trim() ? [entry.trim()] : [];
80
+ if (!entry || typeof entry !== "object" || typeof entry.obsId !== "string" || !entry.obsId.trim()) return [];
81
+ const obsId = entry.obsId.trim();
82
+ return typeof entry.sessionId === "string" && entry.sessionId.trim() ? [{
83
+ obsId,
84
+ sessionId: entry.sessionId.trim()
85
+ }] : [obsId];
86
+ });
87
+ }
88
+ //#endregion
89
+ //#region src/mcp/session-arguments.ts
90
+ function parseSessionArguments(args) {
91
+ const limit = args.limit === void 0 ? 20 : args.limit;
92
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) throw new Error("limit must be a positive integer");
93
+ const query = { limit: String(Math.min(limit, 100)) };
94
+ for (const field of [
95
+ "project",
96
+ "agentId",
97
+ "cursor"
98
+ ]) {
99
+ if (args[field] === void 0) continue;
100
+ if (field === "cursor" && typeof args[field] === "string" && !args[field].trim()) continue;
101
+ if (typeof args[field] !== "string" || !args[field].trim()) throw new Error(`${field} must be a non-empty string`);
102
+ query[field] = args[field].trim();
103
+ }
104
+ if (query.cursor) {
105
+ const position = decodeCursor(query.cursor);
106
+ if (!position || typeof position.key !== "string" || typeof position.id !== "string") throw new Error("cursor must be a session continuation token");
107
+ }
108
+ return query;
109
+ }
110
+ //#endregion
111
+ export { pageAfterCursor as a, sortByKeyDesc as c, matchesText as i, parseSearchExpansionIds as n, pageByOffset as o, encodeCursor as r, parseListQuery as s, parseSessionArguments as t };
112
+
113
+ //# sourceMappingURL=session-arguments-zxsbbd8y.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-arguments-zxsbbd8y.mjs","names":[],"sources":["../src/state/list-query.ts","../src/mcp/search-arguments.ts","../src/mcp/session-arguments.ts"],"sourcesContent":["export const LIST_PAGE_MAX = 500;\n\nexport interface ListQuery {\n limit?: number;\n cursor?: string;\n project?: string;\n type?: string;\n status?: string;\n q?: string;\n}\n\ntype QueryParams = Record<string, string | string[] | undefined> | undefined;\n\nfunction firstParam(params: QueryParams, name: string): string | undefined {\n const raw = params?.[name];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function parseListQuery(params: QueryParams): ListQuery {\n const rawLimit = firstParam(params, \"limit\");\n const parsedLimit = rawLimit === undefined ? Number.NaN : Number(rawLimit);\n return {\n limit:\n Number.isFinite(parsedLimit) && parsedLimit >= 1\n ? Math.min(Math.floor(parsedLimit), LIST_PAGE_MAX)\n : undefined,\n cursor: firstParam(params, \"cursor\"),\n project: firstParam(params, \"project\"),\n type: firstParam(params, \"type\"),\n status: firstParam(params, \"status\"),\n q: firstParam(params, \"q\"),\n };\n}\n\ninterface CursorPosition {\n key?: string;\n id?: string;\n offset?: number;\n}\n\nexport function encodeCursor(position: CursorPosition): string {\n return Buffer.from(JSON.stringify(position), \"utf-8\").toString(\"base64url\");\n}\n\nexport function decodeCursor(cursor: string | undefined): CursorPosition | null {\n if (!cursor) return null;\n try {\n const parsed = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf-8\"));\n if (!parsed || typeof parsed !== \"object\") return null;\n const position: CursorPosition = {};\n if (typeof parsed.key === \"string\") position.key = parsed.key;\n if (typeof parsed.id === \"string\") position.id = parsed.id;\n if (Number.isInteger(parsed.offset) && parsed.offset >= 0) position.offset = parsed.offset;\n return position;\n } catch {\n return null;\n }\n}\n\nfunction compareDesc(aKey: string, aId: string, bKey: string, bId: string): number {\n if (aKey !== bKey) return aKey < bKey ? 1 : -1;\n if (aId === bId) return 0;\n return aId < bId ? 1 : -1;\n}\n\nexport function sortByKeyDesc<T>(items: T[], keyOf: (item: T) => string, idOf: (item: T) => string): T[] {\n return items.sort((a, b) => compareDesc(keyOf(a), idOf(a), keyOf(b), idOf(b)));\n}\n\nexport function pageAfterCursor<T>(\n sortedDesc: T[],\n keyOf: (item: T) => string,\n idOf: (item: T) => string,\n cursor: string | undefined,\n limit: number,\n): { page: T[]; nextCursor: string | null } {\n const position = decodeCursor(cursor);\n let start = 0;\n if (position?.key !== undefined && position.id !== undefined) {\n const { key, id } = position;\n start = sortedDesc.findIndex((item) => compareDesc(keyOf(item), idOf(item), key, id) > 0);\n if (start < 0) start = sortedDesc.length;\n }\n const page = sortedDesc.slice(start, start + limit);\n const last = page[page.length - 1];\n const nextCursor =\n last !== undefined && start + limit < sortedDesc.length\n ? encodeCursor({ key: keyOf(last), id: idOf(last) })\n : null;\n return { page, nextCursor };\n}\n\nexport function pageByOffset<T>(\n ordered: T[],\n cursor: string | undefined,\n limit: number,\n): { page: T[]; nextCursor: string | null } {\n const start = decodeCursor(cursor)?.offset ?? 0;\n const page = ordered.slice(start, start + limit);\n const nextCursor =\n start + limit < ordered.length ? encodeCursor({ offset: start + limit }) : null;\n return { page, nextCursor };\n}\n\nexport function matchesText(q: string | undefined, ...fields: Array<string | undefined | null>): boolean {\n if (!q) return true;\n const needle = q.toLowerCase();\n return fields.some((field) => typeof field === \"string\" && field.toLowerCase().includes(needle));\n}\n","export type SearchExpansionId = string | { obsId: string; sessionId: string };\n\nexport function parseSearchExpansionIds(value: unknown): SearchExpansionId[] {\n const entries = typeof value === \"string\" ? value.split(\",\") : Array.isArray(value) ? value : [];\n return entries.flatMap((entry): SearchExpansionId[] => {\n if (typeof entry === \"string\") return entry.trim() ? [entry.trim()] : [];\n if (!entry || typeof entry !== \"object\" || typeof entry.obsId !== \"string\" || !entry.obsId.trim()) return [];\n const obsId = entry.obsId.trim();\n return typeof entry.sessionId === \"string\" && entry.sessionId.trim()\n ? [{ obsId, sessionId: entry.sessionId.trim() }]\n : [obsId];\n });\n}\n","import { decodeCursor } from \"../state/list-query.js\";\n\nexport function parseSessionArguments(args: Record<string, unknown>): Record<string, string> {\n const limit = args.limit === undefined ? 20 : args.limit;\n if (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1) {\n throw new Error(\"limit must be a positive integer\");\n }\n const query: Record<string, string> = { limit: String(Math.min(limit, 100)) };\n for (const field of [\"project\", \"agentId\", \"cursor\"] as const) {\n if (args[field] === undefined) continue;\n if (field === \"cursor\" && typeof args[field] === \"string\" && !args[field].trim()) continue;\n if (typeof args[field] !== \"string\" || !args[field].trim()) {\n throw new Error(`${field} must be a non-empty string`);\n }\n query[field] = args[field].trim();\n }\n if (query.cursor) {\n const position = decodeCursor(query.cursor);\n if (!position || typeof position.key !== \"string\" || typeof position.id !== \"string\") {\n throw new Error(\"cursor must be a session continuation token\");\n }\n }\n return query;\n}\n"],"mappings":"AAaA,SAAS,WAAW,QAAqB,MAAkC;CACzE,MAAM,MAAM,SAAS;CACrB,MAAM,QAAQ,MAAM,QAAQ,IAAI,GAAG,IAAI,KAAK;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,KAAA;CACtC,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;;AAGxC,SAAgB,eAAe,QAAgC;CAC7D,MAAM,WAAW,WAAW,QAA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