@graphrefly/graphrefly 0.27.0 → 0.29.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 (428) hide show
  1. package/dist/backoff-HPZMEZNF.js +1 -0
  2. package/dist/cascading-Bp99ckMJ.d.ts +180 -0
  3. package/dist/cascading-CcAgRacD.d.cts +180 -0
  4. package/dist/chunk-22F4K3G7.js +1 -0
  5. package/dist/chunk-22SVXUPB.js +64 -0
  6. package/dist/chunk-2GQREQ6C.js +1 -0
  7. package/dist/chunk-3JXNEPCD.js +2 -0
  8. package/dist/chunk-4JJCCD5S.js +2 -0
  9. package/dist/chunk-4OFIQ66T.js +1 -0
  10. package/dist/chunk-4V4C7K56.js +1 -0
  11. package/dist/chunk-4VVTGLXJ.js +1 -0
  12. package/dist/chunk-567NWZ3T.js +1 -0
  13. package/dist/chunk-5JDE5JHE.js +1 -0
  14. package/dist/chunk-5QDBSZBV.js +1 -0
  15. package/dist/chunk-5Z4HDCO6.js +1 -0
  16. package/dist/chunk-63FFOHLA.js +1 -0
  17. package/dist/chunk-6QZNQS5B.js +1 -0
  18. package/dist/chunk-7JDLFI6N.js +1 -0
  19. package/dist/chunk-7TDOES3L.js +1 -0
  20. package/dist/chunk-A7IAQQ63.js +1 -0
  21. package/dist/chunk-AMG5VBHW.js +1 -0
  22. package/dist/chunk-AUY2YKCO.js +1 -0
  23. package/dist/chunk-AV3PIDFQ.js +1 -0
  24. package/dist/chunk-BA5URFYW.js +1 -0
  25. package/dist/chunk-BKPLTBL5.js +1 -0
  26. package/dist/chunk-BZP5T4X6.js +1 -0
  27. package/dist/chunk-CK2E7BTU.js +1 -0
  28. package/dist/chunk-CSJE2EKV.js +1 -0
  29. package/dist/chunk-E3AXATVZ.js +9 -0
  30. package/dist/chunk-ESMPEKEV.js +1 -0
  31. package/dist/chunk-GJR3P6JG.js +1 -0
  32. package/dist/chunk-GNCBXARM.js +1 -0
  33. package/dist/chunk-GPW2V3RE.js +1 -0
  34. package/dist/chunk-HSIEYSDY.js +1 -0
  35. package/dist/chunk-I6VIH3VA.js +1 -0
  36. package/dist/chunk-ISCENNXS.js +1 -0
  37. package/dist/chunk-JYOUF6UQ.js +1 -0
  38. package/dist/chunk-KASHOCF5.js +1 -0
  39. package/dist/chunk-LGSNR4LU.js +5 -0
  40. package/dist/chunk-LVGBLZM2.js +1 -0
  41. package/dist/chunk-MGKAO4EK.js +7 -0
  42. package/dist/chunk-NSG4C6BF.js +23 -0
  43. package/dist/chunk-OL33ZI6R.js +1 -0
  44. package/dist/chunk-PCZ35NXD.js +78 -0
  45. package/dist/chunk-PGMUCUHG.js +43 -0
  46. package/dist/chunk-QYADASLV.js +1 -0
  47. package/dist/chunk-RD52SNH2.js +1 -0
  48. package/dist/chunk-SLMYTGTU.js +1 -0
  49. package/dist/chunk-TWMEGG45.js +1 -0
  50. package/dist/chunk-UVJQ35G2.js +1 -0
  51. package/dist/chunk-VGTCGNRX.js +18 -0
  52. package/dist/chunk-VIMF6LGM.js +1 -0
  53. package/dist/chunk-VJLMUKOI.js +1 -0
  54. package/dist/chunk-VWPRPPKR.js +1 -0
  55. package/dist/chunk-W4TSQ6RJ.js +1 -0
  56. package/dist/chunk-WM7H7WTY.js +3 -0
  57. package/dist/chunk-Y32RJO24.js +1 -0
  58. package/dist/chunk-Y53B6NS4.js +1 -0
  59. package/dist/compat/index.cjs +15 -7656
  60. package/dist/compat/index.d.cts +15 -14
  61. package/dist/compat/index.d.ts +15 -14
  62. package/dist/compat/index.js +1 -50
  63. package/dist/compat/jotai/index.cjs +1 -2048
  64. package/dist/compat/jotai/index.d.cts +2 -2
  65. package/dist/compat/jotai/index.d.ts +2 -2
  66. package/dist/compat/jotai/index.js +1 -9
  67. package/dist/compat/nanostores/index.cjs +1 -2175
  68. package/dist/compat/nanostores/index.d.cts +2 -2
  69. package/dist/compat/nanostores/index.d.ts +2 -2
  70. package/dist/compat/nanostores/index.js +1 -23
  71. package/dist/compat/nestjs/index.cjs +15 -6782
  72. package/dist/compat/nestjs/index.d.cts +7 -6
  73. package/dist/compat/nestjs/index.d.ts +7 -6
  74. package/dist/compat/nestjs/index.js +1 -83
  75. package/dist/compat/react/index.cjs +1 -141
  76. package/dist/compat/react/index.d.cts +2 -2
  77. package/dist/compat/react/index.d.ts +2 -2
  78. package/dist/compat/react/index.js +1 -12
  79. package/dist/compat/solid/index.cjs +1 -128
  80. package/dist/compat/solid/index.d.cts +2 -2
  81. package/dist/compat/solid/index.d.ts +2 -2
  82. package/dist/compat/solid/index.js +1 -12
  83. package/dist/compat/svelte/index.cjs +1 -131
  84. package/dist/compat/svelte/index.d.cts +2 -2
  85. package/dist/compat/svelte/index.d.ts +2 -2
  86. package/dist/compat/svelte/index.js +1 -12
  87. package/dist/compat/vue/index.cjs +1 -146
  88. package/dist/compat/vue/index.d.cts +2 -2
  89. package/dist/compat/vue/index.d.ts +2 -2
  90. package/dist/compat/vue/index.js +1 -12
  91. package/dist/compat/zustand/index.cjs +7 -4931
  92. package/dist/compat/zustand/index.d.cts +5 -5
  93. package/dist/compat/zustand/index.d.ts +5 -5
  94. package/dist/compat/zustand/index.js +1 -12
  95. package/dist/composite-BL-llbnE.d.ts +69 -0
  96. package/dist/composite-Dze--DaA.d.cts +69 -0
  97. package/dist/core/index.cjs +1 -2271
  98. package/dist/core/index.d.cts +4 -4
  99. package/dist/core/index.d.ts +4 -4
  100. package/dist/core/index.js +1 -110
  101. package/dist/extra/browser.cjs +1 -0
  102. package/dist/extra/browser.d.cts +3 -0
  103. package/dist/extra/browser.d.ts +3 -0
  104. package/dist/extra/browser.js +1 -0
  105. package/dist/extra/index.cjs +24 -9971
  106. package/dist/extra/index.d.cts +13 -6
  107. package/dist/extra/index.d.ts +13 -6
  108. package/dist/extra/index.js +1 -381
  109. package/dist/extra/node.cjs +3 -0
  110. package/dist/extra/node.d.cts +81 -0
  111. package/dist/extra/node.d.ts +81 -0
  112. package/dist/extra/node.js +2 -0
  113. package/dist/extra/operators.cjs +1 -0
  114. package/dist/extra/operators.d.cts +910 -0
  115. package/dist/extra/operators.d.ts +910 -0
  116. package/dist/extra/operators.js +1 -0
  117. package/dist/extra/reactive.cjs +1 -0
  118. package/dist/extra/reactive.d.cts +352 -0
  119. package/dist/extra/reactive.d.ts +352 -0
  120. package/dist/extra/reactive.js +1 -0
  121. package/dist/extra/sources.cjs +1 -2486
  122. package/dist/extra/sources.d.cts +6 -2
  123. package/dist/extra/sources.d.ts +6 -2
  124. package/dist/extra/sources.js +1 -57
  125. package/dist/extra/storage-browser.cjs +1 -0
  126. package/dist/extra/storage-browser.d.cts +71 -0
  127. package/dist/extra/storage-browser.d.ts +71 -0
  128. package/dist/extra/storage-browser.js +1 -0
  129. package/dist/extra/storage-core.cjs +1 -0
  130. package/dist/extra/storage-core.d.cts +98 -0
  131. package/dist/extra/storage-core.d.ts +98 -0
  132. package/dist/extra/storage-core.js +1 -0
  133. package/dist/extra/storage-node.cjs +2 -0
  134. package/dist/extra/storage-node.d.cts +60 -0
  135. package/dist/extra/storage-node.d.ts +60 -0
  136. package/dist/extra/storage-node.js +1 -0
  137. package/dist/fallback-BaTS7vVY.d.cts +258 -0
  138. package/dist/fallback-eOm3LNxP.d.ts +258 -0
  139. package/dist/graph/index.cjs +7 -5030
  140. package/dist/graph/index.d.cts +6 -5
  141. package/dist/graph/index.d.ts +6 -5
  142. package/dist/graph/index.js +1 -50
  143. package/dist/{graph-DNCrvZSn.d.cts → graph-DgohqXK-.d.cts} +151 -32
  144. package/dist/{graph-CCwGKLCm.d.ts → graph-Qjg9gWHI.d.ts} +151 -32
  145. package/dist/{index-BwfLUNw4.d.ts → index-2BVuRCI4.d.ts} +173 -2040
  146. package/dist/{index-BPVt8kqc.d.ts → index-2NvguqQA.d.ts} +10 -195
  147. package/dist/index-A65LZhoM.d.ts +186 -0
  148. package/dist/{index-DlLp-2Xn.d.cts → index-B-8FCEua.d.cts} +10 -195
  149. package/dist/index-B-gqvYel.d.ts +135 -0
  150. package/dist/index-B2PRuolf.d.cts +86 -0
  151. package/dist/index-BJqt9EwW.d.ts +231 -0
  152. package/dist/{index-BHlKbUwO.d.cts → index-BKjT5DiZ.d.cts} +173 -2040
  153. package/dist/{index-C0svESO4.d.ts → index-BM8BU4q6.d.ts} +1 -1
  154. package/dist/{index-VdHQMPy1.d.ts → index-BQaEnxBf.d.ts} +1 -1
  155. package/dist/index-BSfwiy5B.d.ts +192 -0
  156. package/dist/index-BTSkeCZs.d.cts +291 -0
  157. package/dist/index-BUVtw1Ay.d.cts +186 -0
  158. package/dist/index-BUi57v_p.d.ts +163 -0
  159. package/dist/{messaging-Gt4LPbyA.d.cts → index-BanNUILp.d.cts} +31 -93
  160. package/dist/{audit-DRlSzBu9.d.ts → index-BayHDRx6.d.cts} +27 -21
  161. package/dist/{index-B6D3QNSA.d.ts → index-BiyjsZ0m.d.ts} +148 -20
  162. package/dist/index-BqZ6vB2A.d.ts +2057 -0
  163. package/dist/{memory-li6FL5RM.d.ts → index-BuVidq3D.d.cts} +26 -26
  164. package/dist/index-Byh-xTyp.d.ts +105 -0
  165. package/dist/index-C08QPDcV.d.cts +321 -0
  166. package/dist/{demo-shell-BDkOptd6.d.ts → index-C66RJiX8.d.ts} +14 -14
  167. package/dist/index-C8RfjffH.d.ts +291 -0
  168. package/dist/index-CA1Cu7Ud.d.ts +873 -0
  169. package/dist/{index-ByQxazQJ.d.cts → index-CABbltIu.d.cts} +1 -1
  170. package/dist/{index-VHqptjhu.d.cts → index-CHEBsnYv.d.cts} +1 -1
  171. package/dist/{index-BuEoe-Qu.d.ts → index-CI0yDnLp.d.ts} +9 -9
  172. package/dist/{index-B9B7_HEY.d.ts → index-CJ45TW-h.d.ts} +1 -1
  173. package/dist/{index-CO8uBlUh.d.cts → index-CJZKZoo4.d.cts} +148 -20
  174. package/dist/{index-wEn0eFe8.d.ts → index-CX2tFJL1.d.ts} +1 -1
  175. package/dist/{index-BaSM3aYt.d.ts → index-CcWOJ6F0.d.ts} +3 -3
  176. package/dist/{audit-ClmqGOCx.d.cts → index-CiaVoZGo.d.ts} +27 -21
  177. package/dist/{index-Dzk2hrlR.d.ts → index-Ct5CWc4E.d.ts} +1 -1
  178. package/dist/index-D38duMCv.d.cts +357 -0
  179. package/dist/{index-C8oil6M6.d.ts → index-D5XJ2tSx.d.ts} +30 -6
  180. package/dist/{index-DO_6JN9Z.d.cts → index-D80do5jX.d.cts} +1 -1
  181. package/dist/index-D9HKAH_-.d.cts +231 -0
  182. package/dist/index-DBe_8XW5.d.cts +143 -0
  183. package/dist/{memory-C6Z2tGpC.d.cts → index-DCeTyFlB.d.ts} +26 -26
  184. package/dist/index-DDy8eeXS.d.ts +321 -0
  185. package/dist/index-DJ5oNBc8.d.ts +143 -0
  186. package/dist/{index-CI3DprxP.d.cts → index-DP0_O3ls.d.cts} +30 -6
  187. package/dist/{demo-shell-Crid1WdR.d.cts → index-DX8xS-yB.d.cts} +14 -14
  188. package/dist/index-DiZejfCI.d.cts +2057 -0
  189. package/dist/index-DknyJ2Fu.d.cts +163 -0
  190. package/dist/index-DoWMs-Kk.d.cts +135 -0
  191. package/dist/{messaging-XDoYablx.d.ts → index-DuB5aO4-.d.ts} +31 -93
  192. package/dist/index-DwjJGKxV.d.ts +357 -0
  193. package/dist/{index-B6EhDnjH.d.cts → index-H_oxVec5.d.cts} +1 -1
  194. package/dist/{index-3lsddbbS.d.ts → index-IMAHq-ia.d.ts} +1 -1
  195. package/dist/{index-B1tloyhO.d.cts → index-U1nir7MX.d.cts} +1 -1
  196. package/dist/index-Vg7tORgk.d.ts +86 -0
  197. package/dist/index-dig-r2tQ.d.cts +873 -0
  198. package/dist/{index-CxFrXH4m.d.ts → index-gsT79Xu9.d.ts} +1 -1
  199. package/dist/{index-D8wS_PeY.d.cts → index-i99Ka8s7.d.cts} +9 -9
  200. package/dist/index-iKkyJosF.d.cts +105 -0
  201. package/dist/{index-Xi3u0HCQ.d.cts → index-jleeotBT.d.cts} +1 -1
  202. package/dist/{index-DVGiGFGT.d.cts → index-kykKWwV-.d.cts} +3 -3
  203. package/dist/index-vgcLF5TH.d.cts +192 -0
  204. package/dist/{index-DYme44FM.d.cts → index-y1RllPn4.d.cts} +1 -1
  205. package/dist/index.cjs +151 -24142
  206. package/dist/index.d.cts +69 -2099
  207. package/dist/index.d.ts +69 -2099
  208. package/dist/index.js +1 -3868
  209. package/dist/{meta-CbznRPYJ.d.ts → meta-CX7YsOzp.d.cts} +5 -5
  210. package/dist/{meta-BxCA7rcr.d.cts → meta-CckhhFRd.d.ts} +5 -5
  211. package/dist/{node-BmerH3kS.d.cts → node-Dd6wHSib.d.cts} +71 -11
  212. package/dist/{node-BmerH3kS.d.ts → node-Dd6wHSib.d.ts} +71 -11
  213. package/dist/{observable-BgGUwcqp.d.ts → observable-BZJgo616.d.ts} +1 -1
  214. package/dist/{observable-DJt_AxzQ.d.cts → observable-kwzpLvbi.d.cts} +1 -1
  215. package/dist/patterns/ai/browser.cjs +25 -0
  216. package/dist/patterns/ai/browser.d.cts +127 -0
  217. package/dist/patterns/ai/browser.d.ts +127 -0
  218. package/dist/patterns/ai/browser.js +3 -0
  219. package/dist/patterns/ai/index.cjs +92 -0
  220. package/dist/patterns/ai/index.d.cts +17 -0
  221. package/dist/patterns/ai/index.d.ts +17 -0
  222. package/dist/patterns/ai/index.js +1 -0
  223. package/dist/patterns/ai/node.cjs +2 -0
  224. package/dist/patterns/ai/node.d.cts +58 -0
  225. package/dist/patterns/ai/node.d.ts +58 -0
  226. package/dist/patterns/ai/node.js +1 -0
  227. package/dist/patterns/audit/index.cjs +7 -0
  228. package/dist/patterns/audit/index.d.cts +6 -0
  229. package/dist/patterns/audit/index.d.ts +6 -0
  230. package/dist/patterns/audit/index.js +1 -0
  231. package/dist/patterns/cqrs/index.cjs +7 -0
  232. package/dist/patterns/cqrs/index.d.cts +5 -0
  233. package/dist/patterns/cqrs/index.d.ts +5 -0
  234. package/dist/patterns/cqrs/index.js +1 -0
  235. package/dist/patterns/demo-shell/index.cjs +8 -0
  236. package/dist/patterns/demo-shell/index.d.cts +6 -0
  237. package/dist/patterns/demo-shell/index.d.ts +6 -0
  238. package/dist/patterns/demo-shell/index.js +1 -0
  239. package/dist/patterns/domain-templates/index.cjs +7 -0
  240. package/dist/patterns/domain-templates/index.d.cts +5 -0
  241. package/dist/patterns/domain-templates/index.d.ts +5 -0
  242. package/dist/patterns/domain-templates/index.js +1 -0
  243. package/dist/patterns/graphspec/index.cjs +84 -0
  244. package/dist/patterns/graphspec/index.d.cts +7 -0
  245. package/dist/patterns/graphspec/index.d.ts +7 -0
  246. package/dist/patterns/graphspec/index.js +1 -0
  247. package/dist/patterns/guarded-execution/index.cjs +7 -0
  248. package/dist/patterns/guarded-execution/index.d.cts +7 -0
  249. package/dist/patterns/guarded-execution/index.d.ts +7 -0
  250. package/dist/patterns/guarded-execution/index.js +1 -0
  251. package/dist/patterns/harness/index.cjs +49 -0
  252. package/dist/patterns/harness/index.d.cts +11 -0
  253. package/dist/patterns/harness/index.d.ts +11 -0
  254. package/dist/patterns/harness/index.js +1 -0
  255. package/dist/patterns/job-queue/index.cjs +7 -0
  256. package/dist/patterns/job-queue/index.d.cts +5 -0
  257. package/dist/patterns/job-queue/index.d.ts +5 -0
  258. package/dist/patterns/job-queue/index.js +1 -0
  259. package/dist/patterns/lens/index.cjs +7 -0
  260. package/dist/patterns/lens/index.d.cts +7 -0
  261. package/dist/patterns/lens/index.d.ts +7 -0
  262. package/dist/patterns/lens/index.js +1 -0
  263. package/dist/patterns/memory/index.cjs +7 -0
  264. package/dist/patterns/memory/index.d.cts +5 -0
  265. package/dist/patterns/memory/index.d.ts +5 -0
  266. package/dist/patterns/memory/index.js +1 -0
  267. package/dist/patterns/messaging/index.cjs +7 -0
  268. package/dist/patterns/messaging/index.d.cts +5 -0
  269. package/dist/patterns/messaging/index.d.ts +5 -0
  270. package/dist/patterns/messaging/index.js +1 -0
  271. package/dist/patterns/orchestration/index.cjs +7 -0
  272. package/dist/patterns/orchestration/index.d.cts +6 -0
  273. package/dist/patterns/orchestration/index.d.ts +6 -0
  274. package/dist/patterns/orchestration/index.js +1 -0
  275. package/dist/patterns/reactive-layout/index.cjs +8 -6444
  276. package/dist/patterns/reactive-layout/index.d.cts +6 -6
  277. package/dist/patterns/reactive-layout/index.d.ts +6 -6
  278. package/dist/patterns/reactive-layout/index.js +1 -56
  279. package/dist/patterns/reduction/index.cjs +7 -0
  280. package/dist/patterns/reduction/index.d.cts +5 -0
  281. package/dist/patterns/reduction/index.d.ts +5 -0
  282. package/dist/patterns/reduction/index.js +1 -0
  283. package/dist/patterns/refine-loop/index.cjs +9 -0
  284. package/dist/patterns/refine-loop/index.d.cts +7 -0
  285. package/dist/patterns/refine-loop/index.d.ts +7 -0
  286. package/dist/patterns/refine-loop/index.js +1 -0
  287. package/dist/patterns/resilient-pipeline/index.cjs +1 -0
  288. package/dist/patterns/resilient-pipeline/index.d.cts +7 -0
  289. package/dist/patterns/resilient-pipeline/index.d.ts +7 -0
  290. package/dist/patterns/resilient-pipeline/index.js +1 -0
  291. package/dist/patterns/surface/index.cjs +15 -0
  292. package/dist/patterns/surface/index.d.cts +8 -0
  293. package/dist/patterns/surface/index.d.ts +8 -0
  294. package/dist/patterns/surface/index.js +1 -0
  295. package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-BkBwVvwm.d.ts} +2 -2
  296. package/dist/{reactive-layout-MQP--J3F.d.cts → reactive-layout-PiFwVaWS.d.cts} +2 -2
  297. package/dist/reactive-log-1QTyx10a.d.ts +190 -0
  298. package/dist/reactive-log-BiVoSxke.d.cts +190 -0
  299. package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CwO_COHy.d.cts} +2 -67
  300. package/dist/{composite-C7PcQvcs.d.cts → reactive-map-FeuTVAJb.d.ts} +2 -67
  301. package/dist/resilience-CBfYJW5C.d.ts +493 -0
  302. package/dist/resilience-XRUF267O.js +1 -0
  303. package/dist/resilience-uBz4yvYB.d.cts +493 -0
  304. package/dist/{sugar-CCOxXK1e.d.ts → sugar-CY-MCfZ9.d.ts} +17 -15
  305. package/dist/{sugar-D02n5JjF.d.cts → sugar-DHttV0LX.d.cts} +17 -15
  306. package/dist/topology-tree-CVjt2gp7.d.cts +25 -0
  307. package/dist/topology-tree-one6oSKY.d.ts +25 -0
  308. package/dist/types-O3GzJY2U.d.cts +401 -0
  309. package/dist/types-u64Ose53.d.ts +401 -0
  310. package/package.json +252 -22
  311. package/dist/ai-CaR_912Q.d.cts +0 -1033
  312. package/dist/ai-WlRltJV7.d.ts +0 -1033
  313. package/dist/chunk-3ZWCKRHX.js +0 -117
  314. package/dist/chunk-3ZWCKRHX.js.map +0 -1
  315. package/dist/chunk-7TAQJHQV.js +0 -103
  316. package/dist/chunk-7TAQJHQV.js.map +0 -1
  317. package/dist/chunk-APFNLIRG.js +0 -62
  318. package/dist/chunk-APFNLIRG.js.map +0 -1
  319. package/dist/chunk-AT5LKYNL.js +0 -395
  320. package/dist/chunk-AT5LKYNL.js.map +0 -1
  321. package/dist/chunk-BQ6RQQFF.js +0 -5087
  322. package/dist/chunk-BQ6RQQFF.js.map +0 -1
  323. package/dist/chunk-BVZYTZ5H.js +0 -599
  324. package/dist/chunk-BVZYTZ5H.js.map +0 -1
  325. package/dist/chunk-DST5DKZS.js +0 -1371
  326. package/dist/chunk-DST5DKZS.js.map +0 -1
  327. package/dist/chunk-GTE6PWRZ.js +0 -866
  328. package/dist/chunk-GTE6PWRZ.js.map +0 -1
  329. package/dist/chunk-HXZEYDUR.js +0 -94
  330. package/dist/chunk-HXZEYDUR.js.map +0 -1
  331. package/dist/chunk-J22W6HV3.js +0 -107
  332. package/dist/chunk-J22W6HV3.js.map +0 -1
  333. package/dist/chunk-J2VBW3DZ.js +0 -302
  334. package/dist/chunk-J2VBW3DZ.js.map +0 -1
  335. package/dist/chunk-JSCT3CR4.js +0 -38
  336. package/dist/chunk-JSCT3CR4.js.map +0 -1
  337. package/dist/chunk-JWBCY4NC.js +0 -330
  338. package/dist/chunk-JWBCY4NC.js.map +0 -1
  339. package/dist/chunk-K2AUJHVP.js +0 -2251
  340. package/dist/chunk-K2AUJHVP.js.map +0 -1
  341. package/dist/chunk-MJ2NKQQL.js +0 -119
  342. package/dist/chunk-MJ2NKQQL.js.map +0 -1
  343. package/dist/chunk-N6UR7YVY.js +0 -198
  344. package/dist/chunk-N6UR7YVY.js.map +0 -1
  345. package/dist/chunk-NC6S43JJ.js +0 -456
  346. package/dist/chunk-NC6S43JJ.js.map +0 -1
  347. package/dist/chunk-OFVJBJXR.js +0 -98
  348. package/dist/chunk-OFVJBJXR.js.map +0 -1
  349. package/dist/chunk-OHISZPOJ.js +0 -97
  350. package/dist/chunk-OHISZPOJ.js.map +0 -1
  351. package/dist/chunk-OU5CQKNW.js +0 -102
  352. package/dist/chunk-OU5CQKNW.js.map +0 -1
  353. package/dist/chunk-PF7GRZMW.js +0 -2712
  354. package/dist/chunk-PF7GRZMW.js.map +0 -1
  355. package/dist/chunk-PHOUUNK7.js +0 -2291
  356. package/dist/chunk-PHOUUNK7.js.map +0 -1
  357. package/dist/chunk-RNHBMHKA.js +0 -1665
  358. package/dist/chunk-RNHBMHKA.js.map +0 -1
  359. package/dist/chunk-SX52TAR4.js +0 -110
  360. package/dist/chunk-SX52TAR4.js.map +0 -1
  361. package/dist/chunk-VYPWMZ6H.js +0 -98
  362. package/dist/chunk-VYPWMZ6H.js.map +0 -1
  363. package/dist/chunk-WBZOVTYK.js +0 -171
  364. package/dist/chunk-WBZOVTYK.js.map +0 -1
  365. package/dist/chunk-WKNUIZOY.js +0 -354
  366. package/dist/chunk-WKNUIZOY.js.map +0 -1
  367. package/dist/chunk-X3VMZYBT.js +0 -713
  368. package/dist/chunk-X3VMZYBT.js.map +0 -1
  369. package/dist/chunk-X5R3GL6H.js +0 -525
  370. package/dist/chunk-X5R3GL6H.js.map +0 -1
  371. package/dist/chunk-XGPU467M.js +0 -136
  372. package/dist/chunk-XGPU467M.js.map +0 -1
  373. package/dist/compat/index.cjs.map +0 -1
  374. package/dist/compat/index.js.map +0 -1
  375. package/dist/compat/jotai/index.cjs.map +0 -1
  376. package/dist/compat/jotai/index.js.map +0 -1
  377. package/dist/compat/nanostores/index.cjs.map +0 -1
  378. package/dist/compat/nanostores/index.js.map +0 -1
  379. package/dist/compat/nestjs/index.cjs.map +0 -1
  380. package/dist/compat/nestjs/index.js.map +0 -1
  381. package/dist/compat/react/index.cjs.map +0 -1
  382. package/dist/compat/react/index.js.map +0 -1
  383. package/dist/compat/solid/index.cjs.map +0 -1
  384. package/dist/compat/solid/index.js.map +0 -1
  385. package/dist/compat/svelte/index.cjs.map +0 -1
  386. package/dist/compat/svelte/index.js.map +0 -1
  387. package/dist/compat/vue/index.cjs.map +0 -1
  388. package/dist/compat/vue/index.js.map +0 -1
  389. package/dist/compat/zustand/index.cjs.map +0 -1
  390. package/dist/compat/zustand/index.js.map +0 -1
  391. package/dist/core/index.cjs.map +0 -1
  392. package/dist/core/index.js.map +0 -1
  393. package/dist/extra/index.cjs.map +0 -1
  394. package/dist/extra/index.js.map +0 -1
  395. package/dist/extra/sources.cjs.map +0 -1
  396. package/dist/extra/sources.js.map +0 -1
  397. package/dist/graph/index.cjs.map +0 -1
  398. package/dist/graph/index.js.map +0 -1
  399. package/dist/index.cjs.map +0 -1
  400. package/dist/index.js.map +0 -1
  401. package/dist/patterns/ai.cjs +0 -7930
  402. package/dist/patterns/ai.cjs.map +0 -1
  403. package/dist/patterns/ai.d.cts +0 -10
  404. package/dist/patterns/ai.d.ts +0 -10
  405. package/dist/patterns/ai.js +0 -71
  406. package/dist/patterns/ai.js.map +0 -1
  407. package/dist/patterns/audit.cjs +0 -5805
  408. package/dist/patterns/audit.cjs.map +0 -1
  409. package/dist/patterns/audit.d.cts +0 -6
  410. package/dist/patterns/audit.d.ts +0 -6
  411. package/dist/patterns/audit.js +0 -29
  412. package/dist/patterns/audit.js.map +0 -1
  413. package/dist/patterns/demo-shell.cjs +0 -5604
  414. package/dist/patterns/demo-shell.cjs.map +0 -1
  415. package/dist/patterns/demo-shell.d.cts +0 -6
  416. package/dist/patterns/demo-shell.d.ts +0 -6
  417. package/dist/patterns/demo-shell.js +0 -15
  418. package/dist/patterns/demo-shell.js.map +0 -1
  419. package/dist/patterns/memory.cjs +0 -5283
  420. package/dist/patterns/memory.cjs.map +0 -1
  421. package/dist/patterns/memory.d.cts +0 -5
  422. package/dist/patterns/memory.d.ts +0 -5
  423. package/dist/patterns/memory.js +0 -20
  424. package/dist/patterns/memory.js.map +0 -1
  425. package/dist/patterns/reactive-layout/index.cjs.map +0 -1
  426. package/dist/patterns/reactive-layout/index.js.map +0 -1
  427. package/dist/storage-CMjUUuxn.d.ts +0 -190
  428. package/dist/storage-DdWlZo6U.d.cts +0 -190
@@ -0,0 +1,2057 @@
1
+ import { T as TokenUsage, L as LLMAdapter, P as PricingFn, C as ChatMessage, a as LLMInvokeOptions, d as ToolDefinition, b as LLMResponse, c as ToolCall, e as CapabilitiesRegistry, M as ModelCapabilities, f as ModelFeatures, g as ModelLimits, h as ModelPricing, i as PriceBreakdown, j as PricingRegistry, R as Rate, S as StreamDelta, k as TieredRate, l as composePricing, m as computePrice, n as createCapabilitiesRegistry, o as createPricingRegistry, r as registryPricing, z as zeroPrice } from './types-O3GzJY2U.cjs';
2
+ import { a as CascadeExhaustionReport, A as AdapterProvider, b as AdapterTier, d as AllTiersExhaustedError, C as CascadingLlmAdapterOptions, e as CreateAdapterOptions, O as OpenAICompatAdapterOptions, f as OpenAICompatPreset, g as OpenAISdkLike, h as cascadingLlmAdapter, c as createAdapter, o as openAICompatAdapter } from './cascading-CcAgRacD.cjs';
3
+ import { a as Node, A as Actor } from './node-Dd6wHSib.cjs';
4
+ import { R as ReactiveLogBundle } from './reactive-log-BiVoSxke.cjs';
5
+ import { a as CircuitBreakerOptions, e as CircuitBreaker, f as CircuitOpenError } from './resilience-uBz4yvYB.cjs';
6
+ import { NodeInput } from './extra/sources.cjs';
7
+ import { F as FallbackAdapterOptions, a as FallbackFixture, b as FallbackMissError, c as FallbackMissPolicy, R as ReplayCacheKeyContext, d as ReplayCacheMissError, e as ReplayCacheMode, W as WithReplayCacheOptions, f as canonicalJson, g as fallbackAdapter, w as withReplayCache } from './fallback-BaTS7vVY.cjs';
8
+ import { G as Graph, a as GraphOptions, h as GraphAttachStorageOptions } from './graph-DgohqXK-.cjs';
9
+ import { T as TopicGraph } from './index-BanNUILp.cjs';
10
+ import { G as GateController, a as GateOptions } from './index-DBe_8XW5.cjs';
11
+ import { D as DistillBundle, E as Extraction } from './composite-Dze--DaA.cjs';
12
+ import { V as VectorSearchResult, L as LightCollectionBundle, a as VectorIndexBundle, K as KnowledgeGraphGraph } from './index-BuVidq3D.cjs';
13
+ import { StorageHandle, StorageTier } from './extra/storage-core.cjs';
14
+
15
+ /**
16
+ * Observable adapter wrapper — the "inverted statistics" surface.
17
+ *
18
+ * The library emits structured facts (token counts, latency, timestamps)
19
+ * as reactive nodes. Users compose interpretation (pricing, dashboards,
20
+ * telemetry, budget breakers) as derived layers on top. Rationale lives in
21
+ * `archive/docs/SESSION-rigor-infrastructure-plan.md` §"v2: reactive LLM
22
+ * statistics + pluggable pricing".
23
+ */
24
+
25
+ /** One call's structured statistics — emitted after `invoke()` / `stream()` settles. */
26
+ interface CallStatsEvent {
27
+ /** `monotonicNs()` at call completion — use for event ordering. */
28
+ readonly timestamp: number;
29
+ /** `wallClockNs()` at call start — use for human-readable attribution. */
30
+ readonly wallClock: number;
31
+ readonly provider: string;
32
+ readonly model: string;
33
+ readonly tier?: string;
34
+ readonly usage: TokenUsage;
35
+ readonly latencyMs: number;
36
+ /** `"invoke"` or `"stream"`. */
37
+ readonly method: "invoke" | "stream";
38
+ /** Populated when the call errored — usage may be zero or partial. */
39
+ readonly error?: {
40
+ readonly type: string;
41
+ readonly message: string;
42
+ };
43
+ }
44
+ interface AdapterStats {
45
+ /**
46
+ * Reactive node for the most-recent call event. Emits `null` initially
47
+ * (no calls yet); emits a {@link CallStatsEvent} after each call. Subscribe
48
+ * and filter `!= null` if you want a `Node<CallStatsEvent>`.
49
+ */
50
+ readonly lastCall: Node<CallStatsEvent | null>;
51
+ /** Full event log (bounded by `opts.logMax`, default 1000). */
52
+ readonly allCalls: ReactiveLogBundle<CallStatsEvent>;
53
+ /** Total calls observed since last reset. */
54
+ readonly totalCalls: Node<number>;
55
+ /** Sum of every input-token class across observed calls. */
56
+ readonly totalInputTokens: Node<number>;
57
+ /** Sum of every output-token class across observed calls. */
58
+ readonly totalOutputTokens: Node<number>;
59
+ /** Reset all counters + clear the log. */
60
+ reset(): void;
61
+ }
62
+ /**
63
+ * Wrap any {@link LLMAdapter} with a reactive stats bundle.
64
+ *
65
+ * Implementation:
66
+ * - `stats.lastCall` is a `state<CallStatsEvent | undefined>` exposed via a
67
+ * null-filtering derived so consumers see a typed `Node<CallStatsEvent>`.
68
+ * - Counters (`totalCalls` / `totalInputTokens` / `totalOutputTokens`) are
69
+ * plain state nodes updated via `.emit()`.
70
+ * - `stats.allCalls` is a `reactiveLog<CallStatsEvent>` — bounded, supports
71
+ * `tail(n)` / `slice(start, stop)` for dashboard views.
72
+ * - The wrapped adapter passes DATA through via a `derived` tap that writes
73
+ * to the stats nodes as a side-effect. No pricing — users compose pricing
74
+ * as a derived on top of `stats.lastCall`.
75
+ */
76
+ declare function observableAdapter(inner: LLMAdapter, opts?: {
77
+ logMax?: number;
78
+ name?: string;
79
+ }): {
80
+ adapter: LLMAdapter;
81
+ stats: AdapterStats;
82
+ };
83
+
84
+ /**
85
+ * `withBreaker` — circuit-breaker middleware for LLM adapters.
86
+ *
87
+ * Reuses the library's existing `circuitBreaker` primitive from
88
+ * `extra/resilience.ts`. When the breaker is open, calls throw
89
+ * `CircuitOpenError` instead of hitting the provider.
90
+ */
91
+
92
+ interface WithBreakerOptions extends CircuitBreakerOptions {
93
+ /**
94
+ * Optional external breaker — pass a shared instance to wire the same
95
+ * breaker across multiple adapters (e.g. all tiers of a `cascadingLlmAdapter`).
96
+ */
97
+ breaker?: CircuitBreaker;
98
+ }
99
+ declare function withBreaker(inner: LLMAdapter, opts?: WithBreakerOptions): {
100
+ adapter: LLMAdapter;
101
+ breaker: CircuitBreaker;
102
+ };
103
+
104
+ /**
105
+ * `withBudgetGate` — cap an adapter by calls / tokens / USD.
106
+ *
107
+ * Totals are an O(1)-per-event running accumulator (a `state<BudgetTotals>`
108
+ * updated imperatively inside `record()`), not a derived reduce over the
109
+ * full log — avoids the quadratic cost at sustained traffic while preserving
110
+ * the reactive surface. The full log is still exposed via the bundle for
111
+ * dashboards / auditors.
112
+ *
113
+ * Budgets are enforced imperatively at `invoke()` / `stream()` entry — the
114
+ * running totals + `isOpen.cache` are read; if closed, the call rejects /
115
+ * throws `BudgetExhaustedError` without hitting the wrapped adapter. On
116
+ * success, the call's usage is appended to the log AND debits the running
117
+ * totals in a single synchronous update.
118
+ */
119
+
120
+ declare class BudgetExhaustedError extends Error {
121
+ readonly which: string;
122
+ readonly limit: number;
123
+ readonly observed: number;
124
+ name: string;
125
+ constructor(which: string, limit: number, observed: number);
126
+ }
127
+ interface BudgetCaps {
128
+ calls?: number;
129
+ inputTokens?: number;
130
+ outputTokens?: number;
131
+ usd?: number;
132
+ }
133
+ interface BudgetTotals {
134
+ calls: number;
135
+ inputTokens: number;
136
+ outputTokens: number;
137
+ usd: number;
138
+ }
139
+ interface BudgetGateBundle {
140
+ totals: Node<BudgetTotals>;
141
+ isOpen: Node<boolean>;
142
+ log: ReactiveLogBundle<CallStatsEvent>;
143
+ reset(): void;
144
+ }
145
+ interface WithBudgetGateOptions {
146
+ caps: BudgetCaps;
147
+ /**
148
+ * Optional pricing function for USD gating. If omitted, `caps.usd` is
149
+ * ignored (caps.calls / caps.inputTokens / caps.outputTokens still apply).
150
+ */
151
+ pricingFn?: PricingFn;
152
+ /**
153
+ * Edge-triggered: fires exactly once when the gate transitions from
154
+ * open to closed. Subsequent invoke/stream attempts against a closed
155
+ * gate do NOT re-fire `onExhausted` — use the reactive `isOpen` node
156
+ * if you need per-attempt notifications. Receives the cap key that
157
+ * triggered the transition.
158
+ */
159
+ onExhausted?: (which: keyof BudgetCaps) => void;
160
+ /** Name for logs / describe output. */
161
+ name?: string;
162
+ /** Max events retained in the log (default 1000). */
163
+ logMax?: number;
164
+ }
165
+ /**
166
+ * Wrap an adapter with budget enforcement. Returns `{adapter, budget}` so
167
+ * callers can subscribe to the bundle for dashboards.
168
+ */
169
+ declare function withBudgetGate(inner: LLMAdapter, opts: WithBudgetGateOptions): {
170
+ adapter: LLMAdapter;
171
+ budget: BudgetGateBundle;
172
+ };
173
+
174
+ /**
175
+ * `withDryRun` — short-circuit to a fake adapter when a flag is on.
176
+ *
177
+ * Useful for CI / preflight / cost-safety pipelines: wrap a real adapter,
178
+ * pass `enabled: true` (or a reactive flag) to bypass the wire call. Default
179
+ * shim is {@link dryRunAdapter}; callers can supply their own.
180
+ *
181
+ * **Returns `{adapter, dispose}`** — call `dispose()` to release the internal
182
+ * keepalive on the reactive `enabled` input. Long-lived adapter instances
183
+ * (module-level singletons) can ignore dispose; transient adapters (per-
184
+ * request or per-user) should call it on teardown to allow the source to
185
+ * be GC'd.
186
+ */
187
+
188
+ interface WithDryRunOptions {
189
+ /**
190
+ * Toggle — `true` always dry-runs; `false` always passes through; a
191
+ * `NodeInput<boolean>` reads the current value at call time (factory-time
192
+ * seed pattern, live-tunable).
193
+ */
194
+ enabled: NodeInput<boolean>;
195
+ /** Dry-run adapter override. Default: `dryRunAdapter({ provider: inner.provider, model: inner.model })`. */
196
+ mock?: LLMAdapter;
197
+ }
198
+ interface WithDryRunBundle {
199
+ adapter: LLMAdapter;
200
+ /**
201
+ * Release the internal keepalive subscription on the reactive `enabled`
202
+ * input. Idempotent. Safe to ignore on long-lived adapters.
203
+ */
204
+ dispose(): void;
205
+ }
206
+ declare function withDryRun(inner: LLMAdapter, opts: WithDryRunOptions): WithDryRunBundle;
207
+
208
+ /**
209
+ * Adaptive rate limiter — reactive, live-tunable, 429-aware.
210
+ *
211
+ * Wraps two `tokenBucket` instances (requests, tokens) with:
212
+ * - Reactive `rpm` / `tpm` knobs that can be re-tuned at runtime via `NodeInput<number>`.
213
+ * - An adaptation signal input (`Node<RateLimitSignal>`) that feeds back
214
+ * provider 429 / retry-after / x-ratelimit-* headers to tighten limits.
215
+ * - A `clampCooldownMs` TTL on signal-induced caps so a transient 429 doesn't
216
+ * permanently throttle — caps decay back to user-configured values after
217
+ * the cooldown elapses.
218
+ * - TPM-miss recovery: consumed RPM tokens are returned to the request
219
+ * bucket when the TPM admit fails, via `TokenBucket.putBack`.
220
+ * - Imperative `acquire()` for bridging to Promise-based call paths
221
+ * (used by the `withRateLimiter` adapter middleware).
222
+ *
223
+ * **Timer policy:** sleeps use `ResettableTimer` (documented spec §5.10
224
+ * escape hatch in `src/extra/timer.ts`) rather than `fromTimer` to avoid
225
+ * allocating a new Node per acquire cycle.
226
+ *
227
+ * Design lives in `docs/optimizations.md` § "Reactive adaptive rate limiter".
228
+ */
229
+
230
+ /**
231
+ * Rate-limit signal emitted by an adaptation source (e.g., an HTTP 429 parser).
232
+ *
233
+ * Any subset of fields may be present. The adaptive rate limiter uses:
234
+ * - `retryAfterMs` — blocks acquire() for this duration.
235
+ * - `rpmCap` / `tpmCap` — tightens effective rpm/tpm to this value (decays
236
+ * back to the user-configured cap after `clampCooldownMs`).
237
+ * - `usageHint` — updates the last-known rpm/tpm usage ratio for logging.
238
+ */
239
+ interface RateLimitSignal {
240
+ /** Throttle duration — pause acquire() for this long. */
241
+ retryAfterMs?: number;
242
+ /** Hard cap for requests-per-minute; effective rpm = min(current, rpmCap) while clamp is active. */
243
+ rpmCap?: number;
244
+ /** Hard cap for tokens-per-minute; effective tpm = min(current, tpmCap) while clamp is active. */
245
+ tpmCap?: number;
246
+ /** Observed usage-percentage hint (0..1) — for observability, not gating. */
247
+ usageHint?: {
248
+ rpm?: number;
249
+ tpm?: number;
250
+ };
251
+ /** Free-form provider-specific payload. */
252
+ metadata?: Record<string, unknown>;
253
+ }
254
+ interface AdaptiveRateLimiterBundle {
255
+ /** Effective requests-per-minute (post-signal-clamp). Reactive. */
256
+ readonly effectiveRpm: Node<number>;
257
+ /** Effective tokens-per-minute (post-signal-clamp). Reactive. */
258
+ readonly effectiveTpm: Node<number>;
259
+ /** Last adaptation signal observed. */
260
+ readonly lastSignal: Node<RateLimitSignal>;
261
+ /** Pending `acquire()` callers waiting for capacity. */
262
+ readonly pending: Node<number>;
263
+ /** Current request-token-bucket fill (approximate). */
264
+ readonly rpmAvailable: Node<number>;
265
+ /** Current token-bucket fill (approximate). */
266
+ readonly tpmAvailable: Node<number>;
267
+ /**
268
+ * Imperative bridge: wait until `requestCost` request-tokens and
269
+ * `tokenCost` tokens are available, then consume them. Honors the
270
+ * most recent `retryAfterMs` from adaptation signals. Rejects with
271
+ * an `AbortError`-named error if `signal` aborts while waiting.
272
+ * `requestCost` defaults to 1; `tokenCost` defaults to 0 (rpm-only gating).
273
+ */
274
+ acquire(opts?: {
275
+ requestCost?: number;
276
+ tokenCost?: number;
277
+ signal?: AbortSignal;
278
+ }): Promise<void>;
279
+ /**
280
+ * Feed back observed token usage (post-call) so the TPM bucket reflects
281
+ * real consumption rather than the pre-call estimate. A positive `delta`
282
+ * debits additional TPM (undershot estimate); a negative `delta` credits
283
+ * back overshoot (`putBack`).
284
+ */
285
+ recordUsage(delta: number): void;
286
+ /** Manually feed an adaptation signal — useful for tests. */
287
+ recordSignal(sig: RateLimitSignal): void;
288
+ /** Dispose internal subscriptions and pending timers. */
289
+ dispose(): void;
290
+ }
291
+
292
+ /**
293
+ * HTTP 429 / rate-limit parser.
294
+ *
295
+ * Produces a {@link RateLimitSignal} from provider HTTP errors so adaptive
296
+ * rate limiters can tighten effective limits. Normalizes:
297
+ * - `Retry-After` (seconds or HTTP-date)
298
+ * - `x-ratelimit-reset` / `x-ratelimit-reset-tokens` (epoch secs or duration)
299
+ * - `x-ratelimit-remaining-{requests,tokens}` + `x-ratelimit-limit-*`
300
+ * - Anthropic `anthropic-ratelimit-*` headers
301
+ * - OpenAI / OpenRouter / Groq headers (same family)
302
+ * - Error message regex fallbacks for providers without structured headers
303
+ */
304
+
305
+ interface HttpErrorLike {
306
+ status?: number;
307
+ headers?: Headers | Record<string, string | string[] | undefined>;
308
+ message?: string;
309
+ }
310
+ /**
311
+ * Extract a {@link RateLimitSignal} from a fetch-style error object, a Response,
312
+ * or any object exposing `.status` + `.headers` + `.message`.
313
+ *
314
+ * Returns `undefined` if no rate-limit information can be extracted.
315
+ */
316
+ declare function parseRateLimitFromError(err: unknown): RateLimitSignal | undefined;
317
+
318
+ /**
319
+ * `withRateLimiter` — adapter middleware bridging to the reactive
320
+ * `adaptiveRateLimiter` primitive.
321
+ *
322
+ * - Consumes live `rpm`/`tpm` caps as reactive `NodeInput<number>` so
323
+ * callers can retune at runtime (e.g. from a `ModelLimits.rpm` node).
324
+ * - Adapts to provider 429 responses via `http429Parser` fed into the
325
+ * limiter's `adaptation` signal.
326
+ * - `costFn` estimates token cost pre-call (e.g. char-based approximation);
327
+ * the post-call actual usage is fed back via `limiter.recordUsage()`.
328
+ */
329
+
330
+ interface WithRateLimiterOptions {
331
+ /** Live rpm cap (defaults to `Infinity`). */
332
+ rpm?: NodeInput<number>;
333
+ /** Live tpm cap (defaults to `Infinity`). */
334
+ tpm?: NodeInput<number>;
335
+ /**
336
+ * Pre-call token-cost estimate. Default: 0 (only rpm gates). Override with
337
+ * e.g. a char-based heuristic:
338
+ * `(msgs) => Math.ceil(msgs.reduce((s, m) => s + m.content.length, 0) / 4)`.
339
+ */
340
+ costFn?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => number;
341
+ /**
342
+ * Manual adaptation signal source. Defaults to a signal derived from
343
+ * provider errors via `parseRateLimitFromError` — users can supply a
344
+ * custom signal chain if they route errors elsewhere.
345
+ */
346
+ adaptation?: NodeInput<RateLimitSignal>;
347
+ burstMultiplier?: number;
348
+ name?: string;
349
+ /**
350
+ * Share an existing {@link AdaptiveRateLimiterBundle} across multiple
351
+ * adapter wraps. When provided, `withRateLimiter` reuses this bundle
352
+ * instead of constructing a new one — useful when the RPM/TPM cap is
353
+ * logically per-provider but the caller wants to harden multiple adapters
354
+ * (e.g. primary + fallback of the same vendor) against the shared cap.
355
+ *
356
+ * When `limiter` is set, `rpm` / `tpm` / `adaptation` / `burstMultiplier`
357
+ * / `name` are ignored (the supplied bundle owns those). `costFn` is still
358
+ * used per-wrap — each wrap supplies its own cost estimator.
359
+ */
360
+ limiter?: AdaptiveRateLimiterBundle;
361
+ }
362
+ /**
363
+ * Wrap an adapter with adaptive rate limiting. Returns `{adapter, limiter}`
364
+ * so callers can subscribe to limiter internals (rpmAvailable, pending, etc.)
365
+ * for dashboards.
366
+ */
367
+ declare function withRateLimiter(inner: LLMAdapter, opts?: WithRateLimiterOptions): {
368
+ adapter: LLMAdapter;
369
+ limiter: AdaptiveRateLimiterBundle;
370
+ };
371
+
372
+ /**
373
+ * `withRetry` — retry `invoke()` / `stream()` on transient errors.
374
+ *
375
+ * Streaming retry is tricky: we retry only if the stream fails before
376
+ * yielding any tokens. Once tokens have started flowing, we surface the
377
+ * error to avoid replaying from scratch (which would double-bill and
378
+ * confuse consumers). Opt out of streaming retry via `opts.retryStreaming = false`.
379
+ *
380
+ * Uses `ResettableTimer` for backoff sleeps (spec §5.10 escape hatch, same
381
+ * pattern as `extra/resilience.ts`). Abort-aware — early-aborts before the
382
+ * first attempt and cleans up the abort listener on both the timer-fires
383
+ * and abort paths.
384
+ */
385
+
386
+ interface WithRetryOptions {
387
+ /** Max total attempts (including the first). Default 3. */
388
+ attempts?: number;
389
+ /** Base delay in ms. Default 500. */
390
+ baseDelayMs?: number;
391
+ /** Max delay in ms. Default 10_000. */
392
+ maxDelayMs?: number;
393
+ /**
394
+ * Delay strategy. Default `"decorrelated"` — AWS-style `random(baseDelay,
395
+ * min(maxDelay, prev * 3))` which smooths retry storms and matches common
396
+ * SDK expectations. `"exp"` and `"linear"` produce deterministic schedules
397
+ * when `jitter: false`.
398
+ */
399
+ strategy?: "exp" | "linear" | "decorrelated";
400
+ /**
401
+ * Add randomized jitter. Ignored for `strategy: "decorrelated"` (which is
402
+ * inherently jittered). For `exp`/`linear`, symmetric jitter in `[0.5x,
403
+ * 1.5x]` of the nominal delay.
404
+ */
405
+ jitter?: boolean;
406
+ /**
407
+ * Predicate: should this error trigger a retry? Default retries network /
408
+ * 5xx / 429 / transient errors, but not 4xx (other than 429), aborts, or
409
+ * `BudgetExhaustedError` from upstream middleware.
410
+ */
411
+ shouldRetry?: (err: unknown, attempt: number) => boolean;
412
+ /** Retry streaming calls if they fail pre-first-token. Default true. */
413
+ retryStreaming?: boolean;
414
+ }
415
+ declare function withRetry(inner: LLMAdapter, opts?: WithRetryOptions): LLMAdapter;
416
+
417
+ /**
418
+ * `resilientAdapter` — compose `withRateLimiter` + `withBudgetGate` +
419
+ * `withBreaker` + `withTimeout` + `withRetry` + fallback over an {@link LLMAdapter}.
420
+ *
421
+ * Call-path peer of {@link resilientPipeline} (which operates on a reactive
422
+ * `Node<T>` chain). Use `resilientPipeline` when composing graph sources; use
423
+ * `resilientAdapter` when wrapping an adapter so downstream users see a
424
+ * single hardened `invoke`/`stream` surface.
425
+ *
426
+ * Composition order (innermost to outermost, mirrors `resilientPipeline`):
427
+ *
428
+ * ```text
429
+ * rateLimit → budget → breaker → timeout → retry → fallback
430
+ * ```
431
+ *
432
+ * Rationale:
433
+ * - **rateLimit innermost** — each attempt acquires a fresh slot; a retry
434
+ * after a 429 waits for admission rather than bursting past the cap.
435
+ * - **budget next** — per-attempt gate close short-circuits retries once a
436
+ * cap trips.
437
+ * - **breaker next** — each attempt observes circuit health; open breaker
438
+ * fast-fails retries into fallback.
439
+ * - **timeout before retry** — each retry re-arms a fresh per-attempt
440
+ * deadline. If `timeout` wrapped `retry`, a single deadline would cover
441
+ * the entire retry chain — surprising for callers.
442
+ * - **retry before fallback** — fallback is entered only after the primary
443
+ * exhausts its retry budget (or immediately fails in a way the predicate
444
+ * doesn't retry).
445
+ *
446
+ * Every option is optional — omit the field and that layer is skipped. The
447
+ * returned bundle exposes the primary adapter plus the internal bundles
448
+ * (`rateLimiter`, `budget`, `breaker`) so callers can wire them into
449
+ * dashboards, alerts, or `graphLens`.
450
+ *
451
+ * Fallback is implemented via {@link cascadingLlmAdapter}: when `fallback`
452
+ * is provided, the wrapped primary adapter is placed at tier 0 and the
453
+ * fallback adapter at tier 1. For N-tier cascades, use `cascadingLlmAdapter`
454
+ * directly and wrap each tier with `resilientAdapter`.
455
+ *
456
+ * @module
457
+ */
458
+
459
+ /** Options for {@link resilientAdapter}. Every field is optional — omit to skip that layer. */
460
+ interface ResilientAdapterOptions {
461
+ /** Admission control. See {@link withRateLimiter}. */
462
+ rateLimit?: WithRateLimiterOptions;
463
+ /** Cost/cap gate. See {@link withBudgetGate}. */
464
+ budget?: WithBudgetGateOptions;
465
+ /** Circuit breaker. See {@link withBreaker}. */
466
+ breaker?: WithBreakerOptions;
467
+ /** Per-attempt deadline in milliseconds. Omit to skip the timeout wrap. */
468
+ timeoutMs?: number;
469
+ /** Retry policy on transient errors. See {@link withRetry}. */
470
+ retry?: WithRetryOptions;
471
+ /**
472
+ * Fallback adapter engaged when the primary (post-retry) fails. Implemented
473
+ * via {@link cascadingLlmAdapter} — the primary becomes tier 0, the
474
+ * fallback becomes tier 1. For N-tier cascades, use `cascadingLlmAdapter`
475
+ * directly and wrap each tier with `resilientAdapter` as needed.
476
+ */
477
+ fallback?: LLMAdapter;
478
+ /** Name used as the primary tier name in the fallback cascade. Default `"primary"`. */
479
+ name?: string;
480
+ /**
481
+ * Called when the cascade switches from one tier to the next after a
482
+ * failure. Only fires when `fallback` is set. Threaded directly to the
483
+ * inner {@link cascadingLlmAdapter}.
484
+ */
485
+ onFallback?: (from: string, to: string, error: unknown) => void;
486
+ /**
487
+ * Called when every tier in the cascade has been exhausted (all failed,
488
+ * skipped by filter, or skipped by breaker). Only fires when `fallback`
489
+ * is set. Threaded directly to the inner {@link cascadingLlmAdapter}.
490
+ */
491
+ onExhausted?: (report: CascadeExhaustionReport) => void;
492
+ }
493
+ /** Output bundle of {@link resilientAdapter}. */
494
+ interface ResilientAdapterBundle {
495
+ /** The final hardened adapter. */
496
+ adapter: LLMAdapter;
497
+ /** Rate-limiter internals (for dashboards). Present only when `opts.rateLimit` was set. */
498
+ rateLimiter?: AdaptiveRateLimiterBundle;
499
+ /** Budget gate internals (for dashboards). Present only when `opts.budget` was set. */
500
+ budget?: BudgetGateBundle;
501
+ /** Circuit breaker (for dashboards). Present only when `opts.breaker` was set. */
502
+ breaker?: CircuitBreaker;
503
+ }
504
+ /**
505
+ * Wrap `inner` with the standard resilience stack. See module docs for the
506
+ * composition order and rationale.
507
+ *
508
+ * @example
509
+ * ```ts
510
+ * const { adapter, budget, breaker } = resilientAdapter(openai, {
511
+ * rateLimit: { rpm: 60, tpm: 90_000 },
512
+ * budget: { caps: { usd: 5 } },
513
+ * breaker: { failureThreshold: 5, resetTimeoutMs: 30_000 },
514
+ * timeoutMs: 30_000,
515
+ * retry: { attempts: 3 },
516
+ * fallback: webllm, // cascades to local on exhaustion
517
+ * });
518
+ *
519
+ * // `adapter` is drop-in for anything expecting LLMAdapter.
520
+ * // Subscribe to `budget.totals`, `breaker.state`, etc. for dashboards.
521
+ * ```
522
+ */
523
+ declare function resilientAdapter(inner: LLMAdapter, opts?: ResilientAdapterOptions): ResilientAdapterBundle;
524
+
525
+ /**
526
+ * `withTimeout` — cancel `invoke()` / `stream()` after `ms` elapse.
527
+ *
528
+ * Wires a child AbortSignal so provider adapters can honor the cancellation
529
+ * (all shipped adapters forward `signal` through to their fetch / SDK call).
530
+ *
531
+ * Uses `ResettableTimer` rather than raw `setTimeout` — same pattern as
532
+ * `extra/resilience.ts` (spec §5.10 escape hatch documented on the class).
533
+ */
534
+
535
+ declare class LLMTimeoutError extends Error {
536
+ readonly ms: number;
537
+ name: string;
538
+ constructor(ms: number);
539
+ }
540
+ declare function withTimeout(inner: LLMAdapter, ms: number): LLMAdapter;
541
+
542
+ /**
543
+ * AnthropicAdapter — default fetch-backed, optional SDK-backed.
544
+ *
545
+ * - `anthropicAdapter({ apiKey })` uses native `fetch` + SSE parsing.
546
+ * - `anthropicAdapter({ sdk })` delegates to a user-provided `@anthropic-ai/sdk` instance.
547
+ *
548
+ * Token usage mapping:
549
+ * - `input_tokens` → `input.regular`
550
+ * - `cache_read_input_tokens` → `input.cacheRead`
551
+ * - `cache_creation.ephemeral_5m_input_tokens` → `input.cacheWrite5m`
552
+ * - `cache_creation.ephemeral_1h_input_tokens` → `input.cacheWrite1h`
553
+ * - `cache_creation_input_tokens` (legacy) → `input.cacheWrite5m` (default TTL)
554
+ * - `output_tokens` → `output.regular`
555
+ * - `server_tool_use.web_search_requests` → `auxiliary.webSearchRequests`
556
+ */
557
+
558
+ interface AnthropicAdapterOptions {
559
+ /** API key. Falls back to `process.env.ANTHROPIC_API_KEY` on Node. */
560
+ apiKey?: string;
561
+ /** Default model (overridable per-call via `LLMInvokeOptions.model`). */
562
+ model?: string;
563
+ /** Override the base URL. Default `https://api.anthropic.com`. */
564
+ baseURL?: string;
565
+ /** API version header. Default `"2023-06-01"`. */
566
+ anthropicVersion?: string;
567
+ /** Additional headers to send on every request (overridden by per-call). */
568
+ headers?: Record<string, string>;
569
+ /**
570
+ * User-provided SDK instance. When present, the adapter delegates to it
571
+ * (uses `.messages.create`) instead of native fetch.
572
+ * Shape matches `@anthropic-ai/sdk` `.messages` API; any object with a
573
+ * compatible `create`/`stream` contract works.
574
+ */
575
+ sdk?: AnthropicSdkLike;
576
+ /** Custom fetch (useful for tests). Default `globalThis.fetch`. */
577
+ fetchImpl?: typeof fetch;
578
+ }
579
+ /** Minimal SDK shape we interoperate with. */
580
+ interface AnthropicSdkLike {
581
+ messages: {
582
+ create(params: Record<string, unknown>, opts?: {
583
+ signal?: AbortSignal;
584
+ }): Promise<AnthropicMessageResponse>;
585
+ stream?(params: Record<string, unknown>, opts?: {
586
+ signal?: AbortSignal;
587
+ }): AsyncIterable<AnthropicStreamEvent>;
588
+ };
589
+ }
590
+ interface AnthropicMessageResponse {
591
+ id: string;
592
+ content: ReadonlyArray<{
593
+ type: "text";
594
+ text: string;
595
+ } | {
596
+ type: "tool_use";
597
+ id: string;
598
+ name: string;
599
+ input: Record<string, unknown>;
600
+ } | {
601
+ type: "thinking";
602
+ thinking: string;
603
+ } | {
604
+ type: string;
605
+ [key: string]: unknown;
606
+ }>;
607
+ stop_reason?: string;
608
+ usage: AnthropicUsage;
609
+ model?: string;
610
+ }
611
+ interface AnthropicUsage {
612
+ input_tokens?: number;
613
+ output_tokens?: number;
614
+ cache_read_input_tokens?: number;
615
+ cache_creation_input_tokens?: number;
616
+ cache_creation?: {
617
+ ephemeral_5m_input_tokens?: number;
618
+ ephemeral_1h_input_tokens?: number;
619
+ };
620
+ server_tool_use?: {
621
+ web_search_requests?: number;
622
+ };
623
+ }
624
+ type AnthropicStreamEvent = {
625
+ type: "message_start";
626
+ message: {
627
+ usage: AnthropicUsage;
628
+ };
629
+ } | {
630
+ type: "content_block_start";
631
+ index: number;
632
+ content_block: Record<string, unknown>;
633
+ } | {
634
+ type: "content_block_delta";
635
+ index: number;
636
+ delta: Record<string, unknown>;
637
+ } | {
638
+ type: "content_block_stop";
639
+ index: number;
640
+ } | {
641
+ type: "message_delta";
642
+ delta: {
643
+ stop_reason?: string;
644
+ usage?: AnthropicUsage;
645
+ };
646
+ } | {
647
+ type: "message_stop";
648
+ } | {
649
+ type: string;
650
+ [key: string]: unknown;
651
+ };
652
+ declare function anthropicAdapter(opts?: AnthropicAdapterOptions): LLMAdapter;
653
+
654
+ /**
655
+ * DryRunAdapter — zero-cost mock provider.
656
+ *
657
+ * Returns a deterministic fake response (plus a configurable hook for
658
+ * customization). Useful for: pipeline smoke tests, CI without API keys,
659
+ * local development, and as the leaf of a `cascadingLlmAdapter` when every
660
+ * real tier fails.
661
+ *
662
+ * The library ships a minimal implementation only — richer scenario-
663
+ * scripted mocks (per-stage responses, call recording) belong at the test
664
+ * harness layer, not in the shipped library.
665
+ *
666
+ * Uses `ResettableTimer` for simulated latency (spec §5.10 escape hatch
667
+ * documented on the class), and throws an `AbortError`-named Error on
668
+ * abort so retry/timeout middleware can classify it.
669
+ */
670
+
671
+ interface DryRunAdapterOptions {
672
+ provider?: string;
673
+ model?: string;
674
+ /** Generate the fake response. Defaults to echoing the last user message. */
675
+ respond?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => string;
676
+ /**
677
+ * Generate a fake usage object. Defaults to a simple character-count
678
+ * heuristic (`input = sum(messages) / 4`, `output = content / 4`).
679
+ */
680
+ usage?: (messages: readonly ChatMessage[], content: string) => TokenUsage;
681
+ /** Simulated latency in milliseconds (applied to both invoke and stream). */
682
+ latencyMs?: number;
683
+ /** Stream chunk size in characters. Default 16. */
684
+ streamChunkSize?: number;
685
+ }
686
+ /**
687
+ * Create a DryRun adapter.
688
+ *
689
+ * @example
690
+ * ```ts
691
+ * const adapter = dryRunAdapter({ respond: (msgs) => "hello from dry-run" });
692
+ * const resp = await Promise.resolve(adapter.invoke([{ role: "user", content: "hi" }]));
693
+ * ```
694
+ */
695
+ declare function dryRunAdapter(opts?: DryRunAdapterOptions): LLMAdapter;
696
+
697
+ /**
698
+ * GoogleAdapter — default fetch-backed, optional SDK-backed.
699
+ *
700
+ * Maps Gemini `usageMetadata`:
701
+ * - `promptTokenCount` minus `cachedContentTokenCount` → `input.regular`
702
+ * - `cachedContentTokenCount` → `input.cacheRead`
703
+ * - `candidatesTokenCount` → `output.regular`
704
+ * - `thoughtsTokenCount` → `output.reasoning`
705
+ * - `toolUsePromptTokenCount` → `input.toolUse`
706
+ * - `promptTokensDetails[]` → `input.{image,audio,video}` per modality
707
+ */
708
+
709
+ interface GoogleAdapterOptions {
710
+ /** API key. Falls back to `process.env.GOOGLE_API_KEY` / `GEMINI_API_KEY` on Node. */
711
+ apiKey?: string;
712
+ model?: string;
713
+ baseURL?: string;
714
+ /** Extra headers on every request. */
715
+ headers?: Record<string, string>;
716
+ /** Optional SDK instance (`@google/genai` or `@google/generative-ai` shape). */
717
+ sdk?: GoogleSdkLike;
718
+ fetchImpl?: typeof fetch;
719
+ }
720
+ interface GoogleSdkLike {
721
+ models: {
722
+ generateContent(params: Record<string, unknown>, opts?: {
723
+ signal?: AbortSignal;
724
+ }): Promise<GeminiResponse>;
725
+ generateContentStream?(params: Record<string, unknown>, opts?: {
726
+ signal?: AbortSignal;
727
+ }): AsyncIterable<GeminiResponse>;
728
+ };
729
+ }
730
+ interface GeminiResponse {
731
+ candidates?: ReadonlyArray<{
732
+ content?: {
733
+ role?: string;
734
+ parts?: ReadonlyArray<{
735
+ text?: string;
736
+ thought?: boolean;
737
+ functionCall?: {
738
+ name: string;
739
+ args: Record<string, unknown>;
740
+ };
741
+ }>;
742
+ };
743
+ finishReason?: string;
744
+ }>;
745
+ usageMetadata?: GeminiUsage;
746
+ modelVersion?: string;
747
+ }
748
+ interface GeminiUsage {
749
+ promptTokenCount?: number;
750
+ candidatesTokenCount?: number;
751
+ totalTokenCount?: number;
752
+ thoughtsTokenCount?: number;
753
+ cachedContentTokenCount?: number;
754
+ toolUsePromptTokenCount?: number;
755
+ promptTokensDetails?: ReadonlyArray<{
756
+ modality: string;
757
+ tokenCount: number;
758
+ }>;
759
+ candidatesTokensDetails?: ReadonlyArray<{
760
+ modality: string;
761
+ tokenCount: number;
762
+ }>;
763
+ cacheTokensDetails?: ReadonlyArray<{
764
+ modality: string;
765
+ tokenCount: number;
766
+ }>;
767
+ }
768
+ declare function googleAdapter(opts?: GoogleAdapterOptions): LLMAdapter;
769
+
770
+ /**
771
+ * Curated `cascadingLlmAdapter` presets — Node/browser-safe subset.
772
+ *
773
+ * Thin compositions over `cascadingLlmAdapter` + `createAdapter`. No new
774
+ * logic — just convenient defaults. Users needing finer control call
775
+ * `cascadingLlmAdapter` directly.
776
+ *
777
+ * Presets that depend on browser-only adapters (WebLLM, Chrome Nano) have
778
+ * been split out to [`./browser-presets.ts`](./browser-presets.ts) and are
779
+ * exported from the `@graphrefly/graphrefly/patterns/ai/browser`
780
+ * subpath so they don't leak into Node bundles.
781
+ *
782
+ * @module
783
+ */
784
+
785
+ declare function dryRunPreset(): LLMAdapter;
786
+
787
+ /**
788
+ * `fromLLM` — reactive LLM invocation sugar.
789
+ *
790
+ * @module
791
+ */
792
+
793
+ type FromLLMOptions = {
794
+ name?: string;
795
+ model?: string;
796
+ temperature?: number;
797
+ maxTokens?: number;
798
+ tools?: readonly ToolDefinition[];
799
+ systemPrompt?: string;
800
+ };
801
+ /**
802
+ * Reactive LLM invocation adapter. Returns a derived node that re-invokes
803
+ * the LLM whenever the messages dep changes.
804
+ *
805
+ * Uses `switchMap` internally — new invocations cancel stale in-flight ones.
806
+ */
807
+ declare function fromLLM(adapter: LLMAdapter, messages: NodeInput<readonly ChatMessage[]>, opts?: FromLLMOptions): Node<LLMResponse | null>;
808
+
809
+ /**
810
+ * `frozenContext` — prefix-cache-friendly snapshot of upstream context.
811
+ *
812
+ * @module
813
+ */
814
+
815
+ type FrozenContextOptions = {
816
+ /**
817
+ * Reactive signal that triggers re-materialization. Each `DATA` emission
818
+ * from this node re-reads the source and refreshes the frozen value.
819
+ * Typical shapes: `fromTimer(ms)` for periodic refresh, a stage-transition
820
+ * node for event-driven refresh, or a manual `state<number>` the caller
821
+ * increments via `setState(n + 1)`.
822
+ *
823
+ * When omitted, the frozen value is materialized exactly once (on first
824
+ * subscribe) and never refreshes — use this for session-start snapshots
825
+ * that must stay stable for the lifetime of the activation.
826
+ */
827
+ refreshTrigger?: NodeInput<unknown>;
828
+ name?: string;
829
+ };
830
+ /**
831
+ * Freeze a reactive source into a stable snapshot that only re-materializes
832
+ * on explicit trigger. Built for long-running harness loops where system
833
+ * prompts include `agentMemory` / stage context — every reactive change to
834
+ * the source invalidates the LLM provider's prefix cache, so re-rendering
835
+ * the prompt every turn is expensive.
836
+ *
837
+ * `frozenContext(source)` reads the source once and caches the value;
838
+ * downstream `promptNode` compositions see a stable reference until the
839
+ * optional `refreshTrigger` fires.
840
+ *
841
+ * Trade-off: slightly stale context vs. prefix cache hit rate. For most
842
+ * harness apps, the memory snapshot at session start is "good enough" —
843
+ * refreshing on a coarse-grained trigger (`fromCron("*\/30min")`, stage
844
+ * transition) preserves 90%+ prefix cache hits while keeping context useful.
845
+ *
846
+ * @example
847
+ * ```ts
848
+ * // Freeze agent memory for the duration of a stage.
849
+ * const frozen = frozenContext(memory.context, {
850
+ * refreshTrigger: stage, // re-materialize on stage change
851
+ * });
852
+ * const reply = promptNode({ context: frozen, ... });
853
+ * ```
854
+ *
855
+ * @category patterns.ai
856
+ */
857
+ declare function frozenContext<T>(source: NodeInput<T>, opts?: FrozenContextOptions): Node<T | null>;
858
+
859
+ /**
860
+ * `promptNode` — universal LLM transform as a reactive derived node.
861
+ *
862
+ * @module
863
+ */
864
+
865
+ type PromptNodeOptions = {
866
+ name?: string;
867
+ model?: string;
868
+ temperature?: number;
869
+ maxTokens?: number;
870
+ /** Output format — `"json"` attempts JSON.parse on the response. Default: `"text"`. */
871
+ format?: "text" | "json";
872
+ /** Number of retries on transient errors. Default: 0. */
873
+ retries?: number;
874
+ /** Cache LLM responses for identical inputs. Default: false. */
875
+ cache?: boolean;
876
+ systemPrompt?: string;
877
+ meta?: Record<string, unknown>;
878
+ };
879
+ /**
880
+ * Universal LLM transform: wraps a prompt template + model adapter into a reactive derived node.
881
+ * Re-invokes the LLM whenever any dep changes. Suitable for triage, QA, hypothesis, parity, etc.
882
+ *
883
+ * @param adapter - LLM adapter (provider-agnostic).
884
+ * @param deps - Input nodes whose values feed the prompt.
885
+ * @param prompt - Static string or template function receiving dep values.
886
+ * @param opts - Optional configuration.
887
+ * @returns `Node` emitting LLM responses (string or parsed JSON).
888
+ */
889
+ declare function promptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: PromptNodeOptions): Node<T | null>;
890
+
891
+ /**
892
+ * `streamingPromptNode` + `gatedStream` — streaming LLM transforms, plus the
893
+ * shared `StreamChunk` shape.
894
+ *
895
+ * @module
896
+ */
897
+
898
+ /**
899
+ * A single chunk from any streaming source (LLM tokens, WebSocket, SSE, file tail).
900
+ * Generic enough for any streaming source, not just LLM.
901
+ */
902
+ type StreamChunk = {
903
+ /** Identifier for the stream source (adapter name, URL, etc.). */
904
+ readonly source: string;
905
+ /** This chunk's content. */
906
+ readonly token: string;
907
+ /** Full accumulated text so far. */
908
+ readonly accumulated: string;
909
+ /** 0-based chunk counter. */
910
+ readonly index: number;
911
+ };
912
+ type StreamingPromptNodeOptions = {
913
+ name?: string;
914
+ model?: string;
915
+ temperature?: number;
916
+ maxTokens?: number;
917
+ /** Output format — `"json"` attempts JSON.parse on the final accumulated text. Default: `"text"`. */
918
+ format?: "text" | "json";
919
+ systemPrompt?: string;
920
+ };
921
+ /**
922
+ * Bundle returned by {@link streamingPromptNode}.
923
+ */
924
+ type StreamingPromptNodeHandle<T> = {
925
+ /** Final parsed result (emits once per invocation, after stream completes). */
926
+ output: Node<T | null>;
927
+ /** Live stream topic — subscribe to `stream.latest` or `stream.events` for chunks. */
928
+ stream: TopicGraph<StreamChunk>;
929
+ /** Tear down the keepalive subscription and release resources. */
930
+ dispose: () => void;
931
+ };
932
+ /**
933
+ * Streaming LLM transform: wraps a prompt template + adapter into a reactive
934
+ * streaming pipeline. Re-invokes the LLM whenever any dep changes; the
935
+ * previous in-flight stream is canceled automatically via `switchMap`.
936
+ *
937
+ * Each token chunk is published to a {@link TopicGraph} as a {@link StreamChunk}.
938
+ * Extractors can mount on the topic independently (see `streamExtractor`).
939
+ * Zero overhead if nobody subscribes to the stream topic.
940
+ *
941
+ * The `output` node emits the final parsed result (like `promptNode`).
942
+ * The async boundary is handled by `fromAny` (spec §5.10 compliant).
943
+ */
944
+ declare function streamingPromptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: StreamingPromptNodeOptions): StreamingPromptNodeHandle<T>;
945
+ type GatedStreamOptions = StreamingPromptNodeOptions & {
946
+ /** Gate options (maxPending, startOpen). */
947
+ gate?: Omit<GateOptions, "meta">;
948
+ };
949
+ /**
950
+ * Bundle returned by {@link gatedStream}.
951
+ */
952
+ type GatedStreamHandle<T> = {
953
+ /** Final parsed result (after gate approval). */
954
+ output: Node<T | null>;
955
+ /** Live stream topic — subscribe to `stream.latest` for chunks. */
956
+ stream: TopicGraph<StreamChunk>;
957
+ /** Gate controller — approve, reject (aborts in-flight stream), modify. */
958
+ gate: GateController<T | null>;
959
+ /** Tear down everything. */
960
+ dispose: () => void;
961
+ };
962
+ /**
963
+ * Streaming LLM transform with human-in-the-loop gate integration.
964
+ *
965
+ * Composes {@link streamingPromptNode} with `gate` so that:
966
+ * - `gate.reject()` discards the pending value **and** aborts the in-flight
967
+ * stream (cancels the `AbortController`).
968
+ * - `gate.modify()` transforms the pending value before forwarding downstream.
969
+ * - `gate.approve()` forwards the final result as normal.
970
+ *
971
+ * The abort-on-reject works by toggling an internal cancel signal that causes
972
+ * the `switchMap` inside `streamingPromptNode` to restart with an empty message
973
+ * list, which triggers the `AbortController.abort()` in the async generator's
974
+ * `finally` block.
975
+ */
976
+ declare function gatedStream<T = string>(graph: Graph, name: string, adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: GatedStreamOptions): GatedStreamHandle<T>;
977
+
978
+ /**
979
+ * `systemPromptBuilder` — assembles a reactive system prompt from sections.
980
+ *
981
+ * @module
982
+ */
983
+
984
+ /**
985
+ * Assembles a system prompt from reactive sections. Each section is a
986
+ * `NodeInput<string>` — the prompt updates when any section changes.
987
+ */
988
+ type SystemPromptHandle = Node<string> & {
989
+ dispose: () => void;
990
+ };
991
+ declare function systemPromptBuilder(sections: readonly NodeInput<string>[], opts?: {
992
+ separator?: string;
993
+ name?: string;
994
+ }): SystemPromptHandle;
995
+
996
+ /**
997
+ * Cost meter extractor — counts chunks, characters, and estimates token usage.
998
+ * @module
999
+ */
1000
+
1001
+ /** A cost meter reading from the stream. */
1002
+ type CostMeterReading = {
1003
+ readonly chunkCount: number;
1004
+ readonly charCount: number;
1005
+ readonly estimatedTokens: number;
1006
+ };
1007
+ type CostMeterOptions = {
1008
+ /** Characters per token approximation. Default: 4 (GPT-family). */
1009
+ charsPerToken?: number;
1010
+ name?: string;
1011
+ };
1012
+ /**
1013
+ * Mounts a cost meter on a streaming topic. Counts chunks, characters, and
1014
+ * estimates token count. Compose with `budgetGate` for hard-stop when LLM
1015
+ * output exceeds budget mid-generation.
1016
+ *
1017
+ * Default structural equals suppresses DATA emission when two consecutive
1018
+ * readings are identical (same chunk count + char count + token estimate).
1019
+ */
1020
+ declare function costMeterExtractor(streamTopic: TopicGraph<StreamChunk>, opts?: CostMeterOptions): Node<CostMeterReading>;
1021
+
1022
+ /**
1023
+ * Keyword-flag extractor — scans accumulated stream text for configured patterns.
1024
+ * @module
1025
+ */
1026
+
1027
+ /** A keyword match detected in the stream. */
1028
+ type KeywordFlag = {
1029
+ readonly label: string;
1030
+ readonly pattern: RegExp;
1031
+ readonly match: string;
1032
+ readonly position: number;
1033
+ };
1034
+ type KeywordFlagExtractorOptions = {
1035
+ patterns: readonly {
1036
+ pattern: RegExp;
1037
+ label: string;
1038
+ }[];
1039
+ name?: string;
1040
+ /**
1041
+ * Maximum length of any pattern's literal text. Used as an overlap window
1042
+ * when cursoring through the accumulated stream so matches that span
1043
+ * chunk boundaries aren't missed. Default: 128.
1044
+ */
1045
+ maxPatternLength?: number;
1046
+ };
1047
+ /**
1048
+ * Mounts a keyword-flag extractor on a streaming topic. Scans accumulated text
1049
+ * for all configured patterns and emits an array of matches.
1050
+ *
1051
+ * Use cases: design invariant violations (`setTimeout`, `EventEmitter`), PII
1052
+ * detection (SSN, email, phone), toxicity keywords, off-track reasoning.
1053
+ *
1054
+ * **Streaming optimization.** Maintains a cursor across chunks in `ctx.store`
1055
+ * so each chunk scans only the delta region `accumulated.slice(scannedTo -
1056
+ * maxPatternLength)` — not the full string. Default structural equals
1057
+ * suppresses DATA emission when no new flags were found this chunk.
1058
+ */
1059
+ declare function keywordFlagExtractor(streamTopic: TopicGraph<StreamChunk>, opts: KeywordFlagExtractorOptions): Node<readonly KeywordFlag[]>;
1060
+
1061
+ /**
1062
+ * Generic stream extractor — mounts an extract function on a streaming topic.
1063
+ * @module
1064
+ */
1065
+
1066
+ /**
1067
+ * Mounts an extractor function on a streaming topic. Returns a derived node
1068
+ * that emits extracted values as chunks arrive.
1069
+ *
1070
+ * `extractFn` receives the accumulated text from the latest chunk and returns
1071
+ * the extracted value, or `null` if nothing detected yet. This is the building
1072
+ * block for keyword flags, tool call detection, cost metering, etc.
1073
+ *
1074
+ * @param streamTopic - The stream topic to extract from.
1075
+ * @param extractFn - `(accumulated: string) => T | null`.
1076
+ * @param opts - Optional name.
1077
+ * @returns Derived node emitting extracted values.
1078
+ */
1079
+ declare function streamExtractor<T>(streamTopic: TopicGraph<StreamChunk>, extractFn: (accumulated: string) => T | null, opts?: {
1080
+ name?: string;
1081
+ /**
1082
+ * Optional structural equals for the extractor output. When two
1083
+ * consecutive chunks produce structurally-equal outputs, the framework
1084
+ * emits `RESOLVED` instead of `DATA`, saving downstream work. Default:
1085
+ * reference equality (`Object.is`). The library cannot know your
1086
+ * output shape — supply this when your `extractFn` returns structured
1087
+ * objects or arrays.
1088
+ */
1089
+ equals?: (a: T | null, b: T | null) => boolean;
1090
+ }): Node<T | null>;
1091
+
1092
+ /**
1093
+ * Tool-call extractor — scans accumulated stream text for complete JSON tool call objects.
1094
+ * @module
1095
+ */
1096
+
1097
+ /** A tool call detected in the stream. */
1098
+ type ExtractedToolCall = {
1099
+ readonly name: string;
1100
+ readonly arguments: Record<string, unknown>;
1101
+ readonly raw: string;
1102
+ readonly startIndex: number;
1103
+ };
1104
+ /**
1105
+ * Mounts a tool-call extractor on a streaming topic. Scans accumulated text
1106
+ * for complete JSON objects containing `"name"` and `"arguments"` keys (the
1107
+ * standard tool_call shape). Partial JSON is ignored until the closing brace.
1108
+ *
1109
+ * Feeds into the tool interception chain for reactive tool gating mid-stream.
1110
+ *
1111
+ * **Streaming optimization.** Maintains a cursor (`scanFrom`) in `ctx.store`
1112
+ * so each chunk resumes brace-scanning from the position after the last
1113
+ * complete parse (or the last incomplete open brace). Already-parsed objects
1114
+ * are not re-parsed. Default structural equals suppresses DATA emission when
1115
+ * no new tool call completed this chunk.
1116
+ */
1117
+ declare function toolCallExtractor(streamTopic: TopicGraph<StreamChunk>, opts?: {
1118
+ name?: string;
1119
+ }): Node<readonly ExtractedToolCall[]>;
1120
+
1121
+ /**
1122
+ * Content gate — classifies accumulated stream text as allow / review / block.
1123
+ * @module
1124
+ */
1125
+
1126
+ /** Content safety decision. */
1127
+ type ContentDecision = "allow" | "block" | "review";
1128
+ /** Options for {@link contentGate}. */
1129
+ type ContentGateOptions = {
1130
+ /**
1131
+ * Hard-block threshold multiplier (default 1.5).
1132
+ * Scores above `threshold * hardMultiplier` emit `"block"`.
1133
+ * Scores between `threshold` and that emit `"review"`.
1134
+ */
1135
+ hardMultiplier?: number;
1136
+ name?: string;
1137
+ };
1138
+ /**
1139
+ * Derived node that classifies accumulated stream text as `"allow"`,
1140
+ * `"review"`, or `"block"` based on a classifier score.
1141
+ *
1142
+ * Emits a three-way decision on every new chunk:
1143
+ * - `"allow"` — score below `threshold`
1144
+ * - `"review"` — score in `[threshold, threshold × hardMultiplier)`
1145
+ * - `"block"` — score at or above `threshold × hardMultiplier`
1146
+ *
1147
+ * Wire the output into a `valve` (automatic) or `gate` (human approval).
1148
+ * This node does not itself control flow — it just classifies.
1149
+ *
1150
+ * @param streamTopic - Streaming topic to classify.
1151
+ * @param classifier - `(accumulated: string) => number` scoring function, or
1152
+ * a `Node<number>` for live scores.
1153
+ * @param threshold - Score at which output becomes "review" or "block".
1154
+ */
1155
+ declare function contentGate(streamTopic: TopicGraph<StreamChunk>, classifier: ((accumulated: string) => number) | Node<number>, threshold: number, opts?: ContentGateOptions): Node<ContentDecision>;
1156
+
1157
+ /**
1158
+ * Redactor — stream extractor that replaces matched patterns in accumulated text.
1159
+ * @module
1160
+ */
1161
+
1162
+ /** Options for {@link redactor}. */
1163
+ type RedactorOptions = {
1164
+ name?: string;
1165
+ };
1166
+ /**
1167
+ * Stream extractor that replaces matched patterns in the accumulated text.
1168
+ *
1169
+ * Returns a derived node emitting a sanitized `StreamChunk` on every chunk:
1170
+ * `accumulated` and `token` have matched substrings replaced by `replaceFn`.
1171
+ * The default `replaceFn` replaces with `"[REDACTED]"`.
1172
+ *
1173
+ * Compose with `contentGate` for in-flight safety pipelines.
1174
+ *
1175
+ * @param streamTopic - Streaming topic to monitor.
1176
+ * @param patterns - Array of RegExps to match against accumulated text.
1177
+ * @param replaceFn - Replacement producer (default: always `"[REDACTED]"`).
1178
+ */
1179
+ declare function redactor(streamTopic: TopicGraph<StreamChunk>, patterns: RegExp[], replaceFn?: (match: string, pattern: RegExp) => string, opts?: RedactorOptions): Node<StreamChunk>;
1180
+
1181
+ type ChatStreamOptions = {
1182
+ graph?: GraphOptions;
1183
+ maxMessages?: number;
1184
+ };
1185
+ declare class ChatStreamGraph extends Graph {
1186
+ private readonly _log;
1187
+ readonly messages: Node<readonly ChatMessage[]>;
1188
+ readonly latest: Node<ChatMessage | null>;
1189
+ readonly messageCount: Node<number>;
1190
+ constructor(name: string, opts?: ChatStreamOptions);
1191
+ append(role: ChatMessage["role"], content: string, extra?: Partial<ChatMessage>): void;
1192
+ appendToolResult(callId: string, content: string): void;
1193
+ clear(): void;
1194
+ allMessages(): readonly ChatMessage[];
1195
+ }
1196
+ declare function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph;
1197
+
1198
+ type ToolRegistryOptions = {
1199
+ graph?: GraphOptions;
1200
+ };
1201
+ declare class ToolRegistryGraph extends Graph {
1202
+ readonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;
1203
+ readonly schemas: Node<readonly ToolDefinition[]>;
1204
+ constructor(name: string, opts?: ToolRegistryOptions);
1205
+ register(tool: ToolDefinition): void;
1206
+ unregister(name: string): void;
1207
+ execute(name: string, args: Record<string, unknown>): Promise<unknown>;
1208
+ getDefinition(name: string): ToolDefinition | undefined;
1209
+ }
1210
+ declare function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph;
1211
+
1212
+ /**
1213
+ * Reactive agent loop — autonomous multi-turn LLM agent with tool execution.
1214
+ */
1215
+ type AgentLoopStatus = "idle" | "thinking" | "acting" | "done" | "error";
1216
+
1217
+ type AgentLoopOptions = {
1218
+ graph?: GraphOptions;
1219
+ adapter: LLMAdapter;
1220
+ tools?: readonly ToolDefinition[];
1221
+ systemPrompt?: string;
1222
+ maxTurns?: number;
1223
+ stopWhen?: (response: LLMResponse) => boolean;
1224
+ onToolCall?: (call: ToolCall) => void;
1225
+ maxMessages?: number;
1226
+ model?: string;
1227
+ temperature?: number;
1228
+ maxTokens?: number;
1229
+ /**
1230
+ * Reactive tool-call splice (COMPOSITION-GUIDE §31 "interception is security").
1231
+ * When set, the raw `toolCalls` node is piped through this transform before
1232
+ * reaching the executor. The transform is a pure reactive composition —
1233
+ * `(calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>` — so the
1234
+ * gate is visible in `describe()` / `explain()` as a real edge (no hidden
1235
+ * imperative wraps; §24).
1236
+ *
1237
+ * Typical uses:
1238
+ * - **Filter / block** — `derived([calls, policy], ([raw, p]) => raw.filter(p))`
1239
+ * - **Throttle / debounce** — `throttle(calls, windowMs)`
1240
+ * - **Human-in-the-loop approval** — pipe through a `gate` controller so
1241
+ * calls wait for human approval before reaching the executor.
1242
+ *
1243
+ * The public `agent.toolCalls` node surfaces the POST-intercept stream, so
1244
+ * audit / telemetry consumers see what the executor actually runs. The raw
1245
+ * pre-intercept stream is not exposed — tests that need it should run
1246
+ * without `interceptToolCalls` set (the identity case).
1247
+ */
1248
+ interceptToolCalls?: (calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>;
1249
+ };
1250
+ /** A single tool execution outcome: `{id, content}` where content is a JSON string. */
1251
+ interface ToolResult {
1252
+ readonly id: string;
1253
+ readonly content: string;
1254
+ }
1255
+ /**
1256
+ * Reactive agent loop.
1257
+ *
1258
+ * The loop is a reactive state machine wired entirely from graph primitives:
1259
+ * `chat.messages` + `tools.schemas` + gating state feed a `promptInput`
1260
+ * derived; `switchMap` turns non-null inputs into an LLM invocation via
1261
+ * `fromAny(adapter.invoke(...))`. The LLM response drives chat writes and
1262
+ * status transitions via effects. Tool calls flow through a reactive
1263
+ * executor (`retrySource` + `rescue`) that retries once on error and
1264
+ * surfaces terminal errors as JSON-shaped `ToolResult` payloads for the
1265
+ * LLM to react to.
1266
+ *
1267
+ * **No imperative control flow inside the reactive layer** (spec §5.8-5.12):
1268
+ * no `while` loops, no manual `await adapter.invoke`, no polling.
1269
+ * `agent.run()` is a thin `awaitSettled` bridge so callers can still `await`
1270
+ * the loop if they want a Promise.
1271
+ *
1272
+ * Public surface:
1273
+ * - `chat` / `tools` — subgraphs (imperative `append` / `execute` at boundary)
1274
+ * - `status` / `turn` / `aborted` — state nodes with explicit initials
1275
+ * - `lastResponse` / `toolCalls` / `toolResults` — reactive outputs (SENTINEL until first emission; callers use `awaitSettled` / `subscribe`)
1276
+ * - `run(userMessage?, signal?)` — optional user append + Promise bridge
1277
+ * - `abort()` — imperative abort shim; flips `aborted` state
1278
+ */
1279
+ declare class AgentLoopGraph extends Graph {
1280
+ readonly chat: ChatStreamGraph;
1281
+ readonly tools: ToolRegistryGraph;
1282
+ /** Current agent status. `initial: "idle"` — always has a real value. */
1283
+ readonly status: Node<AgentLoopStatus>;
1284
+ /** Turn count (completed LLM invocations this run). `initial: 0`. */
1285
+ readonly turn: Node<number>;
1286
+ /** Aborted flag; flipped by `abort()` or external `AbortSignal`. `initial: false`. */
1287
+ readonly aborted: Node<boolean>;
1288
+ /**
1289
+ * Most recent LLM response. State-backed mirror driven by the response
1290
+ * effect. `initial: null` — subscribers can read the cache synchronously;
1291
+ * `awaitSettled(lastResponse)` or `firstWhere(lastResponse, v => v != null)`
1292
+ * bridges to the first non-null value as a Promise.
1293
+ */
1294
+ readonly lastResponse: Node<LLMResponse | null>;
1295
+ /** Tool-call batch emitted by the most recent LLM response. SENTINEL. */
1296
+ readonly toolCalls: Node<readonly ToolCall[]>;
1297
+ /** Tool-result batch (one entry per call) after reactive execution. SENTINEL. */
1298
+ readonly toolResults: Node<readonly ToolResult[]>;
1299
+ /** @deprecated Use `turn` instead. Pre-1.0 rename — this alias will be removed. */
1300
+ readonly turnCount: Node<number>;
1301
+ private readonly _terminalResult;
1302
+ private readonly _disposeRunWiring;
1303
+ /**
1304
+ * Per-agent monotonic run counter. Incremented at the start of every
1305
+ * `run()` call; stamped onto `_terminalResult`'s DATA emissions so a
1306
+ * caller's `awaitSettled` predicate resolves only on the matching run
1307
+ * (prevents stale-resolution under re-entrant-ish composition).
1308
+ */
1309
+ private _runVersion;
1310
+ /** Guards against overlapping `run()` calls. */
1311
+ private _running;
1312
+ /**
1313
+ * Abort controller for the currently-running `adapter.invoke`. Minted per
1314
+ * switchMap project; aborted when the reactive `aborted` node flips true
1315
+ * OR when the caller's external `AbortSignal` fires. Threaded into
1316
+ * `adapter.invoke({ signal })` AND `fromAny(promise, { signal })`, so the
1317
+ * reactive layer sees ERROR when the wire call is cancelled.
1318
+ */
1319
+ private _currentAbortController;
1320
+ constructor(name: string, opts: AgentLoopOptions);
1321
+ /**
1322
+ * Bridge to `Promise<LLMResponse>` over the reactive pipeline.
1323
+ *
1324
+ * - If `userMessage` is provided, appends it as a user message and
1325
+ * transitions status to `"thinking"` to kick the loop.
1326
+ * - If `signal` is provided, binds it to the reactive `aborted` node
1327
+ * AND threads into `adapter.invoke({ signal })` so the wire call can
1328
+ * cancel mid-flight. The reactive `aborted` state + effect 3 guarantee
1329
+ * that even an adapter that ignores `signal` will stop emitting into
1330
+ * the agent graph.
1331
+ * - Resolves when `status === "done"` with the final LLM response.
1332
+ * Rejects with `AbortError` when the abort signal fires pre-response.
1333
+ * Rejects with the stage error when `status === "error"`.
1334
+ *
1335
+ * **Concurrency:** `run()` refuses to overlap with a pending call on the
1336
+ * same agent. Attempting to call `run()` while a previous `run()` is still
1337
+ * in-flight throws a `RangeError` immediately. Each call increments an
1338
+ * internal `_runVersion` and filters `_terminalResult` emissions by that
1339
+ * version — belt-and-suspenders against stale resolution.
1340
+ */
1341
+ run(userMessage?: string, signal?: AbortSignal): Promise<LLMResponse | null>;
1342
+ /**
1343
+ * Flip the reactive `aborted` state. Equivalent to setting an external
1344
+ * `AbortSignal` — the pipeline observes and transitions to `"done"`.
1345
+ */
1346
+ abort(): void;
1347
+ destroy(): void;
1348
+ }
1349
+ declare function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph;
1350
+
1351
+ /**
1352
+ * Options for {@link handoff}.
1353
+ */
1354
+ type HandoffOptions = {
1355
+ /**
1356
+ * Reactive gate: when this node's value is `true`, output flows from
1357
+ * `from` to the `to` specialist; when `false`, `from`'s output flows
1358
+ * through unchanged and `to` stays dormant. Omit to always hand off —
1359
+ * useful when `from` is itself a router whose output shape already
1360
+ * encodes routing intent.
1361
+ */
1362
+ condition?: NodeInput<boolean>;
1363
+ name?: string;
1364
+ };
1365
+ /**
1366
+ * Multi-agent handoff recipe — route `from`'s output into a specialist
1367
+ * agent `toFactory` when `condition` is open. Thin composition over
1368
+ * `switchMap` + gate; not a new primitive, just a named shape.
1369
+ *
1370
+ * The "handoff" pattern (popularized by the OpenAI Agents SDK) covers two
1371
+ * idioms:
1372
+ *
1373
+ * 1. **Full handoff** — a triage agent routes the conversation to a
1374
+ * specialist, and the specialist becomes the active agent for the rest
1375
+ * of the turn. Accumulated context (memory, tool definitions) can travel
1376
+ * along by threading the same `agentMemory` bundle into both.
1377
+ * 2. **Agents-as-tools** — the manager keeps control and calls the
1378
+ * specialist like a tool for a bounded subtask. Build this by registering
1379
+ * a `promptNode` instance as a `ToolDefinition` on the parent via
1380
+ * `toolRegistry`.
1381
+ *
1382
+ * This sugar covers (1) — a reactive route from one agent's output into a
1383
+ * specialist factory. For (2) wire a tool registry manually; the pattern is
1384
+ * additive with this one.
1385
+ *
1386
+ * @example Full handoff on a triage signal.
1387
+ * ```ts
1388
+ * import { handoff, promptNode } from "@graphrefly/graphrefly/patterns/ai";
1389
+ *
1390
+ * const triage = promptNode(adapter, [userMessage], (msg) =>
1391
+ * `Classify urgency of: ${msg}. Reply "high" or "normal".`);
1392
+ * const isUrgent = derived([triage], ([v]) => v === "high");
1393
+ *
1394
+ * const specialist = handoff(
1395
+ * userMessage,
1396
+ * (input) => promptNode(specialistAdapter, [input], (m) => `Respond urgently: ${m}`),
1397
+ * { condition: isUrgent },
1398
+ * );
1399
+ * ```
1400
+ *
1401
+ * @param from - Source node whose value is threaded into the specialist.
1402
+ * @param toFactory - Factory that takes `from` (as a reactive source) and
1403
+ * returns the specialist node. Called once, lazily, when the first
1404
+ * subscriber activates.
1405
+ * @param opts - Optional reactive `condition` gate + name.
1406
+ * @returns Node emitting the specialist's output when the gate is open, or
1407
+ * `from`'s value when the gate is closed. Null when `from` is null.
1408
+ *
1409
+ * @category patterns.ai
1410
+ */
1411
+ declare function handoff<T>(from: NodeInput<T | null>, toFactory: (input: Node<T>) => Node<T | null>, opts?: HandoffOptions): Node<T | null>;
1412
+
1413
+ /**
1414
+ * Options for {@link toolSelector}.
1415
+ */
1416
+ interface ToolSelectorOptions {
1417
+ readonly name?: string;
1418
+ }
1419
+ /**
1420
+ * Reactive tool availability (COMPOSITION-GUIDE §31). Given a base tool set
1421
+ * (reactive or static) and one or more reactive predicates, emit the filtered
1422
+ * subset of tools currently allowed. Feeds into `promptNode({ tools: Node<...> })`
1423
+ * so the LLM sees a reactive menu instead of a frozen config.
1424
+ *
1425
+ * Each predicate is a `NodeInput<(tool) => boolean>`. A tool is included iff
1426
+ * **every** predicate returns `true`. When any predicate value is `null` /
1427
+ * `undefined` (e.g. upstream not yet ready) that predicate is treated as a
1428
+ * pass-through — the tool isn't excluded on its basis. Predicate updates
1429
+ * recompute the selected set.
1430
+ *
1431
+ * Pairs with `toolInterceptor` (§D9 / §31): **selection** controls what's
1432
+ * offered to the LLM (pre-generation UX); **interception** gates what's
1433
+ * executed after the LLM chooses (post-generation security). Tool selection
1434
+ * is NOT a security boundary — an LLM can hallucinate tool calls outside
1435
+ * its offered set; always pair with `toolInterceptor` for enforcement.
1436
+ *
1437
+ * @example
1438
+ * ```ts
1439
+ * const hasBudget = derived([costMeter], (c) => c.total < BUDGET);
1440
+ * const canDestroy = state(false, { name: "destructive-allowed" });
1441
+ * const tools = toolSelector(registry.schemas, [
1442
+ * derived([hasBudget], (b) => (t) => !t.meta?.expensive || b === true),
1443
+ * derived([canDestroy], (c) => (t) => !t.meta?.destructive || c === true),
1444
+ * ]);
1445
+ * const agent = promptNode(graph, "agent", { ..., tools });
1446
+ * ```
1447
+ */
1448
+ declare function toolSelector(allTools: NodeInput<readonly ToolDefinition[]>, constraints: readonly NodeInput<(tool: ToolDefinition) => boolean>[], opts?: ToolSelectorOptions): Node<readonly ToolDefinition[]>;
1449
+
1450
+ /** Scores for the three admission dimensions. Each 0–1. */
1451
+ type AdmissionScores = {
1452
+ readonly persistence: number;
1453
+ readonly structure: number;
1454
+ readonly personalValue: number;
1455
+ };
1456
+ type AdmissionScore3DOptions = {
1457
+ /** Custom scoring function. Default: rule-based (all dimensions 0.5). */
1458
+ scoreFn?: (raw: unknown) => AdmissionScores;
1459
+ /** Minimum persistence score to admit (default 0.3). */
1460
+ persistenceThreshold?: number;
1461
+ /** Minimum personalValue score to admit (default 0.3). */
1462
+ personalValueThreshold?: number;
1463
+ /** Require structure score > 0 to admit (default false). */
1464
+ requireStructured?: boolean;
1465
+ };
1466
+ /**
1467
+ * Creates a 3D admission filter function compatible with `agentMemory`'s
1468
+ * `admissionFilter` option. Scores each candidate on persistence, structure,
1469
+ * and personalValue, then applies thresholds.
1470
+ */
1471
+ declare function admissionFilter3D(opts?: AdmissionScore3DOptions): (raw: unknown) => boolean;
1472
+
1473
+ type RetrievalQuery = {
1474
+ readonly text?: string;
1475
+ readonly vector?: readonly number[];
1476
+ readonly entityIds?: readonly string[];
1477
+ /**
1478
+ * Optional hierarchical context breadcrumb — e.g.
1479
+ * `["projects", "auth", "tokens"]`. When both the query and a candidate
1480
+ * entry supply a `context`, the retrieval pipeline applies a score boost
1481
+ * proportional to `contextWeight` for entries whose context overlaps
1482
+ * (shared prefix). Entries or queries without `context` are scored
1483
+ * flatly (backward-compatible).
1484
+ */
1485
+ readonly context?: readonly string[];
1486
+ };
1487
+ type RetrievalPipelineOptions<TMem> = {
1488
+ /** Max candidates from vector search (default 20). */
1489
+ topK?: number;
1490
+ /** KG expansion depth in hops (default 1). */
1491
+ graphDepth?: number;
1492
+ /** Token budget for final packing (default 2000). */
1493
+ budget?: number;
1494
+ /** Cost function for budget packing. */
1495
+ cost: (mem: TMem) => number;
1496
+ /** Score function for ranking. */
1497
+ score: (mem: TMem, context: unknown) => number;
1498
+ /**
1499
+ * Optional accessor: extracts the hierarchical context breadcrumb from a
1500
+ * memory entry. Used with {@link RetrievalQuery.context} and
1501
+ * `contextWeight` to boost entries whose context overlaps the query.
1502
+ * Entries that don't expose context stay at flat behavior.
1503
+ */
1504
+ contextOf?: (mem: TMem) => readonly string[] | undefined;
1505
+ /**
1506
+ * Boost multiplier applied to a candidate's score when its `context`
1507
+ * shares a prefix with the query's `context`. Score is multiplied by
1508
+ * `(1 + contextWeight * sharedDepth / queryDepth)`. Default: 0 (no
1509
+ * context boost).
1510
+ */
1511
+ contextWeight?: number;
1512
+ };
1513
+ /** A single entry in the retrieval result, with causal trace metadata. */
1514
+ type RetrievalEntry<TMem> = {
1515
+ readonly key: string;
1516
+ readonly value: TMem;
1517
+ readonly score: number;
1518
+ readonly sources: ReadonlyArray<"vector" | "graph" | "store">;
1519
+ /**
1520
+ * Hierarchical context breadcrumb for this entry, when
1521
+ * `RetrievalPipelineOptions.contextOf` is supplied and returns a value.
1522
+ */
1523
+ readonly context?: readonly string[];
1524
+ };
1525
+ /** Causal trace for a retrieval run. */
1526
+ type RetrievalTrace<TMem> = {
1527
+ readonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;
1528
+ readonly graphExpanded: ReadonlyArray<string>;
1529
+ readonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;
1530
+ readonly packed: ReadonlyArray<RetrievalEntry<TMem>>;
1531
+ };
1532
+
1533
+ type MemoryTier = "permanent" | "active" | "archived";
1534
+ type MemoryTiersOptions<TMem> = {
1535
+ /** Exponential decay rate per second for active tier.
1536
+ * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */
1537
+ decayRate?: number;
1538
+ /** Max entries in the active tier before archiving lowest-scored (default 1000). */
1539
+ maxActive?: number;
1540
+ /** Score threshold below which active entries get archived (default 0.1). */
1541
+ archiveThreshold?: number;
1542
+ /** Predicate: true → entry belongs in permanent tier (default: never). */
1543
+ permanentFilter?: (key: string, mem: TMem) => boolean;
1544
+ /** Storage tier for the archive. Omit to disable archiving. */
1545
+ archiveTier?: StorageTier;
1546
+ /** Options forwarded to `graph.attachStorage` for the archive tier. */
1547
+ archiveStorageOptions?: GraphAttachStorageOptions;
1548
+ };
1549
+ /** @internal */
1550
+ declare const DEFAULT_DECAY_RATE: number;
1551
+ type MemoryTiersBundle<TMem> = {
1552
+ /** Permanent tier: never evicted. */
1553
+ readonly permanent: LightCollectionBundle<TMem>;
1554
+ /** Active entries node (reactive, holds ReadonlyMap). */
1555
+ readonly activeEntries: Node<unknown>;
1556
+ /** Archive storage handle (null if no tier configured). */
1557
+ readonly archiveHandle: StorageHandle | null;
1558
+ /** Classify a key into its current tier. */
1559
+ tierOf: (key: string) => MemoryTier;
1560
+ /** Move a key to the permanent tier. */
1561
+ markPermanent: (key: string, value: TMem) => void;
1562
+ };
1563
+
1564
+ type AgentMemoryOptions<TMem = unknown> = {
1565
+ graph?: GraphOptions;
1566
+ /** LLM adapter for extraction and consolidation. */
1567
+ adapter?: LLMAdapter;
1568
+ /** System prompt for the extractor LLM. */
1569
+ extractPrompt?: string;
1570
+ /** Custom extractFn (overrides adapter + extractPrompt). */
1571
+ extractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1572
+ /** System prompt for the consolidation LLM. */
1573
+ consolidatePrompt?: string;
1574
+ /** Custom consolidateFn (overrides adapter + consolidatePrompt). */
1575
+ consolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1576
+ /** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */
1577
+ consolidateTrigger?: NodeInput<unknown>;
1578
+ /** Score function for budget packing (required). */
1579
+ score: (mem: TMem, context: unknown) => number;
1580
+ /** Cost function for budget packing (required). */
1581
+ cost: (mem: TMem) => number;
1582
+ /** Token budget for compact view (default 2000). */
1583
+ budget?: number;
1584
+ /** Context node for scoring. */
1585
+ context?: NodeInput<unknown>;
1586
+ /** Admission filter (default: admit all). */
1587
+ admissionFilter?: (candidate: unknown) => boolean;
1588
+ /** Vector index dimensions (> 0 enables vector index for retrieval). */
1589
+ vectorDimensions?: number;
1590
+ /**
1591
+ * B12: optional accessor for an entry's hierarchical context breadcrumb
1592
+ * (e.g. `["projects", "auth", "tokens"]`). When supplied alongside
1593
+ * `contextWeight > 0`, retrieval applies a score boost for entries whose
1594
+ * context shares a prefix with the query's `context`. Entries without
1595
+ * a breadcrumb are scored flatly.
1596
+ */
1597
+ contextOf?: (mem: TMem) => readonly string[] | undefined;
1598
+ /**
1599
+ * B12: hierarchical context boost multiplier. Score is scaled by
1600
+ * `(1 + contextWeight * sharedDepth / queryDepth)` when both the query
1601
+ * and entry supply a `context`. Default: 0.
1602
+ */
1603
+ contextWeight?: number;
1604
+ /** Extract embedding vector from a memory entry (enables vector index). */
1605
+ embedFn?: (mem: TMem) => readonly number[] | undefined;
1606
+ /** Enable knowledge graph for entity/relation tracking. */
1607
+ enableKnowledgeGraph?: boolean;
1608
+ /** Extract entities and relations from a memory entry. */
1609
+ entityFn?: (key: string, mem: TMem) => {
1610
+ entities?: Array<{
1611
+ id: string;
1612
+ value: unknown;
1613
+ }>;
1614
+ relations?: Array<{
1615
+ from: string;
1616
+ to: string;
1617
+ relation: string;
1618
+ weight?: number;
1619
+ }>;
1620
+ } | undefined;
1621
+ /** 3-tier storage configuration. Omit to use single-tier (existing behavior). */
1622
+ tiers?: MemoryTiersOptions<TMem>;
1623
+ /** Retrieval pipeline configuration. Requires vector index or knowledge graph. */
1624
+ retrieval?: {
1625
+ /** Max candidates from vector search (default 20). */
1626
+ topK?: number;
1627
+ /** KG expansion depth in hops (default 1). */
1628
+ graphDepth?: number;
1629
+ };
1630
+ /** Periodic reflection/consolidation configuration. */
1631
+ reflection?: {
1632
+ /** Interval in ms between consolidation runs (default 300_000 = 5 min). */
1633
+ interval?: number;
1634
+ /** Enable/disable periodic reflection (default true when consolidateFn is available). */
1635
+ enabled?: boolean;
1636
+ };
1637
+ };
1638
+ type AgentMemoryGraph<TMem = unknown> = Graph & {
1639
+ readonly distillBundle: DistillBundle<TMem>;
1640
+ readonly compact: Node<Array<{
1641
+ key: string;
1642
+ value: TMem;
1643
+ score: number;
1644
+ }>>;
1645
+ readonly size: Node<number>;
1646
+ /** Vector index bundle (null if not enabled). */
1647
+ readonly vectors: VectorIndexBundle<TMem> | null;
1648
+ /** Knowledge graph (null if not enabled). */
1649
+ readonly kg: KnowledgeGraphGraph<unknown, string> | null;
1650
+ /** Memory tiers bundle (null if not configured). */
1651
+ readonly memoryTiers: MemoryTiersBundle<TMem> | null;
1652
+ /** Retrieval result node (null if no retrieval pipeline configured). */
1653
+ readonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;
1654
+ /** Latest retrieval trace for observability (null if no retrieval pipeline). */
1655
+ readonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;
1656
+ /**
1657
+ * Execute a retrieval query (null if no retrieval pipeline).
1658
+ *
1659
+ * **Synchronous consumer API** — returns the result immediately and batch-writes
1660
+ * `retrieval` and `retrievalTrace` state nodes for observers. Reads the store
1661
+ * snapshot and context value **at call time** (external-boundary read).
1662
+ *
1663
+ * **Do not call from inside a reactive fn body** (derived fn, subscribe callback,
1664
+ * effect body). The cache reads would become transitive protocol violations and
1665
+ * may observe wave-progressive rather than wave-final state.
1666
+ *
1667
+ * **Caller-batch caveat:** if invoked inside a caller's `batch(() => ...)` alongside
1668
+ * upstream store mutations, the store snapshot reflects what has been committed to
1669
+ * `store.entries.cache` at call time. State-backed stores update cache synchronously
1670
+ * so batched inserts are visible; derived-backed store transforms may defer. If you
1671
+ * need fresh state after batched mutations, call `retrieve` after the batch returns.
1672
+ */
1673
+ readonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;
1674
+ /**
1675
+ * Reactive sibling of {@link retrieve}. Given a reactive
1676
+ * `RetrievalQuery | null` source, returns a `Node` emitting the packed
1677
+ * retrieval results. Composable with graph topology — subscribe it,
1678
+ * chain it into `promptNode`, or switchMap over a user-input node.
1679
+ * Null when no retrieval pipeline is configured.
1680
+ */
1681
+ readonly retrieveReactive: ((queryInput: NodeInput<RetrievalQuery | null>) => Node<ReadonlyArray<RetrievalEntry<TMem>>>) | null;
1682
+ };
1683
+ declare function agentMemory<TMem = unknown>(name: string, source: NodeInput<unknown>, opts: AgentMemoryOptions<TMem>): AgentMemoryGraph<TMem>;
1684
+
1685
+ type LLMExtractorOptions = {
1686
+ adapter: LLMAdapter;
1687
+ model?: string;
1688
+ temperature?: number;
1689
+ maxTokens?: number;
1690
+ };
1691
+ /**
1692
+ * Returns an `extractFn` callback for `distill()` that invokes an LLM to
1693
+ * extract structured memories from raw input.
1694
+ *
1695
+ * The system prompt should instruct the LLM to return JSON matching
1696
+ * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.
1697
+ */
1698
+ declare function llmExtractor<TRaw, TMem>(systemPrompt: string, opts: LLMExtractorOptions): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1699
+ type LLMConsolidatorOptions = LLMExtractorOptions;
1700
+ /**
1701
+ * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to
1702
+ * cluster and merge related memories.
1703
+ */
1704
+ declare function llmConsolidator<TMem>(systemPrompt: string, opts: LLMConsolidatorOptions): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1705
+
1706
+ type GaugesAsContextOptions = {
1707
+ /** Group gauges by `meta.tags` (default true). */
1708
+ groupByTags?: boolean;
1709
+ /** Separator between gauge lines (default "\n"). */
1710
+ separator?: string;
1711
+ /**
1712
+ * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds
1713
+ * the corresponding entry in this map. Nodes without V0 or not in the
1714
+ * map are always included. Callers maintain this map across calls.
1715
+ *
1716
+ * The `id` field guards against node replacement: if a node is removed
1717
+ * and re-added under the same name (new id), it is always included.
1718
+ */
1719
+ sinceVersion?: ReadonlyMap<string, {
1720
+ id: string;
1721
+ version: number;
1722
+ }>;
1723
+ };
1724
+ /**
1725
+ * Format a graph's readable (gauge) nodes as a context string for LLM
1726
+ * system prompts.
1727
+ *
1728
+ * Gauges are nodes with `meta.description` or `meta.format`. Values are
1729
+ * formatted using `meta.format` and `meta.unit` hints.
1730
+ *
1731
+ * @param graph - The graph to introspect.
1732
+ * @param actor - Optional actor for guard-scoped describe.
1733
+ * @param options - Formatting options.
1734
+ * @returns A formatted string ready for system prompt injection.
1735
+ */
1736
+ declare function gaugesAsContext(graph: Graph, actor?: Actor, options?: GaugesAsContextOptions): string;
1737
+
1738
+ type GraphFromSpecOptions = {
1739
+ model?: string;
1740
+ temperature?: number;
1741
+ maxTokens?: number;
1742
+ /** Callback to construct topology before values are applied (passed to `Graph.fromSnapshot`). */
1743
+ build?: (g: Graph) => void;
1744
+ /** Extra instructions appended to the system prompt. */
1745
+ systemPromptExtra?: string;
1746
+ };
1747
+ /**
1748
+ * Ask an LLM to compose a Graph from a natural-language description.
1749
+ *
1750
+ * The LLM returns a JSON graph definition which is validated and then
1751
+ * constructed via `Graph.fromSnapshot()`.
1752
+ *
1753
+ * @param naturalLanguage - The problem/use-case description.
1754
+ * @param adapter - LLM adapter for the generation call.
1755
+ * @param opts - Model options and optional `build` callback for node factories.
1756
+ * @returns A constructed Graph.
1757
+ * @throws On invalid LLM output or validation failure.
1758
+ */
1759
+ declare function graphFromSpec(naturalLanguage: string, adapter: LLMAdapter, opts?: GraphFromSpecOptions): Promise<Graph>;
1760
+
1761
+ /** OpenAI function-calling tool schema. */
1762
+ type OpenAIToolSchema = {
1763
+ readonly type: "function";
1764
+ readonly function: {
1765
+ readonly name: string;
1766
+ readonly description: string;
1767
+ readonly parameters: Record<string, unknown>;
1768
+ };
1769
+ };
1770
+ /** MCP (Model Context Protocol) tool schema. */
1771
+ type McpToolSchema = {
1772
+ readonly name: string;
1773
+ readonly description: string;
1774
+ readonly inputSchema: Record<string, unknown>;
1775
+ };
1776
+ /** Result of {@link knobsAsTools}. */
1777
+ type KnobsAsToolsResult = {
1778
+ /** OpenAI function-calling tool schemas. */
1779
+ readonly openai: readonly OpenAIToolSchema[];
1780
+ /** MCP tool schemas. */
1781
+ readonly mcp: readonly McpToolSchema[];
1782
+ /** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */
1783
+ readonly definitions: readonly ToolDefinition[];
1784
+ };
1785
+ /**
1786
+ * Derive tool schemas from a graph's writable (knob) nodes.
1787
+ *
1788
+ * Knobs are state nodes whose `meta.access` is `"llm"`, `"both"`, or absent
1789
+ * (default: writable). Each knob becomes a tool that calls `graph.set()`.
1790
+ *
1791
+ * Speaks **domain language** (spec §5.4): the returned schemas use node names
1792
+ * and meta descriptions — no protocol internals exposed.
1793
+ *
1794
+ * @param graph - The graph to introspect.
1795
+ * @param actor - Optional actor for guard-scoped describe.
1796
+ * @returns OpenAI, MCP, and GraphReFly tool schemas.
1797
+ */
1798
+ declare function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult;
1799
+
1800
+ /** A single operation in a strategy plan. */
1801
+ type StrategyOperation = {
1802
+ readonly type: "add_node";
1803
+ readonly name: string;
1804
+ readonly nodeType: string;
1805
+ readonly meta?: Record<string, unknown>;
1806
+ readonly initial?: unknown;
1807
+ } | {
1808
+ readonly type: "remove_node";
1809
+ readonly name: string;
1810
+ } | {
1811
+ readonly type: "connect";
1812
+ readonly from: string;
1813
+ readonly to: string;
1814
+ } | {
1815
+ readonly type: "disconnect";
1816
+ readonly from: string;
1817
+ readonly to: string;
1818
+ } | {
1819
+ readonly type: "set_value";
1820
+ readonly name: string;
1821
+ readonly value: unknown;
1822
+ } | {
1823
+ readonly type: "update_meta";
1824
+ readonly name: string;
1825
+ readonly key: string;
1826
+ readonly value: unknown;
1827
+ };
1828
+ /** Structured strategy plan returned by {@link suggestStrategy}. */
1829
+ type StrategyPlan = {
1830
+ readonly summary: string;
1831
+ readonly operations: readonly StrategyOperation[];
1832
+ readonly reasoning: string;
1833
+ };
1834
+ type SuggestStrategyOptions = {
1835
+ model?: string;
1836
+ temperature?: number;
1837
+ maxTokens?: number;
1838
+ actor?: Actor;
1839
+ };
1840
+ /**
1841
+ * Ask an LLM to analyze a graph and suggest topology/parameter changes
1842
+ * to solve a stated problem.
1843
+ *
1844
+ * Returns a structured plan — does NOT auto-apply. The caller reviews
1845
+ * and selectively applies operations.
1846
+ *
1847
+ * @param graph - The graph to analyze.
1848
+ * @param problem - Natural-language problem statement.
1849
+ * @param adapter - LLM adapter for the analysis call.
1850
+ * @param opts - Model and actor options.
1851
+ * @returns A structured strategy plan.
1852
+ * @throws On invalid LLM output.
1853
+ */
1854
+ declare function suggestStrategy(graph: Graph, problem: string, adapter: LLMAdapter, opts?: SuggestStrategyOptions): Promise<StrategyPlan>;
1855
+
1856
+ /** Validation result from {@link validateGraphDef}. */
1857
+ type GraphDefValidation = {
1858
+ readonly valid: boolean;
1859
+ readonly errors: readonly string[];
1860
+ };
1861
+ /**
1862
+ * Validate an LLM-generated graph definition before passing to
1863
+ * `Graph.fromSnapshot()`.
1864
+ *
1865
+ * Checks:
1866
+ * - Required fields: `name`, `nodes`, `edges`
1867
+ * - Node types are valid enum values
1868
+ * - Edge `from`/`to` reference existing nodes
1869
+ * - No duplicate edge entries
1870
+ *
1871
+ * @param def - The graph definition to validate (parsed JSON).
1872
+ * @returns Validation result with errors array.
1873
+ */
1874
+ declare function validateGraphDef(def: unknown): GraphDefValidation;
1875
+
1876
+ /**
1877
+ * AI surface patterns (roadmap §4.4).
1878
+ *
1879
+ * Domain-layer factories for LLM-backed agents, chat, tool registries, and
1880
+ * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.
1881
+ *
1882
+ * This file is the public barrel — it re-exports symbols from the sibling
1883
+ * folders (`prompts/`, `extractors/`, `safety/`, `agents/`, `memory/`,
1884
+ * `graph-integration/`, and the existing `adapters/` tree). No implementation
1885
+ * code lives here; see each sibling folder for the actual primitives.
1886
+ *
1887
+ * @module
1888
+ */
1889
+
1890
+ declare const index_AdapterProvider: typeof AdapterProvider;
1891
+ type index_AdapterStats = AdapterStats;
1892
+ declare const index_AdapterTier: typeof AdapterTier;
1893
+ type index_AdmissionScore3DOptions = AdmissionScore3DOptions;
1894
+ type index_AdmissionScores = AdmissionScores;
1895
+ type index_AgentLoopGraph = AgentLoopGraph;
1896
+ declare const index_AgentLoopGraph: typeof AgentLoopGraph;
1897
+ type index_AgentLoopOptions = AgentLoopOptions;
1898
+ type index_AgentLoopStatus = AgentLoopStatus;
1899
+ type index_AgentMemoryGraph<TMem = unknown> = AgentMemoryGraph<TMem>;
1900
+ type index_AgentMemoryOptions<TMem = unknown> = AgentMemoryOptions<TMem>;
1901
+ declare const index_AllTiersExhaustedError: typeof AllTiersExhaustedError;
1902
+ type index_AnthropicAdapterOptions = AnthropicAdapterOptions;
1903
+ type index_AnthropicSdkLike = AnthropicSdkLike;
1904
+ type index_BudgetCaps = BudgetCaps;
1905
+ type index_BudgetExhaustedError = BudgetExhaustedError;
1906
+ declare const index_BudgetExhaustedError: typeof BudgetExhaustedError;
1907
+ type index_BudgetGateBundle = BudgetGateBundle;
1908
+ type index_BudgetTotals = BudgetTotals;
1909
+ type index_CallStatsEvent = CallStatsEvent;
1910
+ declare const index_CapabilitiesRegistry: typeof CapabilitiesRegistry;
1911
+ declare const index_CascadeExhaustionReport: typeof CascadeExhaustionReport;
1912
+ declare const index_CascadingLlmAdapterOptions: typeof CascadingLlmAdapterOptions;
1913
+ declare const index_ChatMessage: typeof ChatMessage;
1914
+ type index_ChatStreamGraph = ChatStreamGraph;
1915
+ declare const index_ChatStreamGraph: typeof ChatStreamGraph;
1916
+ type index_ChatStreamOptions = ChatStreamOptions;
1917
+ declare const index_CircuitOpenError: typeof CircuitOpenError;
1918
+ type index_ContentDecision = ContentDecision;
1919
+ type index_ContentGateOptions = ContentGateOptions;
1920
+ type index_CostMeterOptions = CostMeterOptions;
1921
+ type index_CostMeterReading = CostMeterReading;
1922
+ declare const index_CreateAdapterOptions: typeof CreateAdapterOptions;
1923
+ declare const index_DEFAULT_DECAY_RATE: typeof DEFAULT_DECAY_RATE;
1924
+ type index_DryRunAdapterOptions = DryRunAdapterOptions;
1925
+ type index_ExtractedToolCall = ExtractedToolCall;
1926
+ declare const index_FallbackAdapterOptions: typeof FallbackAdapterOptions;
1927
+ declare const index_FallbackFixture: typeof FallbackFixture;
1928
+ declare const index_FallbackMissError: typeof FallbackMissError;
1929
+ declare const index_FallbackMissPolicy: typeof FallbackMissPolicy;
1930
+ type index_FromLLMOptions = FromLLMOptions;
1931
+ type index_FrozenContextOptions = FrozenContextOptions;
1932
+ type index_GatedStreamHandle<T> = GatedStreamHandle<T>;
1933
+ type index_GatedStreamOptions = GatedStreamOptions;
1934
+ type index_GaugesAsContextOptions = GaugesAsContextOptions;
1935
+ type index_GoogleAdapterOptions = GoogleAdapterOptions;
1936
+ type index_GoogleSdkLike = GoogleSdkLike;
1937
+ type index_GraphDefValidation = GraphDefValidation;
1938
+ type index_GraphFromSpecOptions = GraphFromSpecOptions;
1939
+ type index_HandoffOptions = HandoffOptions;
1940
+ type index_HttpErrorLike = HttpErrorLike;
1941
+ type index_KeywordFlag = KeywordFlag;
1942
+ type index_KeywordFlagExtractorOptions = KeywordFlagExtractorOptions;
1943
+ type index_KnobsAsToolsResult = KnobsAsToolsResult;
1944
+ declare const index_LLMAdapter: typeof LLMAdapter;
1945
+ type index_LLMConsolidatorOptions = LLMConsolidatorOptions;
1946
+ type index_LLMExtractorOptions = LLMExtractorOptions;
1947
+ declare const index_LLMInvokeOptions: typeof LLMInvokeOptions;
1948
+ declare const index_LLMResponse: typeof LLMResponse;
1949
+ type index_LLMTimeoutError = LLMTimeoutError;
1950
+ declare const index_LLMTimeoutError: typeof LLMTimeoutError;
1951
+ type index_McpToolSchema = McpToolSchema;
1952
+ type index_MemoryTier = MemoryTier;
1953
+ type index_MemoryTiersBundle<TMem> = MemoryTiersBundle<TMem>;
1954
+ type index_MemoryTiersOptions<TMem> = MemoryTiersOptions<TMem>;
1955
+ declare const index_ModelCapabilities: typeof ModelCapabilities;
1956
+ declare const index_ModelFeatures: typeof ModelFeatures;
1957
+ declare const index_ModelLimits: typeof ModelLimits;
1958
+ declare const index_ModelPricing: typeof ModelPricing;
1959
+ declare const index_OpenAICompatAdapterOptions: typeof OpenAICompatAdapterOptions;
1960
+ declare const index_OpenAICompatPreset: typeof OpenAICompatPreset;
1961
+ declare const index_OpenAISdkLike: typeof OpenAISdkLike;
1962
+ type index_OpenAIToolSchema = OpenAIToolSchema;
1963
+ declare const index_PriceBreakdown: typeof PriceBreakdown;
1964
+ declare const index_PricingFn: typeof PricingFn;
1965
+ declare const index_PricingRegistry: typeof PricingRegistry;
1966
+ type index_PromptNodeOptions = PromptNodeOptions;
1967
+ declare const index_Rate: typeof Rate;
1968
+ type index_RedactorOptions = RedactorOptions;
1969
+ declare const index_ReplayCacheKeyContext: typeof ReplayCacheKeyContext;
1970
+ declare const index_ReplayCacheMissError: typeof ReplayCacheMissError;
1971
+ declare const index_ReplayCacheMode: typeof ReplayCacheMode;
1972
+ type index_ResilientAdapterBundle = ResilientAdapterBundle;
1973
+ type index_ResilientAdapterOptions = ResilientAdapterOptions;
1974
+ type index_RetrievalEntry<TMem> = RetrievalEntry<TMem>;
1975
+ type index_RetrievalPipelineOptions<TMem> = RetrievalPipelineOptions<TMem>;
1976
+ type index_RetrievalQuery = RetrievalQuery;
1977
+ type index_RetrievalTrace<TMem> = RetrievalTrace<TMem>;
1978
+ type index_StrategyOperation = StrategyOperation;
1979
+ type index_StrategyPlan = StrategyPlan;
1980
+ type index_StreamChunk = StreamChunk;
1981
+ declare const index_StreamDelta: typeof StreamDelta;
1982
+ type index_StreamingPromptNodeHandle<T> = StreamingPromptNodeHandle<T>;
1983
+ type index_StreamingPromptNodeOptions = StreamingPromptNodeOptions;
1984
+ type index_SuggestStrategyOptions = SuggestStrategyOptions;
1985
+ type index_SystemPromptHandle = SystemPromptHandle;
1986
+ declare const index_TieredRate: typeof TieredRate;
1987
+ declare const index_TokenUsage: typeof TokenUsage;
1988
+ declare const index_ToolCall: typeof ToolCall;
1989
+ declare const index_ToolDefinition: typeof ToolDefinition;
1990
+ type index_ToolRegistryGraph = ToolRegistryGraph;
1991
+ declare const index_ToolRegistryGraph: typeof ToolRegistryGraph;
1992
+ type index_ToolRegistryOptions = ToolRegistryOptions;
1993
+ type index_ToolResult = ToolResult;
1994
+ type index_ToolSelectorOptions = ToolSelectorOptions;
1995
+ type index_WithBreakerOptions = WithBreakerOptions;
1996
+ type index_WithBudgetGateOptions = WithBudgetGateOptions;
1997
+ type index_WithDryRunBundle = WithDryRunBundle;
1998
+ type index_WithDryRunOptions = WithDryRunOptions;
1999
+ type index_WithRateLimiterOptions = WithRateLimiterOptions;
2000
+ declare const index_WithReplayCacheOptions: typeof WithReplayCacheOptions;
2001
+ type index_WithRetryOptions = WithRetryOptions;
2002
+ declare const index_admissionFilter3D: typeof admissionFilter3D;
2003
+ declare const index_agentLoop: typeof agentLoop;
2004
+ declare const index_agentMemory: typeof agentMemory;
2005
+ declare const index_anthropicAdapter: typeof anthropicAdapter;
2006
+ declare const index_canonicalJson: typeof canonicalJson;
2007
+ declare const index_cascadingLlmAdapter: typeof cascadingLlmAdapter;
2008
+ declare const index_chatStream: typeof chatStream;
2009
+ declare const index_composePricing: typeof composePricing;
2010
+ declare const index_computePrice: typeof computePrice;
2011
+ declare const index_contentGate: typeof contentGate;
2012
+ declare const index_costMeterExtractor: typeof costMeterExtractor;
2013
+ declare const index_createAdapter: typeof createAdapter;
2014
+ declare const index_createCapabilitiesRegistry: typeof createCapabilitiesRegistry;
2015
+ declare const index_createPricingRegistry: typeof createPricingRegistry;
2016
+ declare const index_dryRunAdapter: typeof dryRunAdapter;
2017
+ declare const index_dryRunPreset: typeof dryRunPreset;
2018
+ declare const index_fallbackAdapter: typeof fallbackAdapter;
2019
+ declare const index_fromLLM: typeof fromLLM;
2020
+ declare const index_frozenContext: typeof frozenContext;
2021
+ declare const index_gatedStream: typeof gatedStream;
2022
+ declare const index_gaugesAsContext: typeof gaugesAsContext;
2023
+ declare const index_googleAdapter: typeof googleAdapter;
2024
+ declare const index_graphFromSpec: typeof graphFromSpec;
2025
+ declare const index_handoff: typeof handoff;
2026
+ declare const index_keywordFlagExtractor: typeof keywordFlagExtractor;
2027
+ declare const index_knobsAsTools: typeof knobsAsTools;
2028
+ declare const index_llmConsolidator: typeof llmConsolidator;
2029
+ declare const index_llmExtractor: typeof llmExtractor;
2030
+ declare const index_observableAdapter: typeof observableAdapter;
2031
+ declare const index_openAICompatAdapter: typeof openAICompatAdapter;
2032
+ declare const index_parseRateLimitFromError: typeof parseRateLimitFromError;
2033
+ declare const index_promptNode: typeof promptNode;
2034
+ declare const index_redactor: typeof redactor;
2035
+ declare const index_registryPricing: typeof registryPricing;
2036
+ declare const index_resilientAdapter: typeof resilientAdapter;
2037
+ declare const index_streamExtractor: typeof streamExtractor;
2038
+ declare const index_streamingPromptNode: typeof streamingPromptNode;
2039
+ declare const index_suggestStrategy: typeof suggestStrategy;
2040
+ declare const index_systemPromptBuilder: typeof systemPromptBuilder;
2041
+ declare const index_toolCallExtractor: typeof toolCallExtractor;
2042
+ declare const index_toolRegistry: typeof toolRegistry;
2043
+ declare const index_toolSelector: typeof toolSelector;
2044
+ declare const index_validateGraphDef: typeof validateGraphDef;
2045
+ declare const index_withBreaker: typeof withBreaker;
2046
+ declare const index_withBudgetGate: typeof withBudgetGate;
2047
+ declare const index_withDryRun: typeof withDryRun;
2048
+ declare const index_withRateLimiter: typeof withRateLimiter;
2049
+ declare const index_withReplayCache: typeof withReplayCache;
2050
+ declare const index_withRetry: typeof withRetry;
2051
+ declare const index_withTimeout: typeof withTimeout;
2052
+ declare const index_zeroPrice: typeof zeroPrice;
2053
+ declare namespace index {
2054
+ export { index_AdapterProvider as AdapterProvider, type index_AdapterStats as AdapterStats, index_AdapterTier as AdapterTier, type index_AdmissionScore3DOptions as AdmissionScore3DOptions, type index_AdmissionScores as AdmissionScores, index_AgentLoopGraph as AgentLoopGraph, type index_AgentLoopOptions as AgentLoopOptions, type index_AgentLoopStatus as AgentLoopStatus, type index_AgentMemoryGraph as AgentMemoryGraph, type index_AgentMemoryOptions as AgentMemoryOptions, index_AllTiersExhaustedError as AllTiersExhaustedError, type index_AnthropicAdapterOptions as AnthropicAdapterOptions, type index_AnthropicSdkLike as AnthropicSdkLike, type index_BudgetCaps as BudgetCaps, index_BudgetExhaustedError as BudgetExhaustedError, type index_BudgetGateBundle as BudgetGateBundle, type index_BudgetTotals as BudgetTotals, type index_CallStatsEvent as CallStatsEvent, index_CapabilitiesRegistry as CapabilitiesRegistry, index_CascadeExhaustionReport as CascadeExhaustionReport, index_CascadingLlmAdapterOptions as CascadingLlmAdapterOptions, index_ChatMessage as ChatMessage, index_ChatStreamGraph as ChatStreamGraph, type index_ChatStreamOptions as ChatStreamOptions, index_CircuitOpenError as CircuitOpenError, type index_ContentDecision as ContentDecision, type index_ContentGateOptions as ContentGateOptions, type index_CostMeterOptions as CostMeterOptions, type index_CostMeterReading as CostMeterReading, index_CreateAdapterOptions as CreateAdapterOptions, index_DEFAULT_DECAY_RATE as DEFAULT_DECAY_RATE, type index_DryRunAdapterOptions as DryRunAdapterOptions, type index_ExtractedToolCall as ExtractedToolCall, index_FallbackAdapterOptions as FallbackAdapterOptions, index_FallbackFixture as FallbackFixture, index_FallbackMissError as FallbackMissError, index_FallbackMissPolicy as FallbackMissPolicy, type index_FromLLMOptions as FromLLMOptions, type index_FrozenContextOptions as FrozenContextOptions, type index_GatedStreamHandle as GatedStreamHandle, type index_GatedStreamOptions as GatedStreamOptions, type index_GaugesAsContextOptions as GaugesAsContextOptions, type index_GoogleAdapterOptions as GoogleAdapterOptions, type index_GoogleSdkLike as GoogleSdkLike, type index_GraphDefValidation as GraphDefValidation, type index_GraphFromSpecOptions as GraphFromSpecOptions, type index_HandoffOptions as HandoffOptions, type index_HttpErrorLike as HttpErrorLike, type index_KeywordFlag as KeywordFlag, type index_KeywordFlagExtractorOptions as KeywordFlagExtractorOptions, type index_KnobsAsToolsResult as KnobsAsToolsResult, index_LLMAdapter as LLMAdapter, type index_LLMConsolidatorOptions as LLMConsolidatorOptions, type index_LLMExtractorOptions as LLMExtractorOptions, index_LLMInvokeOptions as LLMInvokeOptions, index_LLMResponse as LLMResponse, index_LLMTimeoutError as LLMTimeoutError, type index_McpToolSchema as McpToolSchema, type index_MemoryTier as MemoryTier, type index_MemoryTiersBundle as MemoryTiersBundle, type index_MemoryTiersOptions as MemoryTiersOptions, index_ModelCapabilities as ModelCapabilities, index_ModelFeatures as ModelFeatures, index_ModelLimits as ModelLimits, index_ModelPricing as ModelPricing, index_OpenAICompatAdapterOptions as OpenAICompatAdapterOptions, index_OpenAICompatPreset as OpenAICompatPreset, index_OpenAISdkLike as OpenAISdkLike, type index_OpenAIToolSchema as OpenAIToolSchema, index_PriceBreakdown as PriceBreakdown, index_PricingFn as PricingFn, index_PricingRegistry as PricingRegistry, type index_PromptNodeOptions as PromptNodeOptions, index_Rate as Rate, type index_RedactorOptions as RedactorOptions, index_ReplayCacheKeyContext as ReplayCacheKeyContext, index_ReplayCacheMissError as ReplayCacheMissError, index_ReplayCacheMode as ReplayCacheMode, type index_ResilientAdapterBundle as ResilientAdapterBundle, type index_ResilientAdapterOptions as ResilientAdapterOptions, type index_RetrievalEntry as RetrievalEntry, type index_RetrievalPipelineOptions as RetrievalPipelineOptions, type index_RetrievalQuery as RetrievalQuery, type index_RetrievalTrace as RetrievalTrace, type index_StrategyOperation as StrategyOperation, type index_StrategyPlan as StrategyPlan, type index_StreamChunk as StreamChunk, index_StreamDelta as StreamDelta, type index_StreamingPromptNodeHandle as StreamingPromptNodeHandle, type index_StreamingPromptNodeOptions as StreamingPromptNodeOptions, type index_SuggestStrategyOptions as SuggestStrategyOptions, type index_SystemPromptHandle as SystemPromptHandle, index_TieredRate as TieredRate, index_TokenUsage as TokenUsage, index_ToolCall as ToolCall, index_ToolDefinition as ToolDefinition, index_ToolRegistryGraph as ToolRegistryGraph, type index_ToolRegistryOptions as ToolRegistryOptions, type index_ToolResult as ToolResult, type index_ToolSelectorOptions as ToolSelectorOptions, type index_WithBreakerOptions as WithBreakerOptions, type index_WithBudgetGateOptions as WithBudgetGateOptions, type index_WithDryRunBundle as WithDryRunBundle, type index_WithDryRunOptions as WithDryRunOptions, type index_WithRateLimiterOptions as WithRateLimiterOptions, index_WithReplayCacheOptions as WithReplayCacheOptions, type index_WithRetryOptions as WithRetryOptions, index_admissionFilter3D as admissionFilter3D, index_agentLoop as agentLoop, index_agentMemory as agentMemory, index_anthropicAdapter as anthropicAdapter, index_canonicalJson as canonicalJson, index_cascadingLlmAdapter as cascadingLlmAdapter, index_chatStream as chatStream, index_composePricing as composePricing, index_computePrice as computePrice, index_contentGate as contentGate, index_costMeterExtractor as costMeterExtractor, index_createAdapter as createAdapter, index_createCapabilitiesRegistry as createCapabilitiesRegistry, index_createPricingRegistry as createPricingRegistry, index_dryRunAdapter as dryRunAdapter, index_dryRunPreset as dryRunPreset, index_fallbackAdapter as fallbackAdapter, index_fromLLM as fromLLM, index_frozenContext as frozenContext, index_gatedStream as gatedStream, index_gaugesAsContext as gaugesAsContext, index_googleAdapter as googleAdapter, index_graphFromSpec as graphFromSpec, index_handoff as handoff, index_keywordFlagExtractor as keywordFlagExtractor, index_knobsAsTools as knobsAsTools, index_llmConsolidator as llmConsolidator, index_llmExtractor as llmExtractor, index_observableAdapter as observableAdapter, index_openAICompatAdapter as openAICompatAdapter, index_parseRateLimitFromError as parseRateLimitFromError, index_promptNode as promptNode, index_redactor as redactor, index_registryPricing as registryPricing, index_resilientAdapter as resilientAdapter, index_streamExtractor as streamExtractor, index_streamingPromptNode as streamingPromptNode, index_suggestStrategy as suggestStrategy, index_systemPromptBuilder as systemPromptBuilder, index_toolCallExtractor as toolCallExtractor, index_toolRegistry as toolRegistry, index_toolSelector as toolSelector, index_validateGraphDef as validateGraphDef, index_withBreaker as withBreaker, index_withBudgetGate as withBudgetGate, index_withDryRun as withDryRun, index_withRateLimiter as withRateLimiter, index_withReplayCache as withReplayCache, index_withRetry as withRetry, index_withTimeout as withTimeout, index_zeroPrice as zeroPrice };
2055
+ }
2056
+
2057
+ export { type RetrievalQuery as $, type AdapterStats as A, type BudgetCaps as B, type CallStatsEvent as C, DEFAULT_DECAY_RATE as D, type ExtractedToolCall as E, type FromLLMOptions as F, type GatedStreamHandle as G, type GraphFromSpecOptions as H, type HandoffOptions as I, type HttpErrorLike as J, type KeywordFlag as K, type KeywordFlagExtractorOptions as L, type KnobsAsToolsResult as M, type LLMConsolidatorOptions as N, type LLMExtractorOptions as O, LLMTimeoutError as P, type McpToolSchema as Q, type MemoryTier as R, type MemoryTiersBundle as S, type MemoryTiersOptions as T, type OpenAIToolSchema as U, type PromptNodeOptions as V, type RedactorOptions as W, type ResilientAdapterBundle as X, type ResilientAdapterOptions as Y, type RetrievalEntry as Z, type RetrievalPipelineOptions as _, type AdmissionScore3DOptions as a, type RetrievalTrace as a0, type StrategyOperation as a1, type StrategyPlan as a2, type StreamChunk as a3, type StreamingPromptNodeHandle as a4, type StreamingPromptNodeOptions as a5, type SuggestStrategyOptions as a6, type SystemPromptHandle as a7, ToolRegistryGraph as a8, type ToolRegistryOptions as a9, llmConsolidator as aA, llmExtractor as aB, observableAdapter as aC, parseRateLimitFromError as aD, promptNode as aE, redactor as aF, resilientAdapter as aG, streamExtractor as aH, streamingPromptNode as aI, suggestStrategy as aJ, systemPromptBuilder as aK, toolCallExtractor as aL, toolRegistry as aM, toolSelector as aN, validateGraphDef as aO, withBreaker as aP, withBudgetGate as aQ, withDryRun as aR, withRateLimiter as aS, withRetry as aT, withTimeout as aU, type ToolResult as aa, type ToolSelectorOptions as ab, type WithBreakerOptions as ac, type WithBudgetGateOptions as ad, type WithDryRunBundle as ae, type WithDryRunOptions as af, type WithRateLimiterOptions as ag, type WithRetryOptions as ah, admissionFilter3D as ai, agentLoop as aj, agentMemory as ak, anthropicAdapter as al, chatStream as am, contentGate as an, costMeterExtractor as ao, dryRunAdapter as ap, dryRunPreset as aq, fromLLM as ar, frozenContext as as, gatedStream as at, gaugesAsContext as au, googleAdapter as av, graphFromSpec as aw, handoff as ax, keywordFlagExtractor as ay, knobsAsTools as az, type AdmissionScores as b, AgentLoopGraph as c, type AgentLoopOptions as d, type AgentLoopStatus as e, type AgentMemoryGraph as f, type AgentMemoryOptions as g, type AnthropicAdapterOptions as h, index as i, type AnthropicSdkLike as j, BudgetExhaustedError as k, type BudgetGateBundle as l, type BudgetTotals as m, ChatStreamGraph as n, type ChatStreamOptions as o, type ContentDecision as p, type ContentGateOptions as q, type CostMeterOptions as r, type CostMeterReading as s, type DryRunAdapterOptions as t, type FrozenContextOptions as u, type GatedStreamOptions as v, type GaugesAsContextOptions as w, type GoogleAdapterOptions as x, type GoogleSdkLike as y, type GraphDefValidation as z };