@graphrefly/graphrefly 0.29.0 → 0.31.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 (298) hide show
  1. package/dist/{cascading-CcAgRacD.d.cts → cascading-BfQmSmjU.d.cts} +22 -3
  2. package/dist/{cascading-Bp99ckMJ.d.ts → cascading-D3sapjue.d.ts} +22 -3
  3. package/dist/{chunk-JYOUF6UQ.js → chunk-3JRKP4BH.js} +1 -1
  4. package/dist/{chunk-GJR3P6JG.js → chunk-3Q2WXM6X.js} +1 -1
  5. package/dist/chunk-4KAUNEKV.js +3 -0
  6. package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
  7. package/dist/chunk-4VXL3UZK.js +1 -0
  8. package/dist/{chunk-AV3PIDFQ.js → chunk-4ZPO2EL5.js} +1 -1
  9. package/dist/{chunk-VWPRPPKR.js → chunk-5LJAQTSS.js} +1 -1
  10. package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
  11. package/dist/{chunk-RD52SNH2.js → chunk-7EJTWGKW.js} +1 -1
  12. package/dist/{chunk-GNCBXARM.js → chunk-7EQPXQ7H.js} +1 -1
  13. package/dist/chunk-7QMVU3IX.js +1 -0
  14. package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
  15. package/dist/chunk-ASDKRNOJ.js +60 -0
  16. package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
  17. package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
  18. package/dist/{chunk-Y53B6NS4.js → chunk-EBQ6FXKW.js} +1 -1
  19. package/dist/chunk-FTA5TB2A.js +1 -0
  20. package/dist/{chunk-E3AXATVZ.js → chunk-GF5T7PGC.js} +1 -1
  21. package/dist/{chunk-HSIEYSDY.js → chunk-I4U3TPK2.js} +1 -1
  22. package/dist/{chunk-AMG5VBHW.js → chunk-JMGGCSIC.js} +1 -1
  23. package/dist/chunk-JXRZXP3N.js +1 -0
  24. package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
  25. package/dist/{chunk-63FFOHLA.js → chunk-KN4Q5MQO.js} +1 -1
  26. package/dist/chunk-LWGLBCMU.js +1 -0
  27. package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
  28. package/dist/{chunk-4OFIQ66T.js → chunk-OKQUPJRY.js} +1 -1
  29. package/dist/chunk-PNTBXOQ6.js +5 -0
  30. package/dist/chunk-PSQNYY72.js +7 -0
  31. package/dist/{chunk-22F4K3G7.js → chunk-PZP4MEXK.js} +1 -1
  32. package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
  33. package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
  34. package/dist/chunk-SGS4OJGS.js +1 -0
  35. package/dist/chunk-UMH3HSP7.js +1 -0
  36. package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
  37. package/dist/{chunk-A7IAQQ63.js → chunk-WLPVGXQ6.js} +1 -1
  38. package/dist/chunk-WQ7I7JVU.js +1 -0
  39. package/dist/{chunk-LGSNR4LU.js → chunk-WYJTXYWX.js} +1 -1
  40. package/dist/{chunk-PGMUCUHG.js → chunk-X2VHDT26.js} +1 -1
  41. package/dist/{chunk-PCZ35NXD.js → chunk-XEFAMCEA.js} +1 -1
  42. package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
  43. package/dist/chunk-Y26UN6J5.js +18 -0
  44. package/dist/{chunk-BKPLTBL5.js → chunk-YQJPYEAL.js} +1 -1
  45. package/dist/{chunk-UVJQ35G2.js → chunk-YZ6VYLFD.js} +1 -1
  46. package/dist/{chunk-4JJCCD5S.js → chunk-YZKGGMPT.js} +1 -1
  47. package/dist/chunk-Z3UWIJ3A.js +1 -0
  48. package/dist/{chunk-CSJE2EKV.js → chunk-ZM7C2FUM.js} +1 -1
  49. package/dist/compat/index.cjs +1 -1
  50. package/dist/compat/index.d.cts +14 -14
  51. package/dist/compat/index.d.ts +14 -14
  52. package/dist/compat/index.js +1 -1
  53. package/dist/compat/jotai/index.cjs +1 -1
  54. package/dist/compat/jotai/index.d.cts +2 -2
  55. package/dist/compat/jotai/index.d.ts +2 -2
  56. package/dist/compat/jotai/index.js +1 -1
  57. package/dist/compat/nanostores/index.cjs +1 -1
  58. package/dist/compat/nanostores/index.d.cts +2 -2
  59. package/dist/compat/nanostores/index.d.ts +2 -2
  60. package/dist/compat/nanostores/index.js +1 -1
  61. package/dist/compat/nestjs/index.cjs +5 -5
  62. package/dist/compat/nestjs/index.d.cts +6 -6
  63. package/dist/compat/nestjs/index.d.ts +6 -6
  64. package/dist/compat/nestjs/index.js +1 -1
  65. package/dist/compat/react/index.d.cts +2 -2
  66. package/dist/compat/react/index.d.ts +2 -2
  67. package/dist/compat/solid/index.d.cts +2 -2
  68. package/dist/compat/solid/index.d.ts +2 -2
  69. package/dist/compat/svelte/index.d.cts +2 -2
  70. package/dist/compat/svelte/index.d.ts +2 -2
  71. package/dist/compat/vue/index.d.cts +2 -2
  72. package/dist/compat/vue/index.d.ts +2 -2
  73. package/dist/compat/zustand/index.cjs +1 -1
  74. package/dist/compat/zustand/index.d.cts +4 -4
  75. package/dist/compat/zustand/index.d.ts +4 -4
  76. package/dist/compat/zustand/index.js +1 -1
  77. package/dist/{composite-BL-llbnE.d.ts → composite-BY9hMxN7.d.ts} +2 -2
  78. package/dist/{composite-Dze--DaA.d.cts → composite-CH0S8DFn.d.cts} +2 -2
  79. package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
  80. package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
  81. package/dist/core/index.cjs +1 -1
  82. package/dist/core/index.d.cts +4 -4
  83. package/dist/core/index.d.ts +4 -4
  84. package/dist/core/index.js +1 -1
  85. package/dist/extra/browser.cjs +1 -1
  86. package/dist/extra/browser.d.cts +1 -1
  87. package/dist/extra/browser.d.ts +1 -1
  88. package/dist/extra/browser.js +1 -1
  89. package/dist/extra/index.cjs +18 -18
  90. package/dist/extra/index.d.cts +12 -11
  91. package/dist/extra/index.d.ts +12 -11
  92. package/dist/extra/index.js +1 -1
  93. package/dist/extra/node.cjs +2 -2
  94. package/dist/extra/node.d.cts +1 -1
  95. package/dist/extra/node.d.ts +1 -1
  96. package/dist/extra/node.js +1 -1
  97. package/dist/extra/operators.cjs +1 -1
  98. package/dist/extra/operators.d.cts +42 -2
  99. package/dist/extra/operators.d.ts +42 -2
  100. package/dist/extra/operators.js +1 -1
  101. package/dist/extra/reactive.cjs +1 -1
  102. package/dist/extra/reactive.d.cts +3 -3
  103. package/dist/extra/reactive.d.ts +3 -3
  104. package/dist/extra/reactive.js +1 -1
  105. package/dist/extra/sources.cjs +1 -1
  106. package/dist/extra/sources.d.cts +63 -3
  107. package/dist/extra/sources.d.ts +63 -3
  108. package/dist/extra/sources.js +1 -1
  109. package/dist/extra/storage-browser.cjs +1 -1
  110. package/dist/extra/storage-browser.d.cts +1 -1
  111. package/dist/extra/storage-browser.d.ts +1 -1
  112. package/dist/extra/storage-browser.js +1 -1
  113. package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
  114. package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
  115. package/dist/graph/index.cjs +4 -4
  116. package/dist/graph/index.d.cts +5 -5
  117. package/dist/graph/index.d.ts +5 -5
  118. package/dist/graph/index.js +1 -1
  119. package/dist/{graph-DgohqXK-.d.cts → graph-C4Uxwv0T.d.cts} +2 -2
  120. package/dist/{graph-Qjg9gWHI.d.ts → graph-CWeI0aHd.d.ts} +2 -2
  121. package/dist/{index-DX8xS-yB.d.cts → index-9iguV3bF.d.cts} +2 -2
  122. package/dist/{index-BanNUILp.d.cts → index-B-z8WaSd.d.cts} +2 -2
  123. package/dist/{index-C66RJiX8.d.ts → index-B5iVOD7w.d.ts} +2 -2
  124. package/dist/{index-CcWOJ6F0.d.ts → index-BANwzwBV.d.ts} +3 -3
  125. package/dist/{index-CiaVoZGo.d.ts → index-BBINVimG.d.ts} +3 -3
  126. package/dist/{index-B-gqvYel.d.ts → index-BEpRsvhg.d.ts} +4 -4
  127. package/dist/{index-C8RfjffH.d.ts → index-BMe3pCom.d.cts} +3 -3
  128. package/dist/{index-gsT79Xu9.d.ts → index-BX22kvjh.d.ts} +1 -1
  129. package/dist/{index-CA1Cu7Ud.d.ts → index-BXzl1NDD.d.ts} +6 -6
  130. package/dist/{index-BqZ6vB2A.d.ts → index-Bd6oFZqO.d.ts} +230 -122
  131. package/dist/{index-kykKWwV-.d.cts → index-BpFWP7Bq.d.cts} +3 -3
  132. package/dist/{index-iKkyJosF.d.cts → index-Bs3-LC83.d.cts} +3 -3
  133. package/dist/{index-CJ45TW-h.d.ts → index-Bvi5uJxX.d.ts} +1 -1
  134. package/dist/{index-IMAHq-ia.d.ts → index-ByPnK85n.d.ts} +1 -1
  135. package/dist/{index-CABbltIu.d.cts → index-BydMDMf7.d.cts} +1 -1
  136. package/dist/{index-D5XJ2tSx.d.ts → index-C5Ghnp5B.d.ts} +3 -3
  137. package/dist/{index-BiyjsZ0m.d.ts → index-C6NBfXj-.d.ts} +3 -3
  138. package/dist/{index-D9HKAH_-.d.cts → index-C98oJsEs.d.cts} +2 -2
  139. package/dist/{index-CHEBsnYv.d.cts → index-CDK5RsV5.d.cts} +1 -1
  140. package/dist/{index-DJ5oNBc8.d.ts → index-CFW32Dy1.d.ts} +3 -3
  141. package/dist/{index-D80do5jX.d.cts → index-CIXaiYDE.d.cts} +1 -1
  142. package/dist/{index-2BVuRCI4.d.ts → index-CJymKyzT.d.ts} +86 -11
  143. package/dist/{index-H_oxVec5.d.cts → index-CRAkoq-y.d.cts} +1 -1
  144. package/dist/{index-DiZejfCI.d.cts → index-CZChc85Q.d.cts} +230 -122
  145. package/dist/{index-DDy8eeXS.d.ts → index-CcS0t-l2.d.ts} +3 -3
  146. package/dist/{index-B2PRuolf.d.cts → index-CcpEvuPl.d.cts} +2 -2
  147. package/dist/{index-DwjJGKxV.d.ts → index-CfFYyLR8.d.ts} +3 -3
  148. package/dist/{index-A65LZhoM.d.ts → index-CotRMjtJ.d.ts} +2 -2
  149. package/dist/{index-BQaEnxBf.d.ts → index-CrC7urhX.d.ts} +1 -1
  150. package/dist/{index-DuB5aO4-.d.ts → index-CvS9IuTG.d.ts} +2 -2
  151. package/dist/{index-BUi57v_p.d.ts → index-CwhcFzTA.d.ts} +4 -4
  152. package/dist/{index-BUVtw1Ay.d.cts → index-Cy7eFeIX.d.cts} +2 -2
  153. package/dist/{index-C08QPDcV.d.cts → index-D-kHVedZ.d.cts} +3 -3
  154. package/dist/{index-Ct5CWc4E.d.ts → index-D0C_USMR.d.ts} +1 -1
  155. package/dist/{index-y1RllPn4.d.cts → index-D7XxY1Ff.d.cts} +1 -1
  156. package/dist/{index-BJqt9EwW.d.ts → index-D9HrBx2J.d.ts} +2 -2
  157. package/dist/{index-DP0_O3ls.d.cts → index-D9Y_u6BG.d.cts} +3 -3
  158. package/dist/{index-DoWMs-Kk.d.cts → index-DBQUKh59.d.cts} +4 -4
  159. package/dist/{index-dig-r2tQ.d.cts → index-DD7RhHNJ.d.cts} +6 -6
  160. package/dist/{index-U1nir7MX.d.cts → index-DDo-eqQ4.d.cts} +1 -1
  161. package/dist/{index-2NvguqQA.d.ts → index-DGb1awva.d.ts} +4 -4
  162. package/dist/{index-i99Ka8s7.d.cts → index-DR3gf_DG.d.cts} +9 -9
  163. package/dist/{index-DBe_8XW5.d.cts → index-DVNLe3pS.d.cts} +3 -3
  164. package/dist/{index-DknyJ2Fu.d.cts → index-Dm3_D5Ta.d.cts} +4 -4
  165. package/dist/{index-DCeTyFlB.d.ts → index-DnrZghBB.d.ts} +2 -2
  166. package/dist/{index-Byh-xTyp.d.ts → index-Docdiu9a.d.ts} +3 -3
  167. package/dist/{index-BTSkeCZs.d.cts → index-DxMS0cHM.d.ts} +3 -3
  168. package/dist/{index-D38duMCv.d.cts → index-DylQCKEL.d.cts} +3 -3
  169. package/dist/{index-jleeotBT.d.cts → index-FBqTfL_S.d.cts} +1 -1
  170. package/dist/{index-Vg7tORgk.d.ts → index-FrYrV-Vf.d.ts} +2 -2
  171. package/dist/{index-BSfwiy5B.d.ts → index-IZ3l_vQ9.d.ts} +2 -2
  172. package/dist/{index-CX2tFJL1.d.ts → index-Ip3q9T9x.d.ts} +1 -1
  173. package/dist/{index-CI0yDnLp.d.ts → index-RQg6lTrN.d.ts} +9 -9
  174. package/dist/{index-vgcLF5TH.d.cts → index-SSGqF8mI.d.cts} +2 -2
  175. package/dist/{index-CJZKZoo4.d.cts → index-UZO988ox.d.cts} +3 -3
  176. package/dist/{index-BKjT5DiZ.d.cts → index-gJQqJTKx.d.cts} +86 -11
  177. package/dist/{index-BayHDRx6.d.cts → index-iBp74eGU.d.cts} +3 -3
  178. package/dist/{index-BuVidq3D.d.cts → index-lKuLYmHO.d.cts} +2 -2
  179. package/dist/{index-BM8BU4q6.d.ts → index-wIx1Jisk.d.ts} +1 -1
  180. package/dist/{index-B-8FCEua.d.cts → index-yIdWFo2b.d.cts} +4 -4
  181. package/dist/index.cjs +99 -121
  182. package/dist/index.d.cts +47 -46
  183. package/dist/index.d.ts +47 -46
  184. package/dist/index.js +1 -1
  185. package/dist/{meta-CckhhFRd.d.ts → meta-BMwx3ExI.d.ts} +1 -1
  186. package/dist/{meta-CX7YsOzp.d.cts → meta-COtmHLwT.d.cts} +1 -1
  187. package/dist/{node-Dd6wHSib.d.cts → node-BVV7G1bq.d.cts} +24 -0
  188. package/dist/{node-Dd6wHSib.d.ts → node-BVV7G1bq.d.ts} +24 -0
  189. package/dist/{observable-kwzpLvbi.d.cts → observable-BrUAPeH_.d.cts} +1 -1
  190. package/dist/{observable-BZJgo616.d.ts → observable-ITikPXz3.d.ts} +1 -1
  191. package/dist/patterns/ai/browser.cjs +5 -22
  192. package/dist/patterns/ai/browser.d.cts +4 -4
  193. package/dist/patterns/ai/browser.d.ts +4 -4
  194. package/dist/patterns/ai/browser.js +1 -1
  195. package/dist/patterns/ai/index.cjs +27 -44
  196. package/dist/patterns/ai/index.d.cts +17 -15
  197. package/dist/patterns/ai/index.d.ts +17 -15
  198. package/dist/patterns/ai/index.js +1 -1
  199. package/dist/patterns/ai/node.cjs +2 -2
  200. package/dist/patterns/ai/node.d.cts +5 -4
  201. package/dist/patterns/ai/node.d.ts +5 -4
  202. package/dist/patterns/ai/node.js +1 -1
  203. package/dist/patterns/audit/index.cjs +3 -3
  204. package/dist/patterns/audit/index.d.cts +5 -5
  205. package/dist/patterns/audit/index.d.ts +5 -5
  206. package/dist/patterns/audit/index.js +1 -1
  207. package/dist/patterns/cqrs/index.cjs +6 -6
  208. package/dist/patterns/cqrs/index.d.cts +4 -4
  209. package/dist/patterns/cqrs/index.d.ts +4 -4
  210. package/dist/patterns/cqrs/index.js +1 -1
  211. package/dist/patterns/demo-shell/index.cjs +1 -1
  212. package/dist/patterns/demo-shell/index.d.cts +5 -5
  213. package/dist/patterns/demo-shell/index.d.ts +5 -5
  214. package/dist/patterns/demo-shell/index.js +1 -1
  215. package/dist/patterns/domain-templates/index.cjs +4 -4
  216. package/dist/patterns/domain-templates/index.d.cts +4 -4
  217. package/dist/patterns/domain-templates/index.d.ts +4 -4
  218. package/dist/patterns/domain-templates/index.js +1 -1
  219. package/dist/patterns/graphspec/index.cjs +6 -6
  220. package/dist/patterns/graphspec/index.d.cts +5 -5
  221. package/dist/patterns/graphspec/index.d.ts +5 -5
  222. package/dist/patterns/graphspec/index.js +1 -1
  223. package/dist/patterns/guarded-execution/index.cjs +7 -7
  224. package/dist/patterns/guarded-execution/index.d.cts +6 -6
  225. package/dist/patterns/guarded-execution/index.d.ts +6 -6
  226. package/dist/patterns/guarded-execution/index.js +1 -1
  227. package/dist/patterns/harness/index.cjs +11 -11
  228. package/dist/patterns/harness/index.d.cts +9 -9
  229. package/dist/patterns/harness/index.d.ts +9 -9
  230. package/dist/patterns/harness/index.js +1 -1
  231. package/dist/patterns/job-queue/index.cjs +5 -5
  232. package/dist/patterns/job-queue/index.d.cts +4 -4
  233. package/dist/patterns/job-queue/index.d.ts +4 -4
  234. package/dist/patterns/job-queue/index.js +1 -1
  235. package/dist/patterns/lens/index.cjs +5 -5
  236. package/dist/patterns/lens/index.d.cts +6 -6
  237. package/dist/patterns/lens/index.d.ts +6 -6
  238. package/dist/patterns/lens/index.js +1 -1
  239. package/dist/patterns/memory/index.cjs +4 -4
  240. package/dist/patterns/memory/index.d.cts +4 -4
  241. package/dist/patterns/memory/index.d.ts +4 -4
  242. package/dist/patterns/memory/index.js +1 -1
  243. package/dist/patterns/messaging/index.cjs +5 -5
  244. package/dist/patterns/messaging/index.d.cts +4 -4
  245. package/dist/patterns/messaging/index.d.ts +4 -4
  246. package/dist/patterns/messaging/index.js +1 -1
  247. package/dist/patterns/orchestration/index.cjs +1 -1
  248. package/dist/patterns/orchestration/index.d.cts +5 -5
  249. package/dist/patterns/orchestration/index.d.ts +5 -5
  250. package/dist/patterns/orchestration/index.js +1 -1
  251. package/dist/patterns/reactive-layout/index.cjs +1 -1
  252. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  253. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  254. package/dist/patterns/reactive-layout/index.js +1 -1
  255. package/dist/patterns/reduction/index.cjs +5 -5
  256. package/dist/patterns/reduction/index.d.cts +4 -4
  257. package/dist/patterns/reduction/index.d.ts +4 -4
  258. package/dist/patterns/reduction/index.js +1 -1
  259. package/dist/patterns/refine-loop/index.cjs +8 -8
  260. package/dist/patterns/refine-loop/index.d.cts +5 -5
  261. package/dist/patterns/refine-loop/index.d.ts +5 -5
  262. package/dist/patterns/refine-loop/index.js +1 -1
  263. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  264. package/dist/patterns/resilient-pipeline/index.d.cts +6 -6
  265. package/dist/patterns/resilient-pipeline/index.d.ts +6 -6
  266. package/dist/patterns/resilient-pipeline/index.js +1 -1
  267. package/dist/patterns/surface/index.cjs +7 -7
  268. package/dist/patterns/surface/index.d.cts +6 -6
  269. package/dist/patterns/surface/index.d.ts +6 -6
  270. package/dist/patterns/surface/index.js +1 -1
  271. package/dist/{reactive-layout-PiFwVaWS.d.cts → reactive-layout-5oEn8lHM.d.cts} +2 -2
  272. package/dist/{reactive-layout-BkBwVvwm.d.ts → reactive-layout-BAr6-_o5.d.ts} +2 -2
  273. package/dist/{reactive-log-BiVoSxke.d.cts → reactive-log-5jFeNRmd.d.cts} +1 -1
  274. package/dist/{reactive-log-1QTyx10a.d.ts → reactive-log-BOJDCI5x.d.ts} +1 -1
  275. package/dist/{reactive-map-CwO_COHy.d.cts → reactive-map-CtRaCddO.d.ts} +60 -2
  276. package/dist/{reactive-map-FeuTVAJb.d.ts → reactive-map-IJIfZxoh.d.cts} +60 -2
  277. package/dist/{resilience-CBfYJW5C.d.ts → resilience-CludlzcP.d.ts} +1 -1
  278. package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
  279. package/dist/{resilience-uBz4yvYB.d.cts → resilience-Q6Bt_7y0.d.cts} +1 -1
  280. package/dist/{sugar-CY-MCfZ9.d.ts → sugar-BHbAACDG.d.ts} +1 -1
  281. package/dist/{sugar-DHttV0LX.d.cts → sugar-CqR6DJ7v.d.cts} +1 -1
  282. package/dist/{topology-tree-CVjt2gp7.d.cts → topology-tree-CVREibAc.d.cts} +1 -1
  283. package/dist/{topology-tree-one6oSKY.d.ts → topology-tree-CkjojcB6.d.ts} +1 -1
  284. package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
  285. package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
  286. package/package.json +1 -1
  287. package/dist/chunk-22SVXUPB.js +0 -64
  288. package/dist/chunk-2GQREQ6C.js +0 -1
  289. package/dist/chunk-4V4C7K56.js +0 -1
  290. package/dist/chunk-5JDE5JHE.js +0 -1
  291. package/dist/chunk-7JDLFI6N.js +0 -1
  292. package/dist/chunk-ISCENNXS.js +0 -1
  293. package/dist/chunk-KASHOCF5.js +0 -1
  294. package/dist/chunk-LVGBLZM2.js +0 -1
  295. package/dist/chunk-MGKAO4EK.js +0 -7
  296. package/dist/chunk-NSG4C6BF.js +0 -23
  297. package/dist/chunk-VGTCGNRX.js +0 -18
  298. package/dist/chunk-WM7H7WTY.js +0 -3
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel } from './node-Dd6wHSib.cjs';
1
+ import { a as Node, V as VersioningLevel } from './node-BVV7G1bq.cjs';
2
2
 
3
3
  type ReactiveLogOptions<T> = {
4
4
  name?: string;
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel } from './node-Dd6wHSib.js';
1
+ import { a as Node, V as VersioningLevel } from './node-BVV7G1bq.js';
2
2
 
3
3
  type ReactiveLogOptions<T> = {
4
4
  name?: string;
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-Dd6wHSib.cjs';
1
+ import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-BVV7G1bq.js';
2
2
 
3
3
  type ReactiveMapOptions<K, V> = {
4
4
  /** Optional registry name for `describe()` / debugging. */
@@ -6,6 +6,10 @@ type ReactiveMapOptions<K, V> = {
6
6
  /**
7
7
  * LRU cap. When set, evicts least-recently-used keys after inserts that exceed this size.
8
8
  * Forwarded to the default `NativeMapBackend`. Ignored if a custom `backend` is provided.
9
+ *
10
+ * **Mutually exclusive with `retention`** — the LRU cap is "youngest-access wins,"
11
+ * score-based retention is "highest-score wins." Configuring both would make
12
+ * eviction nondeterministic; construction throws if both are set.
9
13
  */
10
14
  maxSize?: number;
11
15
  /**
@@ -24,7 +28,61 @@ type ReactiveMapOptions<K, V> = {
24
28
  * monotonic version counter, or `1` for V1 + content-addressed cid.
25
29
  */
26
30
  versioning?: VersioningLevel;
31
+ /**
32
+ * Score-based retention policy. After every mutation, each live entry is
33
+ * scored; entries below `archiveThreshold` and / or over `maxSize` (lowest-
34
+ * scored first) are archived via `onArchive` before being removed.
35
+ *
36
+ * Retention replaces the ad-hoc "tierClassifier effect writing back to its
37
+ * own store dep" pattern — the feedback cycle is gone because archival is
38
+ * part of the atomic mutation, not a second reactive wave.
39
+ *
40
+ * Mutually exclusive with top-level `maxSize` (LRU). Pass one or the other.
41
+ */
42
+ retention?: ReactiveMapRetention<K, V>;
27
43
  } & Omit<NodeOptions, "initial" | "describeKind" | "equals" | "versioning">;
44
+ /**
45
+ * Score-based retention policy for {@link reactiveMap}. Evaluated synchronously
46
+ * on every successful mutation (`set` / `setMany` / `delete` / `clear` /
47
+ * `pruneExpired`). Entries are archived in ascending score order until the
48
+ * map satisfies both constraints:
49
+ *
50
+ * 1. Every remaining entry has `score >= archiveThreshold` (if set).
51
+ * 2. Total entry count `<= maxSize` (if set).
52
+ *
53
+ * At least one of `archiveThreshold` / `maxSize` must be set; otherwise there's
54
+ * no eviction trigger.
55
+ *
56
+ * **Archival order.** When multiple entries are candidates for archival in the
57
+ * same mutation, they are archived in ascending score order (lowest first). On
58
+ * score ties, iteration order (insertion order in the default backend) is the
59
+ * tiebreak.
60
+ *
61
+ * **No recursion.** Archival deletes happen on the backend directly — they do
62
+ * NOT re-enter the retention evaluator. The one-pass scan collects archival
63
+ * candidates against the post-mutation snapshot before removing them.
64
+ *
65
+ * @category extra
66
+ */
67
+ type ReactiveMapRetention<K, V> = {
68
+ /** Score entry — higher is kept. Should be a pure function of `(key, value)`. */
69
+ score: (key: K, value: V) => number;
70
+ /** Below-threshold entries are archived. Omit for pure `maxSize`-based retention. */
71
+ archiveThreshold?: number;
72
+ /**
73
+ * Cap on live entry count. Over this, the lowest-scored entries are
74
+ * archived until the size fits. Omit for pure threshold-based retention.
75
+ */
76
+ maxSize?: number;
77
+ /**
78
+ * Synchronous callback fired **before** archival deletion. Receives the
79
+ * key, value, and computed score. Callers typically persist the entry to
80
+ * a cold tier here (`await permanent.set(key, value)` — async is fine but
81
+ * the archival deletion happens synchronously after this callback
82
+ * returns).
83
+ */
84
+ onArchive?: (key: K, value: V, score: number) => void;
85
+ };
28
86
  type ReactiveMapBundle<K, V> = {
29
87
  /** Emits `ReadonlyMap<K, V>` on each structural change (two-phase). */
30
88
  entries: Node<ReadonlyMap<K, V>>;
@@ -235,4 +293,4 @@ declare class NativeMapBackend<K, V> implements MapBackend<K, V> {
235
293
  */
236
294
  declare function reactiveMap<K, V>(options?: ReactiveMapOptions<K, V>): ReactiveMapBundle<K, V>;
237
295
 
238
- export { type MapBackend as M, NativeMapBackend as N, type ReactiveMapBundle as R, type ReactiveMapOptions as a, type NativeMapBackendOptions as b, reactiveMap as r };
296
+ export { type MapBackend as M, NativeMapBackend as N, type ReactiveMapBundle as R, type ReactiveMapOptions as a, type NativeMapBackendOptions as b, type ReactiveMapRetention as c, reactiveMap as r };
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-Dd6wHSib.js';
1
+ import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-BVV7G1bq.cjs';
2
2
 
3
3
  type ReactiveMapOptions<K, V> = {
4
4
  /** Optional registry name for `describe()` / debugging. */
@@ -6,6 +6,10 @@ type ReactiveMapOptions<K, V> = {
6
6
  /**
7
7
  * LRU cap. When set, evicts least-recently-used keys after inserts that exceed this size.
8
8
  * Forwarded to the default `NativeMapBackend`. Ignored if a custom `backend` is provided.
9
+ *
10
+ * **Mutually exclusive with `retention`** — the LRU cap is "youngest-access wins,"
11
+ * score-based retention is "highest-score wins." Configuring both would make
12
+ * eviction nondeterministic; construction throws if both are set.
9
13
  */
10
14
  maxSize?: number;
11
15
  /**
@@ -24,7 +28,61 @@ type ReactiveMapOptions<K, V> = {
24
28
  * monotonic version counter, or `1` for V1 + content-addressed cid.
25
29
  */
26
30
  versioning?: VersioningLevel;
31
+ /**
32
+ * Score-based retention policy. After every mutation, each live entry is
33
+ * scored; entries below `archiveThreshold` and / or over `maxSize` (lowest-
34
+ * scored first) are archived via `onArchive` before being removed.
35
+ *
36
+ * Retention replaces the ad-hoc "tierClassifier effect writing back to its
37
+ * own store dep" pattern — the feedback cycle is gone because archival is
38
+ * part of the atomic mutation, not a second reactive wave.
39
+ *
40
+ * Mutually exclusive with top-level `maxSize` (LRU). Pass one or the other.
41
+ */
42
+ retention?: ReactiveMapRetention<K, V>;
27
43
  } & Omit<NodeOptions, "initial" | "describeKind" | "equals" | "versioning">;
44
+ /**
45
+ * Score-based retention policy for {@link reactiveMap}. Evaluated synchronously
46
+ * on every successful mutation (`set` / `setMany` / `delete` / `clear` /
47
+ * `pruneExpired`). Entries are archived in ascending score order until the
48
+ * map satisfies both constraints:
49
+ *
50
+ * 1. Every remaining entry has `score >= archiveThreshold` (if set).
51
+ * 2. Total entry count `<= maxSize` (if set).
52
+ *
53
+ * At least one of `archiveThreshold` / `maxSize` must be set; otherwise there's
54
+ * no eviction trigger.
55
+ *
56
+ * **Archival order.** When multiple entries are candidates for archival in the
57
+ * same mutation, they are archived in ascending score order (lowest first). On
58
+ * score ties, iteration order (insertion order in the default backend) is the
59
+ * tiebreak.
60
+ *
61
+ * **No recursion.** Archival deletes happen on the backend directly — they do
62
+ * NOT re-enter the retention evaluator. The one-pass scan collects archival
63
+ * candidates against the post-mutation snapshot before removing them.
64
+ *
65
+ * @category extra
66
+ */
67
+ type ReactiveMapRetention<K, V> = {
68
+ /** Score entry — higher is kept. Should be a pure function of `(key, value)`. */
69
+ score: (key: K, value: V) => number;
70
+ /** Below-threshold entries are archived. Omit for pure `maxSize`-based retention. */
71
+ archiveThreshold?: number;
72
+ /**
73
+ * Cap on live entry count. Over this, the lowest-scored entries are
74
+ * archived until the size fits. Omit for pure threshold-based retention.
75
+ */
76
+ maxSize?: number;
77
+ /**
78
+ * Synchronous callback fired **before** archival deletion. Receives the
79
+ * key, value, and computed score. Callers typically persist the entry to
80
+ * a cold tier here (`await permanent.set(key, value)` — async is fine but
81
+ * the archival deletion happens synchronously after this callback
82
+ * returns).
83
+ */
84
+ onArchive?: (key: K, value: V, score: number) => void;
85
+ };
28
86
  type ReactiveMapBundle<K, V> = {
29
87
  /** Emits `ReadonlyMap<K, V>` on each structural change (two-phase). */
30
88
  entries: Node<ReadonlyMap<K, V>>;
@@ -235,4 +293,4 @@ declare class NativeMapBackend<K, V> implements MapBackend<K, V> {
235
293
  */
236
294
  declare function reactiveMap<K, V>(options?: ReactiveMapOptions<K, V>): ReactiveMapBundle<K, V>;
237
295
 
238
- export { type MapBackend as M, NativeMapBackend as N, type ReactiveMapBundle as R, type ReactiveMapOptions as a, type NativeMapBackendOptions as b, reactiveMap as r };
296
+ export { type MapBackend as M, NativeMapBackend as N, type ReactiveMapBundle as R, type ReactiveMapOptions as a, type NativeMapBackendOptions as b, type ReactiveMapRetention as c, reactiveMap as r };
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-Dd6wHSib.js';
1
+ import { a as Node } from './node-BVV7G1bq.js';
2
2
 
3
3
  /**
4
4
  * Backoff strategies for {@link retry} (roadmap §3.1). Delays are in **nanoseconds**.
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-OL33ZI6R.js";import"./chunk-ESMPEKEV.js";import"./chunk-4VVTGLXJ.js";import"./chunk-KASHOCF5.js";import"./chunk-W4TSQ6RJ.js";import"./chunk-CK2E7BTU.js";import"./chunk-QYADASLV.js";export{c as CircuitOpenError,g as RateLimiterOverflowError,j as TimeoutError,d as circuitBreaker,k as fallback,h as rateLimiter,a as retry,b as retrySource,l as timeout,f as tokenBucket,e as withBreaker,i as withStatus};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-RWGJQQLT.js";import"./chunk-ESMPEKEV.js";import"./chunk-4VVTGLXJ.js";import"./chunk-UMH3HSP7.js";import"./chunk-7AJKUA36.js";import"./chunk-CK2E7BTU.js";import"./chunk-QYADASLV.js";export{c as CircuitOpenError,g as RateLimiterOverflowError,j as TimeoutError,d as circuitBreaker,k as fallback,h as rateLimiter,a as retry,b as retrySource,l as timeout,f as tokenBucket,e as withBreaker,i as withStatus};
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-Dd6wHSib.cjs';
1
+ import { a as Node } from './node-BVV7G1bq.cjs';
2
2
 
3
3
  /**
4
4
  * Backoff strategies for {@link retry} (roadmap §3.1). Delays are in **nanoseconds**.
@@ -1,4 +1,4 @@
1
- import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-Dd6wHSib.js';
1
+ import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-BVV7G1bq.js';
2
2
 
3
3
  /**
4
4
  * Sugar constructors over the raw `node()` primitive.
@@ -1,4 +1,4 @@
1
- import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-Dd6wHSib.cjs';
1
+ import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-BVV7G1bq.cjs';
2
2
 
3
3
  /**
4
4
  * Sugar constructors over the raw `node()` primitive.
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-DgohqXK-.cjs';
1
+ import { G as Graph, T as TopologyEvent } from './graph-C4Uxwv0T.cjs';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-Qjg9gWHI.js';
1
+ import { G as Graph, T as TopologyEvent } from './graph-CWeI0aHd.js';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
@@ -1,18 +1,6 @@
1
+ import { a as Node } from './node-BVV7G1bq.cjs';
1
2
  import { NodeInput } from './extra/sources.cjs';
2
3
 
3
- /**
4
- * Pluggable pricing for LLM adapters.
5
- *
6
- * The library ships the **shape** (types + computation helpers + registry
7
- * factory) and **zero model data**. Users populate a `PricingRegistry` with
8
- * the prices for the models they use — either by hand, from a curated table,
9
- * or by importing a third-party dataset (litellm JSON, etc.).
10
- *
11
- * Pricing is a pure function of raw `TokenUsage`. The library does not
12
- * know current prices, regional rates, tier thresholds, or promotional
13
- * discounts — those are all user domain.
14
- */
15
-
16
4
  /**
17
5
  * A rate per 1M tokens. Supports threshold-based tiering (Anthropic
18
6
  * long-context >200K, Gemini >200K) via optional `thresholdTokens` +
@@ -132,6 +120,33 @@ declare function createPricingRegistry(initial?: ReadonlyArray<readonly [provide
132
120
  declare function registryPricing(registry: PricingRegistry, defaultCurrency?: string): PricingFn;
133
121
  /** Compose multiple `PricingFn`s — first non-zero wins. Useful for registry layering. */
134
122
  declare function composePricing(...fns: readonly PricingFn[]): PricingFn;
123
+ /**
124
+ * Convenience: compute a {@link PriceBreakdown} directly from a
125
+ * {@link import("./capabilities.js").ModelCapabilities} object + usage.
126
+ *
127
+ * When callers look up capabilities themselves (via
128
+ * `capabilitiesRegistry.lookup(...)` or `adapter.capabilities?.(model)`),
129
+ * this helper skips the pricing-registry round-trip and computes the price
130
+ * from `capabilities.pricing` directly.
131
+ *
132
+ * Returns `zeroPrice()` when `capabilities.pricing` is undefined — never throws.
133
+ *
134
+ * @param capabilities - Model capabilities object (`capabilities.pricing` may be absent).
135
+ * @param usage - Per-call usage to price.
136
+ * @param opts - Pass-through to {@link computePrice}.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const cap = registry.lookup("anthropic", "claude-sonnet-4-6");
141
+ * const price = pricingFor(cap, resp.usage, { tier: "batch", withBreakdown: true });
142
+ * ```
143
+ *
144
+ * @category ai
145
+ */
146
+ declare function pricingFor(capabilities: ModelCapabilities | undefined, usage: TokenUsage, opts?: {
147
+ tier?: string;
148
+ withBreakdown?: boolean;
149
+ }): PriceBreakdown;
135
150
 
136
151
  /**
137
152
  * Pluggable model capabilities (roadmap §9.3d).
@@ -199,6 +214,18 @@ interface CapabilitiesRegistry {
199
214
  register(cap: ModelCapabilities): void;
200
215
  remove(provider: string, model: string): boolean;
201
216
  entries(): IterableIterator<ModelCapabilities>;
217
+ /**
218
+ * Reactive view of `(provider, model)` → `ModelCapabilities`. Re-emits
219
+ * whenever any `register()` / `remove()` touches the underlying store, so
220
+ * UIs and gated middleware (capability-aware retry, feature flags) can
221
+ * subscribe instead of polling. Prefix fallback mirrors the imperative
222
+ * `lookup()`: exact match first, then longest-prefix within provider.
223
+ */
224
+ lookupNode(provider: string, model: string): Node<ModelCapabilities | undefined>;
225
+ /** Reactive view of every registered entry. */
226
+ readonly entriesNode: Node<readonly ModelCapabilities[]>;
227
+ /** Reactive slice of entries for a single provider. */
228
+ byProvider(provider: string): Node<readonly ModelCapabilities[]>;
202
229
  }
203
230
  /** Create a fresh `CapabilitiesRegistry`. Optionally seed with entries. */
204
231
  declare function createCapabilitiesRegistry(initial?: readonly ModelCapabilities[]): CapabilitiesRegistry;
@@ -398,4 +425,4 @@ interface LLMAdapter {
398
425
  capabilities?(model?: string): ModelCapabilities | undefined;
399
426
  }
400
427
 
401
- export { type ChatMessage as C, type LLMAdapter as L, type ModelCapabilities as M, type PricingFn as P, type Rate as R, type StreamDelta as S, type TokenUsage as T, type LLMInvokeOptions as a, type LLMResponse as b, type ToolCall as c, type ToolDefinition as d, type CapabilitiesRegistry as e, type ModelFeatures as f, type ModelLimits as g, type ModelPricing as h, type PriceBreakdown as i, type PricingRegistry as j, type TieredRate as k, composePricing as l, computePrice as m, createCapabilitiesRegistry as n, createPricingRegistry as o, registryPricing as r, zeroPrice as z };
428
+ export { type ChatMessage as C, type LLMAdapter as L, type ModelCapabilities as M, type PricingFn as P, type Rate as R, type StreamDelta as S, type TokenUsage as T, type LLMInvokeOptions as a, type LLMResponse as b, type ToolCall as c, type ToolDefinition as d, type CapabilitiesRegistry as e, type ModelFeatures as f, type ModelLimits as g, type ModelPricing as h, type PriceBreakdown as i, type PricingRegistry as j, type TieredRate as k, composePricing as l, computePrice as m, createCapabilitiesRegistry as n, createPricingRegistry as o, pricingFor as p, registryPricing as r, zeroPrice as z };
@@ -1,18 +1,6 @@
1
+ import { a as Node } from './node-BVV7G1bq.js';
1
2
  import { NodeInput } from './extra/sources.js';
2
3
 
3
- /**
4
- * Pluggable pricing for LLM adapters.
5
- *
6
- * The library ships the **shape** (types + computation helpers + registry
7
- * factory) and **zero model data**. Users populate a `PricingRegistry` with
8
- * the prices for the models they use — either by hand, from a curated table,
9
- * or by importing a third-party dataset (litellm JSON, etc.).
10
- *
11
- * Pricing is a pure function of raw `TokenUsage`. The library does not
12
- * know current prices, regional rates, tier thresholds, or promotional
13
- * discounts — those are all user domain.
14
- */
15
-
16
4
  /**
17
5
  * A rate per 1M tokens. Supports threshold-based tiering (Anthropic
18
6
  * long-context >200K, Gemini >200K) via optional `thresholdTokens` +
@@ -132,6 +120,33 @@ declare function createPricingRegistry(initial?: ReadonlyArray<readonly [provide
132
120
  declare function registryPricing(registry: PricingRegistry, defaultCurrency?: string): PricingFn;
133
121
  /** Compose multiple `PricingFn`s — first non-zero wins. Useful for registry layering. */
134
122
  declare function composePricing(...fns: readonly PricingFn[]): PricingFn;
123
+ /**
124
+ * Convenience: compute a {@link PriceBreakdown} directly from a
125
+ * {@link import("./capabilities.js").ModelCapabilities} object + usage.
126
+ *
127
+ * When callers look up capabilities themselves (via
128
+ * `capabilitiesRegistry.lookup(...)` or `adapter.capabilities?.(model)`),
129
+ * this helper skips the pricing-registry round-trip and computes the price
130
+ * from `capabilities.pricing` directly.
131
+ *
132
+ * Returns `zeroPrice()` when `capabilities.pricing` is undefined — never throws.
133
+ *
134
+ * @param capabilities - Model capabilities object (`capabilities.pricing` may be absent).
135
+ * @param usage - Per-call usage to price.
136
+ * @param opts - Pass-through to {@link computePrice}.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const cap = registry.lookup("anthropic", "claude-sonnet-4-6");
141
+ * const price = pricingFor(cap, resp.usage, { tier: "batch", withBreakdown: true });
142
+ * ```
143
+ *
144
+ * @category ai
145
+ */
146
+ declare function pricingFor(capabilities: ModelCapabilities | undefined, usage: TokenUsage, opts?: {
147
+ tier?: string;
148
+ withBreakdown?: boolean;
149
+ }): PriceBreakdown;
135
150
 
136
151
  /**
137
152
  * Pluggable model capabilities (roadmap §9.3d).
@@ -199,6 +214,18 @@ interface CapabilitiesRegistry {
199
214
  register(cap: ModelCapabilities): void;
200
215
  remove(provider: string, model: string): boolean;
201
216
  entries(): IterableIterator<ModelCapabilities>;
217
+ /**
218
+ * Reactive view of `(provider, model)` → `ModelCapabilities`. Re-emits
219
+ * whenever any `register()` / `remove()` touches the underlying store, so
220
+ * UIs and gated middleware (capability-aware retry, feature flags) can
221
+ * subscribe instead of polling. Prefix fallback mirrors the imperative
222
+ * `lookup()`: exact match first, then longest-prefix within provider.
223
+ */
224
+ lookupNode(provider: string, model: string): Node<ModelCapabilities | undefined>;
225
+ /** Reactive view of every registered entry. */
226
+ readonly entriesNode: Node<readonly ModelCapabilities[]>;
227
+ /** Reactive slice of entries for a single provider. */
228
+ byProvider(provider: string): Node<readonly ModelCapabilities[]>;
202
229
  }
203
230
  /** Create a fresh `CapabilitiesRegistry`. Optionally seed with entries. */
204
231
  declare function createCapabilitiesRegistry(initial?: readonly ModelCapabilities[]): CapabilitiesRegistry;
@@ -398,4 +425,4 @@ interface LLMAdapter {
398
425
  capabilities?(model?: string): ModelCapabilities | undefined;
399
426
  }
400
427
 
401
- export { type ChatMessage as C, type LLMAdapter as L, type ModelCapabilities as M, type PricingFn as P, type Rate as R, type StreamDelta as S, type TokenUsage as T, type LLMInvokeOptions as a, type LLMResponse as b, type ToolCall as c, type ToolDefinition as d, type CapabilitiesRegistry as e, type ModelFeatures as f, type ModelLimits as g, type ModelPricing as h, type PriceBreakdown as i, type PricingRegistry as j, type TieredRate as k, composePricing as l, computePrice as m, createCapabilitiesRegistry as n, createPricingRegistry as o, registryPricing as r, zeroPrice as z };
428
+ export { type ChatMessage as C, type LLMAdapter as L, type ModelCapabilities as M, type PricingFn as P, type Rate as R, type StreamDelta as S, type TokenUsage as T, type LLMInvokeOptions as a, type LLMResponse as b, type ToolCall as c, type ToolDefinition as d, type CapabilitiesRegistry as e, type ModelFeatures as f, type ModelLimits as g, type ModelPricing as h, type PriceBreakdown as i, type PricingRegistry as j, type TieredRate as k, composePricing as l, computePrice as m, createCapabilitiesRegistry as n, createPricingRegistry as o, pricingFor as p, registryPricing as r, zeroPrice as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphrefly/graphrefly",
3
- "version": "0.29.0",
3
+ "version": "0.31.0",
4
4
  "packageManager": "pnpm@10.33.0+sha512.10568bb4a6afb58c9eb3630da90cc9516417abebd3fabbe6739f0ae795728da1491e9db5a544c76ad8eb7570f5c4bb3d6c637b2cb41bfdcdb47fa823c8649319",
5
5
  "description": "Reactive harness layer for agent workflows. Describe automations in plain language, trace every decision, enforce policies, persist checkpoints. Zero dependencies.",
6
6
  "repository": {
@@ -1,64 +0,0 @@
1
- import{a as mt,b as ct,d as pt,e as ft}from"./chunk-4OFIQ66T.js";import{e as dt}from"./chunk-VWPRPPKR.js";import{e as De}from"./chunk-Y53B6NS4.js";import{a as Ct,b as Pt,c as jt,d as _t,e as Dt,f as _e}from"./chunk-NSG4C6BF.js";import{a as Me,b as At,c as St,d as Et,e as It,f as Ot}from"./chunk-7JDLFI6N.js";import{c as it}from"./chunk-5Z4HDCO6.js";import{b as ut}from"./chunk-LVGBLZM2.js";import{b as rt,c as Re,d as nt,f as je}from"./chunk-OL33ZI6R.js";import{k as Z}from"./chunk-MGKAO4EK.js";import{a as X}from"./chunk-ESMPEKEV.js";import{P as lt,v as J}from"./chunk-5JDE5JHE.js";import{A as K,f as ot,m as w,w as at,y as st}from"./chunk-KASHOCF5.js";import{b as ge}from"./chunk-AUY2YKCO.js";import{D as se,E as v,F as Pe,G as x,H as ie,m as ae,o as W,p as Te}from"./chunk-W4TSQ6RJ.js";import{b as q,d as fe,i as re,j as Y}from"./chunk-CK2E7BTU.js";import{b as Nt}from"./chunk-QYADASLV.js";var _r={};Nt(_r,{AgentLoopGraph:()=>Oe,AllTiersExhaustedError:()=>Dt,BudgetExhaustedError:()=>Ne,ChatStreamGraph:()=>Ee,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>Xe,FallbackMissError:()=>It,LLMTimeoutError:()=>he,ReplayCacheMissError:()=>At,ToolRegistryGraph:()=>Ie,admissionFilter3D:()=>Cr,agentLoop:()=>Rr,agentMemory:()=>Ar,anthropicAdapter:()=>Ct,canonicalJson:()=>Et,cascadingLlmAdapter:()=>_e,chatStream:()=>ze,composePricing:()=>Kt,computePrice:()=>yt,contentGate:()=>kr,costMeterExtractor:()=>gr,createAdapter:()=>_t,createCapabilitiesRegistry:()=>Ft,createPricingRegistry:()=>$t,dryRunAdapter:()=>Me,dryRunPreset:()=>rr,fallbackAdapter:()=>Ot,fromLLM:()=>nr,frozenContext:()=>lr,gatedStream:()=>cr,gaugesAsContext:()=>Sr,googleAdapter:()=>Pt,graphFromSpec:()=>Er,handoff:()=>Lr,keywordFlagExtractor:()=>hr,knobsAsTools:()=>Or,llmConsolidator:()=>Qe,llmExtractor:()=>Ye,observableAdapter:()=>Gt,openAICompatAdapter:()=>jt,parseRateLimitFromError:()=>Ke,promptNode:()=>dr,redactor:()=>vr,registryPricing:()=>Wt,resilientAdapter:()=>tr,streamExtractor:()=>br,streamingPromptNode:()=>mr,suggestStrategy:()=>jr,systemPromptBuilder:()=>pr,toolCallExtractor:()=>Mr,toolRegistry:()=>Je,toolSelector:()=>wr,validateGraphDef:()=>Ze,withBreaker:()=>Be,withBudgetGate:()=>We,withDryRun:()=>Vt,withRateLimiter:()=>Ve,withReplayCache:()=>St,withRetry:()=>He,withTimeout:()=>qe,zeroPrice:()=>Ge});function Le(t,e){return`${t}::${e}`}function Ft(t){let e=new Map,r=new Map,o=n=>{e.set(Le(n.provider,n.id),n);let a=r.get(n.provider);a||(a=new Set,r.set(n.provider,a)),a.add(n.id)};if(t)for(let n of t)o(n);return{register:o,lookup(n,a){let s=e.get(Le(n,a));if(s)return s;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(Le(n,m));d&&(l={key:m,cap:d})}return l?.cap},remove(n,a){let s=e.delete(Le(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){return e.values()}}}function ne(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function le(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function gt(){return{input:{regular:0},output:{regular:0}}}function Gt(t,e){let r=e?.logMax??1e3,o=ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),n=v(null,{name:"adapterStats/lastCall"}),a=v(0,{name:"adapterStats/totalCalls"}),s=v(0,{name:"adapterStats/totalInputTokens"}),i=v(0,{name:"adapterStats/totalOutputTokens"}),l=p=>{o.append(p),n.emit(p),a.emit((a.cache??0)+1),s.emit((s.cache??0)+ne(p.usage)),i.emit((i.cache??0)+le(p.usage))},m=()=>{o.clear(),n.emit(null),a.emit(0),s.emit(0),i.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(p,c){let f=W(),y=Te(),g=t.invoke(p,c),T=b=>{let A=W();return l({timestamp:A,wallClock:y,provider:t.provider,model:t.model??c?.model??b.model??"",tier:c?.tier??b.tier,usage:b.usage??Fe(),latencyMs:Math.max(0,(A-f)/1e6),method:"invoke"}),b};if(g!=null&&typeof g.then=="function")return g.then(T);if(g!=null&&typeof g=="object"&&"content"in g)return T(g);let C=!1;return x([w(g)],([b])=>b==null||C?b:(C=!0,T(b)),{name:"adapterStats/invokeTap"})},async*stream(p,c){let f=W(),y=Te(),g;try{for await(let C of t.stream(p,c))C.type==="usage"&&(g=C.usage),yield C;let T=W();l({timestamp:T,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(T-f)/1e6),method:"stream"})}catch(T){let C=W(),b=T;throw l({timestamp:C,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(C-f)/1e6),method:"stream",error:{type:b?.name??"Error",message:b?.message??String(T)}}),T}}},stats:{lastCall:n,allCalls:o,totalCalls:a,totalInputTokens:s,totalOutputTokens:i,reset:m}}}function Fe(){return{input:{regular:0},output:{regular:0}}}function Bt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ge(t="USD"){return{total:0,currency:t}}function yt(t,e,r){let o=ne(t),n=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,i=0,l=(g,T,C)=>{if(!T||C==null)return;let b=Bt(C,o),A=T*b/1e6;i+=A,a&&(s[g]=(s[g]??0)+A)},m=t.input,d=e.input;if(d&&(l("input.regular",m.regular,d.regular),l("input.cacheRead",m.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",m.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",m.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",m.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",m.audio??0,d.audio),l("input.image",m.image??0,d.image),l("input.video",m.video??0,d.video),l("input.toolUse",m.toolUse??0,d.toolUse),m.extensions&&d.extensions))for(let[g,T]of Object.entries(m.extensions))l(`input.ext.${g}`,T,d.extensions[g]);let u=t.output,p=e.output;if(p&&(l("output.regular",u.regular,p.regular),l("output.reasoning",u.reasoning??0,p.reasoning),l("output.audio",u.audio??0,p.audio),l("output.predictionAccepted",u.predictionAccepted??0,p.predictionAccepted),l("output.predictionRejected",u.predictionRejected??0,p.predictionRejected),u.extensions&&p.extensions))for(let[g,T]of Object.entries(u.extensions))l(`output.ext.${g}`,T,p.extensions[g]);let c=r?.tier;if(c&&e.tierMultipliers){let g=e.tierMultipliers[c];if(g!=null&&(i*=g,a))for(let T of Object.keys(s))s[T]*=g}let f=t.auxiliary,y=e.auxiliary;if(f&&y)for(let[g,T]of Object.entries(f)){let C=y[g];if(C==null||!T)continue;let b=T*C;i+=b,a&&(s[`auxiliary.${g}`]=b)}return a?{total:i,currency:n,breakdown:s}:{total:i,currency:n}}function we(t,e){return`${t}::${e}`}function $t(t){let e=new Map,r=new Map,o=(n,a,s)=>{e.set(we(n,a),{provider:n,model:a,pricing:s});let i=r.get(n);i||(i=new Set,r.set(n,i)),i.add(a)};if(t)for(let[n,a,s]of t)o(n,a,s);return{register:o,lookup(n,a){let s=e.get(we(n,a));if(s)return s.pricing;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(we(n,m));d&&(l={key:m,pricing:d.pricing})}return l?.pricing},remove(n,a){let s=e.delete(we(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){let n=e.values();return(function*(){for(let{provider:a,model:s,pricing:i}of n)yield[a,s,i]})()}}}function Wt(t,e="USD"){return(r,o)=>{let n=t.lookup(o.provider,o.model);return n?yt(r,n,{tier:o.tier,withBreakdown:o.withBreakdown}):Ge(e)}}function Kt(...t){return(e,r)=>{for(let o of t){let n=o(e,r);if(n.total!==0)return n}return t.length>0?t[0](e,r):Ge()}}function Be(t,e={}){let r=e.breaker??nt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){if(!r.canExecute())throw new Re;try{let s=await Promise.resolve(t.invoke(n,a));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(n,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(n,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}},breaker:r}}var Ne=class extends Error{constructor(r,o,n){super(`Budget exhausted: ${r} (limit=${o}, observed=${n})`);this.which=r;this.limit=o;this.observed=n}name="BudgetExhaustedError"},$e=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ht=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function We(t,e){let r=ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),o=v(ht(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),n=x([o],([d])=>{let u=d;return!(e.caps.calls!=null&&u.calls>=e.caps.calls||e.caps.inputTokens!=null&&u.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&u.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&u.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(K(n),e.onExhausted!=null){let d=e.onExhausted,u=!1,p=!0;n.subscribe(c=>{for(let f of c)if(f[0]===q){let y=f[1];if(u&&p&&y===!1){let g=bt(o.cache??$e,e.caps);g&&d(g)}p=y,u=!0}})}let a=()=>{if(n.cache===!1){let d=o.cache??$e,u=bt(d,e.caps);return new Ne(u??"budget",e.caps[u??"calls"]??0,Ut(d,u??"calls"))}},s=(d,u)=>{let p=t.provider,c={timestamp:W(),wallClock:Te(),provider:p,model:u.model,tier:u.tier,usage:d,latencyMs:u.latencyMs,method:u.method,...u.error?{error:u.error}:{}};r.append(c);let f=o.cache??$e,y=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:p,tier:u.tier}).total:f.usd;o.emit({calls:f.calls+1,inputTokens:f.inputTokens+ne(d),outputTokens:f.outputTokens+le(d),usd:y})},i=()=>{r.clear(),o.emit(ht())},l=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,u){let p=a();if(p)return Promise.reject(p);let c=W(),f=t.invoke(d,u),y=T=>{let C=Math.max(0,(W()-c)/1e6);return s(T.usage??l(),{model:t.model??u?.model??T.model??"",tier:u?.tier??T.tier,latencyMs:C,method:"invoke"}),T};if(f!=null&&typeof f.then=="function")return f.then(y);if(f!=null&&typeof f=="object"&&"content"in f)return y(f);let g=!1;return x([w(f)],([T])=>T==null||g?T:(g=!0,y(T)),{name:"budgetGate/invokeTap"})},async*stream(d,u){let p=a();if(p)throw p;let c=W(),f;try{for await(let y of t.stream(d,u))y.type==="usage"&&(f=y.usage),yield y;s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream"})}catch(y){let g=y;throw s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(y)}}),y}}},budget:{totals:o,isOpen:n,log:r,reset:i}}}function bt(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function Ut(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function Vt(t,e){let r=e.mock??Me({provider:t.provider,model:t.model}),o=typeof e.enabled=="boolean"?e.enabled:void 0,n=o===void 0?w(e.enabled):void 0,a;n&&(a=K(n));let s=()=>o!==void 0?o:!!n?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(m,d){return s()?r.invoke(m,d):t.invoke(m,d)},stream(m,d){return s()?r.stream(m,d):t.stream(m,d)}},dispose:()=>{a&&(a(),a=void 0)}}}function Ke(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,o=Ht(e.headers);if(r!==429&&r!==503&&!Xt(e.message))return;let n={},a=o("retry-after"),s=zt(a);s!=null&&(n.retryAfterMs=s);let i=o("anthropic-ratelimit-requests-reset");if(i){let c=Tt(i);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let l=o("anthropic-ratelimit-tokens-reset");if(l){let c=Tt(l);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let m=Ce(o,"x-ratelimit-limit-requests");m!=null&&(n.rpmCap=m);let d=Ce(o,"x-ratelimit-limit-tokens");d!=null&&(n.tpmCap=d);let u=Ce(o,"x-ratelimit-remaining-requests"),p=Ce(o,"x-ratelimit-remaining-tokens");if(u!=null&&m!=null&&m>0&&(n.usageHint??={},n.usageHint.rpm=1-u/m),p!=null&&d!=null&&d>0&&(n.usageHint??={},n.usageHint.tpm=1-p/d),n.retryAfterMs==null&&e.message){let c=Yt(e.message);c!=null&&(n.retryAfterMs=c)}return e.headers&&(n.metadata={headers:qt(e.headers)}),n.retryAfterMs==null&&n.rpmCap==null&&n.tpmCap==null&&n.usageHint==null?n.metadata?n:void 0:n}function Ht(t){if(!t)return()=>{};if(typeof t.get=="function"){let o=t;return n=>o.get(n)??o.get(n.toLowerCase())??void 0}let e=t,r={};for(let[o,n]of Object.entries(e)){let a=Array.isArray(n)?n.join(", "):n;a!=null&&(r[o.toLowerCase()]=a)}return o=>r[o.toLowerCase()]}function qt(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,o)=>{e[o]=r}),e;for(let[r,o]of Object.entries(t))o!=null&&(e[r]=Array.isArray(o)?o.join(", "):o);return e}function Ce(t,e){let r=t(e);if(r==null)return;let o=Number(r);return Number.isFinite(o)?o:void 0}function zt(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let o=Date.parse(e);if(Number.isFinite(o)){let n=o-Date.now();if(n>0)return n}}function Tt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Jt=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Yt(t){let e=Jt.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let o=(e[2]??"s").toLowerCase();if(o==="ms")return r;if(o.startsWith("s"))return r*1e3;if(o.startsWith("m"))return r*6e4}var Qt=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Xt(t){return!!t&&Qt.test(t)}function Ue(t){let e=new Error(t);return e.name="AbortError",e}function kt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,o=t.rpm!=null?w(t.rpm):v(Number.POSITIVE_INFINITY),n=t.tpm!=null?w(t.tpm):v(Number.POSITIVE_INFINITY),a=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=v({},{name:"adaptiveRateLimiter/lastSignal"}),l=x([o,a],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),m=x([n,s],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=ye(Number(o.cache??Number.POSITIVE_INFINITY),e),u=ye(Number(n.cache??Number.POSITIVE_INFINITY),e),p=!1,c=!1,f=l.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(d=ye(P,e),p=!1):P===1/0?(d=ye(1/0,e),p=!1):P<=0&&(p=!0)}}),y=m.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(u=ye(P,e),c=!1):P===1/0?(u=ye(1/0,e),c=!1):P<=0&&(c=!0)}}),g=0,T=new X,C=new X,b;t.adaptation!=null&&(b=w(t.adaptation).subscribe(E=>{for(let P of E)P[0]===q&&A(P[1])}));function A(L){if(i.emit(L),L.rpmCap!=null&&Number.isFinite(L.rpmCap)&&L.rpmCap>=0&&(a.emit(L.rpmCap),Number.isFinite(r)&&r>0&&T.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),L.tpmCap!=null&&Number.isFinite(L.tpmCap)&&L.tpmCap>=0&&(s.emit(L.tpmCap),Number.isFinite(r)&&r>0&&C.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),L.retryAfterMs!=null&&L.retryAfterMs>0){let E=W()+L.retryAfterMs*1e6;E>g&&(g=E)}}let O=v(0,{name:"adaptiveRateLimiter/pending"}),U=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),B=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),V=L=>{O.emit((O.cache??0)+L)},_=()=>{U.emit(d.available()),B.emit(u.available())};async function H(L={}){let E=L.requestCost??1,P=L.tokenCost??0,M=L.signal;V(1);try{for(;;){if(M?.aborted)throw Ue("AdaptiveRateLimiter.acquire aborted");let h=W();if(g>h){let ee=Math.ceil((g-h)/1e6);await Ae(ee,M);continue}if(E>0&&p||P>0&&c){await Ae(250,M);continue}let k=d,R=u;if(!k.tryConsume(E)){await Ae(Mt(k,E),M);continue}if(!(P>0?R.tryConsume(P):!0)){k.putBack(E),await Ae(Mt(R,P),M);continue}_();return}}finally{V(-1)}}function $(L){L>0?u.tryConsume(L):L<0&&u.putBack(-L),_()}function F(){f(),y(),b?.(),T.cancel(),C.cancel()}return{effectiveRpm:l,effectiveTpm:m,lastSignal:i,pending:O,rpmAvailable:U,tpmAvailable:B,acquire:H,recordUsage:$,recordSignal:A,dispose:F}}function ye(t,e){if(!Number.isFinite(t)||t===1/0)return je(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),o=t/60;return je(r,o)}function Mt(t,e){let r=t.available(),o=Math.max(0,e-r);return o<=0?25:Math.min(5e3,Math.max(50,o*100))}function Ae(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ue("AdaptiveRateLimiter.acquire aborted")):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Ue("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ve(t,e={}){let r=e.limiter??kt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),o=(s,i)=>e.costFn?e.costFn(s,i):0,n=s=>{let i=Ke(s);i&&r.recordSignal(i)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=t.invoke(s,i),d=await Zt(m),u=d.usage??gt(),c=ne(u)+le(u)-l;return c>0&&r.recordUsage(c),d}catch(m){throw n(m),m}},async*stream(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=0;for await(let u of t.stream(s,i))u.type==="usage"&&(m=ne(u.usage)+le(u.usage)),yield u;let d=m-l;d>0&&r.recordUsage(d)}catch(m){throw n(m),m}}},limiter:r}}async function Zt(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await at(w(t))}function Se(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function vt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Se()):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Se())},e.addEventListener("abort",a,{once:!0}))})}function He(t,e={}){let r=e.attempts??3,o=e.baseDelayMs??500,n=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,i=e.shouldRetry??er,l=e.retryStreaming??!0,m=(d,u)=>{if(a==="decorrelated"){let y=Math.min(n,Math.max(o,u*3));return o+Math.random()*(y-o)}let p=a==="exp"?o*2**(d-1):o*d,c=Math.min(n,p);if(!s)return c;let f=c*(.5+Math.random());return Math.min(n,f)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,u){if(u?.signal?.aborted)throw Se();let p,c=o;for(let f=1;f<=r;f++)try{return await Promise.resolve(t.invoke(d,u))}catch(y){if(p=y,f>=r||!i(y,f))throw y;let g=m(f,c);c=g,await vt(g,u?.signal)}throw p},async*stream(d,u){if(u?.signal?.aborted)throw Se();if(!l){for await(let f of t.stream(d,u))yield f;return}let p,c=o;for(let f=1;f<=r;f++){let y=!1;try{for await(let g of t.stream(d,u))y=!0,yield g;return}catch(g){if(p=g,y||f>=r||!i(g,f))throw g;let T=m(f,c);c=T,await vt(T,u?.signal)}}throw p}}}function er(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var he=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function qe(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=n=>{let a=new AbortController,s=!1,i;n&&(n.aborted?a.abort(n.reason):(i=()=>a.abort(n.reason),n.addEventListener("abort",i,{once:!0})));let l=new X;return l.start(e,()=>{s=!0,a.abort(new he(e))}),{signal:a.signal,cancel:()=>{l.cancel(),n&&i&&n.removeEventListener("abort",i)},timedOut:()=>s}},o=(n,a)=>{if(!a||n instanceof he)throw n;let s=n;if(s?.name==="AbortError"||s?.name==="DOMException"&&Number(s.code)===20||n?.message==="aborted"){let l=new he(e);throw l.cause=n,l}throw n};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{return await Promise.resolve(t.invoke(n,{...a,signal:s}))}catch(m){return o(m,l())}finally{i()}},async*stream(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{for await(let m of t.stream(n,{...a,signal:s}))yield m}catch(m){o(m,l())}finally{i()}}}}function tr(t,e={}){let r={adapter:t},o=t;if(e.rateLimit){let n=Ve(o,e.rateLimit);o=n.adapter,r.rateLimiter=n.limiter}if(e.budget){let n=We(o,e.budget);o=n.adapter,r.budget=n.budget}if(e.breaker){let n=Be(o,e.breaker);o=n.adapter,r.breaker=n.breaker}if(e.timeoutMs!=null&&(o=qe(o,e.timeoutMs)),e.retry&&(o=He(o,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let n={};e.onFallback&&(n.onFallback=e.onFallback),e.onExhausted&&(n.onExhausted=e.onExhausted),o=_e([{name:e.name??"primary",adapter:o},{name:"fallback",adapter:e.fallback}],n)}return r.adapter=o,r}function rr(){return Me()}function nr(t,e,r){let o=w(e);return J(o,a=>{if(!a||a.length===0)return v(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return it("ai",t,e)}function or(t){return t!=null&&typeof t.then=="function"}function ar(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function sr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ir=3e4;function xt(t,e){if(t.status==="settled"){let o=t.cache;if(o!==void 0)return Promise.resolve(o)}let r=e?.timeoutMs??ir;return new Promise((o,n)=>{let a=new X,s=t.subscribe(i=>{for(let l of i){if(l[0]===q){a.cancel(),s(),o(l[1]);return}if(l[0]===Y){a.cancel(),s(),n(l[1]);return}if(l[0]===re){a.cancel(),s(),n(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),n(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function ue(t){return or(t)?ue(await t):ar(t)?xt(t):sr(t)?xt(w(t)):t}function de(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function lr(t,e){let r=w(t),o=e?.refreshTrigger!=null?w(e.refreshTrigger):null;return o==null?se([r],(n,a,s)=>{if(s.store.emitted===!0)return;let l=n[0],m=l!=null&&l.length>0?l.at(-1):s.prevData[0];if(m!==void 0)return s.store.emitted=!0,a.emit(m),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")}):se([r,o],(n,a,s)=>{let i=n[1];if(!(i!=null&&i.length>0))return;let m=n[0],d=m!=null&&m.length>0?m.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")})}function ur(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function dr(t,e,r,o){let n=o?.format??"text",a=o?.retries??0,s=o?.cache??!1,i=s?new Map:null,l=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p},{name:o?.name?`${o.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(l,d=>{if(!d||d.length===0)return v(null);let u=s?JSON.stringify(d.map(c=>[c.role,c.content])):"";if(i?.has(u))return v(i.get(u));async function p(c){try{let f=await new Promise((T,C)=>{let b=t.invoke(d,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt});b&&typeof b.then=="function"?b.then(T,C):b&&typeof b.subscribe=="function"?T(b.cache):T(b)}),y=ur(f),g;return n==="json"?g=JSON.parse(de(y)):g=y,i?.set(u,g),g}catch(f){if(c>0)return p(c-1);throw f}}return p(a)})}function mr(t,e,r,o){let n=o?.name??"llm",a=o?.format??"text",s=De(`${n}/stream`),i=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p}),l=J(i,d=>{let u=d;if(!u||u.length===0)return v(null);let p=new AbortController;async function*c(){let f="",y=0;try{for await(let T of t.stream(u,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt,signal:p.signal})){if(T.type!=="token")continue;let C=T.delta;f+=C,s.publish({source:n,token:C,accumulated:f,index:y++})}let g;if(a==="json")try{g=JSON.parse(de(f))}catch{g=null}else g=f;yield g}finally{p.abort()}}return w(c())}),m=K(l);return{output:l,stream:s,dispose:()=>{m(),s.destroy()}}}function cr(t,e,r,o,n,a){let s=v(0,{name:`${e}/cancel`}),i=0,l=[...o,s],m=a?.name??e,d=a?.format??"text",u=De(`${m}/stream`),p=x(l,b=>{let A=b.slice(0,-1);if(A.some(B=>B==null))return[];let O=typeof n=="string"?n:n(...A);if(!O)return[];let U=[];return a?.systemPrompt&&U.push({role:"system",content:a.systemPrompt}),U.push({role:"user",content:O}),U}),c=J(p,b=>{let A=b;if(!A||A.length===0)return v(null);let O=new AbortController;async function*U(){let B="",V=0;try{for await(let H of r.stream(A,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:O.signal})){if(H.type!=="token")continue;let $=H.delta;B+=$,u.publish({source:m,token:$,accumulated:B,index:V++})}let _;if(d==="json")try{_=JSON.parse(de(B))}catch{_=null}else _=B;yield _}finally{O.abort()}}return w(U())}),f=K(c),y=x([c],([b])=>{if(b!=null)return b},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let g=dt(t,`${e}/gate`,`${e}/raw`,a?.gate),T=g.reject.bind(g),C={...g,reject(b=1){T(b),s.emit(++i)}};return{output:g.node,stream:u,gate:C,dispose:()=>{f(),u.destroy()}}}function pr(t,e){let r=e?.separator??`
2
-
3
- `,o=t.map(s=>typeof s=="string"?v(s):w(s)),n=x(o,s=>s.filter(i=>i!=null&&i!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=K(n);return Object.assign(n,{dispose:a})}var fr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function gr(t,e){let r=e?.charsPerToken??4;return x([t.latest],([o])=>{if(o==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let n=o,a=n.accumulated.length;return{chunkCount:n.index+1,charCount:a,estimatedTokens:Math.ceil(a/r)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:N("cost_meter_extractor"),equals:fr})}var yr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.label!==n.label||o.pattern!==n.pattern||o.match!==n.match||o.position!==n.position)return!1}return!0};function hr(t,e){let r=e.maxPatternLength??128;return x([t.latest],([o],n)=>{if(o==null)return[];let a=o.accumulated;"flags"in n.store||(n.store.flags=[],n.store.scannedTo=0);let s=n.store.flags,i=n.store.scannedTo,l=Math.max(0,i-r),m=a.slice(l),d=!1;for(let{pattern:u,label:p}of e.patterns){let c=new RegExp(u.source,`${u.flags.replace("g","")}g`);for(let f of m.matchAll(c)){let y=l+f.index;y+f[0].length<=i||(s.push({label:p,pattern:u,match:f[0],position:y}),d=!0)}}return n.store.scannedTo=a.length,d?[...s]:s.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:yr})}function br(t,e,r){return x([t.latest],([o])=>o==null?null:e(o.accumulated),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Tr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.startIndex!==n.startIndex||o.name!==n.name||o.raw!==n.raw)return!1}return!0};function Mr(t,e){return x([t.latest],([r],o)=>{if(r==null)return[];let n=r.accumulated;"calls"in o.store||(o.store.calls=[],o.store.scanFrom=0);let a=o.store.calls,s=o.store.scanFrom,i=!1;for(;s<n.length;){let l=n.indexOf("{",s);if(l===-1){o.store.scanFrom=n.length;break}let m=0,d=-1,u=!1;for(let c=l;c<n.length;c++){let f=n[c];if(u)f==="\\"&&c+1<n.length?c++:f==='"'&&(u=!1);else if(f==='"')u=!0;else if(f==="{")m++;else if(f==="}"&&(m--,m===0)){d=c;break}}if(d===-1){o.store.scanFrom=l;break}let p=n.slice(l,d+1);try{let c=JSON.parse(p);typeof c.name=="string"&&c.arguments!=null&&typeof c.arguments=="object"&&(a.push({name:c.name,arguments:c.arguments,raw:p,startIndex:l}),i=!0)}catch{}s=d+1,o.store.scanFrom=s}return i?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Tr})}function kr(t,e,r,o){let n=r*(o?.hardMultiplier??1.5),a=typeof e!="function",s=[t.latest];return a&&s.push(e),x(s,i=>{let l=i[0];if(l==null)return"allow";let m=a?i[1]??0:e(l.accumulated);return m>=n?"block":m>=r?"review":"allow"},{name:o?.name??"content-gate",initial:"allow"})}function vr(t,e,r,o){let n=r??(()=>"[REDACTED]");function a(s){let i=s;for(let l of e){let m=l.global?l:new RegExp(l.source,`${l.flags}g`);i=i.replace(m,d=>n(d,l))}return i}return x([t.latest],([s])=>{if(s==null)return{source:"",token:"",accumulated:"",index:-1};let i=s,l=a(i.accumulated),m=a(i.token);return{source:i.source,token:m,accumulated:l,index:i.index}},{name:o?.name??"redactor"})}var Ee=class extends Z{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=ge([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=x([this.messages],([o])=>{let n=o;return n.length===0?null:n[n.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(K(this.latest)),this.messageCount=x([this.messages],([o])=>o.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(K(this.messageCount))}append(e,r,o){this._log.append({role:e,content:r,...o})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ze(t,e){return new Ee(t,e)}var Ie=class extends Z{definitions;schemas;constructor(e,r={}){super(e,r.graph),this.definitions=v(new Map,{name:"definitions",describeKind:"state",meta:N("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=x([this.definitions],([o])=>[...(o??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(K(this.schemas))}register(e){let r=this.definitions.cache,o=new Map(r);o.set(e.name,e),this.definitions.emit(o)}unregister(e){let r=this.definitions.cache;if(!r.has(e))return;let o=new Map(r);o.delete(e),this.definitions.emit(o)}async execute(e,r){let n=this.definitions.cache.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let a=n.handler(r);return ue(a)}getDefinition(e){return this.definitions.cache?.get(e)}};function Je(t,e){return new Ie(t,e)}var Oe=class extends Z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=ze(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=Je(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let M of r.tools)this.tools.register(M);this.status=v("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=v(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=v(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let o=0,n=this.turn.subscribe(M=>{for(let h of M)h[0]===q&&(o=h[1])}),a=!1,s=this.aborted.subscribe(M=>{for(let h of M)h[0]===q&&(a=h[1])}),i=r.adapter,l=r.systemPrompt,m=r.model,d=r.temperature,u=r.maxTokens,p=r.maxTurns??10,c=r.stopWhen,f=this.chat,y=this.tools,g=this.status,T=this.turn,C=this.aborted,b=se([g],(M,h,k)=>{if(ke(M,k.prevData,0,"idle")!=="thinking"||a||o>=p){h.down([[fe]]);return}let I=f.allMessages();if(I.length===0){h.down([[fe]]);return}let S=y.schemas.cache??[];h.emit({messages:I,tools:S})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(b,M=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),w(Promise.resolve(i.invoke(M.messages,{tools:M.tools.length>0?M.tools:void 0,systemPrompt:l,model:m,temperature:d,maxTokens:u,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),O=v(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=O;let U=se([O,g],(M,h,k)=>{let R=ke(M,k.prevData,0,null);if(ke(M,k.prevData,1,"idle")!=="acting"){h.down([[fe]]);return}let S=R?.toolCalls;if(S==null||S.length===0){h.down([[fe]]);return}h.emit(S)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),B=r.interceptToolCalls?r.interceptToolCalls(U):U;this.toolCalls=B;let V=(M,h)=>{if(M===h)return!0;if(M.length!==h.length)return!1;for(let k=0;k<M.length;k++){let R=M[k],I=h[k];if(R?.id!==I?.id||R?.content!==I?.content)return!1}return!0},_=J(B,M=>{if(M==null||M.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let h=M.map(k=>xr(k,y));return x(h,k=>k.map((R,I)=>{let S=R;return S!=null&&typeof S=="object"&&"id"in S&&"content"in S?S:{id:M[I].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:V})});this.toolResults=_;let H=ie([A],([M])=>{if(a)return;let h=M,k=o+1,R=h.toolCalls!=null&&h.toolCalls.length>0,I=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),S=c?.(h)===!0,ee=k>=p,te=S||I||!R||ee?"done":"acting";ae(()=>{O.emit(h),g.emit(te),T.emit(k),f.append("assistant",h.content,{toolCalls:h.toolCalls})})}),$=ie([_],([M])=>{if(a)return;let h=M;if(h.length===0)return;let k=o>=p?"done":"thinking";ae(()=>{g.emit(k);for(let R of h)f.appendToolResult(R.id,R.content)})}),F=ie([C],([M])=>{M===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),L=K(H),E=K($),P=K(F);this._terminalResult=se([g,O],(M,h,k)=>{let R=ke(M,k.prevData,0,"idle"),I=ke(M,k.prevData,1,null);if(R==="done"){if(I!=null){h.emit({response:I,runVersion:this._runVersion});return}let S=new Error("agentLoop: aborted");S.name="AbortError",h.down([[Y,S]]);return}if(R==="error"){h.down([[Y,new Error("agentLoop: errored")]]);return}h.down([[fe]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(n),this.addDisposer(s),this.addDisposer(L),this.addDisposer(E),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let o=++this._runVersion;ae(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let n;if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}try{return(await st(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===o})).response}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function xr(t,e){let r=rt(()=>w(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),o=x([r],([n])=>({id:t.id,content:typeof n=="string"?n:JSON.stringify(n)}));return lt(o,n=>({id:t.id,content:JSON.stringify({error:String(n)})}))}function ke(t,e,r,o){let n=t[r];if(n!=null&&n.length>0)return n[n.length-1];let a=e[r];return a!==void 0?a:o}function Rr(t,e){return new Oe(t,e)}function Lr(t,e,r){let o=w(t),n=r?.condition!=null?w(r.condition):null,a=v(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(n==null)return J(o,i=>{if(i==null)return a;let l=v(i);return e(l)});let s=x([o,n],([i,l])=>({v:i,open:l===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:i,open:l})=>{if(i==null)return a;if(!l)return v(i);let m=v(i);return e(m)})}function wr(t,e,r){let o=w(t),n=e.map(s=>w(s)),a=[o,...n];return x(a,s=>{let i=s[0]??[],l=s.slice(1);return i.filter(m=>{for(let d of l)if(d!=null&&!d(m))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),equals:(s,i)=>{let l=s,m=i;if(l.length!==m.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==m[d])return!1;return!0}})}function Nr(t){return{persistence:.5,structure:.5,personalValue:.5}}function Cr(t={}){let e=t.scoreFn??Nr,r=t.persistenceThreshold??.3,o=t.personalValueThreshold??.3,n=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<o||n&&s.structure<=0)}}function Ye(t,e){return(r,o)=>{let n=[...o.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:n})}];return Pe(s=>{let i=!0,l=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=w(l).subscribe(u=>{if(!i)return;let p=!1;for(let c of u){if(p)break;if(c[0]===q){let f=c[1];try{let y=JSON.parse(f.content);s.emit(y),s.down([[re]])}catch{s.down([[Y,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else c[0]===Y?(s.down([[Y,c[1]]]),p=!0):c[0]===re?(s.down([[re]]),p=!0):s.down([[c[0],c[1]]])}});return()=>{d(),i=!1}})}}function Qe(t,e){return r=>{let o=[...r.entries()].map(([a,s])=>({key:a,value:s})),n=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:o})}];return Pe(a=>{let s=!0,i=e.adapter.invoke(n,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),m=w(i).subscribe(d=>{if(!s)return;let u=!1;for(let p of d){if(u)break;if(p[0]===q){let c=p[1];try{let f=JSON.parse(c.content);a.emit(f),a.down([[re]])}catch{a.down([[Y,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}u=!0}else p[0]===Y?(a.down([[Y,p[1]]]),u=!0):p[0]===re?(a.down([[re]]),u=!0):a.down([[p[0],p[1]]])}});return()=>{m(),s=!1}})}}var Xe=Math.LN2/604800;function ve(t){return t instanceof Map?t:new Map}function Ar(t,e,r){let o=new Z(t,r.graph),n=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=Ye(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,A)=>b==null?{upsert:[]}:a(b,A),i=e;if(r.admissionFilter){let b=w(e),A=r.admissionFilter;i=x([b],([O])=>{if(A(O))return O},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=Qe(r.consolidatePrompt,{adapter:r.adapter}));let m=r.consolidateTrigger;if(!m&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;m=ot(b,{period:b})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:m},u=ut(i,s,d);o.add(u.store.entries,{name:"store"}),o.add(u.compact,{name:"compact"}),o.add(u.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=pt({dimension:r.vectorDimensions}),o.add(p.entries,{name:"vectorIndex"}));let c=null;r.enableKnowledgeGraph&&(c=ft(`${t}-kg`),o.mount("kg",c));let f=null;if(r.tiers){let b=r.tiers,A=b.decayRate??Xe,O=b.maxActive??1e3,U=b.archiveThreshold??.1,B=b.permanentFilter??(()=>!1),V=ct({name:"permanent"});o.add(V.entries,{name:"permanent"});let _=new Set,H=h=>_.has(h)?"permanent":ve(u.store.entries.cache).has(h)?"active":"archived",$=(h,k)=>{_.add(h),V.upsert(h,k)},F=new Map,L=u.store.entries,E=r.context?w(r.context):v(null),P=ie([L,E],([h,k])=>{let R=ve(h),I=W(),S=[],ee=[];for(let[D,Q]of R){if(F.has(D)||F.set(D,I),B(D,Q)){ee.push({key:D,value:Q});continue}let z=r.score(Q,k),j=F.get(D)??I,G=Number(I-j)/1e9;mt(z,G,A)<U&&S.push(D)}for(let D of F.keys())R.has(D)||F.delete(D);for(let{key:D,value:Q}of ee)_.has(D)||$(D,Q);let te=R.size-_.size;if(te>O){let D=[...R.entries()].filter(([z])=>!_.has(z)).map(([z,j])=>({key:z,score:r.score(j,k)})).sort((z,j)=>z.score-j.score),Q=te-O;for(let z=0;z<Q&&z<D.length;z++){let j=D[z].key;S.includes(j)||S.push(j)}}S.length>0&&ae(()=>{for(let D of S)u.store.delete(D)})});n.push(P.subscribe(()=>{}));let M=null;b.archiveTier&&(M=o.attachStorage([b.archiveTier],b.archiveStorageOptions??{})),f={permanent:V,activeEntries:L,archiveHandle:M,tierOf:H,markPermanent:$}}if(p||c){let b=r.embedFn,A=r.entityFn,O=u.store.entries,U=ie([O],([B])=>{let V=ve(B);for(let[_,H]of V){if(p&&b){let $=b(H);$&&p.upsert(_,$,H)}if(c&&A){let $=A(_,H);if($){for(let F of $.entities??[])c.upsertEntity(F.id,F.value);for(let F of $.relations??[])c.link(F.from,F.to,F.relation,F.weight)}}}});n.push(U.subscribe(()=>{}))}let y=null,g=null,T=null,C=null;if(p||c){let b=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,O=r.budget??2e3,U=r.cost,B=r.score,V=r.contextOf,_=r.contextWeight??0,H=r.context?w(r.context):v(null),$=(M,h)=>{if(!M||!h)return 0;let k=Math.min(M.length,h.length),R=0;for(;R<k&&M[R]===h[R];)R++;return R},F=(M,h,k)=>{let R=new Map,I=[];if(p&&k.vector){I=p.search(k.vector,b);for(let j of I){let G=M.get(j.id);G&&R.set(j.id,{value:G,sources:new Set(["vector"])})}}let S=[];if(c){let j=[...k.entityIds??[],...R.keys()],G=new Set,me=j;for(let ce=0;ce<A;ce++){let oe=[];for(let be of me){if(G.has(be))continue;G.add(be);let xe=c.related(be);for(let wt of xe){let pe=wt.to;if(!G.has(pe)){oe.push(pe);let et=M.get(pe);if(et){let tt=R.get(pe);tt?tt.sources.add("graph"):R.set(pe,{value:et,sources:new Set(["graph"])}),S.push(pe)}}}}me=oe}}for(let[j,G]of M)R.has(j)||R.set(j,{value:G,sources:new Set(["store"])});let ee=k.context?.length??0,te=[];for(let[j,{value:G,sources:me}]of R){let ce=V?V(G):void 0,oe=B(G,h);if(_>0&&ee>0){let xe=$(k.context,ce);xe>0&&(oe=oe*(1+_*xe/ee))}let be=ce?{key:j,value:G,score:oe,sources:[...me],context:ce}:{key:j,value:G,score:oe,sources:[...me]};te.push(be)}te.sort((j,G)=>G.score-j.score);let D=[],Q=0;for(let j of te){let G=U(j.value);if(Q+G>O&&D.length>0)break;D.push(j),Q+=G}return{packed:D,trace:{vectorCandidates:I,graphExpanded:S,ranked:te,packed:D}}},L=v([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});o.add(L,{name:"retrieval"}),y=L;let E=v(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});o.add(E,{name:"retrievalTrace"}),g=E,T=M=>{let h=ve(u.store.entries.cache),{packed:k,trace:R}=F(h,H.cache,M);return ae(()=>{L.emit(k),E.emit(R)}),k},C=M=>{let h=w(M);return x([u.store.entries,H,h],([k,R,I])=>{if(I==null)return[];let S=ve(k);return F(S,R,I).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return o.addDisposer(()=>{for(let b of n)b();n.length=0}),Object.assign(o,{distillBundle:u,compact:u.compact,size:u.size,vectors:p,kg:c,memoryTiers:f,retrieval:y,retrievalTrace:g,retrieve:T,retrieveReactive:C})}function Sr(t,e,r){let o=t.describe({actor:e,detail:"full"}),n=r?.groupByTags??!0,a=r?.separator??`
4
- `,s=[],i=r?.sinceVersion;for(let[l,m]of Object.entries(o.nodes)){let d=m.meta??{},u=d.description,p=d.format;if(!u&&!p)continue;if(i!=null&&m.v!=null){let T=i.get(l);if(T!=null&&T.id===m.v.id&&m.v.version<=T.version)continue}let c=u??l,f=m.value,y=d.unit,g;p==="currency"&&typeof f=="number"?g=`$${f.toFixed(2)}`:p==="percentage"&&typeof f=="number"?g=`${(f*100).toFixed(1)}%`:f==null?g="(no value)":g=String(f),y&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${y}`),s.push({path:l,description:c,formatted:g})}if(s.length===0)return"";if(n){let l=new Map,m=[];for(let u of s){let c=o.nodes[u.path].meta?.tags;if(c&&c.length>0){let f=c[0],y=l.get(f);y||(y=[],l.set(f,y)),y.push(u)}else m.push(u)}if(l.size===0)return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a);let d=[];for(let[u,p]of[...l.entries()].sort((c,f)=>c[0].localeCompare(f[0])))d.push(`[${u}]${a}${p.map(c=>`- ${c.description}: ${c.formatted}`).join(a)}`);return m.length>0&&d.push(m.map(u=>`- ${u.description}: ${u.formatted}`).join(a)),d.join(a+a)}return s.map(l=>`- ${l.description}: ${l.formatted}`).join(a)}var Rt=new Set(["state","derived","producer","operator","effect"]);function Ze(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let o=new Set(Object.keys(r.nodes));for(let[n,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${n}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Rt.has(s.type))&&e.push(`Node "${n}": invalid type "${String(s.type)}" (expected: ${[...Rt].join(", ")})`),Array.isArray(s.deps))for(let i of s.deps)typeof i=="string"&&!o.has(i)&&e.push(`Node "${n}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let n=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let i=s;(typeof i.from!="string"||!o.has(i.from))&&e.push(`Edge [${a}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!o.has(i.to))&&e.push(`Edge [${a}]: 'to' "${String(i.to)}" does not reference an existing node`);let l=`${i.from}->${i.to}`;n.has(l)&&e.push(`Edge [${a}]: duplicate edge ${l}`),n.add(l)}}return{valid:e.length===0,errors:e}}var Lt=`You are a graph architect for GraphReFly, a reactive graph protocol.
5
-
6
- Given a natural-language description, produce a JSON graph definition with this structure:
7
-
8
- {
9
- "name": "<graph_name>",
10
- "nodes": {
11
- "<node_name>": {
12
- "type": "state" | "derived" | "producer" | "operator" | "effect",
13
- "value": <initial_value_or_null>,
14
- "deps": ["<dep_node_name>", ...],
15
- "meta": {
16
- "description": "<human-readable purpose>",
17
- "type": "string" | "number" | "boolean" | "integer" | "enum",
18
- "range": [min, max],
19
- "values": ["a", "b"],
20
- "format": "currency" | "percentage" | "status",
21
- "access": "human" | "llm" | "both" | "system",
22
- "unit": "<unit>",
23
- "tags": ["<tag>"]
24
- }
25
- }
26
- },
27
- "edges": [
28
- { "from": "<source_node>", "to": "<target_node>" }
29
- ]
30
- }
31
-
32
- Rules:
33
- - "state" nodes have no deps and hold user/LLM-writable values (knobs).
34
- - "derived" nodes have deps and compute from them.
35
- - "effect" nodes have deps but produce side effects (no return value).
36
- - "producer" nodes have no deps but generate values asynchronously.
37
- - Edges wire output of one node as input to another. They must match deps.
38
- - meta.description is required for every node.
39
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Er(t,e,r){let n=[{role:"system",content:r?.systemPromptExtra?`${Lt}
40
-
41
- ${r.systemPromptExtra}`:Lt},{role:"user",content:t}],a=e.invoke(n,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),i=(await ue(a)).content.trim();i.startsWith("```")&&(i=de(i));let l;try{l=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}let m=Ze(l);if(!m.valid)throw new Error(`graphFromSpec: invalid graph definition:
42
- ${m.errors.join(`
43
- `)}`);let d=l;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),Z.fromSnapshot(d,r?.build)}function Ir(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Or(t,e){let r=t.describe({actor:e,detail:"full"}),o=[],n=[],a=[];for(let[s,i]of Object.entries(r.nodes)){if(i.type!=="state"||s.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let l=i.meta??{},m=l.access;if(m==="human"||m==="system")continue;let d=l.description??`Set the value of ${s}`,u=Ir(l),p={type:"object",required:["value"],properties:{value:u},additionalProperties:!1},c=s.replace(/::/g,"__");o.push({type:"function",function:{name:c,description:d,parameters:p}}),n.push({name:s,description:d,inputSchema:p});let f=t,y=e,g=i.v;a.push({name:s,description:d,parameters:p,handler(T){return f.set(s,T.value,y?{actor:y}:void 0),T.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:o,mcp:n,definitions:a}}var Pr=`You are a reactive graph optimizer for GraphReFly.
44
-
45
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
46
-
47
- Return ONLY valid JSON with this structure:
48
- {
49
- "summary": "<one-line summary of the strategy>",
50
- "reasoning": "<explanation of why these changes help>",
51
- "operations": [
52
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
53
- { "type": "remove_node", "name": "<name>" },
54
- { "type": "connect", "from": "<source>", "to": "<target>" },
55
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
56
- { "type": "set_value", "name": "<name>", "value": <new_value> },
57
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
58
- ]
59
- }
60
-
61
- Rules:
62
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
63
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
64
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function jr(t,e,r,o){let{expand:n,...a}=t.describe({actor:o?.actor,detail:"standard"}),s=[{role:"system",content:Pr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],i=r.invoke(s,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens}),m=(await ue(i)).content.trim();m.startsWith("```")&&(m=m.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(m)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${m.slice(0,200)}`)}let u=d;if(typeof u.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof u.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(u.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:u.summary,reasoning:u.reasoning,operations:u.operations}}export{Ft as a,Gt as b,Ge as c,yt as d,$t as e,Wt as f,Kt as g,Be as h,Ne as i,We as j,Vt as k,Ke as l,Ve as m,He as n,he as o,qe as p,tr as q,rr as r,nr as s,lr as t,dr as u,mr as v,cr as w,pr as x,gr as y,hr as z,br as A,Mr as B,kr as C,vr as D,Ee as E,ze as F,Ie as G,Je as H,Oe as I,Rr as J,Lr as K,wr as L,Cr as M,Ye as N,Qe as O,Xe as P,Ar as Q,Sr as R,Ze as S,Er as T,Or as U,jr as V,_r as W};
@@ -1 +0,0 @@
1
- import{E as c,m,o as u}from"./chunk-W4TSQ6RJ.js";import{b as f,c as h}from"./chunk-CK2E7BTU.js";var p=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(t={}){let{maxSize:e,defaultTtl:i}=t;if(e!==void 0&&e<1)throw new RangeError("maxSize must be >= 1");if(i!==void 0&&i<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=e,this._defaultTtl=i}get version(){return this._version}get size(){return this._store.size}has(t){let e=this._store.get(t);return e===void 0?!1:this._isExpired(e)?(this._store.delete(t),this._version+=1,!1):(this._touchLru(t,e),!0)}get(t){let e=this._store.get(t);if(e!==void 0){if(this._isExpired(e)){this._store.delete(t),this._version+=1;return}return this._touchLru(t,e),e.value}}set(t,e,i){let s=this._resolveExpiresAt(i);this._store.has(t)&&this._store.delete(t),this._store.set(t,{value:e,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(t,e){let i=this._resolveExpiresAt(e),s=0;try{for(let[d,n]of t)this._store.has(d)&&this._store.delete(d),this._store.set(d,{value:n,expiresAt:i}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(t){let e=this._store.delete(t);return e&&(this._version+=1),e}deleteMany(t){let e=0;try{for(let i of t)this._store.delete(i)&&(e+=1)}finally{e>0&&(this._version+=1)}return e}clear(){let t=this._store.size;return t===0?0:(this._store.clear(),this._version+=1,t)}pruneExpired(){let t=u(),e=0;for(let[i,s]of this._store)this._isExpired(s,t)&&(this._store.delete(i),e+=1);return e>0&&(this._version+=1),e}toMap(){let t=u(),e=new Map;for(let[i,s]of this._store)this._isExpired(s,t)||e.set(i,s.value);return e}_resolveExpiresAt(t){let e=t??this._defaultTtl;if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${e})`);return u()+e*1e9}}_isExpired(t,e){return t.expiresAt===void 0?!1:(e??u())>=t.expiresAt}_touchLru(t,e){this._store.delete(t),this._store.set(t,e)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let t=this._store.keys().next().value;if(t===void 0)break;this._store.delete(t)}}};function x(v={}){let{name:t,maxSize:e,defaultTtl:i,versioning:s,backend:d}=v,n=d??new p({maxSize:e,defaultTtl:i}),l=c(n.toMap(),{name:t,describeKind:"state",equals:(r,a)=>r===a,...s!=null?{versioning:s}:{}});function _(){let r=n.toMap();m(()=>{l.down([[h]]),l.down([[f,r]])})}function o(r){let a=n.version;try{return r()}finally{n.version!==a&&_()}}return{entries:l,has(r){return o(()=>n.has(r))},get(r){return o(()=>n.get(r))},set(r,a,b){o(()=>n.set(r,a,b?.ttl))},setMany(r,a){o(()=>n.setMany(r,a?.ttl))},delete(r){o(()=>n.delete(r))},deleteMany(r){o(()=>n.deleteMany(r))},clear(){o(()=>n.clear())},pruneExpired(){o(()=>n.pruneExpired())},get size(){return n.size},dispose(){}}}export{p as a,x as b};
@@ -1 +0,0 @@
1
- import{c as R}from"./chunk-5Z4HDCO6.js";import{k}from"./chunk-MGKAO4EK.js";import{A as g}from"./chunk-KASHOCF5.js";import{b as N}from"./chunk-AUY2YKCO.js";import{D as T,E as S,G as y,m as q,p as w,t as u}from"./chunk-W4TSQ6RJ.js";import{b as A}from"./chunk-QYADASLV.js";var P={};A(P,{CqrsGraph:()=>h,MemoryEventStore:()=>_,cqrs:()=>O});var j=u((i,e)=>{i("write"),i("signal"),e("observe")}),D=u((i,e)=>{i("observe"),i("signal"),e("write")}),H=u((i,e)=>{i("observe"),i("signal"),e("write")});function m(i,e){return R("cqrs",i,e)}var _=class{_store=new Map;persist(e){let t=this._store.get(e.type);t||(t=[],this._store.set(e.type,t)),t.push(e)}loadEvents(e,t){let n=this._store.get(e)??[],r=t?.timestampNs,s=t?.seq,o=r==null?[...n]:n.filter(d=>d.timestampNs>r||d.timestampNs===r&&d.seq>(s??-1)),a=o.length>0?o[o.length-1]:void 0;return{events:o,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:t}}clear(){this._store.clear()}},h=class extends k{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,t={}){super(e,t.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let t=this._eventLogs.get(e);if(t)return t.node;let n=N([],{name:e,versioning:0}),r=n.entries,s=y([r],([o])=>o,{name:e,describeKind:"state",meta:m("event",{event_name:e}),guard:H,initial:r.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(g(s)),this._eventLogs.set(e,{log:n,node:s}),s}_appendEvent(e,t){let n=this._eventLogs.get(e);if(n||(this.event(e),n=this._eventLogs.get(e)),n.node.status==="completed"||n.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${n.node.status}).`);let r=n.log.entries.v,s={type:e,payload:t,timestampNs:w(),seq:++this._seq,...r!=null?{v0:{id:r.id,version:r.version}}:{}};n.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,t){let n=S(void 0,{name:e,describeKind:"state",meta:{...m("command",{command_name:e}),error:null},guard:j});return this.add(n,{name:e}),this._commandHandlers.set(e,t),n}dispatch(e,t){let n=this._commandHandlers.get(e);if(!n)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let r=this.resolve(e);q(()=>{r.emit(t,{internal:!0});try{n(t,{emit:(s,o)=>this._appendEvent(s,o)}),r.meta.error.emit(null,{internal:!0})}catch(s){throw r.meta.error.emit(s,{internal:!0}),s}})}projection(e,t,n,r){let s=t.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),o=y(s,a=>{let d=[];for(let v of a){let p=v;d.push(...p)}return d.sort((v,p)=>v.timestampNs-p.timestampNs||v.seq-p.seq),n(r,d)},{name:e,describeKind:"derived",meta:m("projection",{projection_name:e,source_events:t}),guard:D,initial:r});return this.add(o,{name:e}),this._keepaliveDisposers.push(g(o)),this._projections.add(e),o}saga(e,t,n){let r=t.map(d=>(this._eventLogs.has(d)||this.event(d),this._eventLogs.get(d).node)),s=new Map,o={},a=T(r,(d,v)=>{let p=o.n.meta.error;for(let c=0;c<d.length;c++){let E=d[c];if(E==null||E.length===0)continue;let l=E.at(-1);if(!l)continue;let f=t[c],C=s.get(f)??0;if(l.length>C){let b=l.slice(C);for(let L of b)try{n(L),p.emit(null,{internal:!0})}catch(x){p.emit(x,{internal:!0})}s.set(f,l.length)}}},{name:e,describeKind:"effect",meta:{...m("saga",{saga_name:e,source_events:t}),error:null}});return o.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(g(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,t,n){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let r=[];for(let s of e){let o=await this._eventStore.loadEvents(s);r.push(...o.events)}return r.sort((s,o)=>s.timestampNs-o.timestampNs||s.seq-o.seq),t(n,r)}};function O(i,e){return new h(i,e)}export{_ as a,h as b,O as c,P as d};