@theokit/sdk 4.24.0 → 4.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/dist/a2a/index.cjs +10 -171
  2. package/dist/a2a/index.cjs.map +1 -1
  3. package/dist/a2a/index.js +3 -170
  4. package/dist/a2a/index.js.map +1 -1
  5. package/dist/agent-factory-registry-UU46BUMU.cjs +16 -0
  6. package/dist/agent-factory-registry-UU46BUMU.cjs.map +1 -0
  7. package/dist/agent-factory-registry-ZVTABLEY.js +3 -0
  8. package/dist/agent-factory-registry-ZVTABLEY.js.map +1 -0
  9. package/dist/auth/index.cjs +63 -367
  10. package/dist/auth/index.cjs.map +1 -1
  11. package/dist/auth/index.js +6 -342
  12. package/dist/auth/index.js.map +1 -1
  13. package/dist/batch-2FSD2UNL.cjs +244 -0
  14. package/dist/batch-2FSD2UNL.cjs.map +1 -0
  15. package/dist/batch-MR2HKYMS.js +241 -0
  16. package/dist/batch-MR2HKYMS.js.map +1 -0
  17. package/dist/chunk-2HRYBRD7.cjs +31 -0
  18. package/dist/chunk-2HRYBRD7.cjs.map +1 -0
  19. package/dist/chunk-2MF3IE2D.cjs +2863 -0
  20. package/dist/chunk-2MF3IE2D.cjs.map +1 -0
  21. package/dist/chunk-2ONFGMBV.js +6 -0
  22. package/dist/chunk-2ONFGMBV.js.map +1 -0
  23. package/dist/chunk-2SFBB54R.js +23 -0
  24. package/dist/chunk-2SFBB54R.js.map +1 -0
  25. package/dist/chunk-2XLKLVVR.js +18 -0
  26. package/dist/chunk-2XLKLVVR.js.map +1 -0
  27. package/dist/chunk-4HKMQEPX.js +458 -0
  28. package/dist/chunk-4HKMQEPX.js.map +1 -0
  29. package/dist/chunk-4SXHEZIV.cjs +240 -0
  30. package/dist/chunk-4SXHEZIV.cjs.map +1 -0
  31. package/dist/chunk-4VPXM6UU.js +10 -0
  32. package/dist/chunk-4VPXM6UU.js.map +1 -0
  33. package/dist/chunk-4WL52CXU.cjs +148 -0
  34. package/dist/chunk-4WL52CXU.cjs.map +1 -0
  35. package/dist/chunk-5NBUH3NO.js +39 -0
  36. package/dist/chunk-5NBUH3NO.js.map +1 -0
  37. package/dist/chunk-5PZMMF4H.js +43 -0
  38. package/dist/chunk-5PZMMF4H.js.map +1 -0
  39. package/dist/chunk-6CLRANZA.js +289 -0
  40. package/dist/chunk-6CLRANZA.js.map +1 -0
  41. package/dist/chunk-6JSIEDKL.cjs +121 -0
  42. package/dist/chunk-6JSIEDKL.cjs.map +1 -0
  43. package/dist/chunk-6M4ODB2V.cjs +145 -0
  44. package/dist/chunk-6M4ODB2V.cjs.map +1 -0
  45. package/dist/chunk-6X6ID4MO.js +20 -0
  46. package/dist/chunk-6X6ID4MO.js.map +1 -0
  47. package/dist/chunk-77FOZCOT.js +165 -0
  48. package/dist/chunk-77FOZCOT.js.map +1 -0
  49. package/dist/chunk-7AD3ZTZL.js +25 -0
  50. package/dist/chunk-7AD3ZTZL.js.map +1 -0
  51. package/dist/chunk-7GFX45DD.js +57 -0
  52. package/dist/chunk-7GFX45DD.js.map +1 -0
  53. package/dist/chunk-7RMWOMDB.cjs +460 -0
  54. package/dist/chunk-7RMWOMDB.cjs.map +1 -0
  55. package/dist/chunk-7S7KKUO6.cjs +45 -0
  56. package/dist/chunk-7S7KKUO6.cjs.map +1 -0
  57. package/dist/chunk-7W7ZWMLQ.js +99 -0
  58. package/dist/chunk-7W7ZWMLQ.js.map +1 -0
  59. package/dist/chunk-A44COQJJ.cjs +353 -0
  60. package/dist/chunk-A44COQJJ.cjs.map +1 -0
  61. package/dist/chunk-AKSBP7OO.js +185 -0
  62. package/dist/chunk-AKSBP7OO.js.map +1 -0
  63. package/dist/chunk-ANIZEWTU.cjs +196 -0
  64. package/dist/chunk-ANIZEWTU.cjs.map +1 -0
  65. package/dist/chunk-BEURCLDV.cjs +139 -0
  66. package/dist/chunk-BEURCLDV.cjs.map +1 -0
  67. package/dist/chunk-BFWPZMG7.js +379 -0
  68. package/dist/chunk-BFWPZMG7.js.map +1 -0
  69. package/dist/chunk-BUUUWQMB.cjs +34 -0
  70. package/dist/chunk-BUUUWQMB.cjs.map +1 -0
  71. package/dist/chunk-BV2MWEMV.cjs +26 -0
  72. package/dist/chunk-BV2MWEMV.cjs.map +1 -0
  73. package/dist/chunk-BWT67BI4.cjs +268 -0
  74. package/dist/chunk-BWT67BI4.cjs.map +1 -0
  75. package/dist/chunk-BXV2QUIC.js +191 -0
  76. package/dist/chunk-BXV2QUIC.js.map +1 -0
  77. package/dist/chunk-C6Y6CWYD.cjs +44 -0
  78. package/dist/chunk-C6Y6CWYD.cjs.map +1 -0
  79. package/dist/chunk-C7PICHRF.cjs +68 -0
  80. package/dist/chunk-C7PICHRF.cjs.map +1 -0
  81. package/dist/chunk-CAH3G4IS.js +13 -0
  82. package/dist/chunk-CAH3G4IS.js.map +1 -0
  83. package/dist/chunk-CJ6YJ2L3.cjs +10590 -0
  84. package/dist/chunk-CJ6YJ2L3.cjs.map +1 -0
  85. package/dist/chunk-D42XHI4O.cjs +565 -0
  86. package/dist/chunk-D42XHI4O.cjs.map +1 -0
  87. package/dist/chunk-DGRZNMTU.js +104 -0
  88. package/dist/chunk-DGRZNMTU.js.map +1 -0
  89. package/dist/chunk-DUK5WMKJ.js +71 -0
  90. package/dist/chunk-DUK5WMKJ.js.map +1 -0
  91. package/dist/chunk-EEZ7CFMM.js +14 -0
  92. package/dist/chunk-EEZ7CFMM.js.map +1 -0
  93. package/dist/chunk-EPYZOCOL.cjs +82 -0
  94. package/dist/chunk-EPYZOCOL.cjs.map +1 -0
  95. package/dist/chunk-EVADEGM7.cjs +168 -0
  96. package/dist/chunk-EVADEGM7.cjs.map +1 -0
  97. package/dist/chunk-F3XVLFLM.js +10573 -0
  98. package/dist/chunk-F3XVLFLM.js.map +1 -0
  99. package/dist/chunk-FD2UT76F.js +3 -0
  100. package/dist/chunk-FD2UT76F.js.map +1 -0
  101. package/dist/chunk-FV3YEMQ7.js +179 -0
  102. package/dist/chunk-FV3YEMQ7.js.map +1 -0
  103. package/dist/chunk-G2F67XUR.cjs +184 -0
  104. package/dist/chunk-G2F67XUR.cjs.map +1 -0
  105. package/dist/chunk-G6GO6BXD.js +994 -0
  106. package/dist/chunk-G6GO6BXD.js.map +1 -0
  107. package/dist/chunk-GIW4L6HY.cjs +27 -0
  108. package/dist/chunk-GIW4L6HY.cjs.map +1 -0
  109. package/dist/chunk-GJAGKFTR.js +74 -0
  110. package/dist/chunk-GJAGKFTR.js.map +1 -0
  111. package/dist/chunk-HFPGOTVF.cjs +324 -0
  112. package/dist/chunk-HFPGOTVF.cjs.map +1 -0
  113. package/dist/chunk-HRA3CPGG.js +486 -0
  114. package/dist/chunk-HRA3CPGG.js.map +1 -0
  115. package/dist/chunk-HZQEDNF6.js +66 -0
  116. package/dist/chunk-HZQEDNF6.js.map +1 -0
  117. package/dist/chunk-IT3PWBW4.cjs +19 -0
  118. package/dist/chunk-IT3PWBW4.cjs.map +1 -0
  119. package/dist/chunk-JD74LN7R.cjs +171 -0
  120. package/dist/chunk-JD74LN7R.cjs.map +1 -0
  121. package/dist/chunk-JTFYYKDT.js +135 -0
  122. package/dist/chunk-JTFYYKDT.js.map +1 -0
  123. package/dist/chunk-K2BQQ445.js +30 -0
  124. package/dist/chunk-K2BQQ445.js.map +1 -0
  125. package/dist/chunk-KAP4GJHO.js +546 -0
  126. package/dist/chunk-KAP4GJHO.js.map +1 -0
  127. package/dist/chunk-KIO7QFIV.cjs +223 -0
  128. package/dist/chunk-KIO7QFIV.cjs.map +1 -0
  129. package/dist/chunk-KSKU6JY6.cjs +71 -0
  130. package/dist/chunk-KSKU6JY6.cjs.map +1 -0
  131. package/dist/chunk-LSLPF6OI.cjs +192 -0
  132. package/dist/chunk-LSLPF6OI.cjs.map +1 -0
  133. package/dist/chunk-LU7VALW5.js +312 -0
  134. package/dist/chunk-LU7VALW5.js.map +1 -0
  135. package/dist/chunk-LUSXDZPV.cjs +296 -0
  136. package/dist/chunk-LUSXDZPV.cjs.map +1 -0
  137. package/dist/chunk-M72RJVPC.js +69 -0
  138. package/dist/chunk-M72RJVPC.js.map +1 -0
  139. package/dist/chunk-MQLCZ4HJ.cjs +1010 -0
  140. package/dist/chunk-MQLCZ4HJ.cjs.map +1 -0
  141. package/dist/chunk-MUUQ2WFJ.cjs +4 -0
  142. package/dist/chunk-MUUQ2WFJ.cjs.map +1 -0
  143. package/dist/chunk-MZ5ZRORA.cjs +496 -0
  144. package/dist/chunk-MZ5ZRORA.cjs.map +1 -0
  145. package/dist/chunk-N24XBYNX.cjs +140 -0
  146. package/dist/chunk-N24XBYNX.cjs.map +1 -0
  147. package/dist/chunk-NINIJCHU.cjs +23 -0
  148. package/dist/chunk-NINIJCHU.cjs.map +1 -0
  149. package/dist/chunk-NRSH7RJY.js +2841 -0
  150. package/dist/chunk-NRSH7RJY.js.map +1 -0
  151. package/dist/chunk-OIYQBUW4.cjs +111 -0
  152. package/dist/chunk-OIYQBUW4.cjs.map +1 -0
  153. package/dist/chunk-PNVDQL5Y.cjs +15 -0
  154. package/dist/chunk-PNVDQL5Y.cjs.map +1 -0
  155. package/dist/chunk-POQT2OIF.js +214 -0
  156. package/dist/chunk-POQT2OIF.js.map +1 -0
  157. package/dist/chunk-QUTUJ6P6.cjs +76 -0
  158. package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
  159. package/dist/chunk-S2BBRVQX.js +68 -0
  160. package/dist/chunk-S2BBRVQX.js.map +1 -0
  161. package/dist/chunk-S5RCBTSF.js +145 -0
  162. package/dist/chunk-S5RCBTSF.js.map +1 -0
  163. package/dist/chunk-S7OEXQMI.cjs +136 -0
  164. package/dist/chunk-S7OEXQMI.cjs.map +1 -0
  165. package/dist/chunk-SKWVAQAY.js +129 -0
  166. package/dist/chunk-SKWVAQAY.js.map +1 -0
  167. package/dist/chunk-SQLZ7ONU.js +152 -0
  168. package/dist/chunk-SQLZ7ONU.js.map +1 -0
  169. package/dist/chunk-TIZ4TS5V.cjs +72 -0
  170. package/dist/chunk-TIZ4TS5V.cjs.map +1 -0
  171. package/dist/chunk-TQKCU7CL.js +142 -0
  172. package/dist/chunk-TQKCU7CL.js.map +1 -0
  173. package/dist/chunk-U54XCYG3.js +116 -0
  174. package/dist/chunk-U54XCYG3.js.map +1 -0
  175. package/dist/chunk-U6QGZHPN.js +29 -0
  176. package/dist/chunk-U6QGZHPN.js.map +1 -0
  177. package/dist/chunk-UCFONJBG.js +79 -0
  178. package/dist/chunk-UCFONJBG.js.map +1 -0
  179. package/dist/chunk-UJ7IQJAG.js +141 -0
  180. package/dist/chunk-UJ7IQJAG.js.map +1 -0
  181. package/dist/chunk-UVNG67DG.js +253 -0
  182. package/dist/chunk-UVNG67DG.js.map +1 -0
  183. package/dist/chunk-V4XRLPEF.js +25 -0
  184. package/dist/chunk-V4XRLPEF.js.map +1 -0
  185. package/dist/chunk-VJ26EKGJ.cjs +28 -0
  186. package/dist/chunk-VJ26EKGJ.cjs.map +1 -0
  187. package/dist/chunk-VK7MAV65.cjs +90 -0
  188. package/dist/chunk-VK7MAV65.cjs.map +1 -0
  189. package/dist/chunk-VYCKUKPA.cjs +106 -0
  190. package/dist/chunk-VYCKUKPA.cjs.map +1 -0
  191. package/dist/chunk-VYHJZVL5.cjs +29 -0
  192. package/dist/chunk-VYHJZVL5.cjs.map +1 -0
  193. package/dist/chunk-WA3FO4R7.js +155 -0
  194. package/dist/chunk-WA3FO4R7.js.map +1 -0
  195. package/dist/chunk-WJVHMTKB.cjs +12 -0
  196. package/dist/chunk-WJVHMTKB.cjs.map +1 -0
  197. package/dist/chunk-WLKFWQSJ.js +333 -0
  198. package/dist/chunk-WLKFWQSJ.js.map +1 -0
  199. package/dist/chunk-WPZTYOUX.cjs +59 -0
  200. package/dist/chunk-WPZTYOUX.cjs.map +1 -0
  201. package/dist/chunk-X2FR4OIT.js +27 -0
  202. package/dist/chunk-X2FR4OIT.js.map +1 -0
  203. package/dist/chunk-XIG2IE3L.js +134 -0
  204. package/dist/chunk-XIG2IE3L.js.map +1 -0
  205. package/dist/chunk-YLQQX5W2.cjs +20 -0
  206. package/dist/chunk-YLQQX5W2.cjs.map +1 -0
  207. package/dist/chunk-YPEPCZHF.cjs +147 -0
  208. package/dist/chunk-YPEPCZHF.cjs.map +1 -0
  209. package/dist/chunk-YPQF26X7.cjs +8 -0
  210. package/dist/chunk-YPQF26X7.cjs.map +1 -0
  211. package/dist/chunk-YU6KON2I.cjs +160 -0
  212. package/dist/chunk-YU6KON2I.cjs.map +1 -0
  213. package/dist/chunk-Z2OC3UIW.cjs +388 -0
  214. package/dist/chunk-Z2OC3UIW.cjs.map +1 -0
  215. package/dist/chunk-ZZWTY3RX.js +230 -0
  216. package/dist/chunk-ZZWTY3RX.js.map +1 -0
  217. package/dist/compact-session-OO2GD76G.js +17 -0
  218. package/dist/compact-session-OO2GD76G.js.map +1 -0
  219. package/dist/compact-session-OO7NVWPB.cjs +54 -0
  220. package/dist/compact-session-OO7NVWPB.cjs.map +1 -0
  221. package/dist/compaction.cjs +54 -303
  222. package/dist/compaction.cjs.map +1 -1
  223. package/dist/compaction.js +3 -292
  224. package/dist/compaction.js.map +1 -1
  225. package/dist/concurrency.cjs +9 -81
  226. package/dist/concurrency.cjs.map +1 -1
  227. package/dist/concurrency.js +5 -80
  228. package/dist/concurrency.js.map +1 -1
  229. package/dist/context-GWANQLX4.js +5 -0
  230. package/dist/context-GWANQLX4.js.map +1 -0
  231. package/dist/context-KNWVTZSY.cjs +22 -0
  232. package/dist/context-KNWVTZSY.cjs.map +1 -0
  233. package/dist/cron.cjs +44 -20676
  234. package/dist/cron.cjs.map +1 -1
  235. package/dist/cron.js +38 -20676
  236. package/dist/cron.js.map +1 -1
  237. package/dist/errors.cjs +78 -470
  238. package/dist/errors.cjs.map +1 -1
  239. package/dist/errors.js +2 -455
  240. package/dist/errors.js.map +1 -1
  241. package/dist/eval.cjs +72 -20411
  242. package/dist/eval.cjs.map +1 -1
  243. package/dist/eval.js +59 -20402
  244. package/dist/eval.js.map +1 -1
  245. package/dist/executor-ORJS5GV2.js +981 -0
  246. package/dist/executor-ORJS5GV2.js.map +1 -0
  247. package/dist/executor-Y4MKPIUD.cjs +985 -0
  248. package/dist/executor-Y4MKPIUD.cjs.map +1 -0
  249. package/dist/filesystem/index.cjs +7 -112
  250. package/dist/filesystem/index.cjs.map +1 -1
  251. package/dist/filesystem/index.js +4 -109
  252. package/dist/filesystem/index.js.map +1 -1
  253. package/dist/fork-agent-RSV4E3EA.js +61 -0
  254. package/dist/fork-agent-RSV4E3EA.js.map +1 -0
  255. package/dist/fork-agent-Y2IK2RYU.cjs +64 -0
  256. package/dist/fork-agent-Y2IK2RYU.cjs.map +1 -0
  257. package/dist/fs-session-store-KAUQYSGI.cjs +17 -0
  258. package/dist/fs-session-store-KAUQYSGI.cjs.map +1 -0
  259. package/dist/fs-session-store-ZKB5NN37.js +8 -0
  260. package/dist/fs-session-store-ZKB5NN37.js.map +1 -0
  261. package/dist/generate-object-H3RNAM6S.cjs +20 -0
  262. package/dist/generate-object-H3RNAM6S.cjs.map +1 -0
  263. package/dist/generate-object-YJPDV5BS.js +7 -0
  264. package/dist/generate-object-YJPDV5BS.js.map +1 -0
  265. package/dist/index-manager-CB6I7XFQ.cjs +19 -0
  266. package/dist/index-manager-CB6I7XFQ.cjs.map +1 -0
  267. package/dist/index-manager-L27Q3QAC.js +10 -0
  268. package/dist/index-manager-L27Q3QAC.js.map +1 -0
  269. package/dist/index.cjs +371 -22888
  270. package/dist/index.cjs.map +1 -1
  271. package/dist/index.js +92 -22713
  272. package/dist/index.js.map +1 -1
  273. package/dist/inject-session-6MJUSGZP.cjs +27 -0
  274. package/dist/inject-session-6MJUSGZP.cjs.map +1 -0
  275. package/dist/inject-session-KOFHS5K3.js +25 -0
  276. package/dist/inject-session-KOFHS5K3.js.map +1 -0
  277. package/dist/internal/persistence/index.cjs +93 -508
  278. package/dist/internal/persistence/index.cjs.map +1 -1
  279. package/dist/internal/persistence/index.js +11 -489
  280. package/dist/internal/persistence/index.js.map +1 -1
  281. package/dist/internal/security/index.cjs +44 -361
  282. package/dist/internal/security/index.cjs.map +1 -1
  283. package/dist/internal/security/index.js +4 -355
  284. package/dist/internal/security/index.js.map +1 -1
  285. package/dist/judge-call-7CF7D334.cjs +95 -0
  286. package/dist/judge-call-7CF7D334.cjs.map +1 -0
  287. package/dist/judge-call-VIMNK5TA.js +92 -0
  288. package/dist/judge-call-VIMNK5TA.js.map +1 -0
  289. package/dist/models.cjs +24 -919
  290. package/dist/models.cjs.map +1 -1
  291. package/dist/models.js +11 -907
  292. package/dist/models.js.map +1 -1
  293. package/dist/oauth-transaction-store-7CKHPQRN.cjs +32 -0
  294. package/dist/oauth-transaction-store-7CKHPQRN.cjs.map +1 -0
  295. package/dist/oauth-transaction-store-W74I6EFD.js +3 -0
  296. package/dist/oauth-transaction-store-W74I6EFD.js.map +1 -0
  297. package/dist/path-safety.cjs +31 -200
  298. package/dist/path-safety.cjs.map +1 -1
  299. package/dist/path-safety.js +3 -197
  300. package/dist/path-safety.js.map +1 -1
  301. package/dist/persistence.cjs +73 -393
  302. package/dist/persistence.cjs.map +1 -1
  303. package/dist/persistence.js +9 -381
  304. package/dist/persistence.js.map +1 -1
  305. package/dist/project.cjs +8 -112
  306. package/dist/project.cjs.map +1 -1
  307. package/dist/project.js +6 -110
  308. package/dist/project.js.map +1 -1
  309. package/dist/registry-34IWWDQQ.js +9 -0
  310. package/dist/registry-34IWWDQQ.js.map +1 -0
  311. package/dist/registry-APYDISL6.cjs +46 -0
  312. package/dist/registry-APYDISL6.cjs.map +1 -0
  313. package/dist/retry.cjs +7 -87
  314. package/dist/retry.cjs.map +1 -1
  315. package/dist/retry.js +3 -90
  316. package/dist/retry.js.map +1 -1
  317. package/dist/run-to-completion-J73I6IY4.cjs +48 -0
  318. package/dist/run-to-completion-J73I6IY4.cjs.map +1 -0
  319. package/dist/run-to-completion-JDPIUKSH.js +3 -0
  320. package/dist/run-to-completion-JDPIUKSH.js.map +1 -0
  321. package/dist/run-until-2PX4QBHZ.js +168 -0
  322. package/dist/run-until-2PX4QBHZ.js.map +1 -0
  323. package/dist/run-until-DB3LVGZS.cjs +171 -0
  324. package/dist/run-until-DB3LVGZS.cjs.map +1 -0
  325. package/dist/sandbox/index.cjs +35 -337
  326. package/dist/sandbox/index.cjs.map +1 -1
  327. package/dist/sandbox/index.js +7 -323
  328. package/dist/sandbox/index.js.map +1 -1
  329. package/dist/sanitize/index.cjs +5 -112
  330. package/dist/sanitize/index.cjs.map +1 -1
  331. package/dist/sanitize/index.js +1 -114
  332. package/dist/sanitize/index.js.map +1 -1
  333. package/dist/server/auth/index.cjs +35 -175
  334. package/dist/server/auth/index.cjs.map +1 -1
  335. package/dist/server/auth/index.js +7 -161
  336. package/dist/server/auth/index.js.map +1 -1
  337. package/dist/server/errors-envelope.cjs +17 -328
  338. package/dist/server/errors-envelope.cjs.map +1 -1
  339. package/dist/server/errors-envelope.js +4 -317
  340. package/dist/server/errors-envelope.js.map +1 -1
  341. package/dist/session-transcript-LPNZR3YS.cjs +46 -0
  342. package/dist/session-transcript-LPNZR3YS.cjs.map +1 -0
  343. package/dist/session-transcript-T7LGJUGW.js +5 -0
  344. package/dist/session-transcript-T7LGJUGW.js.map +1 -0
  345. package/dist/skills.cjs +12 -280
  346. package/dist/skills.cjs.map +1 -1
  347. package/dist/skills.js +4 -282
  348. package/dist/skills.js.map +1 -1
  349. package/dist/stream-object-QEQJJDTI.cjs +20 -0
  350. package/dist/stream-object-QEQJJDTI.cjs.map +1 -0
  351. package/dist/stream-object-WUQSSRY2.js +7 -0
  352. package/dist/stream-object-WUQSSRY2.js.map +1 -0
  353. package/dist/stream-to-completion-DFJ5T3BK.js +30 -0
  354. package/dist/stream-to-completion-DFJ5T3BK.js.map +1 -0
  355. package/dist/stream-to-completion-H2MHISSK.cjs +32 -0
  356. package/dist/stream-to-completion-H2MHISSK.cjs.map +1 -0
  357. package/dist/subagents.cjs +2 -8
  358. package/dist/subagents.cjs.map +1 -1
  359. package/dist/subagents.js +1 -7
  360. package/dist/subagents.js.map +1 -1
  361. package/dist/subscription/index.cjs +4 -17
  362. package/dist/subscription/index.cjs.map +1 -1
  363. package/dist/subscription/index.js +3 -16
  364. package/dist/subscription/index.js.map +1 -1
  365. package/dist/task-store.cjs +16 -258
  366. package/dist/task-store.cjs.map +1 -1
  367. package/dist/task-store.js +4 -259
  368. package/dist/task-store.js.map +1 -1
  369. package/dist/workflow.cjs +71 -2797
  370. package/dist/workflow.cjs.map +1 -1
  371. package/dist/workflow.js +8 -2812
  372. package/dist/workflow.js.map +1 -1
  373. package/package.json +1 -1
@@ -0,0 +1,1010 @@
1
+ 'use strict';
2
+
3
+ var chunkJD74LN7R_cjs = require('./chunk-JD74LN7R.cjs');
4
+ var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
5
+ var chunkKIO7QFIV_cjs = require('./chunk-KIO7QFIV.cjs');
6
+ var chunkTIZ4TS5V_cjs = require('./chunk-TIZ4TS5V.cjs');
7
+ var chunkA44COQJJ_cjs = require('./chunk-A44COQJJ.cjs');
8
+ var chunkBEURCLDV_cjs = require('./chunk-BEURCLDV.cjs');
9
+ var crypto = require('crypto');
10
+ var promises = require('fs/promises');
11
+ var path = require('path');
12
+ var fs = require('fs');
13
+ var module$1 = require('module');
14
+
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ // src/internal/memory/embedding-cache.ts
17
+ var LruEmbeddingCache = class {
18
+ constructor(capacity = 5e3) {
19
+ this.capacity = capacity;
20
+ }
21
+ capacity;
22
+ map = /* @__PURE__ */ new Map();
23
+ get(key) {
24
+ const value = this.map.get(key);
25
+ if (value === void 0) return void 0;
26
+ this.map.delete(key);
27
+ this.map.set(key, value);
28
+ return value;
29
+ }
30
+ set(key, value) {
31
+ if (this.map.has(key)) this.map.delete(key);
32
+ else if (this.map.size >= this.capacity) {
33
+ const oldest = this.map.keys().next().value;
34
+ if (oldest !== void 0) this.map.delete(oldest);
35
+ }
36
+ this.map.set(key, value);
37
+ }
38
+ size() {
39
+ return this.map.size;
40
+ }
41
+ };
42
+ var globalEmbeddingCache = new LruEmbeddingCache();
43
+
44
+ // src/internal/memory/index-schema.ts
45
+ var SCHEMA_STATEMENTS = [
46
+ `CREATE TABLE IF NOT EXISTS files (
47
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
48
+ path TEXT UNIQUE NOT NULL,
49
+ rel_path TEXT NOT NULL,
50
+ mtime INTEGER NOT NULL,
51
+ hash TEXT NOT NULL,
52
+ source TEXT NOT NULL DEFAULT 'memory'
53
+ )`,
54
+ `CREATE TABLE IF NOT EXISTS chunks (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
57
+ start_line INTEGER NOT NULL,
58
+ end_line INTEGER NOT NULL,
59
+ text TEXT NOT NULL,
60
+ hash TEXT NOT NULL,
61
+ session_key TEXT
62
+ )`,
63
+ `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
64
+ text,
65
+ content='chunks',
66
+ content_rowid='id'
67
+ )`,
68
+ `CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
69
+ INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
70
+ END`,
71
+ `CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
72
+ INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
73
+ END`,
74
+ `CREATE TABLE IF NOT EXISTS meta (
75
+ key TEXT PRIMARY KEY,
76
+ value TEXT
77
+ )`,
78
+ `CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
79
+ ];
80
+ var PRAGMA_STATEMENTS = [
81
+ "PRAGMA synchronous=NORMAL",
82
+ "PRAGMA foreign_keys=ON"
83
+ ];
84
+
85
+ // src/internal/memory/index-db.ts
86
+ async function openMemoryDb(opts) {
87
+ return chunkJD74LN7R_cjs.openSqliteResilient({
88
+ filePath: opts.filePath,
89
+ label: "memory-index",
90
+ recoverCorrupt: opts.recoverCorrupt,
91
+ onOpen: (db) => {
92
+ for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
93
+ for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
94
+ }
95
+ });
96
+ }
97
+ function defaultIndexPath(cwd) {
98
+ return path.join(cwd, ".theokit", "memory", ".index", "memory.sqlite");
99
+ }
100
+ function requireLance() {
101
+ try {
102
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-MQLCZ4HJ.cjs', document.baseURI).href)));
103
+ return r("@lancedb/lancedb");
104
+ } catch (cause) {
105
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
106
+ 'Lance backend selected but `@lancedb/lancedb` is not installed. Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: "lance"`).',
107
+ { code: "lance_backend_unavailable", cause }
108
+ );
109
+ }
110
+ }
111
+ var LanceIndex = class _LanceIndex {
112
+ constructor(table, embedding, embeddingDim) {
113
+ this.table = table;
114
+ this.embedding = embedding;
115
+ this.embeddingDim = embeddingDim;
116
+ }
117
+ table;
118
+ embedding;
119
+ embeddingDim;
120
+ static async open(opts) {
121
+ const lance = requireLance();
122
+ const storagePath = opts.storagePath ?? path.join(opts.cwd, ".theokit", "memory", "lance");
123
+ fs.mkdirSync(storagePath, { recursive: true });
124
+ const conn = await lance.connect(storagePath);
125
+ const dim = opts.embedding.dimension;
126
+ const tableName = "facts";
127
+ const existing = await conn.tableNames();
128
+ let table;
129
+ if (existing.includes(tableName)) {
130
+ table = await conn.openTable(tableName);
131
+ const schema = await table.schema();
132
+ const embField = schema.fields.find((f) => f.name === "embedding");
133
+ const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;
134
+ if (typeof existingDim === "number" && existingDim !== dim) {
135
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
136
+ `Embedding dimension mismatch in Lance index: storage has ${existingDim}-dim vectors, current provider yields ${dim}-dim. Run \`theokit-migrate-memory\` after switching providers, or use a different storagePath.`,
137
+ { code: "embedding_dimension_mismatch" }
138
+ );
139
+ }
140
+ } else {
141
+ const bootstrap = {
142
+ id: "__bootstrap__",
143
+ text: "",
144
+ source: "memory",
145
+ embedding: new Array(dim).fill(0),
146
+ namespace: "__bootstrap__",
147
+ scope: "__bootstrap__",
148
+ user_id: "__bootstrap__",
149
+ timestamp: 0
150
+ };
151
+ table = await conn.createTable(tableName, [bootstrap]);
152
+ await table.delete("namespace = '__bootstrap__'");
153
+ }
154
+ return new _LanceIndex(table, opts.embedding, dim);
155
+ }
156
+ async addFacts(facts) {
157
+ if (facts.length === 0) return;
158
+ const texts = facts.map((f) => f.text);
159
+ const embeddings = await this.embedding.embed(texts);
160
+ const rows = facts.map((f, i) => ({
161
+ ...f,
162
+ embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0)
163
+ }));
164
+ await this.table.add(rows);
165
+ }
166
+ /**
167
+ * Search facts by semantic similarity. EC-1: filters use Lance's
168
+ * structured object filter — NEVER string interpolation.
169
+ */
170
+ async search(query, opts) {
171
+ const [embedding] = await this.embedding.embed([query]);
172
+ if (embedding === void 0) return [];
173
+ const predicates = [`namespace = '${escapeSqlValue(opts.namespace)}'`];
174
+ if (opts.scope !== void 0) {
175
+ predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);
176
+ }
177
+ let q = this.table.search(embedding).where(predicates.join(" AND "));
178
+ if (opts.limit !== void 0) q = q.limit(opts.limit);
179
+ const results = await q.toArray();
180
+ return results.filter((r) => opts.sources === void 0 || opts.sources.includes(r.source)).map((r) => ({
181
+ id: r.id,
182
+ text: r.text,
183
+ source: r.source,
184
+ namespace: r.namespace,
185
+ scope: r.scope,
186
+ userId: r.user_id,
187
+ // Lower _distance = better match; normalize to 0..1 (1=best).
188
+ score: 1 / (1 + (r._distance ?? 1))
189
+ }));
190
+ }
191
+ async countFacts(namespace) {
192
+ return this.table.countRows();
193
+ }
194
+ async removeFacts(ids) {
195
+ if (ids.length === 0) return;
196
+ const escaped = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
197
+ await this.table.delete(`id IN (${escaped})`);
198
+ }
199
+ async close() {
200
+ }
201
+ };
202
+ function escapeSqlValue(value) {
203
+ for (let i = 0; i < value.length; i++) {
204
+ const code = value.charCodeAt(i);
205
+ if (code === 0 || code >= 1 && code <= 31 || code === 127) {
206
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
207
+ `SQL filter value contains control character at position ${i} (0x${code.toString(16)}). This may indicate an injection attempt.`,
208
+ { code: "sql_injection_blocked" }
209
+ );
210
+ }
211
+ }
212
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "''");
213
+ }
214
+ function lanceStoragePath(cwd) {
215
+ return path.join(cwd, ".theokit", "memory", "lance");
216
+ }
217
+
218
+ // src/internal/memory/memory-index.ts
219
+ function parseSearchOptions(options = {}) {
220
+ return {
221
+ maxResults: Math.max(1, options.maxResults ?? 10),
222
+ minScore: options.minScore ?? 0
223
+ };
224
+ }
225
+
226
+ // src/internal/memory/lance-memory-adapter.ts
227
+ var DEFAULT_NAMESPACE = "default";
228
+ var EMPTY_SYNC_RESULT = Object.freeze({
229
+ filesScanned: 0,
230
+ filesUpdated: 0,
231
+ chunksWritten: 0,
232
+ chunksEmbedded: 0
233
+ });
234
+ var LanceMemoryAdapter = class {
235
+ constructor(inner) {
236
+ this.inner = inner;
237
+ }
238
+ inner;
239
+ /**
240
+ * No-op for Lance — see file header. Returns zero counts so callers'
241
+ * existing logging (`filesScanned: X`) does not break.
242
+ */
243
+ async sync() {
244
+ return EMPTY_SYNC_RESULT;
245
+ }
246
+ // jscpd:ignore-start — search signature + early-out is idiomatic
247
+ // overlap with IndexManager.search; further factoring would hurt
248
+ // readability (the bodies diverge sharply right after).
249
+ async search(query, options = {}) {
250
+ if (query.trim().length === 0) return [];
251
+ const { maxResults, minScore } = parseSearchOptions(options);
252
+ const lanceHits = await this.inner.search(query, {
253
+ namespace: DEFAULT_NAMESPACE,
254
+ limit: maxResults * 2,
255
+ ...options.sources !== void 0 ? { sources: options.sources } : {}
256
+ });
257
+ return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h, query));
258
+ }
259
+ status() {
260
+ return {
261
+ backend: "hybrid",
262
+ filesIndexed: 0,
263
+ chunksIndexed: 0
264
+ };
265
+ }
266
+ async close() {
267
+ await this.inner.close();
268
+ }
269
+ /**
270
+ * Escape hatch for advanced callers (migration tool, benchmark script)
271
+ * that need direct access to addFacts/countFacts/removeFacts.
272
+ */
273
+ unwrap() {
274
+ return this.inner;
275
+ }
276
+ };
277
+ function translateLanceHit(hit, query) {
278
+ const textScore = query !== void 0 ? computeTermOverlapScore(query, hit.text) : 0;
279
+ const vectorScore = hit.score;
280
+ const combined = 0.7 * vectorScore + 0.3 * textScore;
281
+ return {
282
+ path: hit.id,
283
+ startLine: 0,
284
+ endLine: 0,
285
+ score: combined,
286
+ textScore,
287
+ vectorScore,
288
+ snippet: hit.text.slice(0, 200),
289
+ source: hit.source,
290
+ citation: hit.id
291
+ };
292
+ }
293
+ function computeTermOverlapScore(query, text) {
294
+ const queryTerms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
295
+ if (queryTerms.length === 0) return 0;
296
+ const textLower = text.toLowerCase();
297
+ const matched = queryTerms.filter((term) => textLower.includes(term)).length;
298
+ return matched / queryTerms.length;
299
+ }
300
+
301
+ // src/internal/memory/index-manager-dispatch.ts
302
+ var VALID_BACKENDS = ["sqlite-vec", "lance"];
303
+ function assertValidBackend(backend) {
304
+ if (!VALID_BACKENDS.includes(backend)) {
305
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
306
+ `Invalid memory backend "${backend}". Valid values: ${VALID_BACKENDS.join(", ")}.`,
307
+ { code: "invalid_memory_backend" }
308
+ );
309
+ }
310
+ }
311
+ async function openLanceIndex(opts) {
312
+ if (opts.embedding === void 0) {
313
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
314
+ "Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).",
315
+ { code: "lance_requires_embedding" }
316
+ );
317
+ }
318
+ const lance = await LanceIndex.open({
319
+ cwd: opts.cwd,
320
+ embedding: opts.embedding,
321
+ ...opts.filePath !== void 0 ? { storagePath: opts.filePath } : {}
322
+ });
323
+ return new LanceMemoryAdapter(lance);
324
+ }
325
+ function legacyMemoryJsonPath(cwd, config) {
326
+ if (config.storePath !== void 0) {
327
+ return path.resolve(cwd, config.storePath);
328
+ }
329
+ const namespace = chunkKIO7QFIV_cjs.sanitizeIdentifier(config.namespace ?? "default");
330
+ const scope = chunkKIO7QFIV_cjs.sanitizeIdentifier(config.scope ?? "agent", { maxLen: 16 });
331
+ const userId = chunkKIO7QFIV_cjs.sanitizeIdentifier(config.userId ?? "default");
332
+ return chunkKIO7QFIV_cjs.safePathJoin(cwd, ".theokit", "memory", namespace, `${scope}-${userId}.json`);
333
+ }
334
+
335
+ // src/internal/memory/storage/markdown-store.ts
336
+ var MEMORY_MD_HEADER = "# Memory\n\n> Auto-managed by @theokit/sdk. Edit freely \u2014 the SDK reads from here.\n";
337
+ var FACTS_HEADING = "## Facts";
338
+ function memoryDir(cwd) {
339
+ return path.join(cwd, ".theokit", "memory");
340
+ }
341
+ function memoryMdPath(cwd) {
342
+ return path.join(memoryDir(cwd), "MEMORY.md");
343
+ }
344
+ function notesDir(cwd) {
345
+ return path.join(memoryDir(cwd), "notes");
346
+ }
347
+ async function readFactsFromMarkdown(cwd) {
348
+ let raw;
349
+ try {
350
+ raw = await promises.readFile(memoryMdPath(cwd), "utf8");
351
+ } catch {
352
+ return [];
353
+ }
354
+ return parseFactsSection(raw);
355
+ }
356
+ function appendFactToMarkdown(cwd, fact) {
357
+ return chunkYLQQX5W2_cjs.withCwdMutex(memoryDir(cwd), async () => {
358
+ const path = memoryMdPath(cwd);
359
+ let raw = "";
360
+ try {
361
+ raw = await promises.readFile(path, "utf8");
362
+ } catch {
363
+ raw = "";
364
+ }
365
+ const sanitized = chunkBEURCLDV_cjs.redactSecrets(fact.text);
366
+ const next = insertFactBullet(raw, sanitized);
367
+ await promises.mkdir(memoryDir(cwd), { recursive: true });
368
+ await chunkTIZ4TS5V_cjs.replaceFileAtomic(path, next);
369
+ });
370
+ }
371
+ function parseFactsSection(raw) {
372
+ const idx = raw.indexOf(FACTS_HEADING);
373
+ if (idx === -1) return [];
374
+ const tail = raw.slice(idx + FACTS_HEADING.length);
375
+ const nextHeading = tail.search(/\n#{1,2}\s/);
376
+ const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);
377
+ return block.split("\n").map((line) => line.trim()).filter((line) => line.startsWith("- ")).map((line) => ({ text: line.slice(2).trim() }));
378
+ }
379
+ function insertFactBullet(raw, fact) {
380
+ const bullet = `- ${fact}`;
381
+ if (raw.length === 0) {
382
+ return `${MEMORY_MD_HEADER}
383
+ ${FACTS_HEADING}
384
+
385
+ ${bullet}
386
+ `;
387
+ }
388
+ const idx = raw.indexOf(FACTS_HEADING);
389
+ if (idx === -1) {
390
+ const sep = raw.endsWith("\n") ? "" : "\n";
391
+ return `${raw}${sep}
392
+ ${FACTS_HEADING}
393
+
394
+ ${bullet}
395
+ `;
396
+ }
397
+ const after = idx + FACTS_HEADING.length;
398
+ const nextHeading = raw.slice(after).search(/\n#{1,2}\s/);
399
+ if (nextHeading === -1) {
400
+ const trailing = raw.endsWith("\n") ? "" : "\n";
401
+ return `${raw}${trailing}${bullet}
402
+ `;
403
+ }
404
+ const insertAt = after + nextHeading;
405
+ return `${raw.slice(0, insertAt)}
406
+ ${bullet}${raw.slice(insertAt)}`;
407
+ }
408
+ async function readFacts(cwd, config) {
409
+ if (!config.enabled) return [];
410
+ return readFactsFromMarkdown(cwd);
411
+ }
412
+ async function appendFact(cwd, config, fact) {
413
+ if (!config.enabled) return;
414
+ await appendFactToMarkdown(cwd, fact);
415
+ }
416
+ var MAX_TURN_CHARS = 2e3;
417
+ function sessionsDir(cwd) {
418
+ return path.join(memoryDir(cwd), "sessions");
419
+ }
420
+ function sessionSummaryPath(cwd, runId) {
421
+ return path.join(sessionsDir(cwd), `${chunkKIO7QFIV_cjs.safeFilenameForId(runId, { maxLen: 128 })}.md`);
422
+ }
423
+ function truncate(text) {
424
+ if (text.length <= MAX_TURN_CHARS) return text;
425
+ return `${text.slice(0, MAX_TURN_CHARS)}\u2026`;
426
+ }
427
+ async function writeSessionSummary(input) {
428
+ if (input.status !== "finished") return;
429
+ const path = sessionSummaryPath(input.cwd, input.runId);
430
+ await promises.mkdir(sessionsDir(input.cwd), { recursive: true });
431
+ const safeUser = chunkBEURCLDV_cjs.redactSecrets(truncate(input.userText));
432
+ const safeAssistant = chunkBEURCLDV_cjs.redactSecrets(truncate(input.assistantText));
433
+ const iso = new Date(input.at).toISOString();
434
+ const body = [
435
+ "---",
436
+ `runId: ${input.runId}`,
437
+ `agentId: ${input.agentId}`,
438
+ `at: ${iso}`,
439
+ `status: ${input.status}`,
440
+ "---",
441
+ "",
442
+ "## User",
443
+ "",
444
+ safeUser,
445
+ "",
446
+ "## Assistant",
447
+ "",
448
+ safeAssistant,
449
+ ""
450
+ ].join("\n");
451
+ await chunkTIZ4TS5V_cjs.replaceFileAtomic(path, body);
452
+ }
453
+
454
+ // src/internal/memory/storage/session-loader.ts
455
+ async function discoverSessionFiles(cwd) {
456
+ let entries;
457
+ try {
458
+ entries = await promises.readdir(sessionsDir(cwd));
459
+ } catch {
460
+ return [];
461
+ }
462
+ const root = memoryDir(cwd);
463
+ return entries.filter((entry) => entry.endsWith(".md")).map((entry) => {
464
+ const absolutePath = path.join(sessionsDir(cwd), entry);
465
+ return {
466
+ absolutePath,
467
+ relPath: relativeToRoot(root, absolutePath)
468
+ };
469
+ });
470
+ }
471
+ function relativeToRoot(root, absolutePath) {
472
+ if (absolutePath.startsWith(`${root}/`)) return absolutePath.slice(root.length + 1);
473
+ return absolutePath;
474
+ }
475
+ function wikiDir(cwd) {
476
+ return path.join(memoryDir(cwd), "wiki");
477
+ }
478
+ async function discoverWikiFiles(cwd) {
479
+ let entries;
480
+ try {
481
+ entries = await promises.readdir(wikiDir(cwd));
482
+ } catch {
483
+ return [];
484
+ }
485
+ const root = memoryDir(cwd);
486
+ return entries.filter((entry) => entry.endsWith(".md")).map((entry) => ({
487
+ absolutePath: path.join(wikiDir(cwd), entry),
488
+ relPath: path.join("wiki", entry)
489
+ })).map((file) => ({
490
+ absolutePath: file.absolutePath,
491
+ relPath: relativeToRoot2(root, file.absolutePath)
492
+ }));
493
+ }
494
+ function relativeToRoot2(root, absolutePath) {
495
+ if (absolutePath.startsWith(`${root}/`)) return absolutePath.slice(root.length + 1);
496
+ return absolutePath;
497
+ }
498
+
499
+ // src/internal/memory/index-manager-helpers.ts
500
+ function resolveWeights(options) {
501
+ const vectorWeight = options.vectorWeight ?? 0.6;
502
+ const textWeight = options.textWeight ?? 0.4;
503
+ const total = vectorWeight + textWeight || 1;
504
+ return { vectorWeight, textWeight, total };
505
+ }
506
+ function blendScores(hit, vectorScore, weights) {
507
+ const score = (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;
508
+ return {
509
+ path: hit.path,
510
+ startLine: hit.startLine,
511
+ endLine: hit.endLine,
512
+ score,
513
+ textScore: hit.textScore,
514
+ snippet: hit.snippet,
515
+ source: hit.source,
516
+ citation: hit.citation,
517
+ ...vectorScore > 0 ? { vectorScore } : {}
518
+ };
519
+ }
520
+ async function collectMarkdownFiles(cwd) {
521
+ const root = memoryDir(cwd);
522
+ const results = [];
523
+ try {
524
+ await promises.stat(memoryMdPath(cwd));
525
+ results.push({
526
+ absolutePath: memoryMdPath(cwd),
527
+ relPath: path.relative(root, memoryMdPath(cwd)),
528
+ source: "memory"
529
+ });
530
+ } catch {
531
+ }
532
+ try {
533
+ const entries = await promises.readdir(notesDir(cwd));
534
+ for (const entry of entries) {
535
+ if (!entry.endsWith(".md")) continue;
536
+ const abs = path.join(notesDir(cwd), entry);
537
+ results.push({ absolutePath: abs, relPath: path.relative(root, abs), source: "memory" });
538
+ }
539
+ } catch {
540
+ }
541
+ const wikiFiles = await discoverWikiFiles(cwd);
542
+ for (const wiki of wikiFiles) {
543
+ results.push({
544
+ absolutePath: wiki.absolutePath,
545
+ relPath: wiki.relPath,
546
+ source: "wiki"
547
+ });
548
+ }
549
+ const sessionFiles = await discoverSessionFiles(cwd);
550
+ for (const session of sessionFiles) {
551
+ results.push({
552
+ absolutePath: session.absolutePath,
553
+ relPath: session.relPath,
554
+ source: "sessions"
555
+ });
556
+ }
557
+ return results;
558
+ }
559
+ function sha256(text) {
560
+ return crypto.createHash("sha256").update(text).digest("hex");
561
+ }
562
+ function truncateSnippet(text) {
563
+ const max = 500;
564
+ return text.length <= max ? text : `${text.slice(0, max)}\u2026`;
565
+ }
566
+
567
+ // src/internal/memory/sqlite-vec-loader.ts
568
+ async function loadSqliteVecExtension(db) {
569
+ try {
570
+ const mod = await import('sqlite-vec');
571
+ const loadFn = mod.load;
572
+ if (typeof loadFn !== "function") {
573
+ throw new Error("sqlite-vec module exposes no `load` export");
574
+ }
575
+ loadFn(db);
576
+ } catch (cause) {
577
+ const message = cause instanceof Error ? cause.message : String(cause);
578
+ throw new chunkA44COQJJ_cjs.ConfigurationError(
579
+ `sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
580
+ { code: "sqlite_vec_unavailable", cause }
581
+ );
582
+ }
583
+ }
584
+ var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
585
+ function chunkMarkdown(text, options = {}) {
586
+ const maxChars = options.maxChars ?? 800;
587
+ if (text.length === 0) return [];
588
+ const lines = text.split("\n");
589
+ const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
590
+ for (let i = 0; i < lines.length; i++) {
591
+ const line = lines[i] ?? "";
592
+ const lineNumber = i + 1;
593
+ processLine(acc, line, lineNumber, maxChars);
594
+ }
595
+ flushAccumulator(acc, lines.length, maxChars);
596
+ return acc.chunks;
597
+ }
598
+ function processLine(acc, line, lineNumber, maxChars) {
599
+ const headingMatch = HEADING_RE.exec(line);
600
+ const isBlank = line.trim().length === 0;
601
+ if (headingMatch !== null && acc.lines.length > 0) {
602
+ flushAccumulator(acc, lineNumber - 1, maxChars);
603
+ }
604
+ if (headingMatch !== null) acc.heading = headingMatch[2];
605
+ acc.lines.push(line);
606
+ if (isBlank && acc.lines.length > 1) {
607
+ const joined = acc.lines.join("\n");
608
+ if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
609
+ }
610
+ }
611
+ function flushAccumulator(acc, endLineExclusive, maxChars) {
612
+ if (acc.lines.length === 0) return;
613
+ const chunkText = acc.lines.join("\n");
614
+ if (chunkText.trim().length === 0) {
615
+ acc.lines = [];
616
+ acc.start = endLineExclusive + 1;
617
+ return;
618
+ }
619
+ if (chunkText.length > maxChars) {
620
+ pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
621
+ } else {
622
+ acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
623
+ }
624
+ acc.lines = [];
625
+ acc.start = endLineExclusive + 1;
626
+ }
627
+ function buildChunk(text, startLine, endLine, heading) {
628
+ return {
629
+ startLine,
630
+ endLine,
631
+ text,
632
+ hash: crypto.createHash("sha256").update(text).digest("hex"),
633
+ ...heading !== void 0 ? { heading } : {}
634
+ };
635
+ }
636
+ function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
637
+ let remaining = text;
638
+ let lineCursor = startLine;
639
+ while (remaining.length > maxChars) {
640
+ const splitAt = findWordBoundarySplit(remaining, maxChars);
641
+ const slice = remaining.slice(0, splitAt);
642
+ const sliceLines = slice.split("\n").length;
643
+ chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
644
+ remaining = remaining.slice(splitAt).replace(/^\s+/, "");
645
+ lineCursor += sliceLines - 1;
646
+ }
647
+ if (remaining.length > 0) {
648
+ const sliceLines = remaining.split("\n").length;
649
+ chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
650
+ }
651
+ }
652
+ function findWordBoundarySplit(text, maxChars) {
653
+ if (text.length <= maxChars) return text.length;
654
+ for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
655
+ if (/\s/.test(text[i] ?? "x")) return i;
656
+ }
657
+ return maxChars;
658
+ }
659
+
660
+ // src/internal/memory/vec-index.ts
661
+ var META_KEY_PROVIDER_ID = "embedding.providerId";
662
+ var META_KEY_MODEL = "embedding.model";
663
+ var META_KEY_DIMENSION = "embedding.dimension";
664
+ function readEmbeddingIdentity(db) {
665
+ const get = (key) => {
666
+ const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
667
+ return row !== void 0 ? String(row.value) : void 0;
668
+ };
669
+ const providerId = get(META_KEY_PROVIDER_ID);
670
+ const model = get(META_KEY_MODEL);
671
+ const dimRaw = get(META_KEY_DIMENSION);
672
+ if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
673
+ const dimension = Number(dimRaw);
674
+ if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
675
+ return { providerId, model, dimension };
676
+ }
677
+ function writeEmbeddingIdentity(db, identity) {
678
+ const stmt = db.prepare(
679
+ "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
680
+ );
681
+ stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
682
+ stmt.run(META_KEY_MODEL, identity.model);
683
+ stmt.run(META_KEY_DIMENSION, String(identity.dimension));
684
+ }
685
+ function identityMatches(a, b) {
686
+ return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
687
+ }
688
+ function dropVectorIndex(db) {
689
+ db.exec("DROP TABLE IF EXISTS embeddings");
690
+ }
691
+ function createVectorIndex(db, dimension) {
692
+ db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
693
+ chunk_id INTEGER PRIMARY KEY,
694
+ vec FLOAT[${dimension}]
695
+ )`);
696
+ }
697
+ function packVector(vec) {
698
+ const f32 = new Float32Array(vec.length);
699
+ for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
700
+ return Buffer.from(f32.buffer);
701
+ }
702
+ function upsertEmbedding(db, chunkId, vec) {
703
+ const id = BigInt(chunkId);
704
+ db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
705
+ db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
706
+ }
707
+ function vectorSearch(db, query, k) {
708
+ const rows = db.prepare(
709
+ `SELECT chunk_id, distance FROM embeddings
710
+ WHERE vec MATCH ? AND k = ?
711
+ ORDER BY distance`
712
+ ).all(packVector(query), BigInt(k));
713
+ return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
714
+ }
715
+ async function embedMissingChunks(args) {
716
+ const rows = args.db.prepare(
717
+ `SELECT chunks.id as id, chunks.text as text
718
+ FROM chunks
719
+ LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
720
+ WHERE embeddings.chunk_id IS NULL`
721
+ ).all();
722
+ if (rows.length === 0) return 0;
723
+ const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
724
+ const vectors = await args.runtime.embed(normalized.map((r) => r.text));
725
+ for (let i = 0; i < normalized.length; i++) {
726
+ const row = normalized[i];
727
+ const vector = vectors[i];
728
+ if (row === void 0 || vector === void 0) continue;
729
+ upsertEmbedding(args.db, row.id, vector);
730
+ }
731
+ return normalized.length;
732
+ }
733
+
734
+ // src/internal/memory/index-manager.ts
735
+ var queryVectorCache = new LruEmbeddingCache(2e3);
736
+ var IndexManager = class _IndexManager {
737
+ constructor(cwd, db, embedding) {
738
+ this.cwd = cwd;
739
+ this.db = db;
740
+ this.embedding = embedding;
741
+ }
742
+ cwd;
743
+ db;
744
+ embedding;
745
+ lastSyncMs;
746
+ vectorReady = false;
747
+ static async open(opts) {
748
+ const backend = opts.backend ?? "sqlite-vec";
749
+ assertValidBackend(backend);
750
+ if (backend === "lance") return await openLanceIndex(opts);
751
+ return await _IndexManager.openSqliteInternal(opts);
752
+ }
753
+ /** Internal SQLite-path open. Renamed from previous public `open`. */
754
+ static async openSqliteInternal(opts) {
755
+ const filePath = opts.filePath ?? defaultIndexPath(opts.cwd);
756
+ const db = await openMemoryDb({ filePath });
757
+ const manager = new _IndexManager(opts.cwd, db, opts.embedding);
758
+ if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
759
+ return manager;
760
+ }
761
+ async initVectorBackend(runtime) {
762
+ await loadSqliteVecExtension(this.db);
763
+ const currentIdentity = {
764
+ providerId: runtime.id,
765
+ model: runtime.model,
766
+ dimension: runtime.dimension
767
+ };
768
+ const persisted = readEmbeddingIdentity(this.db);
769
+ if (persisted !== void 0 && !identityMatches(persisted, currentIdentity)) {
770
+ dropVectorIndex(this.db);
771
+ }
772
+ createVectorIndex(this.db, runtime.dimension);
773
+ writeEmbeddingIdentity(this.db, currentIdentity);
774
+ this.vectorReady = true;
775
+ }
776
+ /** Walk the memory corpus + (re)index changed files. */
777
+ async sync() {
778
+ const files = await collectMarkdownFiles(this.cwd);
779
+ let filesUpdated = 0;
780
+ let chunksWritten = 0;
781
+ const existingByPath = this.loadFilesIndex();
782
+ for (const entry of files) {
783
+ const raw = await promises.readFile(entry.absolutePath, "utf8");
784
+ const hash = sha256(raw);
785
+ const existing = existingByPath.get(entry.absolutePath);
786
+ if (existing !== void 0 && existing.hash === hash) continue;
787
+ const stats = await promises.stat(entry.absolutePath);
788
+ const fileId = this.upsertFile(
789
+ entry.absolutePath,
790
+ entry.relPath,
791
+ hash,
792
+ stats.mtimeMs,
793
+ entry.source
794
+ );
795
+ this.deleteChunksForFile(fileId);
796
+ const chunks = chunkMarkdown(raw);
797
+ for (const chunk of chunks) {
798
+ this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);
799
+ }
800
+ filesUpdated += 1;
801
+ chunksWritten += chunks.length;
802
+ }
803
+ let chunksEmbedded = 0;
804
+ if (this.vectorReady && this.embedding !== void 0) {
805
+ chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });
806
+ }
807
+ this.lastSyncMs = Date.now();
808
+ return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };
809
+ }
810
+ async search(query, options = {}) {
811
+ if (query.trim().length === 0) return [];
812
+ const { maxResults, minScore } = parseSearchOptions(options);
813
+ const textHits = this.ftsSearch(query, maxResults * 2);
814
+ const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);
815
+ const combined = this.combineHybridScores(textHits, vectorHitsById, options);
816
+ return combined.filter((h) => h.score >= minScore).filter((h) => options.sources === void 0 || options.sources.includes(h.source)).slice(0, maxResults);
817
+ }
818
+ status() {
819
+ const files = this.db.prepare("SELECT COUNT(*) as n FROM files").get() ?? { n: 0 };
820
+ const chunks = this.db.prepare("SELECT COUNT(*) as n FROM chunks").get() ?? { n: 0 };
821
+ const status = {
822
+ backend: this.vectorReady ? "hybrid" : "fts-only",
823
+ filesIndexed: Number(files.n ?? 0),
824
+ chunksIndexed: Number(chunks.n ?? 0)
825
+ };
826
+ if (this.lastSyncMs !== void 0) status.lastSyncMs = this.lastSyncMs;
827
+ return status;
828
+ }
829
+ // ───── search internals ──────────────────────────────────────────────
830
+ ftsSearch(query, limit) {
831
+ const sanitized = chunkJD74LN7R_cjs.sanitizeFts5Query(query);
832
+ if (sanitized.length === 0) return [];
833
+ const stmt = this.db.prepare(
834
+ `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
835
+ chunks.start_line as start_line, chunks.end_line as end_line,
836
+ chunks.text as text, bm25(chunks_fts) as bm25_score
837
+ FROM chunks_fts
838
+ JOIN chunks ON chunks_fts.rowid = chunks.id
839
+ JOIN files ON chunks.file_id = files.id
840
+ WHERE chunks_fts MATCH ?
841
+ ORDER BY bm25_score
842
+ LIMIT ?`
843
+ );
844
+ let rows = [];
845
+ try {
846
+ rows = stmt.all(sanitized, limit);
847
+ } catch {
848
+ return this.likeSearchFallback(query, limit);
849
+ }
850
+ return rows.map((row) => {
851
+ const bm25 = Number(row.bm25_score ?? 0);
852
+ const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);
853
+ const startLine = Number(row.start_line ?? 0);
854
+ const endLine = Number(row.end_line ?? 0);
855
+ const path = String(row.rel_path);
856
+ return {
857
+ path,
858
+ startLine,
859
+ endLine,
860
+ score: textScore,
861
+ textScore,
862
+ snippet: truncateSnippet(String(row.text ?? "")),
863
+ source: String(row.source),
864
+ citation: `${path}:${startLine}-${endLine}`,
865
+ // sneak the chunk id through for the hybrid join below
866
+ // (cast away later)
867
+ chunkId: Number(row.id)
868
+ };
869
+ });
870
+ }
871
+ /**
872
+ * T4.8 — LIKE-based fallback for CJK and other scripts that FTS5's
873
+ * default tokenizer cannot segment. Slower than FTS5 (full table scan)
874
+ * but correct for any Unicode input. Returns the same shape as
875
+ * `ftsSearch` so callers are unaware of the fallback.
876
+ */
877
+ likeSearchFallback(query, limit) {
878
+ const pattern = `%${query.replace(/%/g, "\\%").replace(/_/g, "\\_")}%`;
879
+ const stmt = this.db.prepare(
880
+ `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
881
+ chunks.start_line as start_line, chunks.end_line as end_line,
882
+ chunks.text as text
883
+ FROM chunks
884
+ JOIN files ON chunks.file_id = files.id
885
+ WHERE chunks.text LIKE ? ESCAPE '\\'
886
+ LIMIT ?`
887
+ );
888
+ const rows = stmt.all(pattern, limit);
889
+ return rows.map((row) => {
890
+ const path = String(row.rel_path ?? "");
891
+ const startLine = Number(row.start_line ?? 0);
892
+ const endLine = Number(row.end_line ?? 0);
893
+ return {
894
+ path,
895
+ startLine,
896
+ endLine,
897
+ score: 0.5,
898
+ // LIKE has no relevance score — use a neutral midpoint
899
+ textScore: 0.5,
900
+ snippet: truncateSnippet(String(row.text ?? "")),
901
+ source: String(row.source),
902
+ citation: `${path}:${startLine}-${endLine}`,
903
+ chunkId: Number(row.id)
904
+ };
905
+ });
906
+ }
907
+ async vectorSearchById(query, limit) {
908
+ if (!this.vectorReady || this.embedding === void 0) return /* @__PURE__ */ new Map();
909
+ const cacheKey = crypto.createHash("sha256").update(query).digest("hex");
910
+ const cached = queryVectorCache.get(cacheKey);
911
+ const queryVec = cached ?? (await this.embedding.embed([query]))[0];
912
+ if (queryVec === void 0) return /* @__PURE__ */ new Map();
913
+ if (cached === void 0) queryVectorCache.set(cacheKey, queryVec);
914
+ const rows = vectorSearch(this.db, queryVec, limit);
915
+ const out = /* @__PURE__ */ new Map();
916
+ for (const row of rows) {
917
+ const score = 1 / (1 + Math.max(0, row.distance));
918
+ out.set(row.chunk_id, { vectorScore: score });
919
+ }
920
+ return out;
921
+ }
922
+ combineHybridScores(textHits, vectorHitsById, options) {
923
+ const weights = resolveWeights(options);
924
+ const merged = this.mergeHits(textHits, vectorHitsById);
925
+ const combined = [...merged.values()].map(
926
+ (hit) => blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights)
927
+ );
928
+ return combined.sort((a, b) => b.score - a.score);
929
+ }
930
+ mergeHits(textHits, vectorHitsById) {
931
+ const merged = /* @__PURE__ */ new Map();
932
+ for (const hit of textHits) merged.set(hit.chunkId, hit);
933
+ const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));
934
+ if (missingIds.length > 0) {
935
+ for (const hit of this.fetchChunksByIds(missingIds)) {
936
+ merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });
937
+ }
938
+ }
939
+ return merged;
940
+ }
941
+ fetchChunksByIds(ids) {
942
+ if (ids.length === 0) return [];
943
+ const placeholders = ids.map(() => "?").join(",");
944
+ const rows = this.db.prepare(
945
+ `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
946
+ chunks.start_line as start_line, chunks.end_line as end_line,
947
+ chunks.text as text
948
+ FROM chunks JOIN files ON chunks.file_id = files.id
949
+ WHERE chunks.id IN (${placeholders})`
950
+ ).all(...ids);
951
+ return rows.map((row) => {
952
+ const startLine = Number(row.start_line ?? 0);
953
+ const endLine = Number(row.end_line ?? 0);
954
+ const path = String(row.rel_path);
955
+ return {
956
+ chunkId: Number(row.id),
957
+ path,
958
+ startLine,
959
+ endLine,
960
+ score: 0,
961
+ textScore: 0,
962
+ snippet: truncateSnippet(String(row.text ?? "")),
963
+ source: String(row.source),
964
+ citation: `${path}:${startLine}-${endLine}`
965
+ };
966
+ });
967
+ }
968
+ // ───── persistence helpers ─────────────────────────────────────────
969
+ loadFilesIndex() {
970
+ const rows = this.db.prepare("SELECT id, path, hash FROM files").all();
971
+ return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));
972
+ }
973
+ upsertFile(absPath, relPath, hash, mtimeMs, source = "memory") {
974
+ const stmt = this.db.prepare(
975
+ `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)
976
+ ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source
977
+ RETURNING id`
978
+ );
979
+ const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source);
980
+ return row.id;
981
+ }
982
+ deleteChunksForFile(fileId) {
983
+ this.db.prepare("DELETE FROM chunks WHERE file_id = ?").run(fileId);
984
+ }
985
+ insertChunk(fileId, startLine, endLine, text, hash) {
986
+ this.db.prepare(
987
+ "INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)"
988
+ ).run(fileId, startLine, endLine, text, hash);
989
+ }
990
+ close() {
991
+ this.db.close();
992
+ }
993
+ };
994
+
995
+ exports.IndexManager = IndexManager;
996
+ exports.LanceIndex = LanceIndex;
997
+ exports.appendFact = appendFact;
998
+ exports.appendFactToMarkdown = appendFactToMarkdown;
999
+ exports.defaultIndexPath = defaultIndexPath;
1000
+ exports.globalEmbeddingCache = globalEmbeddingCache;
1001
+ exports.lanceStoragePath = lanceStoragePath;
1002
+ exports.legacyMemoryJsonPath = legacyMemoryJsonPath;
1003
+ exports.memoryDir = memoryDir;
1004
+ exports.memoryMdPath = memoryMdPath;
1005
+ exports.openMemoryDb = openMemoryDb;
1006
+ exports.readFacts = readFacts;
1007
+ exports.readFactsFromMarkdown = readFactsFromMarkdown;
1008
+ exports.writeSessionSummary = writeSessionSummary;
1009
+ //# sourceMappingURL=chunk-MQLCZ4HJ.cjs.map
1010
+ //# sourceMappingURL=chunk-MQLCZ4HJ.cjs.map