@graphrefly/graphrefly 0.27.0 → 0.28.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-B-5zmAUv.d.cts +180 -0
  3. package/dist/cascading-D9WG1-9L.d.ts +180 -0
  4. package/dist/chunk-2FOAM3OR.js +1 -0
  5. package/dist/chunk-2PMCKKRK.js +1 -0
  6. package/dist/chunk-3JXNEPCD.js +2 -0
  7. package/dist/chunk-3R5HFPX7.js +78 -0
  8. package/dist/chunk-4GKB4OUJ.js +1 -0
  9. package/dist/chunk-4VVTGLXJ.js +1 -0
  10. package/dist/chunk-5QDBSZBV.js +1 -0
  11. package/dist/chunk-6QZNQS5B.js +1 -0
  12. package/dist/chunk-6V3SEX2I.js +1 -0
  13. package/dist/chunk-76A3HVQE.js +9 -0
  14. package/dist/chunk-7H6LGFUG.js +64 -0
  15. package/dist/chunk-CK2E7BTU.js +1 -0
  16. package/dist/chunk-CKCSDI7T.js +6 -0
  17. package/dist/chunk-CRXTH3SH.js +1 -0
  18. package/dist/chunk-CWLN3X3N.js +1 -0
  19. package/dist/chunk-D7A7DBE4.js +1 -0
  20. package/dist/chunk-DBGGMN3D.js +1 -0
  21. package/dist/chunk-DQA3UIQ2.js +1 -0
  22. package/dist/chunk-ERLIRFPA.js +1 -0
  23. package/dist/chunk-ESMPEKEV.js +1 -0
  24. package/dist/chunk-ETWTCCJI.js +1 -0
  25. package/dist/chunk-FNYWM6JC.js +1 -0
  26. package/dist/chunk-GHJJR5P4.js +1 -0
  27. package/dist/chunk-GPW2V3RE.js +1 -0
  28. package/dist/chunk-I6VIH3VA.js +1 -0
  29. package/dist/chunk-K2GNMCQT.js +1 -0
  30. package/dist/chunk-LBTDSCCO.js +3 -0
  31. package/dist/chunk-LQ3Y5NJS.js +1 -0
  32. package/dist/chunk-MIQTDPY4.js +5 -0
  33. package/dist/chunk-MTTAAPCK.js +1 -0
  34. package/dist/chunk-OAWLCNJJ.js +1 -0
  35. package/dist/chunk-OBKQQA5I.js +1 -0
  36. package/dist/chunk-OYHGKYQM.js +1 -0
  37. package/dist/chunk-PIOGHC63.js +1 -0
  38. package/dist/chunk-QWAPKG3O.js +2 -0
  39. package/dist/chunk-QYADASLV.js +1 -0
  40. package/dist/chunk-RHESUC3V.js +43 -0
  41. package/dist/chunk-S35VARIR.js +1 -0
  42. package/dist/chunk-SC3U7ETD.js +1 -0
  43. package/dist/chunk-U3AICJKU.js +1 -0
  44. package/dist/chunk-UMBIDLJ4.js +1 -0
  45. package/dist/chunk-UPHHLMHE.js +1 -0
  46. package/dist/chunk-UPXUCFMX.js +1 -0
  47. package/dist/chunk-UWJE5FQA.js +18 -0
  48. package/dist/chunk-V6YQICXZ.js +1 -0
  49. package/dist/chunk-VIMF6LGM.js +1 -0
  50. package/dist/chunk-VJLMUKOI.js +1 -0
  51. package/dist/chunk-VPYBOXVT.js +1 -0
  52. package/dist/chunk-VTPVOGHH.js +1 -0
  53. package/dist/chunk-WQ2BN6X6.js +1 -0
  54. package/dist/chunk-XAUNPIMX.js +1 -0
  55. package/dist/chunk-Y2EMPB3I.js +1 -0
  56. package/dist/chunk-Z4HDAS2Q.js +1 -0
  57. package/dist/chunk-ZB5EHBIO.js +1 -0
  58. package/dist/chunk-ZV2DXV5A.js +23 -0
  59. package/dist/compat/index.cjs +14 -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 +14 -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 +6 -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-B-xqw4Kk.d.cts +69 -0
  96. package/dist/composite-BhbKHbOS.d.ts +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 +23 -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 +6 -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-CCwGKLCm.d.ts → graph-BZGRXwOm.d.ts} +134 -31
  144. package/dist/{graph-DNCrvZSn.d.cts → graph-D48Qw9Cg.d.cts} +134 -31
  145. package/dist/index-8FSVk4Uf.d.ts +135 -0
  146. package/dist/index-9oDeHH2u.d.cts +291 -0
  147. package/dist/{messaging-XDoYablx.d.ts → index-B0c4cmIO.d.ts} +31 -93
  148. package/dist/{index-VdHQMPy1.d.ts → index-B1AmmSlb.d.ts} +1 -1
  149. package/dist/{index-VHqptjhu.d.cts → index-B2pwesl9.d.cts} +1 -1
  150. package/dist/index-BHvIquRZ.d.ts +1957 -0
  151. package/dist/{index-Dzk2hrlR.d.ts → index-BVHOrDwO.d.ts} +1 -1
  152. package/dist/{index-CxFrXH4m.d.ts → index-BWJV63ti.d.ts} +1 -1
  153. package/dist/{index-Xi3u0HCQ.d.cts → index-B_agccPe.d.cts} +1 -1
  154. package/dist/index-BgyGlizc.d.ts +163 -0
  155. package/dist/index-BpA5c4G9.d.ts +357 -0
  156. package/dist/index-BpIFjILY.d.cts +357 -0
  157. package/dist/{index-3lsddbbS.d.ts → index-Bqachn9_.d.ts} +1 -1
  158. package/dist/index-Btib9rsU.d.ts +607 -0
  159. package/dist/{index-wEn0eFe8.d.ts → index-BwM9BEkt.d.ts} +1 -1
  160. package/dist/index-BxJ86YZZ.d.cts +105 -0
  161. package/dist/{audit-DRlSzBu9.d.ts → index-C73n7lo-.d.cts} +27 -21
  162. package/dist/index-CEXXwWVH.d.cts +192 -0
  163. package/dist/index-CHEswufn.d.cts +163 -0
  164. package/dist/{index-C0svESO4.d.ts → index-CMn8S8Hw.d.ts} +1 -1
  165. package/dist/{index-ByQxazQJ.d.cts → index-CRO83MmV.d.cts} +1 -1
  166. package/dist/{index-BuEoe-Qu.d.ts → index-CloUk1kY.d.ts} +9 -9
  167. package/dist/index-CpgYhnrG.d.ts +291 -0
  168. package/dist/{index-DO_6JN9Z.d.cts → index-Cyojz0AE.d.cts} +1 -1
  169. package/dist/{demo-shell-BDkOptd6.d.ts → index-CzobVSMr.d.ts} +14 -14
  170. package/dist/index-Czq6ynh8.d.ts +143 -0
  171. package/dist/{index-BaSM3aYt.d.ts → index-D-YB-Vl3.d.ts} +3 -3
  172. package/dist/index-DAlweici.d.ts +231 -0
  173. package/dist/index-DEwTb_fm.d.cts +1957 -0
  174. package/dist/{index-DYme44FM.d.cts → index-DL-rYJrx.d.cts} +1 -1
  175. package/dist/{memory-li6FL5RM.d.ts → index-DP4ZTkdw.d.ts} +26 -26
  176. package/dist/{index-BwfLUNw4.d.ts → index-DUqMOlKZ.d.cts} +173 -2040
  177. package/dist/{index-B1tloyhO.d.cts → index-D_NwnRYS.d.cts} +1 -1
  178. package/dist/index-DaLJvH8Z.d.ts +105 -0
  179. package/dist/index-DcXZBF5a.d.cts +135 -0
  180. package/dist/index-DfyOkTvs.d.ts +321 -0
  181. package/dist/{index-B9B7_HEY.d.ts → index-DiOXyAwt.d.ts} +1 -1
  182. package/dist/index-DpHe5e0Q.d.ts +186 -0
  183. package/dist/index-DraikLjn.d.ts +86 -0
  184. package/dist/{index-D8wS_PeY.d.cts → index-DxsnAMWD.d.cts} +9 -9
  185. package/dist/{messaging-Gt4LPbyA.d.cts → index-DyxjtScX.d.cts} +31 -93
  186. package/dist/{audit-ClmqGOCx.d.cts → index-HDpJe9hX.d.ts} +27 -21
  187. package/dist/{index-DVGiGFGT.d.cts → index-O6TgGUBV.d.cts} +3 -3
  188. package/dist/{index-B6EhDnjH.d.cts → index-Oi8d8w4R.d.cts} +1 -1
  189. package/dist/{index-C8oil6M6.d.ts → index-ROpQmGjE.d.ts} +30 -6
  190. package/dist/index-RukJ4DLS.d.cts +607 -0
  191. package/dist/{index-BHlKbUwO.d.cts → index-ZftwfxJM.d.ts} +173 -2040
  192. package/dist/{index-BPVt8kqc.d.ts → index-cByzxQIC.d.cts} +10 -195
  193. package/dist/index-dtN7YA2x.d.cts +143 -0
  194. package/dist/{index-CI3DprxP.d.cts → index-fM6y00vT.d.cts} +30 -6
  195. package/dist/{index-DlLp-2Xn.d.cts → index-m-yHof5p.d.ts} +10 -195
  196. package/dist/index-pXrDMpRO.d.cts +231 -0
  197. package/dist/index-rHJSKsU8.d.cts +186 -0
  198. package/dist/index-rX8HBM5h.d.cts +321 -0
  199. package/dist/{index-CO8uBlUh.d.cts → index-rnwQly8X.d.cts} +147 -20
  200. package/dist/index-sm373fsH.d.ts +192 -0
  201. package/dist/{memory-C6Z2tGpC.d.cts → index-tbf2gKHd.d.cts} +26 -26
  202. package/dist/{demo-shell-Crid1WdR.d.cts → index-u15meRxL.d.cts} +14 -14
  203. package/dist/{index-B6D3QNSA.d.ts → index-umtoWT8K.d.ts} +147 -20
  204. package/dist/index-vscRDkjW.d.cts +86 -0
  205. package/dist/index.cjs +150 -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-Cgj6zeji.d.cts} +5 -5
  210. package/dist/{meta-BxCA7rcr.d.cts → meta-CwesDrMD.d.ts} +5 -5
  211. package/dist/{node-BmerH3kS.d.cts → node-Cc1TniY8.d.cts} +36 -9
  212. package/dist/{node-BmerH3kS.d.ts → node-Cc1TniY8.d.ts} +36 -9
  213. package/dist/{observable-BgGUwcqp.d.ts → observable-Ct-gJ9jI.d.ts} +1 -1
  214. package/dist/{observable-DJt_AxzQ.d.cts → observable-glXQoGj2.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 +91 -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 +6 -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 +6 -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 +7 -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 +6 -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 +83 -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 +6 -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 +48 -0
  252. package/dist/patterns/harness/index.d.cts +8 -0
  253. package/dist/patterns/harness/index.d.ts +8 -0
  254. package/dist/patterns/harness/index.js +1 -0
  255. package/dist/patterns/job-queue/index.cjs +6 -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 +6 -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 +6 -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 +6 -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 +6 -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 +7 -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 +6 -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 +8 -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 +14 -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-MQP--J3F.d.cts → reactive-layout-CpYb5qLP.d.cts} +2 -2
  296. package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-D8u4wuUR.d.ts} +2 -2
  297. package/dist/reactive-log-DPzuUDj5.d.cts +190 -0
  298. package/dist/reactive-log-YuH9VYN8.d.ts +190 -0
  299. package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CdbNoSgP.d.ts} +2 -67
  300. package/dist/{composite-C7PcQvcs.d.cts → reactive-map-DUeRmb9d.d.cts} +2 -67
  301. package/dist/resilience-Ba5-b4WD.d.cts +493 -0
  302. package/dist/resilience-CGRzhnD3.d.ts +493 -0
  303. package/dist/resilience-QAHKANT5.js +1 -0
  304. package/dist/{sugar-D02n5JjF.d.cts → sugar-BV0htudb.d.cts} +8 -4
  305. package/dist/{sugar-CCOxXK1e.d.ts → sugar-Dtyrq2_q.d.ts} +8 -4
  306. package/dist/topology-tree-CYHOwQZ_.d.ts +25 -0
  307. package/dist/topology-tree-DROUdq5B.d.cts +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,1957 @@
1
+ import { a as Node, A as Actor } from './node-Cc1TniY8.cjs';
2
+ import { D as DistillBundle, E as Extraction } from './composite-B-xqw4Kk.cjs';
3
+ import { NodeInput } from './extra/sources.cjs';
4
+ import { StorageHandle, StorageTier } from './extra/storage-core.cjs';
5
+ import { G as Graph, a as GraphOptions, h as GraphAttachStorageOptions } from './graph-D48Qw9Cg.cjs';
6
+ import { V as VectorIndexBundle, K as KnowledgeGraphGraph, L as LightCollectionBundle, a as VectorSearchResult } from './index-tbf2gKHd.cjs';
7
+ import { T as TopicGraph } from './index-DyxjtScX.cjs';
8
+ import { G as GateController, a as GateOptions } from './index-dtN7YA2x.cjs';
9
+ 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';
10
+ 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-B-5zmAUv.cjs';
11
+ import { R as ReactiveLogBundle } from './reactive-log-DPzuUDj5.cjs';
12
+ import { a as CircuitBreakerOptions, e as CircuitBreaker, f as CircuitOpenError } from './resilience-Ba5-b4WD.cjs';
13
+ 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';
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
+ * AI surface patterns (roadmap §4.4).
789
+ *
790
+ * Domain-layer factories for LLM-backed agents, chat, tool registries, and
791
+ * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.
792
+ */
793
+
794
+ type AgentLoopStatus = "idle" | "thinking" | "acting" | "done" | "error";
795
+ /**
796
+ * A single chunk from any streaming source (LLM tokens, WebSocket, SSE, file tail).
797
+ * Generic enough for any streaming source, not just LLM.
798
+ */
799
+ type StreamChunk = {
800
+ /** Identifier for the stream source (adapter name, URL, etc.). */
801
+ readonly source: string;
802
+ /** This chunk's content. */
803
+ readonly token: string;
804
+ /** Full accumulated text so far. */
805
+ readonly accumulated: string;
806
+ /** 0-based chunk counter. */
807
+ readonly index: number;
808
+ };
809
+ type FrozenContextOptions = {
810
+ /**
811
+ * Reactive signal that triggers re-materialization. Each `DATA` emission
812
+ * from this node re-reads the source and refreshes the frozen value.
813
+ * Typical shapes: `fromTimer(ms)` for periodic refresh, a stage-transition
814
+ * node for event-driven refresh, or a manual `state<number>` the caller
815
+ * increments via `setState(n + 1)`.
816
+ *
817
+ * When omitted, the frozen value is materialized exactly once (on first
818
+ * subscribe) and never refreshes — use this for session-start snapshots
819
+ * that must stay stable for the lifetime of the activation.
820
+ */
821
+ refreshTrigger?: NodeInput<unknown>;
822
+ name?: string;
823
+ };
824
+ /**
825
+ * Freeze a reactive source into a stable snapshot that only re-materializes
826
+ * on explicit trigger. Built for long-running harness loops where system
827
+ * prompts include `agentMemory` / stage context — every reactive change to
828
+ * the source invalidates the LLM provider's prefix cache, so re-rendering
829
+ * the prompt every turn is expensive.
830
+ *
831
+ * `frozenContext(source)` reads the source once and caches the value;
832
+ * downstream `promptNode` compositions see a stable reference until the
833
+ * optional `refreshTrigger` fires.
834
+ *
835
+ * Trade-off: slightly stale context vs. prefix cache hit rate. For most
836
+ * harness apps, the memory snapshot at session start is "good enough" —
837
+ * refreshing on a coarse-grained trigger (`fromCron("*\/30min")`, stage
838
+ * transition) preserves 90%+ prefix cache hits while keeping context useful.
839
+ *
840
+ * @example
841
+ * ```ts
842
+ * // Freeze agent memory for the duration of a stage.
843
+ * const frozen = frozenContext(memory.context, {
844
+ * refreshTrigger: stage, // re-materialize on stage change
845
+ * });
846
+ * const reply = promptNode({ context: frozen, ... });
847
+ * ```
848
+ *
849
+ * @category patterns.ai
850
+ */
851
+ declare function frozenContext<T>(source: NodeInput<T>, opts?: FrozenContextOptions): Node<T | null>;
852
+ type FromLLMOptions = {
853
+ name?: string;
854
+ model?: string;
855
+ temperature?: number;
856
+ maxTokens?: number;
857
+ tools?: readonly ToolDefinition[];
858
+ systemPrompt?: string;
859
+ };
860
+ /**
861
+ * Reactive LLM invocation adapter. Returns a derived node that re-invokes
862
+ * the LLM whenever the messages dep changes.
863
+ *
864
+ * Uses `switchMap` internally — new invocations cancel stale in-flight ones.
865
+ */
866
+ declare function fromLLM(adapter: LLMAdapter, messages: NodeInput<readonly ChatMessage[]>, opts?: FromLLMOptions): Node<LLMResponse | null>;
867
+ type StreamingPromptNodeOptions = {
868
+ name?: string;
869
+ model?: string;
870
+ temperature?: number;
871
+ maxTokens?: number;
872
+ /** Output format — `"json"` attempts JSON.parse on the final accumulated text. Default: `"text"`. */
873
+ format?: "text" | "json";
874
+ systemPrompt?: string;
875
+ };
876
+ /**
877
+ * Bundle returned by {@link streamingPromptNode}.
878
+ */
879
+ type StreamingPromptNodeHandle<T> = {
880
+ /** Final parsed result (emits once per invocation, after stream completes). */
881
+ output: Node<T | null>;
882
+ /** Live stream topic — subscribe to `stream.latest` or `stream.events` for chunks. */
883
+ stream: TopicGraph<StreamChunk>;
884
+ /** Tear down the keepalive subscription and release resources. */
885
+ dispose: () => void;
886
+ };
887
+ /**
888
+ * Streaming LLM transform: wraps a prompt template + adapter into a reactive
889
+ * streaming pipeline. Re-invokes the LLM whenever any dep changes; the
890
+ * previous in-flight stream is canceled automatically via `switchMap`.
891
+ *
892
+ * Each token chunk is published to a {@link TopicGraph} as a {@link StreamChunk}.
893
+ * Extractors can mount on the topic independently (see {@link streamExtractor}).
894
+ * Zero overhead if nobody subscribes to the stream topic.
895
+ *
896
+ * The `output` node emits the final parsed result (like {@link promptNode}).
897
+ * The async boundary is handled by `fromAny` (spec §5.10 compliant).
898
+ */
899
+ declare function streamingPromptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: StreamingPromptNodeOptions): StreamingPromptNodeHandle<T>;
900
+ /**
901
+ * Mounts an extractor function on a streaming topic. Returns a derived node
902
+ * that emits extracted values as chunks arrive.
903
+ *
904
+ * `extractFn` receives the accumulated text from the latest chunk and returns
905
+ * the extracted value, or `null` if nothing detected yet. This is the building
906
+ * block for keyword flags, tool call detection, cost metering, etc.
907
+ *
908
+ * @param streamTopic - The stream topic to extract from.
909
+ * @param extractFn - `(accumulated: string) => T | null`.
910
+ * @param opts - Optional name.
911
+ * @returns Derived node emitting extracted values.
912
+ */
913
+ declare function streamExtractor<T>(streamTopic: TopicGraph<StreamChunk>, extractFn: (accumulated: string) => T | null, opts?: {
914
+ name?: string;
915
+ /**
916
+ * Optional structural equals for the extractor output. When two
917
+ * consecutive chunks produce structurally-equal outputs, the framework
918
+ * emits `RESOLVED` instead of `DATA`, saving downstream work. Default:
919
+ * reference equality (`Object.is`). The library cannot know your
920
+ * output shape — supply this when your `extractFn` returns structured
921
+ * objects or arrays.
922
+ */
923
+ equals?: (a: T | null, b: T | null) => boolean;
924
+ }): Node<T | null>;
925
+ /** A keyword match detected in the stream. */
926
+ type KeywordFlag = {
927
+ readonly label: string;
928
+ readonly pattern: RegExp;
929
+ readonly match: string;
930
+ readonly position: number;
931
+ };
932
+ type KeywordFlagExtractorOptions = {
933
+ patterns: readonly {
934
+ pattern: RegExp;
935
+ label: string;
936
+ }[];
937
+ name?: string;
938
+ /**
939
+ * Maximum length of any pattern's literal text. Used as an overlap window
940
+ * when cursoring through the accumulated stream so matches that span
941
+ * chunk boundaries aren't missed. Default: 128.
942
+ */
943
+ maxPatternLength?: number;
944
+ };
945
+ /**
946
+ * Mounts a keyword-flag extractor on a streaming topic. Scans accumulated text
947
+ * for all configured patterns and emits an array of matches.
948
+ *
949
+ * Use cases: design invariant violations (`setTimeout`, `EventEmitter`), PII
950
+ * detection (SSN, email, phone), toxicity keywords, off-track reasoning.
951
+ *
952
+ * **Streaming optimization.** Maintains a cursor across chunks in `ctx.store`
953
+ * so each chunk scans only the delta region `accumulated.slice(scannedTo -
954
+ * maxPatternLength)` — not the full string. Default structural equals
955
+ * suppresses DATA emission when no new flags were found this chunk.
956
+ */
957
+ declare function keywordFlagExtractor(streamTopic: TopicGraph<StreamChunk>, opts: KeywordFlagExtractorOptions): Node<readonly KeywordFlag[]>;
958
+ /** A tool call detected in the stream. */
959
+ type ExtractedToolCall = {
960
+ readonly name: string;
961
+ readonly arguments: Record<string, unknown>;
962
+ readonly raw: string;
963
+ readonly startIndex: number;
964
+ };
965
+ /**
966
+ * Mounts a tool-call extractor on a streaming topic. Scans accumulated text
967
+ * for complete JSON objects containing `"name"` and `"arguments"` keys (the
968
+ * standard tool_call shape). Partial JSON is ignored until the closing brace.
969
+ *
970
+ * Feeds into the tool interception chain for reactive tool gating mid-stream.
971
+ *
972
+ * **Streaming optimization.** Maintains a cursor (`scanFrom`) in `ctx.store`
973
+ * so each chunk resumes brace-scanning from the position after the last
974
+ * complete parse (or the last incomplete open brace). Already-parsed objects
975
+ * are not re-parsed. Default structural equals suppresses DATA emission when
976
+ * no new tool call completed this chunk.
977
+ */
978
+ declare function toolCallExtractor(streamTopic: TopicGraph<StreamChunk>, opts?: {
979
+ name?: string;
980
+ }): Node<readonly ExtractedToolCall[]>;
981
+ /** A cost meter reading from the stream. */
982
+ type CostMeterReading = {
983
+ readonly chunkCount: number;
984
+ readonly charCount: number;
985
+ readonly estimatedTokens: number;
986
+ };
987
+ type CostMeterOptions = {
988
+ /** Characters per token approximation. Default: 4 (GPT-family). */
989
+ charsPerToken?: number;
990
+ name?: string;
991
+ };
992
+ /**
993
+ * Mounts a cost meter on a streaming topic. Counts chunks, characters, and
994
+ * estimates token count. Compose with `budgetGate` for hard-stop when LLM
995
+ * output exceeds budget mid-generation.
996
+ *
997
+ * Default structural equals suppresses DATA emission when two consecutive
998
+ * readings are identical (same chunk count + char count + token estimate).
999
+ */
1000
+ declare function costMeterExtractor(streamTopic: TopicGraph<StreamChunk>, opts?: CostMeterOptions): Node<CostMeterReading>;
1001
+ /** Options for {@link redactor}. */
1002
+ type RedactorOptions = {
1003
+ name?: string;
1004
+ };
1005
+ /**
1006
+ * Stream extractor that replaces matched patterns in the accumulated text.
1007
+ *
1008
+ * Returns a derived node emitting a sanitized `StreamChunk` on every chunk:
1009
+ * `accumulated` and `token` have matched substrings replaced by `replaceFn`.
1010
+ * The default `replaceFn` replaces with `"[REDACTED]"`.
1011
+ *
1012
+ * Compose with `contentGate` for in-flight safety pipelines.
1013
+ *
1014
+ * @param streamTopic - Streaming topic to monitor.
1015
+ * @param patterns - Array of RegExps to match against accumulated text.
1016
+ * @param replaceFn - Replacement producer (default: always `"[REDACTED]"`).
1017
+ */
1018
+ declare function redactor(streamTopic: TopicGraph<StreamChunk>, patterns: RegExp[], replaceFn?: (match: string, pattern: RegExp) => string, opts?: RedactorOptions): Node<StreamChunk>;
1019
+ /** Content safety decision. */
1020
+ type ContentDecision = "allow" | "block" | "review";
1021
+ /** Options for {@link contentGate}. */
1022
+ type ContentGateOptions = {
1023
+ /**
1024
+ * Hard-block threshold multiplier (default 1.5).
1025
+ * Scores above `threshold * hardMultiplier` emit `"block"`.
1026
+ * Scores between `threshold` and that emit `"review"`.
1027
+ */
1028
+ hardMultiplier?: number;
1029
+ name?: string;
1030
+ };
1031
+ /**
1032
+ * Derived node that classifies accumulated stream text as `"allow"`,
1033
+ * `"review"`, or `"block"` based on a classifier score.
1034
+ *
1035
+ * Emits a three-way decision on every new chunk:
1036
+ * - `"allow"` — score below `threshold`
1037
+ * - `"review"` — score in `[threshold, threshold × hardMultiplier)`
1038
+ * - `"block"` — score at or above `threshold × hardMultiplier`
1039
+ *
1040
+ * Wire the output into a `valve` (automatic) or `gate` (human approval).
1041
+ * This node does not itself control flow — it just classifies.
1042
+ *
1043
+ * @param streamTopic - Streaming topic to classify.
1044
+ * @param classifier - `(accumulated: string) => number` scoring function, or
1045
+ * a `Node<number>` for live scores.
1046
+ * @param threshold - Score at which output becomes "review" or "block".
1047
+ */
1048
+ declare function contentGate(streamTopic: TopicGraph<StreamChunk>, classifier: ((accumulated: string) => number) | Node<number>, threshold: number, opts?: ContentGateOptions): Node<ContentDecision>;
1049
+ type GatedStreamOptions = StreamingPromptNodeOptions & {
1050
+ /** Gate options (maxPending, startOpen). */
1051
+ gate?: Omit<GateOptions, "meta">;
1052
+ };
1053
+ /**
1054
+ * Bundle returned by {@link gatedStream}.
1055
+ */
1056
+ type GatedStreamHandle<T> = {
1057
+ /** Final parsed result (after gate approval). */
1058
+ output: Node<T | null>;
1059
+ /** Live stream topic — subscribe to `stream.latest` for chunks. */
1060
+ stream: TopicGraph<StreamChunk>;
1061
+ /** Gate controller — approve, reject (aborts in-flight stream), modify. */
1062
+ gate: GateController<T | null>;
1063
+ /** Tear down everything. */
1064
+ dispose: () => void;
1065
+ };
1066
+ /**
1067
+ * Streaming LLM transform with human-in-the-loop gate integration.
1068
+ *
1069
+ * Composes {@link streamingPromptNode} with {@link gate} so that:
1070
+ * - `gate.reject()` discards the pending value **and** aborts the in-flight
1071
+ * stream (cancels the `AbortController`).
1072
+ * - `gate.modify()` transforms the pending value before forwarding downstream.
1073
+ * - `gate.approve()` forwards the final result as normal.
1074
+ *
1075
+ * The abort-on-reject works by toggling an internal cancel signal that causes
1076
+ * the `switchMap` inside `streamingPromptNode` to restart with an empty message
1077
+ * list, which triggers the `AbortController.abort()` in the async generator's
1078
+ * `finally` block.
1079
+ */
1080
+ declare function gatedStream<T = string>(graph: Graph, name: string, adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: GatedStreamOptions): GatedStreamHandle<T>;
1081
+ type PromptNodeOptions = {
1082
+ name?: string;
1083
+ model?: string;
1084
+ temperature?: number;
1085
+ maxTokens?: number;
1086
+ /** Output format — `"json"` attempts JSON.parse on the response. Default: `"text"`. */
1087
+ format?: "text" | "json";
1088
+ /** Number of retries on transient errors. Default: 0. */
1089
+ retries?: number;
1090
+ /** Cache LLM responses for identical inputs. Default: false. */
1091
+ cache?: boolean;
1092
+ systemPrompt?: string;
1093
+ meta?: Record<string, unknown>;
1094
+ };
1095
+ /**
1096
+ * Universal LLM transform: wraps a prompt template + model adapter into a reactive derived node.
1097
+ * Re-invokes the LLM whenever any dep changes. Suitable for triage, QA, hypothesis, parity, etc.
1098
+ *
1099
+ * @param adapter - LLM adapter (provider-agnostic).
1100
+ * @param deps - Input nodes whose values feed the prompt.
1101
+ * @param prompt - Static string or template function receiving dep values.
1102
+ * @param opts - Optional configuration.
1103
+ * @returns `Node` emitting LLM responses (string or parsed JSON).
1104
+ */
1105
+ declare function promptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: PromptNodeOptions): Node<T | null>;
1106
+ /**
1107
+ * Options for {@link handoff}.
1108
+ */
1109
+ type HandoffOptions = {
1110
+ /**
1111
+ * Reactive gate: when this node's value is `true`, output flows from
1112
+ * `from` to the `to` specialist; when `false`, `from`'s output flows
1113
+ * through unchanged and `to` stays dormant. Omit to always hand off —
1114
+ * useful when `from` is itself a router whose output shape already
1115
+ * encodes routing intent.
1116
+ */
1117
+ condition?: NodeInput<boolean>;
1118
+ name?: string;
1119
+ };
1120
+ /**
1121
+ * Multi-agent handoff recipe — route `from`'s output into a specialist
1122
+ * agent `toFactory` when `condition` is open. Thin composition over
1123
+ * `switchMap` + gate; not a new primitive, just a named shape.
1124
+ *
1125
+ * The "handoff" pattern (popularized by the OpenAI Agents SDK) covers two
1126
+ * idioms:
1127
+ *
1128
+ * 1. **Full handoff** — a triage agent routes the conversation to a
1129
+ * specialist, and the specialist becomes the active agent for the rest
1130
+ * of the turn. Accumulated context (memory, tool definitions) can travel
1131
+ * along by threading the same `agentMemory` bundle into both.
1132
+ * 2. **Agents-as-tools** — the manager keeps control and calls the
1133
+ * specialist like a tool for a bounded subtask. Build this by registering
1134
+ * a `promptNode` instance as a `ToolDefinition` on the parent via
1135
+ * `toolRegistry`.
1136
+ *
1137
+ * This sugar covers (1) — a reactive route from one agent's output into a
1138
+ * specialist factory. For (2) wire a tool registry manually; the pattern is
1139
+ * additive with this one.
1140
+ *
1141
+ * @example Full handoff on a triage signal.
1142
+ * ```ts
1143
+ * import { handoff, promptNode } from "@graphrefly/graphrefly/patterns/ai";
1144
+ *
1145
+ * const triage = promptNode(adapter, [userMessage], (msg) =>
1146
+ * `Classify urgency of: ${msg}. Reply "high" or "normal".`);
1147
+ * const isUrgent = derived([triage], ([v]) => v === "high");
1148
+ *
1149
+ * const specialist = handoff(
1150
+ * userMessage,
1151
+ * (input) => promptNode(specialistAdapter, [input], (m) => `Respond urgently: ${m}`),
1152
+ * { condition: isUrgent },
1153
+ * );
1154
+ * ```
1155
+ *
1156
+ * @param from - Source node whose value is threaded into the specialist.
1157
+ * @param toFactory - Factory that takes `from` (as a reactive source) and
1158
+ * returns the specialist node. Called once, lazily, when the first
1159
+ * subscriber activates.
1160
+ * @param opts - Optional reactive `condition` gate + name.
1161
+ * @returns Node emitting the specialist's output when the gate is open, or
1162
+ * `from`'s value when the gate is closed. Null when `from` is null.
1163
+ *
1164
+ * @category patterns.ai
1165
+ */
1166
+ declare function handoff<T>(from: NodeInput<T | null>, toFactory: (input: Node<T>) => Node<T | null>, opts?: HandoffOptions): Node<T | null>;
1167
+ type ChatStreamOptions = {
1168
+ graph?: GraphOptions;
1169
+ maxMessages?: number;
1170
+ };
1171
+ declare class ChatStreamGraph extends Graph {
1172
+ private readonly _log;
1173
+ readonly messages: Node<readonly ChatMessage[]>;
1174
+ readonly latest: Node<ChatMessage | null>;
1175
+ readonly messageCount: Node<number>;
1176
+ constructor(name: string, opts?: ChatStreamOptions);
1177
+ append(role: ChatMessage["role"], content: string, extra?: Partial<ChatMessage>): void;
1178
+ appendToolResult(callId: string, content: string): void;
1179
+ clear(): void;
1180
+ allMessages(): readonly ChatMessage[];
1181
+ }
1182
+ declare function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph;
1183
+ type ToolRegistryOptions = {
1184
+ graph?: GraphOptions;
1185
+ };
1186
+ declare class ToolRegistryGraph extends Graph {
1187
+ readonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;
1188
+ readonly schemas: Node<readonly ToolDefinition[]>;
1189
+ constructor(name: string, opts?: ToolRegistryOptions);
1190
+ register(tool: ToolDefinition): void;
1191
+ unregister(name: string): void;
1192
+ execute(name: string, args: Record<string, unknown>): Promise<unknown>;
1193
+ getDefinition(name: string): ToolDefinition | undefined;
1194
+ }
1195
+ declare function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph;
1196
+ /**
1197
+ * Options for {@link toolSelector}.
1198
+ */
1199
+ interface ToolSelectorOptions {
1200
+ readonly name?: string;
1201
+ }
1202
+ /**
1203
+ * Reactive tool availability (COMPOSITION-GUIDE §31). Given a base tool set
1204
+ * (reactive or static) and one or more reactive predicates, emit the filtered
1205
+ * subset of tools currently allowed. Feeds into `promptNode({ tools: Node<...> })`
1206
+ * so the LLM sees a reactive menu instead of a frozen config.
1207
+ *
1208
+ * Each predicate is a `NodeInput<(tool) => boolean>`. A tool is included iff
1209
+ * **every** predicate returns `true`. When any predicate value is `null` /
1210
+ * `undefined` (e.g. upstream not yet ready) that predicate is treated as a
1211
+ * pass-through — the tool isn't excluded on its basis. Predicate updates
1212
+ * recompute the selected set.
1213
+ *
1214
+ * Pairs with `toolInterceptor` (§D9 / §31): **selection** controls what's
1215
+ * offered to the LLM (pre-generation UX); **interception** gates what's
1216
+ * executed after the LLM chooses (post-generation security). Tool selection
1217
+ * is NOT a security boundary — an LLM can hallucinate tool calls outside
1218
+ * its offered set; always pair with `toolInterceptor` for enforcement.
1219
+ *
1220
+ * @example
1221
+ * ```ts
1222
+ * const hasBudget = derived([costMeter], (c) => c.total < BUDGET);
1223
+ * const canDestroy = state(false, { name: "destructive-allowed" });
1224
+ * const tools = toolSelector(registry.schemas, [
1225
+ * derived([hasBudget], (b) => (t) => !t.meta?.expensive || b === true),
1226
+ * derived([canDestroy], (c) => (t) => !t.meta?.destructive || c === true),
1227
+ * ]);
1228
+ * const agent = promptNode(graph, "agent", { ..., tools });
1229
+ * ```
1230
+ */
1231
+ declare function toolSelector(allTools: NodeInput<readonly ToolDefinition[]>, constraints: readonly NodeInput<(tool: ToolDefinition) => boolean>[], opts?: ToolSelectorOptions): Node<readonly ToolDefinition[]>;
1232
+ /**
1233
+ * Assembles a system prompt from reactive sections. Each section is a
1234
+ * `NodeInput<string>` — the prompt updates when any section changes.
1235
+ */
1236
+ type SystemPromptHandle = Node<string> & {
1237
+ dispose: () => void;
1238
+ };
1239
+ declare function systemPromptBuilder(sections: readonly NodeInput<string>[], opts?: {
1240
+ separator?: string;
1241
+ name?: string;
1242
+ }): SystemPromptHandle;
1243
+ type LLMExtractorOptions = {
1244
+ adapter: LLMAdapter;
1245
+ model?: string;
1246
+ temperature?: number;
1247
+ maxTokens?: number;
1248
+ };
1249
+ /**
1250
+ * Returns an `extractFn` callback for `distill()` that invokes an LLM to
1251
+ * extract structured memories from raw input.
1252
+ *
1253
+ * The system prompt should instruct the LLM to return JSON matching
1254
+ * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.
1255
+ */
1256
+ declare function llmExtractor<TRaw, TMem>(systemPrompt: string, opts: LLMExtractorOptions): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1257
+ type LLMConsolidatorOptions = LLMExtractorOptions;
1258
+ /**
1259
+ * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to
1260
+ * cluster and merge related memories.
1261
+ */
1262
+ declare function llmConsolidator<TMem>(systemPrompt: string, opts: LLMConsolidatorOptions): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1263
+ /** Scores for the three admission dimensions. Each 0–1. */
1264
+ type AdmissionScores = {
1265
+ readonly persistence: number;
1266
+ readonly structure: number;
1267
+ readonly personalValue: number;
1268
+ };
1269
+ type AdmissionScore3DOptions = {
1270
+ /** Custom scoring function. Default: rule-based (all dimensions 0.5). */
1271
+ scoreFn?: (raw: unknown) => AdmissionScores;
1272
+ /** Minimum persistence score to admit (default 0.3). */
1273
+ persistenceThreshold?: number;
1274
+ /** Minimum personalValue score to admit (default 0.3). */
1275
+ personalValueThreshold?: number;
1276
+ /** Require structure score > 0 to admit (default false). */
1277
+ requireStructured?: boolean;
1278
+ };
1279
+ /**
1280
+ * Creates a 3D admission filter function compatible with `agentMemory`'s
1281
+ * `admissionFilter` option. Scores each candidate on persistence, structure,
1282
+ * and personalValue, then applies thresholds.
1283
+ */
1284
+ declare function admissionFilter3D(opts?: AdmissionScore3DOptions): (raw: unknown) => boolean;
1285
+ type MemoryTier = "permanent" | "active" | "archived";
1286
+ type MemoryTiersOptions<TMem> = {
1287
+ /** Exponential decay rate per second for active tier.
1288
+ * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */
1289
+ decayRate?: number;
1290
+ /** Max entries in the active tier before archiving lowest-scored (default 1000). */
1291
+ maxActive?: number;
1292
+ /** Score threshold below which active entries get archived (default 0.1). */
1293
+ archiveThreshold?: number;
1294
+ /** Predicate: true → entry belongs in permanent tier (default: never). */
1295
+ permanentFilter?: (key: string, mem: TMem) => boolean;
1296
+ /** Storage tier for the archive. Omit to disable archiving. */
1297
+ archiveTier?: StorageTier;
1298
+ /** Options forwarded to `graph.attachStorage` for the archive tier. */
1299
+ archiveStorageOptions?: GraphAttachStorageOptions;
1300
+ };
1301
+ type MemoryTiersBundle<TMem> = {
1302
+ /** Permanent tier: never evicted. */
1303
+ readonly permanent: LightCollectionBundle<TMem>;
1304
+ /** Active entries node (reactive, holds ReadonlyMap). */
1305
+ readonly activeEntries: Node<unknown>;
1306
+ /** Archive storage handle (null if no tier configured). */
1307
+ readonly archiveHandle: StorageHandle | null;
1308
+ /** Classify a key into its current tier. */
1309
+ tierOf: (key: string) => MemoryTier;
1310
+ /** Move a key to the permanent tier. */
1311
+ markPermanent: (key: string, value: TMem) => void;
1312
+ };
1313
+ type RetrievalQuery = {
1314
+ readonly text?: string;
1315
+ readonly vector?: readonly number[];
1316
+ readonly entityIds?: readonly string[];
1317
+ /**
1318
+ * Optional hierarchical context breadcrumb — e.g.
1319
+ * `["projects", "auth", "tokens"]`. When both the query and a candidate
1320
+ * entry supply a `context`, the retrieval pipeline applies a score boost
1321
+ * proportional to `contextWeight` for entries whose context overlaps
1322
+ * (shared prefix). Entries or queries without `context` are scored
1323
+ * flatly (backward-compatible).
1324
+ */
1325
+ readonly context?: readonly string[];
1326
+ };
1327
+ type RetrievalPipelineOptions<TMem> = {
1328
+ /** Max candidates from vector search (default 20). */
1329
+ topK?: number;
1330
+ /** KG expansion depth in hops (default 1). */
1331
+ graphDepth?: number;
1332
+ /** Token budget for final packing (default 2000). */
1333
+ budget?: number;
1334
+ /** Cost function for budget packing. */
1335
+ cost: (mem: TMem) => number;
1336
+ /** Score function for ranking. */
1337
+ score: (mem: TMem, context: unknown) => number;
1338
+ /**
1339
+ * Optional accessor: extracts the hierarchical context breadcrumb from a
1340
+ * memory entry. Used with {@link RetrievalQuery.context} and
1341
+ * `contextWeight` to boost entries whose context overlaps the query.
1342
+ * Entries that don't expose context stay at flat behavior.
1343
+ */
1344
+ contextOf?: (mem: TMem) => readonly string[] | undefined;
1345
+ /**
1346
+ * Boost multiplier applied to a candidate's score when its `context`
1347
+ * shares a prefix with the query's `context`. Score is multiplied by
1348
+ * `(1 + contextWeight * sharedDepth / queryDepth)`. Default: 0 (no
1349
+ * context boost).
1350
+ */
1351
+ contextWeight?: number;
1352
+ };
1353
+ /** A single entry in the retrieval result, with causal trace metadata. */
1354
+ type RetrievalEntry<TMem> = {
1355
+ readonly key: string;
1356
+ readonly value: TMem;
1357
+ readonly score: number;
1358
+ readonly sources: ReadonlyArray<"vector" | "graph" | "store">;
1359
+ /**
1360
+ * Hierarchical context breadcrumb for this entry, when
1361
+ * `RetrievalPipelineOptions.contextOf` is supplied and returns a value.
1362
+ */
1363
+ readonly context?: readonly string[];
1364
+ };
1365
+ /** Causal trace for a retrieval run. */
1366
+ type RetrievalTrace<TMem> = {
1367
+ readonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;
1368
+ readonly graphExpanded: ReadonlyArray<string>;
1369
+ readonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;
1370
+ readonly packed: ReadonlyArray<RetrievalEntry<TMem>>;
1371
+ };
1372
+ type AgentMemoryOptions<TMem = unknown> = {
1373
+ graph?: GraphOptions;
1374
+ /** LLM adapter for extraction and consolidation. */
1375
+ adapter?: LLMAdapter;
1376
+ /** System prompt for the extractor LLM. */
1377
+ extractPrompt?: string;
1378
+ /** Custom extractFn (overrides adapter + extractPrompt). */
1379
+ extractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1380
+ /** System prompt for the consolidation LLM. */
1381
+ consolidatePrompt?: string;
1382
+ /** Custom consolidateFn (overrides adapter + consolidatePrompt). */
1383
+ consolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
1384
+ /** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */
1385
+ consolidateTrigger?: NodeInput<unknown>;
1386
+ /** Score function for budget packing (required). */
1387
+ score: (mem: TMem, context: unknown) => number;
1388
+ /** Cost function for budget packing (required). */
1389
+ cost: (mem: TMem) => number;
1390
+ /** Token budget for compact view (default 2000). */
1391
+ budget?: number;
1392
+ /** Context node for scoring. */
1393
+ context?: NodeInput<unknown>;
1394
+ /** Admission filter (default: admit all). */
1395
+ admissionFilter?: (candidate: unknown) => boolean;
1396
+ /** Vector index dimensions (> 0 enables vector index for retrieval). */
1397
+ vectorDimensions?: number;
1398
+ /**
1399
+ * B12: optional accessor for an entry's hierarchical context breadcrumb
1400
+ * (e.g. `["projects", "auth", "tokens"]`). When supplied alongside
1401
+ * `contextWeight > 0`, retrieval applies a score boost for entries whose
1402
+ * context shares a prefix with the query's `context`. Entries without
1403
+ * a breadcrumb are scored flatly.
1404
+ */
1405
+ contextOf?: (mem: TMem) => readonly string[] | undefined;
1406
+ /**
1407
+ * B12: hierarchical context boost multiplier. Score is scaled by
1408
+ * `(1 + contextWeight * sharedDepth / queryDepth)` when both the query
1409
+ * and entry supply a `context`. Default: 0.
1410
+ */
1411
+ contextWeight?: number;
1412
+ /** Extract embedding vector from a memory entry (enables vector index). */
1413
+ embedFn?: (mem: TMem) => readonly number[] | undefined;
1414
+ /** Enable knowledge graph for entity/relation tracking. */
1415
+ enableKnowledgeGraph?: boolean;
1416
+ /** Extract entities and relations from a memory entry. */
1417
+ entityFn?: (key: string, mem: TMem) => {
1418
+ entities?: Array<{
1419
+ id: string;
1420
+ value: unknown;
1421
+ }>;
1422
+ relations?: Array<{
1423
+ from: string;
1424
+ to: string;
1425
+ relation: string;
1426
+ weight?: number;
1427
+ }>;
1428
+ } | undefined;
1429
+ /** 3-tier storage configuration. Omit to use single-tier (existing behavior). */
1430
+ tiers?: MemoryTiersOptions<TMem>;
1431
+ /** Retrieval pipeline configuration. Requires vector index or knowledge graph. */
1432
+ retrieval?: {
1433
+ /** Max candidates from vector search (default 20). */
1434
+ topK?: number;
1435
+ /** KG expansion depth in hops (default 1). */
1436
+ graphDepth?: number;
1437
+ };
1438
+ /** Periodic reflection/consolidation configuration. */
1439
+ reflection?: {
1440
+ /** Interval in ms between consolidation runs (default 300_000 = 5 min). */
1441
+ interval?: number;
1442
+ /** Enable/disable periodic reflection (default true when consolidateFn is available). */
1443
+ enabled?: boolean;
1444
+ };
1445
+ };
1446
+ type AgentMemoryGraph<TMem = unknown> = Graph & {
1447
+ readonly distillBundle: DistillBundle<TMem>;
1448
+ readonly compact: Node<Array<{
1449
+ key: string;
1450
+ value: TMem;
1451
+ score: number;
1452
+ }>>;
1453
+ readonly size: Node<number>;
1454
+ /** Vector index bundle (null if not enabled). */
1455
+ readonly vectors: VectorIndexBundle<TMem> | null;
1456
+ /** Knowledge graph (null if not enabled). */
1457
+ readonly kg: KnowledgeGraphGraph<unknown, string> | null;
1458
+ /** Memory tiers bundle (null if not configured). */
1459
+ readonly memoryTiers: MemoryTiersBundle<TMem> | null;
1460
+ /** Retrieval result node (null if no retrieval pipeline configured). */
1461
+ readonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;
1462
+ /** Latest retrieval trace for observability (null if no retrieval pipeline). */
1463
+ readonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;
1464
+ /**
1465
+ * Execute a retrieval query (null if no retrieval pipeline).
1466
+ *
1467
+ * **Synchronous consumer API** — returns the result immediately and batch-writes
1468
+ * `retrieval` and `retrievalTrace` state nodes for observers. Reads the store
1469
+ * snapshot and context value **at call time** (external-boundary read).
1470
+ *
1471
+ * **Do not call from inside a reactive fn body** (derived fn, subscribe callback,
1472
+ * effect body). The cache reads would become transitive protocol violations and
1473
+ * may observe wave-progressive rather than wave-final state.
1474
+ *
1475
+ * **Caller-batch caveat:** if invoked inside a caller's `batch(() => ...)` alongside
1476
+ * upstream store mutations, the store snapshot reflects what has been committed to
1477
+ * `store.entries.cache` at call time. State-backed stores update cache synchronously
1478
+ * so batched inserts are visible; derived-backed store transforms may defer. If you
1479
+ * need fresh state after batched mutations, call `retrieve` after the batch returns.
1480
+ */
1481
+ readonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;
1482
+ /**
1483
+ * Reactive sibling of {@link retrieve}. Given a reactive
1484
+ * `RetrievalQuery | null` source, returns a `Node` emitting the packed
1485
+ * retrieval results. Composable with graph topology — subscribe it,
1486
+ * chain it into `promptNode`, or switchMap over a user-input node.
1487
+ * Null when no retrieval pipeline is configured.
1488
+ */
1489
+ readonly retrieveReactive: ((queryInput: NodeInput<RetrievalQuery | null>) => Node<ReadonlyArray<RetrievalEntry<TMem>>>) | null;
1490
+ };
1491
+ declare function agentMemory<TMem = unknown>(name: string, source: NodeInput<unknown>, opts: AgentMemoryOptions<TMem>): AgentMemoryGraph<TMem>;
1492
+ type AgentLoopOptions = {
1493
+ graph?: GraphOptions;
1494
+ adapter: LLMAdapter;
1495
+ tools?: readonly ToolDefinition[];
1496
+ systemPrompt?: string;
1497
+ maxTurns?: number;
1498
+ stopWhen?: (response: LLMResponse) => boolean;
1499
+ onToolCall?: (call: ToolCall) => void;
1500
+ maxMessages?: number;
1501
+ model?: string;
1502
+ temperature?: number;
1503
+ maxTokens?: number;
1504
+ /**
1505
+ * Reactive tool-call splice (COMPOSITION-GUIDE §31 "interception is security").
1506
+ * When set, the raw `toolCalls` node is piped through this transform before
1507
+ * reaching the executor. The transform is a pure reactive composition —
1508
+ * `(calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>` — so the
1509
+ * gate is visible in `describe()` / `explain()` as a real edge (no hidden
1510
+ * imperative wraps; §24).
1511
+ *
1512
+ * Typical uses:
1513
+ * - **Filter / block** — `derived([calls, policy], ([raw, p]) => raw.filter(p))`
1514
+ * - **Throttle / debounce** — `throttle(calls, windowMs)`
1515
+ * - **Human-in-the-loop approval** — pipe through a `gate` controller so
1516
+ * calls wait for human approval before reaching the executor.
1517
+ *
1518
+ * The public `agent.toolCalls` node surfaces the POST-intercept stream, so
1519
+ * audit / telemetry consumers see what the executor actually runs. The raw
1520
+ * pre-intercept stream is not exposed — tests that need it should run
1521
+ * without `interceptToolCalls` set (the identity case).
1522
+ */
1523
+ interceptToolCalls?: (calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>;
1524
+ };
1525
+ /** A single tool execution outcome: `{id, content}` where content is a JSON string. */
1526
+ interface ToolResult {
1527
+ readonly id: string;
1528
+ readonly content: string;
1529
+ }
1530
+ /**
1531
+ * Reactive agent loop.
1532
+ *
1533
+ * The loop is a reactive state machine wired entirely from graph primitives:
1534
+ * `chat.messages` + `tools.schemas` + gating state feed a `promptInput`
1535
+ * derived; `switchMap` turns non-null inputs into an LLM invocation via
1536
+ * `fromAny(adapter.invoke(...))`. The LLM response drives chat writes and
1537
+ * status transitions via effects. Tool calls flow through a reactive
1538
+ * executor (`retrySource` + `rescue`) that retries once on error and
1539
+ * surfaces terminal errors as JSON-shaped `ToolResult` payloads for the
1540
+ * LLM to react to.
1541
+ *
1542
+ * **No imperative control flow inside the reactive layer** (spec §5.8-5.12):
1543
+ * no `while` loops, no manual `await adapter.invoke`, no polling.
1544
+ * `agent.run()` is a thin `awaitSettled` bridge so callers can still `await`
1545
+ * the loop if they want a Promise.
1546
+ *
1547
+ * Public surface:
1548
+ * - `chat` / `tools` — subgraphs (imperative `append` / `execute` at boundary)
1549
+ * - `status` / `turn` / `aborted` — state nodes with explicit initials
1550
+ * - `lastResponse` / `toolCalls` / `toolResults` — reactive outputs (SENTINEL until first emission; callers use `awaitSettled` / `subscribe`)
1551
+ * - `run(userMessage?, signal?)` — optional user append + Promise bridge
1552
+ * - `abort()` — imperative abort shim; flips `aborted` state
1553
+ */
1554
+ declare class AgentLoopGraph extends Graph {
1555
+ readonly chat: ChatStreamGraph;
1556
+ readonly tools: ToolRegistryGraph;
1557
+ /** Current agent status. `initial: "idle"` — always has a real value. */
1558
+ readonly status: Node<AgentLoopStatus>;
1559
+ /** Turn count (completed LLM invocations this run). `initial: 0`. */
1560
+ readonly turn: Node<number>;
1561
+ /** Aborted flag; flipped by `abort()` or external `AbortSignal`. `initial: false`. */
1562
+ readonly aborted: Node<boolean>;
1563
+ /**
1564
+ * Most recent LLM response. State-backed mirror driven by the response
1565
+ * effect. `initial: null` — subscribers can read the cache synchronously;
1566
+ * `awaitSettled(lastResponse)` or `firstWhere(lastResponse, v => v != null)`
1567
+ * bridges to the first non-null value as a Promise.
1568
+ */
1569
+ readonly lastResponse: Node<LLMResponse | null>;
1570
+ /** Tool-call batch emitted by the most recent LLM response. SENTINEL. */
1571
+ readonly toolCalls: Node<readonly ToolCall[]>;
1572
+ /** Tool-result batch (one entry per call) after reactive execution. SENTINEL. */
1573
+ readonly toolResults: Node<readonly ToolResult[]>;
1574
+ /** @deprecated Use `turn` instead. Pre-1.0 rename — this alias will be removed. */
1575
+ readonly turnCount: Node<number>;
1576
+ private readonly _terminalResult;
1577
+ private readonly _disposeRunWiring;
1578
+ /**
1579
+ * Per-agent monotonic run counter. Incremented at the start of every
1580
+ * `run()` call; stamped onto `_terminalResult`'s DATA emissions so a
1581
+ * caller's `awaitSettled` predicate resolves only on the matching run
1582
+ * (prevents stale-resolution under re-entrant-ish composition).
1583
+ */
1584
+ private _runVersion;
1585
+ /** Guards against overlapping `run()` calls. */
1586
+ private _running;
1587
+ /**
1588
+ * Abort controller for the currently-running `adapter.invoke`. Minted per
1589
+ * switchMap project; aborted when the reactive `aborted` node flips true
1590
+ * OR when the caller's external `AbortSignal` fires. Threaded into
1591
+ * `adapter.invoke({ signal })` AND `fromAny(promise, { signal })`, so the
1592
+ * reactive layer sees ERROR when the wire call is cancelled.
1593
+ */
1594
+ private _currentAbortController;
1595
+ constructor(name: string, opts: AgentLoopOptions);
1596
+ /**
1597
+ * Bridge to `Promise<LLMResponse>` over the reactive pipeline.
1598
+ *
1599
+ * - If `userMessage` is provided, appends it as a user message and
1600
+ * transitions status to `"thinking"` to kick the loop.
1601
+ * - If `signal` is provided, binds it to the reactive `aborted` node
1602
+ * AND threads into `adapter.invoke({ signal })` so the wire call can
1603
+ * cancel mid-flight. The reactive `aborted` state + effect 3 guarantee
1604
+ * that even an adapter that ignores `signal` will stop emitting into
1605
+ * the agent graph.
1606
+ * - Resolves when `status === "done"` with the final LLM response.
1607
+ * Rejects with `AbortError` when the abort signal fires pre-response.
1608
+ * Rejects with the stage error when `status === "error"`.
1609
+ *
1610
+ * **Concurrency:** `run()` refuses to overlap with a pending call on the
1611
+ * same agent. Attempting to call `run()` while a previous `run()` is still
1612
+ * in-flight throws a `RangeError` immediately. Each call increments an
1613
+ * internal `_runVersion` and filters `_terminalResult` emissions by that
1614
+ * version — belt-and-suspenders against stale resolution.
1615
+ */
1616
+ run(userMessage?: string, signal?: AbortSignal): Promise<LLMResponse | null>;
1617
+ /**
1618
+ * Flip the reactive `aborted` state. Equivalent to setting an external
1619
+ * `AbortSignal` — the pipeline observes and transitions to `"done"`.
1620
+ */
1621
+ abort(): void;
1622
+ destroy(): void;
1623
+ }
1624
+ declare function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph;
1625
+ /** OpenAI function-calling tool schema. */
1626
+ type OpenAIToolSchema = {
1627
+ readonly type: "function";
1628
+ readonly function: {
1629
+ readonly name: string;
1630
+ readonly description: string;
1631
+ readonly parameters: Record<string, unknown>;
1632
+ };
1633
+ };
1634
+ /** MCP (Model Context Protocol) tool schema. */
1635
+ type McpToolSchema = {
1636
+ readonly name: string;
1637
+ readonly description: string;
1638
+ readonly inputSchema: Record<string, unknown>;
1639
+ };
1640
+ /** Result of {@link knobsAsTools}. */
1641
+ type KnobsAsToolsResult = {
1642
+ /** OpenAI function-calling tool schemas. */
1643
+ readonly openai: readonly OpenAIToolSchema[];
1644
+ /** MCP tool schemas. */
1645
+ readonly mcp: readonly McpToolSchema[];
1646
+ /** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */
1647
+ readonly definitions: readonly ToolDefinition[];
1648
+ };
1649
+ /**
1650
+ * Derive tool schemas from a graph's writable (knob) nodes.
1651
+ *
1652
+ * Knobs are state nodes whose `meta.access` is `"llm"`, `"both"`, or absent
1653
+ * (default: writable). Each knob becomes a tool that calls `graph.set()`.
1654
+ *
1655
+ * Speaks **domain language** (spec §5.4): the returned schemas use node names
1656
+ * and meta descriptions — no protocol internals exposed.
1657
+ *
1658
+ * @param graph - The graph to introspect.
1659
+ * @param actor - Optional actor for guard-scoped describe.
1660
+ * @returns OpenAI, MCP, and GraphReFly tool schemas.
1661
+ */
1662
+ declare function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult;
1663
+ type GaugesAsContextOptions = {
1664
+ /** Group gauges by `meta.tags` (default true). */
1665
+ groupByTags?: boolean;
1666
+ /** Separator between gauge lines (default "\n"). */
1667
+ separator?: string;
1668
+ /**
1669
+ * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds
1670
+ * the corresponding entry in this map. Nodes without V0 or not in the
1671
+ * map are always included. Callers maintain this map across calls.
1672
+ *
1673
+ * The `id` field guards against node replacement: if a node is removed
1674
+ * and re-added under the same name (new id), it is always included.
1675
+ */
1676
+ sinceVersion?: ReadonlyMap<string, {
1677
+ id: string;
1678
+ version: number;
1679
+ }>;
1680
+ };
1681
+ /**
1682
+ * Format a graph's readable (gauge) nodes as a context string for LLM
1683
+ * system prompts.
1684
+ *
1685
+ * Gauges are nodes with `meta.description` or `meta.format`. Values are
1686
+ * formatted using `meta.format` and `meta.unit` hints.
1687
+ *
1688
+ * @param graph - The graph to introspect.
1689
+ * @param actor - Optional actor for guard-scoped describe.
1690
+ * @param options - Formatting options.
1691
+ * @returns A formatted string ready for system prompt injection.
1692
+ */
1693
+ declare function gaugesAsContext(graph: Graph, actor?: Actor, options?: GaugesAsContextOptions): string;
1694
+ /** Validation result from {@link validateGraphDef}. */
1695
+ type GraphDefValidation = {
1696
+ readonly valid: boolean;
1697
+ readonly errors: readonly string[];
1698
+ };
1699
+ /**
1700
+ * Validate an LLM-generated graph definition before passing to
1701
+ * `Graph.fromSnapshot()`.
1702
+ *
1703
+ * Checks:
1704
+ * - Required fields: `name`, `nodes`, `edges`
1705
+ * - Node types are valid enum values
1706
+ * - Edge `from`/`to` reference existing nodes
1707
+ * - No duplicate edge entries
1708
+ *
1709
+ * @param def - The graph definition to validate (parsed JSON).
1710
+ * @returns Validation result with errors array.
1711
+ */
1712
+ declare function validateGraphDef(def: unknown): GraphDefValidation;
1713
+ type GraphFromSpecOptions = {
1714
+ model?: string;
1715
+ temperature?: number;
1716
+ maxTokens?: number;
1717
+ /** Callback to construct topology before values are applied (passed to `Graph.fromSnapshot`). */
1718
+ build?: (g: Graph) => void;
1719
+ /** Extra instructions appended to the system prompt. */
1720
+ systemPromptExtra?: string;
1721
+ };
1722
+ /**
1723
+ * Ask an LLM to compose a Graph from a natural-language description.
1724
+ *
1725
+ * The LLM returns a JSON graph definition which is validated and then
1726
+ * constructed via `Graph.fromSnapshot()`.
1727
+ *
1728
+ * @param naturalLanguage - The problem/use-case description.
1729
+ * @param adapter - LLM adapter for the generation call.
1730
+ * @param opts - Model options and optional `build` callback for node factories.
1731
+ * @returns A constructed Graph.
1732
+ * @throws On invalid LLM output or validation failure.
1733
+ */
1734
+ declare function graphFromSpec(naturalLanguage: string, adapter: LLMAdapter, opts?: GraphFromSpecOptions): Promise<Graph>;
1735
+ /** A single operation in a strategy plan. */
1736
+ type StrategyOperation = {
1737
+ readonly type: "add_node";
1738
+ readonly name: string;
1739
+ readonly nodeType: string;
1740
+ readonly meta?: Record<string, unknown>;
1741
+ readonly initial?: unknown;
1742
+ } | {
1743
+ readonly type: "remove_node";
1744
+ readonly name: string;
1745
+ } | {
1746
+ readonly type: "connect";
1747
+ readonly from: string;
1748
+ readonly to: string;
1749
+ } | {
1750
+ readonly type: "disconnect";
1751
+ readonly from: string;
1752
+ readonly to: string;
1753
+ } | {
1754
+ readonly type: "set_value";
1755
+ readonly name: string;
1756
+ readonly value: unknown;
1757
+ } | {
1758
+ readonly type: "update_meta";
1759
+ readonly name: string;
1760
+ readonly key: string;
1761
+ readonly value: unknown;
1762
+ };
1763
+ /** Structured strategy plan returned by {@link suggestStrategy}. */
1764
+ type StrategyPlan = {
1765
+ readonly summary: string;
1766
+ readonly operations: readonly StrategyOperation[];
1767
+ readonly reasoning: string;
1768
+ };
1769
+ type SuggestStrategyOptions = {
1770
+ model?: string;
1771
+ temperature?: number;
1772
+ maxTokens?: number;
1773
+ actor?: Actor;
1774
+ };
1775
+ /**
1776
+ * Ask an LLM to analyze a graph and suggest topology/parameter changes
1777
+ * to solve a stated problem.
1778
+ *
1779
+ * Returns a structured plan — does NOT auto-apply. The caller reviews
1780
+ * and selectively applies operations.
1781
+ *
1782
+ * @param graph - The graph to analyze.
1783
+ * @param problem - Natural-language problem statement.
1784
+ * @param adapter - LLM adapter for the analysis call.
1785
+ * @param opts - Model and actor options.
1786
+ * @returns A structured strategy plan.
1787
+ * @throws On invalid LLM output.
1788
+ */
1789
+ declare function suggestStrategy(graph: Graph, problem: string, adapter: LLMAdapter, opts?: SuggestStrategyOptions): Promise<StrategyPlan>;
1790
+
1791
+ declare const index_AdapterProvider: typeof AdapterProvider;
1792
+ type index_AdapterStats = AdapterStats;
1793
+ declare const index_AdapterTier: typeof AdapterTier;
1794
+ type index_AdmissionScore3DOptions = AdmissionScore3DOptions;
1795
+ type index_AdmissionScores = AdmissionScores;
1796
+ type index_AgentLoopGraph = AgentLoopGraph;
1797
+ declare const index_AgentLoopGraph: typeof AgentLoopGraph;
1798
+ type index_AgentLoopOptions = AgentLoopOptions;
1799
+ type index_AgentLoopStatus = AgentLoopStatus;
1800
+ type index_AgentMemoryGraph<TMem = unknown> = AgentMemoryGraph<TMem>;
1801
+ type index_AgentMemoryOptions<TMem = unknown> = AgentMemoryOptions<TMem>;
1802
+ declare const index_AllTiersExhaustedError: typeof AllTiersExhaustedError;
1803
+ type index_AnthropicAdapterOptions = AnthropicAdapterOptions;
1804
+ type index_AnthropicSdkLike = AnthropicSdkLike;
1805
+ type index_BudgetCaps = BudgetCaps;
1806
+ type index_BudgetExhaustedError = BudgetExhaustedError;
1807
+ declare const index_BudgetExhaustedError: typeof BudgetExhaustedError;
1808
+ type index_BudgetGateBundle = BudgetGateBundle;
1809
+ type index_BudgetTotals = BudgetTotals;
1810
+ type index_CallStatsEvent = CallStatsEvent;
1811
+ declare const index_CapabilitiesRegistry: typeof CapabilitiesRegistry;
1812
+ declare const index_CascadeExhaustionReport: typeof CascadeExhaustionReport;
1813
+ declare const index_CascadingLlmAdapterOptions: typeof CascadingLlmAdapterOptions;
1814
+ declare const index_ChatMessage: typeof ChatMessage;
1815
+ type index_ChatStreamGraph = ChatStreamGraph;
1816
+ declare const index_ChatStreamGraph: typeof ChatStreamGraph;
1817
+ type index_ChatStreamOptions = ChatStreamOptions;
1818
+ declare const index_CircuitOpenError: typeof CircuitOpenError;
1819
+ type index_ContentDecision = ContentDecision;
1820
+ type index_ContentGateOptions = ContentGateOptions;
1821
+ type index_CostMeterOptions = CostMeterOptions;
1822
+ type index_CostMeterReading = CostMeterReading;
1823
+ declare const index_CreateAdapterOptions: typeof CreateAdapterOptions;
1824
+ type index_DryRunAdapterOptions = DryRunAdapterOptions;
1825
+ type index_ExtractedToolCall = ExtractedToolCall;
1826
+ declare const index_FallbackAdapterOptions: typeof FallbackAdapterOptions;
1827
+ declare const index_FallbackFixture: typeof FallbackFixture;
1828
+ declare const index_FallbackMissError: typeof FallbackMissError;
1829
+ declare const index_FallbackMissPolicy: typeof FallbackMissPolicy;
1830
+ type index_FromLLMOptions = FromLLMOptions;
1831
+ type index_FrozenContextOptions = FrozenContextOptions;
1832
+ type index_GatedStreamHandle<T> = GatedStreamHandle<T>;
1833
+ type index_GatedStreamOptions = GatedStreamOptions;
1834
+ type index_GaugesAsContextOptions = GaugesAsContextOptions;
1835
+ type index_GoogleAdapterOptions = GoogleAdapterOptions;
1836
+ type index_GoogleSdkLike = GoogleSdkLike;
1837
+ type index_GraphDefValidation = GraphDefValidation;
1838
+ type index_GraphFromSpecOptions = GraphFromSpecOptions;
1839
+ type index_HandoffOptions = HandoffOptions;
1840
+ type index_HttpErrorLike = HttpErrorLike;
1841
+ type index_KeywordFlag = KeywordFlag;
1842
+ type index_KeywordFlagExtractorOptions = KeywordFlagExtractorOptions;
1843
+ type index_KnobsAsToolsResult = KnobsAsToolsResult;
1844
+ declare const index_LLMAdapter: typeof LLMAdapter;
1845
+ type index_LLMConsolidatorOptions = LLMConsolidatorOptions;
1846
+ type index_LLMExtractorOptions = LLMExtractorOptions;
1847
+ declare const index_LLMInvokeOptions: typeof LLMInvokeOptions;
1848
+ declare const index_LLMResponse: typeof LLMResponse;
1849
+ type index_LLMTimeoutError = LLMTimeoutError;
1850
+ declare const index_LLMTimeoutError: typeof LLMTimeoutError;
1851
+ type index_McpToolSchema = McpToolSchema;
1852
+ type index_MemoryTier = MemoryTier;
1853
+ type index_MemoryTiersBundle<TMem> = MemoryTiersBundle<TMem>;
1854
+ type index_MemoryTiersOptions<TMem> = MemoryTiersOptions<TMem>;
1855
+ declare const index_ModelCapabilities: typeof ModelCapabilities;
1856
+ declare const index_ModelFeatures: typeof ModelFeatures;
1857
+ declare const index_ModelLimits: typeof ModelLimits;
1858
+ declare const index_ModelPricing: typeof ModelPricing;
1859
+ declare const index_OpenAICompatAdapterOptions: typeof OpenAICompatAdapterOptions;
1860
+ declare const index_OpenAICompatPreset: typeof OpenAICompatPreset;
1861
+ declare const index_OpenAISdkLike: typeof OpenAISdkLike;
1862
+ type index_OpenAIToolSchema = OpenAIToolSchema;
1863
+ declare const index_PriceBreakdown: typeof PriceBreakdown;
1864
+ declare const index_PricingFn: typeof PricingFn;
1865
+ declare const index_PricingRegistry: typeof PricingRegistry;
1866
+ type index_PromptNodeOptions = PromptNodeOptions;
1867
+ declare const index_Rate: typeof Rate;
1868
+ type index_RedactorOptions = RedactorOptions;
1869
+ declare const index_ReplayCacheKeyContext: typeof ReplayCacheKeyContext;
1870
+ declare const index_ReplayCacheMissError: typeof ReplayCacheMissError;
1871
+ declare const index_ReplayCacheMode: typeof ReplayCacheMode;
1872
+ type index_ResilientAdapterBundle = ResilientAdapterBundle;
1873
+ type index_ResilientAdapterOptions = ResilientAdapterOptions;
1874
+ type index_RetrievalEntry<TMem> = RetrievalEntry<TMem>;
1875
+ type index_RetrievalPipelineOptions<TMem> = RetrievalPipelineOptions<TMem>;
1876
+ type index_RetrievalQuery = RetrievalQuery;
1877
+ type index_RetrievalTrace<TMem> = RetrievalTrace<TMem>;
1878
+ type index_StrategyOperation = StrategyOperation;
1879
+ type index_StrategyPlan = StrategyPlan;
1880
+ type index_StreamChunk = StreamChunk;
1881
+ declare const index_StreamDelta: typeof StreamDelta;
1882
+ type index_StreamingPromptNodeHandle<T> = StreamingPromptNodeHandle<T>;
1883
+ type index_StreamingPromptNodeOptions = StreamingPromptNodeOptions;
1884
+ type index_SuggestStrategyOptions = SuggestStrategyOptions;
1885
+ type index_SystemPromptHandle = SystemPromptHandle;
1886
+ declare const index_TieredRate: typeof TieredRate;
1887
+ declare const index_TokenUsage: typeof TokenUsage;
1888
+ declare const index_ToolCall: typeof ToolCall;
1889
+ declare const index_ToolDefinition: typeof ToolDefinition;
1890
+ type index_ToolRegistryGraph = ToolRegistryGraph;
1891
+ declare const index_ToolRegistryGraph: typeof ToolRegistryGraph;
1892
+ type index_ToolRegistryOptions = ToolRegistryOptions;
1893
+ type index_ToolResult = ToolResult;
1894
+ type index_ToolSelectorOptions = ToolSelectorOptions;
1895
+ type index_WithBreakerOptions = WithBreakerOptions;
1896
+ type index_WithBudgetGateOptions = WithBudgetGateOptions;
1897
+ type index_WithDryRunBundle = WithDryRunBundle;
1898
+ type index_WithDryRunOptions = WithDryRunOptions;
1899
+ type index_WithRateLimiterOptions = WithRateLimiterOptions;
1900
+ declare const index_WithReplayCacheOptions: typeof WithReplayCacheOptions;
1901
+ type index_WithRetryOptions = WithRetryOptions;
1902
+ declare const index_admissionFilter3D: typeof admissionFilter3D;
1903
+ declare const index_agentLoop: typeof agentLoop;
1904
+ declare const index_agentMemory: typeof agentMemory;
1905
+ declare const index_anthropicAdapter: typeof anthropicAdapter;
1906
+ declare const index_canonicalJson: typeof canonicalJson;
1907
+ declare const index_cascadingLlmAdapter: typeof cascadingLlmAdapter;
1908
+ declare const index_chatStream: typeof chatStream;
1909
+ declare const index_composePricing: typeof composePricing;
1910
+ declare const index_computePrice: typeof computePrice;
1911
+ declare const index_contentGate: typeof contentGate;
1912
+ declare const index_costMeterExtractor: typeof costMeterExtractor;
1913
+ declare const index_createAdapter: typeof createAdapter;
1914
+ declare const index_createCapabilitiesRegistry: typeof createCapabilitiesRegistry;
1915
+ declare const index_createPricingRegistry: typeof createPricingRegistry;
1916
+ declare const index_dryRunAdapter: typeof dryRunAdapter;
1917
+ declare const index_dryRunPreset: typeof dryRunPreset;
1918
+ declare const index_fallbackAdapter: typeof fallbackAdapter;
1919
+ declare const index_fromLLM: typeof fromLLM;
1920
+ declare const index_frozenContext: typeof frozenContext;
1921
+ declare const index_gatedStream: typeof gatedStream;
1922
+ declare const index_gaugesAsContext: typeof gaugesAsContext;
1923
+ declare const index_googleAdapter: typeof googleAdapter;
1924
+ declare const index_graphFromSpec: typeof graphFromSpec;
1925
+ declare const index_handoff: typeof handoff;
1926
+ declare const index_keywordFlagExtractor: typeof keywordFlagExtractor;
1927
+ declare const index_knobsAsTools: typeof knobsAsTools;
1928
+ declare const index_llmConsolidator: typeof llmConsolidator;
1929
+ declare const index_llmExtractor: typeof llmExtractor;
1930
+ declare const index_observableAdapter: typeof observableAdapter;
1931
+ declare const index_openAICompatAdapter: typeof openAICompatAdapter;
1932
+ declare const index_parseRateLimitFromError: typeof parseRateLimitFromError;
1933
+ declare const index_promptNode: typeof promptNode;
1934
+ declare const index_redactor: typeof redactor;
1935
+ declare const index_registryPricing: typeof registryPricing;
1936
+ declare const index_resilientAdapter: typeof resilientAdapter;
1937
+ declare const index_streamExtractor: typeof streamExtractor;
1938
+ declare const index_streamingPromptNode: typeof streamingPromptNode;
1939
+ declare const index_suggestStrategy: typeof suggestStrategy;
1940
+ declare const index_systemPromptBuilder: typeof systemPromptBuilder;
1941
+ declare const index_toolCallExtractor: typeof toolCallExtractor;
1942
+ declare const index_toolRegistry: typeof toolRegistry;
1943
+ declare const index_toolSelector: typeof toolSelector;
1944
+ declare const index_validateGraphDef: typeof validateGraphDef;
1945
+ declare const index_withBreaker: typeof withBreaker;
1946
+ declare const index_withBudgetGate: typeof withBudgetGate;
1947
+ declare const index_withDryRun: typeof withDryRun;
1948
+ declare const index_withRateLimiter: typeof withRateLimiter;
1949
+ declare const index_withReplayCache: typeof withReplayCache;
1950
+ declare const index_withRetry: typeof withRetry;
1951
+ declare const index_withTimeout: typeof withTimeout;
1952
+ declare const index_zeroPrice: typeof zeroPrice;
1953
+ declare namespace index {
1954
+ 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, 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 };
1955
+ }
1956
+
1957
+ export { type RetrievalTrace as $, type AdapterStats as A, type BudgetCaps as B, type CallStatsEvent as C, type DryRunAdapterOptions as D, type ExtractedToolCall as E, type FromLLMOptions as F, type GatedStreamHandle as G, type HandoffOptions as H, type HttpErrorLike as I, type KeywordFlagExtractorOptions as J, type KeywordFlag as K, type KnobsAsToolsResult as L, type LLMConsolidatorOptions as M, type LLMExtractorOptions as N, LLMTimeoutError as O, type McpToolSchema as P, type MemoryTier as Q, type MemoryTiersBundle as R, type MemoryTiersOptions as S, type OpenAIToolSchema as T, type PromptNodeOptions as U, type RedactorOptions as V, type ResilientAdapterBundle as W, type ResilientAdapterOptions as X, type RetrievalEntry as Y, type RetrievalPipelineOptions as Z, type RetrievalQuery as _, type AdmissionScore3DOptions as a, type StrategyOperation as a0, type StrategyPlan as a1, type StreamChunk as a2, type StreamingPromptNodeHandle as a3, type StreamingPromptNodeOptions as a4, type SuggestStrategyOptions as a5, type SystemPromptHandle as a6, ToolRegistryGraph as a7, type ToolRegistryOptions as a8, type ToolResult as a9, llmExtractor as aA, observableAdapter as aB, parseRateLimitFromError as aC, promptNode as aD, redactor as aE, resilientAdapter as aF, streamExtractor as aG, streamingPromptNode as aH, suggestStrategy as aI, systemPromptBuilder as aJ, toolCallExtractor as aK, toolRegistry as aL, toolSelector as aM, validateGraphDef as aN, withBreaker as aO, withBudgetGate as aP, withDryRun as aQ, withRateLimiter as aR, withRetry as aS, withTimeout as aT, type ToolSelectorOptions as aa, type WithBreakerOptions as ab, type WithBudgetGateOptions as ac, type WithDryRunBundle as ad, type WithDryRunOptions as ae, type WithRateLimiterOptions as af, type WithRetryOptions as ag, admissionFilter3D as ah, agentLoop as ai, agentMemory as aj, anthropicAdapter as ak, chatStream as al, contentGate as am, costMeterExtractor as an, dryRunAdapter as ao, dryRunPreset as ap, fromLLM as aq, frozenContext as ar, gatedStream as as, gaugesAsContext as at, googleAdapter as au, graphFromSpec as av, handoff as aw, keywordFlagExtractor as ax, knobsAsTools as ay, llmConsolidator 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 FrozenContextOptions as t, type GatedStreamOptions as u, type GaugesAsContextOptions as v, type GoogleAdapterOptions as w, type GoogleSdkLike as x, type GraphDefValidation as y, type GraphFromSpecOptions as z };