@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,3244 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
+ import { s as resolveStateDir } from "./paths-DA9WYabg.js";
3
+ import { D as clampNumber$1, E as clampInt, K as truncateUtf16Safe, U as sleep, l as createSubsystemLogger, z as resolveUserPath } from "./exec-B7sUS164.js";
4
+ import { n as resolveAgentConfig, r as resolveAgentDir$1, s as resolveAgentWorkspaceDir } from "./agent-scope-cj2QCT6R.js";
5
+ import { D as resolveApiKeyForProvider, E as requireApiKey, I as isTruthyEnvValue } from "./auth-profiles-BDrNYX_n.js";
6
+ import { o as resolveSessionTranscriptsDirForAgent } from "./paths-B1vRVCad.js";
7
+ import { n as onSessionTranscriptUpdate } from "./transcript-events-DW_H__a1.js";
8
+ import { n as formatErrorMessage } from "./errors-A_GqUU6B.js";
9
+ 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-CuprTGR7.js";
10
+ import fs from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import fsSync from "node:fs";
14
+ import { randomUUID } from "node:crypto";
15
+ import chokidar from "chokidar";
16
+ import { createInterface } from "node:readline";
17
+ import { Readable } from "node:stream";
18
+
19
+ //#region src/agents/memory-search.ts
20
+ const DEFAULT_OPENAI_MODEL = "text-embedding-3-small";
21
+ const DEFAULT_GEMINI_MODEL = "gemini-embedding-001";
22
+ const DEFAULT_VOYAGE_MODEL = "voyage-4-large";
23
+ const DEFAULT_CHUNK_TOKENS = 400;
24
+ const DEFAULT_CHUNK_OVERLAP = 80;
25
+ const DEFAULT_WATCH_DEBOUNCE_MS = 1500;
26
+ const DEFAULT_SESSION_DELTA_BYTES = 1e5;
27
+ const DEFAULT_SESSION_DELTA_MESSAGES = 50;
28
+ const DEFAULT_MAX_RESULTS = 6;
29
+ const DEFAULT_MIN_SCORE = .35;
30
+ const DEFAULT_HYBRID_ENABLED = true;
31
+ const DEFAULT_HYBRID_VECTOR_WEIGHT = .7;
32
+ const DEFAULT_HYBRID_TEXT_WEIGHT = .3;
33
+ const DEFAULT_HYBRID_CANDIDATE_MULTIPLIER = 4;
34
+ const DEFAULT_CACHE_ENABLED = true;
35
+ const DEFAULT_SOURCES = ["memory"];
36
+ function normalizeSources(sources, sessionMemoryEnabled) {
37
+ const normalized = /* @__PURE__ */ new Set();
38
+ const input = sources?.length ? sources : DEFAULT_SOURCES;
39
+ for (const source of input) {
40
+ if (source === "memory") normalized.add("memory");
41
+ if (source === "sessions" && sessionMemoryEnabled) normalized.add("sessions");
42
+ }
43
+ if (normalized.size === 0) normalized.add("memory");
44
+ return Array.from(normalized);
45
+ }
46
+ function resolveStorePath(agentId, raw) {
47
+ const stateDir = resolveStateDir(process.env, os.homedir);
48
+ const fallback = path.join(stateDir, "memory", `${agentId}.sqlite`);
49
+ if (!raw) return fallback;
50
+ return resolveUserPath(raw.includes("{agentId}") ? raw.replaceAll("{agentId}", agentId) : raw);
51
+ }
52
+ function mergeConfig(defaults, overrides, agentId) {
53
+ const enabled = overrides?.enabled ?? defaults?.enabled ?? true;
54
+ const sessionMemory = overrides?.experimental?.sessionMemory ?? defaults?.experimental?.sessionMemory ?? false;
55
+ const provider = overrides?.provider ?? defaults?.provider ?? "auto";
56
+ const defaultRemote = defaults?.remote;
57
+ const overrideRemote = overrides?.remote;
58
+ const includeRemote = Boolean(overrideRemote?.baseUrl || overrideRemote?.apiKey || overrideRemote?.headers || defaultRemote?.baseUrl || defaultRemote?.apiKey || defaultRemote?.headers) || provider === "openai" || provider === "gemini" || provider === "voyage" || provider === "auto";
59
+ const batch = {
60
+ enabled: overrideRemote?.batch?.enabled ?? defaultRemote?.batch?.enabled ?? false,
61
+ wait: overrideRemote?.batch?.wait ?? defaultRemote?.batch?.wait ?? true,
62
+ concurrency: Math.max(1, overrideRemote?.batch?.concurrency ?? defaultRemote?.batch?.concurrency ?? 2),
63
+ pollIntervalMs: overrideRemote?.batch?.pollIntervalMs ?? defaultRemote?.batch?.pollIntervalMs ?? 2e3,
64
+ timeoutMinutes: overrideRemote?.batch?.timeoutMinutes ?? defaultRemote?.batch?.timeoutMinutes ?? 60
65
+ };
66
+ const remote = includeRemote ? {
67
+ baseUrl: overrideRemote?.baseUrl ?? defaultRemote?.baseUrl,
68
+ apiKey: overrideRemote?.apiKey ?? defaultRemote?.apiKey,
69
+ headers: overrideRemote?.headers ?? defaultRemote?.headers,
70
+ batch
71
+ } : void 0;
72
+ const fallback = overrides?.fallback ?? defaults?.fallback ?? "none";
73
+ const modelDefault = provider === "gemini" ? DEFAULT_GEMINI_MODEL : provider === "openai" ? DEFAULT_OPENAI_MODEL : provider === "voyage" ? DEFAULT_VOYAGE_MODEL : void 0;
74
+ const model = overrides?.model ?? defaults?.model ?? modelDefault ?? "";
75
+ const local = {
76
+ modelPath: overrides?.local?.modelPath ?? defaults?.local?.modelPath,
77
+ modelCacheDir: overrides?.local?.modelCacheDir ?? defaults?.local?.modelCacheDir
78
+ };
79
+ const sources = normalizeSources(overrides?.sources ?? defaults?.sources, sessionMemory);
80
+ const rawPaths = [...defaults?.extraPaths ?? [], ...overrides?.extraPaths ?? []].map((value) => value.trim()).filter(Boolean);
81
+ const extraPaths = Array.from(new Set(rawPaths));
82
+ const vector = {
83
+ enabled: overrides?.store?.vector?.enabled ?? defaults?.store?.vector?.enabled ?? true,
84
+ extensionPath: overrides?.store?.vector?.extensionPath ?? defaults?.store?.vector?.extensionPath
85
+ };
86
+ const store = {
87
+ driver: overrides?.store?.driver ?? defaults?.store?.driver ?? "sqlite",
88
+ path: resolveStorePath(agentId, overrides?.store?.path ?? defaults?.store?.path),
89
+ vector
90
+ };
91
+ const chunking = {
92
+ tokens: overrides?.chunking?.tokens ?? defaults?.chunking?.tokens ?? DEFAULT_CHUNK_TOKENS,
93
+ overlap: overrides?.chunking?.overlap ?? defaults?.chunking?.overlap ?? DEFAULT_CHUNK_OVERLAP
94
+ };
95
+ const sync = {
96
+ onSessionStart: overrides?.sync?.onSessionStart ?? defaults?.sync?.onSessionStart ?? true,
97
+ onSearch: overrides?.sync?.onSearch ?? defaults?.sync?.onSearch ?? true,
98
+ watch: overrides?.sync?.watch ?? defaults?.sync?.watch ?? true,
99
+ watchDebounceMs: overrides?.sync?.watchDebounceMs ?? defaults?.sync?.watchDebounceMs ?? DEFAULT_WATCH_DEBOUNCE_MS,
100
+ intervalMinutes: overrides?.sync?.intervalMinutes ?? defaults?.sync?.intervalMinutes ?? 0,
101
+ sessions: {
102
+ deltaBytes: overrides?.sync?.sessions?.deltaBytes ?? defaults?.sync?.sessions?.deltaBytes ?? DEFAULT_SESSION_DELTA_BYTES,
103
+ deltaMessages: overrides?.sync?.sessions?.deltaMessages ?? defaults?.sync?.sessions?.deltaMessages ?? DEFAULT_SESSION_DELTA_MESSAGES
104
+ }
105
+ };
106
+ const query = {
107
+ maxResults: overrides?.query?.maxResults ?? defaults?.query?.maxResults ?? DEFAULT_MAX_RESULTS,
108
+ minScore: overrides?.query?.minScore ?? defaults?.query?.minScore ?? DEFAULT_MIN_SCORE
109
+ };
110
+ const hybrid = {
111
+ enabled: overrides?.query?.hybrid?.enabled ?? defaults?.query?.hybrid?.enabled ?? DEFAULT_HYBRID_ENABLED,
112
+ vectorWeight: overrides?.query?.hybrid?.vectorWeight ?? defaults?.query?.hybrid?.vectorWeight ?? DEFAULT_HYBRID_VECTOR_WEIGHT,
113
+ textWeight: overrides?.query?.hybrid?.textWeight ?? defaults?.query?.hybrid?.textWeight ?? DEFAULT_HYBRID_TEXT_WEIGHT,
114
+ candidateMultiplier: overrides?.query?.hybrid?.candidateMultiplier ?? defaults?.query?.hybrid?.candidateMultiplier ?? DEFAULT_HYBRID_CANDIDATE_MULTIPLIER
115
+ };
116
+ const cache = {
117
+ enabled: overrides?.cache?.enabled ?? defaults?.cache?.enabled ?? DEFAULT_CACHE_ENABLED,
118
+ maxEntries: overrides?.cache?.maxEntries ?? defaults?.cache?.maxEntries
119
+ };
120
+ const overlap = clampNumber$1(chunking.overlap, 0, Math.max(0, chunking.tokens - 1));
121
+ const minScore = clampNumber$1(query.minScore, 0, 1);
122
+ const vectorWeight = clampNumber$1(hybrid.vectorWeight, 0, 1);
123
+ const textWeight = clampNumber$1(hybrid.textWeight, 0, 1);
124
+ const sum = vectorWeight + textWeight;
125
+ const normalizedVectorWeight = sum > 0 ? vectorWeight / sum : DEFAULT_HYBRID_VECTOR_WEIGHT;
126
+ const normalizedTextWeight = sum > 0 ? textWeight / sum : DEFAULT_HYBRID_TEXT_WEIGHT;
127
+ const candidateMultiplier = clampInt(hybrid.candidateMultiplier, 1, 20);
128
+ const deltaBytes = clampInt(sync.sessions.deltaBytes, 0, Number.MAX_SAFE_INTEGER);
129
+ const deltaMessages = clampInt(sync.sessions.deltaMessages, 0, Number.MAX_SAFE_INTEGER);
130
+ return {
131
+ enabled,
132
+ sources,
133
+ extraPaths,
134
+ provider,
135
+ remote,
136
+ experimental: { sessionMemory },
137
+ fallback,
138
+ model,
139
+ local,
140
+ store,
141
+ chunking: {
142
+ tokens: Math.max(1, chunking.tokens),
143
+ overlap
144
+ },
145
+ sync: {
146
+ ...sync,
147
+ sessions: {
148
+ deltaBytes,
149
+ deltaMessages
150
+ }
151
+ },
152
+ query: {
153
+ ...query,
154
+ minScore,
155
+ hybrid: {
156
+ enabled: Boolean(hybrid.enabled),
157
+ vectorWeight: normalizedVectorWeight,
158
+ textWeight: normalizedTextWeight,
159
+ candidateMultiplier
160
+ }
161
+ },
162
+ cache: {
163
+ enabled: Boolean(cache.enabled),
164
+ maxEntries: typeof cache.maxEntries === "number" && Number.isFinite(cache.maxEntries) ? Math.max(1, Math.floor(cache.maxEntries)) : void 0
165
+ }
166
+ };
167
+ }
168
+ function resolveMemorySearchConfig(cfg, agentId) {
169
+ const defaults = cfg.agents?.defaults?.memorySearch;
170
+ const overrides = resolveAgentConfig(cfg, agentId)?.memorySearch;
171
+ const resolved = mergeConfig(defaults, overrides, agentId);
172
+ if (!resolved.enabled) return null;
173
+ return resolved;
174
+ }
175
+
176
+ //#endregion
177
+ //#region src/memory/embeddings-gemini.ts
178
+ const DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
179
+ const DEFAULT_GEMINI_EMBEDDING_MODEL$1 = "gemini-embedding-001";
180
+ const GEMINI_MAX_INPUT_TOKENS = { "text-embedding-004": 2048 };
181
+ const debugEmbeddings$1 = isTruthyEnvValue(process.env.ANIMA_DEBUG_MEMORY_EMBEDDINGS);
182
+ const log$4 = createSubsystemLogger("memory/embeddings");
183
+ const debugLog$1 = (message, meta) => {
184
+ if (!debugEmbeddings$1) return;
185
+ const suffix = meta ? ` ${JSON.stringify(meta)}` : "";
186
+ log$4.raw(`${message}${suffix}`);
187
+ };
188
+ function resolveRemoteApiKey(remoteApiKey) {
189
+ const trimmed = remoteApiKey?.trim();
190
+ if (!trimmed) return;
191
+ if (trimmed === "GOOGLE_API_KEY" || trimmed === "GEMINI_API_KEY") return process.env[trimmed]?.trim();
192
+ return trimmed;
193
+ }
194
+ function normalizeGeminiModel(model) {
195
+ const trimmed = model.trim();
196
+ if (!trimmed) return DEFAULT_GEMINI_EMBEDDING_MODEL$1;
197
+ const withoutPrefix = trimmed.replace(/^models\//, "");
198
+ if (withoutPrefix.startsWith("gemini/")) return withoutPrefix.slice(7);
199
+ if (withoutPrefix.startsWith("google/")) return withoutPrefix.slice(7);
200
+ return withoutPrefix;
201
+ }
202
+ function normalizeGeminiBaseUrl(raw) {
203
+ const trimmed = raw.replace(/\/+$/, "");
204
+ const openAiIndex = trimmed.indexOf("/openai");
205
+ if (openAiIndex > -1) return trimmed.slice(0, openAiIndex);
206
+ return trimmed;
207
+ }
208
+ function buildGeminiModelPath(model) {
209
+ return model.startsWith("models/") ? model : `models/${model}`;
210
+ }
211
+ async function createGeminiEmbeddingProvider(options) {
212
+ const client = await resolveGeminiEmbeddingClient(options);
213
+ const baseUrl = client.baseUrl.replace(/\/$/, "");
214
+ const embedUrl = `${baseUrl}/${client.modelPath}:embedContent`;
215
+ const batchUrl = `${baseUrl}/${client.modelPath}:batchEmbedContents`;
216
+ const embedQuery = async (text) => {
217
+ if (!text.trim()) return [];
218
+ const res = await fetch(embedUrl, {
219
+ method: "POST",
220
+ headers: client.headers,
221
+ body: JSON.stringify({
222
+ content: { parts: [{ text }] },
223
+ taskType: "RETRIEVAL_QUERY"
224
+ })
225
+ });
226
+ if (!res.ok) {
227
+ const payload = await res.text();
228
+ throw new Error(`gemini embeddings failed: ${res.status} ${payload}`);
229
+ }
230
+ return (await res.json()).embedding?.values ?? [];
231
+ };
232
+ const embedBatch = async (texts) => {
233
+ if (texts.length === 0) return [];
234
+ const requests = texts.map((text) => ({
235
+ model: client.modelPath,
236
+ content: { parts: [{ text }] },
237
+ taskType: "RETRIEVAL_DOCUMENT"
238
+ }));
239
+ const res = await fetch(batchUrl, {
240
+ method: "POST",
241
+ headers: client.headers,
242
+ body: JSON.stringify({ requests })
243
+ });
244
+ if (!res.ok) {
245
+ const payload = await res.text();
246
+ throw new Error(`gemini embeddings failed: ${res.status} ${payload}`);
247
+ }
248
+ const payload = await res.json();
249
+ const embeddings = Array.isArray(payload.embeddings) ? payload.embeddings : [];
250
+ return texts.map((_, index) => embeddings[index]?.values ?? []);
251
+ };
252
+ return {
253
+ provider: {
254
+ id: "gemini",
255
+ model: client.model,
256
+ maxInputTokens: GEMINI_MAX_INPUT_TOKENS[client.model],
257
+ embedQuery,
258
+ embedBatch
259
+ },
260
+ client
261
+ };
262
+ }
263
+ async function resolveGeminiEmbeddingClient(options) {
264
+ const remote = options.remote;
265
+ const remoteApiKey = resolveRemoteApiKey(remote?.apiKey);
266
+ const remoteBaseUrl = remote?.baseUrl?.trim();
267
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
268
+ provider: "google",
269
+ cfg: options.config,
270
+ agentDir: options.agentDir
271
+ }), "google");
272
+ const providerConfig = options.config.models?.providers?.google;
273
+ const rawBaseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_GEMINI_BASE_URL;
274
+ const baseUrl = normalizeGeminiBaseUrl(rawBaseUrl);
275
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
276
+ const headers = {
277
+ "Content-Type": "application/json",
278
+ "x-goog-api-key": apiKey,
279
+ ...headerOverrides
280
+ };
281
+ const model = normalizeGeminiModel(options.model);
282
+ const modelPath = buildGeminiModelPath(model);
283
+ debugLog$1("memory embeddings: gemini client", {
284
+ rawBaseUrl,
285
+ baseUrl,
286
+ model,
287
+ modelPath,
288
+ embedEndpoint: `${baseUrl}/${modelPath}:embedContent`,
289
+ batchEndpoint: `${baseUrl}/${modelPath}:batchEmbedContents`
290
+ });
291
+ return {
292
+ baseUrl,
293
+ headers,
294
+ model,
295
+ modelPath
296
+ };
297
+ }
298
+
299
+ //#endregion
300
+ //#region src/memory/embeddings-openai.ts
301
+ const DEFAULT_OPENAI_EMBEDDING_MODEL$1 = "text-embedding-3-small";
302
+ const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
303
+ const OPENAI_MAX_INPUT_TOKENS = {
304
+ "text-embedding-3-small": 8192,
305
+ "text-embedding-3-large": 8192,
306
+ "text-embedding-ada-002": 8191
307
+ };
308
+ function normalizeOpenAiModel(model) {
309
+ const trimmed = model.trim();
310
+ if (!trimmed) return DEFAULT_OPENAI_EMBEDDING_MODEL$1;
311
+ if (trimmed.startsWith("openai/")) return trimmed.slice(7);
312
+ return trimmed;
313
+ }
314
+ async function createOpenAiEmbeddingProvider(options) {
315
+ const client = await resolveOpenAiEmbeddingClient(options);
316
+ const url = `${client.baseUrl.replace(/\/$/, "")}/embeddings`;
317
+ const embed = async (input) => {
318
+ if (input.length === 0) return [];
319
+ const res = await fetch(url, {
320
+ method: "POST",
321
+ headers: client.headers,
322
+ body: JSON.stringify({
323
+ model: client.model,
324
+ input
325
+ })
326
+ });
327
+ if (!res.ok) {
328
+ const text = await res.text();
329
+ throw new Error(`openai embeddings failed: ${res.status} ${text}`);
330
+ }
331
+ return ((await res.json()).data ?? []).map((entry) => entry.embedding ?? []);
332
+ };
333
+ return {
334
+ provider: {
335
+ id: "openai",
336
+ model: client.model,
337
+ maxInputTokens: OPENAI_MAX_INPUT_TOKENS[client.model],
338
+ embedQuery: async (text) => {
339
+ const [vec] = await embed([text]);
340
+ return vec ?? [];
341
+ },
342
+ embedBatch: embed
343
+ },
344
+ client
345
+ };
346
+ }
347
+ async function resolveOpenAiEmbeddingClient(options) {
348
+ const remote = options.remote;
349
+ const remoteApiKey = remote?.apiKey?.trim();
350
+ const remoteBaseUrl = remote?.baseUrl?.trim();
351
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
352
+ provider: "openai",
353
+ cfg: options.config,
354
+ agentDir: options.agentDir
355
+ }), "openai");
356
+ const providerConfig = options.config.models?.providers?.openai;
357
+ const baseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_OPENAI_BASE_URL;
358
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
359
+ return {
360
+ baseUrl,
361
+ headers: {
362
+ "Content-Type": "application/json",
363
+ Authorization: `Bearer ${apiKey}`,
364
+ ...headerOverrides
365
+ },
366
+ model: normalizeOpenAiModel(options.model)
367
+ };
368
+ }
369
+
370
+ //#endregion
371
+ //#region src/memory/embeddings-voyage.ts
372
+ const DEFAULT_VOYAGE_EMBEDDING_MODEL$1 = "voyage-4-large";
373
+ const DEFAULT_VOYAGE_BASE_URL = "https://api.voyageai.com/v1";
374
+ const VOYAGE_MAX_INPUT_TOKENS = {
375
+ "voyage-3": 32e3,
376
+ "voyage-3-lite": 16e3,
377
+ "voyage-code-3": 32e3
378
+ };
379
+ function normalizeVoyageModel(model) {
380
+ const trimmed = model.trim();
381
+ if (!trimmed) return DEFAULT_VOYAGE_EMBEDDING_MODEL$1;
382
+ if (trimmed.startsWith("voyage/")) return trimmed.slice(7);
383
+ return trimmed;
384
+ }
385
+ async function createVoyageEmbeddingProvider(options) {
386
+ const client = await resolveVoyageEmbeddingClient(options);
387
+ const url = `${client.baseUrl.replace(/\/$/, "")}/embeddings`;
388
+ const embed = async (input, input_type) => {
389
+ if (input.length === 0) return [];
390
+ const body = {
391
+ model: client.model,
392
+ input
393
+ };
394
+ if (input_type) body.input_type = input_type;
395
+ const res = await fetch(url, {
396
+ method: "POST",
397
+ headers: client.headers,
398
+ body: JSON.stringify(body)
399
+ });
400
+ if (!res.ok) {
401
+ const text = await res.text();
402
+ throw new Error(`voyage embeddings failed: ${res.status} ${text}`);
403
+ }
404
+ return ((await res.json()).data ?? []).map((entry) => entry.embedding ?? []);
405
+ };
406
+ return {
407
+ provider: {
408
+ id: "voyage",
409
+ model: client.model,
410
+ maxInputTokens: VOYAGE_MAX_INPUT_TOKENS[client.model],
411
+ embedQuery: async (text) => {
412
+ const [vec] = await embed([text], "query");
413
+ return vec ?? [];
414
+ },
415
+ embedBatch: async (texts) => embed(texts, "document")
416
+ },
417
+ client
418
+ };
419
+ }
420
+ async function resolveVoyageEmbeddingClient(options) {
421
+ const remote = options.remote;
422
+ const remoteApiKey = remote?.apiKey?.trim();
423
+ const remoteBaseUrl = remote?.baseUrl?.trim();
424
+ const apiKey = remoteApiKey ? remoteApiKey : requireApiKey(await resolveApiKeyForProvider({
425
+ provider: "voyage",
426
+ cfg: options.config,
427
+ agentDir: options.agentDir
428
+ }), "voyage");
429
+ const providerConfig = options.config.models?.providers?.voyage;
430
+ const baseUrl = remoteBaseUrl || providerConfig?.baseUrl?.trim() || DEFAULT_VOYAGE_BASE_URL;
431
+ const headerOverrides = Object.assign({}, providerConfig?.headers, remote?.headers);
432
+ return {
433
+ baseUrl,
434
+ headers: {
435
+ "Content-Type": "application/json",
436
+ Authorization: `Bearer ${apiKey}`,
437
+ ...headerOverrides
438
+ },
439
+ model: normalizeVoyageModel(options.model)
440
+ };
441
+ }
442
+
443
+ //#endregion
444
+ //#region src/memory/node-llama.ts
445
+ async function importNodeLlamaCpp() {
446
+ return import("node-llama-cpp");
447
+ }
448
+
449
+ //#endregion
450
+ //#region src/memory/embeddings.ts
451
+ function sanitizeAndNormalizeEmbedding(vec) {
452
+ const sanitized = vec.map((value) => Number.isFinite(value) ? value : 0);
453
+ const magnitude = Math.sqrt(sanitized.reduce((sum, value) => sum + value * value, 0));
454
+ if (magnitude < 1e-10) return sanitized;
455
+ return sanitized.map((value) => value / magnitude);
456
+ }
457
+ const REMOTE_EMBEDDING_PROVIDER_IDS = [
458
+ "openai",
459
+ "gemini",
460
+ "voyage"
461
+ ];
462
+ const DEFAULT_LOCAL_MODEL = "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
463
+ function canAutoSelectLocal(options) {
464
+ const modelPath = options.local?.modelPath?.trim();
465
+ if (!modelPath) return false;
466
+ if (/^(hf:|https?:)/i.test(modelPath)) return false;
467
+ const resolved = resolveUserPath(modelPath);
468
+ try {
469
+ return fsSync.statSync(resolved).isFile();
470
+ } catch {
471
+ return false;
472
+ }
473
+ }
474
+ function isMissingApiKeyError(err) {
475
+ return formatErrorMessage(err).includes("No API key found for provider");
476
+ }
477
+ async function createLocalEmbeddingProvider(options) {
478
+ const modelPath = options.local?.modelPath?.trim() || DEFAULT_LOCAL_MODEL;
479
+ const modelCacheDir = options.local?.modelCacheDir?.trim();
480
+ const { getLlama, resolveModelFile, LlamaLogLevel } = await importNodeLlamaCpp();
481
+ let llama = null;
482
+ let embeddingModel = null;
483
+ let embeddingContext = null;
484
+ const ensureContext = async () => {
485
+ if (!llama) llama = await getLlama({ logLevel: LlamaLogLevel.error });
486
+ if (!embeddingModel) {
487
+ const resolved = await resolveModelFile(modelPath, modelCacheDir || void 0);
488
+ embeddingModel = await llama.loadModel({ modelPath: resolved });
489
+ }
490
+ if (!embeddingContext) embeddingContext = await embeddingModel.createEmbeddingContext();
491
+ return embeddingContext;
492
+ };
493
+ return {
494
+ id: "local",
495
+ model: modelPath,
496
+ embedQuery: async (text) => {
497
+ const embedding = await (await ensureContext()).getEmbeddingFor(text);
498
+ return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
499
+ },
500
+ embedBatch: async (texts) => {
501
+ const ctx = await ensureContext();
502
+ return await Promise.all(texts.map(async (text) => {
503
+ const embedding = await ctx.getEmbeddingFor(text);
504
+ return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
505
+ }));
506
+ }
507
+ };
508
+ }
509
+ async function createEmbeddingProvider$1(options) {
510
+ const requestedProvider = options.provider;
511
+ const fallback = options.fallback;
512
+ const createProvider = async (id) => {
513
+ if (id === "local") return { provider: await createLocalEmbeddingProvider(options) };
514
+ if (id === "gemini") {
515
+ const { provider, client } = await createGeminiEmbeddingProvider(options);
516
+ return {
517
+ provider,
518
+ gemini: client
519
+ };
520
+ }
521
+ if (id === "voyage") {
522
+ const { provider, client } = await createVoyageEmbeddingProvider(options);
523
+ return {
524
+ provider,
525
+ voyage: client
526
+ };
527
+ }
528
+ const { provider, client } = await createOpenAiEmbeddingProvider(options);
529
+ return {
530
+ provider,
531
+ openAi: client
532
+ };
533
+ };
534
+ const formatPrimaryError = (err, provider) => provider === "local" ? formatLocalSetupError(err) : formatErrorMessage(err);
535
+ if (requestedProvider === "auto") {
536
+ const missingKeyErrors = [];
537
+ let localError = null;
538
+ if (canAutoSelectLocal(options)) try {
539
+ return {
540
+ ...await createProvider("local"),
541
+ requestedProvider
542
+ };
543
+ } catch (err) {
544
+ localError = formatLocalSetupError(err);
545
+ }
546
+ for (const provider of REMOTE_EMBEDDING_PROVIDER_IDS) try {
547
+ return {
548
+ ...await createProvider(provider),
549
+ requestedProvider
550
+ };
551
+ } catch (err) {
552
+ const message = formatPrimaryError(err, provider);
553
+ if (isMissingApiKeyError(err)) {
554
+ missingKeyErrors.push(message);
555
+ continue;
556
+ }
557
+ throw new Error(message, { cause: err });
558
+ }
559
+ const details = [...missingKeyErrors, localError].filter(Boolean);
560
+ if (details.length > 0) throw new Error(details.join("\n\n"));
561
+ throw new Error("No embeddings provider available.");
562
+ }
563
+ try {
564
+ return {
565
+ ...await createProvider(requestedProvider),
566
+ requestedProvider
567
+ };
568
+ } catch (primaryErr) {
569
+ const reason = formatPrimaryError(primaryErr, requestedProvider);
570
+ if (fallback && fallback !== "none" && fallback !== requestedProvider) try {
571
+ return {
572
+ ...await createProvider(fallback),
573
+ requestedProvider,
574
+ fallbackFrom: requestedProvider,
575
+ fallbackReason: reason
576
+ };
577
+ } catch (fallbackErr) {
578
+ throw new Error(`${reason}\n\nFallback to ${fallback} failed: ${formatErrorMessage(fallbackErr)}`, { cause: fallbackErr });
579
+ }
580
+ throw new Error(reason, { cause: primaryErr });
581
+ }
582
+ }
583
+ function isNodeLlamaCppMissing(err) {
584
+ if (!(err instanceof Error)) return false;
585
+ if (err.code === "ERR_MODULE_NOT_FOUND") return err.message.includes("node-llama-cpp");
586
+ return false;
587
+ }
588
+ function formatLocalSetupError(err) {
589
+ const detail = formatErrorMessage(err);
590
+ const missing = isNodeLlamaCppMissing(err);
591
+ return [
592
+ "Local embeddings unavailable.",
593
+ missing ? "Reason: optional dependency node-llama-cpp is missing (or failed to install)." : detail ? `Reason: ${detail}` : void 0,
594
+ missing && detail ? `Detail: ${detail}` : null,
595
+ "To enable local embeddings:",
596
+ "1) Use Node 22 LTS (recommended for installs/updates)",
597
+ missing ? "2) Reinstall Anima (this should install node-llama-cpp): npm i -g anima@latest" : null,
598
+ "3) If you use pnpm: pnpm approve-builds (select node-llama-cpp), then pnpm rebuild node-llama-cpp",
599
+ ...REMOTE_EMBEDDING_PROVIDER_IDS.map((provider) => `Or set agents.defaults.memorySearch.provider = "${provider}" (remote).`)
600
+ ].filter(Boolean).join("\n");
601
+ }
602
+
603
+ //#endregion
604
+ //#region src/memory/hybrid.ts
605
+ function buildFtsQuery(raw) {
606
+ const tokens = raw.match(/[A-Za-z0-9_]+/g)?.map((t) => t.trim()).filter(Boolean) ?? [];
607
+ if (tokens.length === 0) return null;
608
+ return tokens.map((t) => `"${t.replaceAll("\"", "")}"`).join(" AND ");
609
+ }
610
+ function bm25RankToScore(rank) {
611
+ return 1 / (1 + (Number.isFinite(rank) ? Math.max(0, rank) : 999));
612
+ }
613
+ function mergeHybridResults(params) {
614
+ const byId = /* @__PURE__ */ new Map();
615
+ for (const r of params.vector) byId.set(r.id, {
616
+ id: r.id,
617
+ path: r.path,
618
+ startLine: r.startLine,
619
+ endLine: r.endLine,
620
+ source: r.source,
621
+ snippet: r.snippet,
622
+ vectorScore: r.vectorScore,
623
+ textScore: 0
624
+ });
625
+ for (const r of params.keyword) {
626
+ const existing = byId.get(r.id);
627
+ if (existing) {
628
+ existing.textScore = r.textScore;
629
+ if (r.snippet && r.snippet.length > 0) existing.snippet = r.snippet;
630
+ } else byId.set(r.id, {
631
+ id: r.id,
632
+ path: r.path,
633
+ startLine: r.startLine,
634
+ endLine: r.endLine,
635
+ source: r.source,
636
+ snippet: r.snippet,
637
+ vectorScore: 0,
638
+ textScore: r.textScore
639
+ });
640
+ }
641
+ return Array.from(byId.values()).map((entry) => {
642
+ const score = params.vectorWeight * entry.vectorScore + params.textWeight * entry.textScore;
643
+ return {
644
+ path: entry.path,
645
+ startLine: entry.startLine,
646
+ endLine: entry.endLine,
647
+ score,
648
+ snippet: entry.snippet,
649
+ source: entry.source
650
+ };
651
+ }).toSorted((a, b) => b.score - a.score);
652
+ }
653
+
654
+ //#endregion
655
+ //#region src/memory/batch-gemini.ts
656
+ const GEMINI_BATCH_MAX_REQUESTS = 5e4;
657
+ const debugEmbeddings = isTruthyEnvValue(process.env.ANIMA_DEBUG_MEMORY_EMBEDDINGS);
658
+ const log$3 = createSubsystemLogger("memory/embeddings");
659
+ const debugLog = (message, meta) => {
660
+ if (!debugEmbeddings) return;
661
+ const suffix = meta ? ` ${JSON.stringify(meta)}` : "";
662
+ log$3.raw(`${message}${suffix}`);
663
+ };
664
+ function getGeminiBaseUrl(gemini) {
665
+ return gemini.baseUrl?.replace(/\/$/, "") ?? "";
666
+ }
667
+ function getGeminiHeaders(gemini, params) {
668
+ const headers = gemini.headers ? { ...gemini.headers } : {};
669
+ if (params.json) {
670
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
671
+ } else {
672
+ delete headers["Content-Type"];
673
+ delete headers["content-type"];
674
+ }
675
+ return headers;
676
+ }
677
+ function getGeminiUploadUrl(baseUrl) {
678
+ if (baseUrl.includes("/v1beta")) return baseUrl.replace(/\/v1beta\/?$/, "/upload/v1beta");
679
+ return `${baseUrl.replace(/\/$/, "")}/upload`;
680
+ }
681
+ function splitGeminiBatchRequests(requests) {
682
+ if (requests.length <= GEMINI_BATCH_MAX_REQUESTS) return [requests];
683
+ const groups = [];
684
+ for (let i = 0; i < requests.length; i += GEMINI_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + GEMINI_BATCH_MAX_REQUESTS));
685
+ return groups;
686
+ }
687
+ function buildGeminiUploadBody(params) {
688
+ const boundary = `anima-${hashText(params.displayName)}`;
689
+ const jsonPart = JSON.stringify({ file: {
690
+ displayName: params.displayName,
691
+ mimeType: "application/jsonl"
692
+ } });
693
+ const delimiter = `--${boundary}\r\n`;
694
+ const closeDelimiter = `--${boundary}--\r\n`;
695
+ const parts = [
696
+ `${delimiter}Content-Type: application/json; charset=UTF-8\r\n\r\n${jsonPart}\r\n`,
697
+ `${delimiter}Content-Type: application/jsonl; charset=UTF-8\r\n\r\n${params.jsonl}\r\n`,
698
+ closeDelimiter
699
+ ];
700
+ return {
701
+ body: new Blob([parts.join("")], { type: "multipart/related" }),
702
+ contentType: `multipart/related; boundary=${boundary}`
703
+ };
704
+ }
705
+ async function submitGeminiBatch(params) {
706
+ const baseUrl = getGeminiBaseUrl(params.gemini);
707
+ const uploadPayload = buildGeminiUploadBody({
708
+ jsonl: params.requests.map((request) => JSON.stringify({
709
+ key: request.custom_id,
710
+ request: {
711
+ content: request.content,
712
+ task_type: request.taskType
713
+ }
714
+ })).join("\n"),
715
+ displayName: `memory-embeddings-${hashText(String(Date.now()))}`
716
+ });
717
+ const uploadUrl = `${getGeminiUploadUrl(baseUrl)}/files?uploadType=multipart`;
718
+ debugLog("memory embeddings: gemini batch upload", {
719
+ uploadUrl,
720
+ baseUrl,
721
+ requests: params.requests.length
722
+ });
723
+ const fileRes = await fetch(uploadUrl, {
724
+ method: "POST",
725
+ headers: {
726
+ ...getGeminiHeaders(params.gemini, { json: false }),
727
+ "Content-Type": uploadPayload.contentType
728
+ },
729
+ body: uploadPayload.body
730
+ });
731
+ if (!fileRes.ok) {
732
+ const text = await fileRes.text();
733
+ throw new Error(`gemini batch file upload failed: ${fileRes.status} ${text}`);
734
+ }
735
+ const filePayload = await fileRes.json();
736
+ const fileId = filePayload.name ?? filePayload.file?.name;
737
+ if (!fileId) throw new Error("gemini batch file upload failed: missing file id");
738
+ const batchBody = { batch: {
739
+ displayName: `memory-embeddings-${params.agentId}`,
740
+ inputConfig: { file_name: fileId }
741
+ } };
742
+ const batchEndpoint = `${baseUrl}/${params.gemini.modelPath}:asyncBatchEmbedContent`;
743
+ debugLog("memory embeddings: gemini batch create", {
744
+ batchEndpoint,
745
+ fileId
746
+ });
747
+ const batchRes = await fetch(batchEndpoint, {
748
+ method: "POST",
749
+ headers: getGeminiHeaders(params.gemini, { json: true }),
750
+ body: JSON.stringify(batchBody)
751
+ });
752
+ if (batchRes.ok) return await batchRes.json();
753
+ const text = await batchRes.text();
754
+ 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.");
755
+ throw new Error(`gemini batch create failed: ${batchRes.status} ${text}`);
756
+ }
757
+ async function fetchGeminiBatchStatus(params) {
758
+ const statusUrl = `${getGeminiBaseUrl(params.gemini)}/${params.batchName.startsWith("batches/") ? params.batchName : `batches/${params.batchName}`}`;
759
+ debugLog("memory embeddings: gemini batch status", { statusUrl });
760
+ const res = await fetch(statusUrl, { headers: getGeminiHeaders(params.gemini, { json: true }) });
761
+ if (!res.ok) {
762
+ const text = await res.text();
763
+ throw new Error(`gemini batch status failed: ${res.status} ${text}`);
764
+ }
765
+ return await res.json();
766
+ }
767
+ async function fetchGeminiFileContent(params) {
768
+ const downloadUrl = `${getGeminiBaseUrl(params.gemini)}/${params.fileId.startsWith("files/") ? params.fileId : `files/${params.fileId}`}:download`;
769
+ debugLog("memory embeddings: gemini batch download", { downloadUrl });
770
+ const res = await fetch(downloadUrl, { headers: getGeminiHeaders(params.gemini, { json: true }) });
771
+ if (!res.ok) {
772
+ const text = await res.text();
773
+ throw new Error(`gemini batch file content failed: ${res.status} ${text}`);
774
+ }
775
+ return await res.text();
776
+ }
777
+ function parseGeminiBatchOutput(text) {
778
+ if (!text.trim()) return [];
779
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
780
+ }
781
+ async function waitForGeminiBatch(params) {
782
+ const start = Date.now();
783
+ let current = params.initial;
784
+ while (true) {
785
+ const status = current ?? await fetchGeminiBatchStatus({
786
+ gemini: params.gemini,
787
+ batchName: params.batchName
788
+ });
789
+ const state = status.state ?? "UNKNOWN";
790
+ if ([
791
+ "SUCCEEDED",
792
+ "COMPLETED",
793
+ "DONE"
794
+ ].includes(state)) {
795
+ const outputFileId = status.outputConfig?.file ?? status.outputConfig?.fileId ?? status.metadata?.output?.responsesFile;
796
+ if (!outputFileId) throw new Error(`gemini batch ${params.batchName} completed without output file`);
797
+ return { outputFileId };
798
+ }
799
+ if ([
800
+ "FAILED",
801
+ "CANCELLED",
802
+ "CANCELED",
803
+ "EXPIRED"
804
+ ].includes(state)) {
805
+ const message = status.error?.message ?? "unknown error";
806
+ throw new Error(`gemini batch ${params.batchName} ${state}: ${message}`);
807
+ }
808
+ if (!params.wait) throw new Error(`gemini batch ${params.batchName} still ${state}; wait disabled`);
809
+ if (Date.now() - start > params.timeoutMs) throw new Error(`gemini batch ${params.batchName} timed out after ${params.timeoutMs}ms`);
810
+ params.debug?.(`gemini batch ${params.batchName} ${state}; waiting ${params.pollIntervalMs}ms`);
811
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
812
+ current = void 0;
813
+ }
814
+ }
815
+ async function runGeminiEmbeddingBatches(params) {
816
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
817
+ const groups = splitGeminiBatchRequests(params.requests);
818
+ const byCustomId = /* @__PURE__ */ new Map();
819
+ const tasks = groups.map((group, groupIndex) => async () => {
820
+ const batchInfo = await submitGeminiBatch({
821
+ gemini: params.gemini,
822
+ requests: group,
823
+ agentId: params.agentId
824
+ });
825
+ const batchName = batchInfo.name ?? "";
826
+ if (!batchName) throw new Error("gemini batch create failed: missing batch name");
827
+ params.debug?.("memory embeddings: gemini batch created", {
828
+ batchName,
829
+ state: batchInfo.state,
830
+ group: groupIndex + 1,
831
+ groups: groups.length,
832
+ requests: group.length
833
+ });
834
+ if (!params.wait && batchInfo.state && ![
835
+ "SUCCEEDED",
836
+ "COMPLETED",
837
+ "DONE"
838
+ ].includes(batchInfo.state)) throw new Error(`gemini batch ${batchName} submitted; enable remote.batch.wait to await completion`);
839
+ const completed = batchInfo.state && [
840
+ "SUCCEEDED",
841
+ "COMPLETED",
842
+ "DONE"
843
+ ].includes(batchInfo.state) ? { outputFileId: batchInfo.outputConfig?.file ?? batchInfo.outputConfig?.fileId ?? batchInfo.metadata?.output?.responsesFile ?? "" } : await waitForGeminiBatch({
844
+ gemini: params.gemini,
845
+ batchName,
846
+ wait: params.wait,
847
+ pollIntervalMs: params.pollIntervalMs,
848
+ timeoutMs: params.timeoutMs,
849
+ debug: params.debug,
850
+ initial: batchInfo
851
+ });
852
+ if (!completed.outputFileId) throw new Error(`gemini batch ${batchName} completed without output file`);
853
+ const outputLines = parseGeminiBatchOutput(await fetchGeminiFileContent({
854
+ gemini: params.gemini,
855
+ fileId: completed.outputFileId
856
+ }));
857
+ const errors = [];
858
+ const remaining = new Set(group.map((request) => request.custom_id));
859
+ for (const line of outputLines) {
860
+ const customId = line.key ?? line.custom_id ?? line.request_id;
861
+ if (!customId) continue;
862
+ remaining.delete(customId);
863
+ if (line.error?.message) {
864
+ errors.push(`${customId}: ${line.error.message}`);
865
+ continue;
866
+ }
867
+ if (line.response?.error?.message) {
868
+ errors.push(`${customId}: ${line.response.error.message}`);
869
+ continue;
870
+ }
871
+ const embedding = line.embedding?.values ?? line.response?.embedding?.values ?? [];
872
+ if (embedding.length === 0) {
873
+ errors.push(`${customId}: empty embedding`);
874
+ continue;
875
+ }
876
+ byCustomId.set(customId, embedding);
877
+ }
878
+ if (errors.length > 0) throw new Error(`gemini batch ${batchName} failed: ${errors.join("; ")}`);
879
+ if (remaining.size > 0) throw new Error(`gemini batch ${batchName} missing ${remaining.size} embedding responses`);
880
+ });
881
+ params.debug?.("memory embeddings: gemini batch submit", {
882
+ requests: params.requests.length,
883
+ groups: groups.length,
884
+ wait: params.wait,
885
+ concurrency: params.concurrency,
886
+ pollIntervalMs: params.pollIntervalMs,
887
+ timeoutMs: params.timeoutMs
888
+ });
889
+ await runWithConcurrency(tasks, params.concurrency);
890
+ return byCustomId;
891
+ }
892
+
893
+ //#endregion
894
+ //#region src/infra/retry.ts
895
+ const DEFAULT_RETRY_CONFIG = {
896
+ attempts: 3,
897
+ minDelayMs: 300,
898
+ maxDelayMs: 3e4,
899
+ jitter: 0
900
+ };
901
+ const asFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
902
+ const clampNumber = (value, fallback, min, max) => {
903
+ const next = asFiniteNumber(value);
904
+ if (next === void 0) return fallback;
905
+ const floor = typeof min === "number" ? min : Number.NEGATIVE_INFINITY;
906
+ const ceiling = typeof max === "number" ? max : Number.POSITIVE_INFINITY;
907
+ return Math.min(Math.max(next, floor), ceiling);
908
+ };
909
+ function resolveRetryConfig(defaults = DEFAULT_RETRY_CONFIG, overrides) {
910
+ const attempts = Math.max(1, Math.round(clampNumber(overrides?.attempts, defaults.attempts, 1)));
911
+ const minDelayMs = Math.max(0, Math.round(clampNumber(overrides?.minDelayMs, defaults.minDelayMs, 0)));
912
+ return {
913
+ attempts,
914
+ minDelayMs,
915
+ maxDelayMs: Math.max(minDelayMs, Math.round(clampNumber(overrides?.maxDelayMs, defaults.maxDelayMs, 0))),
916
+ jitter: clampNumber(overrides?.jitter, defaults.jitter, 0, 1)
917
+ };
918
+ }
919
+ function applyJitter(delayMs, jitter) {
920
+ if (jitter <= 0) return delayMs;
921
+ const offset = (Math.random() * 2 - 1) * jitter;
922
+ return Math.max(0, Math.round(delayMs * (1 + offset)));
923
+ }
924
+ async function retryAsync(fn, attemptsOrOptions = 3, initialDelayMs = 300) {
925
+ if (typeof attemptsOrOptions === "number") {
926
+ const attempts = Math.max(1, Math.round(attemptsOrOptions));
927
+ let lastErr;
928
+ for (let i = 0; i < attempts; i += 1) try {
929
+ return await fn();
930
+ } catch (err) {
931
+ lastErr = err;
932
+ if (i === attempts - 1) break;
933
+ await sleep(initialDelayMs * 2 ** i);
934
+ }
935
+ throw lastErr ?? /* @__PURE__ */ new Error("Retry failed");
936
+ }
937
+ const options = attemptsOrOptions;
938
+ const resolved = resolveRetryConfig(DEFAULT_RETRY_CONFIG, options);
939
+ const maxAttempts = resolved.attempts;
940
+ const minDelayMs = resolved.minDelayMs;
941
+ const maxDelayMs = Number.isFinite(resolved.maxDelayMs) && resolved.maxDelayMs > 0 ? resolved.maxDelayMs : Number.POSITIVE_INFINITY;
942
+ const jitter = resolved.jitter;
943
+ const shouldRetry = options.shouldRetry ?? (() => true);
944
+ let lastErr;
945
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) try {
946
+ return await fn();
947
+ } catch (err) {
948
+ lastErr = err;
949
+ if (attempt >= maxAttempts || !shouldRetry(err, attempt)) break;
950
+ const retryAfterMs = options.retryAfterMs?.(err);
951
+ const baseDelay = typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? Math.max(retryAfterMs, minDelayMs) : minDelayMs * 2 ** (attempt - 1);
952
+ let delay = Math.min(baseDelay, maxDelayMs);
953
+ delay = applyJitter(delay, jitter);
954
+ delay = Math.min(Math.max(delay, minDelayMs), maxDelayMs);
955
+ options.onRetry?.({
956
+ attempt,
957
+ maxAttempts,
958
+ delayMs: delay,
959
+ err,
960
+ label: options.label
961
+ });
962
+ await sleep(delay);
963
+ }
964
+ throw lastErr ?? /* @__PURE__ */ new Error("Retry failed");
965
+ }
966
+
967
+ //#endregion
968
+ //#region src/memory/batch-http.ts
969
+ async function postJsonWithRetry(params) {
970
+ return await (await retryAsync(async () => {
971
+ const res = await fetch(params.url, {
972
+ method: "POST",
973
+ headers: params.headers,
974
+ body: JSON.stringify(params.body)
975
+ });
976
+ if (!res.ok) {
977
+ const text = await res.text();
978
+ const err = /* @__PURE__ */ new Error(`${params.errorPrefix}: ${res.status} ${text}`);
979
+ err.status = res.status;
980
+ throw err;
981
+ }
982
+ return res;
983
+ }, {
984
+ attempts: 3,
985
+ minDelayMs: 300,
986
+ maxDelayMs: 2e3,
987
+ jitter: .2,
988
+ shouldRetry: (err) => {
989
+ const status = err.status;
990
+ return status === 429 || typeof status === "number" && status >= 500;
991
+ }
992
+ })).json();
993
+ }
994
+
995
+ //#endregion
996
+ //#region src/memory/batch-output.ts
997
+ function applyEmbeddingBatchOutputLine(params) {
998
+ const customId = params.line.custom_id;
999
+ if (!customId) return;
1000
+ params.remaining.delete(customId);
1001
+ const errorMessage = params.line.error?.message;
1002
+ if (errorMessage) {
1003
+ params.errors.push(`${customId}: ${errorMessage}`);
1004
+ return;
1005
+ }
1006
+ const response = params.line.response;
1007
+ if ((response?.status_code ?? 0) >= 400) {
1008
+ const messageFromObject = response?.body && typeof response.body === "object" ? response.body.error?.message : void 0;
1009
+ const messageFromString = typeof response?.body === "string" ? response.body : void 0;
1010
+ params.errors.push(`${customId}: ${messageFromObject ?? messageFromString ?? "unknown error"}`);
1011
+ return;
1012
+ }
1013
+ const embedding = (response?.body && typeof response.body === "object" ? response.body.data ?? [] : [])[0]?.embedding ?? [];
1014
+ if (embedding.length === 0) {
1015
+ params.errors.push(`${customId}: empty embedding`);
1016
+ return;
1017
+ }
1018
+ params.byCustomId.set(customId, embedding);
1019
+ }
1020
+
1021
+ //#endregion
1022
+ //#region src/memory/batch-openai.ts
1023
+ const OPENAI_BATCH_ENDPOINT = "/v1/embeddings";
1024
+ const OPENAI_BATCH_COMPLETION_WINDOW = "24h";
1025
+ const OPENAI_BATCH_MAX_REQUESTS = 5e4;
1026
+ function getOpenAiBaseUrl(openAi) {
1027
+ return openAi.baseUrl?.replace(/\/$/, "") ?? "";
1028
+ }
1029
+ function getOpenAiHeaders(openAi, params) {
1030
+ const headers = openAi.headers ? { ...openAi.headers } : {};
1031
+ if (params.json) {
1032
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
1033
+ } else {
1034
+ delete headers["Content-Type"];
1035
+ delete headers["content-type"];
1036
+ }
1037
+ return headers;
1038
+ }
1039
+ function splitOpenAiBatchRequests(requests) {
1040
+ if (requests.length <= OPENAI_BATCH_MAX_REQUESTS) return [requests];
1041
+ const groups = [];
1042
+ for (let i = 0; i < requests.length; i += OPENAI_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + OPENAI_BATCH_MAX_REQUESTS));
1043
+ return groups;
1044
+ }
1045
+ async function submitOpenAiBatch(params) {
1046
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1047
+ const jsonl = params.requests.map((request) => JSON.stringify(request)).join("\n");
1048
+ const form = new FormData();
1049
+ form.append("purpose", "batch");
1050
+ form.append("file", new Blob([jsonl], { type: "application/jsonl" }), `memory-embeddings.${hashText(String(Date.now()))}.jsonl`);
1051
+ const fileRes = await fetch(`${baseUrl}/files`, {
1052
+ method: "POST",
1053
+ headers: getOpenAiHeaders(params.openAi, { json: false }),
1054
+ body: form
1055
+ });
1056
+ if (!fileRes.ok) {
1057
+ const text = await fileRes.text();
1058
+ throw new Error(`openai batch file upload failed: ${fileRes.status} ${text}`);
1059
+ }
1060
+ const filePayload = await fileRes.json();
1061
+ if (!filePayload.id) throw new Error("openai batch file upload failed: missing file id");
1062
+ return await postJsonWithRetry({
1063
+ url: `${baseUrl}/batches`,
1064
+ headers: getOpenAiHeaders(params.openAi, { json: true }),
1065
+ body: {
1066
+ input_file_id: filePayload.id,
1067
+ endpoint: OPENAI_BATCH_ENDPOINT,
1068
+ completion_window: OPENAI_BATCH_COMPLETION_WINDOW,
1069
+ metadata: {
1070
+ source: "anima-memory",
1071
+ agent: params.agentId
1072
+ }
1073
+ },
1074
+ errorPrefix: "openai batch create failed"
1075
+ });
1076
+ }
1077
+ async function fetchOpenAiBatchStatus(params) {
1078
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1079
+ const res = await fetch(`${baseUrl}/batches/${params.batchId}`, { headers: getOpenAiHeaders(params.openAi, { json: true }) });
1080
+ if (!res.ok) {
1081
+ const text = await res.text();
1082
+ throw new Error(`openai batch status failed: ${res.status} ${text}`);
1083
+ }
1084
+ return await res.json();
1085
+ }
1086
+ async function fetchOpenAiFileContent(params) {
1087
+ const baseUrl = getOpenAiBaseUrl(params.openAi);
1088
+ const res = await fetch(`${baseUrl}/files/${params.fileId}/content`, { headers: getOpenAiHeaders(params.openAi, { json: true }) });
1089
+ if (!res.ok) {
1090
+ const text = await res.text();
1091
+ throw new Error(`openai batch file content failed: ${res.status} ${text}`);
1092
+ }
1093
+ return await res.text();
1094
+ }
1095
+ function parseOpenAiBatchOutput(text) {
1096
+ if (!text.trim()) return [];
1097
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
1098
+ }
1099
+ async function readOpenAiBatchError(params) {
1100
+ try {
1101
+ const first = parseOpenAiBatchOutput(await fetchOpenAiFileContent({
1102
+ openAi: params.openAi,
1103
+ fileId: params.errorFileId
1104
+ })).find((line) => line.error?.message || line.response?.body?.error);
1105
+ return first?.error?.message ?? (typeof first?.response?.body?.error?.message === "string" ? first?.response?.body?.error?.message : void 0);
1106
+ } catch (err) {
1107
+ const message = err instanceof Error ? err.message : String(err);
1108
+ return message ? `error file unavailable: ${message}` : void 0;
1109
+ }
1110
+ }
1111
+ async function waitForOpenAiBatch(params) {
1112
+ const start = Date.now();
1113
+ let current = params.initial;
1114
+ while (true) {
1115
+ const status = current ?? await fetchOpenAiBatchStatus({
1116
+ openAi: params.openAi,
1117
+ batchId: params.batchId
1118
+ });
1119
+ const state = status.status ?? "unknown";
1120
+ if (state === "completed") {
1121
+ if (!status.output_file_id) throw new Error(`openai batch ${params.batchId} completed without output file`);
1122
+ return {
1123
+ outputFileId: status.output_file_id,
1124
+ errorFileId: status.error_file_id ?? void 0
1125
+ };
1126
+ }
1127
+ if ([
1128
+ "failed",
1129
+ "expired",
1130
+ "cancelled",
1131
+ "canceled"
1132
+ ].includes(state)) {
1133
+ const detail = status.error_file_id ? await readOpenAiBatchError({
1134
+ openAi: params.openAi,
1135
+ errorFileId: status.error_file_id
1136
+ }) : void 0;
1137
+ const suffix = detail ? `: ${detail}` : "";
1138
+ throw new Error(`openai batch ${params.batchId} ${state}${suffix}`);
1139
+ }
1140
+ if (!params.wait) throw new Error(`openai batch ${params.batchId} still ${state}; wait disabled`);
1141
+ if (Date.now() - start > params.timeoutMs) throw new Error(`openai batch ${params.batchId} timed out after ${params.timeoutMs}ms`);
1142
+ params.debug?.(`openai batch ${params.batchId} ${state}; waiting ${params.pollIntervalMs}ms`);
1143
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
1144
+ current = void 0;
1145
+ }
1146
+ }
1147
+ async function runOpenAiEmbeddingBatches(params) {
1148
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
1149
+ const groups = splitOpenAiBatchRequests(params.requests);
1150
+ const byCustomId = /* @__PURE__ */ new Map();
1151
+ const tasks = groups.map((group, groupIndex) => async () => {
1152
+ const batchInfo = await submitOpenAiBatch({
1153
+ openAi: params.openAi,
1154
+ requests: group,
1155
+ agentId: params.agentId
1156
+ });
1157
+ if (!batchInfo.id) throw new Error("openai batch create failed: missing batch id");
1158
+ params.debug?.("memory embeddings: openai batch created", {
1159
+ batchId: batchInfo.id,
1160
+ status: batchInfo.status,
1161
+ group: groupIndex + 1,
1162
+ groups: groups.length,
1163
+ requests: group.length
1164
+ });
1165
+ if (!params.wait && batchInfo.status !== "completed") throw new Error(`openai batch ${batchInfo.id} submitted; enable remote.batch.wait to await completion`);
1166
+ const completed = batchInfo.status === "completed" ? {
1167
+ outputFileId: batchInfo.output_file_id ?? "",
1168
+ errorFileId: batchInfo.error_file_id ?? void 0
1169
+ } : await waitForOpenAiBatch({
1170
+ openAi: params.openAi,
1171
+ batchId: batchInfo.id,
1172
+ wait: params.wait,
1173
+ pollIntervalMs: params.pollIntervalMs,
1174
+ timeoutMs: params.timeoutMs,
1175
+ debug: params.debug,
1176
+ initial: batchInfo
1177
+ });
1178
+ if (!completed.outputFileId) throw new Error(`openai batch ${batchInfo.id} completed without output file`);
1179
+ const outputLines = parseOpenAiBatchOutput(await fetchOpenAiFileContent({
1180
+ openAi: params.openAi,
1181
+ fileId: completed.outputFileId
1182
+ }));
1183
+ const errors = [];
1184
+ const remaining = new Set(group.map((request) => request.custom_id));
1185
+ for (const line of outputLines) applyEmbeddingBatchOutputLine({
1186
+ line,
1187
+ remaining,
1188
+ errors,
1189
+ byCustomId
1190
+ });
1191
+ if (errors.length > 0) throw new Error(`openai batch ${batchInfo.id} failed: ${errors.join("; ")}`);
1192
+ if (remaining.size > 0) throw new Error(`openai batch ${batchInfo.id} missing ${remaining.size} embedding responses`);
1193
+ });
1194
+ params.debug?.("memory embeddings: openai batch submit", {
1195
+ requests: params.requests.length,
1196
+ groups: groups.length,
1197
+ wait: params.wait,
1198
+ concurrency: params.concurrency,
1199
+ pollIntervalMs: params.pollIntervalMs,
1200
+ timeoutMs: params.timeoutMs
1201
+ });
1202
+ await runWithConcurrency(tasks, params.concurrency);
1203
+ return byCustomId;
1204
+ }
1205
+
1206
+ //#endregion
1207
+ //#region src/memory/batch-voyage.ts
1208
+ const VOYAGE_BATCH_ENDPOINT = "/v1/embeddings";
1209
+ const VOYAGE_BATCH_COMPLETION_WINDOW = "12h";
1210
+ const VOYAGE_BATCH_MAX_REQUESTS = 5e4;
1211
+ function getVoyageBaseUrl(client) {
1212
+ return client.baseUrl?.replace(/\/$/, "") ?? "";
1213
+ }
1214
+ function getVoyageHeaders(client, params) {
1215
+ const headers = client.headers ? { ...client.headers } : {};
1216
+ if (params.json) {
1217
+ if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
1218
+ } else {
1219
+ delete headers["Content-Type"];
1220
+ delete headers["content-type"];
1221
+ }
1222
+ return headers;
1223
+ }
1224
+ function splitVoyageBatchRequests(requests) {
1225
+ if (requests.length <= VOYAGE_BATCH_MAX_REQUESTS) return [requests];
1226
+ const groups = [];
1227
+ for (let i = 0; i < requests.length; i += VOYAGE_BATCH_MAX_REQUESTS) groups.push(requests.slice(i, i + VOYAGE_BATCH_MAX_REQUESTS));
1228
+ return groups;
1229
+ }
1230
+ async function submitVoyageBatch(params) {
1231
+ const baseUrl = getVoyageBaseUrl(params.client);
1232
+ const jsonl = params.requests.map((request) => JSON.stringify(request)).join("\n");
1233
+ const form = new FormData();
1234
+ form.append("purpose", "batch");
1235
+ form.append("file", new Blob([jsonl], { type: "application/jsonl" }), `memory-embeddings.${hashText(String(Date.now()))}.jsonl`);
1236
+ const fileRes = await fetch(`${baseUrl}/files`, {
1237
+ method: "POST",
1238
+ headers: getVoyageHeaders(params.client, { json: false }),
1239
+ body: form
1240
+ });
1241
+ if (!fileRes.ok) {
1242
+ const text = await fileRes.text();
1243
+ throw new Error(`voyage batch file upload failed: ${fileRes.status} ${text}`);
1244
+ }
1245
+ const filePayload = await fileRes.json();
1246
+ if (!filePayload.id) throw new Error("voyage batch file upload failed: missing file id");
1247
+ return await postJsonWithRetry({
1248
+ url: `${baseUrl}/batches`,
1249
+ headers: getVoyageHeaders(params.client, { json: true }),
1250
+ body: {
1251
+ input_file_id: filePayload.id,
1252
+ endpoint: VOYAGE_BATCH_ENDPOINT,
1253
+ completion_window: VOYAGE_BATCH_COMPLETION_WINDOW,
1254
+ request_params: {
1255
+ model: params.client.model,
1256
+ input_type: "document"
1257
+ },
1258
+ metadata: {
1259
+ source: "anima-memory",
1260
+ agent: params.agentId
1261
+ }
1262
+ },
1263
+ errorPrefix: "voyage batch create failed"
1264
+ });
1265
+ }
1266
+ async function fetchVoyageBatchStatus(params) {
1267
+ const baseUrl = getVoyageBaseUrl(params.client);
1268
+ const res = await fetch(`${baseUrl}/batches/${params.batchId}`, { headers: getVoyageHeaders(params.client, { json: true }) });
1269
+ if (!res.ok) {
1270
+ const text = await res.text();
1271
+ throw new Error(`voyage batch status failed: ${res.status} ${text}`);
1272
+ }
1273
+ return await res.json();
1274
+ }
1275
+ async function readVoyageBatchError(params) {
1276
+ try {
1277
+ const baseUrl = getVoyageBaseUrl(params.client);
1278
+ const res = await fetch(`${baseUrl}/files/${params.errorFileId}/content`, { headers: getVoyageHeaders(params.client, { json: true }) });
1279
+ if (!res.ok) {
1280
+ const text = await res.text();
1281
+ throw new Error(`voyage batch error file content failed: ${res.status} ${text}`);
1282
+ }
1283
+ const text = await res.text();
1284
+ if (!text.trim()) return;
1285
+ 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);
1286
+ return first?.error?.message ?? (typeof first?.response?.body?.error?.message === "string" ? first?.response?.body?.error?.message : void 0);
1287
+ } catch (err) {
1288
+ const message = err instanceof Error ? err.message : String(err);
1289
+ return message ? `error file unavailable: ${message}` : void 0;
1290
+ }
1291
+ }
1292
+ async function waitForVoyageBatch(params) {
1293
+ const start = Date.now();
1294
+ let current = params.initial;
1295
+ while (true) {
1296
+ const status = current ?? await fetchVoyageBatchStatus({
1297
+ client: params.client,
1298
+ batchId: params.batchId
1299
+ });
1300
+ const state = status.status ?? "unknown";
1301
+ if (state === "completed") {
1302
+ if (!status.output_file_id) throw new Error(`voyage batch ${params.batchId} completed without output file`);
1303
+ return {
1304
+ outputFileId: status.output_file_id,
1305
+ errorFileId: status.error_file_id ?? void 0
1306
+ };
1307
+ }
1308
+ if ([
1309
+ "failed",
1310
+ "expired",
1311
+ "cancelled",
1312
+ "canceled"
1313
+ ].includes(state)) {
1314
+ const detail = status.error_file_id ? await readVoyageBatchError({
1315
+ client: params.client,
1316
+ errorFileId: status.error_file_id
1317
+ }) : void 0;
1318
+ const suffix = detail ? `: ${detail}` : "";
1319
+ throw new Error(`voyage batch ${params.batchId} ${state}${suffix}`);
1320
+ }
1321
+ if (!params.wait) throw new Error(`voyage batch ${params.batchId} still ${state}; wait disabled`);
1322
+ if (Date.now() - start > params.timeoutMs) throw new Error(`voyage batch ${params.batchId} timed out after ${params.timeoutMs}ms`);
1323
+ params.debug?.(`voyage batch ${params.batchId} ${state}; waiting ${params.pollIntervalMs}ms`);
1324
+ await new Promise((resolve) => setTimeout(resolve, params.pollIntervalMs));
1325
+ current = void 0;
1326
+ }
1327
+ }
1328
+ async function runVoyageEmbeddingBatches(params) {
1329
+ if (params.requests.length === 0) return /* @__PURE__ */ new Map();
1330
+ const groups = splitVoyageBatchRequests(params.requests);
1331
+ const byCustomId = /* @__PURE__ */ new Map();
1332
+ const tasks = groups.map((group, groupIndex) => async () => {
1333
+ const batchInfo = await submitVoyageBatch({
1334
+ client: params.client,
1335
+ requests: group,
1336
+ agentId: params.agentId
1337
+ });
1338
+ if (!batchInfo.id) throw new Error("voyage batch create failed: missing batch id");
1339
+ params.debug?.("memory embeddings: voyage batch created", {
1340
+ batchId: batchInfo.id,
1341
+ status: batchInfo.status,
1342
+ group: groupIndex + 1,
1343
+ groups: groups.length,
1344
+ requests: group.length
1345
+ });
1346
+ if (!params.wait && batchInfo.status !== "completed") throw new Error(`voyage batch ${batchInfo.id} submitted; enable remote.batch.wait to await completion`);
1347
+ const completed = batchInfo.status === "completed" ? {
1348
+ outputFileId: batchInfo.output_file_id ?? "",
1349
+ errorFileId: batchInfo.error_file_id ?? void 0
1350
+ } : await waitForVoyageBatch({
1351
+ client: params.client,
1352
+ batchId: batchInfo.id,
1353
+ wait: params.wait,
1354
+ pollIntervalMs: params.pollIntervalMs,
1355
+ timeoutMs: params.timeoutMs,
1356
+ debug: params.debug,
1357
+ initial: batchInfo
1358
+ });
1359
+ if (!completed.outputFileId) throw new Error(`voyage batch ${batchInfo.id} completed without output file`);
1360
+ const baseUrl = getVoyageBaseUrl(params.client);
1361
+ const contentRes = await fetch(`${baseUrl}/files/${completed.outputFileId}/content`, { headers: getVoyageHeaders(params.client, { json: true }) });
1362
+ if (!contentRes.ok) {
1363
+ const text = await contentRes.text();
1364
+ throw new Error(`voyage batch file content failed: ${contentRes.status} ${text}`);
1365
+ }
1366
+ const errors = [];
1367
+ const remaining = new Set(group.map((request) => request.custom_id));
1368
+ if (contentRes.body) {
1369
+ const reader = createInterface({
1370
+ input: Readable.fromWeb(contentRes.body),
1371
+ terminal: false
1372
+ });
1373
+ for await (const rawLine of reader) {
1374
+ if (!rawLine.trim()) continue;
1375
+ applyEmbeddingBatchOutputLine({
1376
+ line: JSON.parse(rawLine),
1377
+ remaining,
1378
+ errors,
1379
+ byCustomId
1380
+ });
1381
+ }
1382
+ }
1383
+ if (errors.length > 0) throw new Error(`voyage batch ${batchInfo.id} failed: ${errors.join("; ")}`);
1384
+ if (remaining.size > 0) throw new Error(`voyage batch ${batchInfo.id} missing ${remaining.size} embedding responses`);
1385
+ });
1386
+ params.debug?.("memory embeddings: voyage batch submit", {
1387
+ requests: params.requests.length,
1388
+ groups: groups.length,
1389
+ wait: params.wait,
1390
+ concurrency: params.concurrency,
1391
+ pollIntervalMs: params.pollIntervalMs,
1392
+ timeoutMs: params.timeoutMs
1393
+ });
1394
+ await runWithConcurrency(tasks, params.concurrency);
1395
+ return byCustomId;
1396
+ }
1397
+
1398
+ //#endregion
1399
+ //#region src/memory/embedding-input-limits.ts
1400
+ function estimateUtf8Bytes(text) {
1401
+ if (!text) return 0;
1402
+ return Buffer.byteLength(text, "utf8");
1403
+ }
1404
+ function splitTextToUtf8ByteLimit(text, maxUtf8Bytes) {
1405
+ if (maxUtf8Bytes <= 0) return [text];
1406
+ if (estimateUtf8Bytes(text) <= maxUtf8Bytes) return [text];
1407
+ const parts = [];
1408
+ let cursor = 0;
1409
+ while (cursor < text.length) {
1410
+ let low = cursor + 1;
1411
+ let high = Math.min(text.length, cursor + maxUtf8Bytes);
1412
+ let best = cursor;
1413
+ while (low <= high) {
1414
+ const mid = Math.floor((low + high) / 2);
1415
+ if (estimateUtf8Bytes(text.slice(cursor, mid)) <= maxUtf8Bytes) {
1416
+ best = mid;
1417
+ low = mid + 1;
1418
+ } else high = mid - 1;
1419
+ }
1420
+ if (best <= cursor) best = Math.min(text.length, cursor + 1);
1421
+ 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;
1422
+ const part = text.slice(cursor, best);
1423
+ if (!part) break;
1424
+ parts.push(part);
1425
+ cursor = best;
1426
+ }
1427
+ return parts;
1428
+ }
1429
+
1430
+ //#endregion
1431
+ //#region src/memory/embedding-model-limits.ts
1432
+ const DEFAULT_EMBEDDING_MAX_INPUT_TOKENS = 8192;
1433
+ const KNOWN_EMBEDDING_MAX_INPUT_TOKENS = {
1434
+ "openai:text-embedding-3-small": 8192,
1435
+ "openai:text-embedding-3-large": 8192,
1436
+ "openai:text-embedding-ada-002": 8191,
1437
+ "gemini:text-embedding-004": 2048,
1438
+ "voyage:voyage-3": 32e3,
1439
+ "voyage:voyage-3-lite": 16e3,
1440
+ "voyage:voyage-code-3": 32e3
1441
+ };
1442
+ function resolveEmbeddingMaxInputTokens(provider) {
1443
+ if (typeof provider.maxInputTokens === "number") return provider.maxInputTokens;
1444
+ const known = KNOWN_EMBEDDING_MAX_INPUT_TOKENS[`${provider.id}:${provider.model}`.toLowerCase()];
1445
+ if (typeof known === "number") return known;
1446
+ if (provider.id.toLowerCase() === "gemini") return 2048;
1447
+ return DEFAULT_EMBEDDING_MAX_INPUT_TOKENS;
1448
+ }
1449
+
1450
+ //#endregion
1451
+ //#region src/memory/embedding-chunk-limits.ts
1452
+ function enforceEmbeddingMaxInputTokens(provider, chunks) {
1453
+ const maxInputTokens = resolveEmbeddingMaxInputTokens(provider);
1454
+ const out = [];
1455
+ for (const chunk of chunks) {
1456
+ if (estimateUtf8Bytes(chunk.text) <= maxInputTokens) {
1457
+ out.push(chunk);
1458
+ continue;
1459
+ }
1460
+ for (const text of splitTextToUtf8ByteLimit(chunk.text, maxInputTokens)) out.push({
1461
+ startLine: chunk.startLine,
1462
+ endLine: chunk.endLine,
1463
+ text,
1464
+ hash: hashText(text)
1465
+ });
1466
+ }
1467
+ return out;
1468
+ }
1469
+
1470
+ //#endregion
1471
+ //#region src/memory/manager-embedding-ops.ts
1472
+ const VECTOR_TABLE$2 = "chunks_vec";
1473
+ const FTS_TABLE$2 = "chunks_fts";
1474
+ const EMBEDDING_CACHE_TABLE$2 = "embedding_cache";
1475
+ const EMBEDDING_BATCH_MAX_TOKENS = 8e3;
1476
+ const EMBEDDING_INDEX_CONCURRENCY = 4;
1477
+ const EMBEDDING_RETRY_MAX_ATTEMPTS = 3;
1478
+ const EMBEDDING_RETRY_BASE_DELAY_MS = 500;
1479
+ const EMBEDDING_RETRY_MAX_DELAY_MS = 8e3;
1480
+ const BATCH_FAILURE_LIMIT$1 = 2;
1481
+ const EMBEDDING_QUERY_TIMEOUT_REMOTE_MS = 6e4;
1482
+ const EMBEDDING_QUERY_TIMEOUT_LOCAL_MS = 5 * 6e4;
1483
+ const EMBEDDING_BATCH_TIMEOUT_REMOTE_MS = 2 * 6e4;
1484
+ const EMBEDDING_BATCH_TIMEOUT_LOCAL_MS = 10 * 6e4;
1485
+ const vectorToBlob$1 = (embedding) => Buffer.from(new Float32Array(embedding).buffer);
1486
+ const log$2 = createSubsystemLogger("memory");
1487
+ var MemoryManagerEmbeddingOps = class {
1488
+ buildEmbeddingBatches(chunks) {
1489
+ const batches = [];
1490
+ let current = [];
1491
+ let currentTokens = 0;
1492
+ for (const chunk of chunks) {
1493
+ const estimate = estimateUtf8Bytes(chunk.text);
1494
+ if (current.length > 0 && currentTokens + estimate > EMBEDDING_BATCH_MAX_TOKENS) {
1495
+ batches.push(current);
1496
+ current = [];
1497
+ currentTokens = 0;
1498
+ }
1499
+ if (current.length === 0 && estimate > EMBEDDING_BATCH_MAX_TOKENS) {
1500
+ batches.push([chunk]);
1501
+ continue;
1502
+ }
1503
+ current.push(chunk);
1504
+ currentTokens += estimate;
1505
+ }
1506
+ if (current.length > 0) batches.push(current);
1507
+ return batches;
1508
+ }
1509
+ loadEmbeddingCache(hashes) {
1510
+ if (!this.cache.enabled) return /* @__PURE__ */ new Map();
1511
+ if (hashes.length === 0) return /* @__PURE__ */ new Map();
1512
+ const unique = [];
1513
+ const seen = /* @__PURE__ */ new Set();
1514
+ for (const hash of hashes) {
1515
+ if (!hash) continue;
1516
+ if (seen.has(hash)) continue;
1517
+ seen.add(hash);
1518
+ unique.push(hash);
1519
+ }
1520
+ if (unique.length === 0) return /* @__PURE__ */ new Map();
1521
+ const out = /* @__PURE__ */ new Map();
1522
+ const baseParams = [
1523
+ this.provider.id,
1524
+ this.provider.model,
1525
+ this.providerKey
1526
+ ];
1527
+ const batchSize = 400;
1528
+ for (let start = 0; start < unique.length; start += batchSize) {
1529
+ const batch = unique.slice(start, start + batchSize);
1530
+ const placeholders = batch.map(() => "?").join(", ");
1531
+ 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);
1532
+ for (const row of rows) out.set(row.hash, parseEmbedding(row.embedding));
1533
+ }
1534
+ return out;
1535
+ }
1536
+ upsertEmbeddingCache(entries) {
1537
+ if (!this.cache.enabled) return;
1538
+ if (entries.length === 0) return;
1539
+ const now = Date.now();
1540
+ 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`);
1541
+ for (const entry of entries) {
1542
+ const embedding = entry.embedding ?? [];
1543
+ stmt.run(this.provider.id, this.provider.model, this.providerKey, entry.hash, JSON.stringify(embedding), embedding.length, now);
1544
+ }
1545
+ }
1546
+ pruneEmbeddingCacheIfNeeded() {
1547
+ if (!this.cache.enabled) return;
1548
+ const max = this.cache.maxEntries;
1549
+ if (!max || max <= 0) return;
1550
+ const count = this.db.prepare(`SELECT COUNT(*) as c FROM ${EMBEDDING_CACHE_TABLE$2}`).get()?.c ?? 0;
1551
+ if (count <= max) return;
1552
+ const excess = count - max;
1553
+ 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);
1554
+ }
1555
+ async embedChunksInBatches(chunks) {
1556
+ if (chunks.length === 0) return [];
1557
+ const cached = this.loadEmbeddingCache(chunks.map((chunk) => chunk.hash));
1558
+ const embeddings = Array.from({ length: chunks.length }, () => []);
1559
+ const missing = [];
1560
+ for (let i = 0; i < chunks.length; i += 1) {
1561
+ const chunk = chunks[i];
1562
+ const hit = chunk?.hash ? cached.get(chunk.hash) : void 0;
1563
+ if (hit && hit.length > 0) embeddings[i] = hit;
1564
+ else if (chunk) missing.push({
1565
+ index: i,
1566
+ chunk
1567
+ });
1568
+ }
1569
+ if (missing.length === 0) return embeddings;
1570
+ const missingChunks = missing.map((m) => m.chunk);
1571
+ const batches = this.buildEmbeddingBatches(missingChunks);
1572
+ const toCache = [];
1573
+ let cursor = 0;
1574
+ for (const batch of batches) {
1575
+ const batchEmbeddings = await this.embedBatchWithRetry(batch.map((chunk) => chunk.text));
1576
+ for (let i = 0; i < batch.length; i += 1) {
1577
+ const item = missing[cursor + i];
1578
+ const embedding = batchEmbeddings[i] ?? [];
1579
+ if (item) {
1580
+ embeddings[item.index] = embedding;
1581
+ toCache.push({
1582
+ hash: item.chunk.hash,
1583
+ embedding
1584
+ });
1585
+ }
1586
+ }
1587
+ cursor += batch.length;
1588
+ }
1589
+ this.upsertEmbeddingCache(toCache);
1590
+ return embeddings;
1591
+ }
1592
+ computeProviderKey() {
1593
+ if (this.provider.id === "openai" && this.openAi) {
1594
+ const entries = Object.entries(this.openAi.headers).filter(([key]) => key.toLowerCase() !== "authorization").toSorted(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value]);
1595
+ return hashText(JSON.stringify({
1596
+ provider: "openai",
1597
+ baseUrl: this.openAi.baseUrl,
1598
+ model: this.openAi.model,
1599
+ headers: entries
1600
+ }));
1601
+ }
1602
+ if (this.provider.id === "gemini" && this.gemini) {
1603
+ const entries = Object.entries(this.gemini.headers).filter(([key]) => {
1604
+ const lower = key.toLowerCase();
1605
+ return lower !== "authorization" && lower !== "x-goog-api-key";
1606
+ }).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value]);
1607
+ return hashText(JSON.stringify({
1608
+ provider: "gemini",
1609
+ baseUrl: this.gemini.baseUrl,
1610
+ model: this.gemini.model,
1611
+ headers: entries
1612
+ }));
1613
+ }
1614
+ return hashText(JSON.stringify({
1615
+ provider: this.provider.id,
1616
+ model: this.provider.model
1617
+ }));
1618
+ }
1619
+ async embedChunksWithBatch(chunks, entry, source) {
1620
+ if (this.provider.id === "openai" && this.openAi) return this.embedChunksWithOpenAiBatch(chunks, entry, source);
1621
+ if (this.provider.id === "gemini" && this.gemini) return this.embedChunksWithGeminiBatch(chunks, entry, source);
1622
+ if (this.provider.id === "voyage" && this.voyage) return this.embedChunksWithVoyageBatch(chunks, entry, source);
1623
+ return this.embedChunksInBatches(chunks);
1624
+ }
1625
+ collectCachedEmbeddings(chunks) {
1626
+ const cached = this.loadEmbeddingCache(chunks.map((chunk) => chunk.hash));
1627
+ const embeddings = Array.from({ length: chunks.length }, () => []);
1628
+ const missing = [];
1629
+ for (let i = 0; i < chunks.length; i += 1) {
1630
+ const chunk = chunks[i];
1631
+ const hit = chunk?.hash ? cached.get(chunk.hash) : void 0;
1632
+ if (hit && hit.length > 0) embeddings[i] = hit;
1633
+ else if (chunk) missing.push({
1634
+ index: i,
1635
+ chunk
1636
+ });
1637
+ }
1638
+ return {
1639
+ embeddings,
1640
+ missing
1641
+ };
1642
+ }
1643
+ buildBatchCustomId(params) {
1644
+ return hashText(`${params.source}:${params.entry.path}:${params.chunk.startLine}:${params.chunk.endLine}:${params.chunk.hash}:${params.index}`);
1645
+ }
1646
+ buildBatchRequests(params) {
1647
+ const requests = [];
1648
+ const mapping = /* @__PURE__ */ new Map();
1649
+ for (const item of params.missing) {
1650
+ const chunk = item.chunk;
1651
+ const customId = this.buildBatchCustomId({
1652
+ source: params.source,
1653
+ entry: params.entry,
1654
+ chunk,
1655
+ index: item.index
1656
+ });
1657
+ mapping.set(customId, {
1658
+ index: item.index,
1659
+ hash: chunk.hash
1660
+ });
1661
+ const built = params.build(chunk);
1662
+ requests.push({
1663
+ custom_id: customId,
1664
+ ...built
1665
+ });
1666
+ }
1667
+ return {
1668
+ requests,
1669
+ mapping
1670
+ };
1671
+ }
1672
+ applyBatchEmbeddings(params) {
1673
+ const toCache = [];
1674
+ for (const [customId, embedding] of params.byCustomId.entries()) {
1675
+ const mapped = params.mapping.get(customId);
1676
+ if (!mapped) continue;
1677
+ params.embeddings[mapped.index] = embedding;
1678
+ toCache.push({
1679
+ hash: mapped.hash,
1680
+ embedding
1681
+ });
1682
+ }
1683
+ this.upsertEmbeddingCache(toCache);
1684
+ }
1685
+ async embedChunksWithVoyageBatch(chunks, entry, source) {
1686
+ const voyage = this.voyage;
1687
+ if (!voyage) return this.embedChunksInBatches(chunks);
1688
+ if (chunks.length === 0) return [];
1689
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1690
+ if (missing.length === 0) return embeddings;
1691
+ const { requests, mapping } = this.buildBatchRequests({
1692
+ missing,
1693
+ entry,
1694
+ source,
1695
+ build: (chunk) => ({ body: { input: chunk.text } })
1696
+ });
1697
+ const batchResult = await this.runBatchWithFallback({
1698
+ provider: "voyage",
1699
+ run: async () => await runVoyageEmbeddingBatches({
1700
+ client: voyage,
1701
+ agentId: this.agentId,
1702
+ requests,
1703
+ wait: this.batch.wait,
1704
+ concurrency: this.batch.concurrency,
1705
+ pollIntervalMs: this.batch.pollIntervalMs,
1706
+ timeoutMs: this.batch.timeoutMs,
1707
+ debug: (message, data) => log$2.debug(message, {
1708
+ ...data,
1709
+ source,
1710
+ chunks: chunks.length
1711
+ })
1712
+ }),
1713
+ fallback: async () => await this.embedChunksInBatches(chunks)
1714
+ });
1715
+ if (Array.isArray(batchResult)) return batchResult;
1716
+ this.applyBatchEmbeddings({
1717
+ byCustomId: batchResult,
1718
+ mapping,
1719
+ embeddings
1720
+ });
1721
+ return embeddings;
1722
+ }
1723
+ async embedChunksWithOpenAiBatch(chunks, entry, source) {
1724
+ const openAi = this.openAi;
1725
+ if (!openAi) return this.embedChunksInBatches(chunks);
1726
+ if (chunks.length === 0) return [];
1727
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1728
+ if (missing.length === 0) return embeddings;
1729
+ const { requests, mapping } = this.buildBatchRequests({
1730
+ missing,
1731
+ entry,
1732
+ source,
1733
+ build: (chunk) => ({
1734
+ method: "POST",
1735
+ url: OPENAI_BATCH_ENDPOINT,
1736
+ body: {
1737
+ model: this.openAi?.model ?? this.provider.model,
1738
+ input: chunk.text
1739
+ }
1740
+ })
1741
+ });
1742
+ const batchResult = await this.runBatchWithFallback({
1743
+ provider: "openai",
1744
+ run: async () => await runOpenAiEmbeddingBatches({
1745
+ openAi,
1746
+ agentId: this.agentId,
1747
+ requests,
1748
+ wait: this.batch.wait,
1749
+ concurrency: this.batch.concurrency,
1750
+ pollIntervalMs: this.batch.pollIntervalMs,
1751
+ timeoutMs: this.batch.timeoutMs,
1752
+ debug: (message, data) => log$2.debug(message, {
1753
+ ...data,
1754
+ source,
1755
+ chunks: chunks.length
1756
+ })
1757
+ }),
1758
+ fallback: async () => await this.embedChunksInBatches(chunks)
1759
+ });
1760
+ if (Array.isArray(batchResult)) return batchResult;
1761
+ this.applyBatchEmbeddings({
1762
+ byCustomId: batchResult,
1763
+ mapping,
1764
+ embeddings
1765
+ });
1766
+ return embeddings;
1767
+ }
1768
+ async embedChunksWithGeminiBatch(chunks, entry, source) {
1769
+ const gemini = this.gemini;
1770
+ if (!gemini) return this.embedChunksInBatches(chunks);
1771
+ if (chunks.length === 0) return [];
1772
+ const { embeddings, missing } = this.collectCachedEmbeddings(chunks);
1773
+ if (missing.length === 0) return embeddings;
1774
+ const { requests, mapping } = this.buildBatchRequests({
1775
+ missing,
1776
+ entry,
1777
+ source,
1778
+ build: (chunk) => ({
1779
+ content: { parts: [{ text: chunk.text }] },
1780
+ taskType: "RETRIEVAL_DOCUMENT"
1781
+ })
1782
+ });
1783
+ const batchResult = await this.runBatchWithFallback({
1784
+ provider: "gemini",
1785
+ run: async () => await runGeminiEmbeddingBatches({
1786
+ gemini,
1787
+ agentId: this.agentId,
1788
+ requests,
1789
+ wait: this.batch.wait,
1790
+ concurrency: this.batch.concurrency,
1791
+ pollIntervalMs: this.batch.pollIntervalMs,
1792
+ timeoutMs: this.batch.timeoutMs,
1793
+ debug: (message, data) => log$2.debug(message, {
1794
+ ...data,
1795
+ source,
1796
+ chunks: chunks.length
1797
+ })
1798
+ }),
1799
+ fallback: async () => await this.embedChunksInBatches(chunks)
1800
+ });
1801
+ if (Array.isArray(batchResult)) return batchResult;
1802
+ this.applyBatchEmbeddings({
1803
+ byCustomId: batchResult,
1804
+ mapping,
1805
+ embeddings
1806
+ });
1807
+ return embeddings;
1808
+ }
1809
+ async embedBatchWithRetry(texts) {
1810
+ if (texts.length === 0) return [];
1811
+ let attempt = 0;
1812
+ let delayMs = EMBEDDING_RETRY_BASE_DELAY_MS;
1813
+ while (true) try {
1814
+ const timeoutMs = this.resolveEmbeddingTimeout("batch");
1815
+ log$2.debug("memory embeddings: batch start", {
1816
+ provider: this.provider.id,
1817
+ items: texts.length,
1818
+ timeoutMs
1819
+ });
1820
+ return await this.withTimeout(this.provider.embedBatch(texts), timeoutMs, `memory embeddings batch timed out after ${Math.round(timeoutMs / 1e3)}s`);
1821
+ } catch (err) {
1822
+ const message = err instanceof Error ? err.message : String(err);
1823
+ if (!this.isRetryableEmbeddingError(message) || attempt >= EMBEDDING_RETRY_MAX_ATTEMPTS) throw err;
1824
+ const waitMs = Math.min(EMBEDDING_RETRY_MAX_DELAY_MS, Math.round(delayMs * (1 + Math.random() * .2)));
1825
+ log$2.warn(`memory embeddings rate limited; retrying in ${waitMs}ms`);
1826
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
1827
+ delayMs *= 2;
1828
+ attempt += 1;
1829
+ }
1830
+ }
1831
+ isRetryableEmbeddingError(message) {
1832
+ return /(rate[_ ]limit|too many requests|429|resource has been exhausted|5\d\d|cloudflare)/i.test(message);
1833
+ }
1834
+ resolveEmbeddingTimeout(kind) {
1835
+ const isLocal = this.provider.id === "local";
1836
+ if (kind === "query") return isLocal ? EMBEDDING_QUERY_TIMEOUT_LOCAL_MS : EMBEDDING_QUERY_TIMEOUT_REMOTE_MS;
1837
+ return isLocal ? EMBEDDING_BATCH_TIMEOUT_LOCAL_MS : EMBEDDING_BATCH_TIMEOUT_REMOTE_MS;
1838
+ }
1839
+ async embedQueryWithTimeout(text) {
1840
+ const timeoutMs = this.resolveEmbeddingTimeout("query");
1841
+ log$2.debug("memory embeddings: query start", {
1842
+ provider: this.provider.id,
1843
+ timeoutMs
1844
+ });
1845
+ return await this.withTimeout(this.provider.embedQuery(text), timeoutMs, `memory embeddings query timed out after ${Math.round(timeoutMs / 1e3)}s`);
1846
+ }
1847
+ async withTimeout(promise, timeoutMs, message) {
1848
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return await promise;
1849
+ let timer = null;
1850
+ const timeoutPromise = new Promise((_, reject) => {
1851
+ timer = setTimeout(() => reject(new Error(message)), timeoutMs);
1852
+ });
1853
+ try {
1854
+ return await Promise.race([promise, timeoutPromise]);
1855
+ } finally {
1856
+ if (timer) clearTimeout(timer);
1857
+ }
1858
+ }
1859
+ async withBatchFailureLock(fn) {
1860
+ let release;
1861
+ const wait = this.batchFailureLock;
1862
+ this.batchFailureLock = new Promise((resolve) => {
1863
+ release = resolve;
1864
+ });
1865
+ await wait;
1866
+ try {
1867
+ return await fn();
1868
+ } finally {
1869
+ release();
1870
+ }
1871
+ }
1872
+ async resetBatchFailureCount() {
1873
+ await this.withBatchFailureLock(async () => {
1874
+ if (this.batchFailureCount > 0) log$2.debug("memory embeddings: batch recovered; resetting failure count");
1875
+ this.batchFailureCount = 0;
1876
+ this.batchFailureLastError = void 0;
1877
+ this.batchFailureLastProvider = void 0;
1878
+ });
1879
+ }
1880
+ async recordBatchFailure(params) {
1881
+ return await this.withBatchFailureLock(async () => {
1882
+ if (!this.batch.enabled) return {
1883
+ disabled: true,
1884
+ count: this.batchFailureCount
1885
+ };
1886
+ const increment = params.forceDisable ? BATCH_FAILURE_LIMIT$1 : Math.max(1, params.attempts ?? 1);
1887
+ this.batchFailureCount += increment;
1888
+ this.batchFailureLastError = params.message;
1889
+ this.batchFailureLastProvider = params.provider;
1890
+ const disabled = params.forceDisable || this.batchFailureCount >= BATCH_FAILURE_LIMIT$1;
1891
+ if (disabled) this.batch.enabled = false;
1892
+ return {
1893
+ disabled,
1894
+ count: this.batchFailureCount
1895
+ };
1896
+ });
1897
+ }
1898
+ isBatchTimeoutError(message) {
1899
+ return /timed out|timeout/i.test(message);
1900
+ }
1901
+ async runBatchWithTimeoutRetry(params) {
1902
+ try {
1903
+ return await params.run();
1904
+ } catch (err) {
1905
+ const message = err instanceof Error ? err.message : String(err);
1906
+ if (this.isBatchTimeoutError(message)) {
1907
+ log$2.warn(`memory embeddings: ${params.provider} batch timed out; retrying once`);
1908
+ try {
1909
+ return await params.run();
1910
+ } catch (retryErr) {
1911
+ retryErr.batchAttempts = 2;
1912
+ throw retryErr;
1913
+ }
1914
+ }
1915
+ throw err;
1916
+ }
1917
+ }
1918
+ async runBatchWithFallback(params) {
1919
+ if (!this.batch.enabled) return await params.fallback();
1920
+ try {
1921
+ const result = await this.runBatchWithTimeoutRetry({
1922
+ provider: params.provider,
1923
+ run: params.run
1924
+ });
1925
+ await this.resetBatchFailureCount();
1926
+ return result;
1927
+ } catch (err) {
1928
+ const message = err instanceof Error ? err.message : String(err);
1929
+ const attempts = err.batchAttempts ?? 1;
1930
+ const forceDisable = /asyncBatchEmbedContent not available/i.test(message);
1931
+ const failure = await this.recordBatchFailure({
1932
+ provider: params.provider,
1933
+ message,
1934
+ attempts,
1935
+ forceDisable
1936
+ });
1937
+ const suffix = failure.disabled ? "disabling batch" : "keeping batch enabled";
1938
+ log$2.warn(`memory embeddings: ${params.provider} batch failed (${failure.count}/${BATCH_FAILURE_LIMIT$1}); ${suffix}; falling back to non-batch embeddings: ${message}`);
1939
+ return await params.fallback();
1940
+ }
1941
+ }
1942
+ getIndexConcurrency() {
1943
+ return this.batch.enabled ? this.batch.concurrency : EMBEDDING_INDEX_CONCURRENCY;
1944
+ }
1945
+ async indexFile(entry, options) {
1946
+ const content = options.content ?? await fs.readFile(entry.absPath, "utf-8");
1947
+ const chunks = enforceEmbeddingMaxInputTokens(this.provider, chunkMarkdown(content, this.settings.chunking).filter((chunk) => chunk.text.trim().length > 0));
1948
+ if (options.source === "sessions" && "lineMap" in entry) remapChunkLines(chunks, entry.lineMap);
1949
+ const embeddings = this.batch.enabled ? await this.embedChunksWithBatch(chunks, entry, options.source) : await this.embedChunksInBatches(chunks);
1950
+ const sample = embeddings.find((embedding) => embedding.length > 0);
1951
+ const vectorReady = sample ? await this.ensureVectorReady(sample.length) : false;
1952
+ const now = Date.now();
1953
+ if (vectorReady) try {
1954
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$2} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(entry.path, options.source);
1955
+ } catch {}
1956
+ if (this.fts.enabled && this.fts.available) try {
1957
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$2} WHERE path = ? AND source = ? AND model = ?`).run(entry.path, options.source, this.provider.model);
1958
+ } catch {}
1959
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(entry.path, options.source);
1960
+ for (let i = 0; i < chunks.length; i++) {
1961
+ const chunk = chunks[i];
1962
+ const embedding = embeddings[i] ?? [];
1963
+ const id = hashText(`${options.source}:${entry.path}:${chunk.startLine}:${chunk.endLine}:${chunk.hash}:${this.provider.model}`);
1964
+ this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
1965
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1966
+ ON CONFLICT(id) DO UPDATE SET
1967
+ hash=excluded.hash,
1968
+ model=excluded.model,
1969
+ text=excluded.text,
1970
+ embedding=excluded.embedding,
1971
+ 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);
1972
+ if (vectorReady && embedding.length > 0) {
1973
+ try {
1974
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$2} WHERE id = ?`).run(id);
1975
+ } catch {}
1976
+ this.db.prepare(`INSERT INTO ${VECTOR_TABLE$2} (id, embedding) VALUES (?, ?)`).run(id, vectorToBlob$1(embedding));
1977
+ }
1978
+ 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);
1979
+ }
1980
+ this.db.prepare(`INSERT INTO files (path, source, hash, mtime, size) VALUES (?, ?, ?, ?, ?)
1981
+ ON CONFLICT(path) DO UPDATE SET
1982
+ source=excluded.source,
1983
+ hash=excluded.hash,
1984
+ mtime=excluded.mtime,
1985
+ size=excluded.size`).run(entry.path, options.source, entry.hash, entry.mtimeMs, entry.size);
1986
+ }
1987
+ };
1988
+ const memoryManagerEmbeddingOps = MemoryManagerEmbeddingOps.prototype;
1989
+
1990
+ //#endregion
1991
+ //#region src/memory/manager-search.ts
1992
+ const vectorToBlob = (embedding) => Buffer.from(new Float32Array(embedding).buffer);
1993
+ async function searchVector(params) {
1994
+ if (params.queryVec.length === 0 || params.limit <= 0) return [];
1995
+ if (await params.ensureVectorReady(params.queryVec.length)) return params.db.prepare(`SELECT c.id, c.path, c.start_line, c.end_line, c.text,
1996
+ c.source,
1997
+ vec_distance_cosine(v.embedding, ?) AS dist
1998
+ 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) => ({
1999
+ id: row.id,
2000
+ path: row.path,
2001
+ startLine: row.start_line,
2002
+ endLine: row.end_line,
2003
+ score: 1 - row.dist,
2004
+ snippet: truncateUtf16Safe(row.text, params.snippetMaxChars),
2005
+ source: row.source
2006
+ }));
2007
+ return listChunks({
2008
+ db: params.db,
2009
+ providerModel: params.providerModel,
2010
+ sourceFilter: params.sourceFilterChunks
2011
+ }).map((chunk) => ({
2012
+ chunk,
2013
+ score: cosineSimilarity(params.queryVec, chunk.embedding)
2014
+ })).filter((entry) => Number.isFinite(entry.score)).toSorted((a, b) => b.score - a.score).slice(0, params.limit).map((entry) => ({
2015
+ id: entry.chunk.id,
2016
+ path: entry.chunk.path,
2017
+ startLine: entry.chunk.startLine,
2018
+ endLine: entry.chunk.endLine,
2019
+ score: entry.score,
2020
+ snippet: truncateUtf16Safe(entry.chunk.text, params.snippetMaxChars),
2021
+ source: entry.chunk.source
2022
+ }));
2023
+ }
2024
+ function listChunks(params) {
2025
+ return params.db.prepare(`SELECT id, path, start_line, end_line, text, embedding, source
2026
+ FROM chunks
2027
+ WHERE model = ?${params.sourceFilter.sql}`).all(params.providerModel, ...params.sourceFilter.params).map((row) => ({
2028
+ id: row.id,
2029
+ path: row.path,
2030
+ startLine: row.start_line,
2031
+ endLine: row.end_line,
2032
+ text: row.text,
2033
+ embedding: parseEmbedding(row.embedding),
2034
+ source: row.source
2035
+ }));
2036
+ }
2037
+ async function searchKeyword(params) {
2038
+ if (params.limit <= 0) return [];
2039
+ const ftsQuery = params.buildFtsQuery(params.query);
2040
+ if (!ftsQuery) return [];
2041
+ 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) => {
2042
+ const textScore = params.bm25RankToScore(row.rank);
2043
+ return {
2044
+ id: row.id,
2045
+ path: row.path,
2046
+ startLine: row.start_line,
2047
+ endLine: row.end_line,
2048
+ score: textScore,
2049
+ textScore,
2050
+ snippet: truncateUtf16Safe(row.text, params.snippetMaxChars),
2051
+ source: row.source
2052
+ };
2053
+ });
2054
+ }
2055
+
2056
+ //#endregion
2057
+ //#region src/memory/memory-schema.ts
2058
+ function ensureMemoryIndexSchema(params) {
2059
+ params.db.exec(`
2060
+ CREATE TABLE IF NOT EXISTS meta (
2061
+ key TEXT PRIMARY KEY,
2062
+ value TEXT NOT NULL
2063
+ );
2064
+ `);
2065
+ params.db.exec(`
2066
+ CREATE TABLE IF NOT EXISTS files (
2067
+ path TEXT PRIMARY KEY,
2068
+ source TEXT NOT NULL DEFAULT 'memory',
2069
+ hash TEXT NOT NULL,
2070
+ mtime INTEGER NOT NULL,
2071
+ size INTEGER NOT NULL
2072
+ );
2073
+ `);
2074
+ params.db.exec(`
2075
+ CREATE TABLE IF NOT EXISTS chunks (
2076
+ id TEXT PRIMARY KEY,
2077
+ path TEXT NOT NULL,
2078
+ source TEXT NOT NULL DEFAULT 'memory',
2079
+ start_line INTEGER NOT NULL,
2080
+ end_line INTEGER NOT NULL,
2081
+ hash TEXT NOT NULL,
2082
+ model TEXT NOT NULL,
2083
+ text TEXT NOT NULL,
2084
+ embedding TEXT NOT NULL,
2085
+ updated_at INTEGER NOT NULL
2086
+ );
2087
+ `);
2088
+ params.db.exec(`
2089
+ CREATE TABLE IF NOT EXISTS ${params.embeddingCacheTable} (
2090
+ provider TEXT NOT NULL,
2091
+ model TEXT NOT NULL,
2092
+ provider_key TEXT NOT NULL,
2093
+ hash TEXT NOT NULL,
2094
+ embedding TEXT NOT NULL,
2095
+ dims INTEGER,
2096
+ updated_at INTEGER NOT NULL,
2097
+ PRIMARY KEY (provider, model, provider_key, hash)
2098
+ );
2099
+ `);
2100
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${params.embeddingCacheTable}(updated_at);`);
2101
+ let ftsAvailable = false;
2102
+ let ftsError;
2103
+ if (params.ftsEnabled) try {
2104
+ 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);`);
2105
+ ftsAvailable = true;
2106
+ } catch (err) {
2107
+ const message = err instanceof Error ? err.message : String(err);
2108
+ ftsAvailable = false;
2109
+ ftsError = message;
2110
+ }
2111
+ ensureColumn(params.db, "files", "source", "TEXT NOT NULL DEFAULT 'memory'");
2112
+ ensureColumn(params.db, "chunks", "source", "TEXT NOT NULL DEFAULT 'memory'");
2113
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_path ON chunks(path);`);
2114
+ params.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);`);
2115
+ return {
2116
+ ftsAvailable,
2117
+ ...ftsError ? { ftsError } : {}
2118
+ };
2119
+ }
2120
+ function ensureColumn(db, table, column, definition) {
2121
+ if (db.prepare(`PRAGMA table_info(${table})`).all().some((row) => row.name === column)) return;
2122
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
2123
+ }
2124
+
2125
+ //#endregion
2126
+ //#region src/memory/sqlite-vec.ts
2127
+ async function loadSqliteVecExtension(params) {
2128
+ try {
2129
+ const sqliteVec = await import("sqlite-vec");
2130
+ const resolvedPath = params.extensionPath?.trim() ? params.extensionPath.trim() : void 0;
2131
+ const extensionPath = resolvedPath ?? sqliteVec.getLoadablePath();
2132
+ params.db.enableLoadExtension(true);
2133
+ if (resolvedPath) params.db.loadExtension(extensionPath);
2134
+ else sqliteVec.load(params.db);
2135
+ return {
2136
+ ok: true,
2137
+ extensionPath
2138
+ };
2139
+ } catch (err) {
2140
+ return {
2141
+ ok: false,
2142
+ error: err instanceof Error ? err.message : String(err)
2143
+ };
2144
+ }
2145
+ }
2146
+
2147
+ //#endregion
2148
+ //#region src/memory/manager-sync-ops.ts
2149
+ const META_KEY = "memory_index_meta_v1";
2150
+ const VECTOR_TABLE$1 = "chunks_vec";
2151
+ const FTS_TABLE$1 = "chunks_fts";
2152
+ const EMBEDDING_CACHE_TABLE$1 = "embedding_cache";
2153
+ const SESSION_DIRTY_DEBOUNCE_MS = 5e3;
2154
+ const SESSION_DELTA_READ_CHUNK_BYTES = 64 * 1024;
2155
+ const VECTOR_LOAD_TIMEOUT_MS = 3e4;
2156
+ const IGNORED_MEMORY_WATCH_DIR_NAMES = new Set([
2157
+ ".git",
2158
+ "node_modules",
2159
+ ".pnpm-store",
2160
+ ".venv",
2161
+ "venv",
2162
+ ".tox",
2163
+ "__pycache__"
2164
+ ]);
2165
+ const log$1 = createSubsystemLogger("memory");
2166
+ function shouldIgnoreMemoryWatchPath(watchPath) {
2167
+ return path.normalize(watchPath).split(path.sep).map((segment) => segment.trim().toLowerCase()).some((segment) => IGNORED_MEMORY_WATCH_DIR_NAMES.has(segment));
2168
+ }
2169
+ var MemoryManagerSyncOps = class {
2170
+ async ensureVectorReady(dimensions) {
2171
+ if (!this.vector.enabled) return false;
2172
+ 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`);
2173
+ let ready = false;
2174
+ try {
2175
+ ready = await this.vectorReady;
2176
+ } catch (err) {
2177
+ const message = err instanceof Error ? err.message : String(err);
2178
+ this.vector.available = false;
2179
+ this.vector.loadError = message;
2180
+ this.vectorReady = null;
2181
+ log$1.warn(`sqlite-vec unavailable: ${message}`);
2182
+ return false;
2183
+ }
2184
+ if (ready && typeof dimensions === "number" && dimensions > 0) this.ensureVectorTable(dimensions);
2185
+ return ready;
2186
+ }
2187
+ async loadVectorExtension() {
2188
+ if (this.vector.available !== null) return this.vector.available;
2189
+ if (!this.vector.enabled) {
2190
+ this.vector.available = false;
2191
+ return false;
2192
+ }
2193
+ try {
2194
+ const resolvedPath = this.vector.extensionPath?.trim() ? resolveUserPath(this.vector.extensionPath) : void 0;
2195
+ const loaded = await loadSqliteVecExtension({
2196
+ db: this.db,
2197
+ extensionPath: resolvedPath
2198
+ });
2199
+ if (!loaded.ok) throw new Error(loaded.error ?? "unknown sqlite-vec load error");
2200
+ this.vector.extensionPath = loaded.extensionPath;
2201
+ this.vector.available = true;
2202
+ return true;
2203
+ } catch (err) {
2204
+ const message = err instanceof Error ? err.message : String(err);
2205
+ this.vector.available = false;
2206
+ this.vector.loadError = message;
2207
+ log$1.warn(`sqlite-vec unavailable: ${message}`);
2208
+ return false;
2209
+ }
2210
+ }
2211
+ ensureVectorTable(dimensions) {
2212
+ if (this.vector.dims === dimensions) return;
2213
+ if (this.vector.dims && this.vector.dims !== dimensions) this.dropVectorTable();
2214
+ this.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${VECTOR_TABLE$1} USING vec0(\n id TEXT PRIMARY KEY,\n embedding FLOAT[${dimensions}]\n)`);
2215
+ this.vector.dims = dimensions;
2216
+ }
2217
+ dropVectorTable() {
2218
+ try {
2219
+ this.db.exec(`DROP TABLE IF EXISTS ${VECTOR_TABLE$1}`);
2220
+ } catch (err) {
2221
+ const message = err instanceof Error ? err.message : String(err);
2222
+ log$1.debug(`Failed to drop ${VECTOR_TABLE$1}: ${message}`);
2223
+ }
2224
+ }
2225
+ buildSourceFilter(alias) {
2226
+ const sources = Array.from(this.sources);
2227
+ if (sources.length === 0) return {
2228
+ sql: "",
2229
+ params: []
2230
+ };
2231
+ return {
2232
+ sql: ` AND ${alias ? `${alias}.source` : "source"} IN (${sources.map(() => "?").join(", ")})`,
2233
+ params: sources
2234
+ };
2235
+ }
2236
+ openDatabase() {
2237
+ const dbPath = resolveUserPath(this.settings.store.path);
2238
+ return this.openDatabaseAtPath(dbPath);
2239
+ }
2240
+ openDatabaseAtPath(dbPath) {
2241
+ ensureDir(path.dirname(dbPath));
2242
+ const { DatabaseSync } = requireNodeSqlite();
2243
+ return new DatabaseSync(dbPath, { allowExtension: this.settings.store.vector.enabled });
2244
+ }
2245
+ seedEmbeddingCache(sourceDb) {
2246
+ if (!this.cache.enabled) return;
2247
+ try {
2248
+ const rows = sourceDb.prepare(`SELECT provider, model, provider_key, hash, embedding, dims, updated_at FROM ${EMBEDDING_CACHE_TABLE$1}`).all();
2249
+ if (!rows.length) return;
2250
+ const insert = this.db.prepare(`INSERT INTO ${EMBEDDING_CACHE_TABLE$1} (provider, model, provider_key, hash, embedding, dims, updated_at)
2251
+ VALUES (?, ?, ?, ?, ?, ?, ?)
2252
+ ON CONFLICT(provider, model, provider_key, hash) DO UPDATE SET
2253
+ embedding=excluded.embedding,
2254
+ dims=excluded.dims,
2255
+ updated_at=excluded.updated_at`);
2256
+ this.db.exec("BEGIN");
2257
+ for (const row of rows) insert.run(row.provider, row.model, row.provider_key, row.hash, row.embedding, row.dims, row.updated_at);
2258
+ this.db.exec("COMMIT");
2259
+ } catch (err) {
2260
+ try {
2261
+ this.db.exec("ROLLBACK");
2262
+ } catch {}
2263
+ throw err;
2264
+ }
2265
+ }
2266
+ async swapIndexFiles(targetPath, tempPath) {
2267
+ const backupPath = `${targetPath}.backup-${randomUUID()}`;
2268
+ await this.moveIndexFiles(targetPath, backupPath);
2269
+ try {
2270
+ await this.moveIndexFiles(tempPath, targetPath);
2271
+ } catch (err) {
2272
+ await this.moveIndexFiles(backupPath, targetPath);
2273
+ throw err;
2274
+ }
2275
+ await this.removeIndexFiles(backupPath);
2276
+ }
2277
+ async moveIndexFiles(sourceBase, targetBase) {
2278
+ for (const suffix of [
2279
+ "",
2280
+ "-wal",
2281
+ "-shm"
2282
+ ]) {
2283
+ const source = `${sourceBase}${suffix}`;
2284
+ const target = `${targetBase}${suffix}`;
2285
+ try {
2286
+ await fs.rename(source, target);
2287
+ } catch (err) {
2288
+ if (err.code !== "ENOENT") throw err;
2289
+ }
2290
+ }
2291
+ }
2292
+ async removeIndexFiles(basePath) {
2293
+ await Promise.all([
2294
+ "",
2295
+ "-wal",
2296
+ "-shm"
2297
+ ].map((suffix) => fs.rm(`${basePath}${suffix}`, { force: true })));
2298
+ }
2299
+ ensureSchema() {
2300
+ const result = ensureMemoryIndexSchema({
2301
+ db: this.db,
2302
+ embeddingCacheTable: EMBEDDING_CACHE_TABLE$1,
2303
+ ftsTable: FTS_TABLE$1,
2304
+ ftsEnabled: this.fts.enabled
2305
+ });
2306
+ this.fts.available = result.ftsAvailable;
2307
+ if (result.ftsError) {
2308
+ this.fts.loadError = result.ftsError;
2309
+ log$1.warn(`fts unavailable: ${result.ftsError}`);
2310
+ }
2311
+ }
2312
+ ensureWatcher() {
2313
+ if (!this.sources.has("memory") || !this.settings.sync.watch || this.watcher) return;
2314
+ const watchPaths = new Set([
2315
+ path.join(this.workspaceDir, "MEMORY.md"),
2316
+ path.join(this.workspaceDir, "memory.md"),
2317
+ path.join(this.workspaceDir, "memory", "**", "*.md")
2318
+ ]);
2319
+ const additionalPaths = normalizeExtraMemoryPaths(this.workspaceDir, this.settings.extraPaths);
2320
+ for (const entry of additionalPaths) try {
2321
+ const stat = fsSync.lstatSync(entry);
2322
+ if (stat.isSymbolicLink()) continue;
2323
+ if (stat.isDirectory()) {
2324
+ watchPaths.add(path.join(entry, "**", "*.md"));
2325
+ continue;
2326
+ }
2327
+ if (stat.isFile() && entry.toLowerCase().endsWith(".md")) watchPaths.add(entry);
2328
+ } catch {}
2329
+ this.watcher = chokidar.watch(Array.from(watchPaths), {
2330
+ ignoreInitial: true,
2331
+ ignored: (watchPath) => shouldIgnoreMemoryWatchPath(String(watchPath)),
2332
+ awaitWriteFinish: {
2333
+ stabilityThreshold: this.settings.sync.watchDebounceMs,
2334
+ pollInterval: 100
2335
+ }
2336
+ });
2337
+ const markDirty = () => {
2338
+ this.dirty = true;
2339
+ this.scheduleWatchSync();
2340
+ };
2341
+ this.watcher.on("add", markDirty);
2342
+ this.watcher.on("change", markDirty);
2343
+ this.watcher.on("unlink", markDirty);
2344
+ }
2345
+ ensureSessionListener() {
2346
+ if (!this.sources.has("sessions") || this.sessionUnsubscribe) return;
2347
+ this.sessionUnsubscribe = onSessionTranscriptUpdate((update) => {
2348
+ if (this.closed) return;
2349
+ const sessionFile = update.sessionFile;
2350
+ if (!this.isSessionFileForAgent(sessionFile)) return;
2351
+ this.scheduleSessionDirty(sessionFile);
2352
+ });
2353
+ }
2354
+ scheduleSessionDirty(sessionFile) {
2355
+ this.sessionPendingFiles.add(sessionFile);
2356
+ if (this.sessionWatchTimer) return;
2357
+ this.sessionWatchTimer = setTimeout(() => {
2358
+ this.sessionWatchTimer = null;
2359
+ this.processSessionDeltaBatch().catch((err) => {
2360
+ log$1.warn(`memory session delta failed: ${String(err)}`);
2361
+ });
2362
+ }, SESSION_DIRTY_DEBOUNCE_MS);
2363
+ }
2364
+ async processSessionDeltaBatch() {
2365
+ if (this.sessionPendingFiles.size === 0) return;
2366
+ const pending = Array.from(this.sessionPendingFiles);
2367
+ this.sessionPendingFiles.clear();
2368
+ let shouldSync = false;
2369
+ for (const sessionFile of pending) {
2370
+ const delta = await this.updateSessionDelta(sessionFile);
2371
+ if (!delta) continue;
2372
+ const bytesThreshold = delta.deltaBytes;
2373
+ const messagesThreshold = delta.deltaMessages;
2374
+ const bytesHit = bytesThreshold <= 0 ? delta.pendingBytes > 0 : delta.pendingBytes >= bytesThreshold;
2375
+ const messagesHit = messagesThreshold <= 0 ? delta.pendingMessages > 0 : delta.pendingMessages >= messagesThreshold;
2376
+ if (!bytesHit && !messagesHit) continue;
2377
+ this.sessionsDirtyFiles.add(sessionFile);
2378
+ this.sessionsDirty = true;
2379
+ delta.pendingBytes = bytesThreshold > 0 ? Math.max(0, delta.pendingBytes - bytesThreshold) : 0;
2380
+ delta.pendingMessages = messagesThreshold > 0 ? Math.max(0, delta.pendingMessages - messagesThreshold) : 0;
2381
+ shouldSync = true;
2382
+ }
2383
+ if (shouldSync) this.sync({ reason: "session-delta" }).catch((err) => {
2384
+ log$1.warn(`memory sync failed (session-delta): ${String(err)}`);
2385
+ });
2386
+ }
2387
+ async updateSessionDelta(sessionFile) {
2388
+ const thresholds = this.settings.sync.sessions;
2389
+ if (!thresholds) return null;
2390
+ let stat;
2391
+ try {
2392
+ stat = await fs.stat(sessionFile);
2393
+ } catch {
2394
+ return null;
2395
+ }
2396
+ const size = stat.size;
2397
+ let state = this.sessionDeltas.get(sessionFile);
2398
+ if (!state) {
2399
+ state = {
2400
+ lastSize: 0,
2401
+ pendingBytes: 0,
2402
+ pendingMessages: 0
2403
+ };
2404
+ this.sessionDeltas.set(sessionFile, state);
2405
+ }
2406
+ const deltaBytes = Math.max(0, size - state.lastSize);
2407
+ if (deltaBytes === 0 && size === state.lastSize) return {
2408
+ deltaBytes: thresholds.deltaBytes,
2409
+ deltaMessages: thresholds.deltaMessages,
2410
+ pendingBytes: state.pendingBytes,
2411
+ pendingMessages: state.pendingMessages
2412
+ };
2413
+ if (size < state.lastSize) {
2414
+ state.lastSize = size;
2415
+ state.pendingBytes += size;
2416
+ if (thresholds.deltaMessages > 0 && (thresholds.deltaBytes <= 0 || state.pendingBytes < thresholds.deltaBytes)) state.pendingMessages += await this.countNewlines(sessionFile, 0, size);
2417
+ } else {
2418
+ state.pendingBytes += deltaBytes;
2419
+ if (thresholds.deltaMessages > 0 && (thresholds.deltaBytes <= 0 || state.pendingBytes < thresholds.deltaBytes)) state.pendingMessages += await this.countNewlines(sessionFile, state.lastSize, size);
2420
+ state.lastSize = size;
2421
+ }
2422
+ this.sessionDeltas.set(sessionFile, state);
2423
+ return {
2424
+ deltaBytes: thresholds.deltaBytes,
2425
+ deltaMessages: thresholds.deltaMessages,
2426
+ pendingBytes: state.pendingBytes,
2427
+ pendingMessages: state.pendingMessages
2428
+ };
2429
+ }
2430
+ async countNewlines(absPath, start, end) {
2431
+ if (end <= start) return 0;
2432
+ const handle = await fs.open(absPath, "r");
2433
+ try {
2434
+ let offset = start;
2435
+ let count = 0;
2436
+ const buffer = Buffer.alloc(SESSION_DELTA_READ_CHUNK_BYTES);
2437
+ while (offset < end) {
2438
+ const toRead = Math.min(buffer.length, end - offset);
2439
+ const { bytesRead } = await handle.read(buffer, 0, toRead, offset);
2440
+ if (bytesRead <= 0) break;
2441
+ for (let i = 0; i < bytesRead; i += 1) if (buffer[i] === 10) count += 1;
2442
+ offset += bytesRead;
2443
+ }
2444
+ return count;
2445
+ } finally {
2446
+ await handle.close();
2447
+ }
2448
+ }
2449
+ resetSessionDelta(absPath, size) {
2450
+ const state = this.sessionDeltas.get(absPath);
2451
+ if (!state) return;
2452
+ state.lastSize = size;
2453
+ state.pendingBytes = 0;
2454
+ state.pendingMessages = 0;
2455
+ }
2456
+ isSessionFileForAgent(sessionFile) {
2457
+ if (!sessionFile) return false;
2458
+ const sessionsDir = resolveSessionTranscriptsDirForAgent(this.agentId);
2459
+ const resolvedFile = path.resolve(sessionFile);
2460
+ const resolvedDir = path.resolve(sessionsDir);
2461
+ return resolvedFile.startsWith(`${resolvedDir}${path.sep}`);
2462
+ }
2463
+ ensureIntervalSync() {
2464
+ const minutes = this.settings.sync.intervalMinutes;
2465
+ if (!minutes || minutes <= 0 || this.intervalTimer) return;
2466
+ const ms = minutes * 60 * 1e3;
2467
+ this.intervalTimer = setInterval(() => {
2468
+ this.sync({ reason: "interval" }).catch((err) => {
2469
+ log$1.warn(`memory sync failed (interval): ${String(err)}`);
2470
+ });
2471
+ }, ms);
2472
+ }
2473
+ scheduleWatchSync() {
2474
+ if (!this.sources.has("memory") || !this.settings.sync.watch) return;
2475
+ if (this.watchTimer) clearTimeout(this.watchTimer);
2476
+ this.watchTimer = setTimeout(() => {
2477
+ this.watchTimer = null;
2478
+ this.sync({ reason: "watch" }).catch((err) => {
2479
+ log$1.warn(`memory sync failed (watch): ${String(err)}`);
2480
+ });
2481
+ }, this.settings.sync.watchDebounceMs);
2482
+ }
2483
+ shouldSyncSessions(params, needsFullReindex = false) {
2484
+ if (!this.sources.has("sessions")) return false;
2485
+ if (params?.force) return true;
2486
+ const reason = params?.reason;
2487
+ if (reason === "session-start" || reason === "watch") return false;
2488
+ if (needsFullReindex) return true;
2489
+ return this.sessionsDirty && this.sessionsDirtyFiles.size > 0;
2490
+ }
2491
+ async syncMemoryFiles(params) {
2492
+ const files = await listMemoryFiles(this.workspaceDir, this.settings.extraPaths);
2493
+ const fileEntries = await Promise.all(files.map(async (file) => buildFileEntry(file, this.workspaceDir)));
2494
+ log$1.debug("memory sync: indexing memory files", {
2495
+ files: fileEntries.length,
2496
+ needsFullReindex: params.needsFullReindex,
2497
+ batch: this.batch.enabled,
2498
+ concurrency: this.getIndexConcurrency()
2499
+ });
2500
+ const activePaths = new Set(fileEntries.map((entry) => entry.path));
2501
+ if (params.progress) {
2502
+ params.progress.total += fileEntries.length;
2503
+ params.progress.report({
2504
+ completed: params.progress.completed,
2505
+ total: params.progress.total,
2506
+ label: this.batch.enabled ? "Indexing memory files (batch)..." : "Indexing memory files…"
2507
+ });
2508
+ }
2509
+ await runWithConcurrency(fileEntries.map((entry) => async () => {
2510
+ const record = this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(entry.path, "memory");
2511
+ if (!params.needsFullReindex && record?.hash === entry.hash) {
2512
+ if (params.progress) {
2513
+ params.progress.completed += 1;
2514
+ params.progress.report({
2515
+ completed: params.progress.completed,
2516
+ total: params.progress.total
2517
+ });
2518
+ }
2519
+ return;
2520
+ }
2521
+ await this.indexFile(entry, { source: "memory" });
2522
+ if (params.progress) {
2523
+ params.progress.completed += 1;
2524
+ params.progress.report({
2525
+ completed: params.progress.completed,
2526
+ total: params.progress.total
2527
+ });
2528
+ }
2529
+ }), this.getIndexConcurrency());
2530
+ const staleRows = this.db.prepare(`SELECT path FROM files WHERE source = ?`).all("memory");
2531
+ for (const stale of staleRows) {
2532
+ if (activePaths.has(stale.path)) continue;
2533
+ this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "memory");
2534
+ try {
2535
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$1} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(stale.path, "memory");
2536
+ } catch {}
2537
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "memory");
2538
+ if (this.fts.enabled && this.fts.available) try {
2539
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$1} WHERE path = ? AND source = ? AND model = ?`).run(stale.path, "memory", this.provider.model);
2540
+ } catch {}
2541
+ }
2542
+ }
2543
+ async syncSessionFiles(params) {
2544
+ const files = await listSessionFilesForAgent(this.agentId);
2545
+ const activePaths = new Set(files.map((file) => sessionPathForFile(file)));
2546
+ const indexAll = params.needsFullReindex || this.sessionsDirtyFiles.size === 0;
2547
+ log$1.debug("memory sync: indexing session files", {
2548
+ files: files.length,
2549
+ indexAll,
2550
+ dirtyFiles: this.sessionsDirtyFiles.size,
2551
+ batch: this.batch.enabled,
2552
+ concurrency: this.getIndexConcurrency()
2553
+ });
2554
+ if (params.progress) {
2555
+ params.progress.total += files.length;
2556
+ params.progress.report({
2557
+ completed: params.progress.completed,
2558
+ total: params.progress.total,
2559
+ label: this.batch.enabled ? "Indexing session files (batch)..." : "Indexing session files…"
2560
+ });
2561
+ }
2562
+ await runWithConcurrency(files.map((absPath) => async () => {
2563
+ if (!indexAll && !this.sessionsDirtyFiles.has(absPath)) {
2564
+ if (params.progress) {
2565
+ params.progress.completed += 1;
2566
+ params.progress.report({
2567
+ completed: params.progress.completed,
2568
+ total: params.progress.total
2569
+ });
2570
+ }
2571
+ return;
2572
+ }
2573
+ const entry = await buildSessionEntry(absPath);
2574
+ if (!entry) {
2575
+ if (params.progress) {
2576
+ params.progress.completed += 1;
2577
+ params.progress.report({
2578
+ completed: params.progress.completed,
2579
+ total: params.progress.total
2580
+ });
2581
+ }
2582
+ return;
2583
+ }
2584
+ const record = this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(entry.path, "sessions");
2585
+ if (!params.needsFullReindex && record?.hash === entry.hash) {
2586
+ if (params.progress) {
2587
+ params.progress.completed += 1;
2588
+ params.progress.report({
2589
+ completed: params.progress.completed,
2590
+ total: params.progress.total
2591
+ });
2592
+ }
2593
+ this.resetSessionDelta(absPath, entry.size);
2594
+ return;
2595
+ }
2596
+ await this.indexFile(entry, {
2597
+ source: "sessions",
2598
+ content: entry.content
2599
+ });
2600
+ this.resetSessionDelta(absPath, entry.size);
2601
+ if (params.progress) {
2602
+ params.progress.completed += 1;
2603
+ params.progress.report({
2604
+ completed: params.progress.completed,
2605
+ total: params.progress.total
2606
+ });
2607
+ }
2608
+ }), this.getIndexConcurrency());
2609
+ const staleRows = this.db.prepare(`SELECT path FROM files WHERE source = ?`).all("sessions");
2610
+ for (const stale of staleRows) {
2611
+ if (activePaths.has(stale.path)) continue;
2612
+ this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "sessions");
2613
+ try {
2614
+ this.db.prepare(`DELETE FROM ${VECTOR_TABLE$1} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(stale.path, "sessions");
2615
+ } catch {}
2616
+ this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "sessions");
2617
+ if (this.fts.enabled && this.fts.available) try {
2618
+ this.db.prepare(`DELETE FROM ${FTS_TABLE$1} WHERE path = ? AND source = ? AND model = ?`).run(stale.path, "sessions", this.provider.model);
2619
+ } catch {}
2620
+ }
2621
+ }
2622
+ createSyncProgress(onProgress) {
2623
+ const state = {
2624
+ completed: 0,
2625
+ total: 0,
2626
+ label: void 0,
2627
+ report: (update) => {
2628
+ if (update.label) state.label = update.label;
2629
+ const label = update.total > 0 && state.label ? `${state.label} ${update.completed}/${update.total}` : state.label;
2630
+ onProgress({
2631
+ completed: update.completed,
2632
+ total: update.total,
2633
+ label
2634
+ });
2635
+ }
2636
+ };
2637
+ return state;
2638
+ }
2639
+ async runSync(params) {
2640
+ const progress = params?.progress ? this.createSyncProgress(params.progress) : void 0;
2641
+ if (progress) progress.report({
2642
+ completed: progress.completed,
2643
+ total: progress.total,
2644
+ label: "Loading vector extension…"
2645
+ });
2646
+ const vectorReady = await this.ensureVectorReady();
2647
+ const meta = this.readMeta();
2648
+ 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;
2649
+ try {
2650
+ if (needsFullReindex) {
2651
+ if (process.env.ANIMA_TEST_FAST === "1" && process.env.ANIMA_TEST_MEMORY_UNSAFE_REINDEX === "1") await this.runUnsafeReindex({
2652
+ reason: params?.reason,
2653
+ force: params?.force,
2654
+ progress: progress ?? void 0
2655
+ });
2656
+ else await this.runSafeReindex({
2657
+ reason: params?.reason,
2658
+ force: params?.force,
2659
+ progress: progress ?? void 0
2660
+ });
2661
+ return;
2662
+ }
2663
+ const shouldSyncMemory = this.sources.has("memory") && (params?.force || needsFullReindex || this.dirty);
2664
+ const shouldSyncSessions = this.shouldSyncSessions(params, needsFullReindex);
2665
+ if (shouldSyncMemory) {
2666
+ await this.syncMemoryFiles({
2667
+ needsFullReindex,
2668
+ progress: progress ?? void 0
2669
+ });
2670
+ this.dirty = false;
2671
+ }
2672
+ if (shouldSyncSessions) {
2673
+ await this.syncSessionFiles({
2674
+ needsFullReindex,
2675
+ progress: progress ?? void 0
2676
+ });
2677
+ this.sessionsDirty = false;
2678
+ this.sessionsDirtyFiles.clear();
2679
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2680
+ else this.sessionsDirty = false;
2681
+ } catch (err) {
2682
+ const reason = err instanceof Error ? err.message : String(err);
2683
+ if (this.shouldFallbackOnError(reason) && await this.activateFallbackProvider(reason)) {
2684
+ await this.runSafeReindex({
2685
+ reason: params?.reason ?? "fallback",
2686
+ force: true,
2687
+ progress: progress ?? void 0
2688
+ });
2689
+ return;
2690
+ }
2691
+ throw err;
2692
+ }
2693
+ }
2694
+ shouldFallbackOnError(message) {
2695
+ return /embedding|embeddings|batch/i.test(message);
2696
+ }
2697
+ resolveBatchConfig() {
2698
+ const batch = this.settings.remote?.batch;
2699
+ return {
2700
+ enabled: Boolean(batch?.enabled && (this.openAi && this.provider.id === "openai" || this.gemini && this.provider.id === "gemini" || this.voyage && this.provider.id === "voyage")),
2701
+ wait: batch?.wait ?? true,
2702
+ concurrency: Math.max(1, batch?.concurrency ?? 2),
2703
+ pollIntervalMs: batch?.pollIntervalMs ?? 2e3,
2704
+ timeoutMs: (batch?.timeoutMinutes ?? 60) * 60 * 1e3
2705
+ };
2706
+ }
2707
+ async activateFallbackProvider(reason) {
2708
+ const fallback = this.settings.fallback;
2709
+ if (!fallback || fallback === "none" || fallback === this.provider.id) return false;
2710
+ if (this.fallbackFrom) return false;
2711
+ const fallbackFrom = this.provider.id;
2712
+ const fallbackModel = fallback === "gemini" ? DEFAULT_GEMINI_EMBEDDING_MODEL : fallback === "openai" ? DEFAULT_OPENAI_EMBEDDING_MODEL : fallback === "voyage" ? DEFAULT_VOYAGE_EMBEDDING_MODEL : this.settings.model;
2713
+ const fallbackResult = await createEmbeddingProvider({
2714
+ config: this.cfg,
2715
+ agentDir: resolveAgentDir(this.cfg, this.agentId),
2716
+ provider: fallback,
2717
+ remote: this.settings.remote,
2718
+ model: fallbackModel,
2719
+ fallback: "none",
2720
+ local: this.settings.local
2721
+ });
2722
+ this.fallbackFrom = fallbackFrom;
2723
+ this.fallbackReason = reason;
2724
+ this.provider = fallbackResult.provider;
2725
+ this.openAi = fallbackResult.openAi;
2726
+ this.gemini = fallbackResult.gemini;
2727
+ this.voyage = fallbackResult.voyage;
2728
+ this.providerKey = this.computeProviderKey();
2729
+ this.batch = this.resolveBatchConfig();
2730
+ log$1.warn(`memory embeddings: switched to fallback provider (${fallback})`, { reason });
2731
+ return true;
2732
+ }
2733
+ async runSafeReindex(params) {
2734
+ const dbPath = resolveUserPath(this.settings.store.path);
2735
+ const tempDbPath = `${dbPath}.tmp-${randomUUID()}`;
2736
+ const tempDb = this.openDatabaseAtPath(tempDbPath);
2737
+ const originalDb = this.db;
2738
+ let originalDbClosed = false;
2739
+ const originalState = {
2740
+ ftsAvailable: this.fts.available,
2741
+ ftsError: this.fts.loadError,
2742
+ vectorAvailable: this.vector.available,
2743
+ vectorLoadError: this.vector.loadError,
2744
+ vectorDims: this.vector.dims,
2745
+ vectorReady: this.vectorReady
2746
+ };
2747
+ const restoreOriginalState = () => {
2748
+ if (originalDbClosed) this.db = this.openDatabaseAtPath(dbPath);
2749
+ else this.db = originalDb;
2750
+ this.fts.available = originalState.ftsAvailable;
2751
+ this.fts.loadError = originalState.ftsError;
2752
+ this.vector.available = originalDbClosed ? null : originalState.vectorAvailable;
2753
+ this.vector.loadError = originalState.vectorLoadError;
2754
+ this.vector.dims = originalState.vectorDims;
2755
+ this.vectorReady = originalDbClosed ? null : originalState.vectorReady;
2756
+ };
2757
+ this.db = tempDb;
2758
+ this.vectorReady = null;
2759
+ this.vector.available = null;
2760
+ this.vector.loadError = void 0;
2761
+ this.vector.dims = void 0;
2762
+ this.fts.available = false;
2763
+ this.fts.loadError = void 0;
2764
+ this.ensureSchema();
2765
+ let nextMeta = null;
2766
+ try {
2767
+ this.seedEmbeddingCache(originalDb);
2768
+ const shouldSyncMemory = this.sources.has("memory");
2769
+ const shouldSyncSessions = this.shouldSyncSessions({
2770
+ reason: params.reason,
2771
+ force: params.force
2772
+ }, true);
2773
+ if (shouldSyncMemory) {
2774
+ await this.syncMemoryFiles({
2775
+ needsFullReindex: true,
2776
+ progress: params.progress
2777
+ });
2778
+ this.dirty = false;
2779
+ }
2780
+ if (shouldSyncSessions) {
2781
+ await this.syncSessionFiles({
2782
+ needsFullReindex: true,
2783
+ progress: params.progress
2784
+ });
2785
+ this.sessionsDirty = false;
2786
+ this.sessionsDirtyFiles.clear();
2787
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2788
+ else this.sessionsDirty = false;
2789
+ nextMeta = {
2790
+ model: this.provider.model,
2791
+ provider: this.provider.id,
2792
+ providerKey: this.providerKey,
2793
+ chunkTokens: this.settings.chunking.tokens,
2794
+ chunkOverlap: this.settings.chunking.overlap
2795
+ };
2796
+ if (this.vector.available && this.vector.dims) nextMeta.vectorDims = this.vector.dims;
2797
+ this.writeMeta(nextMeta);
2798
+ this.pruneEmbeddingCacheIfNeeded();
2799
+ this.db.close();
2800
+ originalDb.close();
2801
+ originalDbClosed = true;
2802
+ await this.swapIndexFiles(dbPath, tempDbPath);
2803
+ this.db = this.openDatabaseAtPath(dbPath);
2804
+ this.vectorReady = null;
2805
+ this.vector.available = null;
2806
+ this.vector.loadError = void 0;
2807
+ this.ensureSchema();
2808
+ this.vector.dims = nextMeta.vectorDims;
2809
+ } catch (err) {
2810
+ try {
2811
+ this.db.close();
2812
+ } catch {}
2813
+ await this.removeIndexFiles(tempDbPath);
2814
+ restoreOriginalState();
2815
+ throw err;
2816
+ }
2817
+ }
2818
+ async runUnsafeReindex(params) {
2819
+ this.resetIndex();
2820
+ const shouldSyncMemory = this.sources.has("memory");
2821
+ const shouldSyncSessions = this.shouldSyncSessions({
2822
+ reason: params.reason,
2823
+ force: params.force
2824
+ }, true);
2825
+ if (shouldSyncMemory) {
2826
+ await this.syncMemoryFiles({
2827
+ needsFullReindex: true,
2828
+ progress: params.progress
2829
+ });
2830
+ this.dirty = false;
2831
+ }
2832
+ if (shouldSyncSessions) {
2833
+ await this.syncSessionFiles({
2834
+ needsFullReindex: true,
2835
+ progress: params.progress
2836
+ });
2837
+ this.sessionsDirty = false;
2838
+ this.sessionsDirtyFiles.clear();
2839
+ } else if (this.sessionsDirtyFiles.size > 0) this.sessionsDirty = true;
2840
+ else this.sessionsDirty = false;
2841
+ const nextMeta = {
2842
+ model: this.provider.model,
2843
+ provider: this.provider.id,
2844
+ providerKey: this.providerKey,
2845
+ chunkTokens: this.settings.chunking.tokens,
2846
+ chunkOverlap: this.settings.chunking.overlap
2847
+ };
2848
+ if (this.vector.available && this.vector.dims) nextMeta.vectorDims = this.vector.dims;
2849
+ this.writeMeta(nextMeta);
2850
+ this.pruneEmbeddingCacheIfNeeded();
2851
+ }
2852
+ resetIndex() {
2853
+ this.db.exec(`DELETE FROM files`);
2854
+ this.db.exec(`DELETE FROM chunks`);
2855
+ if (this.fts.enabled && this.fts.available) try {
2856
+ this.db.exec(`DELETE FROM ${FTS_TABLE$1}`);
2857
+ } catch {}
2858
+ this.dropVectorTable();
2859
+ this.vector.dims = void 0;
2860
+ this.sessionsDirtyFiles.clear();
2861
+ }
2862
+ readMeta() {
2863
+ const row = this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(META_KEY);
2864
+ if (!row?.value) return null;
2865
+ try {
2866
+ return JSON.parse(row.value);
2867
+ } catch {
2868
+ return null;
2869
+ }
2870
+ }
2871
+ writeMeta(meta) {
2872
+ const value = JSON.stringify(meta);
2873
+ this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(META_KEY, value);
2874
+ }
2875
+ };
2876
+ const memoryManagerSyncOps = MemoryManagerSyncOps.prototype;
2877
+
2878
+ //#endregion
2879
+ //#region src/memory/manager.ts
2880
+ var manager_exports = /* @__PURE__ */ __exportAll({ MemoryIndexManager: () => MemoryIndexManager });
2881
+ const SNIPPET_MAX_CHARS = 700;
2882
+ const VECTOR_TABLE = "chunks_vec";
2883
+ const FTS_TABLE = "chunks_fts";
2884
+ const EMBEDDING_CACHE_TABLE = "embedding_cache";
2885
+ const BATCH_FAILURE_LIMIT = 2;
2886
+ const log = createSubsystemLogger("memory");
2887
+ const INDEX_CACHE = /* @__PURE__ */ new Map();
2888
+ var MemoryIndexManager = class MemoryIndexManager {
2889
+ static async get(params) {
2890
+ const { cfg, agentId } = params;
2891
+ const settings = resolveMemorySearchConfig(cfg, agentId);
2892
+ if (!settings) return null;
2893
+ const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
2894
+ const key = `${agentId}:${workspaceDir}:${JSON.stringify(settings)}`;
2895
+ const existing = INDEX_CACHE.get(key);
2896
+ if (existing) return existing;
2897
+ const manager = new MemoryIndexManager({
2898
+ cacheKey: key,
2899
+ cfg,
2900
+ agentId,
2901
+ workspaceDir,
2902
+ settings,
2903
+ providerResult: await createEmbeddingProvider$1({
2904
+ config: cfg,
2905
+ agentDir: resolveAgentDir$1(cfg, agentId),
2906
+ provider: settings.provider,
2907
+ remote: settings.remote,
2908
+ model: settings.model,
2909
+ fallback: settings.fallback,
2910
+ local: settings.local
2911
+ }),
2912
+ purpose: params.purpose
2913
+ });
2914
+ INDEX_CACHE.set(key, manager);
2915
+ return manager;
2916
+ }
2917
+ constructor(params) {
2918
+ this.batchFailureCount = 0;
2919
+ this.batchFailureLock = Promise.resolve();
2920
+ this.vectorReady = null;
2921
+ this.watcher = null;
2922
+ this.watchTimer = null;
2923
+ this.sessionWatchTimer = null;
2924
+ this.sessionUnsubscribe = null;
2925
+ this.intervalTimer = null;
2926
+ this.closed = false;
2927
+ this.dirty = false;
2928
+ this.sessionsDirty = false;
2929
+ this.sessionsDirtyFiles = /* @__PURE__ */ new Set();
2930
+ this.sessionPendingFiles = /* @__PURE__ */ new Set();
2931
+ this.sessionDeltas = /* @__PURE__ */ new Map();
2932
+ this.sessionWarm = /* @__PURE__ */ new Set();
2933
+ this.syncing = null;
2934
+ this.cacheKey = params.cacheKey;
2935
+ this.cfg = params.cfg;
2936
+ this.agentId = params.agentId;
2937
+ this.workspaceDir = params.workspaceDir;
2938
+ this.settings = params.settings;
2939
+ this.provider = params.providerResult.provider;
2940
+ this.requestedProvider = params.providerResult.requestedProvider;
2941
+ this.fallbackFrom = params.providerResult.fallbackFrom;
2942
+ this.fallbackReason = params.providerResult.fallbackReason;
2943
+ this.openAi = params.providerResult.openAi;
2944
+ this.gemini = params.providerResult.gemini;
2945
+ this.voyage = params.providerResult.voyage;
2946
+ this.sources = new Set(params.settings.sources);
2947
+ this.db = this.openDatabase();
2948
+ this.providerKey = this.computeProviderKey();
2949
+ this.cache = {
2950
+ enabled: params.settings.cache.enabled,
2951
+ maxEntries: params.settings.cache.maxEntries
2952
+ };
2953
+ this.fts = {
2954
+ enabled: params.settings.query.hybrid.enabled,
2955
+ available: false
2956
+ };
2957
+ this.ensureSchema();
2958
+ this.vector = {
2959
+ enabled: params.settings.store.vector.enabled,
2960
+ available: null,
2961
+ extensionPath: params.settings.store.vector.extensionPath
2962
+ };
2963
+ const meta = this.readMeta();
2964
+ if (meta?.vectorDims) this.vector.dims = meta.vectorDims;
2965
+ this.ensureWatcher();
2966
+ this.ensureSessionListener();
2967
+ this.ensureIntervalSync();
2968
+ const statusOnly = params.purpose === "status";
2969
+ this.dirty = this.sources.has("memory") && (statusOnly ? !meta : true);
2970
+ this.batch = this.resolveBatchConfig();
2971
+ }
2972
+ async warmSession(sessionKey) {
2973
+ if (!this.settings.sync.onSessionStart) return;
2974
+ const key = sessionKey?.trim() || "";
2975
+ if (key && this.sessionWarm.has(key)) return;
2976
+ this.sync({ reason: "session-start" }).catch((err) => {
2977
+ log.warn(`memory sync failed (session-start): ${String(err)}`);
2978
+ });
2979
+ if (key) this.sessionWarm.add(key);
2980
+ }
2981
+ async search(query, opts) {
2982
+ this.warmSession(opts?.sessionKey);
2983
+ if (this.settings.sync.onSearch && (this.dirty || this.sessionsDirty)) this.sync({ reason: "search" }).catch((err) => {
2984
+ log.warn(`memory sync failed (search): ${String(err)}`);
2985
+ });
2986
+ const cleaned = query.trim();
2987
+ if (!cleaned) return [];
2988
+ const minScore = opts?.minScore ?? this.settings.query.minScore;
2989
+ const maxResults = opts?.maxResults ?? this.settings.query.maxResults;
2990
+ const hybrid = this.settings.query.hybrid;
2991
+ const candidates = Math.min(200, Math.max(1, Math.floor(maxResults * hybrid.candidateMultiplier)));
2992
+ const keywordResults = hybrid.enabled ? await this.searchKeyword(cleaned, candidates).catch(() => []) : [];
2993
+ const queryVec = await this.embedQueryWithTimeout(cleaned);
2994
+ const vectorResults = queryVec.some((v) => v !== 0) ? await this.searchVector(queryVec, candidates).catch(() => []) : [];
2995
+ if (!hybrid.enabled) return vectorResults.filter((entry) => entry.score >= minScore).slice(0, maxResults);
2996
+ return this.mergeHybridResults({
2997
+ vector: vectorResults,
2998
+ keyword: keywordResults,
2999
+ vectorWeight: hybrid.vectorWeight,
3000
+ textWeight: hybrid.textWeight
3001
+ }).filter((entry) => entry.score >= minScore).slice(0, maxResults);
3002
+ }
3003
+ async searchVector(queryVec, limit) {
3004
+ return (await searchVector({
3005
+ db: this.db,
3006
+ vectorTable: VECTOR_TABLE,
3007
+ providerModel: this.provider.model,
3008
+ queryVec,
3009
+ limit,
3010
+ snippetMaxChars: SNIPPET_MAX_CHARS,
3011
+ ensureVectorReady: async (dimensions) => await this.ensureVectorReady(dimensions),
3012
+ sourceFilterVec: this.buildSourceFilter("c"),
3013
+ sourceFilterChunks: this.buildSourceFilter()
3014
+ })).map((entry) => entry);
3015
+ }
3016
+ buildFtsQuery(raw) {
3017
+ return buildFtsQuery(raw);
3018
+ }
3019
+ async searchKeyword(query, limit) {
3020
+ if (!this.fts.enabled || !this.fts.available) return [];
3021
+ const sourceFilter = this.buildSourceFilter();
3022
+ return (await searchKeyword({
3023
+ db: this.db,
3024
+ ftsTable: FTS_TABLE,
3025
+ providerModel: this.provider.model,
3026
+ query,
3027
+ limit,
3028
+ snippetMaxChars: SNIPPET_MAX_CHARS,
3029
+ sourceFilter,
3030
+ buildFtsQuery: (raw) => this.buildFtsQuery(raw),
3031
+ bm25RankToScore
3032
+ })).map((entry) => entry);
3033
+ }
3034
+ mergeHybridResults(params) {
3035
+ return mergeHybridResults({
3036
+ vector: params.vector.map((r) => ({
3037
+ id: r.id,
3038
+ path: r.path,
3039
+ startLine: r.startLine,
3040
+ endLine: r.endLine,
3041
+ source: r.source,
3042
+ snippet: r.snippet,
3043
+ vectorScore: r.score
3044
+ })),
3045
+ keyword: params.keyword.map((r) => ({
3046
+ id: r.id,
3047
+ path: r.path,
3048
+ startLine: r.startLine,
3049
+ endLine: r.endLine,
3050
+ source: r.source,
3051
+ snippet: r.snippet,
3052
+ textScore: r.textScore
3053
+ })),
3054
+ vectorWeight: params.vectorWeight,
3055
+ textWeight: params.textWeight
3056
+ }).map((entry) => entry);
3057
+ }
3058
+ async sync(params) {
3059
+ if (this.syncing) return this.syncing;
3060
+ this.syncing = this.runSync(params).finally(() => {
3061
+ this.syncing = null;
3062
+ });
3063
+ return this.syncing ?? Promise.resolve();
3064
+ }
3065
+ async readFile(params) {
3066
+ const rawPath = params.relPath.trim();
3067
+ if (!rawPath) throw new Error("path required");
3068
+ const absPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(this.workspaceDir, rawPath);
3069
+ const relPath = path.relative(this.workspaceDir, absPath).replace(/\\/g, "/");
3070
+ const allowedWorkspace = relPath.length > 0 && !relPath.startsWith("..") && !path.isAbsolute(relPath) && isMemoryPath(relPath);
3071
+ let allowedAdditional = false;
3072
+ if (!allowedWorkspace && this.settings.extraPaths.length > 0) {
3073
+ const additionalPaths = normalizeExtraMemoryPaths(this.workspaceDir, this.settings.extraPaths);
3074
+ for (const additionalPath of additionalPaths) try {
3075
+ const stat = await fs.lstat(additionalPath);
3076
+ if (stat.isSymbolicLink()) continue;
3077
+ if (stat.isDirectory()) {
3078
+ if (absPath === additionalPath || absPath.startsWith(`${additionalPath}${path.sep}`)) {
3079
+ allowedAdditional = true;
3080
+ break;
3081
+ }
3082
+ continue;
3083
+ }
3084
+ if (stat.isFile()) {
3085
+ if (absPath === additionalPath && absPath.endsWith(".md")) {
3086
+ allowedAdditional = true;
3087
+ break;
3088
+ }
3089
+ }
3090
+ } catch {}
3091
+ }
3092
+ if (!allowedWorkspace && !allowedAdditional) throw new Error("path required");
3093
+ if (!absPath.endsWith(".md")) throw new Error("path required");
3094
+ const stat = await fs.lstat(absPath);
3095
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("path required");
3096
+ const content = await fs.readFile(absPath, "utf-8");
3097
+ if (!params.from && !params.lines) return {
3098
+ text: content,
3099
+ path: relPath
3100
+ };
3101
+ const lines = content.split("\n");
3102
+ const start = Math.max(1, params.from ?? 1);
3103
+ const count = Math.max(1, params.lines ?? lines.length);
3104
+ return {
3105
+ text: lines.slice(start - 1, start - 1 + count).join("\n"),
3106
+ path: relPath
3107
+ };
3108
+ }
3109
+ status() {
3110
+ const sourceFilter = this.buildSourceFilter();
3111
+ const files = this.db.prepare(`SELECT COUNT(*) as c FROM files WHERE 1=1${sourceFilter.sql}`).get(...sourceFilter.params);
3112
+ const chunks = this.db.prepare(`SELECT COUNT(*) as c FROM chunks WHERE 1=1${sourceFilter.sql}`).get(...sourceFilter.params);
3113
+ const sourceCounts = (() => {
3114
+ const sources = Array.from(this.sources);
3115
+ if (sources.length === 0) return [];
3116
+ const bySource = /* @__PURE__ */ new Map();
3117
+ for (const source of sources) bySource.set(source, {
3118
+ files: 0,
3119
+ chunks: 0
3120
+ });
3121
+ const fileRows = this.db.prepare(`SELECT source, COUNT(*) as c FROM files WHERE 1=1${sourceFilter.sql} GROUP BY source`).all(...sourceFilter.params);
3122
+ for (const row of fileRows) {
3123
+ const entry = bySource.get(row.source) ?? {
3124
+ files: 0,
3125
+ chunks: 0
3126
+ };
3127
+ entry.files = row.c ?? 0;
3128
+ bySource.set(row.source, entry);
3129
+ }
3130
+ const chunkRows = this.db.prepare(`SELECT source, COUNT(*) as c FROM chunks WHERE 1=1${sourceFilter.sql} GROUP BY source`).all(...sourceFilter.params);
3131
+ for (const row of chunkRows) {
3132
+ const entry = bySource.get(row.source) ?? {
3133
+ files: 0,
3134
+ chunks: 0
3135
+ };
3136
+ entry.chunks = row.c ?? 0;
3137
+ bySource.set(row.source, entry);
3138
+ }
3139
+ return sources.map((source) => Object.assign({ source }, bySource.get(source)));
3140
+ })();
3141
+ return {
3142
+ backend: "builtin",
3143
+ files: files?.c ?? 0,
3144
+ chunks: chunks?.c ?? 0,
3145
+ dirty: this.dirty || this.sessionsDirty,
3146
+ workspaceDir: this.workspaceDir,
3147
+ dbPath: this.settings.store.path,
3148
+ provider: this.provider.id,
3149
+ model: this.provider.model,
3150
+ requestedProvider: this.requestedProvider,
3151
+ sources: Array.from(this.sources),
3152
+ extraPaths: this.settings.extraPaths,
3153
+ sourceCounts,
3154
+ cache: this.cache.enabled ? {
3155
+ enabled: true,
3156
+ entries: this.db.prepare(`SELECT COUNT(*) as c FROM ${EMBEDDING_CACHE_TABLE}`).get()?.c ?? 0,
3157
+ maxEntries: this.cache.maxEntries
3158
+ } : {
3159
+ enabled: false,
3160
+ maxEntries: this.cache.maxEntries
3161
+ },
3162
+ fts: {
3163
+ enabled: this.fts.enabled,
3164
+ available: this.fts.available,
3165
+ error: this.fts.loadError
3166
+ },
3167
+ fallback: this.fallbackReason ? {
3168
+ from: this.fallbackFrom ?? "local",
3169
+ reason: this.fallbackReason
3170
+ } : void 0,
3171
+ vector: {
3172
+ enabled: this.vector.enabled,
3173
+ available: this.vector.available ?? void 0,
3174
+ extensionPath: this.vector.extensionPath,
3175
+ loadError: this.vector.loadError,
3176
+ dims: this.vector.dims
3177
+ },
3178
+ batch: {
3179
+ enabled: this.batch.enabled,
3180
+ failures: this.batchFailureCount,
3181
+ limit: BATCH_FAILURE_LIMIT,
3182
+ wait: this.batch.wait,
3183
+ concurrency: this.batch.concurrency,
3184
+ pollIntervalMs: this.batch.pollIntervalMs,
3185
+ timeoutMs: this.batch.timeoutMs,
3186
+ lastError: this.batchFailureLastError,
3187
+ lastProvider: this.batchFailureLastProvider
3188
+ }
3189
+ };
3190
+ }
3191
+ async probeVectorAvailability() {
3192
+ if (!this.vector.enabled) return false;
3193
+ return this.ensureVectorReady();
3194
+ }
3195
+ async probeEmbeddingAvailability() {
3196
+ try {
3197
+ await this.embedBatchWithRetry(["ping"]);
3198
+ return { ok: true };
3199
+ } catch (err) {
3200
+ return {
3201
+ ok: false,
3202
+ error: err instanceof Error ? err.message : String(err)
3203
+ };
3204
+ }
3205
+ }
3206
+ async close() {
3207
+ if (this.closed) return;
3208
+ this.closed = true;
3209
+ if (this.watchTimer) {
3210
+ clearTimeout(this.watchTimer);
3211
+ this.watchTimer = null;
3212
+ }
3213
+ if (this.sessionWatchTimer) {
3214
+ clearTimeout(this.sessionWatchTimer);
3215
+ this.sessionWatchTimer = null;
3216
+ }
3217
+ if (this.intervalTimer) {
3218
+ clearInterval(this.intervalTimer);
3219
+ this.intervalTimer = null;
3220
+ }
3221
+ if (this.watcher) {
3222
+ await this.watcher.close();
3223
+ this.watcher = null;
3224
+ }
3225
+ if (this.sessionUnsubscribe) {
3226
+ this.sessionUnsubscribe();
3227
+ this.sessionUnsubscribe = null;
3228
+ }
3229
+ this.db.close();
3230
+ INDEX_CACHE.delete(this.cacheKey);
3231
+ }
3232
+ };
3233
+ function applyPrototypeMixins(target, ...sources) {
3234
+ for (const source of sources) for (const name of Object.getOwnPropertyNames(source)) {
3235
+ if (name === "constructor") continue;
3236
+ const descriptor = Object.getOwnPropertyDescriptor(source, name);
3237
+ if (!descriptor) continue;
3238
+ Object.defineProperty(target, name, descriptor);
3239
+ }
3240
+ }
3241
+ applyPrototypeMixins(MemoryIndexManager.prototype, memoryManagerSyncOps, memoryManagerEmbeddingOps);
3242
+
3243
+ //#endregion
3244
+ export { resolveMemorySearchConfig as n, manager_exports as t };