@wirecat/drive-cli 0.70.0 → 0.72.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 (262) hide show
  1. package/README.md +150 -70
  2. package/contracts/wirecat.json +77 -8
  3. package/dist/bin/drive.js +2 -2
  4. package/dist/bundle/agent-23OB2NZP.js +46 -0
  5. package/dist/bundle/{all-profiles-FW3GK3QO.js → all-profiles-GXGDVNQJ.js} +67 -25
  6. package/dist/bundle/{anthropic-QVKJT3II.js → anthropic-H5C4GQHC.js} +9 -9
  7. package/dist/bundle/{app-server-QU73RD5R.js → app-server-EQ3UK4C7.js} +97 -79
  8. package/dist/bundle/{bun-5XCD5CBB.js → bun-DTJVSRY3.js} +2 -2
  9. package/dist/bundle/{bun-sqlite-TIGSVNSV.js → bun-sqlite-JIFY7MAE.js} +9 -9
  10. package/dist/bundle/chunk-2Q325BBD.js +353 -0
  11. package/dist/bundle/chunk-35FIJGTT.js +52 -0
  12. package/dist/bundle/{chunk-7C5KENNU.js → chunk-3FRQ6V4T.js} +3 -3
  13. package/dist/bundle/chunk-47L262VI.js +340 -0
  14. package/dist/bundle/chunk-4HP6KGBI.js +32 -0
  15. package/dist/bundle/{chunk-GA3URWIF.js → chunk-4HPXWYTE.js} +1 -1
  16. package/dist/bundle/{chunk-HYXXMSVD.js → chunk-4IUNYYYL.js} +4473 -2685
  17. package/dist/bundle/{chunk-FYPW7NMH.js → chunk-4JS32SRX.js} +64 -4
  18. package/dist/bundle/chunk-4ZAQMDLD.js +1308 -0
  19. package/dist/bundle/chunk-4ZTB7LS3.js +87 -0
  20. package/dist/bundle/{chunk-SONPLYV7.js → chunk-55FH6IEL.js} +5 -5
  21. package/dist/bundle/{chunk-VVN6GHAZ.js → chunk-5BNMWSU2.js} +659 -255
  22. package/dist/bundle/{chunk-FVTKFIQH.js → chunk-5H747A76.js} +5496 -3195
  23. package/dist/bundle/{chunk-PR7XD2DI.js → chunk-5KWCO56H.js} +2 -2
  24. package/dist/bundle/{chunk-3AHBZP33.js → chunk-5U3NCE5R.js} +35 -12
  25. package/dist/bundle/{chunk-HRATXUFH.js → chunk-6CCO3JCM.js} +31 -22
  26. package/dist/bundle/{chunk-RLNZ7NX5.js → chunk-6ZW2ZJYC.js} +2 -2
  27. package/dist/bundle/{chunk-RQNRYF6D.js → chunk-75DAHQOV.js} +3 -3
  28. package/dist/bundle/{chunk-7QSRODXM.js → chunk-77OBW43F.js} +6 -6
  29. package/dist/bundle/{chunk-GV5DGHSA.js → chunk-7EFM6AW3.js} +4 -4
  30. package/dist/bundle/{chunk-BXPC5TFG.js → chunk-A3S7QM5L.js} +3 -3
  31. package/dist/bundle/{chunk-IGNIUDI3.js → chunk-AA4LKC6W.js} +251 -565
  32. package/dist/bundle/chunk-ASTKHB6B.js +3233 -0
  33. package/dist/bundle/{chunk-3TCMANIM.js → chunk-BM6V7456.js} +8 -227
  34. package/dist/bundle/chunk-BO6EDBYJ.js +50 -0
  35. package/dist/bundle/{chunk-F5KJWRF5.js → chunk-BPA3R4KN.js} +2 -100
  36. package/dist/bundle/chunk-CIFE4KPX.js +2159 -0
  37. package/dist/bundle/chunk-CKB4XZZJ.js +730 -0
  38. package/dist/bundle/{chunk-YCL3SK4T.js → chunk-COJTCEZP.js} +113 -860
  39. package/dist/bundle/{chunk-BD2K2ONK.js → chunk-CWPYDT73.js} +6 -6
  40. package/dist/bundle/{chunk-6BMTW5A6.js → chunk-D4JNCXS7.js} +9 -9
  41. package/dist/bundle/chunk-DCPWZIOV.js +696 -0
  42. package/dist/bundle/{chunk-P7PLKNPX.js → chunk-DHMNCOQI.js} +415 -272
  43. package/dist/bundle/chunk-DOQMH4DC.js +280 -0
  44. package/dist/bundle/chunk-DQSOYH6N.js +20 -0
  45. package/dist/bundle/{chunk-ML3R2UHV.js → chunk-DWRUOLBF.js} +4 -4
  46. package/dist/bundle/{chunk-5JTB4URG.js → chunk-E3VWZC3K.js} +14 -13
  47. package/dist/bundle/chunk-ECYOTDJM.js +14 -0
  48. package/dist/bundle/{chunk-7IBENBCK.js → chunk-EVG3AA5M.js} +2 -2
  49. package/dist/bundle/chunk-F4BX7TH2.js +15 -0
  50. package/dist/bundle/{chunk-FCSHWUMW.js → chunk-FBEZSA76.js} +5 -5
  51. package/dist/bundle/{chunk-RHSBXOQM.js → chunk-FBQJN74J.js} +1 -1
  52. package/dist/bundle/{chunk-4WK26MPY.js → chunk-FIZOPJYY.js} +1 -1
  53. package/dist/bundle/chunk-FNAYSZWK.js +783 -0
  54. package/dist/bundle/{chunk-LINBDWJK.js → chunk-FRCJHGZM.js} +2 -2
  55. package/dist/bundle/{chunk-RCTOWLCD.js → chunk-FTG5QBSD.js} +41 -33
  56. package/dist/bundle/{chunk-ABZ2NYDT.js → chunk-FUDUXIVG.js} +1 -1
  57. package/dist/bundle/{chunk-NYECVHFH.js → chunk-G4NHRFS7.js} +755 -0
  58. package/dist/bundle/{chunk-PAPY6Q6H.js → chunk-GIEZYBRC.js} +1 -1
  59. package/dist/bundle/chunk-GTPPUBYU.js +1876 -0
  60. package/dist/bundle/chunk-GU6ICH53.js +108 -0
  61. package/dist/bundle/{chunk-REM5WHHQ.js → chunk-GUMKKRE6.js} +107 -71
  62. package/dist/bundle/{chunk-QBAOIMVB.js → chunk-GWCDOYSC.js} +1 -1
  63. package/dist/bundle/{chunk-HHAZ6DCY.js → chunk-GXGSC622.js} +69 -7
  64. package/dist/bundle/chunk-HAGXTGJC.js +188 -0
  65. package/dist/bundle/{chunk-TNKQDS5A.js → chunk-IMAWQC5K.js} +6 -6
  66. package/dist/bundle/{chunk-ZHZYGY5R.js → chunk-IVGVVSPW.js} +4 -4
  67. package/dist/bundle/{chunk-EDO5LZVF.js → chunk-J4NUHSM7.js} +1 -1
  68. package/dist/bundle/{chunk-DVVUJ254.js → chunk-K652FYCO.js} +6 -6
  69. package/dist/bundle/chunk-K6ZWNTXY.js +561 -0
  70. package/dist/bundle/{chunk-FONIFRYI.js → chunk-KF3ZBQJV.js} +4 -4
  71. package/dist/bundle/chunk-KFZCHJRT.js +80 -0
  72. package/dist/bundle/chunk-KLPFDFLI.js +221 -0
  73. package/dist/bundle/{chunk-LMJBQFW6.js → chunk-KP2XMCNT.js} +13 -13
  74. package/dist/bundle/{chunk-FADAOLGB.js → chunk-KWDZ3KVH.js} +4 -4
  75. package/dist/bundle/{chunk-MXNQZAJQ.js → chunk-KX4C32WD.js} +2 -2
  76. package/dist/bundle/chunk-L7P3LUDQ.js +286 -0
  77. package/dist/bundle/{chunk-ILAQIBEO.js → chunk-M2ZWYVWO.js} +1 -1
  78. package/dist/bundle/chunk-MEYYH47C.js +25 -0
  79. package/dist/bundle/{chunk-ZCXWV4XO.js → chunk-ML2QIWX2.js} +4 -4
  80. package/dist/bundle/{chunk-XOL346TJ.js → chunk-MUFF2YTH.js} +2 -2
  81. package/dist/bundle/{chunk-GAHIHE4K.js → chunk-N24YSLED.js} +9166 -9751
  82. package/dist/bundle/chunk-N4GTCPML.js +7 -0
  83. package/dist/bundle/{chunk-DVI72ZQG.js → chunk-NBMGDRP4.js} +1 -1
  84. package/dist/bundle/chunk-NMQRSEZM.js +37 -0
  85. package/dist/bundle/{chunk-I7YSHUPW.js → chunk-NNGA4QDR.js} +13 -26
  86. package/dist/bundle/{chunk-5DPV7X27.js → chunk-NTZWY5R3.js} +321 -0
  87. package/dist/bundle/chunk-O7CZZ36M.js +80 -0
  88. package/dist/bundle/{chunk-HWUPU6WX.js → chunk-OAONP6KI.js} +13 -9
  89. package/dist/bundle/{chunk-3CHW7JGR.js → chunk-OESP4PHB.js} +17 -17
  90. package/dist/bundle/chunk-OHR6IZNH.js +116 -0
  91. package/dist/bundle/{chunk-54NDYVZA.js → chunk-OLCU7Q2B.js} +1 -1
  92. package/dist/bundle/{chunk-FN3RXBO7.js → chunk-OLDQLEPA.js} +6 -6
  93. package/dist/bundle/{chunk-7DJNURKV.js → chunk-OPIPG6AP.js} +16 -9
  94. package/dist/bundle/{chunk-5D4AEUVA.js → chunk-PL5P7UKW.js} +434 -1
  95. package/dist/bundle/chunk-PRYMT3OG.js +30 -0
  96. package/dist/bundle/chunk-QDUIVMEW.js +36 -0
  97. package/dist/bundle/{chunk-66PL7P4C.js → chunk-QKBPCX7Y.js} +1 -1
  98. package/dist/bundle/{chunk-PN4JYURZ.js → chunk-QSLOACDT.js} +201 -423
  99. package/dist/bundle/{chunk-3UWRAIWA.js → chunk-QUZFDU4K.js} +4 -4
  100. package/dist/bundle/{chunk-KSJAFMU5.js → chunk-R32DHS6J.js} +211 -380
  101. package/dist/bundle/{chunk-2SBC4DVV.js → chunk-R57QUYBG.js} +6 -28
  102. package/dist/bundle/{chunk-IFTX7AQU.js → chunk-R64OSDOD.js} +45 -66
  103. package/dist/bundle/{chunk-WJK6KTCS.js → chunk-RSPBVKOC.js} +8 -8
  104. package/dist/bundle/{chunk-GPDPEHYX.js → chunk-SPNPJ3FZ.js} +3 -4
  105. package/dist/bundle/chunk-SQHDSIFL.js +388 -0
  106. package/dist/bundle/{chunk-XZBA6FVH.js → chunk-ST35FIUG.js} +3 -3
  107. package/dist/bundle/{chunk-37MAA6F2.js → chunk-STUPCKAA.js} +11 -2221
  108. package/dist/bundle/chunk-SZ7XJZGH.js +2231 -0
  109. package/dist/bundle/chunk-TRYYWV7J.js +291 -0
  110. package/dist/bundle/{chunk-OY7TNUEC.js → chunk-TTPWKTVR.js} +1 -1
  111. package/dist/bundle/{chunk-3UZ4OH22.js → chunk-U7VEJ3CW.js} +49 -129
  112. package/dist/bundle/{chunk-6Y2BYFXQ.js → chunk-UC7JLE6J.js} +0 -7
  113. package/dist/bundle/{chunk-HK225DAG.js → chunk-UIQ35CA5.js} +1 -1
  114. package/dist/bundle/{chunk-GK3BJMGK.js → chunk-UJY26HW4.js} +1 -1
  115. package/dist/bundle/{chunk-EG62WVR2.js → chunk-UWG3PRY7.js} +9 -60
  116. package/dist/bundle/{chunk-BBRMDMIR.js → chunk-VAR3MJU6.js} +3 -3
  117. package/dist/bundle/{chunk-GJZSVSV3.js → chunk-VPQSI5IU.js} +4 -4
  118. package/dist/bundle/{chunk-YZPE72GE.js → chunk-VQPT3Y7W.js} +12 -12
  119. package/dist/bundle/{chunk-T5D4OGDC.js → chunk-WMG3H2VK.js} +2 -2
  120. package/dist/bundle/{chunk-6DPOWBKA.js → chunk-X5BGAZC5.js} +6 -6
  121. package/dist/bundle/{chunk-DHX27E5M.js → chunk-XC6TRWLZ.js} +3 -3
  122. package/dist/bundle/{chunk-Q5C6YKAY.js → chunk-XQZEMRCU.js} +402 -402
  123. package/dist/bundle/{chunk-54BQWRJL.js → chunk-XZ7MO6EU.js} +7 -7
  124. package/dist/bundle/{chunk-TGS5VPJD.js → chunk-YAIOEPKU.js} +341 -433
  125. package/dist/bundle/chunk-YHWFF6DN.js +39 -0
  126. package/dist/bundle/{chunk-WWE5GO6G.js → chunk-YWOLQEDV.js} +16 -3
  127. package/dist/bundle/{chunk-DR57KDAY.js → chunk-ZFDSJ5YJ.js} +38 -8
  128. package/dist/bundle/{chunk-BBFXQPKD.js → chunk-ZFUZEFU6.js} +3 -3
  129. package/dist/bundle/{chunk-YRUR3E3E.js → chunk-ZJKXSMXK.js} +72 -59
  130. package/dist/bundle/{chunk-BFKFKDPC.js → chunk-ZKWT6HXT.js} +1 -1
  131. package/dist/bundle/chunk-ZPUY3COZ.js +250 -0
  132. package/dist/bundle/{cli-K4D4DIGQ.js → cli-2P5FW2RL.js} +201 -98
  133. package/dist/bundle/command-contract-BMQT2G5X.js +45 -0
  134. package/dist/bundle/{command-server-entry-WREK3QBB.js → command-server-entry-KP2UDGLA.js} +36 -34
  135. package/dist/bundle/{decode-SEETPKBH.js → decode-K2JZ5D6V.js} +10 -10
  136. package/dist/bundle/{dispatch-SQCEURVK.js → dispatch-KOQZA74A.js} +10 -10
  137. package/dist/bundle/dist-PAKDDIBT.js +191 -0
  138. package/dist/bundle/drive.js +11 -11
  139. package/dist/bundle/{echarts-WZ5RKFCX.js → echarts-URO3QGCG.js} +2 -2
  140. package/dist/bundle/{embed-B2UCRZZR.js → embed-JLIPWTNN.js} +10 -10
  141. package/dist/bundle/{embedder-4R6Z7G7L.js → embedder-LUTDO3HS.js} +15 -15
  142. package/dist/bundle/entry-AVF6LMG7.js +25 -0
  143. package/dist/bundle/{failure-CYNXH3RQ.js → failure-GJMQLM7O.js} +4 -4
  144. package/dist/bundle/first-run-VYTIEUDA.js +31 -0
  145. package/dist/bundle/first-screen-QVZPF7KL.js +45 -0
  146. package/dist/bundle/google-VX7IPACN.js +46 -0
  147. package/dist/bundle/{google-api-SAND2F7L.js → google-api-RFXKRLL4.js} +88 -73
  148. package/dist/bundle/grants-4XWJFVD6.js +133 -0
  149. package/dist/bundle/hast-util-from-html-X2DCPS3T.js +10531 -0
  150. package/dist/bundle/hast-util-to-html-VP6XLPKJ.js +998 -0
  151. package/dist/bundle/hast-util-to-mdast-IZ5PRX72.js +2272 -0
  152. package/dist/bundle/{identity-JVVGS4U6.js → identity-FXPB5EMT.js} +7 -6
  153. package/dist/bundle/{instructions-JSMTSB22.js → instructions-IROIUVZI.js} +1 -1
  154. package/dist/bundle/{login-6WG3YBDU.js → login-WIY5VQU7.js} +96 -81
  155. package/dist/bundle/{mcp-VFIOZDVY.js → mcp-NJIOKW3E.js} +2 -2
  156. package/dist/bundle/{mdast-util-from-markdown-FXEPSNER.js → mdast-util-from-markdown-HEZF7KJ4.js} +137 -195
  157. package/dist/bundle/mdast-util-gfm-AQW6R6MG.js +925 -0
  158. package/dist/bundle/mdast-util-to-hast-DF2QVIRV.js +879 -0
  159. package/dist/bundle/mdast-util-to-markdown-XYLXB3Z3.js +18 -0
  160. package/dist/bundle/meeting-combined-JUNV35GM.js +28 -0
  161. package/dist/bundle/meeting-model-XY4UNWWK.js +29 -0
  162. package/dist/bundle/{meeting-semantic-5U7JQCFF.js → meeting-semantic-62QNQMOM.js} +10 -10
  163. package/dist/bundle/{micromark-extension-gfm-GRL24TU6.js → micromark-extension-gfm-OE2GBORZ.js} +11 -78
  164. package/dist/bundle/{node-VJMVHOWD.js → node-IACCI2CW.js} +2 -2
  165. package/dist/bundle/{node-sqlite-DCNT3HVE.js → node-sqlite-WYIRC7C7.js} +10 -10
  166. package/dist/bundle/notes-search-DEDUJKSN.js +70 -0
  167. package/dist/bundle/oauth-HXBXF4VI.js +22 -0
  168. package/dist/bundle/{open-NFOEHVW7.js → open-H32B6BCT.js} +8 -8
  169. package/dist/bundle/{openai-D47WY7EC.js → openai-VHMPJJUG.js} +22 -21
  170. package/dist/bundle/{process-Q2FRU5VA.js → process-RNHPF5OK.js} +1 -1
  171. package/dist/bundle/{program-T2AJJQEM.js → program-GYMJ3DDH.js} +276 -1132
  172. package/dist/bundle/{prompt-YJSDABXN.js → prompt-TOG2CRCE.js} +8 -8
  173. package/dist/bundle/{reasons-WEHPCSJX.js → reasons-TLFQ45YX.js} +6 -5
  174. package/dist/bundle/{recognize-6OBEIEB3.js → recognize-GYGY45EY.js} +7 -7
  175. package/dist/bundle/remote-6XN2QLI5.js +35 -0
  176. package/dist/bundle/{rerank-L6F5SLIB.js → rerank-HJO3O4TW.js} +11 -11
  177. package/dist/bundle/{serve-GYSWIWH4.js → serve-XPCNLHCR.js} +19 -19
  178. package/dist/bundle/server-UBJZ66XE.js +97 -0
  179. package/dist/bundle/{server-GWWP3RIT.js → server-WPT3NC5B.js} +89 -70
  180. package/dist/bundle/{services-BDQBRXT5.js → services-253KKKVU.js} +109 -89
  181. package/dist/bundle/{sqlite-runtime-ZSZGAUYB.js → sqlite-runtime-EZASGJXW.js} +9 -9
  182. package/dist/bundle/{start-BJ275RUK.js → start-UHI35JFL.js} +7 -7
  183. package/dist/bundle/{state-HLNGFI2T.js → state-KJTSPFGK.js} +9 -9
  184. package/dist/bundle/{store-I43KZNJW.js → store-62J2H2A3.js} +36 -25
  185. package/dist/bundle/{store-OSRTGYGI.js → store-G5B7T7M7.js} +38 -23
  186. package/dist/bundle/store-maintenance-command-C6T4YLVF.js +85 -0
  187. package/dist/bundle/surface-3OT64BHS.js +83 -0
  188. package/dist/bundle/tokens-EHYO6D2X.js +133 -0
  189. package/dist/commands/documents.d.ts.map +1 -1
  190. package/dist/commands/documents.js +11 -1
  191. package/dist/commands/documents.js.map +1 -1
  192. package/dist/commands/remote.d.ts.map +1 -1
  193. package/dist/commands/remote.js +8 -22
  194. package/dist/commands/remote.js.map +1 -1
  195. package/dist/commands/sync.d.ts.map +1 -1
  196. package/dist/commands/sync.js +14 -4
  197. package/dist/commands/sync.js.map +1 -1
  198. package/dist/config.d.ts +5 -0
  199. package/dist/config.d.ts.map +1 -1
  200. package/dist/config.js +7 -1
  201. package/dist/config.js.map +1 -1
  202. package/dist/first-screen.d.ts.map +1 -1
  203. package/dist/first-screen.js +2 -1
  204. package/dist/first-screen.js.map +1 -1
  205. package/dist/generated/manifest.d.ts +2 -1
  206. package/dist/generated/manifest.d.ts.map +1 -1
  207. package/dist/generated/manifest.js +782 -0
  208. package/dist/generated/manifest.js.map +1 -1
  209. package/dist/generated/types.d.ts +262 -58
  210. package/dist/generated/types.d.ts.map +1 -1
  211. package/dist/google.d.ts.map +1 -1
  212. package/dist/google.js +5 -5
  213. package/dist/google.js.map +1 -1
  214. package/dist/model.d.ts +5 -2
  215. package/dist/model.d.ts.map +1 -1
  216. package/dist/model.js.map +1 -1
  217. package/dist/policy-keys.js +1 -1
  218. package/dist/policy-keys.js.map +1 -1
  219. package/dist/program.d.ts.map +1 -1
  220. package/dist/program.js +9 -4
  221. package/dist/program.js.map +1 -1
  222. package/dist/state.d.ts.map +1 -1
  223. package/dist/state.js +6 -1
  224. package/dist/state.js.map +1 -1
  225. package/dist/store.d.ts.map +1 -1
  226. package/dist/store.js +2 -7
  227. package/dist/store.js.map +1 -1
  228. package/dist/supported.d.ts +2 -2
  229. package/dist/supported.d.ts.map +1 -1
  230. package/dist/supported.js +2 -3
  231. package/dist/supported.js.map +1 -1
  232. package/dist/sync.d.ts +2 -1
  233. package/dist/sync.d.ts.map +1 -1
  234. package/dist/sync.js +6 -4
  235. package/dist/sync.js.map +1 -1
  236. package/dist/transcripts.d.ts +0 -6
  237. package/dist/transcripts.d.ts.map +1 -1
  238. package/dist/transcripts.js +0 -13
  239. package/dist/transcripts.js.map +1 -1
  240. package/dist/version.d.ts +1 -1
  241. package/dist/version.js +1 -1
  242. package/package.json +3 -3
  243. package/scenarios/find-decision.md +1 -1
  244. package/skills/drive-cli/SKILL.md +4 -2
  245. package/dist/bundle/chunk-AV5UKJZM.js +0 -729
  246. package/dist/bundle/chunk-NP7LJATI.js +0 -598
  247. package/dist/bundle/chunk-P77FL6RY.js +0 -896
  248. package/dist/bundle/chunk-ZI3YTXSF.js +0 -2
  249. package/dist/bundle/command-contract-V3F452QI.js +0 -43
  250. package/dist/bundle/entry-ORZYRJ5N.js +0 -25
  251. package/dist/bundle/first-run-KAKA6KBY.js +0 -31
  252. package/dist/bundle/first-screen-R645UHRH.js +0 -41
  253. package/dist/bundle/google-BSO3YB7N.js +0 -45
  254. package/dist/bundle/grants-PLNFYARD.js +0 -118
  255. package/dist/bundle/mdast-util-gfm-SZM5GBDF.js +0 -2103
  256. package/dist/bundle/meeting-combined-SUKMFK3F.js +0 -27
  257. package/dist/bundle/meeting-model-S4YGKIFI.js +0 -29
  258. package/dist/bundle/oauth-KCMNQ3ZP.js +0 -22
  259. package/dist/bundle/remote-3SL2QJ7T.js +0 -35
  260. package/dist/bundle/server-BI46BSRE.js +0 -80
  261. package/dist/bundle/store-maintenance-command-FO7LEVSL.js +0 -72
  262. package/dist/bundle/tokens-DB7O7QNB.js +0 -118
@@ -0,0 +1,2159 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ embeddingKeys,
5
+ endpointKeyName,
6
+ modelGateway,
7
+ withRecovery
8
+ } from "./chunk-ZPUY3COZ.js";
9
+ import {
10
+ safeName
11
+ } from "./chunk-QDUIVMEW.js";
12
+ import {
13
+ capability
14
+ } from "./chunk-PRYMT3OG.js";
15
+ import {
16
+ questionLookup,
17
+ questionText
18
+ } from "./chunk-BM6V7456.js";
19
+ import {
20
+ localOnly
21
+ } from "./chunk-OLDQLEPA.js";
22
+ import {
23
+ defaultThreads,
24
+ isTextModelInstalled,
25
+ openEmbedder,
26
+ textModelsDirectory
27
+ } from "./chunk-R64OSDOD.js";
28
+ import {
29
+ DEFAULT_IMAGE_MODEL,
30
+ codeOf,
31
+ imageModel,
32
+ imageModelsDirectory,
33
+ isImageModelInstalled
34
+ } from "./chunk-HAGXTGJC.js";
35
+ import {
36
+ ANSWER_RESERVE_MS,
37
+ deadlineMargin
38
+ } from "./chunk-4JS32SRX.js";
39
+ import {
40
+ envName
41
+ } from "./chunk-5KWCO56H.js";
42
+ import {
43
+ DEFAULT_TEXT_MODEL,
44
+ PREVIOUS_DEFAULT_TEXT_MODEL,
45
+ chosenTextModel,
46
+ meaningFloor,
47
+ textModel,
48
+ textModels,
49
+ vectorModelKey
50
+ } from "./chunk-IMAWQC5K.js";
51
+ import {
52
+ endpoint,
53
+ modelAddressAllowed,
54
+ onThisComputer
55
+ } from "./chunk-ZFDSJ5YJ.js";
56
+ import {
57
+ chatReferenceOf,
58
+ chatsMatching,
59
+ ensureAccount,
60
+ hasStems,
61
+ isId,
62
+ nearest,
63
+ peopleMatching,
64
+ pickChat,
65
+ pickPerson,
66
+ profilesOn
67
+ } from "./chunk-DCPWZIOV.js";
68
+ import {
69
+ DEFAULT_STEMMERS,
70
+ createStemmer
71
+ } from "./chunk-5U3NCE5R.js";
72
+ import {
73
+ RRF_K,
74
+ SEARCH_QUERY,
75
+ isQueryLimit,
76
+ plainQuery,
77
+ validateFields
78
+ } from "./chunk-OPIPG6AP.js";
79
+ import {
80
+ normalize
81
+ } from "./chunk-TTPWKTVR.js";
82
+ import {
83
+ INTERNAL_NOTES,
84
+ accountsOfList,
85
+ entriesOfList,
86
+ fitting,
87
+ formatLocator,
88
+ holdsKindOf,
89
+ isAccountList,
90
+ isDocumentAccountProvider,
91
+ isFolderProvider,
92
+ isGroupName,
93
+ isImportedProvider,
94
+ isKind,
95
+ keyOf,
96
+ providerNamed,
97
+ sameAs,
98
+ sourceOf2 as sourceOf,
99
+ typedCommand
100
+ } from "./chunk-COJTCEZP.js";
101
+ import {
102
+ isCliFailure,
103
+ sqliteCode
104
+ } from "./chunk-6ZW2ZJYC.js";
105
+ import {
106
+ normalizeTag
107
+ } from "./chunk-XC6TRWLZ.js";
108
+ import {
109
+ dateRange,
110
+ parseLucene,
111
+ timezoneOf
112
+ } from "./chunk-XQZEMRCU.js";
113
+ import {
114
+ readSharedSection,
115
+ sharedConfigPath,
116
+ writeSharedSection
117
+ } from "./chunk-RSPBVKOC.js";
118
+ import {
119
+ storePath
120
+ } from "./chunk-WMG3H2VK.js";
121
+ import {
122
+ singleLine
123
+ } from "./chunk-FUDUXIVG.js";
124
+ import {
125
+ array,
126
+ check,
127
+ getDotPath,
128
+ integer,
129
+ isoTimestamp,
130
+ maxLength,
131
+ minLength,
132
+ minValue,
133
+ number,
134
+ object,
135
+ optional,
136
+ parse,
137
+ picklist,
138
+ pipe,
139
+ safeParse,
140
+ strictObject,
141
+ string,
142
+ transform,
143
+ trim,
144
+ unknown
145
+ } from "./chunk-GXGSC622.js";
146
+ import {
147
+ CliError
148
+ } from "./chunk-OLCU7Q2B.js";
149
+ import {
150
+ __name
151
+ } from "./chunk-ZVVMGPBJ.js";
152
+
153
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/search/groups.js
154
+ var ALL = "all";
155
+ var OWNER_NOTES = { provider: "notes", account: INTERNAL_NOTES };
156
+ var NOT_GROUP_NAMES = /* @__PURE__ */ new Set([ALL, "bots"]);
157
+ var hasGroup = /* @__PURE__ */ __name((groups, name) => Object.hasOwn(groups, name), "hasGroup");
158
+ var membersOf = /* @__PURE__ */ __name((entries, context, unresolved) => {
159
+ const members = /* @__PURE__ */ new Map();
160
+ for (const entry of entries)
161
+ try {
162
+ for (const { provider, account } of accountsOfList(entry, context)) {
163
+ const known = members.get(keyOf({ provider, account }));
164
+ if (known)
165
+ known.entries.push(entry);
166
+ else
167
+ members.set(keyOf({ provider, account }), {
168
+ provider,
169
+ account,
170
+ entries: [entry],
171
+ reason: "setting",
172
+ profiles: [],
173
+ also_in: []
174
+ });
175
+ }
176
+ } catch (error) {
177
+ if (!(error instanceof CliError))
178
+ throw error;
179
+ unresolved.push(entry);
180
+ }
181
+ return [...members.values()];
182
+ }, "membersOf");
183
+ var groupMembership = /* @__PURE__ */ __name((context) => {
184
+ const plain = { ...context, groups: {} };
185
+ const unresolved = [];
186
+ const groups = {};
187
+ for (const [name, entries] of Object.entries(context.groups))
188
+ if (name !== ALL)
189
+ groups[name] = membersOf(entries, plain, unresolved);
190
+ const system = [OWNER_NOTES, ...context.held.filter(({ id }) => id === 0)].map(keyOf);
191
+ const every = accountsOfList(ALL, plain).filter((one) => !system.includes(keyOf(one))).map(({ provider, account }) => ({
192
+ provider,
193
+ account,
194
+ entries: [sourceOf({ provider, account })],
195
+ reason: "all",
196
+ profiles: [],
197
+ also_in: []
198
+ }));
199
+ const recorded = Object.entries(context.profiles).flatMap(([app, named]) => Object.entries(named).map(([profile, key]) => ({ app, profile, key })));
200
+ const holding = /* @__PURE__ */ new Map();
201
+ for (const [name, members] of Object.entries(groups))
202
+ for (const one of members)
203
+ holding.set(keyOf(one), [...holding.get(keyOf(one)) ?? [], name]);
204
+ for (const [name, members] of [...Object.entries(groups), [ALL, every]])
205
+ for (const one of members) {
206
+ one.scope = context.held.find(sameAs(one))?.scope ?? "personal";
207
+ one.profiles = recorded.filter(({ key }) => sameAs(key)(one)).map(({ app, profile }) => `${app} ${profile}`);
208
+ one.also_in = (holding.get(keyOf(one)) ?? []).filter((other) => other !== name);
209
+ }
210
+ const duplicates = [...holding.entries()].filter(([, names]) => names.length > 1).map(([key, names]) => ({ member: key.replace("\0", ":"), groups: names }));
211
+ const shared = /* @__PURE__ */ __name((app, profile) => hasGroup(context.groups, profile) || recorded.some((other) => other.app !== app && other.profile === profile), "shared");
212
+ const suggested = recorded.filter(({ app, profile, key }) => isGroupName(profile) && !NOT_GROUP_NAMES.has(profile.toLowerCase()) && shared(app, profile) && !holding.get(keyOf(key))?.includes(profile)).map(({ app, profile, key }) => ({
213
+ group: profile,
214
+ member: sourceOf(key),
215
+ because: `profile named ${profile} (${app} ${profile})`
216
+ }));
217
+ return { groups: { ...groups, [ALL]: every }, duplicates, suggested, unresolved };
218
+ }, "groupMembership");
219
+ var inGroupOf = /* @__PURE__ */ __name((context, group) => (key) => group === ALL || (hasGroup(context.membership.groups, group) ? context.membership.groups[group] ?? [] : []).some(sameAs(key)), "inGroupOf");
220
+ var groupEntries = /* @__PURE__ */ __name((saved) => ({
221
+ ...Object.fromEntries(Object.entries(saved).filter(([name]) => name !== ALL)),
222
+ [ALL]: [ALL]
223
+ }), "groupEntries");
224
+ var fail = /* @__PURE__ */ __name((code, message, details) => {
225
+ throw new CliError(code, message, details);
226
+ }, "fail");
227
+ var unknownGroup = /* @__PURE__ */ __name((run, context) => {
228
+ const names = Object.keys(context.groups);
229
+ const unknown2 = run.from === "first word" ? `"${run.name}" is neither a command nor a group` : `no group "${run.name}" (${run.from})`;
230
+ const suggested = context.membership.suggested.filter(({ group }) => group === run.name);
231
+ const offer = suggested.length ? `; profiles named ${run.name} suggest ${suggested.map(({ member }) => member).join(", ")}` : "";
232
+ return fail("validation_error", `${unknown2} \u2014 groups here: ${names.join(", ")}${offer}`, {
233
+ groups: names,
234
+ ...suggested.length ? { suggested } : {}
235
+ });
236
+ }, "unknownGroup");
237
+ var scopeToGroup = /* @__PURE__ */ __name((run, request, context) => {
238
+ if (!hasGroup(context.groups, run.name))
239
+ unknownGroup(run, context);
240
+ const code = run.locked ? "permission_error" : "validation_error";
241
+ const why = run.locked ? `this process is locked to group ${run.name} (${run.from})` : `this run is in group ${run.name}`;
242
+ if (!context.membership.groups[run.name]?.length)
243
+ fail("validation_error", `group ${run.name} is empty`);
244
+ const inGroup = new Set(accountsOfList(`group:${run.name}`, context).map(keyOf));
245
+ const outside = /* @__PURE__ */ __name((accounts) => accounts.filter((one) => !inGroup.has(keyOf(one))), "outside");
246
+ const namedBy = /* @__PURE__ */ __name((item) => {
247
+ try {
248
+ return accountsOfList(item, context);
249
+ } catch (error) {
250
+ if (run.locked && error instanceof CliError)
251
+ return [];
252
+ throw error;
253
+ }
254
+ }, "namedBy");
255
+ const scoped = {};
256
+ if (request.source === void 0)
257
+ scoped.source = `group:${run.name}`;
258
+ else {
259
+ const items = request.source.split(",").map((item) => item.trim());
260
+ if (items.some((item) => item.toLowerCase() === "all"))
261
+ fail(code, `${why} \u2014 --source all reads outside it`);
262
+ const kept = [];
263
+ let narrowed = false;
264
+ for (const item of items) {
265
+ const accounts = namedBy(item);
266
+ const away = outside(accounts);
267
+ if (item.includes(":") && (away.length || accounts.length === 0))
268
+ fail(code, `${why} \u2014 ${item} is outside it${away.length ? ` (${away.map(sourceOf).join(", ")})` : ""}`);
269
+ if (away.length)
270
+ narrowed = true;
271
+ for (const one of accounts)
272
+ if (inGroup.has(keyOf(one)))
273
+ kept.push(sourceOf(one));
274
+ }
275
+ if (kept.length === 0)
276
+ fail("validation_error", `${why} \u2014 --source ${request.source} names none of its accounts`);
277
+ scoped.source = narrowed ? [...new Set(kept)].join(",") : request.source;
278
+ }
279
+ if (request.account !== void 0) {
280
+ const accounts = namedBy(request.account);
281
+ if (accounts.length === 0 || outside(accounts).length)
282
+ fail(code, `${why} \u2014 --account ${request.account} is outside it`);
283
+ scoped.account = request.account;
284
+ }
285
+ return scoped;
286
+ }, "scopeToGroup");
287
+
288
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/search/lucene/meaning-parts.js
289
+ var WORD_FIELDS = /* @__PURE__ */ new Set(["text", "exact"]);
290
+ var fieldsOfQuery = /* @__PURE__ */ __name((root, everything) => {
291
+ let narrows = false;
292
+ const kept = /* @__PURE__ */ __name((node) => {
293
+ if (node.kind === "boolean")
294
+ return {
295
+ ...node,
296
+ clauses: node.clauses.map(({ occur, node: node2 }) => {
297
+ if (occur !== "must_not")
298
+ return { occur, node: kept(node2) };
299
+ narrows = true;
300
+ return { occur, node: node2 };
301
+ })
302
+ };
303
+ if (!WORD_FIELDS.has(node.field)) {
304
+ narrows = true;
305
+ return node;
306
+ }
307
+ return { ...everything, span: node.span };
308
+ }, "kept");
309
+ const fields = kept(root);
310
+ return narrows ? fields : void 0;
311
+ }, "fieldsOfQuery");
312
+ var meaningWords = /* @__PURE__ */ __name((root) => {
313
+ const wanted = /* @__PURE__ */ __name((node) => node.kind === "boolean" ? node.clauses.flatMap(({ occur, node: node2 }) => occur === "must_not" ? [] : wanted(node2)) : WORD_FIELDS.has(node.field) && (node.operator === "term" || node.operator === "phrase") ? [node.value] : [], "wanted");
314
+ return wanted(root).join(" ").trim();
315
+ }, "meaningWords");
316
+
317
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/search/total.js
318
+ var TOTAL_CAP = 1e4;
319
+ var totalOf = /* @__PURE__ */ __name((count, shown, hasMore, exact = true) => {
320
+ const least = shown + (hasMore ? 1 : 0);
321
+ if (count === void 0 || count < least)
322
+ return { value: least, relation: "gte" };
323
+ if (count > TOTAL_CAP)
324
+ return { value: TOTAL_CAP, relation: "gte" };
325
+ return { value: count, relation: exact ? "eq" : "gte" };
326
+ }, "totalOf");
327
+
328
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/document-pictures.js
329
+ import { createHash } from "node:crypto";
330
+ var refOf = /* @__PURE__ */ __name((target) => target.ref ?? `document:${target.documentId}`, "refOf");
331
+ var openPictureEmbedderFor = /* @__PURE__ */ __name(async ({ env, command } = {}) => {
332
+ const model = imageModel(DEFAULT_IMAGE_MODEL);
333
+ const directory = imageModelsDirectory(env);
334
+ if (!isImageModelInstalled(model, directory))
335
+ throw new CliError("not_found", `the picture model is not downloaded \u2014 ${command === void 0 ? "install it with a WireCat CLI that has `images models download` (tg, max or wa); they share the model folder" : `\`${command} images models download ${model.id}\` fetches it`}`, { reason: "model.not-downloaded", model: model.id });
336
+ const { openPictureEmbedder } = await import("./embedder-LUTDO3HS.js");
337
+ return openPictureEmbedder(model, directory);
338
+ }, "openPictureEmbedderFor");
339
+ var savePicture = /* @__PURE__ */ __name(async (store, target, bytes, options = {}) => {
340
+ const ref = refOf(target);
341
+ const model = imageModel(DEFAULT_IMAGE_MODEL);
342
+ const hash = createHash("sha256").update(bytes).digest("hex");
343
+ if (await store.notes.pictureHash(ref, model.key) === hash)
344
+ return "unchanged";
345
+ const embedder = options.embedder ?? await openPictureEmbedderFor(options);
346
+ try {
347
+ const vector = await embedder.embedImage(bytes);
348
+ await store.notes.savePicture(ref, { model: model.key, dims: model.dims, hash, bytes: bytes.length, vector });
349
+ } finally {
350
+ if (!options.embedder)
351
+ await embedder.close();
352
+ }
353
+ return "saved";
354
+ }, "savePicture");
355
+ var removePicture = /* @__PURE__ */ __name((store, target) => store.notes.removePicture(refOf(target)), "removePicture");
356
+
357
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/document-source.js
358
+ var documentSource = /* @__PURE__ */ __name((note, accounts, profiles, file) => {
359
+ const metadata = note.frontMatter;
360
+ const account = accounts.find(({ id }) => String(id) === note.folderId);
361
+ if (note.source === "file" && account !== void 0 && isImportedProvider(account.provider))
362
+ return {
363
+ kind: "document",
364
+ provider: account.provider,
365
+ account: account.account,
366
+ ...file?.url ? { url: file.url } : {}
367
+ };
368
+ const remote = note.source === "file" && (account !== void 0 && isDocumentAccountProvider(account.provider) || isDocumentAccountProvider(metadata?.source));
369
+ const profile = remote && account ? Object.entries(profiles).flatMap(([command, named]) => Object.entries(named).map(([name, key]) => ({ command, name, key }))).find(({ key }) => key.provider === account.provider && key.account === account.account || isFolderProvider(key.provider) && key.account === account.name) : void 0;
370
+ const url = file?.url ?? (remote && typeof metadata?.sourceUrl === "string" ? metadata.sourceUrl : void 0);
371
+ return {
372
+ kind: remote ? "document" : "note",
373
+ provider: profile ? profile.command : "notes",
374
+ account: profile?.name ?? note.folderId ?? "internal",
375
+ ...remote && url !== void 0 ? { url } : {}
376
+ };
377
+ }, "documentSource");
378
+
379
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/enrichment-setting.js
380
+ var SECTION = "enrichment";
381
+ var ENRICHMENT_PROVIDERS = ["openai", "anthropic"];
382
+ var DEFAULT_BASE_URLS = {
383
+ openai: "https://api.openai.com/v1",
384
+ anthropic: "https://api.anthropic.com"
385
+ };
386
+ var MODEL_CHOICE = {
387
+ provider: picklist(ENRICHMENT_PROVIDERS),
388
+ model: pipe(string(), trim(), minLength(1), maxLength(200)),
389
+ base_url: optional(pipe(string(), check((value) => endpoint(value), "use an HTTP/S endpoint without credentials, query or fragment")))
390
+ };
391
+ var Setting = strictObject({
392
+ ...MODEL_CHOICE,
393
+ /** When the owner agreed that records go to this provider and endpoint; the setting exists only with it. */
394
+ consented_at: pipe(string(), isoTimestamp())
395
+ });
396
+ var enrichmentSettingPath = /* @__PURE__ */ __name((env) => sharedConfigPath(storePath(env), env), "enrichmentSettingPath");
397
+ var readEnrichmentSetting = /* @__PURE__ */ __name((env) => {
398
+ const path = enrichmentSettingPath(env);
399
+ const section = readSharedSection(path, SECTION);
400
+ if (section === void 0 || section === null)
401
+ return void 0;
402
+ const checked = safeParse(Setting, section);
403
+ if (!checked.success)
404
+ throw new CliError("configuration_error", `${path}: enrichment.${getDotPath(checked.issues[0]) ?? "settings"} is invalid \u2014 ${checked.issues[0].message}`);
405
+ return checked.output;
406
+ }, "readEnrichmentSetting");
407
+ var writeEnrichmentSetting = /* @__PURE__ */ __name((env, setting) => writeSharedSection(enrichmentSettingPath(env), SECTION, setting === void 0 ? void 0 : parse(Setting, setting)), "writeEnrichmentSetting");
408
+ var enrichmentEndpoint = /* @__PURE__ */ __name((setting) => setting.base_url ?? DEFAULT_BASE_URLS[setting.provider], "enrichmentEndpoint");
409
+ var isEnrichmentProvider = /* @__PURE__ */ __name((value) => ENRICHMENT_PROVIDERS.includes(value), "isEnrichmentProvider");
410
+ var PRICES = {
411
+ "openai/gpt-4o-mini": {
412
+ input: 15e-8,
413
+ output: 6e-7,
414
+ source: "https://developers.openai.com/api/docs/pricing"
415
+ },
416
+ "anthropic/claude-haiku-5-5": {
417
+ input: 1e-7,
418
+ output: 5e-7,
419
+ source: "https://platform.claude.com/docs/en/about-claude/pricing"
420
+ }
421
+ };
422
+ var DEFAULT_OFFER = { provider: "openai", model: "gpt-4o-mini" };
423
+ var offeredModels = /* @__PURE__ */ __name(() => Object.entries(PRICES).map(([key, price]) => {
424
+ const [provider, model] = key.split("/");
425
+ return {
426
+ provider,
427
+ model,
428
+ default: provider === DEFAULT_OFFER.provider && model === DEFAULT_OFFER.model,
429
+ usd_per_million: {
430
+ input: Math.round(price.input * 1e8) / 100,
431
+ output: Math.round(price.output * 1e8) / 100
432
+ }
433
+ };
434
+ }), "offeredModels");
435
+ var enrichmentPrice = /* @__PURE__ */ __name((provider, model, baseUrl) => baseUrl === void 0 ? PRICES[`${provider}/${model}`] : void 0, "enrichmentPrice");
436
+ var OUTPUT_TOKENS_PER_RECORD = 70;
437
+ var PROMPT_TOKENS_PER_RECORD = 40;
438
+ var estimateEnrichment = /* @__PURE__ */ __name((records, chars, setting) => {
439
+ const input = Math.ceil(chars / 4) + records * PROMPT_TOKENS_PER_RECORD;
440
+ const output = records * OUTPUT_TOKENS_PER_RECORD;
441
+ const price = setting && enrichmentPrice(setting.provider, setting.model, setting.base_url);
442
+ return {
443
+ records,
444
+ input_tokens: input,
445
+ output_tokens: output,
446
+ usd: price ? Math.round((input * price.input + output * price.output) * 1e6) / 1e6 : null
447
+ };
448
+ }, "estimateEnrichment");
449
+ var costOf = /* @__PURE__ */ __name((usage, setting) => {
450
+ const price = enrichmentPrice(setting.provider, setting.model, setting.base_url);
451
+ return price ? Math.round((usage.input * price.input + usage.output * price.output) * 1e6) / 1e6 : null;
452
+ }, "costOf");
453
+
454
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/enrichment.js
455
+ var ENRICH_PER_RUN = 600;
456
+ var BATCH = 20;
457
+ var CONCURRENCY = 4;
458
+ var MAX_INPUT_CHARS = 4e3;
459
+ var MAX_FACTS = 5;
460
+ var MAX_QUESTIONS = 3;
461
+ var MAX_LINE = 400;
462
+ var MAX_FAILED_BATCHES = 3;
463
+ var ENRICH_BATCH_MS = 3e4;
464
+ var SYSTEM = `For each record, write what a memory system would store about it.
465
+
466
+ For each record:
467
+ - facts: one to three standalone sentences, each stating exactly one fact. Name people, projects and things in
468
+ full, leave no pronoun unresolved, and turn relative dates into absolute ones using the record's date. Keep
469
+ amounts, dates and times exactly. Say whether the fact is confirmed, only proposed, rejected or cancelled.
470
+ Small talk with no fact gets an empty list.
471
+ - questions: two questions a person might ask whose answer is in this record, in everyday words that differ
472
+ from the record's own words (synonyms, plainer terms). Empty for small talk.
473
+
474
+ Write in the record's own language. Reply with JSON only: {"records": [{"i": <index>, "facts": [...], "questions": [...]}]}, one entry per record.`;
475
+ var line = pipe(unknown(), transform((value) => typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, MAX_LINE) : ""));
476
+ var Reply = object({
477
+ records: array(object({
478
+ i: pipe(number(), integer(), minValue(0)),
479
+ facts: optional(array(line), []),
480
+ questions: optional(array(line), [])
481
+ }))
482
+ });
483
+ var parseEnrichmentReply = /* @__PURE__ */ __name((text) => {
484
+ const start = text.indexOf("{");
485
+ const end = text.lastIndexOf("}");
486
+ if (start < 0 || end < start)
487
+ throw new CliError("invalid_response", "the enrichment reply holds no JSON object");
488
+ let parsed;
489
+ try {
490
+ parsed = JSON.parse(text.slice(start, end + 1));
491
+ } catch {
492
+ throw new CliError("invalid_response", "the enrichment reply is not valid JSON");
493
+ }
494
+ const checked = safeParse(Reply, parsed);
495
+ if (!checked.success)
496
+ throw new CliError("invalid_response", "the enrichment reply does not have the asked shape");
497
+ return new Map(checked.output.records.map((row) => [
498
+ row.i,
499
+ [...row.facts.slice(0, MAX_FACTS), ...row.questions.slice(0, MAX_QUESTIONS)].filter(Boolean).join("\n")
500
+ ]));
501
+ }, "parseEnrichmentReply");
502
+ var REASON_TEXT = {
503
+ "enrichment.key-rejected": "the provider refused the key; nothing more was sent",
504
+ "enrichment.unreachable": "the provider could not be reached; nothing more was sent",
505
+ "enrichment.deadline": "out of time before the run's deadline; the next sync goes on"
506
+ };
507
+ var reasonIdOf = /* @__PURE__ */ __name((error) => {
508
+ if (!(error instanceof CliError))
509
+ return "enrichment.bad-replies";
510
+ if (error.details.reason === "model.key-rejected")
511
+ return "enrichment.key-rejected";
512
+ if (error.details.reason === "model.unreachable")
513
+ return "enrichment.unreachable";
514
+ if (error.details.reason === "local-only.refused")
515
+ return "enrichment.local-only";
516
+ if (error.code === "rate_limited")
517
+ return "enrichment.rate-limited";
518
+ if (error.code === "cancelled")
519
+ return "enrichment.cancelled";
520
+ if (error.code === "invalid_response")
521
+ return "enrichment.bad-replies";
522
+ return "enrichment.error";
523
+ }, "reasonIdOf");
524
+ var recordsData = /* @__PURE__ */ __name((batch) => JSON.stringify(batch.map((record, i) => ({
525
+ i,
526
+ date: record.at === null ? null : new Date(record.at).toISOString().slice(0, 10),
527
+ kind: record.type === "email" ? "mail" : "note",
528
+ text: record.text.slice(0, MAX_INPUT_CHARS)
529
+ }))), "recordsData");
530
+ var keyLookup = /* @__PURE__ */ __name((options, setting) => {
531
+ if (options.key) {
532
+ const key2 = options.key(setting.provider);
533
+ return key2 === void 0 ? void 0 : { key: key2, source: "given" };
534
+ }
535
+ const name = setting.base_url === void 0 ? setting.provider : endpointKeyName(setting.base_url);
536
+ if (options.app) {
537
+ const keys = embeddingKeys(options.app, options.env, options.keyring);
538
+ const stored = keys.read(name);
539
+ if (stored)
540
+ return {
541
+ key: stored.key,
542
+ source: stored.source === "file" ? "file" : stored.source === "keyring" ? "keyring" : "env"
543
+ };
544
+ const plain = setting.base_url === void 0 ? keys.readPlain(setting.provider) : void 0;
545
+ return plain === void 0 ? void 0 : { key: plain, source: "keyring" };
546
+ }
547
+ const key = setting.base_url === void 0 ? options.env[keyVariable(setting.provider)]?.trim() : void 0;
548
+ return key ? { key, source: "env" } : void 0;
549
+ }, "keyLookup");
550
+ var keyVariable = /* @__PURE__ */ __name((provider) => `${provider.toUpperCase()}_API_KEY`, "keyVariable");
551
+ var enrichRecords = /* @__PURE__ */ __name(async (store, options) => {
552
+ const setting = readEnrichmentSetting(options.env);
553
+ if (!setting || !store.enrichment)
554
+ return { status: "off" };
555
+ const enrichment = store.enrichment;
556
+ const baseUrl = enrichmentEndpoint(setting);
557
+ const target = { provider: setting.provider, model: setting.model, baseUrl };
558
+ const apiKey = keyLookup(options, setting)?.key;
559
+ const maxRecords = options.maxRecords ?? ENRICH_PER_RUN;
560
+ const refused = !modelAddressAllowed(baseUrl) ? "enrichment.address-refused" : !onThisComputer(baseUrl) && localOnly(options.env) ? "enrichment.local-only" : void 0;
561
+ if (refused)
562
+ return {
563
+ status: "stopped",
564
+ provider: setting.provider,
565
+ model: setting.model,
566
+ enriched: 0,
567
+ failed: 0,
568
+ left: (await enrichment.pending(Number.MAX_SAFE_INTEGER, options.narrow)).length,
569
+ usage: { input: 0, output: 0 },
570
+ cost_usd: 0,
571
+ reason: refused === "enrichment.local-only" ? "local only is on and the model is not on this computer; nothing was sent" : "the address is plain http to another computer: use https, or http only on this computer; nothing was sent",
572
+ reason_id: refused
573
+ };
574
+ if (apiKey === void 0 && setting.base_url === void 0)
575
+ return {
576
+ status: "stopped",
577
+ provider: setting.provider,
578
+ model: setting.model,
579
+ enriched: 0,
580
+ failed: 0,
581
+ left: (await enrichment.pending(Number.MAX_SAFE_INTEGER, options.narrow)).length,
582
+ usage: { input: 0, output: 0 },
583
+ cost_usd: 0,
584
+ reason: `no ${setting.provider} key: store one with \`models keys set ${setting.provider}\` or set ${keyVariable(setting.provider)}; nothing was sent`,
585
+ reason_id: "enrichment.no-key"
586
+ };
587
+ const until = options.deadline ? options.deadline.endsAt - deadlineMargin(options.deadline) : Number.POSITIVE_INFINITY;
588
+ const timeUp = Number.isFinite(until) ? AbortSignal.timeout(Math.max(0, until - Date.now())) : void 0;
589
+ const signals = [options.signal, timeUp].filter((one) => one !== void 0);
590
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
591
+ const gateway = modelGateway({
592
+ resolve: /* @__PURE__ */ __name(() => target, "resolve"),
593
+ // The setting exists only with the owner's yes for this provider and endpoint; the endpoint is checked again.
594
+ consent: /* @__PURE__ */ __name((_request, chosen) => chosen.provider === setting.provider && chosen.baseUrl === baseUrl, "consent"),
595
+ key: /* @__PURE__ */ __name(() => apiKey, "key"),
596
+ env: options.env,
597
+ ...options.adapters ? { adapters: options.adapters } : {},
598
+ ...options.fetch ? { fetch: options.fetch } : {},
599
+ ...signal ? { signal } : {}
600
+ });
601
+ const queue = await enrichment.pending(maxRecords, options.narrow);
602
+ const batches = [];
603
+ for (let start = 0; start < queue.length; start += BATCH)
604
+ batches.push(queue.slice(start, start + BATCH));
605
+ const usage = { input: 0, output: 0 };
606
+ let enriched = 0;
607
+ let failed = 0;
608
+ let failedBatches = 0;
609
+ let reason;
610
+ let reasonId;
611
+ const ask = /* @__PURE__ */ __name(async (batch) => {
612
+ const answer = await gateway.complete({
613
+ purpose: "enrichment",
614
+ system: SYSTEM,
615
+ prompt: "Enrich each record of the data.",
616
+ data: recordsData(batch),
617
+ // The facts must keep names, amounts and dates exactly, which the default no-copy policy forbids.
618
+ allowSourceQuotes: true,
619
+ maxTokens: 8192,
620
+ ...setting.provider === "openai" && setting.base_url === void 0 ? { options: { response_format: { type: "json_object" }, temperature: 0 } } : {}
621
+ });
622
+ const rows = parseEnrichmentReply(answer.text);
623
+ const used = answer.usage ?? { input: answer.tokens, output: 0 };
624
+ usage.input += used.input;
625
+ usage.output += used.output;
626
+ const answered = batch.flatMap((record, i) => {
627
+ const text = rows.get(i);
628
+ return text === void 0 ? [] : [
629
+ {
630
+ type: record.type,
631
+ id: record.id,
632
+ hash: record.hash,
633
+ provider: setting.provider,
634
+ model: setting.model,
635
+ text,
636
+ tokens: Math.round(answer.tokens / batch.length)
637
+ }
638
+ ];
639
+ });
640
+ await enrichment.save(answered);
641
+ enriched += answered.length;
642
+ failed += batch.length - answered.length;
643
+ }, "ask");
644
+ let next = 0;
645
+ let slowest = 0;
646
+ const outOfTime = /* @__PURE__ */ __name(() => {
647
+ reason = REASON_TEXT["enrichment.deadline"];
648
+ reasonId = "enrichment.deadline";
649
+ }, "outOfTime");
650
+ const worker = /* @__PURE__ */ __name(async () => {
651
+ while (reason === void 0 && next < batches.length) {
652
+ if (Date.now() + Math.max(options.batchMs ?? ENRICH_BATCH_MS, slowest) + ANSWER_RESERVE_MS >= until) {
653
+ outOfTime();
654
+ break;
655
+ }
656
+ const batch = batches[next++];
657
+ const started = Date.now();
658
+ try {
659
+ await ask(batch);
660
+ slowest = Math.max(slowest, Date.now() - started);
661
+ } catch (error) {
662
+ if (timeUp?.aborted && !options.signal?.aborted) {
663
+ outOfTime();
664
+ break;
665
+ }
666
+ failed += batch.length;
667
+ const id = reasonIdOf(error);
668
+ if (id !== "enrichment.bad-replies" || ++failedBatches >= MAX_FAILED_BATCHES) {
669
+ reason = REASON_TEXT[id] ?? (error instanceof CliError ? error.message : "the enrichment provider failed");
670
+ reasonId = id;
671
+ }
672
+ }
673
+ }
674
+ }, "worker");
675
+ await Promise.all(Array.from({ length: Math.min(options.concurrency ?? CONCURRENCY, batches.length) }, () => worker()));
676
+ const left = (await enrichment.pending(Number.MAX_SAFE_INTEGER, options.narrow)).length;
677
+ const none = enriched === 0 && failed > 0;
678
+ if (none && reason === void 0) {
679
+ reason = `the provider enriched none of the ${failed} records sent; they are sent again next sync`;
680
+ reasonId = "enrichment.bad-replies";
681
+ }
682
+ return {
683
+ status: none ? "failed" : reason === void 0 ? "done" : "stopped",
684
+ provider: setting.provider,
685
+ model: setting.model,
686
+ enriched,
687
+ failed,
688
+ left,
689
+ usage,
690
+ cost_usd: costOf(usage, setting),
691
+ ...reason === void 0 ? {} : { reason },
692
+ ...reasonId === void 0 ? {} : { reason_id: reasonId }
693
+ };
694
+ }, "enrichRecords");
695
+ var MEASURED = {
696
+ reworded_at_10: { off: 0.62, on: 0.79 },
697
+ own_words_first: { off: 0.54, on: 0.48 },
698
+ source: "https://github.com/WireCatLabs/cli-testing/pull/322"
699
+ };
700
+ var enrichmentState = /* @__PURE__ */ __name(async (store, env, estimateFor, keys = {}) => {
701
+ const setting = readEnrichmentSetting(env);
702
+ const counts = await store.enrichment?.counts() ?? {
703
+ records: 0,
704
+ enriched: 0,
705
+ pendingChars: 0,
706
+ pendingByType: { document: 0, note: 0, email: 0 }
707
+ };
708
+ const pending = counts.records - counts.enriched;
709
+ const chosen = estimateFor ?? setting ?? DEFAULT_OFFER;
710
+ const endpoint2 = enrichmentEndpoint(chosen);
711
+ const found = keyLookup({ env, ...keys }, chosen);
712
+ const notes = counts.pendingByType.document + counts.pendingByType.note;
713
+ return {
714
+ on: setting !== void 0,
715
+ provider: setting?.provider ?? null,
716
+ model: setting?.model ?? null,
717
+ endpoint: setting ? enrichmentEndpoint(setting) : null,
718
+ consented_at: setting?.consented_at ?? null,
719
+ target: {
720
+ provider: chosen.provider,
721
+ model: chosen.model,
722
+ endpoint: endpoint2,
723
+ endpoint_host: new URL(endpoint2).host,
724
+ key: { present: found !== void 0, source: found?.source ?? null, env_var: keyVariable(chosen.provider) },
725
+ price_known: enrichmentPrice(chosen.provider, chosen.model, chosen.base_url) !== void 0
726
+ },
727
+ records: counts.records,
728
+ enriched: counts.enriched,
729
+ pending,
730
+ estimate: estimateEnrichment(pending, counts.pendingChars, chosen),
731
+ per_sync: ENRICH_PER_RUN,
732
+ syncs_needed: Math.ceil(Math.max(notes, counts.pendingByType.email) / ENRICH_PER_RUN),
733
+ sends_new_records: true,
734
+ offered: offeredModels(),
735
+ measured: MEASURED
736
+ };
737
+ }, "enrichmentState");
738
+
739
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/meaning-model.js
740
+ var meaningModel = /* @__PURE__ */ __name(async (store, env = process.env) => {
741
+ const chosen = chosenTextModel(env);
742
+ if (chosen.from === "chosen" || chosen.id !== DEFAULT_TEXT_MODEL)
743
+ return chosen.id;
744
+ const models = textModels(env);
745
+ const current = models.find(({ id }) => id === DEFAULT_TEXT_MODEL);
746
+ const previous = models.find(({ id }) => id === PREVIOUS_DEFAULT_TEXT_MODEL);
747
+ if (!current || !previous || !isTextModelInstalled(previous, textModelsDirectory(env)))
748
+ return chosen.id;
749
+ const [now, before] = [vectorModelKey(current), vectorModelKey(previous)];
750
+ const counts = await store.vectors.vectorCounts([now, before]);
751
+ return (counts.get(before) ?? 0) > (counts.get(now) ?? 0) ? previous.id : current.id;
752
+ }, "meaningModel");
753
+
754
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/notes-title-tier.js
755
+ var plainQueryWords = /* @__PURE__ */ __name((query) => {
756
+ let root;
757
+ try {
758
+ root = parseLucene(`(${query})`, { ...SEARCH_QUERY, defaultField: "text" }).root;
759
+ } catch {
760
+ return void 0;
761
+ }
762
+ const leaves = root.kind === "predicate" ? [root] : root.clauses.map(({ occur, node }) => occur === "must" ? node : null);
763
+ const values = [];
764
+ for (const leaf of leaves) {
765
+ if (leaf?.kind !== "predicate" || leaf.implicit !== true || leaf.operator !== "term" && leaf.operator !== "phrase")
766
+ return void 0;
767
+ values.push(leaf.value);
768
+ }
769
+ const words = normalize(values.join(" "));
770
+ return words === "" || /["\\]/u.test(words) ? void 0 : words;
771
+ }, "plainQueryWords");
772
+ var titleQuery = /* @__PURE__ */ __name((words) => words.split(" ").map((word) => `title:"${word}"`).join(" AND "), "titleQuery");
773
+ var titleTiers = /* @__PURE__ */ __name((hits, words) => {
774
+ const rank = /* @__PURE__ */ __name(({ note }) => {
775
+ const title = normalize(note.title ?? "");
776
+ return title === words ? 0 : title.includes(words) ? 1 : 2;
777
+ }, "rank");
778
+ return [...hits].sort((a, b) => rank(a) - rank(b));
779
+ }, "titleTiers");
780
+
781
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/pictures.js
782
+ import { createHash as createHash2 } from "node:crypto";
783
+ import { lstat, readFile } from "node:fs/promises";
784
+ import { setTimeout as sleep } from "node:timers/promises";
785
+
786
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/domain/models.js
787
+ var GROUP_SETTINGS = [
788
+ "allCanPin",
789
+ "onlyAdminsAdd",
790
+ "onlyAdminsCall",
791
+ "onlyOwnerEditsInfo",
792
+ "membersSeeLink"
793
+ ];
794
+ var FOLDER_KINDS = ["contacts", "non-contacts", "groups", "channels", "bots"];
795
+ var FOLDER_SKIPS = ["muted", "read", "archived"];
796
+ var ADMIN_RIGHTS = ["read", "members", "admins", "info", "pin", "link", "post", "edit", "delete"];
797
+ var senderIsMe = /* @__PURE__ */ __name((message, account) => message.outgoing === true || message.senderId !== null && String(message.senderId) === account, "senderIsMe");
798
+ var MEDIA_KINDS = ["photo", "video", "file", "audio", "link"];
799
+
800
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/file-download.js
801
+ import { createWriteStream, mkdirSync } from "node:fs";
802
+ import { link, rm } from "node:fs/promises";
803
+ import { join, resolve } from "node:path";
804
+ import { Readable, Transform } from "node:stream";
805
+ import { pipeline } from "node:stream/promises";
806
+
807
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/batch.js
808
+ var actionable = /* @__PURE__ */ __name((error) => {
809
+ if (isCliFailure(error))
810
+ return withRecovery({ code: error.code, message: error.message, ...error.details });
811
+ if (error && typeof error === "object" && "code" in error && "message" in error && typeof error.code === "string" && typeof error.message === "string")
812
+ return withRecovery(error);
813
+ return withRecovery({
814
+ code: "generic_failure",
815
+ message: "the operation failed; inspect diagnostic logs and retry or skip unfinished read items"
816
+ });
817
+ }, "actionable");
818
+ var batchProgress = /* @__PURE__ */ __name((env = process.env) => {
819
+ const threshold = Number(env.MESSAGING_BATCH_MAX_ERROR_PERCENT ?? 50);
820
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > 100)
821
+ throw new CliError("validation_error", "MESSAGING_BATCH_MAX_ERROR_PERCENT must be a whole percentage from 1 to 100");
822
+ let attempted = 0;
823
+ let succeeded = 0;
824
+ let stopReason;
825
+ const failures = [];
826
+ return {
827
+ ok: /* @__PURE__ */ __name(() => {
828
+ attempted += 1;
829
+ succeeded += 1;
830
+ }, "ok"),
831
+ fail: /* @__PURE__ */ __name((id, stage, error, attachment) => {
832
+ attempted += 1;
833
+ const detail = actionable(error);
834
+ failures.push({ id, stage, error: detail, ...attachment === void 0 ? {} : { attachment } });
835
+ if (detail.code === "rate_limited" || detail.status === 429)
836
+ stopReason = "rate_limited";
837
+ else if (detail.code === "authentication_error")
838
+ stopReason = "authentication";
839
+ else if (detail.code === "cancelled")
840
+ stopReason = "cancelled";
841
+ else if (!stopReason && attempted >= 10 && failures.length * 100 / attempted > threshold)
842
+ stopReason = "error_rate";
843
+ return detail;
844
+ }, "fail"),
845
+ absorb: /* @__PURE__ */ __name((other) => {
846
+ attempted += other.attempted;
847
+ succeeded += other.succeeded;
848
+ failures.push(...other.failures);
849
+ if (other.stopReason === "rate_limited" || !stopReason)
850
+ stopReason = other.stopReason;
851
+ if (!stopReason && attempted >= 10 && failures.length * 100 / attempted > threshold)
852
+ stopReason = "error_rate";
853
+ }, "absorb"),
854
+ get stopped() {
855
+ return stopReason !== void 0;
856
+ },
857
+ get failed() {
858
+ return failures.length;
859
+ },
860
+ result: /* @__PURE__ */ __name(() => ({
861
+ attempted,
862
+ succeeded,
863
+ failed: failures.length,
864
+ errorRate: attempted === 0 ? 0 : failures.length / attempted,
865
+ failures,
866
+ ...stopReason === void 0 ? {} : { stopReason },
867
+ maxErrorPercent: threshold
868
+ }), "result")
869
+ };
870
+ }, "batchProgress");
871
+ var mergeBatches = /* @__PURE__ */ __name((a, b) => {
872
+ if (!a)
873
+ return b;
874
+ if (!b)
875
+ return a;
876
+ const attempted = a.attempted + b.attempted;
877
+ const failed = a.failed + b.failed;
878
+ const stopReason = a.stopReason === "rate_limited" || b.stopReason === "rate_limited" ? "rate_limited" : a.stopReason ?? b.stopReason;
879
+ return {
880
+ attempted,
881
+ failed,
882
+ succeeded: a.succeeded + b.succeeded,
883
+ errorRate: attempted ? failed / attempted : 0,
884
+ failures: [...a.failures, ...b.failures],
885
+ maxErrorPercent: a.maxErrorPercent,
886
+ ...stopReason ? { stopReason } : {}
887
+ };
888
+ }, "mergeBatches");
889
+
890
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/file-download.js
891
+ var refreshedFiles = /* @__PURE__ */ __name((files) => files.flatMap(({ kind, name, position, providerRef }) => providerRef === void 0 || Object.keys(providerRef).length === 0 ? [] : [
892
+ {
893
+ kind,
894
+ providerRef,
895
+ ...name === void 0 ? {} : { name },
896
+ ...position === void 0 ? {} : { position }
897
+ }
898
+ ]), "refreshedFiles");
899
+ var recordPaths = /* @__PURE__ */ __name(async (messages, chat, message, files, saved, warn, onFailure) => {
900
+ const downloaded = saved.map((one, index) => ({
901
+ kind: one.kind,
902
+ path: one.path,
903
+ ...files[index]?.name === void 0 ? {} : { name: files[index]?.name },
904
+ ...files[index]?.position === void 0 ? {} : { position: files[index]?.position },
905
+ ...files[index]?.providerRef === void 0 ? {} : { providerRef: files[index]?.providerRef }
906
+ }));
907
+ try {
908
+ const kept = await messages.keepDownloaded(chat, message, downloaded);
909
+ if (kept < downloaded.length && downloaded.some(({ providerRef }) => Object.keys(providerRef ?? {}).length > 0))
910
+ warn(`message ${message}: a new file reference from the messenger was not saved; the next download asks again`);
911
+ return kept;
912
+ } catch (error) {
913
+ onFailure?.(error);
914
+ warn(`not recorded in the local store where message ${message}'s files went: ${error.message}`);
915
+ return 0;
916
+ }
917
+ }, "recordPaths");
918
+ var downloadMessage = /* @__PURE__ */ __name(async (messages, chat, message, output, warn) => {
919
+ const { files } = await messages.download(chat, message);
920
+ mkdirSync(output, { recursive: true });
921
+ const result = await saveFiles(messages, chat, message, files, output, { unique: true, warn });
922
+ if (result.batch.failed > 0)
923
+ throw new CliError("provider_error", "some attachments failed; completed downloads are retained", {
924
+ batch: result.batch,
925
+ saved: result.saved
926
+ });
927
+ return result.saved;
928
+ }, "downloadMessage");
929
+ var saveFiles = /* @__PURE__ */ __name(async (messages, chat, message, files, output, { unique = false, warn, onSaved, batch = batchProgress() }) => {
930
+ const saved = [];
931
+ const successful = [];
932
+ for (const [index, file] of files.entries()) {
933
+ if (batch.stopped)
934
+ break;
935
+ try {
936
+ const one = await save(file, output, `${message}-${index + 1}`, { unique });
937
+ saved.push(one);
938
+ successful.push(file);
939
+ batch.ok();
940
+ onSaved?.(one);
941
+ } catch (error) {
942
+ const issue = batch.fail(message, "download", error, (file.position ?? index) + 1);
943
+ warn(`message ${message}, attachment ${(file.position ?? index) + 1}: ${issue.code} \u2014 ${issue.message}`);
944
+ }
945
+ }
946
+ await recordPaths(messages, chat, message, successful, saved, warn, (error) => batch.fail(message, "record_downloads", error));
947
+ return { saved, batch: batch.result() };
948
+ }, "saveFiles");
949
+ var EXTENSIONS = {
950
+ "image/jpeg": "jpg",
951
+ "image/png": "png",
952
+ "image/webp": "webp",
953
+ "image/gif": "gif",
954
+ "video/mp4": "mp4",
955
+ "video/webm": "webm",
956
+ "audio/mpeg": "mp3",
957
+ "audio/ogg": "ogg",
958
+ "audio/mp4": "m4a",
959
+ "application/pdf": "pdf"
960
+ };
961
+ var BY_KIND = { photo: "jpg" };
962
+ var save = /* @__PURE__ */ __name(async (file, directory, fallbackName, { unique = false } = {}) => {
963
+ const own = safeName(file.name);
964
+ const fileName = /* @__PURE__ */ __name(() => {
965
+ const extension = EXTENSIONS[file.mime ?? ""] ?? BY_KIND[file.kind];
966
+ return own ?? (extension ? `${fallbackName}.${extension}` : fallbackName);
967
+ }, "fileName");
968
+ const partial = join(directory, `.${fileName()}.${process.pid}.part`);
969
+ let bytes = 0;
970
+ const counting = new Transform({
971
+ transform(chunk, _encoding, done) {
972
+ bytes += chunk.length;
973
+ done(null, chunk);
974
+ }
975
+ });
976
+ try {
977
+ await pipeline(Readable.from(file.bytes()), counting, createWriteStream(partial, { flags: "wx", mode: 384 }));
978
+ const name = fileName();
979
+ const names = unique && own ? [name, `${fallbackName}-${own}`] : [name];
980
+ for (const candidate of names) {
981
+ const path2 = resolve(join(directory, candidate));
982
+ const taken = await link(partial, path2).then(() => false, (error) => {
983
+ if (error.code === "EEXIST")
984
+ return true;
985
+ throw error;
986
+ });
987
+ if (!taken)
988
+ return { kind: file.kind, path: path2, bytes };
989
+ }
990
+ const path = resolve(join(directory, names.at(-1) ?? name));
991
+ if (unique)
992
+ return { kind: file.kind, path, bytes, existing: true };
993
+ throw new CliError("validation_error", `${path} already exists \u2014 nothing was overwritten; choose --output-dir`);
994
+ } finally {
995
+ await rm(partial, { force: true });
996
+ }
997
+ }, "save");
998
+
999
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/deps.js
1000
+ var accountStore = /* @__PURE__ */ __name(async (deps) => (await deps.store()).forAccount(await deps.account()), "accountStore");
1001
+ var crossAccount = /* @__PURE__ */ __name((deps, _reason) => deps.store(), "crossAccount");
1002
+ var NO_LOCAL_STORE = "this answer comes from the messenger, not from the local store";
1003
+ var SQLITE_BUSY = 5;
1004
+ var storeAbsent = /* @__PURE__ */ __name((error) => {
1005
+ if (isCliFailure(error))
1006
+ return error.code === "validation_error" && error.message === NO_LOCAL_STORE;
1007
+ return error instanceof Error && sqliteCode(error) === SQLITE_BUSY;
1008
+ }, "storeAbsent");
1009
+ var accountUnknown = /* @__PURE__ */ __name((error) => isCliFailure(error) && (error.code === "not_found" || error.code === "authentication_error"), "accountUnknown");
1010
+ var unless = /* @__PURE__ */ __name(async (work, expected) => {
1011
+ try {
1012
+ return await work();
1013
+ } catch (error) {
1014
+ if (expected(error))
1015
+ return void 0;
1016
+ throw error;
1017
+ }
1018
+ }, "unless");
1019
+ var unlessBusy = /* @__PURE__ */ __name((work) => unless(work, storeAbsent), "unlessBusy");
1020
+ var accountStoreIfOpen = /* @__PURE__ */ __name(async (deps) => {
1021
+ const held = await storeIfOpen(deps);
1022
+ return held?.store.forAccount(held.account);
1023
+ }, "accountStoreIfOpen");
1024
+ var storeIfOpen = /* @__PURE__ */ __name(async (deps) => {
1025
+ const store = await unless(() => deps.store(), storeAbsent);
1026
+ const account = store && await unless(() => deps.account(), accountUnknown);
1027
+ return store && account ? { store, account } : void 0;
1028
+ }, "storeIfOpen");
1029
+ var fromStore = /* @__PURE__ */ __name((deps) => deps.offline || deps.reads === "store", "fromStore");
1030
+ var nothingStored = /* @__PURE__ */ __name((messenger) => `nothing stored for this chat yet \u2014 keep \`${typedCommand(messenger.app.command, "serve")}\` running`, "nothingStored");
1031
+ var OFFLINE = "--offline answers only from what is kept locally: `chats list|show`, `messages list|show|context|download`, `contacts list|show` and `review`";
1032
+ var onlineDeps = /* @__PURE__ */ __name((messenger, adapter, guard, where = {}) => ({
1033
+ messenger,
1034
+ ...where,
1035
+ offline: false,
1036
+ guard,
1037
+ connection: /* @__PURE__ */ __name(async () => adapter, "connection"),
1038
+ account: /* @__PURE__ */ __name(async () => {
1039
+ const self = adapter.self();
1040
+ if (self === null)
1041
+ throw new CliError("authentication_error", "the connection does not know whose account it is");
1042
+ return { provider: messenger.provider, account: self };
1043
+ }, "account"),
1044
+ store: /* @__PURE__ */ __name(async () => {
1045
+ throw new CliError("validation_error", NO_LOCAL_STORE);
1046
+ }, "store")
1047
+ }), "onlineDeps");
1048
+ var storedDeps = /* @__PURE__ */ __name((messenger, store, account, guard) => ({
1049
+ messenger,
1050
+ offline: true,
1051
+ reads: messenger.history ?? "server",
1052
+ guard,
1053
+ account: /* @__PURE__ */ __name(async () => account, "account"),
1054
+ store: /* @__PURE__ */ __name(async () => store, "store"),
1055
+ connection: /* @__PURE__ */ __name(async () => {
1056
+ throw new CliError("validation_error", OFFLINE);
1057
+ }, "connection")
1058
+ }), "storedDeps");
1059
+ var storeModeDeps = /* @__PURE__ */ __name((messenger, store, account, guard) => ({ ...storedDeps(messenger, store, account, guard), offline: false, reads: "store" }), "storeModeDeps");
1060
+ var NOT_A_MESSENGER = "this program keeps its sources in the store and has no messenger to connect to";
1061
+ var storeOnlyDeps = /* @__PURE__ */ __name((store, account, { app, env }) => {
1062
+ const refuse = /* @__PURE__ */ __name(() => {
1063
+ throw new CliError("validation_error", NOT_A_MESSENGER);
1064
+ }, "refuse");
1065
+ const messenger = {
1066
+ app,
1067
+ provider: account.provider
1068
+ };
1069
+ const guard = { check: refuse, record: /* @__PURE__ */ __name(() => {
1070
+ }, "record") };
1071
+ return { ...storedDeps(messenger, store, account, guard), ...env === void 0 ? {} : { env } };
1072
+ }, "storeOnlyDeps");
1073
+
1074
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/search-kind.js
1075
+ var NO_MAIL = "no_mail";
1076
+ var MAIL = "email";
1077
+ var groupLockOf = /* @__PURE__ */ __name((app, env) => {
1078
+ const lock = app === void 0 || env === void 0 ? void 0 : env[envName(app, "GROUP_LOCK")]?.trim();
1079
+ return lock && lock.toLowerCase() !== ALL ? lock : void 0;
1080
+ }, "groupLockOf");
1081
+ var listContextOf = /* @__PURE__ */ __name(async (store, account, app, stored, env) => {
1082
+ const all = stored ?? await store.accounts.storedAccounts();
1083
+ const held = all.some((one) => one.provider === account.provider && one.account === account.account) ? all : [...all, { id: 0, ...account, name: null, scope: "personal" }];
1084
+ const context = {
1085
+ held,
1086
+ groups: await store.accounts.accountGroups(),
1087
+ profiles: await store.accounts.profiles(),
1088
+ running: { provider: account.provider, ...app ? { command: app.command } : {} }
1089
+ };
1090
+ const membership = groupMembership(context);
1091
+ const groups = groupEntries(context.groups);
1092
+ const lock = groupLockOf(app, env);
1093
+ if (lock === void 0)
1094
+ return { ...context, groups, membership };
1095
+ const members = hasGroup(membership.groups, lock) ? membership.groups[lock] : void 0;
1096
+ if (!members)
1097
+ throw new CliError("permission_error", `this process is locked to group ${lock} (${envName(app, "GROUP_LOCK")}), which does not exist`);
1098
+ const only = new Set([...members, OWNER_NOTES].map(keyOf));
1099
+ const listedAs = /* @__PURE__ */ __name((one) => isFolderProvider(one.provider) || isDocumentAccountProvider(one.provider) ? { provider: "notes", account: String(one.id) } : one, "listedAs");
1100
+ return {
1101
+ ...context,
1102
+ held: held.filter((one) => only.has(keyOf(listedAs(one)))),
1103
+ groups: { [lock]: groups[lock] ?? [] },
1104
+ membership: {
1105
+ groups: { [lock]: members },
1106
+ duplicates: membership.duplicates.filter(({ groups: names }) => names.includes(lock)),
1107
+ suggested: membership.suggested.filter(({ group }) => group === lock),
1108
+ unresolved: membership.unresolved
1109
+ },
1110
+ only
1111
+ };
1112
+ }, "listContextOf");
1113
+ var listedAccounts = /* @__PURE__ */ __name(async (store, account, source, app, kind, env) => {
1114
+ const lock = groupLockOf(app, env);
1115
+ if (source === void 0 && lock === void 0)
1116
+ return void 0;
1117
+ const stored = await store.accounts.storedAccounts();
1118
+ const registered = source !== void 0 && (isKind(source) || providerNamed(source) !== void 0 && !stored.some(({ provider }) => provider === source));
1119
+ if (lock === void 0 && source !== void 0 && !isAccountList(source) && !registered)
1120
+ return void 0;
1121
+ const entries = entriesOfList(source ?? `group:${lock}`, await listContextOf(store, account, app, stored, env));
1122
+ return fitting(entries, kind ? [kind] : ["messages", "mail"], `${app ? `${app.command} ` : ""}search ${kind ?? "messages"}`);
1123
+ }, "listedAccounts");
1124
+ var accountsOfKind = /* @__PURE__ */ __name((kind, chosen, held, explicit, command = void 0, mailAccount, listed = false) => {
1125
+ if (mailAccount !== void 0 && kind !== "mail")
1126
+ throw new CliError("validation_error", "--account names a mail account \u2014 memo search mail reads it");
1127
+ if (kind === void 0)
1128
+ return chosen;
1129
+ if (kind === "messages") {
1130
+ if (explicit === MAIL)
1131
+ throw new CliError("validation_error", "mail is searched with `memo search mail`, not search messages");
1132
+ return chosen.filter(({ provider }) => holdsKindOf(provider, "messages"));
1133
+ }
1134
+ if (explicit !== void 0 && explicit !== MAIL && explicit !== "all")
1135
+ throw new CliError("validation_error", `search mail reads mail only \u2014 \`${command === void 0 ? "" : `${command} `}search messages\` searches ${explicit}`);
1136
+ const mail = (listed ? chosen : held).filter(({ provider }) => holdsKindOf(provider, "mail"));
1137
+ if (mail.length === 0)
1138
+ throw new CliError("not_found", "no mail in the store yet \u2014 `memo sync --only mail --since-time <time>` imports it", {
1139
+ reason: NO_MAIL
1140
+ });
1141
+ const address = mailAccount?.trim().toLowerCase();
1142
+ const chosenMail = address === void 0 ? mail : mail.filter(({ account }) => account === address);
1143
+ if (chosenMail.length === 0)
1144
+ throw new CliError("not_found", `no mail account ${mailAccount} in the store \u2014 it holds ${mail.map(({ account }) => account).join(", ")}`);
1145
+ return chosenMail.map(({ provider, account }) => ({ provider, account }));
1146
+ }, "accountsOfKind");
1147
+
1148
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/message-resolution.js
1149
+ var readChatId = /* @__PURE__ */ __name(async (deps, reference, store, account) => {
1150
+ if (deps.reads !== "store")
1151
+ return keptChatId(deps.messenger, reference, store, account);
1152
+ const chatId = await keptChatId(deps.messenger, reference, store, account).catch((error) => {
1153
+ if (codeOf(error) === "not_found")
1154
+ throw new CliError("not_found", nothingStored(deps.messenger));
1155
+ throw error;
1156
+ });
1157
+ if (await store.messages.countMessages(account, chatId) === 0) {
1158
+ const all = (await store.chats.chats(account, { includeLeft: true })).items;
1159
+ const left = all.some((one) => one.id === chatId && one.membershipState === "left");
1160
+ throw new CliError("not_found", left ? LEFT_EMPTY : nothingStored(deps.messenger), { chat: chatId });
1161
+ }
1162
+ return chatId;
1163
+ }, "readChatId");
1164
+ var LEFT_EMPTY = "you left this chat, and the store holds none of its messages";
1165
+ var storedChatId = /* @__PURE__ */ __name((messenger, reference, store, account, { includeLeft = false } = {}) => {
1166
+ const renamed = /* @__PURE__ */ __name((id) => store.chats.renamedChatId(account, id), "renamed");
1167
+ const profilesOn2 = profilesOnAccount(store, messenger.app?.command, account.provider);
1168
+ const among = chatIdAmong(messenger, reference, account, {
1169
+ held: /* @__PURE__ */ __name(() => store.chats.chats(account, {}), "held"),
1170
+ renamed,
1171
+ left: /* @__PURE__ */ __name(async (id) => leftIn(await store.chats.chats(account, byId(id))), "left"),
1172
+ profilesOn: profilesOn2
1173
+ });
1174
+ if (!includeLeft)
1175
+ return among;
1176
+ return among.catch((error) => {
1177
+ if (codeOf(error) !== "not_found")
1178
+ throw error;
1179
+ return chatIdAmong(messenger, reference, account, {
1180
+ held: /* @__PURE__ */ __name(() => store.chats.chats(account, { includeLeft: true }), "held"),
1181
+ renamed,
1182
+ profilesOn: profilesOn2
1183
+ });
1184
+ });
1185
+ }, "storedChatId");
1186
+ var keptChatId = /* @__PURE__ */ __name((messenger, reference, store, account) => storedChatId(messenger, reference, store, account, { includeLeft: true }), "keptChatId");
1187
+ var chatIdIn = /* @__PURE__ */ __name((messenger, reference, store, { includeLeft = false } = {}) => {
1188
+ const renamed = /* @__PURE__ */ __name((id) => store.chats.renamedChatId(id), "renamed");
1189
+ const among = chatIdAmong(messenger, reference, store.account, {
1190
+ held: /* @__PURE__ */ __name(() => store.chats.chats({}), "held"),
1191
+ renamed,
1192
+ left: /* @__PURE__ */ __name(async (id) => leftIn(await store.chats.chats(byId(id))), "left")
1193
+ });
1194
+ if (!includeLeft)
1195
+ return among;
1196
+ return among.catch((error) => {
1197
+ if (codeOf(error) !== "not_found")
1198
+ throw error;
1199
+ return chatIdAmong(messenger, reference, store.account, {
1200
+ held: /* @__PURE__ */ __name(() => store.chats.chats({ includeLeft: true }), "held"),
1201
+ renamed
1202
+ });
1203
+ });
1204
+ }, "chatIdIn");
1205
+ var byId = /* @__PURE__ */ __name((id) => ({
1206
+ includeLeft: true,
1207
+ limit: 1,
1208
+ where: { sql: "chats.external_id = ?", params: [id] }
1209
+ }), "byId");
1210
+ var leftIn = /* @__PURE__ */ __name(({ items }) => items.some((one) => one.membershipState === "left"), "leftIn");
1211
+ var profilesOnAccount = /* @__PURE__ */ __name((store, app, provider) => async (account) => {
1212
+ if (app === void 0)
1213
+ return void 0;
1214
+ return profilesOn(await store.accounts.profiles(), app, { provider, account });
1215
+ }, "profilesOnAccount");
1216
+ var chatIdAmong = /* @__PURE__ */ __name(async (messenger, reference, account, { held, renamed, left, profilesOn: profilesOn2 }) => {
1217
+ const trimmed = reference.trim();
1218
+ if (messenger.savedChatId && ["me", "self", "saved"].includes(trimmed.toLowerCase())) {
1219
+ return messenger.savedChatId(account);
1220
+ }
1221
+ const named = chatReferenceOf(trimmed, account.provider);
1222
+ if (named)
1223
+ await ensureAccount(named, { account: account.account }, profilesOn2);
1224
+ if (named || /^-?\d+$/.test(trimmed)) {
1225
+ const typed = named?.chat ?? trimmed;
1226
+ const id = await renamed(typed) ?? typed;
1227
+ if (await left?.(id))
1228
+ throw new CliError("not_found", `you left chat ${id}`);
1229
+ return id;
1230
+ }
1231
+ const chats = (await held()).items;
1232
+ const exact = chats.find((one) => one.id === trimmed);
1233
+ if (exact)
1234
+ return exact.id;
1235
+ const moved = await renamed(trimmed);
1236
+ if (moved !== void 0 && chats.some((one) => one.id === moved))
1237
+ return moved;
1238
+ if (trimmed.startsWith("@")) {
1239
+ const username = trimmed.slice(1).toLowerCase();
1240
+ const found = chats.find((one) => String(one.providerMetadata?.username ?? "").toLowerCase() === username);
1241
+ if (!found)
1242
+ throw new CliError("not_found", `no stored chat is ${trimmed}`);
1243
+ return found.id;
1244
+ }
1245
+ return pickChat(trimmed, chats).id;
1246
+ }, "chatIdAmong");
1247
+ var ambiguousAcross = /* @__PURE__ */ __name((reference, what, candidates) => {
1248
+ const width = Math.max(...candidates.map(({ provider, id }) => `${provider} ${id}`.length));
1249
+ const lines = candidates.map(({ provider, id, label }) => ` ${`${provider} ${id}`.padEnd(width)} ${label}`);
1250
+ return new CliError("validation_error", `"${singleLine(reference)}" matches ${candidates.length} ${what} in different accounts \u2014 name one by its id, or narrow the search with in:<messenger>:
1251
+ ${lines.join("\n")}`, { candidates: candidates.map(({ provider, id }) => ({ provider, id })) });
1252
+ }, "ambiguousAcross");
1253
+ var missing = /* @__PURE__ */ __name((error) => {
1254
+ if (codeOf(error) === "not_found")
1255
+ return void 0;
1256
+ throw error;
1257
+ }, "missing");
1258
+ var chatAmong = /* @__PURE__ */ __name(async (messenger, store, accounts, reference) => {
1259
+ const [only] = accounts;
1260
+ if (accounts.length === 1 && only)
1261
+ return { account: only, chatId: await storedChatId(messenger, reference, store, only, { includeLeft: true }) };
1262
+ const among = /* @__PURE__ */ __name(async (includeLeft) => (await Promise.all(accounts.map(async (account) => {
1263
+ const held = (await store.chats.chats(account, includeLeft ? { includeLeft } : {})).items;
1264
+ const chatId = await storedChatId(messenger, reference, store, account, { includeLeft }).catch(missing);
1265
+ const chat = held.find((one2) => one2.id === chatId);
1266
+ return chat ? [{ account, chat }] : [];
1267
+ }))).flat(), "among");
1268
+ const current = await among(false);
1269
+ const found = current.length > 0 ? current : await among(true);
1270
+ const [one] = found;
1271
+ if (found.length === 1 && one)
1272
+ return { account: one.account, chatId: one.chat.id };
1273
+ if (found.length === 0)
1274
+ throw new CliError("not_found", `no stored chat matches "${singleLine(reference)}"`);
1275
+ throw ambiguousAcross(reference, "chats", found.map(({ account, chat }) => ({
1276
+ provider: account.provider,
1277
+ id: chat.id,
1278
+ label: singleLine(chat.title ?? "")
1279
+ })));
1280
+ }, "chatAmong");
1281
+ var senderAmong = /* @__PURE__ */ __name(async (store, accounts, reference, field = "from") => {
1282
+ const providers = [...new Set(accounts.map(({ provider }) => provider))];
1283
+ const [only] = accounts;
1284
+ try {
1285
+ if (accounts.length === 1 && only) {
1286
+ const person = pickPerson(reference, await store.people.people(only.provider, { account: only.account }));
1287
+ return { provider: only.provider, id: person.id };
1288
+ }
1289
+ const found = (await Promise.all(providers.map(async (provider) => {
1290
+ const ids = accounts.filter((one2) => one2.provider === provider).map(({ account }) => account);
1291
+ const person = await store.people.people(provider, { accounts: ids }).then((people) => pickPerson(reference, people)).catch(missing);
1292
+ return person ? [{ provider, person }] : [];
1293
+ }))).flat();
1294
+ const [one] = found;
1295
+ if (found.length === 1 && one)
1296
+ return { provider: one.provider, id: one.person.id };
1297
+ if (found.length === 0) {
1298
+ throw new CliError("not_found", isId(reference) ? `no person ${reference} in what these accounts have seen` : `nobody matches "${reference}"`);
1299
+ }
1300
+ throw ambiguousAcross(reference, "people", found.map(({ provider, person }) => ({ provider, id: person.id, label: singleLine(person.name ?? "") })));
1301
+ } catch (error) {
1302
+ if (error instanceof CliError && error.code === "not_found") {
1303
+ throw new CliError("not_found", `${field}:${reference} \u2014 ${error.message}; a part of the name: ${field}:*${reference}*`, {
1304
+ reason: "query.no-match"
1305
+ });
1306
+ }
1307
+ throw error;
1308
+ }
1309
+ }, "senderAmong");
1310
+ var MOST_NAME_MATCHES = 50;
1311
+ var patternRefused = /* @__PURE__ */ __name((field, pattern, what, found, near) => {
1312
+ if (found === 0) {
1313
+ const inside = `*${pattern.replace(/^\*+|\*+$/gu, "")}*`;
1314
+ const [closest] = near;
1315
+ throw new CliError("not_found", `${field}:${pattern} \u2014 no ${what} fits${near.length ? `; near: ${near.map(({ label }) => label).join(", ")}` : ""} \u2014 a pattern matches the whole name: ${pattern === inside ? "" : `write ${field}:${inside} for a part of it, or `}the name: ${field}:${JSON.stringify(closest?.label ?? pattern.replace(/[*?]/gu, ""))}`, { reason: "query.no-match", candidates: near.map(({ candidate }) => candidate) });
1316
+ }
1317
+ throw new CliError("validation_error", `${field}:${pattern} fits ${found} ${what}, more than ${MOST_NAME_MATCHES} \u2014 write more of the name`, { reason: "query.too-large", budget: "name matches", limit: MOST_NAME_MATCHES, complete: false });
1318
+ }, "patternRefused");
1319
+ var sendersMatching = /* @__PURE__ */ __name(async (store, accounts, field, pattern) => {
1320
+ const providers = [...new Set(accounts.map(({ provider }) => provider))];
1321
+ const seen = await Promise.all(providers.map(async (provider) => {
1322
+ const ids = accounts.filter((one) => one.provider === provider).map(({ account }) => account);
1323
+ const scope = ids.length === 1 ? { account: ids[0] } : { accounts: ids };
1324
+ return { provider, people: (await store.people.people(provider, scope)).all() };
1325
+ }));
1326
+ const found = seen.flatMap(({ provider, people }) => peopleMatching(pattern, people, { byAddress: provider === MAIL }).map(({ id }) => ({ provider, id })));
1327
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
1328
+ const people = seen.flatMap(({ people: people2 }) => people2);
1329
+ const near = nearest(pattern, people, ({ name, alias }) => [name, alias].filter(isText));
1330
+ patternRefused(field, pattern, "person", found.length, near.map(({ id, name, username }) => ({ id, label: name ?? id, candidate: { id, name, username } })));
1331
+ }
1332
+ return found;
1333
+ }, "sendersMatching");
1334
+ var chatsMatchingIn = /* @__PURE__ */ __name(async (store, accounts, pattern) => {
1335
+ const held = await Promise.all(accounts.map(async (account) => ({
1336
+ account,
1337
+ chats: (await store.chats.chats(account, { includeLeft: true })).items
1338
+ })));
1339
+ const found = held.flatMap(({ account, chats }) => chatsMatching(pattern, chats).map((chat) => ({ account, chatId: chat.id })));
1340
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
1341
+ const chats = held.flatMap(({ chats: chats2 }) => chats2);
1342
+ const near = nearest(pattern, chats, ({ title }) => [title].filter(isText));
1343
+ patternRefused("chat", pattern, "chat", found.length, near.map(({ id, title }) => ({ id, label: title ?? id, candidate: { id, title } })));
1344
+ }
1345
+ return found;
1346
+ }, "chatsMatchingIn");
1347
+ var isText = /* @__PURE__ */ __name((value) => typeof value === "string" && value !== "", "isText");
1348
+
1349
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/pictures.js
1350
+ var PICTURE_MAX_BYTES = 25 * 1024 * 1024;
1351
+ var PICTURE_FLOOR = 0.25;
1352
+ var PAGE = 50;
1353
+ var SAVE_EVERY = 8;
1354
+ var PICTURES_OFF = "picture search is off for this profile \u2014 set pictureSearch to true in its config to turn it on";
1355
+ var missingModel = /* @__PURE__ */ __name((id) => `the picture model is not downloaded \u2014 \`images models download ${id}\` fetches it`, "missingModel");
1356
+ var plainWords = /* @__PURE__ */ __name((query) => query.replace(/\b(?:text|content|transcript|filename):("[^"]*"|\S+)/gi, "$1").replace(/\b[a-z_]+:("[^"]*"|\[[^\]]*\]|\{[^}]*\}|\([^)]*\)|\S+)/gi, " ").replace(/\b(?:AND|OR|NOT)\b/g, " ").replace(/[()"+\-~^*?\\[\]{}!|&]/g, " ").replace(/\s+/g, " ").trim(), "plainWords");
1357
+ var pictureBytes = /* @__PURE__ */ __name(async (picture, files, read) => {
1358
+ if (picture.localPath) {
1359
+ try {
1360
+ const found = await lstat(picture.localPath);
1361
+ if (found.isFile() && found.size <= PICTURE_MAX_BYTES)
1362
+ return await readFile(picture.localPath);
1363
+ } catch {
1364
+ }
1365
+ }
1366
+ const images = (await files()).filter(({ kind, mime }) => kind === "photo" || mime?.startsWith("image/"));
1367
+ const file = images.find(({ position }) => position === picture.position) ?? (images.every(({ position }) => position === void 0) ? images[0] : void 0);
1368
+ if (!file || file.size !== void 0 && file.size > PICTURE_MAX_BYTES)
1369
+ return void 0;
1370
+ const parts = [];
1371
+ let total = 0;
1372
+ for await (const part of file.bytes()) {
1373
+ total += part.length;
1374
+ if (total > PICTURE_MAX_BYTES)
1375
+ return void 0;
1376
+ parts.push(part);
1377
+ }
1378
+ await read(file);
1379
+ return Buffer.concat(parts);
1380
+ }, "pictureBytes");
1381
+ var picturesService = /* @__PURE__ */ __name((deps) => {
1382
+ let opened;
1383
+ const open = /* @__PURE__ */ __name(async () => {
1384
+ if (deps.pictureEmbedder)
1385
+ return deps.pictureEmbedder();
1386
+ const model2 = imageModel(DEFAULT_IMAGE_MODEL);
1387
+ const directory = imageModelsDirectory(deps.env);
1388
+ if (!isImageModelInstalled(model2, directory))
1389
+ throw new CliError("not_found", missingModel(model2.id), { reason: "model.not-downloaded", model: model2.id });
1390
+ const { openPictureEmbedder } = await import("./embedder-LUTDO3HS.js");
1391
+ return openPictureEmbedder(model2, directory);
1392
+ }, "open");
1393
+ const embedder = /* @__PURE__ */ __name(() => {
1394
+ opened ??= open().catch((error) => {
1395
+ opened = void 0;
1396
+ throw error;
1397
+ });
1398
+ return opened;
1399
+ }, "embedder");
1400
+ const model = imageModel(DEFAULT_IMAGE_MODEL);
1401
+ return {
1402
+ /**
1403
+ * Gives the images no vector yet one, reading each through the messenger's own download and keeping nothing
1404
+ * of the file: only the vector and the hash of its bytes. One at a time, with a pause, and nothing is marked
1405
+ * read. Run again, it goes on where the last run stopped: an image with a vector is not read twice.
1406
+ */
1407
+ embed: /* @__PURE__ */ __name(async ({ chat, limit, pauseMs = 250, signal }) => {
1408
+ if (!deps.pictures)
1409
+ throw new CliError("validation_error", PICTURES_OFF);
1410
+ const store = await deps.store();
1411
+ const account = await deps.account();
1412
+ const chatId = chat === void 0 ? void 0 : await storedChatId(deps.messenger, chat, store, account, { includeLeft: true });
1413
+ const use = await embedder();
1414
+ const result = { model: model.key, embedded: 0, skipped: 0, failed: 0, more: false };
1415
+ const pending = [];
1416
+ const flush = /* @__PURE__ */ __name(async () => {
1417
+ if (pending.length === 0)
1418
+ return;
1419
+ await store.vectors.savePictures(account, model.key, model.dims, pending.splice(0));
1420
+ }, "flush");
1421
+ let after = 0;
1422
+ let seen = 0;
1423
+ try {
1424
+ while (seen < limit) {
1425
+ const page = await store.vectors.picturesToEmbed(account, {
1426
+ ...chatId === void 0 ? {} : { chatId },
1427
+ after,
1428
+ limit: Math.min(PAGE, limit - seen)
1429
+ });
1430
+ if (page.length === 0)
1431
+ break;
1432
+ let downloaded;
1433
+ for (const picture of page) {
1434
+ if (signal?.aborted)
1435
+ throw new CliError("cancelled", "picture embedding cancelled");
1436
+ after = picture.attachmentPk;
1437
+ seen += 1;
1438
+ const files = /* @__PURE__ */ __name(() => {
1439
+ if (downloaded?.message !== `${picture.chatId}/${picture.messageId}`) {
1440
+ downloaded = {
1441
+ message: `${picture.chatId}/${picture.messageId}`,
1442
+ files: (async () => {
1443
+ const download = capability(await deps.connection(), "download", "download attachments");
1444
+ return (await download(picture.chatId, picture.messageId)).files;
1445
+ })()
1446
+ };
1447
+ }
1448
+ return downloaded.files;
1449
+ }, "files");
1450
+ try {
1451
+ const bytes = await pictureBytes(picture, files, async (file) => {
1452
+ const refreshed = refreshedFiles([file]);
1453
+ if (refreshed.length === 0)
1454
+ return;
1455
+ await store.attachments.keepProviderRefs(account, picture.chatId, picture.messageId, refreshed).catch(() => void 0);
1456
+ });
1457
+ if (!bytes) {
1458
+ result.skipped += 1;
1459
+ continue;
1460
+ }
1461
+ const vector = await use.embedImage(bytes);
1462
+ pending.push({
1463
+ attachmentPk: picture.attachmentPk,
1464
+ hash: createHash2("sha256").update(bytes).digest("hex"),
1465
+ bytes: bytes.length,
1466
+ occurredAt: picture.sentAt,
1467
+ vector
1468
+ });
1469
+ result.embedded += 1;
1470
+ if (pending.length >= SAVE_EVERY)
1471
+ await flush();
1472
+ } catch (error) {
1473
+ if (error instanceof CliError && error.code === "cancelled")
1474
+ throw error;
1475
+ result.failed += 1;
1476
+ }
1477
+ if (pauseMs > 0)
1478
+ await sleep(pauseMs, void 0, signal ? { signal } : {}).catch(() => {
1479
+ });
1480
+ }
1481
+ }
1482
+ result.more = seen >= limit && (await store.vectors.picturesToEmbed(account, {
1483
+ after,
1484
+ limit: 1,
1485
+ ...chatId === void 0 ? {} : { chatId }
1486
+ })).length > 0;
1487
+ } finally {
1488
+ await flush();
1489
+ await use.close();
1490
+ opened = void 0;
1491
+ }
1492
+ return result;
1493
+ }, "embed"),
1494
+ /** The pictures nearest to what the words describe, as their messages; the lane beside the text hits. */
1495
+ lane: /* @__PURE__ */ __name(async (query, { chat, since, limit = 5 } = {}) => {
1496
+ if (!deps.pictures)
1497
+ return {};
1498
+ const words = plainWords(query);
1499
+ if (words === "")
1500
+ return {};
1501
+ const store = await deps.store();
1502
+ const account = await deps.account();
1503
+ const chatId = chat === void 0 ? void 0 : await storedChatId(deps.messenger, chat, store, account, { includeLeft: true });
1504
+ let vector;
1505
+ try {
1506
+ const use = await embedder();
1507
+ vector = await use.embedQuery(words);
1508
+ } catch (error) {
1509
+ if (error instanceof CliError && error.code === "not_found")
1510
+ return { picturesSkipped: error.message, picturesModel: model.id };
1511
+ throw error;
1512
+ } finally {
1513
+ const held = opened;
1514
+ opened = void 0;
1515
+ await held?.then((use) => use.close()).catch(() => {
1516
+ });
1517
+ }
1518
+ const near = await store.vectors.nearestPictures(account, {
1519
+ ...chatId === void 0 ? {} : { chatId },
1520
+ ...since === void 0 ? {} : { since },
1521
+ model: model.key,
1522
+ limit,
1523
+ query: vector
1524
+ });
1525
+ const hits = await Promise.all(near.filter(({ score }) => score >= PICTURE_FLOOR).map(async ({ chatId: chatKey, messageId, score }) => {
1526
+ const message = await store.messages.message(account, messageId, { chatId: chatKey });
1527
+ if (!message)
1528
+ return [];
1529
+ return [
1530
+ {
1531
+ locator: formatLocator({
1532
+ provider: account.provider,
1533
+ account: account.account,
1534
+ chat: chatKey,
1535
+ message: messageId
1536
+ }),
1537
+ chatId: chatKey,
1538
+ messageId,
1539
+ timestamp: message.timestamp,
1540
+ senderName: message.senderName,
1541
+ senderIsMe: senderIsMe(message, account.account),
1542
+ score: Number(score.toFixed(4))
1543
+ }
1544
+ ];
1545
+ }));
1546
+ return { pictures: hits.flat() };
1547
+ }, "lane")
1548
+ };
1549
+ }, "picturesService");
1550
+ var withPictures = /* @__PURE__ */ __name((messages, pictures) => ({
1551
+ ...messages,
1552
+ search: /* @__PURE__ */ __name(async (request) => {
1553
+ const found = await messages.search(request);
1554
+ if (request.kind === "mail" || request.discover || request.text === void 0)
1555
+ return found;
1556
+ if (request.offset)
1557
+ return found;
1558
+ const chat = request.chat ?? found.coverage?.chat;
1559
+ const lane = await pictures.lane(request.text, chat === void 0 ? {} : { chat }).catch((error) => ({ picturesSkipped: error instanceof Error ? error.message : String(error) }));
1560
+ return { ...found, ...lane };
1561
+ }, "search")
1562
+ }), "withPictures");
1563
+
1564
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/services/notes-search.js
1565
+ var storeQuery = /* @__PURE__ */ __name(async (store, text, { exact, timezone } = {}) => resolvedQuery(store, parsedQuery(text, exact), timezone), "storeQuery");
1566
+ var parsedQuery = /* @__PURE__ */ __name((text, exact) => validateFields(parseLucene(text, { ...SEARCH_QUERY, defaultField: exact ? "exact" : "text" })).root, "parsedQuery");
1567
+ var resolvedQuery = /* @__PURE__ */ __name(async (store, root, timezone) => {
1568
+ const ast = { root };
1569
+ const zone = timezoneOf(timezone);
1570
+ const resolve2 = /* @__PURE__ */ __name((node) => {
1571
+ if (node.kind === "boolean")
1572
+ return { ...node, clauses: node.clauses.map(({ occur, node: node2 }) => ({ occur, node: resolve2(node2) })) };
1573
+ if (node.field !== "date")
1574
+ return node;
1575
+ return {
1576
+ ...node,
1577
+ resolution: {
1578
+ date: dateRange(node.value, node.operator === "range" ? node.upper ?? "*" : node.value, node.operator === "range" ? node.lower_inclusive === true : true, node.operator === "range" ? node.upper_inclusive === true : true, zone, node.span)
1579
+ }
1580
+ };
1581
+ }, "resolve");
1582
+ const stemmers = hasStems(ast.root) ? await store.searchIndex.stemmers() : void 0;
1583
+ if (stemmers === null)
1584
+ throw new CliError("validation_error", "the store asks for stemmers this tool does not know \u2014 upgrade this tool, or search exact forms with --exact", { reason: "stemmer.unknown" });
1585
+ return {
1586
+ root: resolve2(ast.root),
1587
+ ...hasStems(ast.root) ? { stemmer: createStemmer(stemmers ?? DEFAULT_STEMMERS) } : {}
1588
+ };
1589
+ }, "resolvedQuery");
1590
+ var searchNotesQuery = /* @__PURE__ */ __name(async (store, request) => {
1591
+ if (!request.text.trim())
1592
+ throw new CliError("validation_error", "say what to find in the notes");
1593
+ const { root, stemmer } = await storeQuery(store, request.text, request);
1594
+ return store.notes.search({
1595
+ root,
1596
+ limit: request.limit,
1597
+ ...request.offset === void 0 ? {} : { offset: request.offset },
1598
+ ...request.newest ? { newest: true } : {},
1599
+ ...request.folderIds ? { folderIds: request.folderIds } : {},
1600
+ ...request.withInternal ? { withInternal: true } : {},
1601
+ ...request.source ? { source: request.source } : {},
1602
+ ...request.signal ? { signal: request.signal } : {},
1603
+ ...stemmer ? { stemmer } : {}
1604
+ });
1605
+ }, "searchNotesQuery");
1606
+ var NOTE_BATCH = 8;
1607
+ var downloadHint = /* @__PURE__ */ __name((model, command) => command === void 0 ? `install it with a WireCat CLI that has \`models download\` (tg, max or wa); they share the model folder` : `\`${command} models download ${model}\``, "downloadHint");
1608
+ var localModel = /* @__PURE__ */ __name((choice, env, command) => {
1609
+ const model = textModel(choice ?? chosenTextModel(env).id, env);
1610
+ const directory = textModelsDirectory(env);
1611
+ if (!isTextModelInstalled(model, directory))
1612
+ throw new CliError("not_found", `${model.id} is not downloaded \u2014 ${downloadHint(model.id, command)}`, {
1613
+ reason: "model.not-downloaded",
1614
+ model: model.id
1615
+ });
1616
+ return { model, directory, key: vectorModelKey(model) };
1617
+ }, "localModel");
1618
+ var withLocal = /* @__PURE__ */ __name(async (model, directory, threads, work, shared) => {
1619
+ if (shared)
1620
+ return work(await shared.get(vectorModelKey(model), () => openEmbedder(model, directory, { threads: threads ?? defaultThreads() })));
1621
+ const embedder = await openEmbedder(model, directory, { threads: threads ?? defaultThreads() });
1622
+ try {
1623
+ return await work(embedder);
1624
+ } finally {
1625
+ await embedder.close();
1626
+ }
1627
+ }, "withLocal");
1628
+ var stopsAt = /* @__PURE__ */ __name((deadline) => deadline ? deadline.endsAt - deadlineMargin(deadline) : Number.POSITIVE_INFINITY, "stopsAt");
1629
+ var embedChunks = /* @__PURE__ */ __name(async (store, source, { model: choice, maxChunks = Number.POSITIVE_INFINITY, env, threads, command, deadline, signal } = {}) => {
1630
+ const { model, directory, key } = localModel(choice, env, command);
1631
+ if ((await source.chunksToEmbed(key, { limit: 1 })).length === 0)
1632
+ return { model: model.id, embedded: 0, left: false };
1633
+ const until = stopsAt(deadline);
1634
+ const stopped = /* @__PURE__ */ __name((slowest) => signal?.aborted ? "cancelled" : Date.now() + slowest >= until ? "deadline" : void 0, "stopped");
1635
+ const stop = /* @__PURE__ */ __name(async (embedded, why) => {
1636
+ const remaining = await source.chunksLeft?.(key);
1637
+ return { model: model.id, embedded, left: true, stopped: why, ...remaining === void 0 ? {} : { remaining } };
1638
+ }, "stop");
1639
+ const early = stopped(0);
1640
+ if (early)
1641
+ return stop(0, early);
1642
+ return withLocal(model, directory, threads, async (embedder) => {
1643
+ let embedded = 0;
1644
+ let after;
1645
+ let slowest = 0;
1646
+ while (embedded < maxChunks) {
1647
+ const started = Date.now();
1648
+ const batch = await source.chunksToEmbed(key, {
1649
+ limit: Math.min(NOTE_BATCH, maxChunks - embedded),
1650
+ ...after === void 0 ? {} : { after }
1651
+ });
1652
+ if (batch.length === 0)
1653
+ break;
1654
+ const why = stopped(slowest);
1655
+ if (why)
1656
+ return stop(embedded, why);
1657
+ after = batch.at(-1)?.hash;
1658
+ const vectors = await embedder.embed(batch.map(({ text }) => text), "passage");
1659
+ await store.vectors.saveVectors(key, model.dims, batch.map(({ hash }, index) => ({ hash, vector: vectors[index] })));
1660
+ embedded += batch.length;
1661
+ slowest = Math.max(slowest, Date.now() - started);
1662
+ }
1663
+ const left = (await source.chunksToEmbed(key, { limit: 1, ...after === void 0 ? {} : { after } })).length > 0;
1664
+ return { model: model.id, embedded, left };
1665
+ });
1666
+ }, "embedChunks");
1667
+ var enrichedFirst = /* @__PURE__ */ __name(async (store, types, options, embed) => {
1668
+ let enrichment;
1669
+ try {
1670
+ const run = await enrichRecords(store, {
1671
+ env: options.env ?? process.env,
1672
+ narrow: { types },
1673
+ ...options.app ? { app: options.app } : {},
1674
+ ...options.keyring ? { keyring: options.keyring } : {},
1675
+ ...options.enrichWith,
1676
+ ...options.deadline ? { deadline: options.deadline } : {},
1677
+ ...options.signal ? { signal: options.signal } : {}
1678
+ });
1679
+ if (run.status !== "off")
1680
+ enrichment = run;
1681
+ } catch (error) {
1682
+ enrichment = {
1683
+ status: "failed",
1684
+ reason: error instanceof Error ? error.message : "enrichment failed",
1685
+ reason_id: "enrichment.error"
1686
+ };
1687
+ }
1688
+ let embedded;
1689
+ try {
1690
+ embedded = await embed();
1691
+ } catch (error) {
1692
+ if (enrichment && error instanceof CliError)
1693
+ throw new CliError(error.code, error.message, { ...error.details, enrichment });
1694
+ throw error;
1695
+ }
1696
+ if (!enrichment)
1697
+ return embedded;
1698
+ const more = enrichment.status !== "failed" && enrichment.left > 0 && enrichment.enriched > 0;
1699
+ return { ...embedded, left: embedded.left || more, enrichment };
1700
+ }, "enrichedFirst");
1701
+ var embedNotes = /* @__PURE__ */ __name((store, options = {}) => enrichedFirst(store, ["document", "note"], options, () => embedChunks(store, store.notes, options)), "embedNotes");
1702
+ var embedEvents = /* @__PURE__ */ __name((store, options = {}) => embedChunks(store, store.calendar, options), "embedEvents");
1703
+ var embedMail = /* @__PURE__ */ __name((store, options = {}) => enrichedFirst(store, ["email"], options, () => embedChunks(store, store.mail, options)), "embedMail");
1704
+ var nearestNotes = /* @__PURE__ */ __name(async (store, query, options) => {
1705
+ const { key, vector, floor } = await queryVector(store, query, options);
1706
+ const nearest2 = await store.notes.nearest(key, vector, {
1707
+ limit: options.limit,
1708
+ ...options.folderIds ? { folderIds: options.folderIds } : {},
1709
+ ...options.withInternal ? { withInternal: true } : {},
1710
+ ...options.source ? { source: options.source } : {}
1711
+ });
1712
+ return nearest2.filter(({ score }) => score > floor);
1713
+ }, "nearestNotes");
1714
+ var queryVector = /* @__PURE__ */ __name(async (store, query, { model: choice, folderIds, withInternal, source, env, threads, command, embedders }) => {
1715
+ if (!query.trim())
1716
+ throw new CliError("validation_error", "say what to find in the notes");
1717
+ const { model, directory, key } = localModel(choice ?? await meaningModel(store, env), env, command);
1718
+ const scope = {
1719
+ ...folderIds ? { folderIds } : {},
1720
+ ...withInternal ? { withInternal: true } : {},
1721
+ ...source ? { source } : {}
1722
+ };
1723
+ if (!await store.notes.embedded(key, scope))
1724
+ throw new CliError("not_found", `nothing searched here has vectors of ${model.id} yet, so only words were matched`);
1725
+ const [vector] = await withLocal(model, directory, threads, (embedder) => embedder.embed([query], "query"), embedders);
1726
+ return { key, vector, floor: meaningFloor(key) };
1727
+ }, "queryVector");
1728
+ var nearestAmong = /* @__PURE__ */ __name(async (store, query, refs, options) => {
1729
+ const { key, vector, floor } = await queryVector(store, query, options);
1730
+ return (await store.notes.scoreNotes(key, vector, refs)).filter(({ score }) => score > floor);
1731
+ }, "nearestAmong");
1732
+ var MAX_LINE2 = 200;
1733
+ var MAX_NOTES_OFFSET = 1e3;
1734
+ var CANDIDATES = 50;
1735
+ var firstLine = /* @__PURE__ */ __name((text, query) => {
1736
+ const words = query.toLowerCase().split(/\s+/).map((word) => word.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter((word) => word.length > 2 && !["and", "or", "not"].includes(word));
1737
+ const lines = text.split("\n");
1738
+ const found = lines.find((line2) => words.some((word) => line2.toLowerCase().includes(word)));
1739
+ return (found ?? lines.find((line2) => line2.trim() !== "") ?? "").trim().slice(0, MAX_LINE2);
1740
+ }, "firstLine");
1741
+ var pictureLane = /* @__PURE__ */ __name(async (store, query, { folderIds, source, limit, env, command, embedder }) => {
1742
+ const words = plainWords(query);
1743
+ if (words === "" || source === "internal")
1744
+ return {};
1745
+ let vector;
1746
+ try {
1747
+ const use = embedder ?? await openPictureEmbedderFor({
1748
+ ...env === void 0 ? {} : { env },
1749
+ ...command === void 0 ? {} : { command }
1750
+ });
1751
+ try {
1752
+ vector = await use.embedQuery(words);
1753
+ } finally {
1754
+ if (!embedder)
1755
+ await use.close();
1756
+ }
1757
+ } catch (error) {
1758
+ if (error instanceof CliError && error.code === "not_found")
1759
+ return { pictures_skipped: error.message };
1760
+ throw error;
1761
+ }
1762
+ const near = await store.notes.nearestPictures(imageModel(DEFAULT_IMAGE_MODEL).key, vector, {
1763
+ limit,
1764
+ ...folderIds === void 0 ? {} : { folderIds }
1765
+ });
1766
+ return {
1767
+ pictures: near.filter(({ score }) => score >= PICTURE_FLOOR).map(({ ref, score }) => ({ ref, score: Number(score.toFixed(4)) }))
1768
+ };
1769
+ }, "pictureLane");
1770
+ var noteSourceOfQuery = /* @__PURE__ */ __name((query) => {
1771
+ let root;
1772
+ try {
1773
+ root = parseLucene(query, { ...SEARCH_QUERY, defaultField: "text" }).root;
1774
+ } catch {
1775
+ return { rest: query };
1776
+ }
1777
+ const required = root.kind === "predicate" ? [root] : root.clauses.flatMap(({ occur, node }) => occur === "must" && node.kind === "predicate" ? [node] : []);
1778
+ const typed = required.find(({ field, operator }) => field === "source" && (operator === "term" || operator === "phrase"));
1779
+ const source = typed?.value.toLowerCase();
1780
+ if (typed === void 0 || source !== "internal" && source !== "file")
1781
+ return { rest: query };
1782
+ const rest = `${query.slice(0, typed.span.start).replace(/\s*(?:AND|&&)\s*$/u, "")} ${query.slice(typed.span.end).replace(/^\s*(?:AND|&&)\s*/u, "")}`.trim();
1783
+ try {
1784
+ if (rest)
1785
+ parseLucene(rest, { ...SEARCH_QUERY, defaultField: "text" });
1786
+ } catch {
1787
+ return { source, rest: query };
1788
+ }
1789
+ return { source, rest };
1790
+ }, "noteSourceOfQuery");
1791
+ var EVERY_NOTE = { kind: "predicate", field: "in", operator: "term", value: "notes" };
1792
+ var fieldsOfQuery2 = /* @__PURE__ */ __name((root) => fieldsOfQuery(root, EVERY_NOTE), "fieldsOfQuery");
1793
+ var allOf = /* @__PURE__ */ __name((nodes) => nodes.length <= 1 ? nodes[0] : {
1794
+ kind: "boolean",
1795
+ clauses: nodes.map((node) => ({ occur: "must", node })),
1796
+ span: { start: 0, end: 0 }
1797
+ }, "allOf");
1798
+ var matching = /* @__PURE__ */ __name(async (store, refs, root, scope) => {
1799
+ if (refs.length === 0)
1800
+ return /* @__PURE__ */ new Map();
1801
+ const resolved = await resolvedQuery(store, root ?? { ...EVERY_NOTE, span: { start: 0, end: 0 } }, scope.timezone);
1802
+ const found = await store.notes.search({
1803
+ root: resolved.root,
1804
+ refs,
1805
+ limit: refs.length,
1806
+ ...scope.folderIds ? { folderIds: scope.folderIds } : {},
1807
+ ...scope.withInternal ? { withInternal: true } : {},
1808
+ ...scope.source ? { source: scope.source } : {},
1809
+ ...resolved.stemmer ? { stemmer: resolved.stemmer } : {}
1810
+ });
1811
+ return new Map(found.items.map(({ ref, note, at }) => [ref, { note, at }]));
1812
+ }, "matching");
1813
+ var RANK_WITHIN = 2e3;
1814
+ var filterRefs = /* @__PURE__ */ __name(async (store, narrowing, scope) => {
1815
+ const resolved = await resolvedQuery(store, narrowing, scope.timezone);
1816
+ try {
1817
+ const found = await store.notes.matchingRefs({
1818
+ root: resolved.root,
1819
+ limit: RANK_WITHIN,
1820
+ ...scope.folderIds ? { folderIds: scope.folderIds } : {},
1821
+ ...scope.withInternal ? { withInternal: true } : {},
1822
+ ...scope.source ? { source: scope.source } : {},
1823
+ ...resolved.stemmer ? { stemmer: resolved.stemmer } : {}
1824
+ });
1825
+ return found.hasMore ? void 0 : found.refs;
1826
+ } catch (error) {
1827
+ if (isQueryLimit(error))
1828
+ return void 0;
1829
+ throw error;
1830
+ }
1831
+ }, "filterRefs");
1832
+ var notesTotal = /* @__PURE__ */ __name(async (store, text, { exact, scope, shown, hasMore }, others, othersComplete) => {
1833
+ let words;
1834
+ try {
1835
+ const { root, stemmer } = await storeQuery(store, text, {
1836
+ exact,
1837
+ ...scope.timezone ? { timezone: scope.timezone } : {}
1838
+ });
1839
+ words = await store.notes.matchingRefs({
1840
+ root,
1841
+ limit: TOTAL_CAP,
1842
+ ...scope.folderIds ? { folderIds: scope.folderIds } : {},
1843
+ ...scope.withInternal ? { withInternal: true } : {},
1844
+ ...scope.source ? { source: scope.source } : {},
1845
+ ...stemmer ? { stemmer } : {}
1846
+ });
1847
+ } catch (error) {
1848
+ if (isQueryLimit(error))
1849
+ return totalOf(void 0, shown, hasMore);
1850
+ throw error;
1851
+ }
1852
+ const count = (/* @__PURE__ */ new Set([...words.refs, ...others])).size + (words.hasMore ? 1 : 0);
1853
+ return totalOf(count, shown, hasMore, othersComplete);
1854
+ }, "notesTotal");
1855
+ var searchNotes = /* @__PURE__ */ __name(async (store, query, { limit = 20, offset = 0, tag, filter: expression, folderIds, withInternal, source: given, exact = false, discover = false, timezone, env, command, embedders, pictures: withPictures2 = false, pictureLimit = 5, pictureEmbedder } = {}) => {
1856
+ query = plainQuery(query);
1857
+ const typed = noteSourceOfQuery(query);
1858
+ const source = given ?? typed.source;
1859
+ const rest = typed.source !== void 0 && typed.source === source ? typed.rest : query;
1860
+ const label = tag === void 0 ? void 0 : normalizeTag(tag);
1861
+ const filter = [expression ? `(${expression})` : "", label === void 0 ? "" : `tag:${label}`].filter(Boolean).join(" AND ") || void 0;
1862
+ const lookup = discover && !exact ? questionLookup(query) : void 0;
1863
+ const parsed = query.trim() ? parsedQuery(lookup === void 0 ? query : questionText(query), exact) : void 0;
1864
+ const words = parsed === void 0 ? "" : meaningWords(parsed);
1865
+ const narrowing = allOf([
1866
+ ...parsed === void 0 ? [] : [fieldsOfQuery2(parsed)].filter((node) => node !== void 0),
1867
+ ...filter === void 0 ? [] : [parsedQuery(filter)]
1868
+ ]);
1869
+ const asked = lookup ?? query;
1870
+ const text = [asked.trim() ? `(${asked})` : "", filter ?? ""].filter(Boolean).join(" AND ");
1871
+ const window = offset + limit;
1872
+ const scope = {
1873
+ ...folderIds === void 0 ? {} : { folderIds },
1874
+ ...withInternal ? { withInternal: true } : {},
1875
+ ...source === void 0 ? {} : { source },
1876
+ ...timezone === void 0 ? {} : { timezone }
1877
+ };
1878
+ let meaningSkipped;
1879
+ let meaning;
1880
+ const cosines = /* @__PURE__ */ new Map();
1881
+ let meaningRefs;
1882
+ let meaningComplete = true;
1883
+ if (exact)
1884
+ meaningSkipped = "--exact searches words as written";
1885
+ else if (words) {
1886
+ const lane2 = {
1887
+ command,
1888
+ ...env === void 0 ? {} : { env },
1889
+ ...embedders === void 0 ? {} : { embedders },
1890
+ ...folderIds === void 0 ? {} : { folderIds },
1891
+ ...withInternal ? { withInternal: true } : {},
1892
+ ...source === void 0 ? {} : { source }
1893
+ };
1894
+ const depth = Math.max(window, CANDIDATES);
1895
+ try {
1896
+ const within = narrowing === void 0 ? void 0 : await filterRefs(store, narrowing, scope);
1897
+ let nearest2;
1898
+ if (within === void 0) {
1899
+ nearest2 = await nearestNotes(store, words, { ...lane2, limit: depth });
1900
+ meaningComplete = nearest2.length < depth;
1901
+ } else {
1902
+ const ranked2 = within.length ? await nearestAmong(store, words, within, lane2) : [];
1903
+ meaningRefs = new Set(ranked2.map(({ ref }) => ref));
1904
+ nearest2 = ranked2.slice(0, depth);
1905
+ }
1906
+ const allowed = await matching(store, nearest2.map(({ ref }) => ref), narrowing, scope);
1907
+ meaning = nearest2.flatMap(({ ref, score }) => {
1908
+ const found = allowed.get(ref);
1909
+ if (found)
1910
+ cosines.set(ref, score);
1911
+ return found ? [{ ref, ...found }] : [];
1912
+ });
1913
+ meaningRefs ??= new Set(meaning.map(({ ref }) => ref));
1914
+ } catch (error) {
1915
+ if (!(error instanceof CliError && error.code === "not_found"))
1916
+ throw error;
1917
+ meaningSkipped = error.message;
1918
+ }
1919
+ }
1920
+ const titleWords = plainQueryWords(rest);
1921
+ const titled = titleWords === void 0 ? { items: [], hasMore: false } : await searchNotesQuery(store, {
1922
+ text: [titleQuery(titleWords), filter ?? ""].filter(Boolean).join(" AND "),
1923
+ limit: Math.max(window, CANDIDATES),
1924
+ ...scope
1925
+ });
1926
+ const tier = titleWords === void 0 ? [] : titleTiers(titled.items, titleWords);
1927
+ const tierRefs = new Set(tier.map(({ ref }) => ref));
1928
+ const slice = meaning === void 0 && tier.length === 0;
1929
+ const matched = await searchNotesQuery(store, {
1930
+ text,
1931
+ limit: slice ? limit : Math.max(window, CANDIDATES) + tier.length,
1932
+ offset: slice ? offset : 0,
1933
+ exact,
1934
+ ...scope
1935
+ });
1936
+ const ranked = /* @__PURE__ */ new Map();
1937
+ const add = /* @__PURE__ */ __name((list, by) => list.forEach(({ ref, note, at }, rank) => {
1938
+ if (tierRefs.has(ref))
1939
+ return;
1940
+ const held = ranked.get(ref) ?? { note, at, score: 0, foundBy: [] };
1941
+ held.foundBy.push(by);
1942
+ ranked.set(ref, held);
1943
+ const vote = 1 / (RRF_K + rank + 1);
1944
+ if (by === "meaning" && lookup !== void 0 && held.foundBy.includes("words"))
1945
+ held.score = Math.max(held.score, vote);
1946
+ else
1947
+ held.score += vote;
1948
+ }), "add");
1949
+ add(matched.items, "words");
1950
+ if (meaning !== void 0)
1951
+ add(meaning, "meaning");
1952
+ const ordered = [
1953
+ ...tier.map(({ ref, note, at }) => [ref, { note, at, score: 0, foundBy: ["title"] }]),
1954
+ ...[...ranked.entries()].sort(([, a], [, b]) => b.score - a.score)
1955
+ ];
1956
+ const page = slice ? ordered : ordered.slice(offset, window);
1957
+ const hasMore = slice ? matched.hasMore : ordered.length > window || matched.hasMore || titled.hasMore;
1958
+ const total = await notesTotal(store, text, { exact, scope, shown: offset + page.length, hasMore }, [...tier.map(({ ref }) => ref), ...meaningRefs ?? []], meaningComplete);
1959
+ const hits = [];
1960
+ const counts = /* @__PURE__ */ new Map();
1961
+ const accounts = await store.accounts.storedAccounts();
1962
+ const profiles = await store.accounts.profiles();
1963
+ for (const [ref, { note, at, foundBy }] of page) {
1964
+ const links = (await store.notes.links({ from: ref })).map(({ to, targetText, kind, anchor }) => ({
1965
+ to,
1966
+ target_text: targetText,
1967
+ kind,
1968
+ anchor
1969
+ }));
1970
+ hits.push({
1971
+ ref,
1972
+ source: note.source,
1973
+ folder_id: note.folderId,
1974
+ path: note.path,
1975
+ title: note.title,
1976
+ ...documentSource(note, accounts, profiles, note.source === "file" ? (await store.files.ofDocument(note.ref))[0] : void 0),
1977
+ updated_at: at,
1978
+ excerpt: firstLine(note.text, words),
1979
+ links,
1980
+ found_by: foundBy,
1981
+ ...cosines.has(ref) ? { meaning_score: cosines.get(ref) } : {}
1982
+ });
1983
+ for (const link2 of new Map(links.map((link3) => [link3.to ?? `?${link3.target_text}`, link3])).values()) {
1984
+ const key = link2.to ?? `?${link2.target_text}`;
1985
+ const known = counts.get(key) ?? { ref: link2.to, name: link2.target_text, notes: 0 };
1986
+ known.notes++;
1987
+ counts.set(key, known);
1988
+ }
1989
+ }
1990
+ const names = new Map([...await store.knowledge.organizations(), ...await store.knowledge.projects()].map(({ ref, name }) => [
1991
+ ref,
1992
+ name
1993
+ ]));
1994
+ for (const record of counts.values()) {
1995
+ if (record.ref && names.has(record.ref))
1996
+ record.name = names.get(record.ref) ?? record.name;
1997
+ if (record.ref?.startsWith("person:"))
1998
+ record.name = (await store.people.personByUid(record.ref.slice("person:".length)))?.name ?? record.name;
1999
+ if (record.ref?.startsWith("note:") || record.ref?.startsWith("document:"))
2000
+ record.name = (await store.notes.note(record.ref).catch(() => void 0))?.title ?? record.name;
2001
+ }
2002
+ const lane = withPictures2 ? await pictureLane(store, words, {
2003
+ folderIds,
2004
+ source,
2005
+ limit: pictureLimit,
2006
+ env,
2007
+ command,
2008
+ embedder: pictureEmbedder
2009
+ }) : {};
2010
+ if (lane.pictures && narrowing !== void 0) {
2011
+ const allowed = await matching(store, lane.pictures.map(({ ref }) => ref), narrowing, scope);
2012
+ lane.pictures = lane.pictures.filter(({ ref }) => allowed.has(ref));
2013
+ }
2014
+ return {
2015
+ query,
2016
+ ...label === void 0 ? {} : { tag: label },
2017
+ ...filter === void 0 ? {} : { filter },
2018
+ by: meaning === void 0 ? "words" : "words and meaning",
2019
+ ...meaningSkipped === void 0 ? {} : { meaning_skipped: meaningSkipped },
2020
+ items: hits,
2021
+ total,
2022
+ hasMore,
2023
+ ...hasMore && window <= MAX_NOTES_OFFSET ? { nextOffset: window } : {},
2024
+ linked: [...counts.values()].sort((a, b) => b.notes - a.notes || (a.name ?? a.ref ?? "").localeCompare(b.name ?? b.ref ?? "")),
2025
+ ...lane
2026
+ };
2027
+ }, "searchNotes");
2028
+ var notesScopeOf = /* @__PURE__ */ __name((accounts, stored = []) => {
2029
+ const folderIds = accounts.filter(({ provider, account }) => provider !== "notes" || account !== INTERNAL_NOTES).map(({ provider, account }) => provider === "notes" ? account : String(stored.find((one) => one.provider === provider && one.account === account)?.id ?? 0));
2030
+ if (!folderIds.length)
2031
+ return { source: "internal" };
2032
+ return { folderIds, ...accounts.length > folderIds.length ? { withInternal: true } : {} };
2033
+ }, "notesScopeOf");
2034
+ var importAccounts = /* @__PURE__ */ __name(async (store) => (await store.accounts.storedAccounts()).filter(({ provider }) => isImportedProvider(provider)), "importAccounts");
2035
+ var searchNotesOf = /* @__PURE__ */ __name(async (store, account, text, { accounts: list, app, env, ...query }) => {
2036
+ text = plainQuery(text);
2037
+ const own = app?.command ?? query.command;
2038
+ const what = `${own === void 0 ? "" : `${own} `}search notes`;
2039
+ const held = [
2040
+ { provider: "notes", account: INTERNAL_NOTES },
2041
+ ...(await store.notes.folders()).map(({ id }) => ({ provider: "notes", account: id })),
2042
+ ...(await store.notes.documentsAccounts()).map(({ id }) => ({ provider: "notes", account: id })),
2043
+ ...[await store.notes.addedAccount()].flatMap((added) => added ? [{ provider: "notes", account: added.id }] : []),
2044
+ ...(await importAccounts(store)).map(({ provider, account: account2 }) => ({ provider, account: account2 }))
2045
+ ];
2046
+ const lock = groupLockOf(app, env);
2047
+ const typedScope = list ?? (lock === void 0 ? void 0 : `group:${lock}`);
2048
+ const notesScope = typedScope !== void 0 && /(^|,)\s*group:/i.test(typedScope) ? `${typedScope},${sourceOf(OWNER_NOTES)}` : typedScope;
2049
+ const named = notesScope === void 0 ? { accounts: held, skipped: [] } : fitting(entriesOfList(notesScope, await listContextOf(store, account, app, void 0, env)), ["notes", "documents"], what);
2050
+ const source = query.source ?? noteSourceOfQuery(text).source;
2051
+ const internal = /* @__PURE__ */ __name(({ provider, account: account2 }) => provider === "notes" && account2 === INTERNAL_NOTES, "internal");
2052
+ const typed = named.accounts.filter((one) => source === void 0 || internal(one) === (source === "internal"));
2053
+ if (!typed.length && list !== void 0)
2054
+ throw new CliError("validation_error", source === "internal" ? "the query's source:internal keeps the notes written in memo, and the --source list names none of them: add notes:internal to --source, or drop source:internal from the query" : "the query's source:file keeps the files from notes folders, and the --source list names none of them: add notes:<folder id> to --source, or drop source:file from the query");
2055
+ const scope = list === void 0 ? {} : notesScopeOf(typed, await store.accounts.storedAccounts());
2056
+ const found = await searchNotes(store, text, {
2057
+ ...query,
2058
+ ...scope,
2059
+ ...source ? { source } : {},
2060
+ ...env === void 0 ? {} : { env }
2061
+ });
2062
+ return {
2063
+ ...found,
2064
+ accounts: typed.map(({ provider, account: account2 }) => ({ resource: "notes", provider, account: account2 })),
2065
+ skipped: named.skipped
2066
+ };
2067
+ }, "searchNotesOf");
2068
+
2069
+ export {
2070
+ actionable,
2071
+ batchProgress,
2072
+ mergeBatches,
2073
+ accountStore,
2074
+ crossAccount,
2075
+ unlessBusy,
2076
+ accountStoreIfOpen,
2077
+ storeIfOpen,
2078
+ fromStore,
2079
+ nothingStored,
2080
+ OFFLINE,
2081
+ onlineDeps,
2082
+ storedDeps,
2083
+ storeModeDeps,
2084
+ storeOnlyDeps,
2085
+ ALL,
2086
+ OWNER_NOTES,
2087
+ NOT_GROUP_NAMES,
2088
+ hasGroup,
2089
+ groupMembership,
2090
+ inGroupOf,
2091
+ scopeToGroup,
2092
+ MAIL,
2093
+ groupLockOf,
2094
+ listContextOf,
2095
+ listedAccounts,
2096
+ accountsOfKind,
2097
+ readChatId,
2098
+ storedChatId,
2099
+ chatIdIn,
2100
+ profilesOnAccount,
2101
+ chatAmong,
2102
+ senderAmong,
2103
+ sendersMatching,
2104
+ chatsMatchingIn,
2105
+ refreshedFiles,
2106
+ downloadMessage,
2107
+ saveFiles,
2108
+ save,
2109
+ GROUP_SETTINGS,
2110
+ FOLDER_KINDS,
2111
+ FOLDER_SKIPS,
2112
+ ADMIN_RIGHTS,
2113
+ senderIsMe,
2114
+ MEDIA_KINDS,
2115
+ PICTURE_MAX_BYTES,
2116
+ plainWords,
2117
+ pictureBytes,
2118
+ picturesService,
2119
+ withPictures,
2120
+ TOTAL_CAP,
2121
+ totalOf,
2122
+ fieldsOfQuery,
2123
+ meaningWords,
2124
+ meaningModel,
2125
+ openPictureEmbedderFor,
2126
+ savePicture,
2127
+ removePicture,
2128
+ ENRICHMENT_PROVIDERS,
2129
+ MODEL_CHOICE,
2130
+ enrichmentSettingPath,
2131
+ readEnrichmentSetting,
2132
+ writeEnrichmentSetting,
2133
+ enrichmentEndpoint,
2134
+ isEnrichmentProvider,
2135
+ enrichmentPrice,
2136
+ estimateEnrichment,
2137
+ costOf,
2138
+ ENRICH_PER_RUN,
2139
+ keyLookup,
2140
+ keyVariable,
2141
+ enrichRecords,
2142
+ enrichmentState,
2143
+ plainQueryWords,
2144
+ storeQuery,
2145
+ searchNotesQuery,
2146
+ localModel,
2147
+ withLocal,
2148
+ embedNotes,
2149
+ embedEvents,
2150
+ embedMail,
2151
+ nearestNotes,
2152
+ noteSourceOfQuery,
2153
+ fieldsOfQuery2,
2154
+ RANK_WITHIN,
2155
+ searchNotes,
2156
+ notesScopeOf,
2157
+ importAccounts,
2158
+ searchNotesOf
2159
+ };