@noxsoft/anima 2.0.2 → 2.0.4

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 (829) hide show
  1. package/README.md +1260 -28
  2. package/dist/accounts-Bth3PpPD.js +260 -0
  3. package/dist/accounts-D8CPKNkN.js +259 -0
  4. package/dist/acp-cli-ByK6lS6c.js +1081 -0
  5. package/dist/acp-cli-CaQCjIw4.js +1084 -0
  6. package/dist/agent-BgIkqd3F.js +725 -0
  7. package/dist/agent-N5BDcge4.js +725 -0
  8. package/dist/agent-events-COH7NDW2.js +182 -0
  9. package/dist/agent-scope-CPphqq-U.js +452 -0
  10. package/dist/agent-scope-DZgptr9J.js +452 -0
  11. package/dist/agent-scope-cj2QCT6R.js +112 -0
  12. package/dist/agents-NEudYMdg.js +774 -0
  13. package/dist/agents.config-Bujs-NIy.js +182 -0
  14. package/dist/agents.config-jp7OLssr.js +182 -0
  15. package/dist/argv-BMZMiW7v.js +73 -0
  16. package/dist/audit-C-UJhfdv.js +2401 -0
  17. package/dist/audit-CeCO7SK5.js +2401 -0
  18. package/dist/auth-BNZsOHGF.js +648 -0
  19. package/dist/auth-DMPZWzEa.js +639 -0
  20. package/dist/auth-choice-5VnaGMD-.js +2681 -0
  21. package/dist/auth-choice-DA2k4vs8.js +2681 -0
  22. package/dist/auth-health-B7FqA26_.js +149 -0
  23. package/dist/auth-health-VO_MPqVX.js +149 -0
  24. package/dist/auth-profiles-BDrNYX_n.js +1564 -0
  25. package/dist/auth-profiles-CxSHydjn.js +2689 -0
  26. package/dist/banner-BtDZPRzi.js +294 -0
  27. package/dist/browser-cli-8yQMpxb8.js +1679 -0
  28. package/dist/browser-cli-Czg3JtDH.js +1676 -0
  29. package/dist/build-info.json +3 -3
  30. package/dist/bundled/boot-md/handler.js +16 -16
  31. package/dist/bundled/bootstrap-extra-files/handler.js +4 -4
  32. package/dist/bundled/command-logger/handler.js +1 -1
  33. package/dist/bundled/session-memory/handler.js +5 -5
  34. package/dist/call-BIzCaKZb.js +282 -0
  35. package/dist/call-BYDpTVCZ.js +282 -0
  36. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  37. package/dist/catalog-CqKiUgu6.js +185 -0
  38. package/dist/catalog-DMfEg-oK.js +185 -0
  39. package/dist/channel-options-BrtCtyrT.js +32 -0
  40. package/dist/channel-options-CO21Gl8p.js +33 -0
  41. package/dist/channel-selection-Bbm1lq3P.js +51 -0
  42. package/dist/channel-selection-CqcX7Ocw.js +51 -0
  43. package/dist/channel-web-DrsT6OAE.js +2162 -0
  44. package/dist/channels-cli-Juyh1S6n.js +1304 -0
  45. package/dist/channels-cli-zNvi1m5c.js +1306 -0
  46. package/dist/channels-status-issues-CqzqshW4.js +18 -0
  47. package/dist/channels-status-issues-DdJdO866.js +18 -0
  48. package/dist/chrome-C4dOMO8z.js +1601 -0
  49. package/dist/chrome-DdcDzAtH.js +1629 -0
  50. package/dist/chrome-U3DRzjJD.js +1601 -0
  51. package/dist/chunk-D2nLsrEW.js +348 -0
  52. package/dist/clack-prompter-BI3RDW5w.js +92 -0
  53. package/dist/clack-prompter-Dwr1m_IZ.js +92 -0
  54. package/dist/cli/daemon-cli.js +1 -1
  55. package/dist/cli-C3cpDaz8.js +99 -0
  56. package/dist/cli-CjWUGdGC.js +101 -0
  57. package/dist/cli-session-BVjY_XrW.js +5463 -0
  58. package/dist/cli-session-gtuYN2Iq.js +5408 -0
  59. package/dist/client-Dswwze5_.js +1692 -0
  60. package/dist/client-LRKFjo4A.js +1692 -0
  61. package/dist/clipboard-BZKS9O1u.js +31 -0
  62. package/dist/clipboard-DES8b1AM.js +31 -0
  63. package/dist/command-format-CP1YTNCl.js +52 -0
  64. package/dist/command-format-CVL4K5cj.js +52 -0
  65. package/dist/command-format-G6N2zghg.js +38 -0
  66. package/dist/command-registry-BBvNvysr.js +248 -0
  67. package/dist/commands-AZ3n8Y2c.js +726 -0
  68. package/dist/commands-BMnD_QRY.js +726 -0
  69. package/dist/commands-registry-cFqZ6Ib4.js +766 -0
  70. package/dist/commands-registry-q13H7ng5.js +766 -0
  71. package/dist/common-CX5458fH.js +287 -0
  72. package/dist/common-DJbnT8ws.js +287 -0
  73. package/dist/completion-cli-BADRBcIl.js +432 -0
  74. package/dist/completion-cli-DMQgiObF.js +431 -0
  75. package/dist/config-CU-Axg8P.js +5704 -0
  76. package/dist/config-DaqbUdkI.js +5705 -0
  77. package/dist/config-cli-BPlbwiuA.js +244 -0
  78. package/dist/config-cli-DXgZJkPU.js +247 -0
  79. package/dist/config-guard-Ba49JNds.js +76 -0
  80. package/dist/config-guard-Cu0qMKZJ.js +93 -0
  81. package/dist/config-kVVm5EYV.js +6523 -0
  82. package/dist/config-sync-CzLnLTXt.js +91 -0
  83. package/dist/config-sync-DuydxPWx.js +91 -0
  84. package/dist/configure-CHgacLyi.js +960 -0
  85. package/dist/configure-DfHXDa1L.js +959 -0
  86. package/dist/context-DzgXOckU.js +60 -0
  87. package/dist/control-service-8_wKHwBa.js +72 -0
  88. package/dist/control-service-BtL1Jto_.js +72 -0
  89. package/dist/cron-cli-BCzSR2c0.js +448 -0
  90. package/dist/cron-cli-CCWNkykU.js +451 -0
  91. package/dist/daemon-cli-Bjkbu9Vy.js +565 -0
  92. package/dist/daemon-cli-CmlHcC1J.js +566 -0
  93. package/dist/daemon-cli.js +16 -16
  94. package/dist/daemon-runtime-C0tz7VAC.js +460 -0
  95. package/dist/daemon-runtime-rUTqCVwJ.js +460 -0
  96. package/dist/deliver-BBggsviM.js +1097 -0
  97. package/dist/deliver-CePITOl8.js +1162 -0
  98. package/dist/deliver-DFnVaetP.js +1097 -0
  99. package/dist/delivery-queue-BJQK3oh5.js +220 -0
  100. package/dist/deps-CeEKhrp7.js +42 -0
  101. package/dist/devices-cli-DQrDMrZH.js +198 -0
  102. package/dist/devices-cli-Oe-A1Dv0.js +195 -0
  103. package/dist/diagnostics-DxMFrBLO.js +35 -0
  104. package/dist/diagnostics-m79ZlMmZ.js +35 -0
  105. package/dist/directory-cli-BL6h8cGF.js +246 -0
  106. package/dist/directory-cli-Cjgmi_sj.js +243 -0
  107. package/dist/dispatcher-DAFbQM-c.js +100 -0
  108. package/dist/dispatcher-DNd40gUn.js +100 -0
  109. package/dist/dist-CqDI82ei.js +929 -0
  110. package/dist/dist-DnHRxR5U.js +929 -0
  111. package/dist/dns-cli-CFtV3BXK.js +200 -0
  112. package/dist/dns-cli-NyIHvQ5S.js +197 -0
  113. package/dist/dock-BdXLb5oY.js +753 -0
  114. package/dist/dock-jYICmNcI.js +753 -0
  115. package/dist/docs-cli-CrOaIK_H.js +161 -0
  116. package/dist/docs-cli-D_cmJDSr.js +159 -0
  117. package/dist/doctor-BpGxKrBl.js +1815 -0
  118. package/dist/doctor-D12wNQPU.js +1813 -0
  119. package/dist/doctor-completion-DeOfofek.js +92 -0
  120. package/dist/doctor-completion-DwjqdEcK.js +92 -0
  121. package/dist/doctor-config-flow-BI3mpkbd.js +1232 -0
  122. package/dist/doctor-config-flow-wMHheFkC.js +1232 -0
  123. package/dist/engine-BCtL-AMw.js +563 -0
  124. package/dist/engine-Bk_UT413.js +563 -0
  125. package/dist/entry.js +5 -5
  126. package/dist/env-v6411I8h.js +32 -0
  127. package/dist/exec-B7sUS164.js +1167 -0
  128. package/dist/exec-approvals-CroGJRUg.js +1221 -0
  129. package/dist/exec-approvals-cli-BTxF_RsH.js +371 -0
  130. package/dist/exec-approvals-cli-n1gyGwH2.js +368 -0
  131. package/dist/exec-mhSykkaa.js +255 -0
  132. package/dist/extensionAPI.js +3 -3
  133. package/dist/frontmatter-BmHq0vRD.js +204 -0
  134. package/dist/gateway-cli-DDBadlrS.js +19971 -0
  135. package/dist/gateway-cli-IZNkOMBe.js +19972 -0
  136. package/dist/gateway-rpc-Dtx8HN-n.js +28 -0
  137. package/dist/gateway-rpc-L2PVSqGj.js +28 -0
  138. package/dist/github-copilot-auth-DKyqDaGU.js +1418 -0
  139. package/dist/github-copilot-auth-DXpOMSd3.js +1418 -0
  140. package/dist/gmail-setup-utils-BKNczIJ9.js +428 -0
  141. package/dist/gmail-setup-utils-co0ppccC.js +428 -0
  142. package/dist/health-Bm8ZTvC3.js +1253 -0
  143. package/dist/health-DUf1gt4E.js +1258 -0
  144. package/dist/health-format-BksT6F68.js +208 -0
  145. package/dist/health-format-uzh1xYLD.js +208 -0
  146. package/dist/heartbeat-visibility-1TJb1Zao.js +98 -0
  147. package/dist/heartbeat-visibility-CwodtdcX.js +98 -0
  148. package/dist/help-format-C6cv_aZp.js +17 -0
  149. package/dist/helpers-N-uSFKOn.js +10 -0
  150. package/dist/hooks-cli-1POsXqOl.js +993 -0
  151. package/dist/hooks-cli-BGjILbze.js +991 -0
  152. package/dist/hooks-status-DE07n5RC.js +356 -0
  153. package/dist/hooks-status-Du-d1jde.js +356 -0
  154. package/dist/image-ops-B_AYV3tp.js +541 -0
  155. package/dist/image-ops-Bp0C6Mvr.js +541 -0
  156. package/dist/index.js +82 -82
  157. package/dist/init-9A0s7bWG.js +122 -0
  158. package/dist/init-DoyCHJDC.js +122 -0
  159. package/dist/installs-D1C9wHAq.js +383 -0
  160. package/dist/installs-Dh4dHayM.js +383 -0
  161. package/dist/ipv4-DCItfaJo.js +1964 -0
  162. package/dist/ipv4-DSOUVx0i.js +1964 -0
  163. package/dist/lanes-BvSnHq2h.js +232 -0
  164. package/dist/lifecycle-core-BY4WIf9g.js +388 -0
  165. package/dist/lifecycle-core-TQKyXO-6.js +387 -0
  166. package/dist/links-CNu_8RZl.js +15 -0
  167. package/dist/links-D2tt2ouh.js +15 -0
  168. package/dist/llm-slug-generator.js +4 -4
  169. package/dist/logging-BIeRw0WR.js +15 -0
  170. package/dist/logging-C7lb3Vjc.js +15 -0
  171. package/dist/login-DXWKewA2.js +59 -0
  172. package/dist/login-Fhh4uWmf.js +61 -0
  173. package/dist/login-pPs3UO38.js +61 -0
  174. package/dist/login-qr-CevLD8cV.js +326 -0
  175. package/dist/login-qr-GF2JMIy-.js +323 -0
  176. package/dist/login-qr-ZYYKD6Yt.js +321 -0
  177. package/dist/logs-cli-CzXbX8HZ.js +242 -0
  178. package/dist/logs-cli-D9ngH9PF.js +245 -0
  179. package/dist/manager-BD5rA3w0.js +3244 -0
  180. package/dist/manager-BDPgBQSH.js +3246 -0
  181. package/dist/manager-DRWMWM--.js +3244 -0
  182. package/dist/manifest-registry-DbvPaBXY.js +748 -0
  183. package/dist/manifest-registry-kHX_MFa1.js +748 -0
  184. package/dist/markdown-tables-CqwihY2m.js +347 -0
  185. package/dist/markdown-tables-DJV7eAJZ.js +348 -0
  186. package/dist/media-lUqN-0O9.js +1342 -0
  187. package/dist/memory-cli-BLXSpgnN.js +868 -0
  188. package/dist/memory-cli-BcGVkkRJ.js +869 -0
  189. package/dist/message-channel-D_jIO87f.js +110 -0
  190. package/dist/migrate-BpVOar4L.js +157 -0
  191. package/dist/migrate-CkgGDkWy.js +157 -0
  192. package/dist/model-selection-Cqt6aJ0G.js +2691 -0
  193. package/dist/models-CExsNQPH.js +2510 -0
  194. package/dist/models-cli-Ba3Jmwev.js +2739 -0
  195. package/dist/models-cli-iDAlsbL2.js +258 -0
  196. package/dist/net-0A_zcaQD.js +218 -0
  197. package/dist/node-cli-ATmwCXIk.js +1319 -0
  198. package/dist/node-cli-DYFR_V25.js +1322 -0
  199. package/dist/node-service-CN4LqR1A.js +67 -0
  200. package/dist/node-service-CWt3MdSC.js +67 -0
  201. package/dist/nodes-cli-BeVmhTz3.js +1197 -0
  202. package/dist/nodes-cli-QeJIfa18.js +1200 -0
  203. package/dist/nodes-screen-DHyWAlla.js +234 -0
  204. package/dist/nodes-screen-qs3jRBPk.js +234 -0
  205. package/dist/note-CSlg2BnB.js +73 -0
  206. package/dist/note-Ctvglhp1.js +73 -0
  207. package/dist/npm-registry-spec-DQd4M22q.js +351 -0
  208. package/dist/npm-registry-spec-PxisIMts.js +351 -0
  209. package/dist/onboard-DeruD10m.js +1166 -0
  210. package/dist/onboard-SAcu5N6N.js +1165 -0
  211. package/dist/onboard-channels-C4iSfFXR.js +672 -0
  212. package/dist/onboard-channels-oVTVgoyg.js +672 -0
  213. package/dist/onboard-helpers-B8roRwLP.js +365 -0
  214. package/dist/onboard-helpers-Dgh26hgP.js +365 -0
  215. package/dist/onboarding-Bi-ac8we.js +911 -0
  216. package/dist/onboarding-C2gjB2u8.js +910 -0
  217. package/dist/orchestrator-DlbAYMQP.js +357 -0
  218. package/dist/orchestrator-DlwVRVDA.js +357 -0
  219. package/dist/outbound-CkKgc6iR.js +2062 -0
  220. package/dist/outbound-Vfm5yDh3.js +214 -0
  221. package/dist/outbound-bs_VK51X.js +214 -0
  222. package/dist/outbound-send-deps-DDjiMfEL.js +55 -0
  223. package/dist/pairing-cli-CJYeuEik.js +118 -0
  224. package/dist/pairing-cli-mqopHI8s.js +121 -0
  225. package/dist/pairing-store-BsXzUDPv.js +388 -0
  226. package/dist/pairing-store-DoNj00-X.js +388 -0
  227. package/dist/path-env-C_xpiG8l.js +89 -0
  228. package/dist/path-env-DSSMHu5A.js +89 -0
  229. package/dist/paths-B1vRVCad.js +126 -0
  230. package/dist/paths-BMuHNFxg.js +238 -0
  231. package/dist/paths-BXQQzXGQ.js +129 -0
  232. package/dist/paths-Buw_geoe.js +54 -0
  233. package/dist/paths-DA9WYabg.js +222 -0
  234. package/dist/paths-DfQGx0_k.js +129 -0
  235. package/dist/pi-auth-json-DOPW3e4X.js +78 -0
  236. package/dist/pi-auth-json-MruLmI_X.js +82 -0
  237. package/dist/pi-auth-json-lae_wwwo.js +80 -0
  238. package/dist/pi-model-discovery-7q0GxMrp.js +3 -0
  239. package/dist/pi-tools.policy-Csmla32P.js +200 -0
  240. package/dist/pi-tools.policy-xYdDLEv9.js +200 -0
  241. package/dist/plugin-auto-enable-CViVVWgg.js +282 -0
  242. package/dist/plugin-auto-enable-CjZ238UI.js +282 -0
  243. package/dist/plugin-registry-B4Aw2hzq.js +32 -0
  244. package/dist/plugin-registry-DW81arxW.js +32 -0
  245. package/dist/plugin-sdk/cli/cli-name.d.ts +1 -1
  246. package/dist/plugin-sdk/config/paths.d.ts +2 -2
  247. package/dist/plugin-sdk/index.js +7 -7
  248. package/dist/plugins-DhcGAPDB.js +38 -0
  249. package/dist/plugins-DtghNRtM.js +168 -0
  250. package/dist/plugins-cli-4vWTmOAb.js +736 -0
  251. package/dist/plugins-cli-CdTMbP0X.js +734 -0
  252. package/dist/polls-D6eCdatA.js +1343 -0
  253. package/dist/ports-BtZx-JKD.js +96 -0
  254. package/dist/ports-C8bKN8s0.js +96 -0
  255. package/dist/ports-DHiKnPRX.js +344 -0
  256. package/dist/ports-vd93M_Pt.js +317 -0
  257. package/dist/program-CX3aUVeb.js +176 -0
  258. package/dist/program-context-BPos0ivo.js +496 -0
  259. package/dist/progress-oiAjiiNi.js +133 -0
  260. package/dist/prompt-style-Cm4wOtKm.js +9 -0
  261. package/dist/pw-ai-4QbK5YFe.js +1865 -0
  262. package/dist/pw-ai-BWz3Cxt7.js +1868 -0
  263. package/dist/pw-ai-C83HBue2.js +1867 -0
  264. package/dist/qmd-manager-BcMeZiGD.js +938 -0
  265. package/dist/qmd-manager-CPypGJ0P.js +935 -0
  266. package/dist/qmd-manager-CRrSkfia.js +937 -0
  267. package/dist/register.agent-DDY8KJhn.js +265 -0
  268. package/dist/register.agent-DKawm-9d.js +1003 -0
  269. package/dist/register.anima-CEWUo29k.js +193 -0
  270. package/dist/register.anima-DBWz2rk_.js +193 -0
  271. package/dist/register.configure-BX67qV8k.js +103 -0
  272. package/dist/register.configure-CWsySuiq.js +101 -0
  273. package/dist/register.maintenance-0k-ZNhDg.js +543 -0
  274. package/dist/register.maintenance-BIwx1fzX.js +543 -0
  275. package/dist/register.message-CXPsoakA.js +657 -0
  276. package/dist/register.message-DA3jvfgI.js +660 -0
  277. package/dist/register.onboard-C4HG7Hqv.js +170 -0
  278. package/dist/register.onboard-GOpdif-j.js +170 -0
  279. package/dist/register.setup-B17vZT7C.js +175 -0
  280. package/dist/register.setup-GJyUDCqh.js +175 -0
  281. package/dist/register.status-health-sessions-D5876dGx.js +313 -0
  282. package/dist/register.status-health-sessions-lOewVIZR.js +142 -0
  283. package/dist/register.subclis-Dwnujj5C.js +255 -0
  284. package/dist/reply-CR5T_oQJ.js +32212 -0
  285. package/dist/reply-prefix-BcrS4Umd.js +100 -0
  286. package/dist/reply-prefix-Btb5o2NH.js +100 -0
  287. package/dist/reply-r089HuRA.js +32212 -0
  288. package/dist/routes-B4czFzIb.js +1820 -0
  289. package/dist/routes-ucJWAk5O.js +1820 -0
  290. package/dist/rpc-BnKxnQ0v.js +70 -0
  291. package/dist/rpc-DgE-xnyx.js +70 -0
  292. package/dist/run-main-B74kv84C.js +371 -0
  293. package/dist/runtime-guard-CKFdts2L.js +60 -0
  294. package/dist/sandbox-CJTS3er6.js +858 -0
  295. package/dist/sandbox-DBSiVHt_.js +859 -0
  296. package/dist/sandbox-cli-CrkjyU5M.js +461 -0
  297. package/dist/sandbox-cli-D1r5y6Sz.js +458 -0
  298. package/dist/security-cli-BZUdnkhn.js +462 -0
  299. package/dist/security-cli-DS09ebvA.js +465 -0
  300. package/dist/server-context-C0xZbYhg.js +824 -0
  301. package/dist/server-context-DVh2z7om.js +824 -0
  302. package/dist/server-node-events-bu9lpkMH.js +233 -0
  303. package/dist/server-node-events-i1Rrww31.js +231 -0
  304. package/dist/service-CJJwLEor.js +642 -0
  305. package/dist/service-DxLxBhaU.js +642 -0
  306. package/dist/service-audit-DB4Y3Ekp.js +488 -0
  307. package/dist/service-audit-M8y4TXVb.js +488 -0
  308. package/dist/session-CGxOLFs2.js +179 -0
  309. package/dist/session-DTTbdKb0.js +181 -0
  310. package/dist/session-cost-usage-FcdJl9c3.js +600 -0
  311. package/dist/session-cost-usage-qdfsGU2a.js +600 -0
  312. package/dist/session-yOhWcsD2.js +181 -0
  313. package/dist/sessions-B-Cu7JZq.js +1296 -0
  314. package/dist/sessions-BgLN4KFr.js +180 -0
  315. package/dist/sessions-CnRjwdVr.js +1296 -0
  316. package/dist/sessions-wRKla1Qh.js +2038 -0
  317. package/dist/shared-DS3UaJSP.js +66 -0
  318. package/dist/shared-DxNHzky3.js +77 -0
  319. package/dist/shared-Qpt4hUDi.js +66 -0
  320. package/dist/shared-kzrojZ1B.js +77 -0
  321. package/dist/skill-scanner-DLJji5Ye.js +263 -0
  322. package/dist/skills-BWFIEp4j.js +807 -0
  323. package/dist/skills-DV4zKdCx.js +808 -0
  324. package/dist/skills-cli-BY53ILm2.js +289 -0
  325. package/dist/skills-cli-CO3gxl8A.js +286 -0
  326. package/dist/skills-status-DX5pcqY3.js +166 -0
  327. package/dist/skills-status-zhcKzGkp.js +166 -0
  328. package/dist/sqlite-B6MojU1I.js +321 -0
  329. package/dist/sqlite-CuprTGR7.js +453 -0
  330. package/dist/sqlite-dzD-jMjs.js +368 -0
  331. package/dist/start-Cu3aLoSf.js +297 -0
  332. package/dist/start-Dz7tMAl8.js +296 -0
  333. package/dist/status-CaSxhxfV.js +2132 -0
  334. package/dist/status-D2C0JCX3.js +2137 -0
  335. package/dist/status-DlFMsQzh.js +27 -0
  336. package/dist/status-G0CITnKR.js +27 -0
  337. package/dist/status.update-CHjhVxJY.js +79 -0
  338. package/dist/status.update-DVFelehi.js +79 -0
  339. package/dist/subagent-registry-3Xb4el-8.js +14 -0
  340. package/dist/subagent-registry-CdSjz14I.js +2760 -0
  341. package/dist/subagent-registry-DNDhbHWi.js +2759 -0
  342. package/dist/subsystem-DfKstnEK.js +860 -0
  343. package/dist/system-cli-B5mt0FWa.js +82 -0
  344. package/dist/system-cli-Dg3UQ3Zz.js +79 -0
  345. package/dist/systemd-B43AvOGx.js +452 -0
  346. package/dist/systemd-RpPE0XGg.js +452 -0
  347. package/dist/systemd-hints-DMJT-Bbc.js +36 -0
  348. package/dist/systemd-hints-vRInKcz9.js +36 -0
  349. package/dist/systemd-linger-Dzyxqsod.js +75 -0
  350. package/dist/systemd-linger-EujbmI5A.js +75 -0
  351. package/dist/table-DhXHfRX2.js +279 -0
  352. package/dist/table-bWCLW-3P.js +279 -0
  353. package/dist/timeout-Ddn-5kAO.js +232 -0
  354. package/dist/tokens-3psI_Qk2.js +14 -0
  355. package/dist/tokens-BaM53PEx.js +14 -0
  356. package/dist/trash-Bmxs1Rnm.js +23 -0
  357. package/dist/trash-C39a6hKA.js +23 -0
  358. package/dist/tui-BHgBWhHE.js +3894 -0
  359. package/dist/tui-cli-B9Sq5-cC.js +50 -0
  360. package/dist/tui-cli-Dw7v4JoJ.js +47 -0
  361. package/dist/tui-mUwDwqvd.js +3894 -0
  362. package/dist/update-DF0GHG0j.js +317 -0
  363. package/dist/update-DoZLVjva.js +317 -0
  364. package/dist/update-check-Bt1dVPVN.js +400 -0
  365. package/dist/update-check-D5qAKes7.js +400 -0
  366. package/dist/update-cli-BNu2Oi7H.js +1105 -0
  367. package/dist/update-cli-D36AmALA.js +1105 -0
  368. package/dist/update-runner-CNQQaTwA.js +894 -0
  369. package/dist/update-runner-CvxZmbu-.js +894 -0
  370. package/dist/usage-BGCwNnjk.js +4516 -0
  371. package/dist/utils-DZ8pnOD5.js +243 -0
  372. package/dist/web-B5QG839O.js +46842 -0
  373. package/dist/web-Cmnvk9v0.js +2203 -0
  374. package/dist/web-Cv2KnTnL.js +63 -0
  375. package/dist/webhooks-cli-B6y89Pj_.js +319 -0
  376. package/dist/webhooks-cli-BDzHON4w.js +316 -0
  377. package/dist/whatsapp-actions-C_5MwVxM.js +45 -0
  378. package/dist/whatsapp-actions-hgYA12To.js +53 -0
  379. package/dist/whatsapp-actions-zTiVOoOV.js +49 -0
  380. package/dist/widearea-dns-BeIdnISJ.js +127 -0
  381. package/dist/widearea-dns-CF1gxpJ-.js +127 -0
  382. package/dist/workspace-DLna1IxR.js +649 -0
  383. package/dist/ws-log-Q4wO1Ztb.js +267 -0
  384. package/dist/ws-log-xF0kxDzp.js +267 -0
  385. package/package.json +1 -2
  386. package/dist/accounts-Cc5E4IDO.js +0 -260
  387. package/dist/accounts-CcVrwKqv.js +0 -259
  388. package/dist/acp-cli-DvphOKuh.js +0 -1081
  389. package/dist/acp-cli-p28pQ65a.js +0 -1084
  390. package/dist/agent-Cj7uDJaZ.js +0 -725
  391. package/dist/agent-Cuj9-2sT.js +0 -725
  392. package/dist/agent-events-BEBQsyE5.js +0 -182
  393. package/dist/agent-scope-BVf4aSwY.js +0 -112
  394. package/dist/agent-scope-OZi7lb8S.js +0 -452
  395. package/dist/agent-scope-V1bi9OYL.js +0 -452
  396. package/dist/agents-BUWqn_Ui.js +0 -774
  397. package/dist/agents.config-Dvo2ULxs.js +0 -182
  398. package/dist/agents.config-d6H0_3oj.js +0 -182
  399. package/dist/argv-DqUHKf0o.js +0 -73
  400. package/dist/audit-C6okOOSh.js +0 -2401
  401. package/dist/audit-VWjIdwC7.js +0 -2401
  402. package/dist/auth-91o2YM96.js +0 -648
  403. package/dist/auth-choice-CAmACV13.js +0 -2681
  404. package/dist/auth-choice-p3SeHPj2.js +0 -2681
  405. package/dist/auth-health-B_jXrWe6.js +0 -149
  406. package/dist/auth-health-DCicUKYR.js +0 -149
  407. package/dist/auth-lZ26wsbN.js +0 -639
  408. package/dist/auth-profiles-CCDD56dU.js +0 -1564
  409. package/dist/auth-profiles-DxI8L7bs.js +0 -2689
  410. package/dist/banner-Cohn04J6.js +0 -294
  411. package/dist/browser-cli-DANzjztE.js +0 -1676
  412. package/dist/browser-cli-WjsVH741.js +0 -1679
  413. package/dist/call-BAHvlu2G.js +0 -282
  414. package/dist/call-Ct7EGP_L.js +0 -282
  415. package/dist/catalog-BAayBt1L.js +0 -185
  416. package/dist/catalog-BNsf97BM.js +0 -185
  417. package/dist/channel-options-Dx9nPlX8.js +0 -33
  418. package/dist/channel-options-ZdvXrTGs.js +0 -32
  419. package/dist/channel-selection-CujyiWGM.js +0 -51
  420. package/dist/channel-selection-DfGpCyh2.js +0 -51
  421. package/dist/channel-web-CC0hkgkR.js +0 -2162
  422. package/dist/channels-cli-D7lNBpIb.js +0 -1304
  423. package/dist/channels-cli-DUPG8WDv.js +0 -1306
  424. package/dist/channels-status-issues-DBc1pU_R.js +0 -18
  425. package/dist/channels-status-issues-DjO9MHIG.js +0 -18
  426. package/dist/chrome-Bi6iZ5sG.js +0 -1601
  427. package/dist/chrome-DNSv7Cpy.js +0 -1629
  428. package/dist/chrome-DScZx4Lk.js +0 -1601
  429. package/dist/chunk-mxPVo000.js +0 -348
  430. package/dist/clack-prompter-B0kl7shw.js +0 -92
  431. package/dist/clack-prompter-B1YxZdRy.js +0 -92
  432. package/dist/cli-CfHUkOD0.js +0 -101
  433. package/dist/cli-ClMrIh6l.js +0 -99
  434. package/dist/cli-session-BkPTd9Pk.js +0 -5463
  435. package/dist/cli-session-Dd8DKb5a.js +0 -5408
  436. package/dist/client-C1avc0vD.js +0 -1692
  437. package/dist/client-CC94YZrT.js +0 -1692
  438. package/dist/clipboard-B2fBy8tG.js +0 -31
  439. package/dist/clipboard-BbGnZskJ.js +0 -31
  440. package/dist/command-format-Clp46jkj.js +0 -38
  441. package/dist/command-format-DELazozB.js +0 -52
  442. package/dist/command-format-SkzzRqR1.js +0 -52
  443. package/dist/command-registry-DZ4hkmA0.js +0 -248
  444. package/dist/commands-DtYZJSPn.js +0 -568
  445. package/dist/commands-Dujk1JmY.js +0 -568
  446. package/dist/commands-registry-Bd0xbvwG.js +0 -766
  447. package/dist/commands-registry-DYfRSVF3.js +0 -766
  448. package/dist/common-D6bu0zHC.js +0 -287
  449. package/dist/common-zW9Y2P1B.js +0 -287
  450. package/dist/completion-cli-tSe7Pmqm.js +0 -431
  451. package/dist/completion-cli-vn4IScs5.js +0 -432
  452. package/dist/config-C8rUDJXY.js +0 -5704
  453. package/dist/config-CLZ_XGVw.js +0 -6523
  454. package/dist/config-SY8M0kM_.js +0 -5705
  455. package/dist/config-cli-1V7D2Wsw.js +0 -247
  456. package/dist/config-cli-CjWEC81L.js +0 -244
  457. package/dist/config-guard-BW2gpKj_.js +0 -93
  458. package/dist/config-guard-BvxuzHpo.js +0 -76
  459. package/dist/config-sync-CoIIbEOe.js +0 -91
  460. package/dist/config-sync-DvAttep0.js +0 -91
  461. package/dist/configure-Bf0oupCE.js +0 -959
  462. package/dist/configure-DRM-7zFf.js +0 -960
  463. package/dist/context-D5iEFzv9.js +0 -60
  464. package/dist/control-service-C8m8F9pr.js +0 -72
  465. package/dist/control-service-DKotCWCg.js +0 -72
  466. package/dist/cron-cli-DB_FLYHD.js +0 -448
  467. package/dist/cron-cli-bxm5lrrO.js +0 -451
  468. package/dist/daemon-cli-1LsOnICv.js +0 -566
  469. package/dist/daemon-cli-CC2NrJ7a.js +0 -565
  470. package/dist/daemon-runtime-BXZhtBL9.js +0 -460
  471. package/dist/daemon-runtime-DW4USC7r.js +0 -460
  472. package/dist/deliver-B4HuPwJA.js +0 -1162
  473. package/dist/deliver-LiY5oL52.js +0 -1097
  474. package/dist/deliver-xrmk7xjh.js +0 -1097
  475. package/dist/delivery-queue-TnQykYsg.js +0 -220
  476. package/dist/deps-CMMOiOsF.js +0 -42
  477. package/dist/devices-cli-Be5he2SA.js +0 -195
  478. package/dist/devices-cli-z6ecoFe9.js +0 -198
  479. package/dist/diagnostics-Dj75aEHN.js +0 -35
  480. package/dist/diagnostics-DlIw6fqD.js +0 -35
  481. package/dist/directory-cli-CEy-0nxj.js +0 -243
  482. package/dist/directory-cli-DpzKcigr.js +0 -246
  483. package/dist/dispatcher-10Shiuz3.js +0 -100
  484. package/dist/dispatcher-3Jae6AiW.js +0 -100
  485. package/dist/dns-cli-Bat1pkc-.js +0 -200
  486. package/dist/dns-cli-NohNyEo0.js +0 -197
  487. package/dist/dock-DbxBBv30.js +0 -753
  488. package/dist/dock-cPBY4qGl.js +0 -753
  489. package/dist/docs-cli-BWp6p-Tq.js +0 -161
  490. package/dist/docs-cli-x22FnZfL.js +0 -159
  491. package/dist/doctor-BrT5m_on.js +0 -1815
  492. package/dist/doctor-Pp2HVnjM.js +0 -1813
  493. package/dist/doctor-completion-DNTimX9o.js +0 -92
  494. package/dist/doctor-completion-ylN9QAJ6.js +0 -92
  495. package/dist/doctor-config-flow-D1w3700T.js +0 -1232
  496. package/dist/doctor-config-flow-Dq50iE1R.js +0 -1232
  497. package/dist/engine-B9avUJL5.js +0 -563
  498. package/dist/engine-BiUQ25D4.js +0 -563
  499. package/dist/env-0lJfCPsw.js +0 -32
  500. package/dist/exec-BenD3A5l.js +0 -1167
  501. package/dist/exec-Bv3pyjeM.js +0 -255
  502. package/dist/exec-approvals-CdLmKX2R.js +0 -1221
  503. package/dist/exec-approvals-cli-DXfV6G8H.js +0 -368
  504. package/dist/exec-approvals-cli-J2cZs10o.js +0 -371
  505. package/dist/frontmatter-YijVi0FQ.js +0 -204
  506. package/dist/gateway-cli-DOAbA0pc.js +0 -19972
  507. package/dist/gateway-cli-QpWtBhQy.js +0 -19971
  508. package/dist/gateway-rpc-DJKBil9s.js +0 -28
  509. package/dist/gateway-rpc-DVterpLP.js +0 -28
  510. package/dist/github-copilot-auth-4IUFp669.js +0 -1418
  511. package/dist/github-copilot-auth-C9E0IROs.js +0 -1418
  512. package/dist/gmail-setup-utils-BPo_LkKI.js +0 -428
  513. package/dist/gmail-setup-utils-D3Yqgor7.js +0 -428
  514. package/dist/health-BeZnqp6m.js +0 -1258
  515. package/dist/health-Cn2OoVWZ.js +0 -1253
  516. package/dist/health-format-CdP99j3Y.js +0 -208
  517. package/dist/health-format-JEChH08S.js +0 -208
  518. package/dist/heartbeat-visibility-BL3WAchI.js +0 -98
  519. package/dist/heartbeat-visibility-CQ9QimI7.js +0 -98
  520. package/dist/help-format-Dl4bsrLI.js +0 -17
  521. package/dist/helpers-ZKNRexvX.js +0 -10
  522. package/dist/hooks-cli-D99hXt7K.js +0 -991
  523. package/dist/hooks-cli-DMB8RiEO.js +0 -993
  524. package/dist/hooks-status-B-e96dZj.js +0 -356
  525. package/dist/hooks-status-C_9sE0ox.js +0 -356
  526. package/dist/image-ops-Dlt3T7th.js +0 -541
  527. package/dist/image-ops-omlvdfah.js +0 -541
  528. package/dist/init-Bm04RagW.js +0 -122
  529. package/dist/init-CaJBf4p1.js +0 -122
  530. package/dist/installs-C2iMRBVz.js +0 -383
  531. package/dist/installs-D-cPGdCw.js +0 -383
  532. package/dist/ipv4-Bf7NS3QU.js +0 -1964
  533. package/dist/ipv4-wWNs8IH_.js +0 -1964
  534. package/dist/lanes-CNxj3tit.js +0 -232
  535. package/dist/lifecycle-core-B_7XRcvF.js +0 -388
  536. package/dist/lifecycle-core-By83PVAK.js +0 -387
  537. package/dist/links-BfjHVTB_.js +0 -15
  538. package/dist/links-DPGe0OHw.js +0 -15
  539. package/dist/logging-DB6BQmhi.js +0 -15
  540. package/dist/logging-mcb66J0p.js +0 -15
  541. package/dist/login-BDCg6D0N.js +0 -61
  542. package/dist/login-BDfnbjnZ.js +0 -59
  543. package/dist/login-BqH1itcg.js +0 -61
  544. package/dist/login-qr-CyOw3R4r.js +0 -321
  545. package/dist/login-qr-D8ECtb72.js +0 -323
  546. package/dist/login-qr-RnR7e4Bw.js +0 -326
  547. package/dist/logs-cli--j89L74J.js +0 -245
  548. package/dist/logs-cli-DpEMg_Gq.js +0 -242
  549. package/dist/manager-B4OyvcxT.js +0 -3244
  550. package/dist/manager-Cqc1CeH7.js +0 -3246
  551. package/dist/manager-DUyQPFvj.js +0 -3244
  552. package/dist/manifest-registry-CW1zCyRF.js +0 -748
  553. package/dist/manifest-registry-D4lM2RdV.js +0 -748
  554. package/dist/markdown-tables-BT1X6jqH.js +0 -347
  555. package/dist/markdown-tables-DHgOK2vI.js +0 -348
  556. package/dist/media-THyainiE.js +0 -1342
  557. package/dist/memory-cli-BKocCWXM.js +0 -868
  558. package/dist/memory-cli-Jmma-xI_.js +0 -869
  559. package/dist/message-channel-dSTVVCyX.js +0 -110
  560. package/dist/migrate-BR6iAIjO.js +0 -157
  561. package/dist/migrate-D0EcMs0f.js +0 -157
  562. package/dist/model-selection-YcSr9CgC.js +0 -2691
  563. package/dist/models-1vUQBVfw.js +0 -2510
  564. package/dist/models-cli-BK3BwUhL.js +0 -2739
  565. package/dist/models-cli-DECrM8oA.js +0 -258
  566. package/dist/net-B5lXhYLV.js +0 -218
  567. package/dist/node-cli-cLHUNpPD.js +0 -1319
  568. package/dist/node-cli-fO7Y132S.js +0 -1322
  569. package/dist/node-service-BFxHJsno.js +0 -67
  570. package/dist/node-service-DUnan4uK.js +0 -67
  571. package/dist/nodes-cli-BCq35E6N.js +0 -1200
  572. package/dist/nodes-cli-vD7MwAKP.js +0 -1197
  573. package/dist/nodes-screen-1YiLkqr5.js +0 -234
  574. package/dist/nodes-screen-DZeD8hE5.js +0 -234
  575. package/dist/note-Bi8Wb8DV.js +0 -73
  576. package/dist/note-uiuPxhyX.js +0 -73
  577. package/dist/npm-registry-spec-B-XIShkB.js +0 -351
  578. package/dist/npm-registry-spec-za3itb5Y.js +0 -351
  579. package/dist/onboard-Ds6w_sWo.js +0 -1165
  580. package/dist/onboard-SAVx3bp4.js +0 -1166
  581. package/dist/onboard-channels-Cg_EkBa4.js +0 -672
  582. package/dist/onboard-channels-D7NbA55V.js +0 -672
  583. package/dist/onboard-helpers-DO_hgZb9.js +0 -365
  584. package/dist/onboard-helpers-_XgJgeqh.js +0 -365
  585. package/dist/onboarding-3hLmDd0r.js +0 -911
  586. package/dist/onboarding-B4LKLsbU.js +0 -910
  587. package/dist/orchestrator-BKzmyBWy.js +0 -357
  588. package/dist/orchestrator-BN3QCz2s.js +0 -357
  589. package/dist/outbound-BgA9hNlP.js +0 -2062
  590. package/dist/outbound-CjdvVhUI.js +0 -214
  591. package/dist/outbound-DOGe6qb2.js +0 -214
  592. package/dist/outbound-send-deps-Du5aBpd7.js +0 -55
  593. package/dist/pairing-cli-2vnyg_Nd.js +0 -118
  594. package/dist/pairing-cli-BH1KQtNV.js +0 -121
  595. package/dist/pairing-store-DJz_9Gv0.js +0 -388
  596. package/dist/pairing-store-DmOzxcuk.js +0 -388
  597. package/dist/path-env-Bu6k0jDQ.js +0 -89
  598. package/dist/path-env-C0zQSjw8.js +0 -89
  599. package/dist/paths-BTc4nk-6.js +0 -126
  600. package/dist/paths-BgUi2Z2G.js +0 -54
  601. package/dist/paths-C6VCWKo3.js +0 -238
  602. package/dist/paths-CCxa0o9c.js +0 -222
  603. package/dist/paths-CxRf2rBG.js +0 -129
  604. package/dist/paths-hcX1Gqg5.js +0 -129
  605. package/dist/pi-auth-json-B68R7q7_.js +0 -82
  606. package/dist/pi-auth-json-CR0jXAgq.js +0 -78
  607. package/dist/pi-auth-json-ZYzi3nxs.js +0 -80
  608. package/dist/pi-model-discovery-Cxs4pvC2.js +0 -3
  609. package/dist/pi-tools.policy-D81U5xy0.js +0 -200
  610. package/dist/pi-tools.policy-DSHkkb5b.js +0 -200
  611. package/dist/plugin-auto-enable-CxF4bpDN.js +0 -282
  612. package/dist/plugin-auto-enable-jNaAeyEh.js +0 -282
  613. package/dist/plugin-registry-C7XWotZG.js +0 -32
  614. package/dist/plugin-registry-DcUCbGax.js +0 -32
  615. package/dist/plugins-B362e77G.js +0 -168
  616. package/dist/plugins-CmSUIUNi.js +0 -38
  617. package/dist/plugins-cli-BsCEnoQ7.js +0 -734
  618. package/dist/plugins-cli-QSIsMUG7.js +0 -736
  619. package/dist/polls-CItfB1H8.js +0 -1343
  620. package/dist/ports-BVLMN1Sr.js +0 -96
  621. package/dist/ports-CqLSlU6Z.js +0 -317
  622. package/dist/ports-D94CwCrv.js +0 -344
  623. package/dist/ports-D_NHthOz.js +0 -96
  624. package/dist/program-DkJHjI0R.js +0 -176
  625. package/dist/program-context-DnyGM2SC.js +0 -496
  626. package/dist/progress-Bek_GyWS.js +0 -133
  627. package/dist/prompt-style-lu0clOOE.js +0 -9
  628. package/dist/pw-ai-BLVMuSLv.js +0 -1867
  629. package/dist/pw-ai-DZJWEF_f.js +0 -1865
  630. package/dist/pw-ai-dzf-ptcn.js +0 -1868
  631. package/dist/qmd-manager-Cur_Ekn0.js +0 -937
  632. package/dist/qmd-manager-DNAUuwjK.js +0 -938
  633. package/dist/qmd-manager-DepEoASu.js +0 -935
  634. package/dist/register.agent-CSWvzOkR.js +0 -265
  635. package/dist/register.agent-UeH2NXmH.js +0 -1003
  636. package/dist/register.anima-DOdee0dh.js +0 -193
  637. package/dist/register.anima-HHDWsz6r.js +0 -193
  638. package/dist/register.configure-CSJFxdz9.js +0 -103
  639. package/dist/register.configure-D84Fvcz4.js +0 -101
  640. package/dist/register.maintenance-B3pvNbZb.js +0 -543
  641. package/dist/register.maintenance-BKVOwkw6.js +0 -543
  642. package/dist/register.message-BAO6CPl2.js +0 -657
  643. package/dist/register.message-OXoOKE_6.js +0 -660
  644. package/dist/register.onboard-BK_ixVmD.js +0 -170
  645. package/dist/register.onboard-cfCaPx6j.js +0 -170
  646. package/dist/register.setup-BGfDnzph.js +0 -175
  647. package/dist/register.setup-Y-Q74M-0.js +0 -175
  648. package/dist/register.status-health-sessions-CT14eitH.js +0 -142
  649. package/dist/register.status-health-sessions-TfZMzAUn.js +0 -313
  650. package/dist/register.subclis-BZwdlNHC.js +0 -255
  651. package/dist/reply-mlsExaZm.js +0 -32212
  652. package/dist/reply-prefix-B0CfR4bM.js +0 -100
  653. package/dist/reply-prefix-w4a39ybC.js +0 -100
  654. package/dist/reply-qalRISe_.js +0 -32212
  655. package/dist/routes-CENsHJyg.js +0 -1820
  656. package/dist/routes-DO0HqW2e.js +0 -1820
  657. package/dist/rpc-C0pjNhBi.js +0 -70
  658. package/dist/rpc-DZ44PIXE.js +0 -70
  659. package/dist/run-main-BMpKw8Mp.js +0 -371
  660. package/dist/runtime-guard-BSUFiAQV.js +0 -60
  661. package/dist/sandbox-BIGfMYEI.js +0 -858
  662. package/dist/sandbox-DxP3IpUP.js +0 -859
  663. package/dist/sandbox-cli-DtLGH8sL.js +0 -461
  664. package/dist/sandbox-cli-_Tg7lfJ_.js +0 -458
  665. package/dist/security-cli-BRwgbedo.js +0 -462
  666. package/dist/security-cli-D3bSuyZt.js +0 -465
  667. package/dist/server-context-49XFFxFg.js +0 -824
  668. package/dist/server-context-LrlgrZzS.js +0 -824
  669. package/dist/server-node-events-Dm52i7NW.js +0 -231
  670. package/dist/server-node-events-QX523UyF.js +0 -233
  671. package/dist/service-BNVpYcQe.js +0 -642
  672. package/dist/service-D56aMXUB.js +0 -642
  673. package/dist/service-audit-D0X_XAB2.js +0 -488
  674. package/dist/service-audit-qmf6XMmP.js +0 -488
  675. package/dist/session-CrQQLLhx.js +0 -179
  676. package/dist/session-LocsOOWJ.js +0 -181
  677. package/dist/session-Vlce2BAT.js +0 -181
  678. package/dist/session-cost-usage-BwiTZuKl.js +0 -600
  679. package/dist/session-cost-usage-DT9YNXTJ.js +0 -600
  680. package/dist/sessions-BfV53TbG.js +0 -1296
  681. package/dist/sessions-BimpX_km.js +0 -180
  682. package/dist/sessions-DcXpzig0.js +0 -1296
  683. package/dist/sessions-Wd18dukK.js +0 -2038
  684. package/dist/shared-Bsr69u_7.js +0 -77
  685. package/dist/shared-Cgly1vPb.js +0 -66
  686. package/dist/shared-JOo05hST.js +0 -66
  687. package/dist/shared-f7dvQsi7.js +0 -77
  688. package/dist/skill-scanner-CkaVLABv.js +0 -263
  689. package/dist/skills-B-G7UHOa.js +0 -808
  690. package/dist/skills-B5LQx4lT.js +0 -807
  691. package/dist/skills-cli-DUGe2ZWW.js +0 -286
  692. package/dist/skills-cli-DtOk0bvK.js +0 -289
  693. package/dist/skills-status-Clq9ZnYu.js +0 -166
  694. package/dist/skills-status-JQluhU-P.js +0 -166
  695. package/dist/sqlite-BukcjdJa.js +0 -321
  696. package/dist/sqlite-CGcOZZ0C.js +0 -368
  697. package/dist/sqlite-Ck6f9KWc.js +0 -453
  698. package/dist/start--xmSFepB.js +0 -372
  699. package/dist/start-BdlZbqrr.js +0 -371
  700. package/dist/status-BgoeFm6g.js +0 -2137
  701. package/dist/status-BjjDrUq7.js +0 -27
  702. package/dist/status-Ct0DgOZ-.js +0 -2132
  703. package/dist/status-RA_uNmK0.js +0 -27
  704. package/dist/status.update-BjOH3GlS.js +0 -79
  705. package/dist/status.update-DLU1qBf0.js +0 -79
  706. package/dist/subagent-registry-9RLdKxES.js +0 -2760
  707. package/dist/subagent-registry-Byuex3zp.js +0 -2759
  708. package/dist/subagent-registry-DOBunBYS.js +0 -14
  709. package/dist/subsystem-Dowf8fSU.js +0 -860
  710. package/dist/system-cli-C5oBpzni.js +0 -79
  711. package/dist/system-cli-DXNKD_Id.js +0 -82
  712. package/dist/systemd-BSrHDyeU.js +0 -452
  713. package/dist/systemd-By5xdSB4.js +0 -452
  714. package/dist/systemd-hints-BtjL_5Rh.js +0 -36
  715. package/dist/systemd-hints-sJmr6cjb.js +0 -36
  716. package/dist/systemd-linger-CTmV2Gci.js +0 -75
  717. package/dist/systemd-linger-CmyqQkeC.js +0 -75
  718. package/dist/table-BL0lJzsm.js +0 -279
  719. package/dist/table-DoiRPsn0.js +0 -279
  720. package/dist/timeout-CswI_K-U.js +0 -232
  721. package/dist/tokens-C-X7wDKj.js +0 -14
  722. package/dist/tokens-DkvqA72p.js +0 -14
  723. package/dist/trash-BJLK1vMn.js +0 -23
  724. package/dist/trash-_x5UZ94k.js +0 -23
  725. package/dist/tui-BHjxDFZC.js +0 -3894
  726. package/dist/tui-CgOocwN8.js +0 -3894
  727. package/dist/tui-cli-5ANH8dE5.js +0 -47
  728. package/dist/tui-cli-BQ4P-JW_.js +0 -50
  729. package/dist/update-LFgxHHPd.js +0 -317
  730. package/dist/update-TxptCqk7.js +0 -317
  731. package/dist/update-check-CWc7YXmc.js +0 -400
  732. package/dist/update-check-IhlWaui6.js +0 -400
  733. package/dist/update-cli-PtXU62w7.js +0 -1105
  734. package/dist/update-cli-Va0EtETG.js +0 -1105
  735. package/dist/update-runner-BLeKFkiB.js +0 -894
  736. package/dist/update-runner-Iuzpc-_y.js +0 -894
  737. package/dist/usage-ApGvBLVg.js +0 -4516
  738. package/dist/utils-Bsw__U-F.js +0 -243
  739. package/dist/web-B6_Ky60G.js +0 -63
  740. package/dist/web-EZLQEWXY.js +0 -46842
  741. package/dist/web-pec8YJUX.js +0 -2203
  742. package/dist/webhooks-cli-BYQKTHTp.js +0 -319
  743. package/dist/webhooks-cli-C2_xtsUQ.js +0 -316
  744. package/dist/whatsapp-actions-C72VCq8f.js +0 -49
  745. package/dist/whatsapp-actions-Ck9Uv0Nw.js +0 -45
  746. package/dist/whatsapp-actions-D0reTj2k.js +0 -53
  747. package/dist/widearea-dns-B6ocX23x.js +0 -127
  748. package/dist/widearea-dns-NsEUNYwz.js +0 -127
  749. package/dist/workspace-Dcfoy5JJ.js +0 -649
  750. package/dist/ws-log-N8R5MvGE.js +0 -267
  751. package/dist/ws-log-gwFxPxj5.js +0 -267
  752. /package/dist/{auto-update-CUeF99gI.js → auto-update-CpF0fycd.js} +0 -0
  753. /package/dist/{auto-update-cgkp9ZTJ.js → auto-update-DNWdO7uF.js} +0 -0
  754. /package/dist/{brew-CVZkr0GU.js → brew-nqf_MiE4.js} +0 -0
  755. /package/dist/{budget-DxYQSekw.js → budget-CPedI-qW.js} +0 -0
  756. /package/dist/{budget-BWBp8Res.js → budget-CRpvqDRX.js} +0 -0
  757. /package/dist/{cli-utils-DtAxdCte.js → cli-utils-C1YHVD4o.js} +0 -0
  758. /package/dist/{command-options-CSbuuqHr.js → command-options-BbponVnw.js} +0 -0
  759. /package/dist/{command-options-Cp1tf96a.js → command-options-s0gnvXnS.js} +0 -0
  760. /package/dist/{constants-O8yBqCBv.js → constants-Dhb6zSIV.js} +0 -0
  761. /package/dist/{dangerous-tools-5ObDWy1N.js → dangerous-tools-DGTtJ_JR.js} +0 -0
  762. /package/dist/{dangerous-tools-Jwr7jqNw.js → dangerous-tools-DxrfTOfT.js} +0 -0
  763. /package/dist/{delivery-queue-B6IHz4Ry.js → delivery-queue-Bxm0nzw7.js} +0 -0
  764. /package/dist/{display-BDOsXu8F.js → display-Jy3UdGzA.js} +0 -0
  765. /package/dist/{errors-CHow2wtt.js → errors-CKaCqKga.js} +0 -0
  766. /package/dist/{exec-BizYYQgP.js → exec-DDmuVVNq.js} +0 -0
  767. /package/dist/{format-Mq6iU0_5.js → format-ByEjgyTF.js} +0 -0
  768. /package/dist/{format-duration-DhWzz_5b.js → format-duration-Aaj5tjJd.js} +0 -0
  769. /package/dist/{format-relative-C6kUHuOj.js → format-relative-79_Y1n2Y.js} +0 -0
  770. /package/dist/{help-format-DUBI91Ti.js → help-format-BMKzarov.js} +0 -0
  771. /package/dist/{helpers-eJFa4K6r.js → helpers-DpEB9Mh0.js} +0 -0
  772. /package/dist/{helpers-DLgbkcEn.js → helpers-FMld9sBT.js} +0 -0
  773. /package/dist/{input-provenance-DJBdpeKk.js → input-provenance-Cy_KnBlP.js} +0 -0
  774. /package/dist/{is-main-Dt9DTcH1.js → is-main-yjaVwMtJ.js} +0 -0
  775. /package/dist/{loader-l2OBdJ8x.js → loader-Br7Vr0zn.js} +0 -0
  776. /package/dist/{loader-BoYxRfcW.js → loader-CkmOrXcC.js} +0 -0
  777. /package/dist/{logging-BdnOSVPD.js → logging-CY-Q5cwf.js} +0 -0
  778. /package/dist/{message-channel-w4F2b2F6.js → message-channel-dua8OOGJ.js} +0 -0
  779. /package/dist/{mime-B1ZoR53M.js → mime-CBg4KybI.js} +0 -0
  780. /package/dist/{model-param-b-DPwyNGn8.js → model-param-b-DW9f0NN8.js} +0 -0
  781. /package/dist/{node-match-8XZnaid6.js → node-match-BV8bTBd4.js} +0 -0
  782. /package/dist/{normalize-GDK8JTNW.js → normalize-_lmlBOW9.js} +0 -0
  783. /package/dist/{openclaw-root-C85WMnVV.js → openclaw-root-JPvmPTf7.js} +0 -0
  784. /package/dist/{outbound-send-deps-ANnAhImn.js → outbound-send-deps-BfUvuWGa.js} +0 -0
  785. /package/dist/{parse-6-2MDhdT.js → parse-CZRwKocn.js} +0 -0
  786. /package/dist/{parse-log-line-Bqh1SSzC.js → parse-log-line-CvrZEK6A.js} +0 -0
  787. /package/dist/{parse-log-line-DUZCjXbl.js → parse-log-line-mLdat0AH.js} +0 -0
  788. /package/dist/{parse-port-BKB9Exlg.js → parse-port-BSOOdo7I.js} +0 -0
  789. /package/dist/{parse-port-DrfvwwiL.js → parse-port-Y0NK62x1.js} +0 -0
  790. /package/dist/{parse-timeout-Di_tcEmi.js → parse-timeout-DVPQ3n9j.js} +0 -0
  791. /package/dist/{paths-DcVEkYX5.js → paths-DHjlJ6cn.js} +0 -0
  792. /package/dist/{pi-model-discovery-DsRqYJLy.js → pi-model-discovery-DzEIEgHL.js} +0 -0
  793. /package/dist/{plugins-CDJw924T.js → plugins-D6PBOdkn.js} +0 -0
  794. /package/dist/{program-context-Bvn8046-.js → program-context-Q1hkT73c.js} +0 -0
  795. /package/dist/{progress-CbZ2D53A.js → progress-C9Ha1NJh.js} +0 -0
  796. /package/dist/{prompt-style-DKy6qQxR.js → prompt-style-DQi8j03a.js} +0 -0
  797. /package/dist/{prompts-BI__va99.js → prompts-BEHxUC3w.js} +0 -0
  798. /package/dist/{prompts-_dDWkCAz.js → prompts-CSOhuiqe.js} +0 -0
  799. /package/dist/{queue-D_u34pbL.js → queue-BJGo7kAB.js} +0 -0
  800. /package/dist/{queue-PG591iID.js → queue-DYgUbdoq.js} +0 -0
  801. /package/dist/{redact-ClVwO7Nn.js → redact-CyKvdFrg.js} +0 -0
  802. /package/dist/{registry-Bs_DJK9E.js → registry-C5MAYD4V.js} +0 -0
  803. /package/dist/{registry-D_zlP1U-.js → registry-CRrXXVs0.js} +0 -0
  804. /package/dist/{requirements-BzZxj2Wu.js → requirements-CGkxTCu4.js} +0 -0
  805. /package/dist/{requirements-DIW1svgA.js → requirements-CIDaOcbO.js} +0 -0
  806. /package/dist/{runtime-guard-DeOXA_86.js → runtime-guard-nL3Lp8T-.js} +0 -0
  807. /package/dist/{secret-equal-Dghy3xsA.js → secret-equal-DJpmLXlG.js} +0 -0
  808. /package/dist/{send-BhAfdGII.js → send-CTcxgDDU.js} +0 -0
  809. /package/dist/{send-ga9udK1_.js → send-DPezUR3-.js} +0 -0
  810. /package/dist/{send-C2t9xpXI.js → send-DZQTaG7-.js} +0 -0
  811. /package/dist/{send-DigO-i9j.js → send-VDff2gra.js} +0 -0
  812. /package/dist/{send-Dz2BDHll.js → send-bgQNV8d1.js} +0 -0
  813. /package/dist/{session-key-BGiG_JcT.js → session-key-CQT-NR6w.js} +0 -0
  814. /package/dist/{shell-argv-CAq1mLa2.js → shell-argv-n9IueeJQ.js} +0 -0
  815. /package/dist/{skill-scanner-Coo4QoCd.js → skill-scanner-o6NgVMD9.js} +0 -0
  816. /package/dist/{status-CMnlcBVc.js → status-C53kTIXF.js} +0 -0
  817. /package/dist/{status-tDZPwewW.js → status-CZDDA_Sy.js} +0 -0
  818. /package/dist/{system-run-command-X9lDJIy0.js → system-run-command-BCjUffN9.js} +0 -0
  819. /package/dist/{system-run-command-DGk7dwQP.js → system-run-command-CqAqKL9K.js} +0 -0
  820. /package/dist/{tailnet-CuiNECdL.js → tailnet-Ciwjv243.js} +0 -0
  821. /package/dist/{templates-CeYJjVzw.js → templates-37RKpACb.js} +0 -0
  822. /package/dist/{templates-I3Z0xplD.js → templates-DPalk30o.js} +0 -0
  823. /package/dist/{thinking-BXEswx1X.js → thinking-2hxwmvTl.js} +0 -0
  824. /package/dist/{transcript-events-C1hdue6u.js → transcript-events-Bp7fGnwv.js} +0 -0
  825. /package/dist/{transcript-tools-DuyYOkUq.js → transcript-tools-D4Lbxlka.js} +0 -0
  826. /package/dist/{usage-format-BAirWUSO.js → usage-format-6Uar63S0.js} +0 -0
  827. /package/dist/{utils-C9sj30YY.js → utils-DT8uXjFS.js} +0 -0
  828. /package/dist/{wsl-CqyuRvtM.js → wsl-CrPvx2kZ.js} +0 -0
  829. /package/dist/{wsl-ymJYvc9Q.js → wsl-UvJ5dHah.js} +0 -0
@@ -0,0 +1,3246 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
+ import { g as resolveStateDir } from "./paths-BMuHNFxg.js";
3
+ import { t as createSubsystemLogger } from "./subsystem-DfKstnEK.js";
4
+ import { D as truncateUtf16Safe, a as clampNumber$1, b as resolveUserPath, i as clampInt, w as sleep } from "./utils-DZ8pnOD5.js";
5
+ import { n as resolveAgentConfig, r as resolveAgentDir$1, s as resolveAgentWorkspaceDir } from "./agent-scope-CPphqq-U.js";
6
+ import { F as requireApiKey, I as resolveApiKeyForProvider } from "./model-selection-Cqt6aJ0G.js";
7
+ import { t as isTruthyEnvValue } from "./env-v6411I8h.js";
8
+ import { n as formatErrorMessage } from "./errors-Cojm0Kl7.js";
9
+ import { s as resolveSessionTranscriptsDirForAgent } from "./paths-BXQQzXGQ.js";
10
+ import { n as onSessionTranscriptUpdate } from "./transcript-events-C8Tqw4td.js";
11
+ import { a as buildFileEntry, c as ensureDir, d as listMemoryFiles, f as normalizeExtraMemoryPaths, h as runWithConcurrency, i as sessionPathForFile, l as hashText, m as remapChunkLines, n as buildSessionEntry, o as chunkMarkdown, p as parseEmbedding, r as listSessionFilesForAgent, s as cosineSimilarity, t as requireNodeSqlite, u as isMemoryPath } from "./sqlite-dzD-jMjs.js";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import fs$1 from "node:fs/promises";
16
+ import { randomUUID } from "node:crypto";
17
+ import chokidar from "chokidar";
18
+ import { createInterface } from "node:readline";
19
+ import { Readable } from "node:stream";
20
+
21
+ //#region src/agents/memory-search.ts
22
+ const DEFAULT_OPENAI_MODEL = "text-embedding-3-small";
23
+ const DEFAULT_GEMINI_MODEL = "gemini-embedding-001";
24
+ const DEFAULT_VOYAGE_MODEL = "voyage-4-large";
25
+ const DEFAULT_CHUNK_TOKENS = 400;
26
+ const DEFAULT_CHUNK_OVERLAP = 80;
27
+ const DEFAULT_WATCH_DEBOUNCE_MS = 1500;
28
+ const DEFAULT_SESSION_DELTA_BYTES = 1e5;
29
+ const DEFAULT_SESSION_DELTA_MESSAGES = 50;
30
+ const DEFAULT_MAX_RESULTS = 6;
31
+ const DEFAULT_MIN_SCORE = .35;
32
+ const DEFAULT_HYBRID_ENABLED = true;
33
+ const DEFAULT_HYBRID_VECTOR_WEIGHT = .7;
34
+ const DEFAULT_HYBRID_TEXT_WEIGHT = .3;
35
+ const DEFAULT_HYBRID_CANDIDATE_MULTIPLIER = 4;
36
+ const DEFAULT_CACHE_ENABLED = true;
37
+ const DEFAULT_SOURCES = ["memory"];
38
+ function normalizeSources(sources, sessionMemoryEnabled) {
39
+ const normalized = /* @__PURE__ */ new Set();
40
+ const input = sources?.length ? sources : DEFAULT_SOURCES;
41
+ for (const source of input) {
42
+ if (source === "memory") normalized.add("memory");
43
+ if (source === "sessions" && sessionMemoryEnabled) normalized.add("sessions");
44
+ }
45
+ if (normalized.size === 0) normalized.add("memory");
46
+ return Array.from(normalized);
47
+ }
48
+ function resolveStorePath(agentId, raw) {
49
+ const stateDir = resolveStateDir(process.env, os.homedir);
50
+ const fallback = path.join(stateDir, "memory", `${agentId}.sqlite`);
51
+ if (!raw) return fallback;
52
+ return resolveUserPath(raw.includes("{agentId}") ? raw.replaceAll("{agentId}", agentId) : raw);
53
+ }
54
+ function mergeConfig(defaults, overrides, agentId) {
55
+ const enabled = overrides?.enabled ?? defaults?.enabled ?? true;
56
+ const sessionMemory = overrides?.experimental?.sessionMemory ?? defaults?.experimental?.sessionMemory ?? false;
57
+ const provider = overrides?.provider ?? defaults?.provider ?? "auto";
58
+ const defaultRemote = defaults?.remote;
59
+ const overrideRemote = overrides?.remote;
60
+ const includeRemote = Boolean(overrideRemote?.baseUrl || overrideRemote?.apiKey || overrideRemote?.headers || defaultRemote?.baseUrl || defaultRemote?.apiKey || defaultRemote?.headers) || provider === "openai" || provider === "gemini" || provider === "voyage" || provider === "auto";
61
+ const batch = {
62
+ enabled: overrideRemote?.batch?.enabled ?? defaultRemote?.batch?.enabled ?? false,
63
+ wait: overrideRemote?.batch?.wait ?? defaultRemote?.batch?.wait ?? true,
64
+ concurrency: Math.max(1, overrideRemote?.batch?.concurrency ?? defaultRemote?.batch?.concurrency ?? 2),
65
+ pollIntervalMs: overrideRemote?.batch?.pollIntervalMs ?? defaultRemote?.batch?.pollIntervalMs ?? 2e3,
66
+ timeoutMinutes: overrideRemote?.batch?.timeoutMinutes ?? defaultRemote?.batch?.timeoutMinutes ?? 60
67
+ };
68
+ const remote = includeRemote ? {
69
+ baseUrl: overrideRemote?.baseUrl ?? defaultRemote?.baseUrl,
70
+ apiKey: overrideRemote?.apiKey ?? defaultRemote?.apiKey,
71
+ headers: overrideRemote?.headers ?? defaultRemote?.headers,
72
+ batch
73
+ } : void 0;
74
+ const fallback = overrides?.fallback ?? defaults?.fallback ?? "none";
75
+ const modelDefault = provider === "gemini" ? DEFAULT_GEMINI_MODEL : provider === "openai" ? DEFAULT_OPENAI_MODEL : provider === "voyage" ? DEFAULT_VOYAGE_MODEL : void 0;
76
+ const model = overrides?.model ?? defaults?.model ?? modelDefault ?? "";
77
+ const local = {
78
+ modelPath: overrides?.local?.modelPath ?? defaults?.local?.modelPath,
79
+ modelCacheDir: overrides?.local?.modelCacheDir ?? defaults?.local?.modelCacheDir
80
+ };
81
+ const sources = normalizeSources(overrides?.sources ?? defaults?.sources, sessionMemory);
82
+ const rawPaths = [...defaults?.extraPaths ?? [], ...overrides?.extraPaths ?? []].map((value) => value.trim()).filter(Boolean);
83
+ const extraPaths = Array.from(new Set(rawPaths));
84
+ const vector = {
85
+ enabled: overrides?.store?.vector?.enabled ?? defaults?.store?.vector?.enabled ?? true,
86
+ extensionPath: overrides?.store?.vector?.extensionPath ?? defaults?.store?.vector?.extensionPath
87
+ };
88
+ const store = {
89
+ driver: overrides?.store?.driver ?? defaults?.store?.driver ?? "sqlite",
90
+ path: resolveStorePath(agentId, overrides?.store?.path ?? defaults?.store?.path),
91
+ vector
92
+ };
93
+ const chunking = {
94
+ tokens: overrides?.chunking?.tokens ?? defaults?.chunking?.tokens ?? DEFAULT_CHUNK_TOKENS,
95
+ overlap: overrides?.chunking?.overlap ?? defaults?.chunking?.overlap ?? DEFAULT_CHUNK_OVERLAP
96
+ };
97
+ const sync = {
98
+ onSessionStart: overrides?.sync?.onSessionStart ?? defaults?.sync?.onSessionStart ?? true,
99
+ onSearch: overrides?.sync?.onSearch ?? defaults?.sync?.onSearch ?? true,
100
+ watch: overrides?.sync?.watch ?? defaults?.sync?.watch ?? true,
101
+ watchDebounceMs: overrides?.sync?.watchDebounceMs ?? defaults?.sync?.watchDebounceMs ?? DEFAULT_WATCH_DEBOUNCE_MS,
102
+ intervalMinutes: overrides?.sync?.intervalMinutes ?? defaults?.sync?.intervalMinutes ?? 0,
103
+ sessions: {
104
+ deltaBytes: overrides?.sync?.sessions?.deltaBytes ?? defaults?.sync?.sessions?.deltaBytes ?? DEFAULT_SESSION_DELTA_BYTES,
105
+ deltaMessages: overrides?.sync?.sessions?.deltaMessages ?? defaults?.sync?.sessions?.deltaMessages ?? DEFAULT_SESSION_DELTA_MESSAGES
106
+ }
107
+ };
108
+ const query = {
109
+ maxResults: overrides?.query?.maxResults ?? defaults?.query?.maxResults ?? DEFAULT_MAX_RESULTS,
110
+ minScore: overrides?.query?.minScore ?? defaults?.query?.minScore ?? DEFAULT_MIN_SCORE
111
+ };
112
+ const hybrid = {
113
+ enabled: overrides?.query?.hybrid?.enabled ?? defaults?.query?.hybrid?.enabled ?? DEFAULT_HYBRID_ENABLED,
114
+ vectorWeight: overrides?.query?.hybrid?.vectorWeight ?? defaults?.query?.hybrid?.vectorWeight ?? DEFAULT_HYBRID_VECTOR_WEIGHT,
115
+ textWeight: overrides?.query?.hybrid?.textWeight ?? defaults?.query?.hybrid?.textWeight ?? DEFAULT_HYBRID_TEXT_WEIGHT,
116
+ candidateMultiplier: overrides?.query?.hybrid?.candidateMultiplier ?? defaults?.query?.hybrid?.candidateMultiplier ?? DEFAULT_HYBRID_CANDIDATE_MULTIPLIER
117
+ };
118
+ const cache = {
119
+ enabled: overrides?.cache?.enabled ?? defaults?.cache?.enabled ?? DEFAULT_CACHE_ENABLED,
120
+ maxEntries: overrides?.cache?.maxEntries ?? defaults?.cache?.maxEntries
121
+ };
122
+ const overlap = clampNumber$1(chunking.overlap, 0, Math.max(0, chunking.tokens - 1));
123
+ const minScore = clampNumber$1(query.minScore, 0, 1);
124
+ const vectorWeight = clampNumber$1(hybrid.vectorWeight, 0, 1);
125
+ const textWeight = clampNumber$1(hybrid.textWeight, 0, 1);
126
+ const sum = vectorWeight + textWeight;
127
+ const normalizedVectorWeight = sum > 0 ? vectorWeight / sum : DEFAULT_HYBRID_VECTOR_WEIGHT;
128
+ const normalizedTextWeight = sum > 0 ? textWeight / sum : DEFAULT_HYBRID_TEXT_WEIGHT;
129
+ const candidateMultiplier = clampInt(hybrid.candidateMultiplier, 1, 20);
130
+ const deltaBytes = clampInt(sync.sessions.deltaBytes, 0, Number.MAX_SAFE_INTEGER);
131
+ const deltaMessages = clampInt(sync.sessions.deltaMessages, 0, Number.MAX_SAFE_INTEGER);
132
+ return {
133
+ enabled,
134
+ sources,
135
+ extraPaths,
136
+ provider,
137
+ remote,
138
+ experimental: { sessionMemory },
139
+ fallback,
140
+ model,
141
+ local,
142
+ store,
143
+ chunking: {
144
+ tokens: Math.max(1, chunking.tokens),
145
+ overlap
146
+ },
147
+ sync: {
148
+ ...sync,
149
+ sessions: {
150
+ deltaBytes,
151
+ deltaMessages
152
+ }
153
+ },
154
+ query: {
155
+ ...query,
156
+ minScore,
157
+ hybrid: {
158
+ enabled: Boolean(hybrid.enabled),
159
+ vectorWeight: normalizedVectorWeight,
160
+ textWeight: normalizedTextWeight,
161
+ candidateMultiplier
162
+ }
163
+ },
164
+ cache: {
165
+ enabled: Boolean(cache.enabled),
166
+ maxEntries: typeof cache.maxEntries === "number" && Number.isFinite(cache.maxEntries) ? Math.max(1, Math.floor(cache.maxEntries)) : void 0
167
+ }
168
+ };
169
+ }
170
+ function resolveMemorySearchConfig(cfg, agentId) {
171
+ const defaults = cfg.agents?.defaults?.memorySearch;
172
+ const overrides = resolveAgentConfig(cfg, agentId)?.memorySearch;
173
+ const resolved = mergeConfig(defaults, overrides, agentId);
174
+ if (!resolved.enabled) return null;
175
+ return resolved;
176
+ }
177
+
178
+ //#endregion
179
+ //#region src/memory/embeddings-gemini.ts
180
+ const DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
181
+ const DEFAULT_GEMINI_EMBEDDING_MODEL$1 = "gemini-embedding-001";
182
+ const GEMINI_MAX_INPUT_TOKENS = { "text-embedding-004": 2048 };
183
+ const debugEmbeddings$1 = isTruthyEnvValue(process.env.ANIMA_DEBUG_MEMORY_EMBEDDINGS);
184
+ const log$4 = createSubsystemLogger("memory/embeddings");
185
+ const debugLog$1 = (message, meta) => {
186
+ if (!debugEmbeddings$1) return;
187
+ const suffix = meta ? ` ${JSON.stringify(meta)}` : "";
188
+ log$4.raw(`${message}${suffix}`);
189
+ };
190
+ function resolveRemoteApiKey(remoteApiKey) {
191
+ const trimmed = remoteApiKey?.trim();
192
+ if (!trimmed) return;
193
+ if (trimmed === "GOOGLE_API_KEY" || trimmed === "GEMINI_API_KEY") return process.env[trimmed]?.trim();
194
+ return trimmed;
195
+ }
196
+ function normalizeGeminiModel(model) {
197
+ const trimmed = model.trim();
198
+ if (!trimmed) return DEFAULT_GEMINI_EMBEDDING_MODEL$1;
199
+ const withoutPrefix = trimmed.replace(/^models\//, "");
200
+ if (withoutPrefix.startsWith("gemini/")) return withoutPrefix.slice(7);
201
+ if (withoutPrefix.startsWith("google/")) return withoutPrefix.slice(7);
202
+ return withoutPrefix;
203
+ }
204
+ function normalizeGeminiBaseUrl(raw) {
205
+ const trimmed = raw.replace(/\/+$/, "");
206
+ const openAiIndex = trimmed.indexOf("/openai");
207
+ if (openAiIndex > -1) return trimmed.slice(0, openAiIndex);
208
+ return trimmed;
209
+ }
210
+ function buildGeminiModelPath(model) {
211
+ return model.startsWith("models/") ? model : `models/${model}`;
212
+ }
213
+ async function createGeminiEmbeddingProvider(options) {
214
+ const client = await resolveGeminiEmbeddingClient(options);
215
+ const baseUrl = client.baseUrl.replace(/\/$/, "");
216
+ const embedUrl = `${baseUrl}/${client.modelPath}:embedContent`;
217
+ const batchUrl = `${baseUrl}/${client.modelPath}:batchEmbedContents`;
218
+ const embedQuery = async (text) => {
219
+ if (!text.trim()) return [];
220
+ const res = await fetch(embedUrl, {
221
+ method: "POST",
222
+ headers: client.headers,
223
+ body: JSON.stringify({
224
+ content: { parts: [{ text }] },
225
+ taskType: "RETRIEVAL_QUERY"
226
+ })
227
+ });
228
+ if (!res.ok) {
229
+ const payload = await res.text();
230
+ throw new Error(`gemini embeddings failed: ${res.status} ${payload}`);
231
+ }
232
+ return (await res.json()).embedding?.values ?? [];
233
+ };
234
+ const embedBatch = async (texts) => {
235
+ if (texts.length === 0) return [];
236
+ const requests = texts.map((text) => ({
237
+ model: client.modelPath,
238
+ content: { parts: [{ text }] },
239
+ taskType: "RETRIEVAL_DOCUMENT"
240
+ }));
241
+ const res = await fetch(batchUrl, {
242
+ method: "POST",
243
+ headers: client.headers,
244
+ body: JSON.stringify({ requests })
245
+ });
246
+ if (!res.ok) {
247
+ const payload = await res.text();
248
+ throw new Error(`gemini embeddings failed: ${res.status} ${payload}`);
249
+ }
250
+ const payload = await res.json();
251
+ const embeddings = Array.isArray(payload.embeddings) ? payload.embeddings : [];
252
+ return texts.map((_, index) => embeddings[index]?.values ?? []);
253
+ };
254
+ return {
255
+ provider: {
256
+ id: "gemini",
257
+ model: client.model,
258
+ maxInputTokens: GEMINI_MAX_INPUT_TOKENS[client.model],
259
+ embedQuery,
260
+ embedBatch
261
+ },
262
+ client
263
+ };
264
+ }
265
+ async function resolveGeminiEmbeddingClient(options) {
266
+ const remote = options.remote;
267
+ const remoteApiKey = resolveRemoteApiKey(remote?.apiKey);
268
+ const remoteBaseUrl = remote?.baseUrl?.trim();
269
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
270
+ provider: "google",
271
+ cfg: options.config,
272
+ agentDir: options.agentDir
273
+ }), "google");
274
+ const providerConfig = options.config.models?.providers?.google;
275
+ const rawBaseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_GEMINI_BASE_URL;
276
+ const baseUrl = normalizeGeminiBaseUrl(rawBaseUrl);
277
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
278
+ const headers = {
279
+ "Content-Type": "application/json",
280
+ "x-goog-api-key": apiKey,
281
+ ...headerOverrides
282
+ };
283
+ const model = normalizeGeminiModel(options.model);
284
+ const modelPath = buildGeminiModelPath(model);
285
+ debugLog$1("memory embeddings: gemini client", {
286
+ rawBaseUrl,
287
+ baseUrl,
288
+ model,
289
+ modelPath,
290
+ embedEndpoint: `${baseUrl}/${modelPath}:embedContent`,
291
+ batchEndpoint: `${baseUrl}/${modelPath}:batchEmbedContents`
292
+ });
293
+ return {
294
+ baseUrl,
295
+ headers,
296
+ model,
297
+ modelPath
298
+ };
299
+ }
300
+
301
+ //#endregion
302
+ //#region src/memory/embeddings-openai.ts
303
+ const DEFAULT_OPENAI_EMBEDDING_MODEL$1 = "text-embedding-3-small";
304
+ const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
305
+ const OPENAI_MAX_INPUT_TOKENS = {
306
+ "text-embedding-3-small": 8192,
307
+ "text-embedding-3-large": 8192,
308
+ "text-embedding-ada-002": 8191
309
+ };
310
+ function normalizeOpenAiModel(model) {
311
+ const trimmed = model.trim();
312
+ if (!trimmed) return DEFAULT_OPENAI_EMBEDDING_MODEL$1;
313
+ if (trimmed.startsWith("openai/")) return trimmed.slice(7);
314
+ return trimmed;
315
+ }
316
+ async function createOpenAiEmbeddingProvider(options) {
317
+ const client = await resolveOpenAiEmbeddingClient(options);
318
+ const url = `${client.baseUrl.replace(/\/$/, "")}/embeddings`;
319
+ const embed = async (input) => {
320
+ if (input.length === 0) return [];
321
+ const res = await fetch(url, {
322
+ method: "POST",
323
+ headers: client.headers,
324
+ body: JSON.stringify({
325
+ model: client.model,
326
+ input
327
+ })
328
+ });
329
+ if (!res.ok) {
330
+ const text = await res.text();
331
+ throw new Error(`openai embeddings failed: ${res.status} ${text}`);
332
+ }
333
+ return ((await res.json()).data ?? []).map((entry) => entry.embedding ?? []);
334
+ };
335
+ return {
336
+ provider: {
337
+ id: "openai",
338
+ model: client.model,
339
+ maxInputTokens: OPENAI_MAX_INPUT_TOKENS[client.model],
340
+ embedQuery: async (text) => {
341
+ const [vec] = await embed([text]);
342
+ return vec ?? [];
343
+ },
344
+ embedBatch: embed
345
+ },
346
+ client
347
+ };
348
+ }
349
+ async function resolveOpenAiEmbeddingClient(options) {
350
+ const remote = options.remote;
351
+ const remoteApiKey = remote?.apiKey?.trim();
352
+ const remoteBaseUrl = remote?.baseUrl?.trim();
353
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
354
+ provider: "openai",
355
+ cfg: options.config,
356
+ agentDir: options.agentDir
357
+ }), "openai");
358
+ const providerConfig = options.config.models?.providers?.openai;
359
+ const baseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_OPENAI_BASE_URL;
360
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
361
+ return {
362
+ baseUrl,
363
+ headers: {
364
+ "Content-Type": "application/json",
365
+ Authorization: `Bearer ${apiKey}`,
366
+ ...headerOverrides
367
+ },
368
+ model: normalizeOpenAiModel(options.model)
369
+ };
370
+ }
371
+
372
+ //#endregion
373
+ //#region src/memory/embeddings-voyage.ts
374
+ const DEFAULT_VOYAGE_EMBEDDING_MODEL$1 = "voyage-4-large";
375
+ const DEFAULT_VOYAGE_BASE_URL = "https://api.voyageai.com/v1";
376
+ const VOYAGE_MAX_INPUT_TOKENS = {
377
+ "voyage-3": 32e3,
378
+ "voyage-3-lite": 16e3,
379
+ "voyage-code-3": 32e3
380
+ };
381
+ function normalizeVoyageModel(model) {
382
+ const trimmed = model.trim();
383
+ if (!trimmed) return DEFAULT_VOYAGE_EMBEDDING_MODEL$1;
384
+ if (trimmed.startsWith("voyage/")) return trimmed.slice(7);
385
+ return trimmed;
386
+ }
387
+ async function createVoyageEmbeddingProvider(options) {
388
+ const client = await resolveVoyageEmbeddingClient(options);
389
+ const url = `${client.baseUrl.replace(/\/$/, "")}/embeddings`;
390
+ const embed = async (input, input_type) => {
391
+ if (input.length === 0) return [];
392
+ const body = {
393
+ model: client.model,
394
+ input
395
+ };
396
+ if (input_type) body.input_type = input_type;
397
+ const res = await fetch(url, {
398
+ method: "POST",
399
+ headers: client.headers,
400
+ body: JSON.stringify(body)
401
+ });
402
+ if (!res.ok) {
403
+ const text = await res.text();
404
+ throw new Error(`voyage embeddings failed: ${res.status} ${text}`);
405
+ }
406
+ return ((await res.json()).data ?? []).map((entry) => entry.embedding ?? []);
407
+ };
408
+ return {
409
+ provider: {
410
+ id: "voyage",
411
+ model: client.model,
412
+ maxInputTokens: VOYAGE_MAX_INPUT_TOKENS[client.model],
413
+ embedQuery: async (text) => {
414
+ const [vec] = await embed([text], "query");
415
+ return vec ?? [];
416
+ },
417
+ embedBatch: async (texts) => embed(texts, "document")
418
+ },
419
+ client
420
+ };
421
+ }
422
+ async function resolveVoyageEmbeddingClient(options) {
423
+ const remote = options.remote;
424
+ const remoteApiKey = remote?.apiKey?.trim();
425
+ const remoteBaseUrl = remote?.baseUrl?.trim();
426
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
427
+ provider: "voyage",
428
+ cfg: options.config,
429
+ agentDir: options.agentDir
430
+ }), "voyage");
431
+ const providerConfig = options.config.models?.providers?.voyage;
432
+ const baseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_VOYAGE_BASE_URL;
433
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
434
+ return {
435
+ baseUrl,
436
+ headers: {
437
+ "Content-Type": "application/json",
438
+ Authorization: `Bearer ${apiKey}`,
439
+ ...headerOverrides
440
+ },
441
+ model: normalizeVoyageModel(options.model)
442
+ };
443
+ }
444
+
445
+ //#endregion
446
+ //#region src/memory/node-llama.ts
447
+ async function importNodeLlamaCpp() {
448
+ return import("node-llama-cpp");
449
+ }
450
+
451
+ //#endregion
452
+ //#region src/memory/embeddings.ts
453
+ function sanitizeAndNormalizeEmbedding(vec) {
454
+ const sanitized = vec.map((value) => Number.isFinite(value) ? value : 0);
455
+ const magnitude = Math.sqrt(sanitized.reduce((sum, value) => sum + value * value, 0));
456
+ if (magnitude < 1e-10) return sanitized;
457
+ return sanitized.map((value) => value / magnitude);
458
+ }
459
+ const REMOTE_EMBEDDING_PROVIDER_IDS = [
460
+ "openai",
461
+ "gemini",
462
+ "voyage"
463
+ ];
464
+ const DEFAULT_LOCAL_MODEL = "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
465
+ function canAutoSelectLocal(options) {
466
+ const modelPath = options.local?.modelPath?.trim();
467
+ if (!modelPath) return false;
468
+ if (/^(hf:|https?:)/i.test(modelPath)) return false;
469
+ const resolved = resolveUserPath(modelPath);
470
+ try {
471
+ return fs.statSync(resolved).isFile();
472
+ } catch {
473
+ return false;
474
+ }
475
+ }
476
+ function isMissingApiKeyError(err) {
477
+ return formatErrorMessage(err).includes("No API key found for provider");
478
+ }
479
+ async function createLocalEmbeddingProvider(options) {
480
+ const modelPath = options.local?.modelPath?.trim() || DEFAULT_LOCAL_MODEL;
481
+ const modelCacheDir = options.local?.modelCacheDir?.trim();
482
+ const { getLlama, resolveModelFile, LlamaLogLevel } = await importNodeLlamaCpp();
483
+ let llama = null;
484
+ let embeddingModel = null;
485
+ let embeddingContext = null;
486
+ const ensureContext = async () => {
487
+ if (!llama) llama = await getLlama({ logLevel: LlamaLogLevel.error });
488
+ if (!embeddingModel) {
489
+ const resolved = await resolveModelFile(modelPath, modelCacheDir || void 0);
490
+ embeddingModel = await llama.loadModel({ modelPath: resolved });
491
+ }
492
+ if (!embeddingContext) embeddingContext = await embeddingModel.createEmbeddingContext();
493
+ return embeddingContext;
494
+ };
495
+ return {
496
+ id: "local",
497
+ model: modelPath,
498
+ embedQuery: async (text) => {
499
+ const embedding = await (await ensureContext()).getEmbeddingFor(text);
500
+ return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
501
+ },
502
+ embedBatch: async (texts) => {
503
+ const ctx = await ensureContext();
504
+ return await Promise.all(texts.map(async (text) => {
505
+ const embedding = await ctx.getEmbeddingFor(text);
506
+ return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
507
+ }));
508
+ }
509
+ };
510
+ }
511
+ async function createEmbeddingProvider$1(options) {
512
+ const requestedProvider = options.provider;
513
+ const fallback = options.fallback;
514
+ const createProvider = async (id) => {
515
+ if (id === "local") return { provider: await createLocalEmbeddingProvider(options) };
516
+ if (id === "gemini") {
517
+ const { provider, client } = await createGeminiEmbeddingProvider(options);
518
+ return {
519
+ provider,
520
+ gemini: client
521
+ };
522
+ }
523
+ if (id === "voyage") {
524
+ const { provider, client } = await createVoyageEmbeddingProvider(options);
525
+ return {
526
+ provider,
527
+ voyage: client
528
+ };
529
+ }
530
+ const { provider, client } = await createOpenAiEmbeddingProvider(options);
531
+ return {
532
+ provider,
533
+ openAi: client
534
+ };
535
+ };
536
+ const formatPrimaryError = (err, provider) => provider === "local" ? formatLocalSetupError(err) : formatErrorMessage(err);
537
+ if (requestedProvider === "auto") {
538
+ const missingKeyErrors = [];
539
+ let localError = null;
540
+ if (canAutoSelectLocal(options)) try {
541
+ return {
542
+ ...await createProvider("local"),
543
+ requestedProvider
544
+ };
545
+ } catch (err) {
546
+ localError = formatLocalSetupError(err);
547
+ }
548
+ for (const provider of REMOTE_EMBEDDING_PROVIDER_IDS) try {
549
+ return {
550
+ ...await createProvider(provider),
551
+ requestedProvider
552
+ };
553
+ } catch (err) {
554
+ const message = formatPrimaryError(err, provider);
555
+ if (isMissingApiKeyError(err)) {
556
+ missingKeyErrors.push(message);
557
+ continue;
558
+ }
559
+ throw new Error(message, { cause: err });
560
+ }
561
+ const details = [...missingKeyErrors, localError].filter(Boolean);
562
+ if (details.length > 0) throw new Error(details.join("\n\n"));
563
+ throw new Error("No embeddings provider available.");
564
+ }
565
+ try {
566
+ return {
567
+ ...await createProvider(requestedProvider),
568
+ requestedProvider
569
+ };
570
+ } catch (primaryErr) {
571
+ const reason = formatPrimaryError(primaryErr, requestedProvider);
572
+ if (fallback && fallback !== "none" && fallback !== requestedProvider) try {
573
+ return {
574
+ ...await createProvider(fallback),
575
+ requestedProvider,
576
+ fallbackFrom: requestedProvider,
577
+ fallbackReason: reason
578
+ };
579
+ } catch (fallbackErr) {
580
+ throw new Error(`${reason}\n\nFallback to ${fallback} failed: ${formatErrorMessage(fallbackErr)}`, { cause: fallbackErr });
581
+ }
582
+ throw new Error(reason, { cause: primaryErr });
583
+ }
584
+ }
585
+ function isNodeLlamaCppMissing(err) {
586
+ if (!(err instanceof Error)) return false;
587
+ if (err.code === "ERR_MODULE_NOT_FOUND") return err.message.includes("node-llama-cpp");
588
+ return false;
589
+ }
590
+ function formatLocalSetupError(err) {
591
+ const detail = formatErrorMessage(err);
592
+ const missing = isNodeLlamaCppMissing(err);
593
+ return [
594
+ "Local embeddings unavailable.",
595
+ missing ? "Reason: optional dependency node-llama-cpp is missing (or failed to install)." : detail ? `Reason: ${detail}` : void 0,
596
+ missing && detail ? `Detail: ${detail}` : null,
597
+ "To enable local embeddings:",
598
+ "1) Use Node 22 LTS (recommended for installs/updates)",
599
+ missing ? "2) Reinstall Anima (this should install node-llama-cpp): npm i -g anima@latest" : null,
600
+ "3) If you use pnpm: pnpm approve-builds (select node-llama-cpp), then pnpm rebuild node-llama-cpp",
601
+ ...REMOTE_EMBEDDING_PROVIDER_IDS.map((provider) => `Or set agents.defaults.memorySearch.provider = "${provider}" (remote).`)
602
+ ].filter(Boolean).join("\n");
603
+ }
604
+
605
+ //#endregion
606
+ //#region src/memory/hybrid.ts
607
+ function buildFtsQuery(raw) {
608
+ const tokens = raw.match(/[A-Za-z0-9_]+/g)?.map((t) => t.trim()).filter(Boolean) ?? [];
609
+ if (tokens.length === 0) return null;
610
+ return tokens.map((t) => `"${t.replaceAll("\"", "")}"`).join(" AND ");
611
+ }
612
+ function bm25RankToScore(rank) {
613
+ return 1 / (1 + (Number.isFinite(rank) ? Math.max(0, rank) : 999));
614
+ }
615
+ function mergeHybridResults(params) {
616
+ const byId = /* @__PURE__ */ new Map();
617
+ for (const r of params.vector) byId.set(r.id, {
618
+ id: r.id,
619
+ path: r.path,
620
+ startLine: r.startLine,
621
+ endLine: r.endLine,
622
+ source: r.source,
623
+ snippet: r.snippet,
624
+ vectorScore: r.vectorScore,
625
+ textScore: 0
626
+ });
627
+ for (const r of params.keyword) {
628
+ const existing = byId.get(r.id);
629
+ if (existing) {
630
+ existing.textScore = r.textScore;
631
+ if (r.snippet && r.snippet.length > 0) existing.snippet = r.snippet;
632
+ } else byId.set(r.id, {
633
+ id: r.id,
634
+ path: r.path,
635
+ startLine: r.startLine,
636
+ endLine: r.endLine,
637
+ source: r.source,
638
+ snippet: r.snippet,
639
+ vectorScore: 0,
640
+ textScore: r.textScore
641
+ });
642
+ }
643
+ return Array.from(byId.values()).map((entry) => {
644
+ const score = params.vectorWeight * entry.vectorScore + params.textWeight * entry.textScore;
645
+ return {
646
+ path: entry.path,
647
+ startLine: entry.startLine,
648
+ endLine: entry.endLine,
649
+ score,
650
+ snippet: entry.snippet,
651
+ source: entry.source
652
+ };
653
+ }).toSorted((a, b) => b.score - a.score);
654
+ }
655
+
656
+ //#endregion
657
+ //#region src/memory/batch-gemini.ts
658
+ const GEMINI_BATCH_MAX_REQUESTS = 5e4;
659
+ const debugEmbeddings = isTruthyEnvValue(process.env.ANIMA_DEBUG_MEMORY_EMBEDDINGS);
660
+ const log$3 = createSubsystemLogger("memory/embeddings");
661
+ const debugLog = (message, meta) => {
662
+ if (!debugEmbeddings) return;
663
+ const suffix = meta ? ` ${JSON.stringify(meta)}` : "";
664
+ log$3.raw(`${message}${suffix}`);
665
+ };
666
+ function getGeminiBaseUrl(gemini) {
667
+ return gemini.baseUrl?.replace(/\/$/, "") ?? "";
668
+ }
669
+ function getGeminiHeaders(gemini, params) {
670
+ const headers = gemini.headers ? { ...gemini.headers } : {};
671
+ if (params.json) {
672
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
673
+ } else {
674
+ delete headers["Content-Type"];
675
+ delete headers["content-type"];
676
+ }
677
+ return headers;
678
+ }
679
+ function getGeminiUploadUrl(baseUrl) {
680
+ if (baseUrl.includes("/v1beta")) return baseUrl.replace(/\/v1beta\/?$/, "/upload/v1beta");
681
+ return `${baseUrl.replace(/\/$/, "")}/upload`;
682
+ }
683
+ function splitGeminiBatchRequests(requests) {
684
+ if (requests.length <= GEMINI_BATCH_MAX_REQUESTS) return [requests];
685
+ const groups = [];
686
+ for (let i = 0; i < requests.length; i += GEMINI_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + GEMINI_BATCH_MAX_REQUESTS));
687
+ return groups;
688
+ }
689
+ function buildGeminiUploadBody(params) {
690
+ const boundary = `anima-${hashText(params.displayName)}`;
691
+ const jsonPart = JSON.stringify({ file: {
692
+ displayName: params.displayName,
693
+ mimeType: "application/jsonl"
694
+ } });
695
+ const delimiter = `--${boundary}\r\n`;
696
+ const closeDelimiter = `--${boundary}--\r\n`;
697
+ const parts = [
698
+ `${delimiter}Content-Type: application/json; charset=UTF-8\r\n\r\n${jsonPart}\r\n`,
699
+ `${delimiter}Content-Type: application/jsonl; charset=UTF-8\r\n\r\n${params.jsonl}\r\n`,
700
+ closeDelimiter
701
+ ];
702
+ return {
703
+ body: new Blob([parts.join("")], { type: "multipart/related" }),
704
+ contentType: `multipart/related; boundary=${boundary}`
705
+ };
706
+ }
707
+ async function submitGeminiBatch(params) {
708
+ const baseUrl = getGeminiBaseUrl(params.gemini);
709
+ const uploadPayload = buildGeminiUploadBody({
710
+ jsonl: params.requests.map((request) => JSON.stringify({
711
+ key: request.custom_id,
712
+ request: {
713
+ content: request.content,
714
+ task_type: request.taskType
715
+ }
716
+ })).join("\n"),
717
+ displayName: `memory-embeddings-${hashText(String(Date.now()))}`
718
+ });
719
+ const uploadUrl = `${getGeminiUploadUrl(baseUrl)}/files?uploadType=multipart`;
720
+ debugLog("memory embeddings: gemini batch upload", {
721
+ uploadUrl,
722
+ baseUrl,
723
+ requests: params.requests.length
724
+ });
725
+ const fileRes = await fetch(uploadUrl, {
726
+ method: "POST",
727
+ headers: {
728
+ ...getGeminiHeaders(params.gemini, { json: false }),
729
+ "Content-Type": uploadPayload.contentType
730
+ },
731
+ body: uploadPayload.body
732
+ });
733
+ if (!fileRes.ok) {
734
+ const text = await fileRes.text();
735
+ throw new Error(`gemini batch file upload failed: ${fileRes.status} ${text}`);
736
+ }
737
+ const filePayload = await fileRes.json();
738
+ const fileId = filePayload.name ?? filePayload.file?.name;
739
+ if (!fileId) throw new Error("gemini batch file upload failed: missing file id");
740
+ const batchBody = { batch: {
741
+ displayName: `memory-embeddings-${params.agentId}`,
742
+ inputConfig: { file_name: fileId }
743
+ } };
744
+ const batchEndpoint = `${baseUrl}/${params.gemini.modelPath}:asyncBatchEmbedContent`;
745
+ debugLog("memory embeddings: gemini batch create", {
746
+ batchEndpoint,
747
+ fileId
748
+ });
749
+ const batchRes = await fetch(batchEndpoint, {
750
+ method: "POST",
751
+ headers: getGeminiHeaders(params.gemini, { json: true }),
752
+ body: JSON.stringify(batchBody)
753
+ });
754
+ if (batchRes.ok) return await batchRes.json();
755
+ const text = await batchRes.text();
756
+ if (batchRes.status === 404) throw new Error("gemini batch create failed: 404 (asyncBatchEmbedContent not available for this model/baseUrl). Disable remote.batch.enabled or switch providers.");
757
+ throw new Error(`gemini batch create failed: ${batchRes.status} ${text}`);
758
+ }
759
+ async function fetchGeminiBatchStatus(params) {
760
+ const statusUrl = `${getGeminiBaseUrl(params.gemini)}/${params.batchName.startsWith("batches/") ? params.batchName : `batches/${params.batchName}`}`;
761
+ debugLog("memory embeddings: gemini batch status", { statusUrl });
762
+ const res = await fetch(statusUrl, { headers: getGeminiHeaders(params.gemini, { json: true }) });
763
+ if (!res.ok) {
764
+ const text = await res.text();
765
+ throw new Error(`gemini batch status failed: ${res.status} ${text}`);
766
+ }
767
+ return await res.json();
768
+ }
769
+ async function fetchGeminiFileContent(params) {
770
+ const downloadUrl = `${getGeminiBaseUrl(params.gemini)}/${params.fileId.startsWith("files/") ? params.fileId : `files/${params.fileId}`}:download`;
771
+ debugLog("memory embeddings: gemini batch download", { downloadUrl });
772
+ const res = await fetch(downloadUrl, { headers: getGeminiHeaders(params.gemini, { json: true }) });
773
+ if (!res.ok) {
774
+ const text = await res.text();
775
+ throw new Error(`gemini batch file content failed: ${res.status} ${text}`);
776
+ }
777
+ return await res.text();
778
+ }
779
+ function parseGeminiBatchOutput(text) {
780
+ if (!text.trim()) return [];
781
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
782
+ }
783
+ async function waitForGeminiBatch(params) {
784
+ const start = Date.now();
785
+ let current = params.initial;
786
+ while (true) {
787
+ const status = current ?? await fetchGeminiBatchStatus({
788
+ gemini: params.gemini,
789
+ batchName: params.batchName
790
+ });
791
+ const state = status.state ?? "UNKNOWN";
792
+ if ([
793
+ "SUCCEEDED",
794
+ "COMPLETED",
795
+ "DONE"
796
+ ].includes(state)) {
797
+ const outputFileId = status.outputConfig?.file ?? status.outputConfig?.fileId ?? status.metadata?.output?.responsesFile;
798
+ if (!outputFileId) throw new Error(`gemini batch ${params.batchName} completed without output file`);
799
+ return { outputFileId };
800
+ }
801
+ if ([
802
+ "FAILED",
803
+ "CANCELLED",
804
+ "CANCELED",
805
+ "EXPIRED"
806
+ ].includes(state)) {
807
+ const message = status.error?.message ?? "unknown error";
808
+ throw new Error(`gemini batch ${params.batchName} ${state}: ${message}`);
809
+ }
810
+ if (!params.wait) throw new Error(`gemini batch ${params.batchName} still ${state}; wait disabled`);
811
+ if (Date.now() - start > params.timeoutMs) throw new Error(`gemini batch ${params.batchName} timed out after ${params.timeoutMs}ms`);
812
+ params.debug?.(`gemini batch ${params.batchName} ${state}; waiting ${params.pollIntervalMs}ms`);
813
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
814
+ current = void 0;
815
+ }
816
+ }
817
+ async function runGeminiEmbeddingBatches(params) {
818
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
819
+ const groups = splitGeminiBatchRequests(params.requests);
820
+ const byCustomId = /* @__PURE__ */ new Map();
821
+ const tasks = groups.map((group, groupIndex) => async () => {
822
+ const batchInfo = await submitGeminiBatch({
823
+ gemini: params.gemini,
824
+ requests: group,
825
+ agentId: params.agentId
826
+ });
827
+ const batchName = batchInfo.name ?? "";
828
+ if (!batchName) throw new Error("gemini batch create failed: missing batch name");
829
+ params.debug?.("memory embeddings: gemini batch created", {
830
+ batchName,
831
+ state: batchInfo.state,
832
+ group: groupIndex + 1,
833
+ groups: groups.length,
834
+ requests: group.length
835
+ });
836
+ if (!params.wait && batchInfo.state && ![
837
+ "SUCCEEDED",
838
+ "COMPLETED",
839
+ "DONE"
840
+ ].includes(batchInfo.state)) throw new Error(`gemini batch ${batchName} submitted; enable remote.batch.wait to await completion`);
841
+ const completed = batchInfo.state && [
842
+ "SUCCEEDED",
843
+ "COMPLETED",
844
+ "DONE"
845
+ ].includes(batchInfo.state) ? { outputFileId: batchInfo.outputConfig?.file ?? batchInfo.outputConfig?.fileId ?? batchInfo.metadata?.output?.responsesFile ?? "" } : await waitForGeminiBatch({
846
+ gemini: params.gemini,
847
+ batchName,
848
+ wait: params.wait,
849
+ pollIntervalMs: params.pollIntervalMs,
850
+ timeoutMs: params.timeoutMs,
851
+ debug: params.debug,
852
+ initial: batchInfo
853
+ });
854
+ if (!completed.outputFileId) throw new Error(`gemini batch ${batchName} completed without output file`);
855
+ const outputLines = parseGeminiBatchOutput(await fetchGeminiFileContent({
856
+ gemini: params.gemini,
857
+ fileId: completed.outputFileId
858
+ }));
859
+ const errors = [];
860
+ const remaining = new Set(group.map((request) => request.custom_id));
861
+ for (const line of outputLines) {
862
+ const customId = line.key ?? line.custom_id ?? line.request_id;
863
+ if (!customId) continue;
864
+ remaining.delete(customId);
865
+ if (line.error?.message) {
866
+ errors.push(`${customId}: ${line.error.message}`);
867
+ continue;
868
+ }
869
+ if (line.response?.error?.message) {
870
+ errors.push(`${customId}: ${line.response.error.message}`);
871
+ continue;
872
+ }
873
+ const embedding = line.embedding?.values ?? line.response?.embedding?.values ?? [];
874
+ if (embedding.length === 0) {
875
+ errors.push(`${customId}: empty embedding`);
876
+ continue;
877
+ }
878
+ byCustomId.set(customId, embedding);
879
+ }
880
+ if (errors.length > 0) throw new Error(`gemini batch ${batchName} failed: ${errors.join("; ")}`);
881
+ if (remaining.size > 0) throw new Error(`gemini batch ${batchName} missing ${remaining.size} embedding responses`);
882
+ });
883
+ params.debug?.("memory embeddings: gemini batch submit", {
884
+ requests: params.requests.length,
885
+ groups: groups.length,
886
+ wait: params.wait,
887
+ concurrency: params.concurrency,
888
+ pollIntervalMs: params.pollIntervalMs,
889
+ timeoutMs: params.timeoutMs
890
+ });
891
+ await runWithConcurrency(tasks, params.concurrency);
892
+ return byCustomId;
893
+ }
894
+
895
+ //#endregion
896
+ //#region src/infra/retry.ts
897
+ const DEFAULT_RETRY_CONFIG = {
898
+ attempts: 3,
899
+ minDelayMs: 300,
900
+ maxDelayMs: 3e4,
901
+ jitter: 0
902
+ };
903
+ const asFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
904
+ const clampNumber = (value, fallback, min, max) => {
905
+ const next = asFiniteNumber(value);
906
+ if (next === void 0) return fallback;
907
+ const floor = typeof min === "number" ? min : Number.NEGATIVE_INFINITY;
908
+ const ceiling = typeof max === "number" ? max : Number.POSITIVE_INFINITY;
909
+ return Math.min(Math.max(next, floor), ceiling);
910
+ };
911
+ function resolveRetryConfig(defaults = DEFAULT_RETRY_CONFIG, overrides) {
912
+ const attempts = Math.max(1, Math.round(clampNumber(overrides?.attempts, defaults.attempts, 1)));
913
+ const minDelayMs = Math.max(0, Math.round(clampNumber(overrides?.minDelayMs, defaults.minDelayMs, 0)));
914
+ return {
915
+ attempts,
916
+ minDelayMs,
917
+ maxDelayMs: Math.max(minDelayMs, Math.round(clampNumber(overrides?.maxDelayMs, defaults.maxDelayMs, 0))),
918
+ jitter: clampNumber(overrides?.jitter, defaults.jitter, 0, 1)
919
+ };
920
+ }
921
+ function applyJitter(delayMs, jitter) {
922
+ if (jitter <= 0) return delayMs;
923
+ const offset = (Math.random() * 2 - 1) * jitter;
924
+ return Math.max(0, Math.round(delayMs * (1 + offset)));
925
+ }
926
+ async function retryAsync(fn, attemptsOrOptions = 3, initialDelayMs = 300) {
927
+ if (typeof attemptsOrOptions === "number") {
928
+ const attempts = Math.max(1, Math.round(attemptsOrOptions));
929
+ let lastErr;
930
+ for (let i = 0; i < attempts; i += 1) try {
931
+ return await fn();
932
+ } catch (err) {
933
+ lastErr = err;
934
+ if (i === attempts - 1) break;
935
+ await sleep(initialDelayMs * 2 ** i);
936
+ }
937
+ throw lastErr ?? /* @__PURE__ */ new Error("Retry failed");
938
+ }
939
+ const options = attemptsOrOptions;
940
+ const resolved = resolveRetryConfig(DEFAULT_RETRY_CONFIG, options);
941
+ const maxAttempts = resolved.attempts;
942
+ const minDelayMs = resolved.minDelayMs;
943
+ const maxDelayMs = Number.isFinite(resolved.maxDelayMs) && resolved.maxDelayMs > 0 ? resolved.maxDelayMs : Number.POSITIVE_INFINITY;
944
+ const jitter = resolved.jitter;
945
+ const shouldRetry = options.shouldRetry ?? (() => true);
946
+ let lastErr;
947
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) try {
948
+ return await fn();
949
+ } catch (err) {
950
+ lastErr = err;
951
+ if (attempt >= maxAttempts || !shouldRetry(err, attempt)) break;
952
+ const retryAfterMs = options.retryAfterMs?.(err);
953
+ const baseDelay = typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? Math.max(retryAfterMs, minDelayMs) : minDelayMs * 2 ** (attempt - 1);
954
+ let delay = Math.min(baseDelay, maxDelayMs);
955
+ delay = applyJitter(delay, jitter);
956
+ delay = Math.min(Math.max(delay, minDelayMs), maxDelayMs);
957
+ options.onRetry?.({
958
+ attempt,
959
+ maxAttempts,
960
+ delayMs: delay,
961
+ err,
962
+ label: options.label
963
+ });
964
+ await sleep(delay);
965
+ }
966
+ throw lastErr ?? /* @__PURE__ */ new Error("Retry failed");
967
+ }
968
+
969
+ //#endregion
970
+ //#region src/memory/batch-http.ts
971
+ async function postJsonWithRetry(params) {
972
+ return await (await retryAsync(async () => {
973
+ const res = await fetch(params.url, {
974
+ method: "POST",
975
+ headers: params.headers,
976
+ body: JSON.stringify(params.body)
977
+ });
978
+ if (!res.ok) {
979
+ const text = await res.text();
980
+ const err = /* @__PURE__ */ new Error(`${params.errorPrefix}: ${res.status} ${text}`);
981
+ err.status = res.status;
982
+ throw err;
983
+ }
984
+ return res;
985
+ }, {
986
+ attempts: 3,
987
+ minDelayMs: 300,
988
+ maxDelayMs: 2e3,
989
+ jitter: .2,
990
+ shouldRetry: (err) => {
991
+ const status = err.status;
992
+ return status === 429 || typeof status === "number" && status >= 500;
993
+ }
994
+ })).json();
995
+ }
996
+
997
+ //#endregion
998
+ //#region src/memory/batch-output.ts
999
+ function applyEmbeddingBatchOutputLine(params) {
1000
+ const customId = params.line.custom_id;
1001
+ if (!customId) return;
1002
+ params.remaining.delete(customId);
1003
+ const errorMessage = params.line.error?.message;
1004
+ if (errorMessage) {
1005
+ params.errors.push(`${customId}: ${errorMessage}`);
1006
+ return;
1007
+ }
1008
+ const response = params.line.response;
1009
+ if ((response?.status_code ?? 0) >= 400) {
1010
+ const messageFromObject = response?.body && typeof response.body === "object" ? response.body.error?.message : void 0;
1011
+ const messageFromString = typeof response?.body === "string" ? response.body : void 0;
1012
+ params.errors.push(`${customId}: ${messageFromObject ?? messageFromString ?? "unknown error"}`);
1013
+ return;
1014
+ }
1015
+ const embedding = (response?.body && typeof response.body === "object" ? response.body.data ?? [] : [])[0]?.embedding ?? [];
1016
+ if (embedding.length === 0) {
1017
+ params.errors.push(`${customId}: empty embedding`);
1018
+ return;
1019
+ }
1020
+ params.byCustomId.set(customId, embedding);
1021
+ }
1022
+
1023
+ //#endregion
1024
+ //#region src/memory/batch-openai.ts
1025
+ const OPENAI_BATCH_ENDPOINT = "/v1/embeddings";
1026
+ const OPENAI_BATCH_COMPLETION_WINDOW = "24h";
1027
+ const OPENAI_BATCH_MAX_REQUESTS = 5e4;
1028
+ function getOpenAiBaseUrl(openAi) {
1029
+ return openAi.baseUrl?.replace(/\/$/, "") ?? "";
1030
+ }
1031
+ function getOpenAiHeaders(openAi, params) {
1032
+ const headers = openAi.headers ? { ...openAi.headers } : {};
1033
+ if (params.json) {
1034
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
1035
+ } else {
1036
+ delete headers["Content-Type"];
1037
+ delete headers["content-type"];
1038
+ }
1039
+ return headers;
1040
+ }
1041
+ function splitOpenAiBatchRequests(requests) {
1042
+ if (requests.length <= OPENAI_BATCH_MAX_REQUESTS) return [requests];
1043
+ const groups = [];
1044
+ for (let i = 0; i < requests.length; i += OPENAI_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + OPENAI_BATCH_MAX_REQUESTS));
1045
+ return groups;
1046
+ }
1047
+ async function submitOpenAiBatch(params) {
1048
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1049
+ const jsonl = params.requests.map((request) => JSON.stringify(request)).join("\n");
1050
+ const form = new FormData();
1051
+ form.append("purpose", "batch");
1052
+ form.append("file", new Blob([jsonl], { type: "application/jsonl" }), `memory-embeddings.${hashText(String(Date.now()))}.jsonl`);
1053
+ const fileRes = await fetch(`${baseUrl}/files`, {
1054
+ method: "POST",
1055
+ headers: getOpenAiHeaders(params.openAi, { json: false }),
1056
+ body: form
1057
+ });
1058
+ if (!fileRes.ok) {
1059
+ const text = await fileRes.text();
1060
+ throw new Error(`openai batch file upload failed: ${fileRes.status} ${text}`);
1061
+ }
1062
+ const filePayload = await fileRes.json();
1063
+ if (!filePayload.id) throw new Error("openai batch file upload failed: missing file id");
1064
+ return await postJsonWithRetry({
1065
+ url: `${baseUrl}/batches`,
1066
+ headers: getOpenAiHeaders(params.openAi, { json: true }),
1067
+ body: {
1068
+ input_file_id: filePayload.id,
1069
+ endpoint: OPENAI_BATCH_ENDPOINT,
1070
+ completion_window: OPENAI_BATCH_COMPLETION_WINDOW,
1071
+ metadata: {
1072
+ source: "anima-memory",
1073
+ agent: params.agentId
1074
+ }
1075
+ },
1076
+ errorPrefix: "openai batch create failed"
1077
+ });
1078
+ }
1079
+ async function fetchOpenAiBatchStatus(params) {
1080
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1081
+ const res = await fetch(`${baseUrl}/batches/${params.batchId}`, { headers: getOpenAiHeaders(params.openAi, { json: true }) });
1082
+ if (!res.ok) {
1083
+ const text = await res.text();
1084
+ throw new Error(`openai batch status failed: ${res.status} ${text}`);
1085
+ }
1086
+ return await res.json();
1087
+ }
1088
+ async function fetchOpenAiFileContent(params) {
1089
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1090
+ const res = await fetch(`${baseUrl}/files/${params.fileId}/content`, { headers: getOpenAiHeaders(params.openAi, { json: true }) });
1091
+ if (!res.ok) {
1092
+ const text = await res.text();
1093
+ throw new Error(`openai batch file content failed: ${res.status} ${text}`);
1094
+ }
1095
+ return await res.text();
1096
+ }
1097
+ function parseOpenAiBatchOutput(text) {
1098
+ if (!text.trim()) return [];
1099
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
1100
+ }
1101
+ async function readOpenAiBatchError(params) {
1102
+ try {
1103
+ const first = parseOpenAiBatchOutput(await fetchOpenAiFileContent({
1104
+ openAi: params.openAi,
1105
+ fileId: params.errorFileId
1106
+ })).find((line) => line.error?.message || line.response?.body?.error);
1107
+ return first?.error?.message ?? (typeof first?.response?.body?.error?.message === "string" ? first?.response?.body?.error?.message : void 0);
1108
+ } catch (err) {
1109
+ const message = err instanceof Error ? err.message : String(err);
1110
+ return message ? `error file unavailable: ${message}` : void 0;
1111
+ }
1112
+ }
1113
+ async function waitForOpenAiBatch(params) {
1114
+ const start = Date.now();
1115
+ let current = params.initial;
1116
+ while (true) {
1117
+ const status = current ?? await fetchOpenAiBatchStatus({
1118
+ openAi: params.openAi,
1119
+ batchId: params.batchId
1120
+ });
1121
+ const state = status.status ?? "unknown";
1122
+ if (state === "completed") {
1123
+ if (!status.output_file_id) throw new Error(`openai batch ${params.batchId} completed without output file`);
1124
+ return {
1125
+ outputFileId: status.output_file_id,
1126
+ errorFileId: status.error_file_id ?? void 0
1127
+ };
1128
+ }
1129
+ if ([
1130
+ "failed",
1131
+ "expired",
1132
+ "cancelled",
1133
+ "canceled"
1134
+ ].includes(state)) {
1135
+ const detail = status.error_file_id ? await readOpenAiBatchError({
1136
+ openAi: params.openAi,
1137
+ errorFileId: status.error_file_id
1138
+ }) : void 0;
1139
+ const suffix = detail ? `: ${detail}` : "";
1140
+ throw new Error(`openai batch ${params.batchId} ${state}${suffix}`);
1141
+ }
1142
+ if (!params.wait) throw new Error(`openai batch ${params.batchId} still ${state}; wait disabled`);
1143
+ if (Date.now() - start > params.timeoutMs) throw new Error(`openai batch ${params.batchId} timed out after ${params.timeoutMs}ms`);
1144
+ params.debug?.(`openai batch ${params.batchId} ${state}; waiting ${params.pollIntervalMs}ms`);
1145
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
1146
+ current = void 0;
1147
+ }
1148
+ }
1149
+ async function runOpenAiEmbeddingBatches(params) {
1150
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
1151
+ const groups = splitOpenAiBatchRequests(params.requests);
1152
+ const byCustomId = /* @__PURE__ */ new Map();
1153
+ const tasks = groups.map((group, groupIndex) => async () => {
1154
+ const batchInfo = await submitOpenAiBatch({
1155
+ openAi: params.openAi,
1156
+ requests: group,
1157
+ agentId: params.agentId
1158
+ });
1159
+ if (!batchInfo.id) throw new Error("openai batch create failed: missing batch id");
1160
+ params.debug?.("memory embeddings: openai batch created", {
1161
+ batchId: batchInfo.id,
1162
+ status: batchInfo.status,
1163
+ group: groupIndex + 1,
1164
+ groups: groups.length,
1165
+ requests: group.length
1166
+ });
1167
+ if (!params.wait && batchInfo.status !== "completed") throw new Error(`openai batch ${batchInfo.id} submitted; enable remote.batch.wait to await completion`);
1168
+ const completed = batchInfo.status === "completed" ? {
1169
+ outputFileId: batchInfo.output_file_id ?? "",
1170
+ errorFileId: batchInfo.error_file_id ?? void 0
1171
+ } : await waitForOpenAiBatch({
1172
+ openAi: params.openAi,
1173
+ batchId: batchInfo.id,
1174
+ wait: params.wait,
1175
+ pollIntervalMs: params.pollIntervalMs,
1176
+ timeoutMs: params.timeoutMs,
1177
+ debug: params.debug,
1178
+ initial: batchInfo
1179
+ });
1180
+ if (!completed.outputFileId) throw new Error(`openai batch ${batchInfo.id} completed without output file`);
1181
+ const outputLines = parseOpenAiBatchOutput(await fetchOpenAiFileContent({
1182
+ openAi: params.openAi,
1183
+ fileId: completed.outputFileId
1184
+ }));
1185
+ const errors = [];
1186
+ const remaining = new Set(group.map((request) => request.custom_id));
1187
+ for (const line of outputLines) applyEmbeddingBatchOutputLine({
1188
+ line,
1189
+ remaining,
1190
+ errors,
1191
+ byCustomId
1192
+ });
1193
+ if (errors.length > 0) throw new Error(`openai batch ${batchInfo.id} failed: ${errors.join("; ")}`);
1194
+ if (remaining.size > 0) throw new Error(`openai batch ${batchInfo.id} missing ${remaining.size} embedding responses`);
1195
+ });
1196
+ params.debug?.("memory embeddings: openai batch submit", {
1197
+ requests: params.requests.length,
1198
+ groups: groups.length,
1199
+ wait: params.wait,
1200
+ concurrency: params.concurrency,
1201
+ pollIntervalMs: params.pollIntervalMs,
1202
+ timeoutMs: params.timeoutMs
1203
+ });
1204
+ await runWithConcurrency(tasks, params.concurrency);
1205
+ return byCustomId;
1206
+ }
1207
+
1208
+ //#endregion
1209
+ //#region src/memory/batch-voyage.ts
1210
+ const VOYAGE_BATCH_ENDPOINT = "/v1/embeddings";
1211
+ const VOYAGE_BATCH_COMPLETION_WINDOW = "12h";
1212
+ const VOYAGE_BATCH_MAX_REQUESTS = 5e4;
1213
+ function getVoyageBaseUrl(client) {
1214
+ return client.baseUrl?.replace(/\/$/, "") ?? "";
1215
+ }
1216
+ function getVoyageHeaders(client, params) {
1217
+ const headers = client.headers ? { ...client.headers } : {};
1218
+ if (params.json) {
1219
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
1220
+ } else {
1221
+ delete headers["Content-Type"];
1222
+ delete headers["content-type"];
1223
+ }
1224
+ return headers;
1225
+ }
1226
+ function splitVoyageBatchRequests(requests) {
1227
+ if (requests.length <= VOYAGE_BATCH_MAX_REQUESTS) return [requests];
1228
+ const groups = [];
1229
+ for (let i = 0; i < requests.length; i += VOYAGE_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + VOYAGE_BATCH_MAX_REQUESTS));
1230
+ return groups;
1231
+ }
1232
+ async function submitVoyageBatch(params) {
1233
+ const baseUrl = getVoyageBaseUrl(params.client);
1234
+ const jsonl = params.requests.map((request) => JSON.stringify(request)).join("\n");
1235
+ const form = new FormData();
1236
+ form.append("purpose", "batch");
1237
+ form.append("file", new Blob([jsonl], { type: "application/jsonl" }), `memory-embeddings.${hashText(String(Date.now()))}.jsonl`);
1238
+ const fileRes = await fetch(`${baseUrl}/files`, {
1239
+ method: "POST",
1240
+ headers: getVoyageHeaders(params.client, { json: false }),
1241
+ body: form
1242
+ });
1243
+ if (!fileRes.ok) {
1244
+ const text = await fileRes.text();
1245
+ throw new Error(`voyage batch file upload failed: ${fileRes.status} ${text}`);
1246
+ }
1247
+ const filePayload = await fileRes.json();
1248
+ if (!filePayload.id) throw new Error("voyage batch file upload failed: missing file id");
1249
+ return await postJsonWithRetry({
1250
+ url: `${baseUrl}/batches`,
1251
+ headers: getVoyageHeaders(params.client, { json: true }),
1252
+ body: {
1253
+ input_file_id: filePayload.id,
1254
+ endpoint: VOYAGE_BATCH_ENDPOINT,
1255
+ completion_window: VOYAGE_BATCH_COMPLETION_WINDOW,
1256
+ request_params: {
1257
+ model: params.client.model,
1258
+ input_type: "document"
1259
+ },
1260
+ metadata: {
1261
+ source: "anima-memory",
1262
+ agent: params.agentId
1263
+ }
1264
+ },
1265
+ errorPrefix: "voyage batch create failed"
1266
+ });
1267
+ }
1268
+ async function fetchVoyageBatchStatus(params) {
1269
+ const baseUrl = getVoyageBaseUrl(params.client);
1270
+ const res = await fetch(`${baseUrl}/batches/${params.batchId}`, { headers: getVoyageHeaders(params.client, { json: true }) });
1271
+ if (!res.ok) {
1272
+ const text = await res.text();
1273
+ throw new Error(`voyage batch status failed: ${res.status} ${text}`);
1274
+ }
1275
+ return await res.json();
1276
+ }
1277
+ async function readVoyageBatchError(params) {
1278
+ try {
1279
+ const baseUrl = getVoyageBaseUrl(params.client);
1280
+ const res = await fetch(`${baseUrl}/files/${params.errorFileId}/content`, { headers: getVoyageHeaders(params.client, { json: true }) });
1281
+ if (!res.ok) {
1282
+ const text = await res.text();
1283
+ throw new Error(`voyage batch error file content failed: ${res.status} ${text}`);
1284
+ }
1285
+ const text = await res.text();
1286
+ if (!text.trim()) return;
1287
+ const first = text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line)).find((line) => line.error?.message || line.response?.body?.error);
1288
+ return first?.error?.message ?? (typeof first?.response?.body?.error?.message === "string" ? first?.response?.body?.error?.message : void 0);
1289
+ } catch (err) {
1290
+ const message = err instanceof Error ? err.message : String(err);
1291
+ return message ? `error file unavailable: ${message}` : void 0;
1292
+ }
1293
+ }
1294
+ async function waitForVoyageBatch(params) {
1295
+ const start = Date.now();
1296
+ let current = params.initial;
1297
+ while (true) {
1298
+ const status = current ?? await fetchVoyageBatchStatus({
1299
+ client: params.client,
1300
+ batchId: params.batchId
1301
+ });
1302
+ const state = status.status ?? "unknown";
1303
+ if (state === "completed") {
1304
+ if (!status.output_file_id) throw new Error(`voyage batch ${params.batchId} completed without output file`);
1305
+ return {
1306
+ outputFileId: status.output_file_id,
1307
+ errorFileId: status.error_file_id ?? void 0
1308
+ };
1309
+ }
1310
+ if ([
1311
+ "failed",
1312
+ "expired",
1313
+ "cancelled",
1314
+ "canceled"
1315
+ ].includes(state)) {
1316
+ const detail = status.error_file_id ? await readVoyageBatchError({
1317
+ client: params.client,
1318
+ errorFileId: status.error_file_id
1319
+ }) : void 0;
1320
+ const suffix = detail ? `: ${detail}` : "";
1321
+ throw new Error(`voyage batch ${params.batchId} ${state}${suffix}`);
1322
+ }
1323
+ if (!params.wait) throw new Error(`voyage batch ${params.batchId} still ${state}; wait disabled`);
1324
+ if (Date.now() - start > params.timeoutMs) throw new Error(`voyage batch ${params.batchId} timed out after ${params.timeoutMs}ms`);
1325
+ params.debug?.(`voyage batch ${params.batchId} ${state}; waiting ${params.pollIntervalMs}ms`);
1326
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
1327
+ current = void 0;
1328
+ }
1329
+ }
1330
+ async function runVoyageEmbeddingBatches(params) {
1331
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
1332
+ const groups = splitVoyageBatchRequests(params.requests);
1333
+ const byCustomId = /* @__PURE__ */ new Map();
1334
+ const tasks = groups.map((group, groupIndex) => async () => {
1335
+ const batchInfo = await submitVoyageBatch({
1336
+ client: params.client,
1337
+ requests: group,
1338
+ agentId: params.agentId
1339
+ });
1340
+ if (!batchInfo.id) throw new Error("voyage batch create failed: missing batch id");
1341
+ params.debug?.("memory embeddings: voyage batch created", {
1342
+ batchId: batchInfo.id,
1343
+ status: batchInfo.status,
1344
+ group: groupIndex + 1,
1345
+ groups: groups.length,
1346
+ requests: group.length
1347
+ });
1348
+ if (!params.wait && batchInfo.status !== "completed") throw new Error(`voyage batch ${batchInfo.id} submitted; enable remote.batch.wait to await completion`);
1349
+ const completed = batchInfo.status === "completed" ? {
1350
+ outputFileId: batchInfo.output_file_id ?? "",
1351
+ errorFileId: batchInfo.error_file_id ?? void 0
1352
+ } : await waitForVoyageBatch({
1353
+ client: params.client,
1354
+ batchId: batchInfo.id,
1355
+ wait: params.wait,
1356
+ pollIntervalMs: params.pollIntervalMs,
1357
+ timeoutMs: params.timeoutMs,
1358
+ debug: params.debug,
1359
+ initial: batchInfo
1360
+ });
1361
+ if (!completed.outputFileId) throw new Error(`voyage batch ${batchInfo.id} completed without output file`);
1362
+ const baseUrl = getVoyageBaseUrl(params.client);
1363
+ const contentRes = await fetch(`${baseUrl}/files/${completed.outputFileId}/content`, { headers: getVoyageHeaders(params.client, { json: true }) });
1364
+ if (!contentRes.ok) {
1365
+ const text = await contentRes.text();
1366
+ throw new Error(`voyage batch file content failed: ${contentRes.status} ${text}`);
1367
+ }
1368
+ const errors = [];
1369
+ const remaining = new Set(group.map((request) => request.custom_id));
1370
+ if (contentRes.body) {
1371
+ const reader = createInterface({
1372
+ input: Readable.fromWeb(contentRes.body),
1373
+ terminal: false
1374
+ });
1375
+ for await (const rawLine of reader) {
1376
+ if (!rawLine.trim()) continue;
1377
+ applyEmbeddingBatchOutputLine({
1378
+ line: JSON.parse(rawLine),
1379
+ remaining,
1380
+ errors,
1381
+ byCustomId
1382
+ });
1383
+ }
1384
+ }
1385
+ if (errors.length > 0) throw new Error(`voyage batch ${batchInfo.id} failed: ${errors.join("; ")}`);
1386
+ if (remaining.size > 0) throw new Error(`voyage batch ${batchInfo.id} missing ${remaining.size} embedding responses`);
1387
+ });
1388
+ params.debug?.("memory embeddings: voyage batch submit", {
1389
+ requests: params.requests.length,
1390
+ groups: groups.length,
1391
+ wait: params.wait,
1392
+ concurrency: params.concurrency,
1393
+ pollIntervalMs: params.pollIntervalMs,
1394
+ timeoutMs: params.timeoutMs
1395
+ });
1396
+ await runWithConcurrency(tasks, params.concurrency);
1397
+ return byCustomId;
1398
+ }
1399
+
1400
+ //#endregion
1401
+ //#region src/memory/embedding-input-limits.ts
1402
+ function estimateUtf8Bytes(text) {
1403
+ if (!text) return 0;
1404
+ return Buffer.byteLength(text, "utf8");
1405
+ }
1406
+ function splitTextToUtf8ByteLimit(text, maxUtf8Bytes) {
1407
+ if (maxUtf8Bytes <= 0) return [text];
1408
+ if (estimateUtf8Bytes(text) <= maxUtf8Bytes) return [text];
1409
+ const parts = [];
1410
+ let cursor = 0;
1411
+ while (cursor < text.length) {
1412
+ let low = cursor + 1;
1413
+ let high = Math.min(text.length, cursor + maxUtf8Bytes);
1414
+ let best = cursor;
1415
+ while (low <= high) {
1416
+ const mid = Math.floor((low + high) / 2);
1417
+ if (estimateUtf8Bytes(text.slice(cursor, mid)) <= maxUtf8Bytes) {
1418
+ best = mid;
1419
+ low = mid + 1;
1420
+ } else high = mid - 1;
1421
+ }
1422
+ if (best <= cursor) best = Math.min(text.length, cursor + 1);
1423
+ if (best < text.length && best > cursor && text.charCodeAt(best - 1) >= 55296 && text.charCodeAt(best - 1) <= 56319 && text.charCodeAt(best) >= 56320 && text.charCodeAt(best) <= 57343) best -= 1;
1424
+ const part = text.slice(cursor, best);
1425
+ if (!part) break;
1426
+ parts.push(part);
1427
+ cursor = best;
1428
+ }
1429
+ return parts;
1430
+ }
1431
+
1432
+ //#endregion
1433
+ //#region src/memory/embedding-model-limits.ts
1434
+ const DEFAULT_EMBEDDING_MAX_INPUT_TOKENS = 8192;
1435
+ const KNOWN_EMBEDDING_MAX_INPUT_TOKENS = {
1436
+ "openai:text-embedding-3-small": 8192,
1437
+ "openai:text-embedding-3-large": 8192,
1438
+ "openai:text-embedding-ada-002": 8191,
1439
+ "gemini:text-embedding-004": 2048,
1440
+ "voyage:voyage-3": 32e3,
1441
+ "voyage:voyage-3-lite": 16e3,
1442
+ "voyage:voyage-code-3": 32e3
1443
+ };
1444
+ function resolveEmbeddingMaxInputTokens(provider) {
1445
+ if (typeof provider.maxInputTokens === "number") return provider.maxInputTokens;
1446
+ const known = KNOWN_EMBEDDING_MAX_INPUT_TOKENS[`${provider.id}:${provider.model}`.toLowerCase()];
1447
+ if (typeof known === "number") return known;
1448
+ if (provider.id.toLowerCase() === "gemini") return 2048;
1449
+ return DEFAULT_EMBEDDING_MAX_INPUT_TOKENS;
1450
+ }
1451
+
1452
+ //#endregion
1453
+ //#region src/memory/embedding-chunk-limits.ts
1454
+ function enforceEmbeddingMaxInputTokens(provider, chunks) {
1455
+ const maxInputTokens = resolveEmbeddingMaxInputTokens(provider);
1456
+ const out = [];
1457
+ for (const chunk of chunks) {
1458
+ if (estimateUtf8Bytes(chunk.text) <= maxInputTokens) {
1459
+ out.push(chunk);
1460
+ continue;
1461
+ }
1462
+ for (const text of splitTextToUtf8ByteLimit(chunk.text, maxInputTokens)) out.push({
1463
+ startLine: chunk.startLine,
1464
+ endLine: chunk.endLine,
1465
+ text,
1466
+ hash: hashText(text)
1467
+ });
1468
+ }
1469
+ return out;
1470
+ }
1471
+
1472
+ //#endregion
1473
+ //#region src/memory/manager-embedding-ops.ts
1474
+ const VECTOR_TABLE$2 = "chunks_vec";
1475
+ const FTS_TABLE$2 = "chunks_fts";
1476
+ const EMBEDDING_CACHE_TABLE$2 = "embedding_cache";
1477
+ const EMBEDDING_BATCH_MAX_TOKENS = 8e3;
1478
+ const EMBEDDING_INDEX_CONCURRENCY = 4;
1479
+ const EMBEDDING_RETRY_MAX_ATTEMPTS = 3;
1480
+ const EMBEDDING_RETRY_BASE_DELAY_MS = 500;
1481
+ const EMBEDDING_RETRY_MAX_DELAY_MS = 8e3;
1482
+ const BATCH_FAILURE_LIMIT$1 = 2;
1483
+ const EMBEDDING_QUERY_TIMEOUT_REMOTE_MS = 6e4;
1484
+ const EMBEDDING_QUERY_TIMEOUT_LOCAL_MS = 5 * 6e4;
1485
+ const EMBEDDING_BATCH_TIMEOUT_REMOTE_MS = 2 * 6e4;
1486
+ const EMBEDDING_BATCH_TIMEOUT_LOCAL_MS = 10 * 6e4;
1487
+ const vectorToBlob$1 = (embedding) => Buffer.from(new Float32Array(embedding).buffer);
1488
+ const log$2 = createSubsystemLogger("memory");
1489
+ var MemoryManagerEmbeddingOps = class {
1490
+ buildEmbeddingBatches(chunks) {
1491
+ const batches = [];
1492
+ let current = [];
1493
+ let currentTokens = 0;
1494
+ for (const chunk of chunks) {
1495
+ const estimate = estimateUtf8Bytes(chunk.text);
1496
+ if (current.length > 0 && currentTokens + estimate > EMBEDDING_BATCH_MAX_TOKENS) {
1497
+ batches.push(current);
1498
+ current = [];
1499
+ currentTokens = 0;
1500
+ }
1501
+ if (current.length === 0 && estimate > EMBEDDING_BATCH_MAX_TOKENS) {
1502
+ batches.push([chunk]);
1503
+ continue;
1504
+ }
1505
+ current.push(chunk);
1506
+ currentTokens += estimate;
1507
+ }
1508
+ if (current.length > 0) batches.push(current);
1509
+ return batches;
1510
+ }
1511
+ loadEmbeddingCache(hashes) {
1512
+ if (!this.cache.enabled) return /* @__PURE__ */ new Map();
1513
+ if (hashes.length === 0) return /* @__PURE__ */ new Map();
1514
+ const unique = [];
1515
+ const seen = /* @__PURE__ */ new Set();
1516
+ for (const hash of hashes) {
1517
+ if (!hash) continue;
1518
+ if (seen.has(hash)) continue;
1519
+ seen.add(hash);
1520
+ unique.push(hash);
1521
+ }
1522
+ if (unique.length === 0) return /* @__PURE__ */ new Map();
1523
+ const out = /* @__PURE__ */ new Map();
1524
+ const baseParams = [
1525
+ this.provider.id,
1526
+ this.provider.model,
1527
+ this.providerKey
1528
+ ];
1529
+ const batchSize = 400;
1530
+ for (let start = 0; start < unique.length; start += batchSize) {
1531
+ const batch = unique.slice(start, start + batchSize);
1532
+ const placeholders = batch.map(() => "?").join(", ");
1533
+ const rows = this.db.prepare(`SELECT hash, embedding FROM ${EMBEDDING_CACHE_TABLE$2}\n WHERE provider = ? AND model = ? AND provider_key = ? AND hash IN (${placeholders})`).all(...baseParams, ...batch);
1534
+ for (const row of rows) out.set(row.hash, parseEmbedding(row.embedding));
1535
+ }
1536
+ return out;
1537
+ }
1538
+ upsertEmbeddingCache(entries) {
1539
+ if (!this.cache.enabled) return;
1540
+ if (entries.length === 0) return;
1541
+ const now = Date.now();
1542
+ const stmt = this.db.prepare(`INSERT INTO ${EMBEDDING_CACHE_TABLE$2} (provider, model, provider_key, hash, embedding, dims, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider, model, provider_key, hash) DO UPDATE SET\n embedding=excluded.embedding,\n dims=excluded.dims,\n updated_at=excluded.updated_at`);
1543
+ for (const entry of entries) {
1544
+ const embedding = entry.embedding ?? [];
1545
+ stmt.run(this.provider.id, this.provider.model, this.providerKey, entry.hash, JSON.stringify(embedding), embedding.length, now);
1546
+ }
1547
+ }
1548
+ pruneEmbeddingCacheIfNeeded() {
1549
+ if (!this.cache.enabled) return;
1550
+ const max = this.cache.maxEntries;
1551
+ if (!max || max <= 0) return;
1552
+ const count = this.db.prepare(`SELECT COUNT(*) as c FROM ${EMBEDDING_CACHE_TABLE$2}`).get()?.c ?? 0;
1553
+ if (count <= max) return;
1554
+ const excess = count - max;
1555
+ this.db.prepare(`DELETE FROM ${EMBEDDING_CACHE_TABLE$2}\n WHERE rowid IN (\n SELECT rowid FROM ${EMBEDDING_CACHE_TABLE$2}\n ORDER BY updated_at ASC\n LIMIT ?\n )`).run(excess);
1556
+ }
1557
+ async embedChunksInBatches(chunks) {
1558
+ if (chunks.length === 0) return [];
1559
+ const cached = this.loadEmbeddingCache(chunks.map((chunk) => chunk.hash));
1560
+ const embeddings = Array.from({ length: chunks.length }, () => []);
1561
+ const missing = [];
1562
+ for (let i = 0; i < chunks.length; i += 1) {
1563
+ const chunk = chunks[i];
1564
+ const hit = chunk?.hash ? cached.get(chunk.hash) : void 0;
1565
+ if (hit && hit.length > 0) embeddings[i] = hit;
1566
+ else if (chunk) missing.push({
1567
+ index: i,
1568
+ chunk
1569
+ });
1570
+ }
1571
+ if (missing.length === 0) return embeddings;
1572
+ const missingChunks = missing.map((m) => m.chunk);
1573
+ const batches = this.buildEmbeddingBatches(missingChunks);
1574
+ const toCache = [];
1575
+ let cursor = 0;
1576
+ for (const batch of batches) {
1577
+ const batchEmbeddings = await this.embedBatchWithRetry(batch.map((chunk) => chunk.text));
1578
+ for (let i = 0; i < batch.length; i += 1) {
1579
+ const item = missing[cursor + i];
1580
+ const embedding = batchEmbeddings[i] ?? [];
1581
+ if (item) {
1582
+ embeddings[item.index] = embedding;
1583
+ toCache.push({
1584
+ hash: item.chunk.hash,
1585
+ embedding
1586
+ });
1587
+ }
1588
+ }
1589
+ cursor += batch.length;
1590
+ }
1591
+ this.upsertEmbeddingCache(toCache);
1592
+ return embeddings;
1593
+ }
1594
+ computeProviderKey() {
1595
+ if (this.provider.id === "openai" && this.openAi) {
1596
+ const entries = Object.entries(this.openAi.headers).filter(([key]) => key.toLowerCase() !== "authorization").toSorted(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value]);
1597
+ return hashText(JSON.stringify({
1598
+ provider: "openai",
1599
+ baseUrl: this.openAi.baseUrl,
1600
+ model: this.openAi.model,
1601
+ headers: entries
1602
+ }));
1603
+ }
1604
+ if (this.provider.id === "gemini" && this.gemini) {
1605
+ const entries = Object.entries(this.gemini.headers).filter(([key]) => {
1606
+ const lower = key.toLowerCase();
1607
+ return lower !== "authorization" && lower !== "x-goog-api-key";
1608
+ }).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value]);
1609
+ return hashText(JSON.stringify({
1610
+ provider: "gemini",
1611
+ baseUrl: this.gemini.baseUrl,
1612
+ model: this.gemini.model,
1613
+ headers: entries
1614
+ }));
1615
+ }
1616
+ return hashText(JSON.stringify({
1617
+ provider: this.provider.id,
1618
+ model: this.provider.model
1619
+ }));
1620
+ }
1621
+ async embedChunksWithBatch(chunks, entry, source) {
1622
+ if (this.provider.id === "openai" && this.openAi) return this.embedChunksWithOpenAiBatch(chunks, entry, source);
1623
+ if (this.provider.id === "gemini" && this.gemini) return this.embedChunksWithGeminiBatch(chunks, entry, source);
1624
+ if (this.provider.id === "voyage" && this.voyage) return this.embedChunksWithVoyageBatch(chunks, entry, source);
1625
+ return this.embedChunksInBatches(chunks);
1626
+ }
1627
+ collectCachedEmbeddings(chunks) {
1628
+ const cached = this.loadEmbeddingCache(chunks.map((chunk) => chunk.hash));
1629
+ const embeddings = Array.from({ length: chunks.length }, () => []);
1630
+ const missing = [];
1631
+ for (let i = 0; i < chunks.length; i += 1) {
1632
+ const chunk = chunks[i];
1633
+ const hit = chunk?.hash ? cached.get(chunk.hash) : void 0;
1634
+ if (hit && hit.length > 0) embeddings[i] = hit;
1635
+ else if (chunk) missing.push({
1636
+ index: i,
1637
+ chunk
1638
+ });
1639
+ }
1640
+ return {
1641
+ embeddings,
1642
+ missing
1643
+ };
1644
+ }
1645
+ buildBatchCustomId(params) {
1646
+ return hashText(`${params.source}:${params.entry.path}:${params.chunk.startLine}:${params.chunk.endLine}:${params.chunk.hash}:${params.index}`);
1647
+ }
1648
+ buildBatchRequests(params) {
1649
+ const requests = [];
1650
+ const mapping = /* @__PURE__ */ new Map();
1651
+ for (const item of params.missing) {
1652
+ const chunk = item.chunk;
1653
+ const customId = this.buildBatchCustomId({
1654
+ source: params.source,
1655
+ entry: params.entry,
1656
+ chunk,
1657
+ index: item.index
1658
+ });
1659
+ mapping.set(customId, {
1660
+ index: item.index,
1661
+ hash: chunk.hash
1662
+ });
1663
+ const built = params.build(chunk);
1664
+ requests.push({
1665
+ custom_id: customId,
1666
+ ...built
1667
+ });
1668
+ }
1669
+ return {
1670
+ requests,
1671
+ mapping
1672
+ };
1673
+ }
1674
+ applyBatchEmbeddings(params) {
1675
+ const toCache = [];
1676
+ for (const [customId, embedding] of params.byCustomId.entries()) {
1677
+ const mapped = params.mapping.get(customId);
1678
+ if (!mapped) continue;
1679
+ params.embeddings[mapped.index] = embedding;
1680
+ toCache.push({
1681
+ hash: mapped.hash,
1682
+ embedding
1683
+ });
1684
+ }
1685
+ this.upsertEmbeddingCache(toCache);
1686
+ }
1687
+ async embedChunksWithVoyageBatch(chunks, entry, source) {
1688
+ const voyage = this.voyage;
1689
+ if (!voyage) return this.embedChunksInBatches(chunks);
1690
+ if (chunks.length === 0) return [];
1691
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1692
+ if (missing.length === 0) return embeddings;
1693
+ const { requests, mapping } = this.buildBatchRequests({
1694
+ missing,
1695
+ entry,
1696
+ source,
1697
+ build: (chunk) => ({ body: { input: chunk.text } })
1698
+ });
1699
+ const batchResult = await this.runBatchWithFallback({
1700
+ provider: "voyage",
1701
+ run: async () => await runVoyageEmbeddingBatches({
1702
+ client: voyage,
1703
+ agentId: this.agentId,
1704
+ requests,
1705
+ wait: this.batch.wait,
1706
+ concurrency: this.batch.concurrency,
1707
+ pollIntervalMs: this.batch.pollIntervalMs,
1708
+ timeoutMs: this.batch.timeoutMs,
1709
+ debug: (message, data) => log$2.debug(message, {
1710
+ ...data,
1711
+ source,
1712
+ chunks: chunks.length
1713
+ })
1714
+ }),
1715
+ fallback: async () => await this.embedChunksInBatches(chunks)
1716
+ });
1717
+ if (Array.isArray(batchResult)) return batchResult;
1718
+ this.applyBatchEmbeddings({
1719
+ byCustomId: batchResult,
1720
+ mapping,
1721
+ embeddings
1722
+ });
1723
+ return embeddings;
1724
+ }
1725
+ async embedChunksWithOpenAiBatch(chunks, entry, source) {
1726
+ const openAi = this.openAi;
1727
+ if (!openAi) return this.embedChunksInBatches(chunks);
1728
+ if (chunks.length === 0) return [];
1729
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1730
+ if (missing.length === 0) return embeddings;
1731
+ const { requests, mapping } = this.buildBatchRequests({
1732
+ missing,
1733
+ entry,
1734
+ source,
1735
+ build: (chunk) => ({
1736
+ method: "POST",
1737
+ url: OPENAI_BATCH_ENDPOINT,
1738
+ body: {
1739
+ model: this.openAi?.model ?? this.provider.model,
1740
+ input: chunk.text
1741
+ }
1742
+ })
1743
+ });
1744
+ const batchResult = await this.runBatchWithFallback({
1745
+ provider: "openai",
1746
+ run: async () => await runOpenAiEmbeddingBatches({
1747
+ openAi,
1748
+ agentId: this.agentId,
1749
+ requests,
1750
+ wait: this.batch.wait,
1751
+ concurrency: this.batch.concurrency,
1752
+ pollIntervalMs: this.batch.pollIntervalMs,
1753
+ timeoutMs: this.batch.timeoutMs,
1754
+ debug: (message, data) => log$2.debug(message, {
1755
+ ...data,
1756
+ source,
1757
+ chunks: chunks.length
1758
+ })
1759
+ }),
1760
+ fallback: async () => await this.embedChunksInBatches(chunks)
1761
+ });
1762
+ if (Array.isArray(batchResult)) return batchResult;
1763
+ this.applyBatchEmbeddings({
1764
+ byCustomId: batchResult,
1765
+ mapping,
1766
+ embeddings
1767
+ });
1768
+ return embeddings;
1769
+ }
1770
+ async embedChunksWithGeminiBatch(chunks, entry, source) {
1771
+ const gemini = this.gemini;
1772
+ if (!gemini) return this.embedChunksInBatches(chunks);
1773
+ if (chunks.length === 0) return [];
1774
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1775
+ if (missing.length === 0) return embeddings;
1776
+ const { requests, mapping } = this.buildBatchRequests({
1777
+ missing,
1778
+ entry,
1779
+ source,
1780
+ build: (chunk) => ({
1781
+ content: { parts: [{ text: chunk.text }] },
1782
+ taskType: "RETRIEVAL_DOCUMENT"
1783
+ })
1784
+ });
1785
+ const batchResult = await this.runBatchWithFallback({
1786
+ provider: "gemini",
1787
+ run: async () => await runGeminiEmbeddingBatches({
1788
+ gemini,
1789
+ agentId: this.agentId,
1790
+ requests,
1791
+ wait: this.batch.wait,
1792
+ concurrency: this.batch.concurrency,
1793
+ pollIntervalMs: this.batch.pollIntervalMs,
1794
+ timeoutMs: this.batch.timeoutMs,
1795
+ debug: (message, data) => log$2.debug(message, {
1796
+ ...data,
1797
+ source,
1798
+ chunks: chunks.length
1799
+ })
1800
+ }),
1801
+ fallback: async () => await this.embedChunksInBatches(chunks)
1802
+ });
1803
+ if (Array.isArray(batchResult)) return batchResult;
1804
+ this.applyBatchEmbeddings({
1805
+ byCustomId: batchResult,
1806
+ mapping,
1807
+ embeddings
1808
+ });
1809
+ return embeddings;
1810
+ }
1811
+ async embedBatchWithRetry(texts) {
1812
+ if (texts.length === 0) return [];
1813
+ let attempt = 0;
1814
+ let delayMs = EMBEDDING_RETRY_BASE_DELAY_MS;
1815
+ while (true) try {
1816
+ const timeoutMs = this.resolveEmbeddingTimeout("batch");
1817
+ log$2.debug("memory embeddings: batch start", {
1818
+ provider: this.provider.id,
1819
+ items: texts.length,
1820
+ timeoutMs
1821
+ });
1822
+ return await this.withTimeout(this.provider.embedBatch(texts), timeoutMs, `memory embeddings batch timed out after ${Math.round(timeoutMs / 1e3)}s`);
1823
+ } catch (err) {
1824
+ const message = err instanceof Error ? err.message : String(err);
1825
+ if (!this.isRetryableEmbeddingError(message) || attempt >= EMBEDDING_RETRY_MAX_ATTEMPTS) throw err;
1826
+ const waitMs = Math.min(EMBEDDING_RETRY_MAX_DELAY_MS, Math.round(delayMs * (1 + Math.random() * .2)));
1827
+ log$2.warn(`memory embeddings rate limited; retrying in ${waitMs}ms`);
1828
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
1829
+ delayMs *= 2;
1830
+ attempt += 1;
1831
+ }
1832
+ }
1833
+ isRetryableEmbeddingError(message) {
1834
+ return /(rate[_ ]limit|too many requests|429|resource has been exhausted|5\d\d|cloudflare)/i.test(message);
1835
+ }
1836
+ resolveEmbeddingTimeout(kind) {
1837
+ const isLocal = this.provider.id === "local";
1838
+ if (kind === "query") return isLocal ? EMBEDDING_QUERY_TIMEOUT_LOCAL_MS : EMBEDDING_QUERY_TIMEOUT_REMOTE_MS;
1839
+ return isLocal ? EMBEDDING_BATCH_TIMEOUT_LOCAL_MS : EMBEDDING_BATCH_TIMEOUT_REMOTE_MS;
1840
+ }
1841
+ async embedQueryWithTimeout(text) {
1842
+ const timeoutMs = this.resolveEmbeddingTimeout("query");
1843
+ log$2.debug("memory embeddings: query start", {
1844
+ provider: this.provider.id,
1845
+ timeoutMs
1846
+ });
1847
+ return await this.withTimeout(this.provider.embedQuery(text), timeoutMs, `memory embeddings query timed out after ${Math.round(timeoutMs / 1e3)}s`);
1848
+ }
1849
+ async withTimeout(promise, timeoutMs, message) {
1850
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return await promise;
1851
+ let timer = null;
1852
+ const timeoutPromise = new Promise((_, reject) => {
1853
+ timer = setTimeout(() => reject(new Error(message)), timeoutMs);
1854
+ });
1855
+ try {
1856
+ return await Promise.race([promise, timeoutPromise]);
1857
+ } finally {
1858
+ if (timer) clearTimeout(timer);
1859
+ }
1860
+ }
1861
+ async withBatchFailureLock(fn) {
1862
+ let release;
1863
+ const wait = this.batchFailureLock;
1864
+ this.batchFailureLock = new Promise((resolve) => {
1865
+ release = resolve;
1866
+ });
1867
+ await wait;
1868
+ try {
1869
+ return await fn();
1870
+ } finally {
1871
+ release();
1872
+ }
1873
+ }
1874
+ async resetBatchFailureCount() {
1875
+ await this.withBatchFailureLock(async () => {
1876
+ if (this.batchFailureCount > 0) log$2.debug("memory embeddings: batch recovered; resetting failure count");
1877
+ this.batchFailureCount = 0;
1878
+ this.batchFailureLastError = void 0;
1879
+ this.batchFailureLastProvider = void 0;
1880
+ });
1881
+ }
1882
+ async recordBatchFailure(params) {
1883
+ return await this.withBatchFailureLock(async () => {
1884
+ if (!this.batch.enabled) return {
1885
+ disabled: true,
1886
+ count: this.batchFailureCount
1887
+ };
1888
+ const increment = params.forceDisable ? BATCH_FAILURE_LIMIT$1 : Math.max(1, params.attempts ?? 1);
1889
+ this.batchFailureCount += increment;
1890
+ this.batchFailureLastError = params.message;
1891
+ this.batchFailureLastProvider = params.provider;
1892
+ const disabled = params.forceDisable || this.batchFailureCount >= BATCH_FAILURE_LIMIT$1;
1893
+ if (disabled) this.batch.enabled = false;
1894
+ return {
1895
+ disabled,
1896
+ count: this.batchFailureCount
1897
+ };
1898
+ });
1899
+ }
1900
+ isBatchTimeoutError(message) {
1901
+ return /timed out|timeout/i.test(message);
1902
+ }
1903
+ async runBatchWithTimeoutRetry(params) {
1904
+ try {
1905
+ return await params.run();
1906
+ } catch (err) {
1907
+ const message = err instanceof Error ? err.message : String(err);
1908
+ if (this.isBatchTimeoutError(message)) {
1909
+ log$2.warn(`memory embeddings: ${params.provider} batch timed out; retrying once`);
1910
+ try {
1911
+ return await params.run();
1912
+ } catch (retryErr) {
1913
+ retryErr.batchAttempts = 2;
1914
+ throw retryErr;
1915
+ }
1916
+ }
1917
+ throw err;
1918
+ }
1919
+ }
1920
+ async runBatchWithFallback(params) {
1921
+ if (!this.batch.enabled) return await params.fallback();
1922
+ try {
1923
+ const result = await this.runBatchWithTimeoutRetry({
1924
+ provider: params.provider,
1925
+ run: params.run
1926
+ });
1927
+ await this.resetBatchFailureCount();
1928
+ return result;
1929
+ } catch (err) {
1930
+ const message = err instanceof Error ? err.message : String(err);
1931
+ const attempts = err.batchAttempts ?? 1;
1932
+ const forceDisable = /asyncBatchEmbedContent not available/i.test(message);
1933
+ const failure = await this.recordBatchFailure({
1934
+ provider: params.provider,
1935
+ message,
1936
+ attempts,
1937
+ forceDisable
1938
+ });
1939
+ const suffix = failure.disabled ? "disabling batch" : "keeping batch enabled";
1940
+ log$2.warn(`memory embeddings: ${params.provider} batch failed (${failure.count}/${BATCH_FAILURE_LIMIT$1}); ${suffix}; falling back to non-batch embeddings: ${message}`);
1941
+ return await params.fallback();
1942
+ }
1943
+ }
1944
+ getIndexConcurrency() {
1945
+ return this.batch.enabled ? this.batch.concurrency : EMBEDDING_INDEX_CONCURRENCY;
1946
+ }
1947
+ async indexFile(entry, options) {
1948
+ const content = options.content ?? await fs$1.readFile(entry.absPath, "utf-8");
1949
+ const chunks = enforceEmbeddingMaxInputTokens(this.provider, chunkMarkdown(content, this.settings.chunking).filter((chunk) => chunk.text.trim().length > 0));
1950
+ if (options.source === "sessions" && "lineMap" in entry) remapChunkLines(chunks, entry.lineMap);
1951
+ const embeddings = this.batch.enabled ? await this.embedChunksWithBatch(chunks, entry, options.source) : await this.embedChunksInBatches(chunks);
1952
+ const sample = embeddings.find((embedding) => embedding.length > 0);
1953
+ const vectorReady = sample ? await this.ensureVectorReady(sample.length) : false;
1954
+ const now = Date.now();
1955
+ if (vectorReady) try {
1956
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$2} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(entry.path, options.source);
1957
+ } catch {}
1958
+ if (this.fts.enabled && this.fts.available) try {
1959
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$2} WHERE path = ? AND source = ? AND model = ?`).run(entry.path, options.source, this.provider.model);
1960
+ } catch {}
1961
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(entry.path, options.source);
1962
+ for (let i = 0; i < chunks.length; i++) {
1963
+ const chunk = chunks[i];
1964
+ const embedding = embeddings[i] ?? [];
1965
+ const id = hashText(`${options.source}:${entry.path}:${chunk.startLine}:${chunk.endLine}:${chunk.hash}:${this.provider.model}`);
1966
+ this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
1967
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1968
+ ON CONFLICT(id) DO UPDATE SET
1969
+ hash=excluded.hash,
1970
+ model=excluded.model,
1971
+ text=excluded.text,
1972
+ embedding=excluded.embedding,
1973
+ updated_at=excluded.updated_at`).run(id, entry.path, options.source, chunk.startLine, chunk.endLine, chunk.hash, this.provider.model, chunk.text, JSON.stringify(embedding), now);
1974
+ if (vectorReady && embedding.length > 0) {
1975
+ try {
1976
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$2} WHERE id = ?`).run(id);
1977
+ } catch {}
1978
+ this.db.prepare(`INSERT INTO ${VECTOR_TABLE$2} (id, embedding) VALUES (?, ?)`).run(id, vectorToBlob$1(embedding));
1979
+ }
1980
+ if (this.fts.enabled && this.fts.available) this.db.prepare(`INSERT INTO ${FTS_TABLE$2} (text, id, path, source, model, start_line, end_line)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(chunk.text, id, entry.path, options.source, this.provider.model, chunk.startLine, chunk.endLine);
1981
+ }
1982
+ this.db.prepare(`INSERT INTO files (path, source, hash, mtime, size) VALUES (?, ?, ?, ?, ?)
1983
+ ON CONFLICT(path) DO UPDATE SET
1984
+ source=excluded.source,
1985
+ hash=excluded.hash,
1986
+ mtime=excluded.mtime,
1987
+ size=excluded.size`).run(entry.path, options.source, entry.hash, entry.mtimeMs, entry.size);
1988
+ }
1989
+ };
1990
+ const memoryManagerEmbeddingOps = MemoryManagerEmbeddingOps.prototype;
1991
+
1992
+ //#endregion
1993
+ //#region src/memory/manager-search.ts
1994
+ const vectorToBlob = (embedding) => Buffer.from(new Float32Array(embedding).buffer);
1995
+ async function searchVector(params) {
1996
+ if (params.queryVec.length === 0 || params.limit <= 0) return [];
1997
+ if (await params.ensureVectorReady(params.queryVec.length)) return params.db.prepare(`SELECT c.id, c.path, c.start_line, c.end_line, c.text,
1998
+ c.source,
1999
+ vec_distance_cosine(v.embedding, ?) AS dist
2000
+ FROM ${params.vectorTable} v\n JOIN chunks c ON c.id = v.id\n WHERE c.model = ?${params.sourceFilterVec.sql}\n ORDER BY dist ASC\n LIMIT ?`).all(vectorToBlob(params.queryVec), params.providerModel, ...params.sourceFilterVec.params, params.limit).map((row) => ({
2001
+ id: row.id,
2002
+ path: row.path,
2003
+ startLine: row.start_line,
2004
+ endLine: row.end_line,
2005
+ score: 1 - row.dist,
2006
+ snippet: truncateUtf16Safe(row.text, params.snippetMaxChars),
2007
+ source: row.source
2008
+ }));
2009
+ return listChunks({
2010
+ db: params.db,
2011
+ providerModel: params.providerModel,
2012
+ sourceFilter: params.sourceFilterChunks
2013
+ }).map((chunk) => ({
2014
+ chunk,
2015
+ score: cosineSimilarity(params.queryVec, chunk.embedding)
2016
+ })).filter((entry) => Number.isFinite(entry.score)).toSorted((a, b) => b.score - a.score).slice(0, params.limit).map((entry) => ({
2017
+ id: entry.chunk.id,
2018
+ path: entry.chunk.path,
2019
+ startLine: entry.chunk.startLine,
2020
+ endLine: entry.chunk.endLine,
2021
+ score: entry.score,
2022
+ snippet: truncateUtf16Safe(entry.chunk.text, params.snippetMaxChars),
2023
+ source: entry.chunk.source
2024
+ }));
2025
+ }
2026
+ function listChunks(params) {
2027
+ return params.db.prepare(`SELECT id, path, start_line, end_line, text, embedding, source
2028
+ FROM chunks
2029
+ WHERE model = ?${params.sourceFilter.sql}`).all(params.providerModel, ...params.sourceFilter.params).map((row) => ({
2030
+ id: row.id,
2031
+ path: row.path,
2032
+ startLine: row.start_line,
2033
+ endLine: row.end_line,
2034
+ text: row.text,
2035
+ embedding: parseEmbedding(row.embedding),
2036
+ source: row.source
2037
+ }));
2038
+ }
2039
+ async function searchKeyword(params) {
2040
+ if (params.limit <= 0) return [];
2041
+ const ftsQuery = params.buildFtsQuery(params.query);
2042
+ if (!ftsQuery) return [];
2043
+ return params.db.prepare(`SELECT id, path, source, start_line, end_line, text,\n bm25(${params.ftsTable}) AS rank\n FROM ${params.ftsTable}\n WHERE ${params.ftsTable} MATCH ? AND model = ?${params.sourceFilter.sql}\n ORDER BY rank ASC\n LIMIT ?`).all(ftsQuery, params.providerModel, ...params.sourceFilter.params, params.limit).map((row) => {
2044
+ const textScore = params.bm25RankToScore(row.rank);
2045
+ return {
2046
+ id: row.id,
2047
+ path: row.path,
2048
+ startLine: row.start_line,
2049
+ endLine: row.end_line,
2050
+ score: textScore,
2051
+ textScore,
2052
+ snippet: truncateUtf16Safe(row.text, params.snippetMaxChars),
2053
+ source: row.source
2054
+ };
2055
+ });
2056
+ }
2057
+
2058
+ //#endregion
2059
+ //#region src/memory/memory-schema.ts
2060
+ function ensureMemoryIndexSchema(params) {
2061
+ params.db.exec(`
2062
+ CREATE TABLE IF NOT EXISTS meta (
2063
+ key TEXT PRIMARY KEY,
2064
+ value TEXT NOT NULL
2065
+ );
2066
+ `);
2067
+ params.db.exec(`
2068
+ CREATE TABLE IF NOT EXISTS files (
2069
+ path TEXT PRIMARY KEY,
2070
+ source TEXT NOT NULL DEFAULT 'memory',
2071
+ hash TEXT NOT NULL,
2072
+ mtime INTEGER NOT NULL,
2073
+ size INTEGER NOT NULL
2074
+ );
2075
+ `);
2076
+ params.db.exec(`
2077
+ CREATE TABLE IF NOT EXISTS chunks (
2078
+ id TEXT PRIMARY KEY,
2079
+ path TEXT NOT NULL,
2080
+ source TEXT NOT NULL DEFAULT 'memory',
2081
+ start_line INTEGER NOT NULL,
2082
+ end_line INTEGER NOT NULL,
2083
+ hash TEXT NOT NULL,
2084
+ model TEXT NOT NULL,
2085
+ text TEXT NOT NULL,
2086
+ embedding TEXT NOT NULL,
2087
+ updated_at INTEGER NOT NULL
2088
+ );
2089
+ `);
2090
+ params.db.exec(`
2091
+ CREATE TABLE IF NOT EXISTS ${params.embeddingCacheTable} (
2092
+ provider TEXT NOT NULL,
2093
+ model TEXT NOT NULL,
2094
+ provider_key TEXT NOT NULL,
2095
+ hash TEXT NOT NULL,
2096
+ embedding TEXT NOT NULL,
2097
+ dims INTEGER,
2098
+ updated_at INTEGER NOT NULL,
2099
+ PRIMARY KEY (provider, model, provider_key, hash)
2100
+ );
2101
+ `);
2102
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${params.embeddingCacheTable}(updated_at);`);
2103
+ let ftsAvailable = false;
2104
+ let ftsError;
2105
+ if (params.ftsEnabled) try {
2106
+ params.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${params.ftsTable} USING fts5(\n text,\n id UNINDEXED,\n path UNINDEXED,\n source UNINDEXED,\n model UNINDEXED,\n start_line UNINDEXED,\n end_line UNINDEXED\n);`);
2107
+ ftsAvailable = true;
2108
+ } catch (err) {
2109
+ const message = err instanceof Error ? err.message : String(err);
2110
+ ftsAvailable = false;
2111
+ ftsError = message;
2112
+ }
2113
+ ensureColumn(params.db, "files", "source", "TEXT NOT NULL DEFAULT 'memory'");
2114
+ ensureColumn(params.db, "chunks", "source", "TEXT NOT NULL DEFAULT 'memory'");
2115
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_path ON chunks(path);`);
2116
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);`);
2117
+ return {
2118
+ ftsAvailable,
2119
+ ...ftsError ? { ftsError } : {}
2120
+ };
2121
+ }
2122
+ function ensureColumn(db, table, column, definition) {
2123
+ if (db.prepare(`PRAGMA table_info(${table})`).all().some((row) => row.name === column)) return;
2124
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
2125
+ }
2126
+
2127
+ //#endregion
2128
+ //#region src/memory/sqlite-vec.ts
2129
+ async function loadSqliteVecExtension(params) {
2130
+ try {
2131
+ const sqliteVec = await import("sqlite-vec");
2132
+ const resolvedPath = params.extensionPath?.trim() ? params.extensionPath.trim() : void 0;
2133
+ const extensionPath = resolvedPath ?? sqliteVec.getLoadablePath();
2134
+ params.db.enableLoadExtension(true);
2135
+ if (resolvedPath) params.db.loadExtension(extensionPath);
2136
+ else sqliteVec.load(params.db);
2137
+ return {
2138
+ ok: true,
2139
+ extensionPath
2140
+ };
2141
+ } catch (err) {
2142
+ return {
2143
+ ok: false,
2144
+ error: err instanceof Error ? err.message : String(err)
2145
+ };
2146
+ }
2147
+ }
2148
+
2149
+ //#endregion
2150
+ //#region src/memory/manager-sync-ops.ts
2151
+ const META_KEY = "memory_index_meta_v1";
2152
+ const VECTOR_TABLE$1 = "chunks_vec";
2153
+ const FTS_TABLE$1 = "chunks_fts";
2154
+ const EMBEDDING_CACHE_TABLE$1 = "embedding_cache";
2155
+ const SESSION_DIRTY_DEBOUNCE_MS = 5e3;
2156
+ const SESSION_DELTA_READ_CHUNK_BYTES = 64 * 1024;
2157
+ const VECTOR_LOAD_TIMEOUT_MS = 3e4;
2158
+ const IGNORED_MEMORY_WATCH_DIR_NAMES = new Set([
2159
+ ".git",
2160
+ "node_modules",
2161
+ ".pnpm-store",
2162
+ ".venv",
2163
+ "venv",
2164
+ ".tox",
2165
+ "__pycache__"
2166
+ ]);
2167
+ const log$1 = createSubsystemLogger("memory");
2168
+ function shouldIgnoreMemoryWatchPath(watchPath) {
2169
+ return path.normalize(watchPath).split(path.sep).map((segment) => segment.trim().toLowerCase()).some((segment) => IGNORED_MEMORY_WATCH_DIR_NAMES.has(segment));
2170
+ }
2171
+ var MemoryManagerSyncOps = class {
2172
+ async ensureVectorReady(dimensions) {
2173
+ if (!this.vector.enabled) return false;
2174
+ if (!this.vectorReady) this.vectorReady = this.withTimeout(this.loadVectorExtension(), VECTOR_LOAD_TIMEOUT_MS, `sqlite-vec load timed out after ${Math.round(VECTOR_LOAD_TIMEOUT_MS / 1e3)}s`);
2175
+ let ready = false;
2176
+ try {
2177
+ ready = await this.vectorReady;
2178
+ } catch (err) {
2179
+ const message = err instanceof Error ? err.message : String(err);
2180
+ this.vector.available = false;
2181
+ this.vector.loadError = message;
2182
+ this.vectorReady = null;
2183
+ log$1.warn(`sqlite-vec unavailable: ${message}`);
2184
+ return false;
2185
+ }
2186
+ if (ready && typeof dimensions === "number" && dimensions > 0) this.ensureVectorTable(dimensions);
2187
+ return ready;
2188
+ }
2189
+ async loadVectorExtension() {
2190
+ if (this.vector.available !== null) return this.vector.available;
2191
+ if (!this.vector.enabled) {
2192
+ this.vector.available = false;
2193
+ return false;
2194
+ }
2195
+ try {
2196
+ const resolvedPath = this.vector.extensionPath?.trim() ? resolveUserPath(this.vector.extensionPath) : void 0;
2197
+ const loaded = await loadSqliteVecExtension({
2198
+ db: this.db,
2199
+ extensionPath: resolvedPath
2200
+ });
2201
+ if (!loaded.ok) throw new Error(loaded.error ?? "unknown sqlite-vec load error");
2202
+ this.vector.extensionPath = loaded.extensionPath;
2203
+ this.vector.available = true;
2204
+ return true;
2205
+ } catch (err) {
2206
+ const message = err instanceof Error ? err.message : String(err);
2207
+ this.vector.available = false;
2208
+ this.vector.loadError = message;
2209
+ log$1.warn(`sqlite-vec unavailable: ${message}`);
2210
+ return false;
2211
+ }
2212
+ }
2213
+ ensureVectorTable(dimensions) {
2214
+ if (this.vector.dims === dimensions) return;
2215
+ if (this.vector.dims && this.vector.dims !== dimensions) this.dropVectorTable();
2216
+ this.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${VECTOR_TABLE$1} USING vec0(\n id TEXT PRIMARY KEY,\n embedding FLOAT[${dimensions}]\n)`);
2217
+ this.vector.dims = dimensions;
2218
+ }
2219
+ dropVectorTable() {
2220
+ try {
2221
+ this.db.exec(`DROP TABLE IF EXISTS ${VECTOR_TABLE$1}`);
2222
+ } catch (err) {
2223
+ const message = err instanceof Error ? err.message : String(err);
2224
+ log$1.debug(`Failed to drop ${VECTOR_TABLE$1}: ${message}`);
2225
+ }
2226
+ }
2227
+ buildSourceFilter(alias) {
2228
+ const sources = Array.from(this.sources);
2229
+ if (sources.length === 0) return {
2230
+ sql: "",
2231
+ params: []
2232
+ };
2233
+ return {
2234
+ sql: ` AND ${alias ? `${alias}.source` : "source"} IN (${sources.map(() => "?").join(", ")})`,
2235
+ params: sources
2236
+ };
2237
+ }
2238
+ openDatabase() {
2239
+ const dbPath = resolveUserPath(this.settings.store.path);
2240
+ return this.openDatabaseAtPath(dbPath);
2241
+ }
2242
+ openDatabaseAtPath(dbPath) {
2243
+ ensureDir(path.dirname(dbPath));
2244
+ const { DatabaseSync } = requireNodeSqlite();
2245
+ return new DatabaseSync(dbPath, { allowExtension: this.settings.store.vector.enabled });
2246
+ }
2247
+ seedEmbeddingCache(sourceDb) {
2248
+ if (!this.cache.enabled) return;
2249
+ try {
2250
+ const rows = sourceDb.prepare(`SELECT provider, model, provider_key, hash, embedding, dims, updated_at FROM ${EMBEDDING_CACHE_TABLE$1}`).all();
2251
+ if (!rows.length) return;
2252
+ const insert = this.db.prepare(`INSERT INTO ${EMBEDDING_CACHE_TABLE$1} (provider, model, provider_key, hash, embedding, dims, updated_at)
2253
+ VALUES (?, ?, ?, ?, ?, ?, ?)
2254
+ ON CONFLICT(provider, model, provider_key, hash) DO UPDATE SET
2255
+ embedding=excluded.embedding,
2256
+ dims=excluded.dims,
2257
+ updated_at=excluded.updated_at`);
2258
+ this.db.exec("BEGIN");
2259
+ for (const row of rows) insert.run(row.provider, row.model, row.provider_key, row.hash, row.embedding, row.dims, row.updated_at);
2260
+ this.db.exec("COMMIT");
2261
+ } catch (err) {
2262
+ try {
2263
+ this.db.exec("ROLLBACK");
2264
+ } catch {}
2265
+ throw err;
2266
+ }
2267
+ }
2268
+ async swapIndexFiles(targetPath, tempPath) {
2269
+ const backupPath = `${targetPath}.backup-${randomUUID()}`;
2270
+ await this.moveIndexFiles(targetPath, backupPath);
2271
+ try {
2272
+ await this.moveIndexFiles(tempPath, targetPath);
2273
+ } catch (err) {
2274
+ await this.moveIndexFiles(backupPath, targetPath);
2275
+ throw err;
2276
+ }
2277
+ await this.removeIndexFiles(backupPath);
2278
+ }
2279
+ async moveIndexFiles(sourceBase, targetBase) {
2280
+ for (const suffix of [
2281
+ "",
2282
+ "-wal",
2283
+ "-shm"
2284
+ ]) {
2285
+ const source = `${sourceBase}${suffix}`;
2286
+ const target = `${targetBase}${suffix}`;
2287
+ try {
2288
+ await fs$1.rename(source, target);
2289
+ } catch (err) {
2290
+ if (err.code !== "ENOENT") throw err;
2291
+ }
2292
+ }
2293
+ }
2294
+ async removeIndexFiles(basePath) {
2295
+ await Promise.all([
2296
+ "",
2297
+ "-wal",
2298
+ "-shm"
2299
+ ].map((suffix) => fs$1.rm(`${basePath}${suffix}`, { force: true })));
2300
+ }
2301
+ ensureSchema() {
2302
+ const result = ensureMemoryIndexSchema({
2303
+ db: this.db,
2304
+ embeddingCacheTable: EMBEDDING_CACHE_TABLE$1,
2305
+ ftsTable: FTS_TABLE$1,
2306
+ ftsEnabled: this.fts.enabled
2307
+ });
2308
+ this.fts.available = result.ftsAvailable;
2309
+ if (result.ftsError) {
2310
+ this.fts.loadError = result.ftsError;
2311
+ log$1.warn(`fts unavailable: ${result.ftsError}`);
2312
+ }
2313
+ }
2314
+ ensureWatcher() {
2315
+ if (!this.sources.has("memory") || !this.settings.sync.watch || this.watcher) return;
2316
+ const watchPaths = new Set([
2317
+ path.join(this.workspaceDir, "MEMORY.md"),
2318
+ path.join(this.workspaceDir, "memory.md"),
2319
+ path.join(this.workspaceDir, "memory", "**", "*.md")
2320
+ ]);
2321
+ const additionalPaths = normalizeExtraMemoryPaths(this.workspaceDir, this.settings.extraPaths);
2322
+ for (const entry of additionalPaths) try {
2323
+ const stat = fs.lstatSync(entry);
2324
+ if (stat.isSymbolicLink()) continue;
2325
+ if (stat.isDirectory()) {
2326
+ watchPaths.add(path.join(entry, "**", "*.md"));
2327
+ continue;
2328
+ }
2329
+ if (stat.isFile() && entry.toLowerCase().endsWith(".md")) watchPaths.add(entry);
2330
+ } catch {}
2331
+ this.watcher = chokidar.watch(Array.from(watchPaths), {
2332
+ ignoreInitial: true,
2333
+ ignored: (watchPath) => shouldIgnoreMemoryWatchPath(String(watchPath)),
2334
+ awaitWriteFinish: {
2335
+ stabilityThreshold: this.settings.sync.watchDebounceMs,
2336
+ pollInterval: 100
2337
+ }
2338
+ });
2339
+ const markDirty = () => {
2340
+ this.dirty = true;
2341
+ this.scheduleWatchSync();
2342
+ };
2343
+ this.watcher.on("add", markDirty);
2344
+ this.watcher.on("change", markDirty);
2345
+ this.watcher.on("unlink", markDirty);
2346
+ }
2347
+ ensureSessionListener() {
2348
+ if (!this.sources.has("sessions") || this.sessionUnsubscribe) return;
2349
+ this.sessionUnsubscribe = onSessionTranscriptUpdate((update) => {
2350
+ if (this.closed) return;
2351
+ const sessionFile = update.sessionFile;
2352
+ if (!this.isSessionFileForAgent(sessionFile)) return;
2353
+ this.scheduleSessionDirty(sessionFile);
2354
+ });
2355
+ }
2356
+ scheduleSessionDirty(sessionFile) {
2357
+ this.sessionPendingFiles.add(sessionFile);
2358
+ if (this.sessionWatchTimer) return;
2359
+ this.sessionWatchTimer = setTimeout(() => {
2360
+ this.sessionWatchTimer = null;
2361
+ this.processSessionDeltaBatch().catch((err) => {
2362
+ log$1.warn(`memory session delta failed: ${String(err)}`);
2363
+ });
2364
+ }, SESSION_DIRTY_DEBOUNCE_MS);
2365
+ }
2366
+ async processSessionDeltaBatch() {
2367
+ if (this.sessionPendingFiles.size === 0) return;
2368
+ const pending = Array.from(this.sessionPendingFiles);
2369
+ this.sessionPendingFiles.clear();
2370
+ let shouldSync = false;
2371
+ for (const sessionFile of pending) {
2372
+ const delta = await this.updateSessionDelta(sessionFile);
2373
+ if (!delta) continue;
2374
+ const bytesThreshold = delta.deltaBytes;
2375
+ const messagesThreshold = delta.deltaMessages;
2376
+ const bytesHit = bytesThreshold <= 0 ? delta.pendingBytes > 0 : delta.pendingBytes >= bytesThreshold;
2377
+ const messagesHit = messagesThreshold <= 0 ? delta.pendingMessages > 0 : delta.pendingMessages >= messagesThreshold;
2378
+ if (!bytesHit && !messagesHit) continue;
2379
+ this.sessionsDirtyFiles.add(sessionFile);
2380
+ this.sessionsDirty = true;
2381
+ delta.pendingBytes = bytesThreshold > 0 ? Math.max(0, delta.pendingBytes - bytesThreshold) : 0;
2382
+ delta.pendingMessages = messagesThreshold > 0 ? Math.max(0, delta.pendingMessages - messagesThreshold) : 0;
2383
+ shouldSync = true;
2384
+ }
2385
+ if (shouldSync) this.sync({ reason: "session-delta" }).catch((err) => {
2386
+ log$1.warn(`memory sync failed (session-delta): ${String(err)}`);
2387
+ });
2388
+ }
2389
+ async updateSessionDelta(sessionFile) {
2390
+ const thresholds = this.settings.sync.sessions;
2391
+ if (!thresholds) return null;
2392
+ let stat;
2393
+ try {
2394
+ stat = await fs$1.stat(sessionFile);
2395
+ } catch {
2396
+ return null;
2397
+ }
2398
+ const size = stat.size;
2399
+ let state = this.sessionDeltas.get(sessionFile);
2400
+ if (!state) {
2401
+ state = {
2402
+ lastSize: 0,
2403
+ pendingBytes: 0,
2404
+ pendingMessages: 0
2405
+ };
2406
+ this.sessionDeltas.set(sessionFile, state);
2407
+ }
2408
+ const deltaBytes = Math.max(0, size - state.lastSize);
2409
+ if (deltaBytes === 0 && size === state.lastSize) return {
2410
+ deltaBytes: thresholds.deltaBytes,
2411
+ deltaMessages: thresholds.deltaMessages,
2412
+ pendingBytes: state.pendingBytes,
2413
+ pendingMessages: state.pendingMessages
2414
+ };
2415
+ if (size < state.lastSize) {
2416
+ state.lastSize = size;
2417
+ state.pendingBytes += size;
2418
+ if (thresholds.deltaMessages > 0 && (thresholds.deltaBytes <= 0 || state.pendingBytes < thresholds.deltaBytes)) state.pendingMessages += await this.countNewlines(sessionFile, 0, size);
2419
+ } else {
2420
+ state.pendingBytes += deltaBytes;
2421
+ if (thresholds.deltaMessages > 0 && (thresholds.deltaBytes <= 0 || state.pendingBytes < thresholds.deltaBytes)) state.pendingMessages += await this.countNewlines(sessionFile, state.lastSize, size);
2422
+ state.lastSize = size;
2423
+ }
2424
+ this.sessionDeltas.set(sessionFile, state);
2425
+ return {
2426
+ deltaBytes: thresholds.deltaBytes,
2427
+ deltaMessages: thresholds.deltaMessages,
2428
+ pendingBytes: state.pendingBytes,
2429
+ pendingMessages: state.pendingMessages
2430
+ };
2431
+ }
2432
+ async countNewlines(absPath, start, end) {
2433
+ if (end <= start) return 0;
2434
+ const handle = await fs$1.open(absPath, "r");
2435
+ try {
2436
+ let offset = start;
2437
+ let count = 0;
2438
+ const buffer = Buffer.alloc(SESSION_DELTA_READ_CHUNK_BYTES);
2439
+ while (offset < end) {
2440
+ const toRead = Math.min(buffer.length, end - offset);
2441
+ const { bytesRead } = await handle.read(buffer, 0, toRead, offset);
2442
+ if (bytesRead <= 0) break;
2443
+ for (let i = 0; i < bytesRead; i += 1) if (buffer[i] === 10) count += 1;
2444
+ offset += bytesRead;
2445
+ }
2446
+ return count;
2447
+ } finally {
2448
+ await handle.close();
2449
+ }
2450
+ }
2451
+ resetSessionDelta(absPath, size) {
2452
+ const state = this.sessionDeltas.get(absPath);
2453
+ if (!state) return;
2454
+ state.lastSize = size;
2455
+ state.pendingBytes = 0;
2456
+ state.pendingMessages = 0;
2457
+ }
2458
+ isSessionFileForAgent(sessionFile) {
2459
+ if (!sessionFile) return false;
2460
+ const sessionsDir = resolveSessionTranscriptsDirForAgent(this.agentId);
2461
+ const resolvedFile = path.resolve(sessionFile);
2462
+ const resolvedDir = path.resolve(sessionsDir);
2463
+ return resolvedFile.startsWith(`${resolvedDir}${path.sep}`);
2464
+ }
2465
+ ensureIntervalSync() {
2466
+ const minutes = this.settings.sync.intervalMinutes;
2467
+ if (!minutes || minutes <= 0 || this.intervalTimer) return;
2468
+ const ms = minutes * 60 * 1e3;
2469
+ this.intervalTimer = setInterval(() => {
2470
+ this.sync({ reason: "interval" }).catch((err) => {
2471
+ log$1.warn(`memory sync failed (interval): ${String(err)}`);
2472
+ });
2473
+ }, ms);
2474
+ }
2475
+ scheduleWatchSync() {
2476
+ if (!this.sources.has("memory") || !this.settings.sync.watch) return;
2477
+ if (this.watchTimer) clearTimeout(this.watchTimer);
2478
+ this.watchTimer = setTimeout(() => {
2479
+ this.watchTimer = null;
2480
+ this.sync({ reason: "watch" }).catch((err) => {
2481
+ log$1.warn(`memory sync failed (watch): ${String(err)}`);
2482
+ });
2483
+ }, this.settings.sync.watchDebounceMs);
2484
+ }
2485
+ shouldSyncSessions(params, needsFullReindex = false) {
2486
+ if (!this.sources.has("sessions")) return false;
2487
+ if (params?.force) return true;
2488
+ const reason = params?.reason;
2489
+ if (reason === "session-start" || reason === "watch") return false;
2490
+ if (needsFullReindex) return true;
2491
+ return this.sessionsDirty && this.sessionsDirtyFiles.size > 0;
2492
+ }
2493
+ async syncMemoryFiles(params) {
2494
+ const files = await listMemoryFiles(this.workspaceDir, this.settings.extraPaths);
2495
+ const fileEntries = await Promise.all(files.map(async (file) => buildFileEntry(file, this.workspaceDir)));
2496
+ log$1.debug("memory sync: indexing memory files", {
2497
+ files: fileEntries.length,
2498
+ needsFullReindex: params.needsFullReindex,
2499
+ batch: this.batch.enabled,
2500
+ concurrency: this.getIndexConcurrency()
2501
+ });
2502
+ const activePaths = new Set(fileEntries.map((entry) => entry.path));
2503
+ if (params.progress) {
2504
+ params.progress.total += fileEntries.length;
2505
+ params.progress.report({
2506
+ completed: params.progress.completed,
2507
+ total: params.progress.total,
2508
+ label: this.batch.enabled ? "Indexing memory files (batch)..." : "Indexing memory files…"
2509
+ });
2510
+ }
2511
+ await runWithConcurrency(fileEntries.map((entry) => async () => {
2512
+ const record = this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(entry.path, "memory");
2513
+ if (!params.needsFullReindex && record?.hash === entry.hash) {
2514
+ if (params.progress) {
2515
+ params.progress.completed += 1;
2516
+ params.progress.report({
2517
+ completed: params.progress.completed,
2518
+ total: params.progress.total
2519
+ });
2520
+ }
2521
+ return;
2522
+ }
2523
+ await this.indexFile(entry, { source: "memory" });
2524
+ if (params.progress) {
2525
+ params.progress.completed += 1;
2526
+ params.progress.report({
2527
+ completed: params.progress.completed,
2528
+ total: params.progress.total
2529
+ });
2530
+ }
2531
+ }), this.getIndexConcurrency());
2532
+ const staleRows = this.db.prepare(`SELECT path FROM files WHERE source = ?`).all("memory");
2533
+ for (const stale of staleRows) {
2534
+ if (activePaths.has(stale.path)) continue;
2535
+ this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "memory");
2536
+ try {
2537
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$1} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(stale.path, "memory");
2538
+ } catch {}
2539
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "memory");
2540
+ if (this.fts.enabled && this.fts.available) try {
2541
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$1} WHERE path = ? AND source = ? AND model = ?`).run(stale.path, "memory", this.provider.model);
2542
+ } catch {}
2543
+ }
2544
+ }
2545
+ async syncSessionFiles(params) {
2546
+ const files = await listSessionFilesForAgent(this.agentId);
2547
+ const activePaths = new Set(files.map((file) => sessionPathForFile(file)));
2548
+ const indexAll = params.needsFullReindex || this.sessionsDirtyFiles.size === 0;
2549
+ log$1.debug("memory sync: indexing session files", {
2550
+ files: files.length,
2551
+ indexAll,
2552
+ dirtyFiles: this.sessionsDirtyFiles.size,
2553
+ batch: this.batch.enabled,
2554
+ concurrency: this.getIndexConcurrency()
2555
+ });
2556
+ if (params.progress) {
2557
+ params.progress.total += files.length;
2558
+ params.progress.report({
2559
+ completed: params.progress.completed,
2560
+ total: params.progress.total,
2561
+ label: this.batch.enabled ? "Indexing session files (batch)..." : "Indexing session files…"
2562
+ });
2563
+ }
2564
+ await runWithConcurrency(files.map((absPath) => async () => {
2565
+ if (!indexAll && !this.sessionsDirtyFiles.has(absPath)) {
2566
+ if (params.progress) {
2567
+ params.progress.completed += 1;
2568
+ params.progress.report({
2569
+ completed: params.progress.completed,
2570
+ total: params.progress.total
2571
+ });
2572
+ }
2573
+ return;
2574
+ }
2575
+ const entry = await buildSessionEntry(absPath);
2576
+ if (!entry) {
2577
+ if (params.progress) {
2578
+ params.progress.completed += 1;
2579
+ params.progress.report({
2580
+ completed: params.progress.completed,
2581
+ total: params.progress.total
2582
+ });
2583
+ }
2584
+ return;
2585
+ }
2586
+ const record = this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(entry.path, "sessions");
2587
+ if (!params.needsFullReindex && record?.hash === entry.hash) {
2588
+ if (params.progress) {
2589
+ params.progress.completed += 1;
2590
+ params.progress.report({
2591
+ completed: params.progress.completed,
2592
+ total: params.progress.total
2593
+ });
2594
+ }
2595
+ this.resetSessionDelta(absPath, entry.size);
2596
+ return;
2597
+ }
2598
+ await this.indexFile(entry, {
2599
+ source: "sessions",
2600
+ content: entry.content
2601
+ });
2602
+ this.resetSessionDelta(absPath, entry.size);
2603
+ if (params.progress) {
2604
+ params.progress.completed += 1;
2605
+ params.progress.report({
2606
+ completed: params.progress.completed,
2607
+ total: params.progress.total
2608
+ });
2609
+ }
2610
+ }), this.getIndexConcurrency());
2611
+ const staleRows = this.db.prepare(`SELECT path FROM files WHERE source = ?`).all("sessions");
2612
+ for (const stale of staleRows) {
2613
+ if (activePaths.has(stale.path)) continue;
2614
+ this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "sessions");
2615
+ try {
2616
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$1} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(stale.path, "sessions");
2617
+ } catch {}
2618
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "sessions");
2619
+ if (this.fts.enabled && this.fts.available) try {
2620
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$1} WHERE path = ? AND source = ? AND model = ?`).run(stale.path, "sessions", this.provider.model);
2621
+ } catch {}
2622
+ }
2623
+ }
2624
+ createSyncProgress(onProgress) {
2625
+ const state = {
2626
+ completed: 0,
2627
+ total: 0,
2628
+ label: void 0,
2629
+ report: (update) => {
2630
+ if (update.label) state.label = update.label;
2631
+ const label = update.total > 0 && state.label ? `${state.label} ${update.completed}/${update.total}` : state.label;
2632
+ onProgress({
2633
+ completed: update.completed,
2634
+ total: update.total,
2635
+ label
2636
+ });
2637
+ }
2638
+ };
2639
+ return state;
2640
+ }
2641
+ async runSync(params) {
2642
+ const progress = params?.progress ? this.createSyncProgress(params.progress) : void 0;
2643
+ if (progress) progress.report({
2644
+ completed: progress.completed,
2645
+ total: progress.total,
2646
+ label: "Loading vector extension…"
2647
+ });
2648
+ const vectorReady = await this.ensureVectorReady();
2649
+ const meta = this.readMeta();
2650
+ const needsFullReindex = params?.force || !meta || meta.model !== this.provider.model || meta.provider !== this.provider.id || meta.providerKey !== this.providerKey || meta.chunkTokens !== this.settings.chunking.tokens || meta.chunkOverlap !== this.settings.chunking.overlap || vectorReady && !meta?.vectorDims;
2651
+ try {
2652
+ if (needsFullReindex) {
2653
+ if (process.env.ANIMA_TEST_FAST === "1" && process.env.ANIMA_TEST_MEMORY_UNSAFE_REINDEX === "1") await this.runUnsafeReindex({
2654
+ reason: params?.reason,
2655
+ force: params?.force,
2656
+ progress: progress ?? void 0
2657
+ });
2658
+ else await this.runSafeReindex({
2659
+ reason: params?.reason,
2660
+ force: params?.force,
2661
+ progress: progress ?? void 0
2662
+ });
2663
+ return;
2664
+ }
2665
+ const shouldSyncMemory = this.sources.has("memory") && (params?.force || needsFullReindex || this.dirty);
2666
+ const shouldSyncSessions = this.shouldSyncSessions(params, needsFullReindex);
2667
+ if (shouldSyncMemory) {
2668
+ await this.syncMemoryFiles({
2669
+ needsFullReindex,
2670
+ progress: progress ?? void 0
2671
+ });
2672
+ this.dirty = false;
2673
+ }
2674
+ if (shouldSyncSessions) {
2675
+ await this.syncSessionFiles({
2676
+ needsFullReindex,
2677
+ progress: progress ?? void 0
2678
+ });
2679
+ this.sessionsDirty = false;
2680
+ this.sessionsDirtyFiles.clear();
2681
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2682
+ else this.sessionsDirty = false;
2683
+ } catch (err) {
2684
+ const reason = err instanceof Error ? err.message : String(err);
2685
+ if (this.shouldFallbackOnError(reason) && await this.activateFallbackProvider(reason)) {
2686
+ await this.runSafeReindex({
2687
+ reason: params?.reason ?? "fallback",
2688
+ force: true,
2689
+ progress: progress ?? void 0
2690
+ });
2691
+ return;
2692
+ }
2693
+ throw err;
2694
+ }
2695
+ }
2696
+ shouldFallbackOnError(message) {
2697
+ return /embedding|embeddings|batch/i.test(message);
2698
+ }
2699
+ resolveBatchConfig() {
2700
+ const batch = this.settings.remote?.batch;
2701
+ return {
2702
+ enabled: Boolean(batch?.enabled && (this.openAi && this.provider.id === "openai" || this.gemini && this.provider.id === "gemini" || this.voyage && this.provider.id === "voyage")),
2703
+ wait: batch?.wait ?? true,
2704
+ concurrency: Math.max(1, batch?.concurrency ?? 2),
2705
+ pollIntervalMs: batch?.pollIntervalMs ?? 2e3,
2706
+ timeoutMs: (batch?.timeoutMinutes ?? 60) * 60 * 1e3
2707
+ };
2708
+ }
2709
+ async activateFallbackProvider(reason) {
2710
+ const fallback = this.settings.fallback;
2711
+ if (!fallback || fallback === "none" || fallback === this.provider.id) return false;
2712
+ if (this.fallbackFrom) return false;
2713
+ const fallbackFrom = this.provider.id;
2714
+ const fallbackModel = fallback === "gemini" ? DEFAULT_GEMINI_EMBEDDING_MODEL : fallback === "openai" ? DEFAULT_OPENAI_EMBEDDING_MODEL : fallback === "voyage" ? DEFAULT_VOYAGE_EMBEDDING_MODEL : this.settings.model;
2715
+ const fallbackResult = await createEmbeddingProvider({
2716
+ config: this.cfg,
2717
+ agentDir: resolveAgentDir(this.cfg, this.agentId),
2718
+ provider: fallback,
2719
+ remote: this.settings.remote,
2720
+ model: fallbackModel,
2721
+ fallback: "none",
2722
+ local: this.settings.local
2723
+ });
2724
+ this.fallbackFrom = fallbackFrom;
2725
+ this.fallbackReason = reason;
2726
+ this.provider = fallbackResult.provider;
2727
+ this.openAi = fallbackResult.openAi;
2728
+ this.gemini = fallbackResult.gemini;
2729
+ this.voyage = fallbackResult.voyage;
2730
+ this.providerKey = this.computeProviderKey();
2731
+ this.batch = this.resolveBatchConfig();
2732
+ log$1.warn(`memory embeddings: switched to fallback provider (${fallback})`, { reason });
2733
+ return true;
2734
+ }
2735
+ async runSafeReindex(params) {
2736
+ const dbPath = resolveUserPath(this.settings.store.path);
2737
+ const tempDbPath = `${dbPath}.tmp-${randomUUID()}`;
2738
+ const tempDb = this.openDatabaseAtPath(tempDbPath);
2739
+ const originalDb = this.db;
2740
+ let originalDbClosed = false;
2741
+ const originalState = {
2742
+ ftsAvailable: this.fts.available,
2743
+ ftsError: this.fts.loadError,
2744
+ vectorAvailable: this.vector.available,
2745
+ vectorLoadError: this.vector.loadError,
2746
+ vectorDims: this.vector.dims,
2747
+ vectorReady: this.vectorReady
2748
+ };
2749
+ const restoreOriginalState = () => {
2750
+ if (originalDbClosed) this.db = this.openDatabaseAtPath(dbPath);
2751
+ else this.db = originalDb;
2752
+ this.fts.available = originalState.ftsAvailable;
2753
+ this.fts.loadError = originalState.ftsError;
2754
+ this.vector.available = originalDbClosed ? null : originalState.vectorAvailable;
2755
+ this.vector.loadError = originalState.vectorLoadError;
2756
+ this.vector.dims = originalState.vectorDims;
2757
+ this.vectorReady = originalDbClosed ? null : originalState.vectorReady;
2758
+ };
2759
+ this.db = tempDb;
2760
+ this.vectorReady = null;
2761
+ this.vector.available = null;
2762
+ this.vector.loadError = void 0;
2763
+ this.vector.dims = void 0;
2764
+ this.fts.available = false;
2765
+ this.fts.loadError = void 0;
2766
+ this.ensureSchema();
2767
+ let nextMeta = null;
2768
+ try {
2769
+ this.seedEmbeddingCache(originalDb);
2770
+ const shouldSyncMemory = this.sources.has("memory");
2771
+ const shouldSyncSessions = this.shouldSyncSessions({
2772
+ reason: params.reason,
2773
+ force: params.force
2774
+ }, true);
2775
+ if (shouldSyncMemory) {
2776
+ await this.syncMemoryFiles({
2777
+ needsFullReindex: true,
2778
+ progress: params.progress
2779
+ });
2780
+ this.dirty = false;
2781
+ }
2782
+ if (shouldSyncSessions) {
2783
+ await this.syncSessionFiles({
2784
+ needsFullReindex: true,
2785
+ progress: params.progress
2786
+ });
2787
+ this.sessionsDirty = false;
2788
+ this.sessionsDirtyFiles.clear();
2789
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2790
+ else this.sessionsDirty = false;
2791
+ nextMeta = {
2792
+ model: this.provider.model,
2793
+ provider: this.provider.id,
2794
+ providerKey: this.providerKey,
2795
+ chunkTokens: this.settings.chunking.tokens,
2796
+ chunkOverlap: this.settings.chunking.overlap
2797
+ };
2798
+ if (this.vector.available && this.vector.dims) nextMeta.vectorDims = this.vector.dims;
2799
+ this.writeMeta(nextMeta);
2800
+ this.pruneEmbeddingCacheIfNeeded();
2801
+ this.db.close();
2802
+ originalDb.close();
2803
+ originalDbClosed = true;
2804
+ await this.swapIndexFiles(dbPath, tempDbPath);
2805
+ this.db = this.openDatabaseAtPath(dbPath);
2806
+ this.vectorReady = null;
2807
+ this.vector.available = null;
2808
+ this.vector.loadError = void 0;
2809
+ this.ensureSchema();
2810
+ this.vector.dims = nextMeta.vectorDims;
2811
+ } catch (err) {
2812
+ try {
2813
+ this.db.close();
2814
+ } catch {}
2815
+ await this.removeIndexFiles(tempDbPath);
2816
+ restoreOriginalState();
2817
+ throw err;
2818
+ }
2819
+ }
2820
+ async runUnsafeReindex(params) {
2821
+ this.resetIndex();
2822
+ const shouldSyncMemory = this.sources.has("memory");
2823
+ const shouldSyncSessions = this.shouldSyncSessions({
2824
+ reason: params.reason,
2825
+ force: params.force
2826
+ }, true);
2827
+ if (shouldSyncMemory) {
2828
+ await this.syncMemoryFiles({
2829
+ needsFullReindex: true,
2830
+ progress: params.progress
2831
+ });
2832
+ this.dirty = false;
2833
+ }
2834
+ if (shouldSyncSessions) {
2835
+ await this.syncSessionFiles({
2836
+ needsFullReindex: true,
2837
+ progress: params.progress
2838
+ });
2839
+ this.sessionsDirty = false;
2840
+ this.sessionsDirtyFiles.clear();
2841
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2842
+ else this.sessionsDirty = false;
2843
+ const nextMeta = {
2844
+ model: this.provider.model,
2845
+ provider: this.provider.id,
2846
+ providerKey: this.providerKey,
2847
+ chunkTokens: this.settings.chunking.tokens,
2848
+ chunkOverlap: this.settings.chunking.overlap
2849
+ };
2850
+ if (this.vector.available && this.vector.dims) nextMeta.vectorDims = this.vector.dims;
2851
+ this.writeMeta(nextMeta);
2852
+ this.pruneEmbeddingCacheIfNeeded();
2853
+ }
2854
+ resetIndex() {
2855
+ this.db.exec(`DELETE FROM files`);
2856
+ this.db.exec(`DELETE FROM chunks`);
2857
+ if (this.fts.enabled && this.fts.available) try {
2858
+ this.db.exec(`DELETE FROM ${FTS_TABLE$1}`);
2859
+ } catch {}
2860
+ this.dropVectorTable();
2861
+ this.vector.dims = void 0;
2862
+ this.sessionsDirtyFiles.clear();
2863
+ }
2864
+ readMeta() {
2865
+ const row = this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(META_KEY);
2866
+ if (!row?.value) return null;
2867
+ try {
2868
+ return JSON.parse(row.value);
2869
+ } catch {
2870
+ return null;
2871
+ }
2872
+ }
2873
+ writeMeta(meta) {
2874
+ const value = JSON.stringify(meta);
2875
+ this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(META_KEY, value);
2876
+ }
2877
+ };
2878
+ const memoryManagerSyncOps = MemoryManagerSyncOps.prototype;
2879
+
2880
+ //#endregion
2881
+ //#region src/memory/manager.ts
2882
+ var manager_exports = /* @__PURE__ */ __exportAll({ MemoryIndexManager: () => MemoryIndexManager });
2883
+ const SNIPPET_MAX_CHARS = 700;
2884
+ const VECTOR_TABLE = "chunks_vec";
2885
+ const FTS_TABLE = "chunks_fts";
2886
+ const EMBEDDING_CACHE_TABLE = "embedding_cache";
2887
+ const BATCH_FAILURE_LIMIT = 2;
2888
+ const log = createSubsystemLogger("memory");
2889
+ const INDEX_CACHE = /* @__PURE__ */ new Map();
2890
+ var MemoryIndexManager = class MemoryIndexManager {
2891
+ static async get(params) {
2892
+ const { cfg, agentId } = params;
2893
+ const settings = resolveMemorySearchConfig(cfg, agentId);
2894
+ if (!settings) return null;
2895
+ const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
2896
+ const key = `${agentId}:${workspaceDir}:${JSON.stringify(settings)}`;
2897
+ const existing = INDEX_CACHE.get(key);
2898
+ if (existing) return existing;
2899
+ const manager = new MemoryIndexManager({
2900
+ cacheKey: key,
2901
+ cfg,
2902
+ agentId,
2903
+ workspaceDir,
2904
+ settings,
2905
+ providerResult: await createEmbeddingProvider$1({
2906
+ config: cfg,
2907
+ agentDir: resolveAgentDir$1(cfg, agentId),
2908
+ provider: settings.provider,
2909
+ remote: settings.remote,
2910
+ model: settings.model,
2911
+ fallback: settings.fallback,
2912
+ local: settings.local
2913
+ }),
2914
+ purpose: params.purpose
2915
+ });
2916
+ INDEX_CACHE.set(key, manager);
2917
+ return manager;
2918
+ }
2919
+ constructor(params) {
2920
+ this.batchFailureCount = 0;
2921
+ this.batchFailureLock = Promise.resolve();
2922
+ this.vectorReady = null;
2923
+ this.watcher = null;
2924
+ this.watchTimer = null;
2925
+ this.sessionWatchTimer = null;
2926
+ this.sessionUnsubscribe = null;
2927
+ this.intervalTimer = null;
2928
+ this.closed = false;
2929
+ this.dirty = false;
2930
+ this.sessionsDirty = false;
2931
+ this.sessionsDirtyFiles = /* @__PURE__ */ new Set();
2932
+ this.sessionPendingFiles = /* @__PURE__ */ new Set();
2933
+ this.sessionDeltas = /* @__PURE__ */ new Map();
2934
+ this.sessionWarm = /* @__PURE__ */ new Set();
2935
+ this.syncing = null;
2936
+ this.cacheKey = params.cacheKey;
2937
+ this.cfg = params.cfg;
2938
+ this.agentId = params.agentId;
2939
+ this.workspaceDir = params.workspaceDir;
2940
+ this.settings = params.settings;
2941
+ this.provider = params.providerResult.provider;
2942
+ this.requestedProvider = params.providerResult.requestedProvider;
2943
+ this.fallbackFrom = params.providerResult.fallbackFrom;
2944
+ this.fallbackReason = params.providerResult.fallbackReason;
2945
+ this.openAi = params.providerResult.openAi;
2946
+ this.gemini = params.providerResult.gemini;
2947
+ this.voyage = params.providerResult.voyage;
2948
+ this.sources = new Set(params.settings.sources);
2949
+ this.db = this.openDatabase();
2950
+ this.providerKey = this.computeProviderKey();
2951
+ this.cache = {
2952
+ enabled: params.settings.cache.enabled,
2953
+ maxEntries: params.settings.cache.maxEntries
2954
+ };
2955
+ this.fts = {
2956
+ enabled: params.settings.query.hybrid.enabled,
2957
+ available: false
2958
+ };
2959
+ this.ensureSchema();
2960
+ this.vector = {
2961
+ enabled: params.settings.store.vector.enabled,
2962
+ available: null,
2963
+ extensionPath: params.settings.store.vector.extensionPath
2964
+ };
2965
+ const meta = this.readMeta();
2966
+ if (meta?.vectorDims) this.vector.dims = meta.vectorDims;
2967
+ this.ensureWatcher();
2968
+ this.ensureSessionListener();
2969
+ this.ensureIntervalSync();
2970
+ const statusOnly = params.purpose === "status";
2971
+ this.dirty = this.sources.has("memory") && (statusOnly ? !meta : true);
2972
+ this.batch = this.resolveBatchConfig();
2973
+ }
2974
+ async warmSession(sessionKey) {
2975
+ if (!this.settings.sync.onSessionStart) return;
2976
+ const key = sessionKey?.trim() || "";
2977
+ if (key && this.sessionWarm.has(key)) return;
2978
+ this.sync({ reason: "session-start" }).catch((err) => {
2979
+ log.warn(`memory sync failed (session-start): ${String(err)}`);
2980
+ });
2981
+ if (key) this.sessionWarm.add(key);
2982
+ }
2983
+ async search(query, opts) {
2984
+ this.warmSession(opts?.sessionKey);
2985
+ if (this.settings.sync.onSearch && (this.dirty || this.sessionsDirty)) this.sync({ reason: "search" }).catch((err) => {
2986
+ log.warn(`memory sync failed (search): ${String(err)}`);
2987
+ });
2988
+ const cleaned = query.trim();
2989
+ if (!cleaned) return [];
2990
+ const minScore = opts?.minScore ?? this.settings.query.minScore;
2991
+ const maxResults = opts?.maxResults ?? this.settings.query.maxResults;
2992
+ const hybrid = this.settings.query.hybrid;
2993
+ const candidates = Math.min(200, Math.max(1, Math.floor(maxResults * hybrid.candidateMultiplier)));
2994
+ const keywordResults = hybrid.enabled ? await this.searchKeyword(cleaned, candidates).catch(() => []) : [];
2995
+ const queryVec = await this.embedQueryWithTimeout(cleaned);
2996
+ const vectorResults = queryVec.some((v) => v !== 0) ? await this.searchVector(queryVec, candidates).catch(() => []) : [];
2997
+ if (!hybrid.enabled) return vectorResults.filter((entry) => entry.score >= minScore).slice(0, maxResults);
2998
+ return this.mergeHybridResults({
2999
+ vector: vectorResults,
3000
+ keyword: keywordResults,
3001
+ vectorWeight: hybrid.vectorWeight,
3002
+ textWeight: hybrid.textWeight
3003
+ }).filter((entry) => entry.score >= minScore).slice(0, maxResults);
3004
+ }
3005
+ async searchVector(queryVec, limit) {
3006
+ return (await searchVector({
3007
+ db: this.db,
3008
+ vectorTable: VECTOR_TABLE,
3009
+ providerModel: this.provider.model,
3010
+ queryVec,
3011
+ limit,
3012
+ snippetMaxChars: SNIPPET_MAX_CHARS,
3013
+ ensureVectorReady: async (dimensions) => await this.ensureVectorReady(dimensions),
3014
+ sourceFilterVec: this.buildSourceFilter("c"),
3015
+ sourceFilterChunks: this.buildSourceFilter()
3016
+ })).map((entry) => entry);
3017
+ }
3018
+ buildFtsQuery(raw) {
3019
+ return buildFtsQuery(raw);
3020
+ }
3021
+ async searchKeyword(query, limit) {
3022
+ if (!this.fts.enabled || !this.fts.available) return [];
3023
+ const sourceFilter = this.buildSourceFilter();
3024
+ return (await searchKeyword({
3025
+ db: this.db,
3026
+ ftsTable: FTS_TABLE,
3027
+ providerModel: this.provider.model,
3028
+ query,
3029
+ limit,
3030
+ snippetMaxChars: SNIPPET_MAX_CHARS,
3031
+ sourceFilter,
3032
+ buildFtsQuery: (raw) => this.buildFtsQuery(raw),
3033
+ bm25RankToScore
3034
+ })).map((entry) => entry);
3035
+ }
3036
+ mergeHybridResults(params) {
3037
+ return mergeHybridResults({
3038
+ vector: params.vector.map((r) => ({
3039
+ id: r.id,
3040
+ path: r.path,
3041
+ startLine: r.startLine,
3042
+ endLine: r.endLine,
3043
+ source: r.source,
3044
+ snippet: r.snippet,
3045
+ vectorScore: r.score
3046
+ })),
3047
+ keyword: params.keyword.map((r) => ({
3048
+ id: r.id,
3049
+ path: r.path,
3050
+ startLine: r.startLine,
3051
+ endLine: r.endLine,
3052
+ source: r.source,
3053
+ snippet: r.snippet,
3054
+ textScore: r.textScore
3055
+ })),
3056
+ vectorWeight: params.vectorWeight,
3057
+ textWeight: params.textWeight
3058
+ }).map((entry) => entry);
3059
+ }
3060
+ async sync(params) {
3061
+ if (this.syncing) return this.syncing;
3062
+ this.syncing = this.runSync(params).finally(() => {
3063
+ this.syncing = null;
3064
+ });
3065
+ return this.syncing ?? Promise.resolve();
3066
+ }
3067
+ async readFile(params) {
3068
+ const rawPath = params.relPath.trim();
3069
+ if (!rawPath) throw new Error("path required");
3070
+ const absPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(this.workspaceDir, rawPath);
3071
+ const relPath = path.relative(this.workspaceDir, absPath).replace(/\\/g, "/");
3072
+ const allowedWorkspace = relPath.length > 0 && !relPath.startsWith("..") && !path.isAbsolute(relPath) && isMemoryPath(relPath);
3073
+ let allowedAdditional = false;
3074
+ if (!allowedWorkspace && this.settings.extraPaths.length > 0) {
3075
+ const additionalPaths = normalizeExtraMemoryPaths(this.workspaceDir, this.settings.extraPaths);
3076
+ for (const additionalPath of additionalPaths) try {
3077
+ const stat = await fs$1.lstat(additionalPath);
3078
+ if (stat.isSymbolicLink()) continue;
3079
+ if (stat.isDirectory()) {
3080
+ if (absPath === additionalPath || absPath.startsWith(`${additionalPath}${path.sep}`)) {
3081
+ allowedAdditional = true;
3082
+ break;
3083
+ }
3084
+ continue;
3085
+ }
3086
+ if (stat.isFile()) {
3087
+ if (absPath === additionalPath && absPath.endsWith(".md")) {
3088
+ allowedAdditional = true;
3089
+ break;
3090
+ }
3091
+ }
3092
+ } catch {}
3093
+ }
3094
+ if (!allowedWorkspace && !allowedAdditional) throw new Error("path required");
3095
+ if (!absPath.endsWith(".md")) throw new Error("path required");
3096
+ const stat = await fs$1.lstat(absPath);
3097
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("path required");
3098
+ const content = await fs$1.readFile(absPath, "utf-8");
3099
+ if (!params.from && !params.lines) return {
3100
+ text: content,
3101
+ path: relPath
3102
+ };
3103
+ const lines = content.split("\n");
3104
+ const start = Math.max(1, params.from ?? 1);
3105
+ const count = Math.max(1, params.lines ?? lines.length);
3106
+ return {
3107
+ text: lines.slice(start - 1, start - 1 + count).join("\n"),
3108
+ path: relPath
3109
+ };
3110
+ }
3111
+ status() {
3112
+ const sourceFilter = this.buildSourceFilter();
3113
+ const files = this.db.prepare(`SELECT COUNT(*) as c FROM files WHERE 1=1${sourceFilter.sql}`).get(...sourceFilter.params);
3114
+ const chunks = this.db.prepare(`SELECT COUNT(*) as c FROM chunks WHERE 1=1${sourceFilter.sql}`).get(...sourceFilter.params);
3115
+ const sourceCounts = (() => {
3116
+ const sources = Array.from(this.sources);
3117
+ if (sources.length === 0) return [];
3118
+ const bySource = /* @__PURE__ */ new Map();
3119
+ for (const source of sources) bySource.set(source, {
3120
+ files: 0,
3121
+ chunks: 0
3122
+ });
3123
+ const fileRows = this.db.prepare(`SELECT source, COUNT(*) as c FROM files WHERE 1=1${sourceFilter.sql} GROUP BY source`).all(...sourceFilter.params);
3124
+ for (const row of fileRows) {
3125
+ const entry = bySource.get(row.source) ?? {
3126
+ files: 0,
3127
+ chunks: 0
3128
+ };
3129
+ entry.files = row.c ?? 0;
3130
+ bySource.set(row.source, entry);
3131
+ }
3132
+ const chunkRows = this.db.prepare(`SELECT source, COUNT(*) as c FROM chunks WHERE 1=1${sourceFilter.sql} GROUP BY source`).all(...sourceFilter.params);
3133
+ for (const row of chunkRows) {
3134
+ const entry = bySource.get(row.source) ?? {
3135
+ files: 0,
3136
+ chunks: 0
3137
+ };
3138
+ entry.chunks = row.c ?? 0;
3139
+ bySource.set(row.source, entry);
3140
+ }
3141
+ return sources.map((source) => Object.assign({ source }, bySource.get(source)));
3142
+ })();
3143
+ return {
3144
+ backend: "builtin",
3145
+ files: files?.c ?? 0,
3146
+ chunks: chunks?.c ?? 0,
3147
+ dirty: this.dirty || this.sessionsDirty,
3148
+ workspaceDir: this.workspaceDir,
3149
+ dbPath: this.settings.store.path,
3150
+ provider: this.provider.id,
3151
+ model: this.provider.model,
3152
+ requestedProvider: this.requestedProvider,
3153
+ sources: Array.from(this.sources),
3154
+ extraPaths: this.settings.extraPaths,
3155
+ sourceCounts,
3156
+ cache: this.cache.enabled ? {
3157
+ enabled: true,
3158
+ entries: this.db.prepare(`SELECT COUNT(*) as c FROM ${EMBEDDING_CACHE_TABLE}`).get()?.c ?? 0,
3159
+ maxEntries: this.cache.maxEntries
3160
+ } : {
3161
+ enabled: false,
3162
+ maxEntries: this.cache.maxEntries
3163
+ },
3164
+ fts: {
3165
+ enabled: this.fts.enabled,
3166
+ available: this.fts.available,
3167
+ error: this.fts.loadError
3168
+ },
3169
+ fallback: this.fallbackReason ? {
3170
+ from: this.fallbackFrom ?? "local",
3171
+ reason: this.fallbackReason
3172
+ } : void 0,
3173
+ vector: {
3174
+ enabled: this.vector.enabled,
3175
+ available: this.vector.available ?? void 0,
3176
+ extensionPath: this.vector.extensionPath,
3177
+ loadError: this.vector.loadError,
3178
+ dims: this.vector.dims
3179
+ },
3180
+ batch: {
3181
+ enabled: this.batch.enabled,
3182
+ failures: this.batchFailureCount,
3183
+ limit: BATCH_FAILURE_LIMIT,
3184
+ wait: this.batch.wait,
3185
+ concurrency: this.batch.concurrency,
3186
+ pollIntervalMs: this.batch.pollIntervalMs,
3187
+ timeoutMs: this.batch.timeoutMs,
3188
+ lastError: this.batchFailureLastError,
3189
+ lastProvider: this.batchFailureLastProvider
3190
+ }
3191
+ };
3192
+ }
3193
+ async probeVectorAvailability() {
3194
+ if (!this.vector.enabled) return false;
3195
+ return this.ensureVectorReady();
3196
+ }
3197
+ async probeEmbeddingAvailability() {
3198
+ try {
3199
+ await this.embedBatchWithRetry(["ping"]);
3200
+ return { ok: true };
3201
+ } catch (err) {
3202
+ return {
3203
+ ok: false,
3204
+ error: err instanceof Error ? err.message : String(err)
3205
+ };
3206
+ }
3207
+ }
3208
+ async close() {
3209
+ if (this.closed) return;
3210
+ this.closed = true;
3211
+ if (this.watchTimer) {
3212
+ clearTimeout(this.watchTimer);
3213
+ this.watchTimer = null;
3214
+ }
3215
+ if (this.sessionWatchTimer) {
3216
+ clearTimeout(this.sessionWatchTimer);
3217
+ this.sessionWatchTimer = null;
3218
+ }
3219
+ if (this.intervalTimer) {
3220
+ clearInterval(this.intervalTimer);
3221
+ this.intervalTimer = null;
3222
+ }
3223
+ if (this.watcher) {
3224
+ await this.watcher.close();
3225
+ this.watcher = null;
3226
+ }
3227
+ if (this.sessionUnsubscribe) {
3228
+ this.sessionUnsubscribe();
3229
+ this.sessionUnsubscribe = null;
3230
+ }
3231
+ this.db.close();
3232
+ INDEX_CACHE.delete(this.cacheKey);
3233
+ }
3234
+ };
3235
+ function applyPrototypeMixins(target, ...sources) {
3236
+ for (const source of sources) for (const name of Object.getOwnPropertyNames(source)) {
3237
+ if (name === "constructor") continue;
3238
+ const descriptor = Object.getOwnPropertyDescriptor(source, name);
3239
+ if (!descriptor) continue;
3240
+ Object.defineProperty(target, name, descriptor);
3241
+ }
3242
+ }
3243
+ applyPrototypeMixins(MemoryIndexManager.prototype, memoryManagerSyncOps, memoryManagerEmbeddingOps);
3244
+
3245
+ //#endregion
3246
+ export { resolveMemorySearchConfig as n, manager_exports as t };