@graphrefly/graphrefly 0.44.0 → 0.45.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 (420) hide show
  1. package/README.md +21 -17
  2. package/dist/compat/index.cjs +20 -10
  3. package/dist/compat/index.cjs.map +1 -0
  4. package/dist/compat/index.d.cts +1 -22
  5. package/dist/compat/index.d.ts +1 -22
  6. package/dist/compat/index.js +3 -1
  7. package/dist/compat/index.js.map +1 -0
  8. package/dist/compat/jotai/index.cjs +21 -1
  9. package/dist/compat/jotai/index.cjs.map +1 -0
  10. package/dist/compat/jotai/index.d.cts +1 -2
  11. package/dist/compat/jotai/index.d.ts +1 -2
  12. package/dist/compat/jotai/index.js +3 -1
  13. package/dist/compat/jotai/index.js.map +1 -0
  14. package/dist/compat/nanostores/index.cjs +21 -1
  15. package/dist/compat/nanostores/index.cjs.map +1 -0
  16. package/dist/compat/nanostores/index.d.cts +1 -2
  17. package/dist/compat/nanostores/index.d.ts +1 -2
  18. package/dist/compat/nanostores/index.js +3 -1
  19. package/dist/compat/nanostores/index.js.map +1 -0
  20. package/dist/compat/nestjs/index.cjs +20 -10
  21. package/dist/compat/nestjs/index.cjs.map +1 -0
  22. package/dist/compat/nestjs/index.d.cts +1 -13
  23. package/dist/compat/nestjs/index.d.ts +1 -13
  24. package/dist/compat/nestjs/index.js +3 -1
  25. package/dist/compat/nestjs/index.js.map +1 -0
  26. package/dist/compat/react/index.cjs +21 -1
  27. package/dist/compat/react/index.cjs.map +1 -0
  28. package/dist/compat/react/index.d.cts +1 -2
  29. package/dist/compat/react/index.d.ts +1 -2
  30. package/dist/compat/react/index.js +3 -1
  31. package/dist/compat/react/index.js.map +1 -0
  32. package/dist/compat/solid/index.cjs +21 -1
  33. package/dist/compat/solid/index.cjs.map +1 -0
  34. package/dist/compat/solid/index.d.cts +1 -2
  35. package/dist/compat/solid/index.d.ts +1 -2
  36. package/dist/compat/solid/index.js +3 -1
  37. package/dist/compat/solid/index.js.map +1 -0
  38. package/dist/compat/svelte/index.cjs +21 -1
  39. package/dist/compat/svelte/index.cjs.map +1 -0
  40. package/dist/compat/svelte/index.d.cts +1 -2
  41. package/dist/compat/svelte/index.d.ts +1 -2
  42. package/dist/compat/svelte/index.js +3 -1
  43. package/dist/compat/svelte/index.js.map +1 -0
  44. package/dist/compat/vue/index.cjs +21 -1
  45. package/dist/compat/vue/index.cjs.map +1 -0
  46. package/dist/compat/vue/index.d.cts +1 -3
  47. package/dist/compat/vue/index.d.ts +1 -3
  48. package/dist/compat/vue/index.js +3 -1
  49. package/dist/compat/vue/index.js.map +1 -0
  50. package/dist/compat/zustand/index.cjs +21 -3
  51. package/dist/compat/zustand/index.cjs.map +1 -0
  52. package/dist/compat/zustand/index.d.cts +1 -6
  53. package/dist/compat/zustand/index.d.ts +1 -6
  54. package/dist/compat/zustand/index.js +3 -1
  55. package/dist/compat/zustand/index.js.map +1 -0
  56. package/dist/core/index.cjs +21 -1
  57. package/dist/core/index.cjs.map +1 -0
  58. package/dist/core/index.d.cts +1 -3
  59. package/dist/core/index.d.ts +1 -3
  60. package/dist/core/index.js +3 -1
  61. package/dist/core/index.js.map +1 -0
  62. package/dist/extra/browser.cjs +21 -1
  63. package/dist/extra/browser.cjs.map +1 -0
  64. package/dist/extra/browser.d.cts +1 -4
  65. package/dist/extra/browser.d.ts +1 -4
  66. package/dist/extra/browser.js +3 -1
  67. package/dist/extra/browser.js.map +1 -0
  68. package/dist/extra/index.cjs +20 -19
  69. package/dist/extra/index.cjs.map +1 -0
  70. package/dist/extra/index.d.cts +1 -17
  71. package/dist/extra/index.d.ts +1 -17
  72. package/dist/extra/index.js +3 -1
  73. package/dist/extra/index.js.map +1 -0
  74. package/dist/extra/node.cjs +21 -2
  75. package/dist/extra/node.cjs.map +1 -0
  76. package/dist/extra/node.d.cts +1 -187
  77. package/dist/extra/node.d.ts +1 -187
  78. package/dist/extra/node.js +3 -2
  79. package/dist/extra/node.js.map +1 -0
  80. package/dist/extra/operators.cjs +21 -1
  81. package/dist/extra/operators.cjs.map +1 -0
  82. package/dist/extra/operators.d.cts +1 -958
  83. package/dist/extra/operators.d.ts +1 -958
  84. package/dist/extra/operators.js +3 -1
  85. package/dist/extra/operators.js.map +1 -0
  86. package/dist/extra/reactive.cjs +21 -1
  87. package/dist/extra/reactive.cjs.map +1 -0
  88. package/dist/extra/reactive.d.cts +1 -353
  89. package/dist/extra/reactive.d.ts +1 -353
  90. package/dist/extra/reactive.js +3 -1
  91. package/dist/extra/reactive.js.map +1 -0
  92. package/dist/extra/render/index.cjs +21 -5
  93. package/dist/extra/render/index.cjs.map +1 -0
  94. package/dist/extra/render/index.d.cts +1 -183
  95. package/dist/extra/render/index.d.ts +1 -183
  96. package/dist/extra/render/index.js +3 -1
  97. package/dist/extra/render/index.js.map +1 -0
  98. package/dist/extra/sources.cjs +21 -3
  99. package/dist/extra/sources.cjs.map +1 -0
  100. package/dist/extra/sources.d.cts +1 -584
  101. package/dist/extra/sources.d.ts +1 -584
  102. package/dist/extra/sources.js +3 -1
  103. package/dist/extra/sources.js.map +1 -0
  104. package/dist/extra/storage-browser.cjs +21 -1
  105. package/dist/extra/storage-browser.cjs.map +1 -0
  106. package/dist/extra/storage-browser.d.cts +1 -37
  107. package/dist/extra/storage-browser.d.ts +1 -37
  108. package/dist/extra/storage-browser.js +3 -1
  109. package/dist/extra/storage-browser.js.map +1 -0
  110. package/dist/extra/storage-core.cjs +21 -1
  111. package/dist/extra/storage-core.cjs.map +1 -0
  112. package/dist/extra/storage-core.d.cts +1 -28
  113. package/dist/extra/storage-core.d.ts +1 -28
  114. package/dist/extra/storage-core.js +3 -1
  115. package/dist/extra/storage-core.js.map +1 -0
  116. package/dist/extra/storage-node.cjs +20 -0
  117. package/dist/extra/storage-node.cjs.map +1 -0
  118. package/dist/extra/storage-node.d.cts +1 -2
  119. package/dist/extra/storage-node.d.ts +1 -2
  120. package/dist/extra/storage-node.js +3 -0
  121. package/dist/extra/storage-node.js.map +1 -0
  122. package/dist/extra/storage-tiers-browser.cjs +21 -1
  123. package/dist/extra/storage-tiers-browser.cjs.map +1 -0
  124. package/dist/extra/storage-tiers-browser.d.cts +1 -120
  125. package/dist/extra/storage-tiers-browser.d.ts +1 -120
  126. package/dist/extra/storage-tiers-browser.js +3 -1
  127. package/dist/extra/storage-tiers-browser.js.map +1 -0
  128. package/dist/extra/storage-tiers-node.cjs +21 -1
  129. package/dist/extra/storage-tiers-node.cjs.map +1 -0
  130. package/dist/extra/storage-tiers-node.d.cts +1 -210
  131. package/dist/extra/storage-tiers-node.d.ts +1 -210
  132. package/dist/extra/storage-tiers-node.js +3 -1
  133. package/dist/extra/storage-tiers-node.js.map +1 -0
  134. package/dist/extra/storage-tiers.cjs +21 -1
  135. package/dist/extra/storage-tiers.cjs.map +1 -0
  136. package/dist/extra/storage-tiers.d.cts +1 -412
  137. package/dist/extra/storage-tiers.d.ts +1 -412
  138. package/dist/extra/storage-tiers.js +3 -1
  139. package/dist/extra/storage-tiers.js.map +1 -0
  140. package/dist/extra/storage-wal.cjs +21 -0
  141. package/dist/extra/storage-wal.cjs.map +1 -0
  142. package/dist/extra/storage-wal.d.cts +1 -0
  143. package/dist/extra/storage-wal.d.ts +1 -0
  144. package/dist/extra/storage-wal.js +3 -0
  145. package/dist/extra/storage-wal.js.map +1 -0
  146. package/dist/graph/index.cjs +21 -7
  147. package/dist/graph/index.cjs.map +1 -0
  148. package/dist/graph/index.d.cts +1 -7
  149. package/dist/graph/index.d.ts +1 -7
  150. package/dist/graph/index.js +3 -1
  151. package/dist/graph/index.js.map +1 -0
  152. package/dist/index.cjs +20 -227
  153. package/dist/index.cjs.map +1 -0
  154. package/dist/index.d.cts +45 -95
  155. package/dist/index.d.ts +45 -95
  156. package/dist/index.js +3 -1
  157. package/dist/index.js.map +1 -0
  158. package/dist/patterns/ai/browser.cjs +20 -7
  159. package/dist/patterns/ai/browser.cjs.map +1 -0
  160. package/dist/patterns/ai/browser.d.cts +1 -127
  161. package/dist/patterns/ai/browser.d.ts +1 -127
  162. package/dist/patterns/ai/browser.js +3 -3
  163. package/dist/patterns/ai/browser.js.map +1 -0
  164. package/dist/patterns/ai/index.cjs +20 -73
  165. package/dist/patterns/ai/index.cjs.map +1 -0
  166. package/dist/patterns/ai/index.d.cts +1 -20
  167. package/dist/patterns/ai/index.d.ts +1 -20
  168. package/dist/patterns/ai/index.js +3 -1
  169. package/dist/patterns/ai/index.js.map +1 -0
  170. package/dist/patterns/ai/node.cjs +21 -1
  171. package/dist/patterns/ai/node.cjs.map +1 -0
  172. package/dist/patterns/ai/node.d.cts +1 -59
  173. package/dist/patterns/ai/node.d.ts +1 -59
  174. package/dist/patterns/ai/node.js +3 -1
  175. package/dist/patterns/ai/node.js.map +1 -0
  176. package/dist/patterns/cqrs/index.cjs +21 -3
  177. package/dist/patterns/cqrs/index.cjs.map +1 -0
  178. package/dist/patterns/cqrs/index.d.cts +1 -8
  179. package/dist/patterns/cqrs/index.d.ts +1 -8
  180. package/dist/patterns/cqrs/index.js +3 -1
  181. package/dist/patterns/cqrs/index.js.map +1 -0
  182. package/dist/patterns/demo-shell/index.cjs +21 -5
  183. package/dist/patterns/demo-shell/index.cjs.map +1 -0
  184. package/dist/patterns/demo-shell/index.d.cts +1 -7
  185. package/dist/patterns/demo-shell/index.d.ts +1 -7
  186. package/dist/patterns/demo-shell/index.js +3 -1
  187. package/dist/patterns/demo-shell/index.js.map +1 -0
  188. package/dist/patterns/domain-templates/index.cjs +21 -3
  189. package/dist/patterns/domain-templates/index.cjs.map +1 -0
  190. package/dist/patterns/domain-templates/index.d.cts +1 -6
  191. package/dist/patterns/domain-templates/index.d.ts +1 -6
  192. package/dist/patterns/domain-templates/index.js +3 -1
  193. package/dist/patterns/domain-templates/index.js.map +1 -0
  194. package/dist/patterns/graphspec/index.cjs +21 -86
  195. package/dist/patterns/graphspec/index.cjs.map +1 -0
  196. package/dist/patterns/graphspec/index.d.cts +1 -8
  197. package/dist/patterns/graphspec/index.d.ts +1 -8
  198. package/dist/patterns/graphspec/index.js +3 -1
  199. package/dist/patterns/graphspec/index.js.map +1 -0
  200. package/dist/patterns/harness/index.cjs +21 -48
  201. package/dist/patterns/harness/index.cjs.map +1 -0
  202. package/dist/patterns/harness/index.d.cts +1 -13
  203. package/dist/patterns/harness/index.d.ts +1 -13
  204. package/dist/patterns/harness/index.js +3 -1
  205. package/dist/patterns/harness/index.js.map +1 -0
  206. package/dist/patterns/inspect/index.cjs +21 -3
  207. package/dist/patterns/inspect/index.cjs.map +1 -0
  208. package/dist/patterns/inspect/index.d.cts +1 -9
  209. package/dist/patterns/inspect/index.d.ts +1 -9
  210. package/dist/patterns/inspect/index.js +3 -1
  211. package/dist/patterns/inspect/index.js.map +1 -0
  212. package/dist/patterns/job-queue/index.cjs +21 -3
  213. package/dist/patterns/job-queue/index.cjs.map +1 -0
  214. package/dist/patterns/job-queue/index.d.cts +1 -9
  215. package/dist/patterns/job-queue/index.d.ts +1 -9
  216. package/dist/patterns/job-queue/index.js +3 -1
  217. package/dist/patterns/job-queue/index.js.map +1 -0
  218. package/dist/patterns/memory/index.cjs +21 -3
  219. package/dist/patterns/memory/index.cjs.map +1 -0
  220. package/dist/patterns/memory/index.d.cts +1 -8
  221. package/dist/patterns/memory/index.d.ts +1 -8
  222. package/dist/patterns/memory/index.js +3 -1
  223. package/dist/patterns/memory/index.js.map +1 -0
  224. package/dist/patterns/messaging/index.cjs +21 -3
  225. package/dist/patterns/messaging/index.cjs.map +1 -0
  226. package/dist/patterns/messaging/index.d.cts +1 -7
  227. package/dist/patterns/messaging/index.d.ts +1 -7
  228. package/dist/patterns/messaging/index.js +3 -1
  229. package/dist/patterns/messaging/index.js.map +1 -0
  230. package/dist/patterns/orchestration/index.cjs +21 -3
  231. package/dist/patterns/orchestration/index.cjs.map +1 -0
  232. package/dist/patterns/orchestration/index.d.cts +1 -8
  233. package/dist/patterns/orchestration/index.d.ts +1 -8
  234. package/dist/patterns/orchestration/index.js +3 -1
  235. package/dist/patterns/orchestration/index.js.map +1 -0
  236. package/dist/patterns/process/index.cjs +21 -3
  237. package/dist/patterns/process/index.cjs.map +1 -0
  238. package/dist/patterns/process/index.d.cts +1 -10
  239. package/dist/patterns/process/index.d.ts +1 -10
  240. package/dist/patterns/process/index.js +3 -1
  241. package/dist/patterns/process/index.js.map +1 -0
  242. package/dist/patterns/reactive-layout/index.cjs +21 -4
  243. package/dist/patterns/reactive-layout/index.cjs.map +1 -0
  244. package/dist/patterns/reactive-layout/index.d.cts +1 -7
  245. package/dist/patterns/reactive-layout/index.d.ts +1 -7
  246. package/dist/patterns/reactive-layout/index.js +3 -1
  247. package/dist/patterns/reactive-layout/index.js.map +1 -0
  248. package/dist/patterns/reduction/index.cjs +21 -3
  249. package/dist/patterns/reduction/index.cjs.map +1 -0
  250. package/dist/patterns/reduction/index.d.cts +1 -6
  251. package/dist/patterns/reduction/index.d.ts +1 -6
  252. package/dist/patterns/reduction/index.js +3 -1
  253. package/dist/patterns/reduction/index.js.map +1 -0
  254. package/dist/patterns/surface/index.cjs +21 -13
  255. package/dist/patterns/surface/index.cjs.map +1 -0
  256. package/dist/patterns/surface/index.d.cts +1 -9
  257. package/dist/patterns/surface/index.d.ts +1 -9
  258. package/dist/patterns/surface/index.js +3 -1
  259. package/dist/patterns/surface/index.js.map +1 -0
  260. package/dist/patterns/topology-view/index.cjs +21 -0
  261. package/dist/patterns/topology-view/index.cjs.map +1 -0
  262. package/dist/patterns/topology-view/index.d.cts +1 -0
  263. package/dist/patterns/topology-view/index.d.ts +1 -0
  264. package/dist/patterns/topology-view/index.js +3 -0
  265. package/dist/patterns/topology-view/index.js.map +1 -0
  266. package/dist/testing/index.cjs +21 -0
  267. package/dist/testing/index.cjs.map +1 -0
  268. package/dist/testing/index.d.cts +1 -0
  269. package/dist/testing/index.d.ts +1 -0
  270. package/dist/testing/index.js +3 -0
  271. package/dist/testing/index.js.map +1 -0
  272. package/package.json +608 -584
  273. package/dist/backoff-HPZMEZNF.js +0 -1
  274. package/dist/cascading-BglDkMdX.d.cts +0 -199
  275. package/dist/cascading-MFgxu7Yo.d.ts +0 -199
  276. package/dist/chunk-2T7U5EU6.js +0 -1
  277. package/dist/chunk-3G5U5QNE.js +0 -5
  278. package/dist/chunk-4VVTGLXJ.js +0 -1
  279. package/dist/chunk-5M4CCMMD.js +0 -45
  280. package/dist/chunk-5QDBSZBV.js +0 -1
  281. package/dist/chunk-5XJ6B66J.js +0 -1
  282. package/dist/chunk-6QZNQS5B.js +0 -1
  283. package/dist/chunk-6X7AFUJV.js +0 -9
  284. package/dist/chunk-7K6PWTDQ.js +0 -1
  285. package/dist/chunk-7LIAPXJB.js +0 -1
  286. package/dist/chunk-7WPU3UHQ.js +0 -1
  287. package/dist/chunk-A5WCQ5NO.js +0 -1
  288. package/dist/chunk-APPIWSGD.js +0 -84
  289. package/dist/chunk-BEZWM2SY.js +0 -1
  290. package/dist/chunk-C72GO4IZ.js +0 -1
  291. package/dist/chunk-CB676TKJ.js +0 -1
  292. package/dist/chunk-CE6TI2TL.js +0 -1
  293. package/dist/chunk-CE72X3WO.js +0 -1
  294. package/dist/chunk-CK2E7BTU.js +0 -1
  295. package/dist/chunk-CLVB32RD.js +0 -1
  296. package/dist/chunk-CRVT7D2P.js +0 -1
  297. package/dist/chunk-D5RFJOZ2.js +0 -1
  298. package/dist/chunk-D7GPHKFH.js +0 -1
  299. package/dist/chunk-DHRX7JX4.js +0 -2
  300. package/dist/chunk-ESMPEKEV.js +0 -1
  301. package/dist/chunk-F672GV32.js +0 -1
  302. package/dist/chunk-FZMYDOWV.js +0 -1
  303. package/dist/chunk-GHBWHMRZ.js +0 -1
  304. package/dist/chunk-GLERH466.js +0 -1
  305. package/dist/chunk-GPW2V3RE.js +0 -1
  306. package/dist/chunk-HIDYF36O.js +0 -1
  307. package/dist/chunk-HITNVN6B.js +0 -3
  308. package/dist/chunk-HY4DJBA7.js +0 -5
  309. package/dist/chunk-KZIEYVXN.js +0 -1
  310. package/dist/chunk-L6NSJVJZ.js +0 -1
  311. package/dist/chunk-N4MQX6JU.js +0 -18
  312. package/dist/chunk-N7FHEL4D.js +0 -1
  313. package/dist/chunk-NTEURFZH.js +0 -1
  314. package/dist/chunk-OIVP6KFV.js +0 -1
  315. package/dist/chunk-OPHBU3LG.js +0 -1
  316. package/dist/chunk-OYQOZP2F.js +0 -5
  317. package/dist/chunk-PTZK576G.js +0 -1
  318. package/dist/chunk-QYADASLV.js +0 -1
  319. package/dist/chunk-ST7UXLWR.js +0 -1
  320. package/dist/chunk-SVY7VUYU.js +0 -1
  321. package/dist/chunk-TK3NWWD4.js +0 -1
  322. package/dist/chunk-TSOYJ743.js +0 -1
  323. package/dist/chunk-UNGSTR4X.js +0 -61
  324. package/dist/chunk-VIMF6LGM.js +0 -1
  325. package/dist/chunk-VJLMUKOI.js +0 -1
  326. package/dist/chunk-VN6RDSK2.js +0 -1
  327. package/dist/chunk-VV4N5P64.js +0 -1
  328. package/dist/chunk-W3I423PS.js +0 -1
  329. package/dist/chunk-WJR24TAG.js +0 -1
  330. package/dist/chunk-XTGKMHSW.js +0 -1
  331. package/dist/chunk-YBB7ZGTY.js +0 -1
  332. package/dist/chunk-Z4NPUARF.js +0 -1
  333. package/dist/chunk-ZGNQRPDT.js +0 -1
  334. package/dist/chunk-ZKPSFFKU.js +0 -1
  335. package/dist/chunk-ZLV5SQSX.js +0 -1
  336. package/dist/content-addressed-storage-4-ST1tYk.d.cts +0 -124
  337. package/dist/content-addressed-storage-DuYMjV7o.d.ts +0 -124
  338. package/dist/decay-BvOWTZ00.d.ts +0 -112
  339. package/dist/decay-CFlLvXUT.d.cts +0 -112
  340. package/dist/fallback-74oxi34l.d.cts +0 -250
  341. package/dist/fallback-DUyyBTBK.d.ts +0 -250
  342. package/dist/graph-CWvEUQAq.d.cts +0 -1861
  343. package/dist/graph-D9LFnda9.d.ts +0 -1861
  344. package/dist/index-5k1T6jl0.d.cts +0 -121
  345. package/dist/index-9770hRuQ.d.cts +0 -779
  346. package/dist/index-B-_tFaqV.d.cts +0 -468
  347. package/dist/index-B17QddL1.d.cts +0 -374
  348. package/dist/index-B1F8Enjf.d.ts +0 -704
  349. package/dist/index-B5S8ULbU.d.ts +0 -515
  350. package/dist/index-B8YnZpIR.d.ts +0 -102
  351. package/dist/index-BHskSB8v.d.ts +0 -3413
  352. package/dist/index-BIYAkbAi.d.cts +0 -26
  353. package/dist/index-BQSKmbuG.d.cts +0 -127
  354. package/dist/index-BaQaY_IQ.d.cts +0 -231
  355. package/dist/index-BmZXHqkE.d.ts +0 -36
  356. package/dist/index-BoJ5JHxI.d.ts +0 -557
  357. package/dist/index-BocU7pqs.d.ts +0 -779
  358. package/dist/index-BrPrLl4e.d.cts +0 -86
  359. package/dist/index-BxNs2HB9.d.cts +0 -1858
  360. package/dist/index-Byu-OpX_.d.ts +0 -113
  361. package/dist/index-C1T3d7V-.d.cts +0 -704
  362. package/dist/index-C5ri2Axc.d.cts +0 -301
  363. package/dist/index-C5stwKcw.d.cts +0 -44
  364. package/dist/index-C9l6OEBL.d.ts +0 -26
  365. package/dist/index-CBBLl_rc.d.ts +0 -127
  366. package/dist/index-CBGUK09R.d.ts +0 -754
  367. package/dist/index-CC-AvFTy.d.cts +0 -557
  368. package/dist/index-CJF1URuX.d.ts +0 -121
  369. package/dist/index-CK29LV56.d.cts +0 -34
  370. package/dist/index-CMh5Rz1y.d.ts +0 -385
  371. package/dist/index-CPQlGA29.d.ts +0 -34
  372. package/dist/index-CR8QpwX8.d.ts +0 -2680
  373. package/dist/index-CS0LTlB8.d.cts +0 -385
  374. package/dist/index-CSOmP7xT.d.cts +0 -291
  375. package/dist/index-CYq8vAyV.d.ts +0 -291
  376. package/dist/index-CZ3r5Rxp.d.ts +0 -374
  377. package/dist/index-CasX6Pfq.d.cts +0 -358
  378. package/dist/index-CdAlHFEt.d.ts +0 -44
  379. package/dist/index-CdTelp1M.d.ts +0 -202
  380. package/dist/index-CeFiHtAg.d.ts +0 -468
  381. package/dist/index-Cj3WohTd.d.cts +0 -202
  382. package/dist/index-Climxqsu.d.cts +0 -754
  383. package/dist/index-Co7uli2l.d.cts +0 -3413
  384. package/dist/index-CviRnE4K.d.ts +0 -45
  385. package/dist/index-Cwv0KWcU.d.cts +0 -102
  386. package/dist/index-CzLVrjxn.d.ts +0 -231
  387. package/dist/index-D0aciIex.d.cts +0 -209
  388. package/dist/index-DHen9Klo.d.ts +0 -1858
  389. package/dist/index-DV_1YuVk.d.cts +0 -221
  390. package/dist/index-Dc4AYqrJ.d.cts +0 -515
  391. package/dist/index-Dgl1HpPn.d.ts +0 -86
  392. package/dist/index-DisjX8a-.d.ts +0 -221
  393. package/dist/index-UPSiS-X7.d.cts +0 -2680
  394. package/dist/index-Yq60JP3s.d.ts +0 -209
  395. package/dist/index-ZVQhLa2i.d.cts +0 -37
  396. package/dist/index-_6ODbuOu.d.cts +0 -45
  397. package/dist/index-hcDJ8PSI.d.cts +0 -36
  398. package/dist/index-nozs3fFC.d.ts +0 -301
  399. package/dist/index-p09KSrTN.d.ts +0 -358
  400. package/dist/index-sqkqlb1p.d.ts +0 -37
  401. package/dist/index-tRCxuAXF.d.cts +0 -113
  402. package/dist/node-kK3CvTrR.d.cts +0 -1347
  403. package/dist/node-kK3CvTrR.d.ts +0 -1347
  404. package/dist/observable-DWjNfLvC.d.ts +0 -36
  405. package/dist/observable-e3eiPPFy.d.cts +0 -36
  406. package/dist/pipeline-graph-CIKhynsF.d.cts +0 -142
  407. package/dist/pipeline-graph-Sgj0gCwn.d.ts +0 -142
  408. package/dist/reactive-layout-DOTs9P3X.d.ts +0 -183
  409. package/dist/reactive-layout-DgctbqZo.d.cts +0 -183
  410. package/dist/reactive-log-BKALbfal.d.ts +0 -223
  411. package/dist/reactive-log-DIGdYqQ6.d.cts +0 -223
  412. package/dist/reactive-map-CEFGp8TK.d.cts +0 -296
  413. package/dist/reactive-map-DS_SIAxv.d.ts +0 -296
  414. package/dist/resilience-6LYQJAC5.js +0 -1
  415. package/dist/sugar-DQjFmVqb.d.cts +0 -399
  416. package/dist/sugar-fhLIE7TT.d.ts +0 -399
  417. package/dist/topology-tree-Bcz27hpF.d.cts +0 -25
  418. package/dist/topology-tree-xvaD0fOX.d.ts +0 -25
  419. package/dist/types-C0_yquda.d.cts +0 -442
  420. package/dist/types-CWFysE9E.d.ts +0 -442
@@ -1,2680 +0,0 @@
1
- import { T as TokenUsage, L as LLMAdapter, P as PricingFn, C as ChatMessage, a as LLMInvokeOptions, d as ToolDefinition, b as LLMResponse, S as StreamDelta, 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, k as TieredRate, l as composePricing, m as computePrice, n as createCapabilitiesRegistry, o as createPricingRegistry, p as pricingFor, r as registryPricing, z as zeroPrice } from './types-C0_yquda.cjs';
2
- import { a as CascadeExhaustionReport, A as AdapterProvider, b as AdapterTier, d as AllTiersExhaustedError, C as CascadingLlmAdapterOptions, e as CreateAdapterOptions, O as OpenAICompatAdapterOptions, f as OpenAICompatPreset, g as OpenAISdkLike, h as cascadingLlmAdapter, c as createAdapter, o as openAICompatAdapter, t as tier } from './cascading-BglDkMdX.cjs';
3
- import { N as Node, A as Actor } from './node-kK3CvTrR.cjs';
4
- import { a as ReactiveLogBundle } from './reactive-log-DIGdYqQ6.cjs';
5
- import { b as CircuitBreakerOptions, C as CircuitBreaker, c as CircuitOpenError } from './index-C1T3d7V-.cjs';
6
- import { NodeInput } from './extra/sources.cjs';
7
- import { W as WithReplayCacheOptions, F as FallbackAdapterOptions, a as FallbackFixture, b as FallbackMissError, c as FallbackMissPolicy, R as ReplayCacheKeyContext, d as ReplayCacheMissError, e as ReplayCacheMode, f as canonicalJson, g as fallbackAdapter, w as withReplayCache } from './fallback-74oxi34l.cjs';
8
- import { E as Extraction, a as DistillOptions, D as DistillBundle, f as DEFAULT_DECAY_RATE } from './decay-CFlLvXUT.cjs';
9
- import { G as Graph, a as GraphOptions, i as GraphCheckpointRecord, h as GraphAttachStorageOptions } from './graph-CWvEUQAq.cjs';
10
- import { T as TopicGraph } from './index-C5ri2Axc.cjs';
11
- import { G as GateController, c as GateOptions } from './pipeline-graph-CIKhynsF.cjs';
12
- import { V as VectorSearchResult, C as CollectionGraph, a as VectorIndexGraph, K as KnowledgeGraph } from './index-B17QddL1.cjs';
13
- import { StorageHandle } from './extra/storage-core.cjs';
14
- import { SnapshotStorageTier } from './extra/storage-tiers.cjs';
15
- import { c as GraphSpecCatalog } from './index-CS0LTlB8.cjs';
16
-
17
- /**
18
- * Observable adapter wrapper — the "inverted statistics" surface.
19
- *
20
- * The library emits structured facts (token counts, latency, timestamps)
21
- * as reactive nodes. Users compose interpretation (pricing, dashboards,
22
- * telemetry, budget breakers) as derived layers on top.
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
- * Release the internal keepalive subscriptions on the three counter
63
- * derives (`totalCalls` / `totalInputTokens` / `totalOutputTokens`) so the
64
- * bundle can be GC'd when the caller discards it. Idempotent. Long-lived
65
- * adapter bundles (module-level singletons) can ignore; transient bundles
66
- * (per-request / per-user) should call on teardown.
67
- */
68
- dispose(): void;
69
- }
70
- /**
71
- * Wrap any {@link LLMAdapter} with a reactive stats bundle.
72
- *
73
- * Implementation (Unit 10 B):
74
- * - `stats.lastCall` is a `state<CallStatsEvent | null>`.
75
- * - Counters (`totalCalls` / `totalInputTokens` / `totalOutputTokens`) are
76
- * **derived views** over `allCalls.entries` — self-maintaining, no manual
77
- * `.cache + 1 + emit` pattern, visible topology in `describe()`.
78
- * - `stats.allCalls` is a `reactiveLog<CallStatsEvent>` — bounded, supports
79
- * `tail(n)` / `slice(start, stop)` for dashboard views.
80
- * - The wrapped adapter passes DATA through via `adaptInvokeResult`, which
81
- * uses `onFirstData` internally to guard against re-subscription double-fire
82
- * and wires `.catch` for Promise-path error recording (Unit 10 A).
83
- */
84
- declare function observableAdapter(inner: LLMAdapter, opts?: {
85
- logMax?: number;
86
- name?: string;
87
- }): {
88
- adapter: LLMAdapter;
89
- stats: AdapterStats;
90
- };
91
-
92
- /**
93
- * `withBreaker` — circuit-breaker middleware for LLM adapters.
94
- *
95
- * Reuses the library's existing `circuitBreaker` primitive from
96
- * `extra/resilience.ts`. When the breaker is open, calls throw
97
- * `CircuitOpenError` instead of hitting the provider.
98
- */
99
-
100
- interface WithBreakerOptions extends CircuitBreakerOptions {
101
- /**
102
- * Optional external breaker — pass a shared instance to wire the same
103
- * breaker across multiple adapters (e.g. all tiers of a `cascadingLlmAdapter`).
104
- */
105
- breaker?: CircuitBreaker;
106
- }
107
- declare function withBreaker(inner: LLMAdapter, opts?: WithBreakerOptions): {
108
- adapter: LLMAdapter;
109
- breaker: CircuitBreaker;
110
- };
111
-
112
- /**
113
- * `withBudgetGate` — cap an adapter by calls / tokens / USD.
114
- *
115
- * Totals are an O(1)-per-event running accumulator (a `state<BudgetTotals>`
116
- * updated imperatively inside `record()`), not a derived reduce over the
117
- * full log — avoids the quadratic cost at sustained traffic while preserving
118
- * the reactive surface. The full log is still exposed via the bundle for
119
- * dashboards / auditors.
120
- *
121
- * Budgets are enforced imperatively at `invoke()` / `stream()` entry — the
122
- * running totals + `isOpen.cache` are read; if closed, the call rejects /
123
- * throws `BudgetExhaustedError` without hitting the wrapped adapter. On
124
- * success, the call's usage is appended to the log AND debits the running
125
- * totals in a single synchronous update.
126
- *
127
- * Wave A Unit 11 Q4: rejected-Promise path now wires `.catch` (via
128
- * `adaptInvokeResult.onError`) so failed invoke calls record a CallStatsEvent
129
- * with `error` populated. Prior code silently dropped rejection from the
130
- * `totals` / `log` surface.
131
- */
132
-
133
- declare class BudgetExhaustedError extends Error {
134
- readonly which: string;
135
- readonly limit: number;
136
- readonly observed: number;
137
- name: string;
138
- constructor(which: string, limit: number, observed: number);
139
- }
140
- interface BudgetCaps {
141
- calls?: number;
142
- inputTokens?: number;
143
- outputTokens?: number;
144
- usd?: number;
145
- }
146
- interface BudgetTotals {
147
- calls: number;
148
- inputTokens: number;
149
- outputTokens: number;
150
- usd: number;
151
- }
152
- interface BudgetGateBundle {
153
- totals: Node<BudgetTotals>;
154
- isOpen: Node<boolean>;
155
- log: ReactiveLogBundle<CallStatsEvent>;
156
- reset(): void;
157
- }
158
- interface WithBudgetGateOptions {
159
- caps: BudgetCaps;
160
- /**
161
- * Optional pricing function for USD gating. If omitted, `caps.usd` is
162
- * ignored (caps.calls / caps.inputTokens / caps.outputTokens still apply).
163
- */
164
- pricingFn?: PricingFn;
165
- /**
166
- * Edge-triggered: fires exactly once when the gate transitions from
167
- * open to closed. Subsequent invoke/stream attempts against a closed
168
- * gate do NOT re-fire `onExhausted` — use the reactive `isOpen` node
169
- * if you need per-attempt notifications. Receives the cap key that
170
- * triggered the transition.
171
- */
172
- onExhausted?: (which: keyof BudgetCaps) => void;
173
- /** Name for logs / describe output. */
174
- name?: string;
175
- /** Max events retained in the log (default 1000). */
176
- logMax?: number;
177
- }
178
- /**
179
- * Wrap an adapter with budget enforcement. Returns `{adapter, budget}` so
180
- * callers can subscribe to the bundle for dashboards.
181
- */
182
- declare function withBudgetGate(inner: LLMAdapter, opts: WithBudgetGateOptions): {
183
- adapter: LLMAdapter;
184
- budget: BudgetGateBundle;
185
- };
186
-
187
- /**
188
- * `withDryRun` — short-circuit to a fake adapter when a flag is on.
189
- *
190
- * Useful for CI / preflight / cost-safety pipelines: wrap a real adapter,
191
- * pass `enabled: true` (or a reactive flag) to bypass the wire call. Default
192
- * shim is {@link dryRunAdapter}; callers can supply their own.
193
- *
194
- * **Returns `{adapter, dispose}`** — call `dispose()` to release the internal
195
- * keepalive on the reactive `enabled` input. Long-lived adapter instances
196
- * (module-level singletons) can ignore dispose; transient adapters (per-
197
- * request or per-user) should call it on teardown to allow the source to
198
- * be GC'd.
199
- */
200
-
201
- interface WithDryRunOptions {
202
- /**
203
- * Toggle — `true` always dry-runs; `false` always passes through; a
204
- * `NodeInput<boolean>` reads the current value at call time (factory-time
205
- * seed pattern, live-tunable).
206
- */
207
- enabled: NodeInput<boolean>;
208
- /** Dry-run adapter override. Default: `dryRunAdapter({ provider: inner.provider, model: inner.model })`. */
209
- mock?: LLMAdapter;
210
- }
211
- interface WithDryRunBundle {
212
- adapter: LLMAdapter;
213
- /**
214
- * Release the internal keepalive subscription on the reactive `enabled`
215
- * input. Idempotent. Safe to ignore on long-lived adapters.
216
- */
217
- dispose(): void;
218
- }
219
- declare function withDryRun(inner: LLMAdapter, opts: WithDryRunOptions): WithDryRunBundle;
220
-
221
- /**
222
- * Adaptive rate limiter — reactive, live-tunable, 429-aware.
223
- *
224
- * Wraps two `tokenBucket` instances (requests, tokens) with:
225
- * - Reactive `rpm` / `tpm` knobs that can be re-tuned at runtime via `NodeInput<number>`.
226
- * - An adaptation signal input (`Node<RateLimitSignal>`) that feeds back
227
- * provider 429 / retry-after / x-ratelimit-* headers to tighten limits.
228
- * - A `clampCooldownMs` TTL on signal-induced caps so a transient 429 doesn't
229
- * permanently throttle — caps decay back to user-configured values after
230
- * the cooldown elapses.
231
- * - TPM-miss recovery: consumed RPM tokens are returned to the request
232
- * bucket when the TPM admit fails, via `TokenBucket.putBack`.
233
- * - Imperative `acquire()` for bridging to Promise-based call paths
234
- * (used by the `withRateLimiter` adapter middleware).
235
- *
236
- * **Timer policy:** sleeps use `ResettableTimer` (documented spec §5.10
237
- * escape hatch in `src/extra/timer.ts`) rather than `fromTimer` to avoid
238
- * allocating a new Node per acquire cycle.
239
- *
240
- * Design lives in `docs/optimizations.md` § "Reactive adaptive rate limiter".
241
- */
242
-
243
- /**
244
- * Rate-limit signal emitted by an adaptation source (e.g., an HTTP 429 parser).
245
- *
246
- * Any subset of fields may be present. The adaptive rate limiter uses:
247
- * - `retryAfterMs` — blocks acquire() for this duration.
248
- * - `rpmCap` / `tpmCap` — tightens effective rpm/tpm to this value (decays
249
- * back to the user-configured cap after `clampCooldownMs`).
250
- * - `usageHint` — updates the last-known rpm/tpm usage ratio for logging.
251
- */
252
- interface RateLimitSignal {
253
- /** Throttle duration — pause acquire() for this long. */
254
- retryAfterMs?: number;
255
- /** Hard cap for requests-per-minute; effective rpm = min(current, rpmCap) while clamp is active. */
256
- rpmCap?: number;
257
- /** Hard cap for tokens-per-minute; effective tpm = min(current, tpmCap) while clamp is active. */
258
- tpmCap?: number;
259
- /** Observed usage-percentage hint (0..1) — for observability, not gating. */
260
- usageHint?: {
261
- rpm?: number;
262
- tpm?: number;
263
- };
264
- /** Free-form provider-specific payload. */
265
- metadata?: Record<string, unknown>;
266
- }
267
- interface AdaptiveRateLimiterBundle {
268
- /** Effective requests-per-minute (post-signal-clamp). Reactive. */
269
- readonly effectiveRpm: Node<number>;
270
- /** Effective tokens-per-minute (post-signal-clamp). Reactive. */
271
- readonly effectiveTpm: Node<number>;
272
- /** Last adaptation signal observed. */
273
- readonly lastSignal: Node<RateLimitSignal>;
274
- /** Pending `acquire()` callers waiting for capacity. */
275
- readonly pending: Node<number>;
276
- /** Current request-token-bucket fill (approximate). */
277
- readonly rpmAvailable: Node<number>;
278
- /** Current token-bucket fill (approximate). */
279
- readonly tpmAvailable: Node<number>;
280
- /**
281
- * Imperative bridge: wait until `requestCost` request-tokens and
282
- * `tokenCost` tokens are available, then consume them. Honors the
283
- * most recent `retryAfterMs` from adaptation signals. Rejects with
284
- * an `AbortError`-named error if `signal` aborts while waiting.
285
- * `requestCost` defaults to 1; `tokenCost` defaults to 0 (rpm-only gating).
286
- */
287
- acquire(opts?: {
288
- requestCost?: number;
289
- tokenCost?: number;
290
- signal?: AbortSignal;
291
- }): Promise<void>;
292
- /**
293
- * Feed back observed token usage (post-call) so the TPM bucket reflects
294
- * real consumption rather than the pre-call estimate. A positive `delta`
295
- * debits additional TPM (undershot estimate); a negative `delta` credits
296
- * back overshoot (`putBack`).
297
- */
298
- recordUsage(delta: number): void;
299
- /** Manually feed an adaptation signal — useful for tests. */
300
- recordSignal(sig: RateLimitSignal): void;
301
- /** Dispose internal subscriptions and pending timers. */
302
- dispose(): void;
303
- }
304
-
305
- /**
306
- * HTTP 429 / rate-limit parser.
307
- *
308
- * Produces a {@link RateLimitSignal} from provider HTTP errors so adaptive
309
- * rate limiters can tighten effective limits. Normalizes:
310
- * - `Retry-After` (seconds or HTTP-date)
311
- * - `x-ratelimit-reset` / `x-ratelimit-reset-tokens` (epoch secs or duration)
312
- * - `x-ratelimit-remaining-{requests,tokens}` + `x-ratelimit-limit-*`
313
- * - Anthropic `anthropic-ratelimit-*` headers
314
- * - OpenAI / OpenRouter / Groq headers (same family)
315
- * - Error message regex fallbacks for providers without structured headers
316
- */
317
-
318
- interface HttpErrorLike {
319
- status?: number;
320
- headers?: Headers | Record<string, string | string[] | undefined>;
321
- message?: string;
322
- }
323
- /**
324
- * Extract a {@link RateLimitSignal} from a fetch-style error object, a Response,
325
- * or any object exposing `.status` + `.headers` + `.message`.
326
- *
327
- * Returns `undefined` if no rate-limit information can be extracted.
328
- */
329
- declare function parseRateLimitFromError(err: unknown): RateLimitSignal | undefined;
330
-
331
- /**
332
- * `withRateLimiter` — adapter middleware bridging to the reactive
333
- * `adaptiveRateLimiter` primitive.
334
- *
335
- * - Consumes live `rpm`/`tpm` caps as reactive `NodeInput<number>` so
336
- * callers can retune at runtime (e.g. from a `ModelLimits.rpm` node).
337
- * - Adapts to provider 429 responses via `http429Parser` fed into the
338
- * limiter's `adaptation` signal.
339
- * - `costFn` estimates token cost pre-call (e.g. char-based approximation);
340
- * the post-call actual usage is fed back via `limiter.recordUsage()`.
341
- */
342
-
343
- interface WithRateLimiterOptions {
344
- /** Live rpm cap (defaults to `Infinity`). */
345
- rpm?: NodeInput<number>;
346
- /** Live tpm cap (defaults to `Infinity`). */
347
- tpm?: NodeInput<number>;
348
- /**
349
- * Pre-call token-cost estimate. Default: 0 (only rpm gates). Override with
350
- * e.g. a char-based heuristic:
351
- * `(msgs) => Math.ceil(msgs.reduce((s, m) => s + m.content.length, 0) / 4)`.
352
- */
353
- costFn?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => number;
354
- /**
355
- * Manual adaptation signal source. Defaults to a signal derived from
356
- * provider errors via `parseRateLimitFromError` — users can supply a
357
- * custom signal chain if they route errors elsewhere.
358
- */
359
- adaptation?: NodeInput<RateLimitSignal>;
360
- burstMultiplier?: number;
361
- name?: string;
362
- /**
363
- * Share an existing {@link AdaptiveRateLimiterBundle} across multiple
364
- * adapter wraps. When provided, `withRateLimiter` reuses this bundle
365
- * instead of constructing a new one — useful when the RPM/TPM cap is
366
- * logically per-provider but the caller wants to harden multiple adapters
367
- * (e.g. primary + fallback of the same vendor) against the shared cap.
368
- *
369
- * When `limiter` is set, `rpm` / `tpm` / `adaptation` / `burstMultiplier`
370
- * / `name` are ignored (the supplied bundle owns those). `costFn` is still
371
- * used per-wrap — each wrap supplies its own cost estimator.
372
- */
373
- limiter?: AdaptiveRateLimiterBundle;
374
- }
375
- /**
376
- * Wrap an adapter with adaptive rate limiting. Returns `{adapter, limiter}`
377
- * so callers can subscribe to limiter internals (rpmAvailable, pending, etc.)
378
- * for dashboards.
379
- */
380
- declare function withRateLimiter(inner: LLMAdapter, opts?: WithRateLimiterOptions): {
381
- adapter: LLMAdapter;
382
- limiter: AdaptiveRateLimiterBundle;
383
- };
384
-
385
- /**
386
- * `withRetry` — retry `invoke()` / `stream()` on transient errors.
387
- *
388
- * Streaming retry is tricky: we retry only if the stream fails before
389
- * yielding any tokens. Once tokens have started flowing, we surface the
390
- * error to avoid replaying from scratch (which would double-bill and
391
- * confuse consumers). Opt out of streaming retry via `opts.retryStreaming = false`.
392
- *
393
- * Uses `ResettableTimer` for backoff sleeps (spec §5.10 escape hatch, same
394
- * pattern as `extra/resilience.ts`). Abort-aware — early-aborts before the
395
- * first attempt and cleans up the abort listener on both the timer-fires
396
- * and abort paths.
397
- */
398
-
399
- interface WithRetryOptions {
400
- /** Max total attempts (including the first). Default 3. */
401
- attempts?: number;
402
- /** Base delay in ms. Default 500. */
403
- baseDelayMs?: number;
404
- /** Max delay in ms. Default 10_000. */
405
- maxDelayMs?: number;
406
- /**
407
- * Delay strategy. Default `"decorrelated"` — AWS-style `random(baseDelay,
408
- * min(maxDelay, prev * 3))` which smooths retry storms and matches common
409
- * SDK expectations. `"exp"` and `"linear"` produce deterministic schedules
410
- * when `jitter: false`.
411
- */
412
- strategy?: "exp" | "linear" | "decorrelated";
413
- /**
414
- * Add randomized jitter. Ignored for `strategy: "decorrelated"` (which is
415
- * inherently jittered). For `exp`/`linear`, symmetric jitter in `[0.5x,
416
- * 1.5x]` of the nominal delay.
417
- */
418
- jitter?: boolean;
419
- /**
420
- * Predicate: should this error trigger a retry? Default retries network /
421
- * 5xx / 429 / transient errors, but not 4xx (other than 429), aborts, or
422
- * `BudgetExhaustedError` from upstream middleware.
423
- */
424
- shouldRetry?: (err: unknown, attempt: number) => boolean;
425
- /** Retry streaming calls if they fail pre-first-token. Default true. */
426
- retryStreaming?: boolean;
427
- }
428
- declare function withRetry(inner: LLMAdapter, opts?: WithRetryOptions): LLMAdapter;
429
-
430
- /**
431
- * `resilientAdapter` — compose `withRateLimiter` + `withBudgetGate` +
432
- * `withBreaker` + `withTimeout` + `withRetry` + fallback over an {@link LLMAdapter}.
433
- *
434
- * Call-path peer of {@link resilientPipeline} (which operates on a reactive
435
- * `Node<T>` chain). Use `resilientPipeline` when composing graph sources; use
436
- * `resilientAdapter` when wrapping an adapter so downstream users see a
437
- * single hardened `invoke`/`stream` surface.
438
- *
439
- * Composition order (innermost to outermost, mirrors `resilientPipeline`):
440
- *
441
- * ```text
442
- * rateLimit → budget → breaker → timeout → retry → fallback
443
- * ```
444
- *
445
- * Rationale:
446
- * - **rateLimit innermost** — each attempt acquires a fresh slot; a retry
447
- * after a 429 waits for admission rather than bursting past the cap.
448
- * - **budget next** — per-attempt gate close short-circuits retries once a
449
- * cap trips.
450
- * - **breaker next** — each attempt observes circuit health; open breaker
451
- * fast-fails retries into fallback.
452
- * - **timeout before retry** — each retry re-arms a fresh per-attempt
453
- * deadline. If `timeout` wrapped `retry`, a single deadline would cover
454
- * the entire retry chain — surprising for callers.
455
- * - **retry before fallback** — fallback is entered only after the primary
456
- * exhausts its retry budget (or immediately fails in a way the predicate
457
- * doesn't retry).
458
- *
459
- * Every option is optional — omit the field and that layer is skipped. The
460
- * returned bundle exposes the primary adapter plus the internal bundles
461
- * (`rateLimiter`, `budget`, `breaker`) so callers can wire them into
462
- * dashboards, alerts, or `graphLens`.
463
- *
464
- * Fallback is implemented via {@link cascadingLlmAdapter}: when `fallback`
465
- * is provided, the wrapped primary adapter is placed at tier 0 and the
466
- * fallback adapter at tier 1. For N-tier cascades, use `cascadingLlmAdapter`
467
- * directly and wrap each tier with `resilientAdapter`.
468
- *
469
- * @module
470
- */
471
-
472
- /** Options for {@link resilientAdapter}. Every field is optional — omit to skip that layer. */
473
- interface ResilientAdapterOptions {
474
- /** Admission control. See {@link withRateLimiter}. */
475
- rateLimit?: WithRateLimiterOptions;
476
- /** Cost/cap gate. See {@link withBudgetGate}. */
477
- budget?: WithBudgetGateOptions;
478
- /** Circuit breaker. See {@link withBreaker}. */
479
- breaker?: WithBreakerOptions;
480
- /** Per-attempt deadline in milliseconds. Omit to skip the timeout wrap. */
481
- timeoutMs?: number;
482
- /** Retry policy on transient errors. See {@link withRetry}. */
483
- retry?: WithRetryOptions;
484
- /**
485
- * Fallback adapter engaged when the primary (post-retry) fails. Implemented
486
- * via {@link cascadingLlmAdapter} — the primary becomes tier 0, the
487
- * fallback becomes tier 1. For N-tier cascades, use `cascadingLlmAdapter`
488
- * directly and wrap each tier with `resilientAdapter` as needed.
489
- */
490
- fallback?: LLMAdapter;
491
- /** Name used as the primary tier name in the fallback cascade. Default `"primary"`. */
492
- name?: string;
493
- /**
494
- * Called when the cascade switches from one tier to the next after a
495
- * failure. Only fires when `fallback` is set. Threaded directly to the
496
- * inner {@link cascadingLlmAdapter}.
497
- */
498
- onFallback?: (from: string, to: string, error: unknown) => void;
499
- /**
500
- * Called when every tier in the cascade has been exhausted (all failed,
501
- * skipped by filter, or skipped by breaker). Only fires when `fallback`
502
- * is set. Threaded directly to the inner {@link cascadingLlmAdapter}.
503
- */
504
- onExhausted?: (report: CascadeExhaustionReport) => void;
505
- /**
506
- * Content-addressed replay cache wrapped OUTERMOST — a cache HIT short-
507
- * circuits the entire stack (rate-limit / budget / breaker / retry /
508
- * fallback), saving money and latency. Cache MISSes flow through the
509
- * normal stack; the successful result is stored on success. See
510
- * {@link withReplayCache}.
511
- */
512
- cache?: WithReplayCacheOptions;
513
- }
514
- /** Output bundle of {@link resilientAdapter}. */
515
- interface ResilientAdapterBundle {
516
- /** The final hardened adapter. */
517
- adapter: LLMAdapter;
518
- /** Rate-limiter internals (for dashboards). Present only when `opts.rateLimit` was set. */
519
- rateLimiter?: AdaptiveRateLimiterBundle;
520
- /** Budget gate internals (for dashboards). Present only when `opts.budget` was set. */
521
- budget?: BudgetGateBundle;
522
- /** Circuit breaker (for dashboards). Present only when `opts.breaker` was set. */
523
- breaker?: CircuitBreaker;
524
- }
525
- /**
526
- * Wrap `inner` with the standard resilience stack. See module docs for the
527
- * composition order and rationale.
528
- *
529
- * @example
530
- * ```ts
531
- * const { adapter, budget, breaker } = resilientAdapter(openai, {
532
- * rateLimit: { rpm: 60, tpm: 90_000 },
533
- * budget: { caps: { usd: 5 } },
534
- * breaker: { failureThreshold: 5, resetTimeoutMs: 30_000 },
535
- * timeoutMs: 30_000,
536
- * retry: { attempts: 3 },
537
- * fallback: webllm, // cascades to local on exhaustion
538
- * });
539
- *
540
- * // `adapter` is drop-in for anything expecting LLMAdapter.
541
- * // Subscribe to `budget.totals`, `breaker.state`, etc. for dashboards.
542
- * ```
543
- */
544
- declare function resilientAdapter(inner: LLMAdapter, opts?: ResilientAdapterOptions): ResilientAdapterBundle;
545
-
546
- /**
547
- * `withTimeout` — cancel `invoke()` / `stream()` after `ms` elapse.
548
- *
549
- * Wires a child AbortSignal so provider adapters can honor the cancellation
550
- * (all shipped adapters forward `signal` through to their fetch / SDK call).
551
- *
552
- * Uses `ResettableTimer` rather than raw `setTimeout` — same pattern as
553
- * `extra/resilience.ts` (spec §5.10 escape hatch documented on the class).
554
- */
555
-
556
- declare class LLMTimeoutError extends Error {
557
- readonly ms: number;
558
- name: string;
559
- constructor(ms: number);
560
- }
561
- declare function withTimeout(inner: LLMAdapter, ms: number): LLMAdapter;
562
-
563
- /**
564
- * AnthropicAdapter — default fetch-backed, optional SDK-backed.
565
- *
566
- * - `anthropicAdapter({ apiKey })` uses native `fetch` + SSE parsing.
567
- * - `anthropicAdapter({ sdk })` delegates to a user-provided `@anthropic-ai/sdk` instance.
568
- *
569
- * Token usage mapping:
570
- * - `input_tokens` → `input.regular`
571
- * - `cache_read_input_tokens` → `input.cacheRead`
572
- * - `cache_creation.ephemeral_5m_input_tokens` → `input.cacheWrite5m`
573
- * - `cache_creation.ephemeral_1h_input_tokens` → `input.cacheWrite1h`
574
- * - `cache_creation_input_tokens` (legacy) → `input.cacheWrite5m` (default TTL)
575
- * - `output_tokens` → `output.regular`
576
- * - `server_tool_use.web_search_requests` → `auxiliary.webSearchRequests`
577
- */
578
-
579
- interface AnthropicAdapterOptions {
580
- /** API key. Falls back to `process.env.ANTHROPIC_API_KEY` on Node. */
581
- apiKey?: string;
582
- /** Default model (overridable per-call via `LLMInvokeOptions.model`). */
583
- model?: string;
584
- /** Override the base URL. Default `https://api.anthropic.com`. */
585
- baseURL?: string;
586
- /** API version header. Default `"2023-06-01"`. */
587
- anthropicVersion?: string;
588
- /** Additional headers to send on every request (overridden by per-call). */
589
- headers?: Record<string, string>;
590
- /**
591
- * User-provided SDK instance. When present, the adapter delegates to it
592
- * (uses `.messages.create`) instead of native fetch.
593
- * Shape matches `@anthropic-ai/sdk` `.messages` API; any object with a
594
- * compatible `create`/`stream` contract works.
595
- */
596
- sdk?: AnthropicSdkLike;
597
- /** Custom fetch (useful for tests). Default `globalThis.fetch`. */
598
- fetchImpl?: typeof fetch;
599
- }
600
- /** Minimal SDK shape we interoperate with. */
601
- interface AnthropicSdkLike {
602
- messages: {
603
- create(params: Record<string, unknown>, opts?: {
604
- signal?: AbortSignal;
605
- }): Promise<AnthropicMessageResponse>;
606
- stream?(params: Record<string, unknown>, opts?: {
607
- signal?: AbortSignal;
608
- }): AsyncIterable<AnthropicStreamEvent>;
609
- };
610
- }
611
- interface AnthropicMessageResponse {
612
- id: string;
613
- content: ReadonlyArray<{
614
- type: "text";
615
- text: string;
616
- } | {
617
- type: "tool_use";
618
- id: string;
619
- name: string;
620
- input: Record<string, unknown>;
621
- } | {
622
- type: "thinking";
623
- thinking: string;
624
- } | {
625
- type: string;
626
- [key: string]: unknown;
627
- }>;
628
- stop_reason?: string;
629
- usage: AnthropicUsage;
630
- model?: string;
631
- }
632
- interface AnthropicUsage {
633
- input_tokens?: number;
634
- output_tokens?: number;
635
- cache_read_input_tokens?: number;
636
- cache_creation_input_tokens?: number;
637
- cache_creation?: {
638
- ephemeral_5m_input_tokens?: number;
639
- ephemeral_1h_input_tokens?: number;
640
- };
641
- server_tool_use?: {
642
- web_search_requests?: number;
643
- };
644
- }
645
- type AnthropicStreamEvent = {
646
- type: "message_start";
647
- message: {
648
- usage: AnthropicUsage;
649
- };
650
- } | {
651
- type: "content_block_start";
652
- index: number;
653
- content_block: Record<string, unknown>;
654
- } | {
655
- type: "content_block_delta";
656
- index: number;
657
- delta: Record<string, unknown>;
658
- } | {
659
- type: "content_block_stop";
660
- index: number;
661
- } | {
662
- type: "message_delta";
663
- delta: {
664
- stop_reason?: string;
665
- usage?: AnthropicUsage;
666
- };
667
- } | {
668
- type: "message_stop";
669
- } | {
670
- type: string;
671
- [key: string]: unknown;
672
- };
673
- declare function anthropicAdapter(opts?: AnthropicAdapterOptions): LLMAdapter;
674
-
675
- /**
676
- * DryRunAdapter — zero-cost mock provider.
677
- *
678
- * Returns a deterministic fake response (plus a configurable hook for
679
- * customization). Useful for: pipeline smoke tests, CI without API keys,
680
- * local development, and as the leaf of a `cascadingLlmAdapter` when every
681
- * real tier fails.
682
- *
683
- * The library ships a minimal implementation only — richer scenario-
684
- * scripted mocks (per-stage responses, call recording) belong at the test
685
- * harness layer, not in the shipped library.
686
- *
687
- * Uses `ResettableTimer` for simulated latency (spec §5.10 escape hatch
688
- * documented on the class), and throws an `AbortError`-named Error on
689
- * abort so retry/timeout middleware can classify it.
690
- */
691
-
692
- interface DryRunAdapterOptions {
693
- provider?: string;
694
- model?: string;
695
- /** Generate the fake response. Defaults to echoing the last user message. */
696
- respond?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => string;
697
- /**
698
- * Generate a fake usage object. Defaults to a simple character-count
699
- * heuristic (`input = sum(messages) / 4`, `output = content / 4`).
700
- */
701
- usage?: (messages: readonly ChatMessage[], content: string) => TokenUsage;
702
- /** Simulated latency in milliseconds (applied to both invoke and stream). */
703
- latencyMs?: number;
704
- /** Stream chunk size in characters. Default 16. */
705
- streamChunkSize?: number;
706
- }
707
- /**
708
- * Create a DryRun adapter.
709
- *
710
- * @example
711
- * ```ts
712
- * const adapter = dryRunAdapter({ respond: (msgs) => "hello from dry-run" });
713
- * const resp = await Promise.resolve(adapter.invoke([{ role: "user", content: "hi" }]));
714
- * ```
715
- */
716
- declare function dryRunAdapter(opts?: DryRunAdapterOptions): LLMAdapter;
717
-
718
- /**
719
- * GoogleAdapter — default fetch-backed, optional SDK-backed.
720
- *
721
- * The SDK-backed path targets the `@google/genai` SDK shape:
722
- * `client.models.generateContent({ model, contents, config })` — single
723
- * param, with generation params and `abortSignal` under `config`. The
724
- * legacy `@google/generative-ai` two-arg `(params, {signal})` shape is no
725
- * longer accepted; pass a `GoogleGenAI` instance via `opts.sdk`.
726
- *
727
- * Maps Gemini `usageMetadata`:
728
- * - `promptTokenCount` minus `cachedContentTokenCount` → `input.regular`
729
- * - `cachedContentTokenCount` → `input.cacheRead`
730
- * - `candidatesTokenCount` → `output.regular`
731
- * - `thoughtsTokenCount` → `output.reasoning`
732
- * - `toolUsePromptTokenCount` → `input.toolUse`
733
- * - `promptTokensDetails[]` → `input.{image,audio,video}` per modality
734
- */
735
-
736
- interface GoogleAdapterOptions {
737
- /** API key. Falls back to `process.env.GOOGLE_API_KEY` / `GEMINI_API_KEY` on Node. */
738
- apiKey?: string;
739
- model?: string;
740
- baseURL?: string;
741
- /** Extra headers on every request. */
742
- headers?: Record<string, string>;
743
- /**
744
- * Optional `@google/genai` SDK instance (e.g. `new GoogleGenAI({apiKey})`).
745
- * When omitted, the adapter uses the fetch-backed path against the
746
- * Generative Language REST API.
747
- */
748
- sdk?: GoogleSdkLike;
749
- fetchImpl?: typeof fetch;
750
- }
751
- /**
752
- * Duck-type matching the `@google/genai` (`GoogleGenAI`) SDK shape:
753
- * single-param `generateContent({ model, contents, config })` where
754
- * generation parameters and `abortSignal` live under `config`.
755
- *
756
- * The `@google/generative-ai` predecessor's two-arg `(params, {signal})`
757
- * shape is no longer accepted.
758
- */
759
- interface GoogleSdkLike {
760
- models: {
761
- generateContent(params: GoogleSdkRequestParams): Promise<GeminiResponse>;
762
- generateContentStream?(params: GoogleSdkRequestParams): Promise<AsyncIterable<GeminiResponse>> | AsyncIterable<GeminiResponse>;
763
- };
764
- }
765
- /** Single-param request shape consumed by `@google/genai`'s `models.generateContent`. */
766
- interface GoogleSdkRequestParams {
767
- model: string;
768
- contents: unknown;
769
- config?: GoogleSdkRequestConfig;
770
- }
771
- /**
772
- * Generation config under the new SDK. `abortSignal` is the cancellation
773
- * channel — there is no second-arg `{signal}`.
774
- */
775
- interface GoogleSdkRequestConfig {
776
- abortSignal?: AbortSignal;
777
- temperature?: number;
778
- maxOutputTokens?: number;
779
- systemInstruction?: unknown;
780
- tools?: unknown;
781
- thinkingConfig?: unknown;
782
- [extra: string]: unknown;
783
- }
784
- interface GeminiResponse {
785
- candidates?: ReadonlyArray<{
786
- content?: {
787
- role?: string;
788
- parts?: ReadonlyArray<{
789
- text?: string;
790
- thought?: boolean;
791
- functionCall?: {
792
- name: string;
793
- args: Record<string, unknown>;
794
- };
795
- }>;
796
- };
797
- finishReason?: string;
798
- }>;
799
- usageMetadata?: GeminiUsage;
800
- modelVersion?: string;
801
- }
802
- interface GeminiUsage {
803
- promptTokenCount?: number;
804
- candidatesTokenCount?: number;
805
- totalTokenCount?: number;
806
- thoughtsTokenCount?: number;
807
- cachedContentTokenCount?: number;
808
- toolUsePromptTokenCount?: number;
809
- promptTokensDetails?: ReadonlyArray<{
810
- modality: string;
811
- tokenCount: number;
812
- }>;
813
- candidatesTokensDetails?: ReadonlyArray<{
814
- modality: string;
815
- tokenCount: number;
816
- }>;
817
- cacheTokensDetails?: ReadonlyArray<{
818
- modality: string;
819
- tokenCount: number;
820
- }>;
821
- }
822
- declare function googleAdapter(opts?: GoogleAdapterOptions): LLMAdapter;
823
-
824
- /**
825
- * `frozenContext` — prefix-cache-friendly snapshot of upstream context.
826
- *
827
- * @module
828
- */
829
-
830
- type FrozenContextOptions = {
831
- /**
832
- * Reactive signal that triggers re-materialization. Each `DATA` emission
833
- * from this node re-reads the source and refreshes the frozen value.
834
- * Typical shapes: `fromTimer(ms)` for periodic refresh, a stage-transition
835
- * node for event-driven refresh, or a manual `state<number>` the caller
836
- * increments via `setState(n + 1)`.
837
- *
838
- * When omitted, the frozen value is materialized exactly once (on first
839
- * subscribe) and never refreshes for the lifetime of the activation —
840
- * use this for session-start snapshots that must stay stable. The
841
- * single-shot latch IS reset on `INVALIDATE` (graph-wide flush via
842
- * `graph.signal([[INVALIDATE]])`), so callers who need an "evict and
843
- * re-materialize" escape hatch get one through the standard graph
844
- * lifecycle without having to wire a `refreshTrigger`.
845
- */
846
- refreshTrigger?: NodeInput<unknown>;
847
- name?: string;
848
- };
849
- /**
850
- * Freeze a reactive source into a stable snapshot that only re-materializes
851
- * on explicit trigger. Built for long-running harness loops where system
852
- * prompts include `agentMemory` / stage context — every reactive change to
853
- * the source invalidates the LLM provider's prefix cache, so re-rendering
854
- * the prompt every turn is expensive.
855
- *
856
- * `frozenContext(source)` reads the source once and caches the value;
857
- * downstream `promptNode` compositions see a stable reference until the
858
- * optional `refreshTrigger` fires.
859
- *
860
- * Trade-off: slightly stale context vs. prefix cache hit rate. For most
861
- * harness apps, the memory snapshot at session start is "good enough" —
862
- * refreshing on a coarse-grained trigger (`fromCron("*\/30min")`, stage
863
- * transition) preserves 90%+ prefix cache hits while keeping context useful.
864
- *
865
- * @example
866
- * ```ts
867
- * // Freeze agent memory for the duration of a stage.
868
- * const frozen = frozenContext(memory.context, {
869
- * refreshTrigger: stage, // re-materialize on stage change
870
- * });
871
- * const reply = promptNode({ context: frozen, ... });
872
- * ```
873
- *
874
- * @category patterns.ai
875
- */
876
- declare function frozenContext<T>(source: NodeInput<T>, opts?: FrozenContextOptions): Node<T | null>;
877
-
878
- /** Options accepted by {@link promptCall}, {@link llmExtractor}, and {@link llmConsolidator}. */
879
- type PromptCallOptions = {
880
- adapter: LLMAdapter;
881
- model?: string;
882
- temperature?: number;
883
- maxTokens?: number;
884
- /**
885
- * Optional name forwarded to the underlying `promptNode` (used as the
886
- * `<name>::messages` / `<name>::call` / `<name>::output` path prefix).
887
- * Defaults differ per call site so multiple `promptCall`s wired into the
888
- * same graph don't collide on `prompt_node::output`.
889
- */
890
- name?: string;
891
- };
892
- /**
893
- * Build a one-shot LLM JSON-call factory: each invocation wraps `input` in a
894
- * fresh `state(input)`, delegates to `promptNode({format: "json"})`, and
895
- * returns a `NodeInput<TOut>` that the caller plugs into `distill` /
896
- * `agentLoop` / any reactive composition that accepts `NodeInput`.
897
- *
898
- * **Per-call lifecycle.** The returned `NodeInput<TOut>` is a producer that
899
- * emits exactly one `DATA` per upstream input (per Tier 1.2 Session C lock —
900
- * `promptNode` guarantees one DATA per wave). When the consumer's switchMap
901
- * supersedes it, the per-call `state(input)` and the inner `prompt_node::call`
902
- * tear down together.
903
- *
904
- * @param systemPrompt - System message sent on every call.
905
- * @param buildUserContent - Per-input user-content builder (must be JSON-stringifiable).
906
- * @param opts - Adapter + model/temperature/maxTokens + optional name prefix.
907
- * @param defaultName - Path-prefix fallback when `opts.name` is omitted.
908
- * @returns Factory `(input: TIn) => NodeInput<TOut>`.
909
- *
910
- * @category patterns
911
- */
912
- declare function promptCall<TIn, TOut>(systemPrompt: string, buildUserContent: (input: TIn) => string, opts: PromptCallOptions, defaultName: string): (input: TIn) => NodeInput<TOut>;
913
- /** Options accepted by {@link llmExtractor} and {@link llmConsolidator}. */
914
- type LLMExtractorOptions = PromptCallOptions & {
915
- /**
916
- * Cap the dedup-hint slice of `existingKeys` passed to the LLM. Larger
917
- * stores ship more keys (better dedup recall) at the cost of prompt size.
918
- * Default 100. Set to `Infinity` to forward every key.
919
- */
920
- maxExistingKeys?: number;
921
- };
922
- /** Alias for backward compatibility. */
923
- type LLMConsolidatorOptions = LLMExtractorOptions;
924
- /**
925
- * Returns an `extractFn` callback for `distill()` that invokes an LLM to
926
- * extract structured memories from raw input.
927
- *
928
- * The system prompt should instruct the LLM to return JSON matching
929
- * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.
930
- *
931
- * Built on `promptNode({format: "json"})` — inherits markdown-fence stripping
932
- * and content-preview parse errors. Stack `withRetry` on the adapter for
933
- * transient-error tolerance (see `patterns/ai/adapters/middleware/retry.ts`).
934
- */
935
- declare function llmExtractor<TRaw, TMem>(systemPrompt: string, opts: LLMExtractorOptions): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
936
- /**
937
- * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to
938
- * cluster and merge related memories.
939
- */
940
- declare function llmConsolidator<TMem>(systemPrompt: string, opts: LLMConsolidatorOptions): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
941
-
942
- /**
943
- * `promptNode` — universal LLM transform as a reactive derived node.
944
- *
945
- * The shape: `deps → messagesNode (derived) → switchMap → call (producer) → output`.
946
- * Each upstream wave is one LLM call; superseding waves cancel the in-flight
947
- * call via the abort signal threaded through `nodeSignal(opts.abort)`.
948
- *
949
- * The producer-shape on the inner is load-bearing: it emits exactly one DATA
950
- * + COMPLETE per wave, so the outer switchMap sees one DATA per wave (matches
951
- * the `HarnessExecutor` contract). A `derived([call], parse)` would have its
952
- * own first-run / push-on-subscribe semantics that can leak a transient null
953
- * before the real response arrives — observed and reverted in an earlier
954
- * attempt; see SESSION-ai-harness-module-review.md line 3654 for context.
955
- * Locked as path (b) producer-based by Session C (2026-04-27).
956
- *
957
- * **Retry / replay-cache.** Stack middleware on the adapter:
958
- *
959
- * ```ts
960
- * import { withRetry, withReplayCache } from "@graphrefly/graphrefly/patterns/ai";
961
- *
962
- * const adapter = withRetry(
963
- * withReplayCache(baseAdapter, { keyFn: (ctx) => ctx.messages[0].content }),
964
- * { count: 3, backoff: 200 },
965
- * );
966
- * const result = promptNode(adapter, [input], (q) => q);
967
- * ```
968
- *
969
- * `promptNode` no longer ships `retries` / `cache` options — they duplicated
970
- * middleware already at the adapter layer.
971
- *
972
- * **Cross-wave cache (COMPOSITION-GUIDE §32).** The switchMap output cache
973
- * survives across new outer DATAs — `promptNode`'s cached value persists
974
- * until the next wave fully resolves. Consumers that need to distinguish
975
- * "fresh value for THIS session" from "stale cache from a prior session"
976
- * (e.g. `agentLoop` resetting on new `run()`) must add a `state()` mirror
977
- * at their session boundary and depend on the mirror, not the `promptNode`
978
- * output directly. `promptNode` itself stays primitive — it does not
979
- * embed a state-mirror.
980
- *
981
- * @module
982
- */
983
-
984
- type PromptNodeOptions = {
985
- name?: string;
986
- model?: string;
987
- temperature?: number;
988
- maxTokens?: number;
989
- /**
990
- * Output format:
991
- * - `"text"` (default) — emit the response content as a string.
992
- * - `"json"` — `JSON.parse` the content (markdown fences stripped).
993
- * - `"raw"` — emit the full {@link LLMResponse} object (subsumes the
994
- * pre-Tier-2.3 `fromLLM` shape; use this when you need `usage` /
995
- * `toolCalls` / `finishReason` alongside `content`).
996
- */
997
- format?: "text" | "json" | "raw";
998
- /**
999
- * Reactive tool definitions forwarded to the adapter. Pair with
1000
- * `format: "raw"` (or read `toolCalls` from a downstream parser) when
1001
- * tool-calling is in scope.
1002
- *
1003
- * **Reactive declared edge** (DF12, Tier 7): `tools` is a `Node` so the
1004
- * tools list participates in `describe()` topology and `explain()` causal
1005
- * chains. The tools Node is added to `messagesNode`'s declared deps —
1006
- * tools changes re-invoke the LLM (treated as a new call envelope).
1007
- * Wrap with `distinctUntilChanged` upstream if your tool selector emits
1008
- * noisy duplicates that would otherwise spam the adapter. See
1009
- * COMPOSITION-GUIDE §31 (Dynamic tool selection) for the canonical
1010
- * `toolSelector` pattern that produces this Node.
1011
- *
1012
- * **Activation note:** since `tools` is a real declared dep, `messagesNode`
1013
- * waits for the tools Node to DATA at least once before firing
1014
- * (push-on-subscribe SENTINEL gate). Pass a `state<ToolDefinition[]>([])`
1015
- * if you want immediate activation with no tools, or the latest published
1016
- * `toolSelector.tools` Node.
1017
- */
1018
- tools?: Node<readonly ToolDefinition[]>;
1019
- /**
1020
- * Optional system prompt. Forwarded via `opts.systemPrompt` to the adapter
1021
- * only — never pushed as a `{role:"system"}` message (avoiding the
1022
- * double-send class of bug where adapters that normalize both shapes end
1023
- * up with two system entries).
1024
- */
1025
- systemPrompt?: string;
1026
- /**
1027
- * Optional reactive abort signal. When the node emits `true`, the in-flight
1028
- * `adapter.invoke()` call is cancelled via `AbortController.abort()`.
1029
- * Threaded through `nodeSignal(abort)` — a one-shot bridge. Useful inside
1030
- * agent state machines where a separate `aborted` state should cancel the
1031
- * current LLM call without superseding via switchMap.
1032
- */
1033
- abort?: Node<boolean>;
1034
- meta?: Record<string, unknown>;
1035
- };
1036
- /**
1037
- * Universal LLM transform: wraps a prompt template + model adapter into a reactive derived node.
1038
- * Re-invokes the LLM whenever any dep changes. Suitable for triage, QA, hypothesis, parity, etc.
1039
- *
1040
- * **Topology** (visible in `describe()`):
1041
- * ```
1042
- * <deps...>, [tools?] → <name>::messages (derived, meta.ai = prompt_node)
1043
- * <name>::messages → <name>::output (switchMap product, meta.ai = prompt_node::output)
1044
- * per-wave inner: <name>::call (producer, meta.ai = prompt_node::call)
1045
- * ```
1046
- * When `opts.tools` is supplied, the tools `Node` is appended to
1047
- * `messagesNode`'s declared deps so it appears as a real edge in `describe()`
1048
- * / `explain()` (DF12, Tier 7).
1049
- *
1050
- * **No-input semantics** (matches the codebase-wide SENTINEL convention):
1051
- * - **Initial no-input** (no real input has ever arrived) — emits nothing.
1052
- * Outer cache stays `undefined`; `subscribe` consumers see no DATA event.
1053
- * Use this to keep downstream gating clean: a `withLatestFrom`-paired
1054
- * trigger won't fire until the LLM has actually produced something.
1055
- * - **Mid-flow no-input** (input dropped to nullish after at least one
1056
- * real LLM call) — emits `null` as a domain "input went away" signal.
1057
- * Downstream consumers can distinguish "haven't started" from "input
1058
- * gone."
1059
- *
1060
- * **Retries / caching:** stack `withRetry` / `withReplayCache` middleware on the
1061
- * `adapter` argument — `promptNode` no longer ships its own duplicated retry /
1062
- * cache loops (pre-1.0 cleanup, see review session 1).
1063
- *
1064
- * @param adapter - LLM adapter (provider-agnostic). Wrap with `withRetry` /
1065
- * `withReplayCache` middleware for transient-error tolerance
1066
- * or replay caching.
1067
- * @param deps - Input nodes whose values feed the prompt.
1068
- * @param prompt - Static string or template function receiving dep values.
1069
- * @param opts - Optional configuration.
1070
- * @returns `Node` emitting LLM responses (string or parsed JSON).
1071
- */
1072
- declare function promptNode(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts: PromptNodeOptions & {
1073
- format: "raw";
1074
- }): Node<LLMResponse | null>;
1075
- declare function promptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: Omit<PromptNodeOptions, "format"> & {
1076
- format?: "text" | "json";
1077
- }): Node<T | null>;
1078
-
1079
- /**
1080
- * `streamingPromptNode` + `gatedStream` — streaming LLM transforms.
1081
- *
1082
- * **Wave A Unit 2 rewrite:**
1083
- * - `StreamChunk` retired. The live stream surface is now `deltaTopic:
1084
- * TopicGraph<StreamDelta & {seq, ts}>` — every adapter delta (token,
1085
- * thinking, tool-call, usage, finish) is published in order. The previous
1086
- * shape retained the accumulated text per-chunk, producing O(N²) memory;
1087
- * the new shape stores only per-delta payloads (O(N)).
1088
- * - New `accumulatedText: Node<string>` on the bundle — lazy-built via
1089
- * `ctx.store` over token-type deltas. Text-only extractors (`streamExtractor`,
1090
- * `keywordFlagExtractor`, `toolCallExtractor`) consume this node.
1091
- * - `retainedLimit?: number` option exposed for the delta topic (no default —
1092
- * session scale is domain-specific per Unit 2 Q2).
1093
- * - Unconditional `keepalive(output)` removed — callers subscribe as needed.
1094
- * - System-prompt double-send fixed (matches promptNode Unit 1 fix).
1095
- * - `format: "json"` throws on parse error with a content-preview diagnostic
1096
- * (parity with `promptNode`).
1097
- * - Shared body between `streamingPromptNode` and `gatedStream` extracted
1098
- * into `streamingInvoke` per Unit 2 locked scope.
1099
- *
1100
- * @module
1101
- */
1102
-
1103
- /**
1104
- * A single delta published to the `deltaTopic`. Every adapter emission is
1105
- * forwarded — not just token deltas — so consumers see the full event log
1106
- * (thinking, tool-call-delta, usage, finish).
1107
- */
1108
- type StampedDelta = StreamDelta & {
1109
- /** Monotonic per-stream counter starting at 0. */
1110
- readonly seq: number;
1111
- /** Wall-clock nanoseconds at publish time (spec §5.11 central timer). */
1112
- readonly ts: number;
1113
- };
1114
- type StreamingPromptNodeOptions = {
1115
- name?: string;
1116
- model?: string;
1117
- temperature?: number;
1118
- maxTokens?: number;
1119
- /** Output format — `"json"` attempts JSON.parse on accumulated text. Throws on parse failure. Default: `"text"`. */
1120
- format?: "text" | "json";
1121
- systemPrompt?: string;
1122
- meta?: Record<string, unknown>;
1123
- /**
1124
- * Optional retention cap on the delta topic. Omit for unbounded retention
1125
- * (the topic grows until `dispose()`). Recommended values: `8_192` for
1126
- * single-shot 8K-token responses, `1_000_000` for persistent session
1127
- * topics, or explicit `dispose()` for worker-pool patterns.
1128
- */
1129
- retainedLimit?: number;
1130
- };
1131
- /**
1132
- * Bundle returned by {@link streamingPromptNode}.
1133
- */
1134
- type StreamingPromptNodeHandle<T> = {
1135
- /** Final parsed result (emits once per invocation, after stream completes). */
1136
- output: Node<T | null>;
1137
- /** Live delta topic — every adapter delta in order, stamped with `seq` + `ts`. */
1138
- deltaTopic: TopicGraph<StampedDelta>;
1139
- /**
1140
- * Reactive accumulated-text view — lazy-built over `deltaTopic.latest`
1141
- * filtered on `type === "token"`. Text-only extractors compose on this.
1142
- * Emits the empty string before any token arrives.
1143
- */
1144
- accumulatedText: Node<string>;
1145
- /** Tear down the delta topic and release resources. */
1146
- dispose: () => void;
1147
- };
1148
- /**
1149
- * Streaming LLM transform: wraps a prompt template + adapter into a reactive
1150
- * streaming pipeline. Re-invokes the LLM whenever any dep changes; the
1151
- * previous in-flight stream is canceled automatically via `switchMap`.
1152
- *
1153
- * Every adapter delta is published to `deltaTopic` stamped with `seq` + `ts`.
1154
- * Text consumers subscribe to `accumulatedText` (auto-maintained). Delta-
1155
- * specific consumers (`costMeterExtractor` on `usage` deltas) subscribe to
1156
- * `deltaTopic` directly and filter by `delta.type`.
1157
- *
1158
- * The async boundary is handled by `fromAny(asyncGenerator)` (spec §5.10).
1159
- */
1160
- declare function streamingPromptNode<T = string>(adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: StreamingPromptNodeOptions): StreamingPromptNodeHandle<T>;
1161
- type GatedStreamOptions = StreamingPromptNodeOptions & {
1162
- /** Gate options (maxPending, startOpen). */
1163
- gate?: Omit<GateOptions, "meta">;
1164
- };
1165
- /**
1166
- * Bundle returned by {@link gatedStream}.
1167
- */
1168
- type GatedStreamHandle<T> = {
1169
- /** Final parsed result (after gate approval). */
1170
- output: Node<T | null>;
1171
- /** Live delta topic — every adapter delta in order, stamped with `seq` + `ts`. */
1172
- deltaTopic: TopicGraph<StampedDelta>;
1173
- /** Reactive accumulated-text view. */
1174
- accumulatedText: Node<string>;
1175
- /**
1176
- * Gate controller — approve, reject (aborts in-flight stream), modify.
1177
- * The gate's DATA domain is `T` (not `T | null`): the pre-gate `filter`
1178
- * drops nulls, so the pending queue never holds a null. The controller's
1179
- * `node` output type stays `T | null` only because `gate.approve()` on an
1180
- * empty queue would surface `null` — callers should treat `null` as "no
1181
- * value" rather than as a modeled null signal.
1182
- */
1183
- gate: GateController<T>;
1184
- /** Tear down the delta topic + gate keepalive. */
1185
- dispose: () => void;
1186
- };
1187
- /**
1188
- * Streaming LLM transform with human-in-the-loop gate integration.
1189
- *
1190
- * Composes {@link streamingPromptNode} with `gate` so that:
1191
- * - `gate.reject()` discards the pending value **and** aborts the in-flight
1192
- * stream (toggles an internal cancel signal → switchMap restart → abort).
1193
- * - `gate.modify()` transforms the pending value before forwarding downstream.
1194
- * - `gate.approve()` forwards the final result as normal.
1195
- *
1196
- * Wave A Unit 2 defers full `gatedStream` review to Wave B Unit 17 (the
1197
- * `gate()` primitive itself is reviewed there). This implementation retains
1198
- * the existing gate API while adopting the Unit 2 delta-topic shape.
1199
- */
1200
- declare function gatedStream<T = string>(graph: Graph, name: string, adapter: LLMAdapter, deps: readonly Node<unknown>[], prompt: string | ((...depValues: unknown[]) => string), opts?: GatedStreamOptions): GatedStreamHandle<T>;
1201
-
1202
- /**
1203
- * `systemPromptBuilder` — assembles a reactive system prompt from sections.
1204
- *
1205
- * @module
1206
- */
1207
-
1208
- /**
1209
- * Assembles a system prompt from reactive sections. Each section is a
1210
- * `NodeInput<string>` — the prompt updates when any section changes.
1211
- */
1212
- type SystemPromptHandle = Node<string> & {
1213
- dispose: () => void;
1214
- };
1215
- declare function systemPromptBuilder(sections: readonly NodeInput<string>[], opts?: {
1216
- separator?: string;
1217
- name?: string;
1218
- }): SystemPromptHandle;
1219
-
1220
- /**
1221
- * Cost meter extractor — derives live cost readings from the delta topic.
1222
- *
1223
- * **Wave A Unit 3 rewrite:** signature takes `deltaTopic: TopicGraph<StampedDelta>`
1224
- * instead of the old `TopicGraph<StreamChunk>`. The meter prefers real
1225
- * `usage` deltas from the adapter; when no `usage` has been seen yet it
1226
- * falls back to a char-based estimate over token deltas and stamps
1227
- * `estimated: true` on the reading. Chunk count is the count of
1228
- * token-type deltas seen (was `chunk.index + 1`).
1229
- *
1230
- * @module
1231
- */
1232
-
1233
- /** A cost meter reading from the stream. */
1234
- type CostMeterReading = {
1235
- readonly chunkCount: number;
1236
- readonly charCount: number;
1237
- readonly estimatedTokens: number;
1238
- /**
1239
- * `true` when no adapter `usage` delta has been observed yet —
1240
- * `estimatedTokens` is a char-based heuristic and should be treated as an
1241
- * approximation. Flips to `false` once a real `usage` delta arrives.
1242
- */
1243
- readonly estimated: boolean;
1244
- };
1245
- type CostMeterOptions = {
1246
- /** Characters per token approximation. Default: 4 (GPT-family). */
1247
- charsPerToken?: number;
1248
- name?: string;
1249
- };
1250
- /**
1251
- * Mounts a cost meter on the delta topic. Prefers real `usage` deltas from
1252
- * the provider; falls back to char-based estimation on token deltas alone
1253
- * (with `meta.estimated: true` on the reading).
1254
- *
1255
- * Default structural equals suppresses DATA emission when two consecutive
1256
- * readings are identical.
1257
- */
1258
- declare function costMeterExtractor(deltaTopic: TopicGraph<StampedDelta>, opts?: CostMeterOptions): Node<CostMeterReading>;
1259
-
1260
- /**
1261
- * Keyword-flag extractor — scans accumulated stream text for configured patterns.
1262
- * @module
1263
- */
1264
-
1265
- /** A keyword match detected in the stream. */
1266
- type KeywordFlag = {
1267
- readonly label: string;
1268
- readonly pattern: RegExp;
1269
- readonly match: string;
1270
- readonly position: number;
1271
- };
1272
- type KeywordFlagExtractorOptions = {
1273
- patterns: readonly {
1274
- pattern: RegExp;
1275
- label: string;
1276
- }[];
1277
- name?: string;
1278
- /**
1279
- * Maximum length of any pattern's literal text. Used as an overlap window
1280
- * when cursoring through the accumulated stream so matches that span
1281
- * chunk boundaries aren't missed. Default: 128.
1282
- */
1283
- maxPatternLength?: number;
1284
- };
1285
- /**
1286
- * Mounts a keyword-flag extractor on accumulated text. Scans for all
1287
- * configured patterns and emits an array of matches.
1288
- *
1289
- * **Wave A Unit 3 rewrite:** signature takes `accumulatedText: Node<string>`
1290
- * instead of the old `TopicGraph<StreamChunk>`. Patterns are compiled once
1291
- * at factory time (was per-chunk). `maxPatternLength` is validated at
1292
- * factory time — any pattern whose source exceeds the window throws
1293
- * immediately.
1294
- *
1295
- * Use cases: design invariant violations (`setTimeout`, `EventEmitter`), PII
1296
- * detection (SSN, email, phone), toxicity keywords, off-track reasoning.
1297
- *
1298
- * **Streaming optimization.** Maintains a cursor across waves in `ctx.store`
1299
- * so each emission scans only the delta region `accumulated.slice(scannedTo -
1300
- * maxPatternLength)` — not the full string. Reactivation clears `ctx.store`
1301
- * and resumes from offset 0 (COMPOSITION-GUIDE §20 RAM semantics).
1302
- *
1303
- * Default structural equals suppresses DATA emission when no new flags were
1304
- * found this wave.
1305
- */
1306
- declare function keywordFlagExtractor(accumulatedText: Node<string>, opts: KeywordFlagExtractorOptions): Node<readonly KeywordFlag[]>;
1307
-
1308
- /**
1309
- * Generic stream extractor — mounts an extract function on accumulated text.
1310
- *
1311
- * **Wave A Unit 3 rewrite:** signature changed from
1312
- * `streamExtractor(topic: TopicGraph<StreamChunk>, fn)` to
1313
- * `streamExtractor(accumulatedText: Node<string>, fn)`. The Unit 2 delta-
1314
- * topic redesign removed the per-chunk `accumulated` field; callers pass
1315
- * `streamingPromptNode(...).accumulatedText` (or any other `Node<string>`
1316
- * source of accumulated text). Source-agnostic — the extractor doesn't care
1317
- * whether the text came from an LLM, WebSocket, SSE tail, or file reader.
1318
- *
1319
- * @module
1320
- */
1321
-
1322
- /**
1323
- * Mounts an extractor function on a reactive accumulated-text source. Returns
1324
- * a derived node that emits extracted values as the text grows.
1325
- *
1326
- * @param accumulatedText - Reactive `Node<string>` of accumulated text.
1327
- * @param extractFn - `(accumulated: string) => T | null`.
1328
- * @param opts - Optional name + structural equals.
1329
- * @returns Derived node emitting extracted values.
1330
- */
1331
- declare function streamExtractor<T>(accumulatedText: Node<string>, extractFn: (accumulated: string) => T | null, opts?: {
1332
- name?: string;
1333
- /**
1334
- * Optional structural equals for the extractor output. When two
1335
- * consecutive chunks produce structurally-equal outputs, the framework
1336
- * emits `RESOLVED` instead of `DATA`, saving downstream work. Default:
1337
- * reference equality (`Object.is`). The library cannot know your
1338
- * output shape — supply this when your `extractFn` returns structured
1339
- * objects or arrays.
1340
- */
1341
- equals?: (a: T | null, b: T | null) => boolean;
1342
- }): Node<T | null>;
1343
-
1344
- /**
1345
- * Tool-call extractor — scans accumulated stream text for complete JSON tool call objects.
1346
- * @module
1347
- */
1348
-
1349
- /** A tool call detected in the stream. */
1350
- type ExtractedToolCall = {
1351
- readonly name: string;
1352
- readonly arguments: Record<string, unknown>;
1353
- readonly raw: string;
1354
- readonly startIndex: number;
1355
- };
1356
- /**
1357
- * Mounts a tool-call extractor on a streaming topic. Scans accumulated text
1358
- * for complete JSON objects containing `"name"` and `"arguments"` keys (the
1359
- * standard tool_call shape). Partial JSON is ignored until the closing brace.
1360
- *
1361
- * Feeds into the tool interception chain for reactive tool gating mid-stream.
1362
- *
1363
- * **Streaming optimization.** Maintains a cursor (`scanFrom`) in `ctx.store`
1364
- * so each chunk resumes brace-scanning from the position after the last
1365
- * complete parse (or the last incomplete open brace). Already-parsed objects
1366
- * are not re-parsed. Default structural equals suppresses DATA emission when
1367
- * no new tool call completed this chunk.
1368
- */
1369
- declare function toolCallExtractor(accumulatedText: Node<string>, opts?: {
1370
- name?: string;
1371
- }): Node<readonly ExtractedToolCall[]>;
1372
-
1373
- /**
1374
- * Content gate — classifies accumulated stream text as allow / review / block.
1375
- * @module
1376
- */
1377
-
1378
- /** Content safety decision. */
1379
- type ContentDecision = "allow" | "block" | "review";
1380
- /** Options for {@link contentGate}. */
1381
- type ContentGateOptions = {
1382
- /**
1383
- * Hard-block threshold multiplier (default 1.5).
1384
- * Scores above `threshold * hardMultiplier` emit `"block"`.
1385
- * Scores between `threshold` and that emit `"review"`.
1386
- */
1387
- hardMultiplier?: number;
1388
- name?: string;
1389
- };
1390
- /**
1391
- * Derived node that classifies accumulated stream text as `"allow"`,
1392
- * `"review"`, or `"block"` based on a classifier score.
1393
- *
1394
- * **Wave A Unit 3 rewrite:** signature now takes `accumulatedText: Node<string>`
1395
- * instead of a `TopicGraph<StreamChunk>` (the `StreamChunk` shape was retired
1396
- * when the delta topic replaced the per-chunk accumulated-text shape).
1397
- *
1398
- * Emits a three-way decision on every text change:
1399
- * - `"allow"` — score below `threshold`
1400
- * - `"review"` — score in `[threshold, threshold × hardMultiplier)`
1401
- * - `"block"` — score at or above `threshold × hardMultiplier`
1402
- *
1403
- * @param accumulatedText - Reactive accumulated-text source
1404
- * (`streamingPromptNode(...).accumulatedText`).
1405
- * @param classifier - `(accumulated: string) => number` scoring function, or
1406
- * a `Node<number>` for live scores.
1407
- * @param threshold - Score at which output becomes `"review"` or `"block"`.
1408
- */
1409
- declare function contentGate(accumulatedText: Node<string>, classifier: ((accumulated: string) => number) | Node<number>, threshold: number, opts?: ContentGateOptions): Node<ContentDecision>;
1410
-
1411
- /**
1412
- * Redactor — stream extractor that replaces matched patterns in accumulated text.
1413
- *
1414
- * **Wave A Unit 3 rewrite:** signature now takes `accumulatedText: Node<string>`
1415
- * instead of the retired `TopicGraph<StreamChunk>`. The output is a
1416
- * `Node<string>` carrying the sanitized accumulated text — compose with
1417
- * `contentGate` or downstream UI directly.
1418
- *
1419
- * @module
1420
- */
1421
-
1422
- /** Options for {@link redactor}. */
1423
- type RedactorOptions = {
1424
- name?: string;
1425
- };
1426
- /**
1427
- * Derived node that replaces matched patterns in accumulated text.
1428
- *
1429
- * @param accumulatedText - Reactive accumulated-text source.
1430
- * @param patterns - Array of RegExps to match against the text.
1431
- * @param replaceFn - Replacement producer (default: always `"[REDACTED]"`).
1432
- * @returns `Node<string>` emitting the sanitized accumulated text.
1433
- */
1434
- declare function redactor(accumulatedText: Node<string>, patterns: RegExp[], replaceFn?: (match: string, pattern: RegExp) => string, opts?: RedactorOptions): Node<string>;
1435
-
1436
- type ChatStreamOptions = {
1437
- graph?: GraphOptions;
1438
- maxMessages?: number;
1439
- };
1440
- declare class ChatStreamGraph extends Graph {
1441
- private readonly _log;
1442
- readonly messages: Node<readonly ChatMessage[]>;
1443
- readonly latest: Node<ChatMessage | null>;
1444
- readonly messageCount: Node<number>;
1445
- constructor(name: string, opts?: ChatStreamOptions);
1446
- append(role: ChatMessage["role"], content: string, extra?: Partial<ChatMessage>): void;
1447
- appendToolResult(callId: string, content: string): void;
1448
- clear(): void;
1449
- allMessages(): readonly ChatMessage[];
1450
- }
1451
- declare function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph;
1452
-
1453
- /**
1454
- * Options for {@link handoff}.
1455
- */
1456
- type HandoffOptions = {
1457
- /**
1458
- * Reactive gate: when this node's value is `true`, output flows from
1459
- * `from` to the `to` specialist; when `false`, `from`'s output flows
1460
- * through unchanged and `to` stays dormant. Omit to always hand off —
1461
- * useful when `from` is itself a router whose output shape already
1462
- * encodes routing intent.
1463
- */
1464
- condition?: NodeInput<boolean>;
1465
- name?: string;
1466
- };
1467
- /**
1468
- * Multi-agent handoff recipe — route `from`'s output into a specialist
1469
- * agent `toFactory` when `condition` is open. Thin composition over
1470
- * `switchMap` + gate; not a new primitive, just a named shape.
1471
- *
1472
- * The "handoff" pattern (popularized by the OpenAI Agents SDK) covers two
1473
- * idioms:
1474
- *
1475
- * 1. **Full handoff** — a triage agent routes the conversation to a
1476
- * specialist, and the specialist becomes the active agent for the rest
1477
- * of the turn. Accumulated context (memory, tool definitions) can travel
1478
- * along by threading the same `agentMemory` bundle into both.
1479
- * 2. **Agents-as-tools** — the manager keeps control and calls the
1480
- * specialist like a tool for a bounded subtask. Build this by registering
1481
- * a `promptNode` instance as a `ToolDefinition` on the parent via
1482
- * `toolRegistry`.
1483
- *
1484
- * This sugar covers (1) — a reactive route from one agent's output into a
1485
- * specialist factory. For (2) wire a tool registry manually; the pattern is
1486
- * additive with this one.
1487
- *
1488
- * @example Full handoff on a triage signal.
1489
- * ```ts
1490
- * import { handoff, promptNode } from "@graphrefly/graphrefly/patterns/ai";
1491
- *
1492
- * const triage = promptNode(adapter, [userMessage], (msg) =>
1493
- * `Classify urgency of: ${msg}. Reply "high" or "normal".`);
1494
- * const isUrgent = derived([triage], ([v]) => v === "high");
1495
- *
1496
- * const specialist = handoff(
1497
- * userMessage,
1498
- * (input) => promptNode(specialistAdapter, [input], (m) => `Respond urgently: ${m}`),
1499
- * { condition: isUrgent },
1500
- * );
1501
- * ```
1502
- *
1503
- * @param from - Source node whose value is threaded into the specialist.
1504
- * @param toFactory - Factory that takes `from` (as a reactive source) and
1505
- * returns the specialist node. Called once, lazily, when the first
1506
- * subscriber activates.
1507
- * @param opts - Optional reactive `condition` gate + name.
1508
- * @returns Node emitting the specialist's output when the gate is open, or
1509
- * `from`'s value when the gate is closed. Null when `from` is null.
1510
- *
1511
- * **Performance caveat (Wave A Unit 5):** the specialist is mounted per
1512
- * source emission — each `v != null` DATA on `from` allocates a fresh
1513
- * `state<T>(v)` + invokes `toFactory`, and switchMap cancels the prior
1514
- * branch. For per-turn routing (≤1 emit/sec) this is negligible. For
1515
- * high-frequency sources (per-token routing, tight event loops), batch
1516
- * upstream (e.g. via `audit`, `throttle`, or `distinctUntilChanged`) before
1517
- * handing off — each mount/unmount cycle spins up full subgraphs
1518
- * (`messagesNode` + adapter bridge + output for a `promptNode` specialist).
1519
- *
1520
- * @category patterns.ai
1521
- */
1522
- declare function handoff<T>(from: NodeInput<T | null>, toFactory: (input: Node<T>) => Node<T | null>, opts?: HandoffOptions): Node<T | null>;
1523
-
1524
- type ToolRegistryOptions = {
1525
- graph?: GraphOptions;
1526
- };
1527
- /**
1528
- * `ToolRegistryGraph` — name-keyed registry of {@link ToolDefinition}s.
1529
- *
1530
- * **Reactive-only execution.** The only execution path is
1531
- * {@link executeReactive}, which returns a `Node<unknown>` for the handler
1532
- * result. Composing factories (`toolExecution`, `agentLoop`) consume it
1533
- * directly inside `retrySource` / `switchMap` chains. There is intentionally
1534
- * no imperative `execute()` Promise method — the registry was originally a
1535
- * dual-boundary class (imperative + reactive) and the imperative path was
1536
- * the only thing in the codebase bridging through `Promise.resolve().then()`
1537
- * to feed `fromAny`. Removing it left every consumer on a single
1538
- * reactive-all-the-way path with real abort propagation.
1539
- *
1540
- * For non-reactive callers (debug scripts, one-shot tests), bridge with
1541
- * `awaitSettled(toolRegistry.executeReactive(name, args))`.
1542
- *
1543
- * **Wave A Unit 6 refactor:** internal storage migrated from `state<Map>`
1544
- * (O(N) Map-copy per mutation) to `ReactiveMapBundle<string, ToolDefinition>`
1545
- * (O(1) mutations + version counter).
1546
- */
1547
- declare class ToolRegistryGraph extends Graph {
1548
- readonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;
1549
- readonly schemas: Node<readonly ToolDefinition[]>;
1550
- private readonly _bundle;
1551
- constructor(name: string, opts?: ToolRegistryOptions);
1552
- register(tool: ToolDefinition): void;
1553
- unregister(name: string): void;
1554
- /**
1555
- * Reactive execution — returns a `Node<unknown>` that emits the handler
1556
- * result. The returned node is a `producer` that:
1557
- *
1558
- * 1. Mints a per-call `AbortController` whose `signal` is threaded into
1559
- * the handler call AND into `fromAny` (so a `fromPromise` /
1560
- * `fromAsyncIter` inner abandons cleanly when the consumer
1561
- * unsubscribes).
1562
- * 2. Runs `tool.handler(args, {signal})` inside a try/catch — a
1563
- * synchronous throw surfaces as `[[ERROR, err]]` downstream instead
1564
- * of escaping the producer.
1565
- * 3. Forwards every message from the inner `fromAny` chain to the
1566
- * producer's outputs.
1567
- * 4. On teardown (subscriber count drops to zero, e.g. `switchMap`
1568
- * supersede) calls `ac.abort()` and unsubscribes the inner.
1569
- * Signal-aware handlers (e.g. `fetch(url, {signal})`) actually stop.
1570
- *
1571
- * Each call mints a fresh node tied to a fresh `handler(args, ...)`
1572
- * invocation — call `executeReactive` again for repeated invocations.
1573
- *
1574
- * @throws `Error` synchronously when `name` is not registered (no node is
1575
- * constructed — the caller gets a pre-wiring failure rather than a
1576
- * silent ERROR wave on an empty graph).
1577
- */
1578
- executeReactive(name: string, args: Record<string, unknown>): Node<unknown>;
1579
- getDefinition(name: string): ToolDefinition | undefined;
1580
- }
1581
- declare function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph;
1582
-
1583
- /**
1584
- * `toolExecution` — reactive per-tool-call executor with retry + rescue.
1585
- *
1586
- * Lifted from the inlined `executeToolReactively` helper inside `agent-loop.ts`
1587
- * so it can be consumed standalone by any caller with a reactive `toolCalls`
1588
- * batch — not just `agentLoop`. The shape is: one input `Node<readonly
1589
- * ToolCall[]>` + a `ToolRegistryGraph` → one output `Node<readonly
1590
- * ToolResult[]>`. Each call maps to a per-call `retrySource(executeReactive)`
1591
- * → optional `rescue` chain that emits the handler result on success, or a
1592
- * JSON-wrapped `{ error }` payload on terminal failure so the LLM can see the
1593
- * error as tool output and decide whether to try again via another tool call.
1594
- *
1595
- * **Cancellation.** `executeReactive` mints a per-call `AbortController` and
1596
- * threads its signal into the handler call. When `switchMap` supersedes the
1597
- * inner (a fresh `toolCalls` batch arrives) or the outer graph tears down,
1598
- * the per-call node unsubscribes and `ac.abort()` fires. Signal-aware
1599
- * handlers (`fetch(url, {signal})`, child-process kill, DB cancel) actually
1600
- * stop in-flight work; handlers that ignore the signal still complete to
1601
- * their original termination, but their result is discarded.
1602
- *
1603
- * @module
1604
- */
1605
-
1606
- /** A single tool execution outcome: `{id, content}` where content is a JSON string. */
1607
- interface ToolResult {
1608
- readonly id: string;
1609
- readonly content: string;
1610
- }
1611
- type ToolExecutionOptions = {
1612
- /**
1613
- * Reactive tool-call batch. Each non-empty emission triggers a fresh
1614
- * per-call execution fan-out; superseding emissions cancel the prior fan.
1615
- */
1616
- toolCalls: Node<readonly ToolCall[]>;
1617
- /** Registry that resolves tool name → handler. */
1618
- tools: ToolRegistryGraph;
1619
- /**
1620
- * Retry count per individual tool call. `retrySource({count: N})` retries
1621
- * up to N times on error (N retries = N+1 total attempts). Default: 1.
1622
- */
1623
- retryCount?: number;
1624
- /**
1625
- * How to surface a terminal error after retries are exhausted.
1626
- * - `"rescue"` (default): emit `{id, content: JSON.stringify({error})}`
1627
- * so the LLM sees the failure as structured tool output and can decide
1628
- * how to react. Sibling calls in the same batch continue to their own
1629
- * completion; one call's failure does not affect the others.
1630
- * - `"propagate"`: let the ERROR propagate downstream. **Blast radius:**
1631
- * the per-batch `derived` join auto-errors when any per-call node
1632
- * terminates with ERROR, so one call's failure discards every sibling's
1633
- * DATA (even ones that already settled with a valid ToolResult). Use
1634
- * `"propagate"` only when a single tool failure should be fatal for the
1635
- * whole batch; prefer `"rescue"` when you want the LLM to see partial
1636
- * results plus per-call error markers.
1637
- */
1638
- onError?: "rescue" | "propagate";
1639
- };
1640
- /**
1641
- * Reactive executor for a batch of LLM tool calls.
1642
- *
1643
- * Each DATA emission on `toolCalls` dispatches a fresh per-call fan-out: for
1644
- * every call in the batch, construct a `retrySource(fromAny(tools.execute(
1645
- * name, args)))` node, optionally `rescue` it into a JSON error shape, and
1646
- * join the results via a `derived` whose first-run gate waits for every call
1647
- * to settle before emitting the batch. Empty batches (`calls.length === 0`)
1648
- * are a caller-side invariant violation (the upstream gate should emit
1649
- * RESOLVED for empty batches, not DATA) and trigger a loud error — callers
1650
- * that want to accept empty batches should upstream-filter them first.
1651
- *
1652
- * Reference-equality + content-equality dedup is applied to the output batch
1653
- * so duplicate re-emissions from a completing retrySource don't propagate.
1654
- *
1655
- * @param opts - `{ toolCalls, tools, retryCount?, onError? }`.
1656
- * @returns `Node<readonly ToolResult[]>` — one ToolResult per input ToolCall.
1657
- */
1658
- declare function toolExecution(opts: ToolExecutionOptions): Node<readonly ToolResult[]>;
1659
-
1660
- /**
1661
- * Options for {@link toolSelector}.
1662
- */
1663
- interface ToolSelectorOptions {
1664
- readonly name?: string;
1665
- }
1666
- /**
1667
- * Reactive tool availability (COMPOSITION-GUIDE §31). Given a base tool set
1668
- * (reactive or static) and one or more reactive predicates, emit the filtered
1669
- * subset of tools currently allowed. Feeds into `promptNode({ tools: Node<...> })`
1670
- * so the LLM sees a reactive menu instead of a frozen config.
1671
- *
1672
- * Each predicate is a `NodeInput<(tool) => boolean>`. A tool is included iff
1673
- * **every** predicate returns `true`. When any predicate value is `null` /
1674
- * `undefined` (e.g. upstream not yet ready) that predicate is treated as a
1675
- * pass-through — the tool isn't excluded on its basis. Predicate updates
1676
- * recompute the selected set.
1677
- *
1678
- * Pairs with `toolInterceptor` (§D9 / §31): **selection** controls what's
1679
- * offered to the LLM (pre-generation UX); **interception** gates what's
1680
- * executed after the LLM chooses (post-generation security). Tool selection
1681
- * is NOT a security boundary — an LLM can hallucinate tool calls outside
1682
- * its offered set; always pair with `toolInterceptor` for enforcement.
1683
- *
1684
- * @example
1685
- * ```ts
1686
- * const hasBudget = derived([costMeter], (c) => c.total < BUDGET);
1687
- * const canDestroy = state(false, { name: "destructive-allowed" });
1688
- * const tools = toolSelector(registry.schemas, [
1689
- * derived([hasBudget], (b) => (t) => !t.meta?.expensive || b === true),
1690
- * derived([canDestroy], (c) => (t) => !t.meta?.destructive || c === true),
1691
- * ]);
1692
- * const agent = promptNode(graph, "agent", { ..., tools });
1693
- * ```
1694
- */
1695
- declare function toolSelector(allTools: NodeInput<readonly ToolDefinition[]>, constraints: readonly NodeInput<(tool: ToolDefinition) => boolean>[], opts?: ToolSelectorOptions): Node<readonly ToolDefinition[]>;
1696
-
1697
- /** Generic per-dimension thresholds. Any dim below its threshold → reject. */
1698
- type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;
1699
- type AdmissionScoredOptions<Dims extends string, TRaw = unknown> = {
1700
- /** Score function — must return a finite number for every dimension named in `thresholds`. */
1701
- scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;
1702
- /** Per-dim minimums. Dims absent here are scored but not gated. */
1703
- thresholds?: AdmissionThresholds<Dims>;
1704
- };
1705
- /**
1706
- * Generic N-dimension admission filter. Rejects any input where one of the
1707
- * configured threshold dimensions scores below its minimum. Missing scores
1708
- * (`undefined` / `null`) AND non-finite values (`NaN`, `±Infinity`) are
1709
- * treated as below all thresholds — reject by default rather than admit.
1710
- *
1711
- * @example
1712
- * ```ts
1713
- * const filter = admissionScored({
1714
- * scoreFn: (raw: Note) => ({ relevance: scoreRelevance(raw), age: ageScore(raw) }),
1715
- * thresholds: { relevance: 0.4 }, // age scored but ungated
1716
- * });
1717
- * ```
1718
- */
1719
- declare function admissionScored<Dims extends string, TRaw = unknown>(opts: AdmissionScoredOptions<Dims, TRaw>): (raw: TRaw) => boolean;
1720
- /** Scores for the three admission dimensions. Each 0–1. */
1721
- type AdmissionScores = {
1722
- readonly persistence: number;
1723
- readonly structure: number;
1724
- readonly personalValue: number;
1725
- };
1726
- type AdmissionScore3DOptions = {
1727
- /** Custom scoring function. Required — the previous always-0.5 default was misleading. */
1728
- scoreFn: (raw: unknown) => AdmissionScores;
1729
- /** Minimum persistence score to admit (default 0.3). */
1730
- persistenceThreshold?: number;
1731
- /** Minimum personalValue score to admit (default 0.3). */
1732
- personalValueThreshold?: number;
1733
- /** Require structure score > 0 to admit (default false). */
1734
- requireStructured?: boolean;
1735
- };
1736
- /**
1737
- * 3D admission sugar — the persistence / structure / personalValue triple
1738
- * commonly used in agent-memory literature. Composes `admissionScored`
1739
- * with thresholds derived from the option fields. Use directly when those
1740
- * three named dimensions match your domain, or use `admissionScored` with
1741
- * an arbitrary dimension set instead.
1742
- *
1743
- * `requireStructured: true` rejects entries where `structure <= 0` (matches
1744
- * the pre-Unit-8 `requireStructured && scores.structure <= 0` check).
1745
- * Implemented as a final-step predicate around `admissionScored` rather
1746
- * than a `Number.MIN_VALUE` threshold, which would have been a footgun for
1747
- * future readers.
1748
- */
1749
- declare function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean;
1750
-
1751
- type RetrievalQuery = {
1752
- readonly text?: string;
1753
- readonly vector?: readonly number[];
1754
- readonly entityIds?: readonly string[];
1755
- /**
1756
- * Optional hierarchical context breadcrumb — e.g.
1757
- * `["projects", "auth", "tokens"]`. When both the query and a candidate
1758
- * entry supply a `context`, the retrieval pipeline applies a score boost
1759
- * proportional to `contextWeight` for entries whose context overlaps
1760
- * (shared prefix). Entries or queries without `context` are scored
1761
- * flatly (backward-compatible).
1762
- */
1763
- readonly context?: readonly string[];
1764
- };
1765
- type RetrievalPipelineOptions<TMem> = {
1766
- /** Max candidates from vector search (default 20). */
1767
- topK?: number;
1768
- /** KG expansion depth in hops (default 1). */
1769
- graphDepth?: number;
1770
- /** Token budget for final packing (default 2000). */
1771
- budget?: number;
1772
- /** Cost function for budget packing. */
1773
- cost: (mem: TMem) => number;
1774
- /** Score function for ranking. */
1775
- score: (mem: TMem, context: unknown) => number;
1776
- /**
1777
- * Optional accessor: extracts the hierarchical context breadcrumb from a
1778
- * memory entry. Used with {@link RetrievalQuery.context} and
1779
- * `contextWeight` to boost entries whose context overlaps the query.
1780
- * Entries that don't expose context stay at flat behavior.
1781
- */
1782
- contextOf?: (mem: TMem) => readonly string[] | undefined;
1783
- /**
1784
- * Boost multiplier applied to a candidate's score when its `context`
1785
- * shares a prefix with the query's `context`. Score is multiplied by
1786
- * `(1 + contextWeight * sharedDepth / queryDepth)`. Default: 0 (no
1787
- * context boost).
1788
- */
1789
- contextWeight?: number;
1790
- };
1791
- /** A single entry in the retrieval result, with causal trace metadata. */
1792
- type RetrievalEntry<TMem> = {
1793
- readonly key: string;
1794
- readonly value: TMem;
1795
- readonly score: number;
1796
- readonly sources: ReadonlyArray<"vector" | "graph" | "store">;
1797
- /**
1798
- * Hierarchical context breadcrumb for this entry, when
1799
- * `RetrievalPipelineOptions.contextOf` is supplied and returns a value.
1800
- */
1801
- readonly context?: readonly string[];
1802
- };
1803
- /** Causal trace for a retrieval run. */
1804
- type RetrievalTrace<TMem> = {
1805
- readonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;
1806
- readonly graphExpanded: ReadonlyArray<string>;
1807
- readonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;
1808
- readonly packed: ReadonlyArray<RetrievalEntry<TMem>>;
1809
- };
1810
-
1811
- type MemoryTier = "permanent" | "active" | "archived";
1812
- type MemoryTiersOptions<TMem> = {
1813
- /** Exponential decay rate per second for active tier.
1814
- * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */
1815
- decayRate?: number;
1816
- /** Max entries in the active tier before archiving lowest-scored (default 1000). */
1817
- maxActive?: number;
1818
- /** Score threshold below which active entries get archived (default 0.1). */
1819
- archiveThreshold?: number;
1820
- /** Predicate: true → entry belongs in permanent tier (default: never). */
1821
- permanentFilter?: (key: string, mem: TMem) => boolean;
1822
- /** Storage tier for the archive. Omit to disable archiving. */
1823
- archiveTier?: SnapshotStorageTier<GraphCheckpointRecord>;
1824
- /** Options forwarded to `graph.attachSnapshotStorage` for the archive tier. */
1825
- archiveStorageOptions?: GraphAttachStorageOptions;
1826
- };
1827
-
1828
- type MemoryTiersBundle<TMem> = {
1829
- /**
1830
- * Permanent tier: never evicted. Backed by a `collection({ranked:false})`
1831
- * Graph (Tier 2.3 — was previously a `LightCollectionBundle`; the no-Graph
1832
- * bundle shape was folded into the unified `CollectionGraph`).
1833
- */
1834
- readonly permanent: CollectionGraph<TMem>;
1835
- /** Active entries node (reactive, holds ReadonlyMap). */
1836
- readonly activeEntries: Node<unknown>;
1837
- /** Archive storage handle (null if no tier configured). */
1838
- readonly archiveHandle: StorageHandle | null;
1839
- /** Classify a key into its current tier. */
1840
- tierOf: (key: string) => MemoryTier;
1841
- /** Move a key to the permanent tier. */
1842
- markPermanent: (key: string, value: TMem) => void;
1843
- };
1844
-
1845
- type MemoryWithVectorsOptions<TMem> = {
1846
- /** Embedding dimension. Must match the `embedFn` output length. */
1847
- dimension: number;
1848
- /** Extract an embedding vector for a memory entry. */
1849
- embedFn: (mem: TMem) => readonly number[] | undefined;
1850
- };
1851
- /**
1852
- * Attach a vector index to a `DistillBundle`. Indexes every entry in the
1853
- * store as it changes. Returns the `VectorIndexGraph` so retrieval can read
1854
- * its `entries` and call `search()`.
1855
- *
1856
- * The indexer's keepalive is registered with `graph.addDisposer` so it tears
1857
- * down on `graph.destroy()`. The returned `dispose()` is also available for
1858
- * early release without destroying the parent graph.
1859
- */
1860
- declare function memoryWithVectors<TMem>(graph: Graph, store: DistillBundle<TMem>, opts: MemoryWithVectorsOptions<TMem>): {
1861
- vectors: VectorIndexGraph<TMem>;
1862
- dispose: () => void;
1863
- };
1864
- type MemoryWithKGOptions<TMem> = {
1865
- /**
1866
- * Mount path for the KG subgraph on the parent graph. Defaults to `name`.
1867
- * Pass a different value when the parent graph reserves a stable mount
1868
- * path (e.g. `agentMemory` mounts at `"kg"` regardless of outer name).
1869
- */
1870
- mountPath?: string;
1871
- /**
1872
- * Extract entities + relations for a memory entry. Omit to mount an empty
1873
- * KG without an indexer effect — caller upserts entities / relations
1874
- * directly on the returned `kg` handle.
1875
- */
1876
- entityFn?: (key: string, mem: TMem) => {
1877
- entities?: Array<{
1878
- id: string;
1879
- value: unknown;
1880
- }>;
1881
- relations?: Array<{
1882
- from: string;
1883
- to: string;
1884
- relation: string;
1885
- weight?: number;
1886
- }>;
1887
- } | undefined;
1888
- };
1889
- /**
1890
- * Attach a knowledge graph alongside a `DistillBundle`. Inner graph is named
1891
- * `${name}-kg`; mount path defaults to `name` but can be overridden via
1892
- * `opts.mountPath` so a parent factory (e.g. `agentMemory`) can keep a stable
1893
- * mount path independent of the inner graph's identity.
1894
- *
1895
- * If `opts.entityFn` is omitted, no indexer effect is wired — the empty KG is
1896
- * mounted for manual `upsertEntity` / `link` use.
1897
- *
1898
- * Indexer keepalive (when present) is registered with `graph.addDisposer`;
1899
- * explicit `dispose()` is also available.
1900
- */
1901
- declare function memoryWithKG<TMem>(graph: Graph, store: DistillBundle<TMem>, name: string, opts: MemoryWithKGOptions<TMem>): {
1902
- kg: KnowledgeGraph<unknown, string>;
1903
- dispose: () => void;
1904
- };
1905
- /**
1906
- * Full options for {@link memoryWithTiers} (Tier 4.1 B + 4.3 B refactor,
1907
- * 2026-04-29). Combines tier-policy options with the distill-side options
1908
- * needed to construct the underlying store — `memoryWithTiers` is now the
1909
- * **construction site** for the distill bundle so it can wire
1910
- * `reactiveMap.retention` into the store at construction (eliminating the
1911
- * §7 feedback cycle the previous `tierClassifier` effect carried).
1912
- *
1913
- * The retention config built internally maps tier policy to the substrate:
1914
- * - `archiveThreshold` → `retention.archiveThreshold`
1915
- * - `maxActive` → `retention.maxSize`
1916
- * - per-entry `decay(score(mem, ctx), age, decayRate)` → `retention.score`
1917
- * (capturing `latestCtx` + `entryCreatedAtNs` via closure-mirror; permanent
1918
- * entries score `Infinity` to bypass eviction).
1919
- */
1920
- type MemoryWithTiersOptions<TMem> = MemoryTiersOptions<TMem> & Omit<DistillOptions<TMem>, "mapOptions" | "score" | "context"> & {
1921
- /** Score function — same signature as `agentMemory.score`. */
1922
- score: (mem: TMem, context: unknown) => number;
1923
- /** Optional reactive context node (passed to `score`). */
1924
- context?: NodeInput<unknown>;
1925
- };
1926
- /**
1927
- * Attach 3-tier storage (active / archived / permanent) to a fresh distill
1928
- * store, wiring `reactiveMap.retention` at construction so archival happens
1929
- * synchronously inside the substrate's mutation pipeline (no §7 feedback
1930
- * cycle). Promotes `permanentKeys` and `entryCreatedAtNs` to reactive maps
1931
- * mounted on the graph (Tier 4.3 B — Unit 7 Q3) so `describe()`/`explain()`
1932
- * can walk to "why was X archived?".
1933
- *
1934
- * **API shape** (Tier 4.1 B, 2026-04-29 — breaking change vs. pre-refactor):
1935
- * `memoryWithTiers` constructs the distill bundle internally rather than
1936
- * accepting a pre-built one. Callers pass `(graph, source, extractFn,
1937
- * opts)`. The bundle is exposed as `result.store` for downstream composers
1938
- * (vectors / KG / retrieval).
1939
- *
1940
- * - `permanentFilter`-matching entries score `Infinity` in retention →
1941
- * never archived. Independent permanent-promotion effect upserts them
1942
- * into the `permanent` collection.
1943
- * - Below-threshold entries → retention archives synchronously.
1944
- * - Over-`maxActive` entries → retention's `maxSize` evicts lowest-scored.
1945
- */
1946
- declare function memoryWithTiers<TRaw, TMem>(graph: Graph, source: NodeInput<TRaw>, extractFn: (raw: Node<TRaw>, existing: Node<ReadonlyMap<string, TMem>>) => NodeInput<Extraction<TMem>>, opts: MemoryWithTiersOptions<TMem>): {
1947
- store: DistillBundle<TMem>;
1948
- tiers: MemoryTiersBundle<TMem>;
1949
- dispose: () => void;
1950
- };
1951
- type MemoryRetrievalOptions<TMem> = {
1952
- /** Score function (same shape as `agentMemory.score`). */
1953
- score: (mem: TMem, context: unknown) => number;
1954
- /** Cost function for budget packing. */
1955
- cost: (mem: TMem) => number;
1956
- /** Token / cost budget. Default 2000. */
1957
- budget?: number;
1958
- /** Top-K vector candidates. Default 20. */
1959
- topK?: number;
1960
- /** KG expansion depth in hops. Default 1. */
1961
- graphDepth?: number;
1962
- /** Hierarchical-context boost weight. Default 0. */
1963
- contextWeight?: number;
1964
- /** Hierarchical-context accessor for entries. */
1965
- contextOf?: (mem: TMem) => readonly string[] | undefined;
1966
- /** Optional reactive context node (passed to `score`). */
1967
- context?: NodeInput<unknown>;
1968
- };
1969
- type MemoryRetrievalBundle<TMem> = {
1970
- /** State node mirroring the latest packed retrieval result. */
1971
- readonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>>;
1972
- /** State node mirroring the latest retrieval trace. */
1973
- readonly retrievalTrace: Node<RetrievalTrace<TMem> | null>;
1974
- /** Imperative consumer API — synchronous; reads cache at call time. */
1975
- readonly retrieve: (query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>;
1976
- /** Reactive sibling — chain into the graph. Mirrors observability state. */
1977
- readonly retrieveReactive: (queryInput: NodeInput<RetrievalQuery | null>) => Node<ReadonlyArray<RetrievalEntry<TMem>>>;
1978
- };
1979
- /**
1980
- * Build the retrieval pipeline (vector + KG + budget packing) over a
1981
- * `DistillBundle` and optional `vectors` / `kg` bundles.
1982
- *
1983
- * Both consumer surfaces (`retrieve`, `retrieveReactive`) write to the same
1984
- * `retrieval` + `retrievalTrace` state nodes — observers subscribed to those
1985
- * see ALL queries regardless of which API issued them.
1986
- */
1987
- declare function memoryRetrieval<TMem>(graph: Graph, store: DistillBundle<TMem>, vectors: VectorIndexGraph<TMem> | null, kg: KnowledgeGraph<unknown, string> | null, opts: MemoryRetrievalOptions<TMem>): MemoryRetrievalBundle<TMem>;
1988
-
1989
- /**
1990
- * Reactive agent loop — autonomous multi-turn LLM agent with tool execution.
1991
- */
1992
- type AgentLoopStatus = "idle" | "thinking" | "acting" | "done" | "error";
1993
-
1994
- type AgentLoopOptions = {
1995
- graph?: GraphOptions;
1996
- adapter: LLMAdapter;
1997
- tools?: readonly ToolDefinition[];
1998
- systemPrompt?: string;
1999
- maxTurns?: number;
2000
- stopWhen?: (response: LLMResponse) => boolean;
2001
- onToolCall?: (call: ToolCall) => void;
2002
- maxMessages?: number;
2003
- model?: string;
2004
- temperature?: number;
2005
- maxTokens?: number;
2006
- /**
2007
- * Reactive tool-call splice (COMPOSITION-GUIDE §31 "interception is security").
2008
- * When set, the raw `toolCalls` node is piped through this transform before
2009
- * reaching the executor. The transform is a pure reactive composition —
2010
- * `(calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>` — so the
2011
- * gate is visible in `describe()` / `explain()` as a real edge (no hidden
2012
- * imperative wraps; §24).
2013
- *
2014
- * Typical uses:
2015
- * - **Filter / block** — `derived([calls, policy], ([raw, p]) => raw.filter(p))`
2016
- * - **Throttle / debounce** — `throttle(calls, windowMs)`
2017
- * - **Human-in-the-loop approval** — pipe through a `gate` controller so
2018
- * calls wait for human approval before reaching the executor.
2019
- *
2020
- * The public `agent.toolCalls` node surfaces the POST-intercept stream, so
2021
- * audit / telemetry consumers see what the executor actually runs. The raw
2022
- * pre-intercept stream is not exposed — tests that need it should run
2023
- * without `interceptToolCalls` set (the identity case).
2024
- */
2025
- interceptToolCalls?: (calls: Node<readonly ToolCall[]>) => Node<readonly ToolCall[]>;
2026
- };
2027
- /**
2028
- * Reactive agent loop.
2029
- *
2030
- * The loop is a reactive state machine wired entirely from graph primitives:
2031
- * `chat.messages` + `tools.schemas` + gating state feed a `promptInput`
2032
- * derived; `switchMap` turns non-null inputs into an LLM invocation via
2033
- * `fromAny(adapter.invoke(...))`. The LLM response drives chat writes and
2034
- * status transitions via effects. Tool calls flow through a reactive
2035
- * executor (`retrySource` + `rescue`) that retries once on error and
2036
- * surfaces terminal errors as JSON-shaped `ToolResult` payloads for the
2037
- * LLM to react to.
2038
- *
2039
- * **No imperative control flow inside the reactive layer** (spec §5.8-5.12):
2040
- * no `while` loops, no manual `await adapter.invoke`, no polling.
2041
- * `agent.run()` is a thin `awaitSettled` bridge so callers can still `await`
2042
- * the loop if they want a Promise.
2043
- *
2044
- * Public surface:
2045
- * - `chat` / `tools` — subgraphs (imperative `append` at boundary, reactive `executeReactive` for tool invocation)
2046
- * - `status` / `turn` / `aborted` — state nodes with explicit initials
2047
- * - `lastResponse` / `toolCalls` / `toolResults` — reactive outputs (SENTINEL until first emission; callers use `awaitSettled` / `subscribe`)
2048
- * - `run(userMessage?, signal?)` — optional user append + Promise bridge
2049
- * - `abort()` — imperative abort shim; flips `aborted` state
2050
- *
2051
- * **Lifecycle: single-mount.** `AgentLoopGraph` instances expect to be
2052
- * constructed once and used until `destroy()`. The internal closure mirrors
2053
- * (`latestTurn` / `latestAborted` / `latestStatus` / `latestMessages` /
2054
- * `latestSchemas`) are wired by subscribe-and-capture at construction time;
2055
- * their corresponding `addDisposer`-registered subscriptions are torn down
2056
- * on subgraph unmount or `destroy()`. After teardown the mirrors freeze at
2057
- * their last value, so re-using a destroyed instance — calling `run()`
2058
- * again, or remounting under a new parent — would silently feed stale
2059
- * mirror data into `promptInput`. If you need to "reset" an agent, build a
2060
- * fresh `AgentLoopGraph` instance instead of recycling.
2061
- */
2062
- declare class AgentLoopGraph extends Graph {
2063
- readonly chat: ChatStreamGraph;
2064
- readonly tools: ToolRegistryGraph;
2065
- /** Current agent status. `initial: "idle"` — always has a real value. */
2066
- readonly status: Node<AgentLoopStatus>;
2067
- /** Turn count (completed LLM invocations this run). `initial: 0`. */
2068
- readonly turn: Node<number>;
2069
- /** Aborted flag; flipped by `abort()` or external `AbortSignal`. `initial: false`. */
2070
- readonly aborted: Node<boolean>;
2071
- /**
2072
- * Most recent LLM response. State-backed mirror driven by the response
2073
- * effect. `initial: null` — subscribers can read the cache synchronously;
2074
- * `awaitSettled(lastResponse)` or `firstWhere(lastResponse, v => v != null)`
2075
- * bridges to the first non-null value as a Promise.
2076
- */
2077
- readonly lastResponse: Node<LLMResponse | null>;
2078
- /** Tool-call batch emitted by the most recent LLM response. SENTINEL. */
2079
- readonly toolCalls: Node<readonly ToolCall[]>;
2080
- /** Tool-result batch (one entry per call) after reactive execution. SENTINEL. */
2081
- readonly toolResults: Node<readonly ToolResult[]>;
2082
- private readonly _terminalResult;
2083
- private readonly _disposeRunWiring;
2084
- /** Guards against overlapping `run()` calls. */
2085
- private _running;
2086
- /**
2087
- * Abort controller for the currently-running `adapter.invoke`. Minted per
2088
- * switchMap project; aborted when the reactive `aborted` node flips true
2089
- * OR when the caller's external `AbortSignal` fires. Threaded into
2090
- * `adapter.invoke({ signal })` AND `fromAny(promise, { signal })`, so the
2091
- * reactive layer sees ERROR when the wire call is cancelled.
2092
- */
2093
- private _currentAbortController;
2094
- constructor(name: string, opts: AgentLoopOptions);
2095
- /**
2096
- * Bridge to `Promise<LLMResponse>` over the reactive pipeline.
2097
- *
2098
- * - If `userMessage` is provided, appends it as a user message and
2099
- * transitions status to `"thinking"` to kick the loop.
2100
- * - If `signal` is provided, binds it to the reactive `aborted` node
2101
- * AND threads into `adapter.invoke({ signal })` so the wire call can
2102
- * cancel mid-flight. The reactive `aborted` state + effect 3 guarantee
2103
- * that even an adapter that ignores `signal` will stop emitting into
2104
- * the agent graph.
2105
- * - Resolves when `status === "done"` with the final LLM response.
2106
- * Rejects with `AbortError` when the abort signal fires pre-response.
2107
- * Rejects with the stage error when `status === "error"`.
2108
- *
2109
- * **Concurrency:** `run()` refuses to overlap with a pending call on the
2110
- * same agent. Attempting to call `run()` while a previous `run()` is
2111
- * still in-flight throws a `RangeError` immediately. Stale-resolution
2112
- * safety is provided by `awaitSettled({skipCurrent: true})`, which
2113
- * ignores the cached initial DATA from any previous run and resolves
2114
- * only on a fresh post-subscribe emission of `_terminalResult`.
2115
- */
2116
- run(userMessage?: string, signal?: AbortSignal): Promise<LLMResponse | null>;
2117
- /**
2118
- * Flip the reactive `aborted` state. Equivalent to setting an external
2119
- * `AbortSignal` — the pipeline observes and transitions to `"done"`.
2120
- */
2121
- abort(): void;
2122
- destroy(): void;
2123
- }
2124
- declare function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph;
2125
-
2126
- type AgentMemoryOptions<TMem = unknown> = {
2127
- graph?: GraphOptions;
2128
- /** LLM adapter for extraction and consolidation. */
2129
- adapter?: LLMAdapter;
2130
- /** System prompt for the extractor LLM. */
2131
- extractPrompt?: string;
2132
- /** Custom extractFn (overrides adapter + extractPrompt). */
2133
- extractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
2134
- /** System prompt for the consolidation LLM. */
2135
- consolidatePrompt?: string;
2136
- /** Custom consolidateFn (overrides adapter + consolidatePrompt). */
2137
- consolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;
2138
- /** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */
2139
- consolidateTrigger?: NodeInput<unknown>;
2140
- /** Score function for budget packing (required). */
2141
- score: (mem: TMem, context: unknown) => number;
2142
- /** Cost function for budget packing (required). */
2143
- cost: (mem: TMem) => number;
2144
- /** Token budget for compact view (default 2000). */
2145
- budget?: number;
2146
- /** Context node for scoring. */
2147
- context?: NodeInput<unknown>;
2148
- /** Admission filter (default: admit all). */
2149
- admissionFilter?: (candidate: unknown) => boolean;
2150
- /** Vector index dimensions (> 0 enables vector index for retrieval). */
2151
- vectorDimensions?: number;
2152
- /**
2153
- * B12: optional accessor for an entry's hierarchical context breadcrumb
2154
- * (e.g. `["projects", "auth", "tokens"]`). When supplied alongside
2155
- * `contextWeight > 0`, retrieval applies a score boost for entries whose
2156
- * context shares a prefix with the query's `context`. Entries without
2157
- * a breadcrumb are scored flatly.
2158
- */
2159
- contextOf?: (mem: TMem) => readonly string[] | undefined;
2160
- /**
2161
- * B12: hierarchical context boost multiplier. Score is scaled by
2162
- * `(1 + contextWeight * sharedDepth / queryDepth)` when both the query
2163
- * and entry supply a `context`. Default: 0.
2164
- */
2165
- contextWeight?: number;
2166
- /** Extract embedding vector from a memory entry (enables vector index). */
2167
- embedFn?: (mem: TMem) => readonly number[] | undefined;
2168
- /** Enable knowledge graph for entity/relation tracking. */
2169
- enableKnowledgeGraph?: boolean;
2170
- /** Extract entities and relations from a memory entry. */
2171
- entityFn?: (key: string, mem: TMem) => {
2172
- entities?: Array<{
2173
- id: string;
2174
- value: unknown;
2175
- }>;
2176
- relations?: Array<{
2177
- from: string;
2178
- to: string;
2179
- relation: string;
2180
- weight?: number;
2181
- }>;
2182
- } | undefined;
2183
- /** 3-tier storage configuration. Omit to use single-tier (existing behavior). */
2184
- tiers?: MemoryTiersOptions<TMem>;
2185
- /** Retrieval pipeline configuration. Requires vector index or knowledge graph. */
2186
- retrieval?: {
2187
- /** Max candidates from vector search (default 20). */
2188
- topK?: number;
2189
- /** KG expansion depth in hops (default 1). */
2190
- graphDepth?: number;
2191
- };
2192
- /** Periodic reflection/consolidation configuration. */
2193
- reflection?: {
2194
- /** Interval in ms between consolidation runs (default 300_000 = 5 min). */
2195
- interval?: number;
2196
- /** Enable/disable periodic reflection (default true when consolidateFn is available). */
2197
- enabled?: boolean;
2198
- };
2199
- };
2200
- type AgentMemoryGraph<TMem = unknown> = Graph & {
2201
- readonly distillBundle: DistillBundle<TMem>;
2202
- readonly compact: Node<Array<{
2203
- key: string;
2204
- value: TMem;
2205
- score: number;
2206
- }>>;
2207
- readonly size: Node<number>;
2208
- /** Vector index bundle (null if not enabled). */
2209
- readonly vectors: VectorIndexGraph<TMem> | null;
2210
- /** Knowledge graph (null if not enabled). */
2211
- readonly kg: KnowledgeGraph<unknown, string> | null;
2212
- /** Memory tiers bundle (null if not configured). */
2213
- readonly memoryTiers: MemoryTiersBundle<TMem> | null;
2214
- /** Retrieval result node (null if no retrieval pipeline configured). */
2215
- readonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;
2216
- /** Latest retrieval trace for observability (null if no retrieval pipeline). */
2217
- readonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;
2218
- /**
2219
- * Execute a retrieval query (null if no retrieval pipeline).
2220
- *
2221
- * **Synchronous consumer API** — returns the result immediately and batch-writes
2222
- * `retrieval` and `retrievalTrace` state nodes for observers. Reads the store
2223
- * snapshot and context value **at call time** (external-boundary read).
2224
- *
2225
- * **Do not call from inside a reactive fn body** (derived fn, subscribe callback,
2226
- * effect body). The cache reads would become transitive protocol violations and
2227
- * may observe wave-progressive rather than wave-final state.
2228
- *
2229
- * **Caller-batch caveat:** if invoked inside a caller's `batch(() => ...)` alongside
2230
- * upstream store mutations, the store snapshot reflects what has been committed to
2231
- * `store.entries.cache` at call time. State-backed stores update cache synchronously
2232
- * so batched inserts are visible; derived-backed store transforms may defer. If you
2233
- * need fresh state after batched mutations, call `retrieve` after the batch returns.
2234
- */
2235
- readonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;
2236
- /**
2237
- * Reactive sibling of {@link retrieve}. Given a reactive
2238
- * `RetrievalQuery | null` source, returns a `Node` emitting the packed
2239
- * retrieval results. Composable with graph topology — subscribe it,
2240
- * chain it into `promptNode`, or switchMap over a user-input node.
2241
- * Null when no retrieval pipeline is configured.
2242
- */
2243
- readonly retrieveReactive: ((queryInput: NodeInput<RetrievalQuery | null>) => Node<ReadonlyArray<RetrievalEntry<TMem>>>) | null;
2244
- };
2245
- /**
2246
- * Pre-wired agentic memory graph. Sugar over `distill` plus the
2247
- * `memoryWithVectors` / `memoryWithKG` / `memoryWithTiers` / `memoryRetrieval`
2248
- * composers. Power users who want a subset of capabilities can call those
2249
- * composers directly; this factory bundles them into one ergonomic call.
2250
- */
2251
- declare function agentMemory<TMem = unknown>(name: string, source: NodeInput<unknown>, opts: AgentMemoryOptions<TMem>): AgentMemoryGraph<TMem>;
2252
-
2253
- type GaugesAsContextOptions = {
2254
- /** Group gauges by `meta.tags` (default true). */
2255
- groupByTags?: boolean;
2256
- /** Separator between gauge lines (default "\n"). */
2257
- separator?: string;
2258
- /**
2259
- * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds
2260
- * the corresponding entry in this map. Nodes without V0 or not in the
2261
- * map are always included. Callers maintain this map across calls.
2262
- *
2263
- * The `id` field guards against node replacement: if a node is removed
2264
- * and re-added under the same name (new id), it is always included.
2265
- */
2266
- sinceVersion?: ReadonlyMap<string, {
2267
- id: string;
2268
- version: number;
2269
- }>;
2270
- };
2271
- /**
2272
- * Format a graph's readable (gauge) nodes as a context string for LLM
2273
- * system prompts.
2274
- *
2275
- * Gauges are nodes with `meta.description` or `meta.format`. Values are
2276
- * formatted using `meta.format` and `meta.unit` hints.
2277
- *
2278
- * @param graph - The graph to introspect.
2279
- * @param actor - Optional actor for guard-scoped describe.
2280
- * @param options - Formatting options.
2281
- * @returns A formatted string ready for system prompt injection.
2282
- */
2283
- declare function gaugesAsContext(graph: Graph, actor?: Actor, options?: GaugesAsContextOptions): string;
2284
-
2285
- type GraphFromSpecOptions = {
2286
- model?: string;
2287
- temperature?: number;
2288
- maxTokens?: number;
2289
- /** Fn/source catalog for resolving named node factories from the LLM-generated spec. */
2290
- catalog?: GraphSpecCatalog;
2291
- /** Extra instructions appended to the system prompt. */
2292
- systemPromptExtra?: string;
2293
- /**
2294
- * Optional AbortSignal forwarded to `adapter.invoke({ signal })`. Lets
2295
- * callers cancel the in-flight LLM call (e.g. when the reactive variant
2296
- * supersedes mid-flight). When the signal aborts, the underlying call
2297
- * propagates the abort and `graphFromSpec` rejects with the abort reason.
2298
- */
2299
- signal?: AbortSignal;
2300
- };
2301
- /**
2302
- * Ask an LLM to compose a Graph from a natural-language description.
2303
- *
2304
- * The LLM returns a JSON {@link GraphSpec} which is validated, catalog-expanded,
2305
- * and instantiated via {@link compileSpec} (gains catalog validation, template
2306
- * expansion, and feedback wiring that `Graph.fromSnapshot` bypasses).
2307
- *
2308
- * @param naturalLanguage - The problem/use-case description.
2309
- * @param adapter - LLM adapter for the generation call.
2310
- * @param opts - Model options and optional catalog for named node factories.
2311
- * @returns A constructed Graph.
2312
- * @throws On invalid LLM output, validation failure, or unresolvable deps.
2313
- */
2314
- declare function graphFromSpec(naturalLanguage: string, adapter: LLMAdapter, opts?: GraphFromSpecOptions): Promise<Graph>;
2315
- /**
2316
- * Reactive variant of {@link graphFromSpec}: re-invokes the LLM and
2317
- * recompiles the graph whenever `input` emits a new natural-language
2318
- * description. Useful inside the harness or refine loop when the spec text
2319
- * itself is a reactive value (e.g. fed by a `state(...)` knob, a memory
2320
- * snapshot, or an upstream `promptNode` output).
2321
- *
2322
- * **Supersede:** when the input changes mid-flight, switchMap tears the
2323
- * inner producer down. The producer's cleanup aborts the in-flight LLM
2324
- * call via an internal `AbortController` (threaded into `graphFromSpec`'s
2325
- * new `signal` option) AND destroys any Graph that lands after cancel —
2326
- * no token leak, no unreferenced compiled graphs. If the user's input
2327
- * already changed by the time the LLM responds, the about-to-be-discarded
2328
- * Graph is freed instead of orphaned.
2329
- *
2330
- * **Lifetime of the latest emitted Graph:** the caller owns each Graph
2331
- * that actually reaches them. If you keep multiple historical values, call
2332
- * `prev?.destroy()` before storing the new one.
2333
- *
2334
- * @param input - Reactive source of natural-language descriptions.
2335
- * @param adapter - LLM adapter for the generation call.
2336
- * @param opts - Model options and optional catalog for named node factories.
2337
- * @returns `Node<Graph | null>` — emits the latest compiled graph, or `null`
2338
- * while the input is empty / unsettled.
2339
- */
2340
- declare function graphFromSpecReactive(input: NodeInput<string>, adapter: LLMAdapter, opts?: GraphFromSpecOptions): Node<Graph | null>;
2341
-
2342
- /** OpenAI function-calling tool schema. */
2343
- type OpenAIToolSchema = {
2344
- readonly type: "function";
2345
- readonly function: {
2346
- readonly name: string;
2347
- readonly description: string;
2348
- readonly parameters: Record<string, unknown>;
2349
- };
2350
- };
2351
- /** MCP (Model Context Protocol) tool schema. */
2352
- type McpToolSchema = {
2353
- readonly name: string;
2354
- readonly description: string;
2355
- readonly inputSchema: Record<string, unknown>;
2356
- };
2357
- /** Result of {@link knobsAsTools}. */
2358
- type KnobsAsToolsResult = {
2359
- /** OpenAI function-calling tool schemas. */
2360
- readonly openai: readonly OpenAIToolSchema[];
2361
- /** MCP tool schemas. */
2362
- readonly mcp: readonly McpToolSchema[];
2363
- /** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */
2364
- readonly definitions: readonly ToolDefinition[];
2365
- };
2366
- /**
2367
- * Derive tool schemas from a graph's writable (knob) nodes.
2368
- *
2369
- * Knobs are state nodes whose `meta.access` is `"llm"`, `"both"`, or absent
2370
- * (default: writable). Each knob becomes a tool that calls `graph.set()`.
2371
- *
2372
- * Speaks **domain language** (spec §5.4): the returned schemas use node names
2373
- * and meta descriptions — no protocol internals exposed.
2374
- *
2375
- * @param graph - The graph to introspect.
2376
- * @param actor - Optional actor for guard-scoped describe.
2377
- * @returns OpenAI, MCP, and GraphReFly tool schemas.
2378
- */
2379
- declare function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult;
2380
-
2381
- /** A single operation in a strategy plan. */
2382
- type StrategyOperation = {
2383
- readonly type: "add_node";
2384
- readonly name: string;
2385
- readonly nodeType: string;
2386
- readonly meta?: Record<string, unknown>;
2387
- readonly initial?: unknown;
2388
- } | {
2389
- readonly type: "remove_node";
2390
- readonly name: string;
2391
- } | {
2392
- readonly type: "connect";
2393
- readonly from: string;
2394
- readonly to: string;
2395
- } | {
2396
- readonly type: "disconnect";
2397
- readonly from: string;
2398
- readonly to: string;
2399
- } | {
2400
- readonly type: "set_value";
2401
- readonly name: string;
2402
- readonly value: unknown;
2403
- } | {
2404
- readonly type: "update_meta";
2405
- readonly name: string;
2406
- readonly key: string;
2407
- readonly value: unknown;
2408
- };
2409
- /** Structured strategy plan returned by {@link suggestStrategy}. */
2410
- type StrategyPlan = {
2411
- readonly summary: string;
2412
- readonly operations: readonly StrategyOperation[];
2413
- readonly reasoning: string;
2414
- };
2415
- type SuggestStrategyOptions = {
2416
- model?: string;
2417
- temperature?: number;
2418
- maxTokens?: number;
2419
- actor?: Actor;
2420
- /**
2421
- * Optional AbortSignal forwarded to `adapter.invoke({ signal })`. Lets
2422
- * callers cancel the in-flight LLM call (e.g. when the reactive variant
2423
- * supersedes mid-flight). When the signal aborts, the underlying call
2424
- * propagates the abort and `suggestStrategy` rejects with the abort reason.
2425
- */
2426
- signal?: AbortSignal;
2427
- };
2428
- /**
2429
- * Ask an LLM to analyze a graph and suggest topology/parameter changes
2430
- * to solve a stated problem.
2431
- *
2432
- * Returns a structured plan — does NOT auto-apply. The caller reviews
2433
- * and selectively applies operations.
2434
- *
2435
- * @param graph - The graph to analyze.
2436
- * @param problem - Natural-language problem statement.
2437
- * @param adapter - LLM adapter for the analysis call.
2438
- * @param opts - Model and actor options.
2439
- * @returns A structured strategy plan.
2440
- * @throws On invalid LLM output.
2441
- */
2442
- declare function suggestStrategy(graph: Graph, problem: string, adapter: LLMAdapter, opts?: SuggestStrategyOptions): Promise<StrategyPlan>;
2443
- /**
2444
- * Reactive variant of {@link suggestStrategy}: re-invokes the LLM whenever
2445
- * the `problem` source emits, sampling the latest `graph` value (via
2446
- * `withLatestFrom`) to describe. The graph is the *secondary* dep — only
2447
- * problem changes re-trigger analysis. This breaks the feedback cycle that
2448
- * would otherwise arise if downstream consumers wired `apply(plan)` back
2449
- * into the same graph node (graph mutation must not auto-fire a re-analysis).
2450
- *
2451
- * @param graph - Reactive source of graphs to analyze.
2452
- * @param problem - Reactive source of natural-language problem statements.
2453
- * @param adapter - LLM adapter for the analysis call.
2454
- * @param opts - Model and actor options.
2455
- * @returns `Node<StrategyPlan | null>` — emits the latest plan, or `null`
2456
- * while inputs are unsettled.
2457
- */
2458
- declare function suggestStrategyReactive(graph: Node<Graph | null>, problem: NodeInput<string>, adapter: LLMAdapter, opts?: SuggestStrategyOptions): Node<StrategyPlan | null>;
2459
-
2460
- /** Validation result from {@link validateGraphDef}. */
2461
- type GraphDefValidation = {
2462
- readonly valid: boolean;
2463
- readonly errors: readonly string[];
2464
- };
2465
- /**
2466
- * Validate an LLM-generated graph definition before passing to
2467
- * `Graph.fromSnapshot()`.
2468
- *
2469
- * Checks:
2470
- * - Required fields: `name`, `nodes`, `edges`
2471
- * - Node types are valid enum values
2472
- * - Edge `from`/`to` reference existing nodes
2473
- * - No duplicate edge entries
2474
- *
2475
- * @param def - The graph definition to validate (parsed JSON).
2476
- * @returns Validation result with errors array.
2477
- */
2478
- declare function validateGraphDef(def: unknown): GraphDefValidation;
2479
-
2480
- /**
2481
- * AI surface patterns (roadmap §4.4).
2482
- *
2483
- * Domain-layer factories for LLM-backed agents, chat, tool registries, and
2484
- * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.
2485
- *
2486
- * This file is the public barrel — it re-exports symbols from the sibling
2487
- * folders (`prompts/`, `extractors/`, `safety/`, `agents/`, `memory/`,
2488
- * `graph-integration/`, and the existing `adapters/` tree). No implementation
2489
- * code lives here; see each sibling folder for the actual primitives.
2490
- *
2491
- * @module
2492
- */
2493
-
2494
- declare const index_AdapterProvider: typeof AdapterProvider;
2495
- type index_AdapterStats = AdapterStats;
2496
- declare const index_AdapterTier: typeof AdapterTier;
2497
- type index_AdmissionScore3DOptions = AdmissionScore3DOptions;
2498
- type index_AdmissionScoredOptions<Dims extends string, TRaw = unknown> = AdmissionScoredOptions<Dims, TRaw>;
2499
- type index_AdmissionScores = AdmissionScores;
2500
- type index_AdmissionThresholds<Dims extends string> = AdmissionThresholds<Dims>;
2501
- type index_AgentLoopGraph = AgentLoopGraph;
2502
- declare const index_AgentLoopGraph: typeof AgentLoopGraph;
2503
- type index_AgentLoopOptions = AgentLoopOptions;
2504
- type index_AgentLoopStatus = AgentLoopStatus;
2505
- type index_AgentMemoryGraph<TMem = unknown> = AgentMemoryGraph<TMem>;
2506
- type index_AgentMemoryOptions<TMem = unknown> = AgentMemoryOptions<TMem>;
2507
- declare const index_AllTiersExhaustedError: typeof AllTiersExhaustedError;
2508
- type index_AnthropicAdapterOptions = AnthropicAdapterOptions;
2509
- type index_AnthropicSdkLike = AnthropicSdkLike;
2510
- type index_BudgetCaps = BudgetCaps;
2511
- type index_BudgetExhaustedError = BudgetExhaustedError;
2512
- declare const index_BudgetExhaustedError: typeof BudgetExhaustedError;
2513
- type index_BudgetGateBundle = BudgetGateBundle;
2514
- type index_BudgetTotals = BudgetTotals;
2515
- type index_CallStatsEvent = CallStatsEvent;
2516
- declare const index_CapabilitiesRegistry: typeof CapabilitiesRegistry;
2517
- declare const index_CascadeExhaustionReport: typeof CascadeExhaustionReport;
2518
- declare const index_CascadingLlmAdapterOptions: typeof CascadingLlmAdapterOptions;
2519
- declare const index_ChatMessage: typeof ChatMessage;
2520
- type index_ChatStreamGraph = ChatStreamGraph;
2521
- declare const index_ChatStreamGraph: typeof ChatStreamGraph;
2522
- type index_ChatStreamOptions = ChatStreamOptions;
2523
- declare const index_CircuitOpenError: typeof CircuitOpenError;
2524
- type index_ContentDecision = ContentDecision;
2525
- type index_ContentGateOptions = ContentGateOptions;
2526
- type index_CostMeterOptions = CostMeterOptions;
2527
- type index_CostMeterReading = CostMeterReading;
2528
- declare const index_CreateAdapterOptions: typeof CreateAdapterOptions;
2529
- declare const index_DEFAULT_DECAY_RATE: typeof DEFAULT_DECAY_RATE;
2530
- type index_DryRunAdapterOptions = DryRunAdapterOptions;
2531
- type index_ExtractedToolCall = ExtractedToolCall;
2532
- declare const index_FallbackAdapterOptions: typeof FallbackAdapterOptions;
2533
- declare const index_FallbackFixture: typeof FallbackFixture;
2534
- declare const index_FallbackMissError: typeof FallbackMissError;
2535
- declare const index_FallbackMissPolicy: typeof FallbackMissPolicy;
2536
- type index_FrozenContextOptions = FrozenContextOptions;
2537
- type index_GatedStreamHandle<T> = GatedStreamHandle<T>;
2538
- type index_GatedStreamOptions = GatedStreamOptions;
2539
- type index_GaugesAsContextOptions = GaugesAsContextOptions;
2540
- type index_GoogleAdapterOptions = GoogleAdapterOptions;
2541
- type index_GoogleSdkLike = GoogleSdkLike;
2542
- type index_GoogleSdkRequestConfig = GoogleSdkRequestConfig;
2543
- type index_GoogleSdkRequestParams = GoogleSdkRequestParams;
2544
- type index_GraphDefValidation = GraphDefValidation;
2545
- type index_GraphFromSpecOptions = GraphFromSpecOptions;
2546
- type index_HandoffOptions = HandoffOptions;
2547
- type index_HttpErrorLike = HttpErrorLike;
2548
- type index_KeywordFlag = KeywordFlag;
2549
- type index_KeywordFlagExtractorOptions = KeywordFlagExtractorOptions;
2550
- type index_KnobsAsToolsResult = KnobsAsToolsResult;
2551
- declare const index_LLMAdapter: typeof LLMAdapter;
2552
- type index_LLMConsolidatorOptions = LLMConsolidatorOptions;
2553
- type index_LLMExtractorOptions = LLMExtractorOptions;
2554
- declare const index_LLMInvokeOptions: typeof LLMInvokeOptions;
2555
- declare const index_LLMResponse: typeof LLMResponse;
2556
- type index_LLMTimeoutError = LLMTimeoutError;
2557
- declare const index_LLMTimeoutError: typeof LLMTimeoutError;
2558
- type index_McpToolSchema = McpToolSchema;
2559
- type index_MemoryRetrievalBundle<TMem> = MemoryRetrievalBundle<TMem>;
2560
- type index_MemoryRetrievalOptions<TMem> = MemoryRetrievalOptions<TMem>;
2561
- type index_MemoryTier = MemoryTier;
2562
- type index_MemoryTiersBundle<TMem> = MemoryTiersBundle<TMem>;
2563
- type index_MemoryTiersOptions<TMem> = MemoryTiersOptions<TMem>;
2564
- type index_MemoryWithKGOptions<TMem> = MemoryWithKGOptions<TMem>;
2565
- type index_MemoryWithTiersOptions<TMem> = MemoryWithTiersOptions<TMem>;
2566
- type index_MemoryWithVectorsOptions<TMem> = MemoryWithVectorsOptions<TMem>;
2567
- declare const index_ModelCapabilities: typeof ModelCapabilities;
2568
- declare const index_ModelFeatures: typeof ModelFeatures;
2569
- declare const index_ModelLimits: typeof ModelLimits;
2570
- declare const index_ModelPricing: typeof ModelPricing;
2571
- declare const index_OpenAICompatAdapterOptions: typeof OpenAICompatAdapterOptions;
2572
- declare const index_OpenAICompatPreset: typeof OpenAICompatPreset;
2573
- declare const index_OpenAISdkLike: typeof OpenAISdkLike;
2574
- type index_OpenAIToolSchema = OpenAIToolSchema;
2575
- declare const index_PriceBreakdown: typeof PriceBreakdown;
2576
- declare const index_PricingFn: typeof PricingFn;
2577
- declare const index_PricingRegistry: typeof PricingRegistry;
2578
- type index_PromptCallOptions = PromptCallOptions;
2579
- type index_PromptNodeOptions = PromptNodeOptions;
2580
- declare const index_Rate: typeof Rate;
2581
- type index_RedactorOptions = RedactorOptions;
2582
- declare const index_ReplayCacheKeyContext: typeof ReplayCacheKeyContext;
2583
- declare const index_ReplayCacheMissError: typeof ReplayCacheMissError;
2584
- declare const index_ReplayCacheMode: typeof ReplayCacheMode;
2585
- type index_ResilientAdapterBundle = ResilientAdapterBundle;
2586
- type index_ResilientAdapterOptions = ResilientAdapterOptions;
2587
- type index_RetrievalEntry<TMem> = RetrievalEntry<TMem>;
2588
- type index_RetrievalPipelineOptions<TMem> = RetrievalPipelineOptions<TMem>;
2589
- type index_RetrievalQuery = RetrievalQuery;
2590
- type index_RetrievalTrace<TMem> = RetrievalTrace<TMem>;
2591
- type index_StampedDelta = StampedDelta;
2592
- type index_StrategyOperation = StrategyOperation;
2593
- type index_StrategyPlan = StrategyPlan;
2594
- declare const index_StreamDelta: typeof StreamDelta;
2595
- type index_StreamingPromptNodeHandle<T> = StreamingPromptNodeHandle<T>;
2596
- type index_StreamingPromptNodeOptions = StreamingPromptNodeOptions;
2597
- type index_SuggestStrategyOptions = SuggestStrategyOptions;
2598
- type index_SystemPromptHandle = SystemPromptHandle;
2599
- declare const index_TieredRate: typeof TieredRate;
2600
- declare const index_TokenUsage: typeof TokenUsage;
2601
- declare const index_ToolCall: typeof ToolCall;
2602
- declare const index_ToolDefinition: typeof ToolDefinition;
2603
- type index_ToolExecutionOptions = ToolExecutionOptions;
2604
- type index_ToolRegistryGraph = ToolRegistryGraph;
2605
- declare const index_ToolRegistryGraph: typeof ToolRegistryGraph;
2606
- type index_ToolRegistryOptions = ToolRegistryOptions;
2607
- type index_ToolResult = ToolResult;
2608
- type index_ToolSelectorOptions = ToolSelectorOptions;
2609
- type index_WithBreakerOptions = WithBreakerOptions;
2610
- type index_WithBudgetGateOptions = WithBudgetGateOptions;
2611
- type index_WithDryRunBundle = WithDryRunBundle;
2612
- type index_WithDryRunOptions = WithDryRunOptions;
2613
- type index_WithRateLimiterOptions = WithRateLimiterOptions;
2614
- declare const index_WithReplayCacheOptions: typeof WithReplayCacheOptions;
2615
- type index_WithRetryOptions = WithRetryOptions;
2616
- declare const index_admissionFilter3D: typeof admissionFilter3D;
2617
- declare const index_admissionScored: typeof admissionScored;
2618
- declare const index_agentLoop: typeof agentLoop;
2619
- declare const index_agentMemory: typeof agentMemory;
2620
- declare const index_anthropicAdapter: typeof anthropicAdapter;
2621
- declare const index_canonicalJson: typeof canonicalJson;
2622
- declare const index_cascadingLlmAdapter: typeof cascadingLlmAdapter;
2623
- declare const index_chatStream: typeof chatStream;
2624
- declare const index_composePricing: typeof composePricing;
2625
- declare const index_computePrice: typeof computePrice;
2626
- declare const index_contentGate: typeof contentGate;
2627
- declare const index_costMeterExtractor: typeof costMeterExtractor;
2628
- declare const index_createAdapter: typeof createAdapter;
2629
- declare const index_createCapabilitiesRegistry: typeof createCapabilitiesRegistry;
2630
- declare const index_createPricingRegistry: typeof createPricingRegistry;
2631
- declare const index_dryRunAdapter: typeof dryRunAdapter;
2632
- declare const index_fallbackAdapter: typeof fallbackAdapter;
2633
- declare const index_frozenContext: typeof frozenContext;
2634
- declare const index_gatedStream: typeof gatedStream;
2635
- declare const index_gaugesAsContext: typeof gaugesAsContext;
2636
- declare const index_googleAdapter: typeof googleAdapter;
2637
- declare const index_graphFromSpec: typeof graphFromSpec;
2638
- declare const index_graphFromSpecReactive: typeof graphFromSpecReactive;
2639
- declare const index_handoff: typeof handoff;
2640
- declare const index_keywordFlagExtractor: typeof keywordFlagExtractor;
2641
- declare const index_knobsAsTools: typeof knobsAsTools;
2642
- declare const index_llmConsolidator: typeof llmConsolidator;
2643
- declare const index_llmExtractor: typeof llmExtractor;
2644
- declare const index_memoryRetrieval: typeof memoryRetrieval;
2645
- declare const index_memoryWithKG: typeof memoryWithKG;
2646
- declare const index_memoryWithTiers: typeof memoryWithTiers;
2647
- declare const index_memoryWithVectors: typeof memoryWithVectors;
2648
- declare const index_observableAdapter: typeof observableAdapter;
2649
- declare const index_openAICompatAdapter: typeof openAICompatAdapter;
2650
- declare const index_parseRateLimitFromError: typeof parseRateLimitFromError;
2651
- declare const index_pricingFor: typeof pricingFor;
2652
- declare const index_promptCall: typeof promptCall;
2653
- declare const index_promptNode: typeof promptNode;
2654
- declare const index_redactor: typeof redactor;
2655
- declare const index_registryPricing: typeof registryPricing;
2656
- declare const index_resilientAdapter: typeof resilientAdapter;
2657
- declare const index_streamExtractor: typeof streamExtractor;
2658
- declare const index_streamingPromptNode: typeof streamingPromptNode;
2659
- declare const index_suggestStrategy: typeof suggestStrategy;
2660
- declare const index_suggestStrategyReactive: typeof suggestStrategyReactive;
2661
- declare const index_systemPromptBuilder: typeof systemPromptBuilder;
2662
- declare const index_tier: typeof tier;
2663
- declare const index_toolCallExtractor: typeof toolCallExtractor;
2664
- declare const index_toolExecution: typeof toolExecution;
2665
- declare const index_toolRegistry: typeof toolRegistry;
2666
- declare const index_toolSelector: typeof toolSelector;
2667
- declare const index_validateGraphDef: typeof validateGraphDef;
2668
- declare const index_withBreaker: typeof withBreaker;
2669
- declare const index_withBudgetGate: typeof withBudgetGate;
2670
- declare const index_withDryRun: typeof withDryRun;
2671
- declare const index_withRateLimiter: typeof withRateLimiter;
2672
- declare const index_withReplayCache: typeof withReplayCache;
2673
- declare const index_withRetry: typeof withRetry;
2674
- declare const index_withTimeout: typeof withTimeout;
2675
- declare const index_zeroPrice: typeof zeroPrice;
2676
- declare namespace index {
2677
- export { index_AdapterProvider as AdapterProvider, type index_AdapterStats as AdapterStats, index_AdapterTier as AdapterTier, type index_AdmissionScore3DOptions as AdmissionScore3DOptions, type index_AdmissionScoredOptions as AdmissionScoredOptions, type index_AdmissionScores as AdmissionScores, type index_AdmissionThresholds as AdmissionThresholds, index_AgentLoopGraph as AgentLoopGraph, type index_AgentLoopOptions as AgentLoopOptions, type index_AgentLoopStatus as AgentLoopStatus, type index_AgentMemoryGraph as AgentMemoryGraph, type index_AgentMemoryOptions as AgentMemoryOptions, index_AllTiersExhaustedError as AllTiersExhaustedError, type index_AnthropicAdapterOptions as AnthropicAdapterOptions, type index_AnthropicSdkLike as AnthropicSdkLike, type index_BudgetCaps as BudgetCaps, index_BudgetExhaustedError as BudgetExhaustedError, type index_BudgetGateBundle as BudgetGateBundle, type index_BudgetTotals as BudgetTotals, type index_CallStatsEvent as CallStatsEvent, index_CapabilitiesRegistry as CapabilitiesRegistry, index_CascadeExhaustionReport as CascadeExhaustionReport, index_CascadingLlmAdapterOptions as CascadingLlmAdapterOptions, index_ChatMessage as ChatMessage, index_ChatStreamGraph as ChatStreamGraph, type index_ChatStreamOptions as ChatStreamOptions, index_CircuitOpenError as CircuitOpenError, type index_ContentDecision as ContentDecision, type index_ContentGateOptions as ContentGateOptions, type index_CostMeterOptions as CostMeterOptions, type index_CostMeterReading as CostMeterReading, index_CreateAdapterOptions as CreateAdapterOptions, index_DEFAULT_DECAY_RATE as DEFAULT_DECAY_RATE, type index_DryRunAdapterOptions as DryRunAdapterOptions, type index_ExtractedToolCall as ExtractedToolCall, index_FallbackAdapterOptions as FallbackAdapterOptions, index_FallbackFixture as FallbackFixture, index_FallbackMissError as FallbackMissError, index_FallbackMissPolicy as FallbackMissPolicy, type index_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_GoogleSdkRequestConfig as GoogleSdkRequestConfig, type index_GoogleSdkRequestParams as GoogleSdkRequestParams, 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_MemoryRetrievalBundle as MemoryRetrievalBundle, type index_MemoryRetrievalOptions as MemoryRetrievalOptions, type index_MemoryTier as MemoryTier, type index_MemoryTiersBundle as MemoryTiersBundle, type index_MemoryTiersOptions as MemoryTiersOptions, type index_MemoryWithKGOptions as MemoryWithKGOptions, type index_MemoryWithTiersOptions as MemoryWithTiersOptions, type index_MemoryWithVectorsOptions as MemoryWithVectorsOptions, 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_PromptCallOptions as PromptCallOptions, 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_StampedDelta as StampedDelta, type index_StrategyOperation as StrategyOperation, type index_StrategyPlan as StrategyPlan, 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, type index_ToolExecutionOptions as ToolExecutionOptions, 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_admissionScored as admissionScored, 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_fallbackAdapter as fallbackAdapter, index_frozenContext as frozenContext, index_gatedStream as gatedStream, index_gaugesAsContext as gaugesAsContext, index_googleAdapter as googleAdapter, index_graphFromSpec as graphFromSpec, index_graphFromSpecReactive as graphFromSpecReactive, index_handoff as handoff, index_keywordFlagExtractor as keywordFlagExtractor, index_knobsAsTools as knobsAsTools, index_llmConsolidator as llmConsolidator, index_llmExtractor as llmExtractor, index_memoryRetrieval as memoryRetrieval, index_memoryWithKG as memoryWithKG, index_memoryWithTiers as memoryWithTiers, index_memoryWithVectors as memoryWithVectors, index_observableAdapter as observableAdapter, index_openAICompatAdapter as openAICompatAdapter, index_parseRateLimitFromError as parseRateLimitFromError, index_pricingFor as pricingFor, index_promptCall as promptCall, 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_suggestStrategyReactive as suggestStrategyReactive, index_systemPromptBuilder as systemPromptBuilder, index_tier as tier, index_toolCallExtractor as toolCallExtractor, index_toolExecution as toolExecution, 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 };
2678
- }
2679
-
2680
- export { type OpenAIToolSchema as $, type AdapterStats as A, type BudgetCaps as B, type CallStatsEvent as C, type DryRunAdapterOptions as D, type ExtractedToolCall as E, type FrozenContextOptions as F, type GatedStreamHandle as G, type GoogleSdkRequestParams as H, type GraphDefValidation as I, type GraphFromSpecOptions as J, type HandoffOptions as K, type HttpErrorLike as L, type KeywordFlag as M, type KeywordFlagExtractorOptions as N, type KnobsAsToolsResult as O, type LLMConsolidatorOptions as P, type LLMExtractorOptions as Q, LLMTimeoutError as R, type McpToolSchema as S, type MemoryRetrievalBundle as T, type MemoryRetrievalOptions as U, type MemoryTier as V, type MemoryTiersBundle as W, type MemoryTiersOptions as X, type MemoryWithKGOptions as Y, type MemoryWithTiersOptions as Z, type MemoryWithVectorsOptions as _, type AdmissionScore3DOptions as a, toolExecution as a$, type PromptCallOptions as a0, type PromptNodeOptions as a1, type RedactorOptions as a2, type ResilientAdapterBundle as a3, type ResilientAdapterOptions as a4, type RetrievalEntry as a5, type RetrievalPipelineOptions as a6, type RetrievalQuery as a7, type RetrievalTrace as a8, type StampedDelta as a9, frozenContext as aA, gatedStream as aB, gaugesAsContext as aC, googleAdapter as aD, graphFromSpec as aE, graphFromSpecReactive as aF, handoff as aG, keywordFlagExtractor as aH, knobsAsTools as aI, llmConsolidator as aJ, llmExtractor as aK, memoryRetrieval as aL, memoryWithKG as aM, memoryWithTiers as aN, memoryWithVectors as aO, observableAdapter as aP, parseRateLimitFromError as aQ, promptCall as aR, promptNode as aS, redactor as aT, resilientAdapter as aU, streamExtractor as aV, streamingPromptNode as aW, suggestStrategy as aX, suggestStrategyReactive as aY, systemPromptBuilder as aZ, toolCallExtractor as a_, type StrategyOperation as aa, type StrategyPlan as ab, type StreamingPromptNodeHandle as ac, type StreamingPromptNodeOptions as ad, type SuggestStrategyOptions as ae, type SystemPromptHandle as af, type ToolExecutionOptions as ag, ToolRegistryGraph as ah, type ToolRegistryOptions as ai, type ToolResult as aj, type ToolSelectorOptions as ak, type WithBreakerOptions as al, type WithBudgetGateOptions as am, type WithDryRunBundle as an, type WithDryRunOptions as ao, type WithRateLimiterOptions as ap, type WithRetryOptions as aq, admissionFilter3D as ar, admissionScored as as, agentLoop as at, agentMemory as au, anthropicAdapter as av, chatStream as aw, contentGate as ax, costMeterExtractor as ay, dryRunAdapter as az, type AdmissionScoredOptions as b, toolRegistry as b0, toolSelector as b1, validateGraphDef as b2, withBreaker as b3, withBudgetGate as b4, withDryRun as b5, withRateLimiter as b6, withRetry as b7, withTimeout as b8, type AdmissionScores as c, type AdmissionThresholds as d, AgentLoopGraph as e, type AgentLoopOptions as f, type AgentLoopStatus as g, type AgentMemoryGraph as h, index as i, type AgentMemoryOptions as j, type AnthropicAdapterOptions as k, type AnthropicSdkLike as l, BudgetExhaustedError as m, type BudgetGateBundle as n, type BudgetTotals as o, ChatStreamGraph as p, type ChatStreamOptions as q, type ContentDecision as r, type ContentGateOptions as s, type CostMeterOptions as t, type CostMeterReading as u, type GatedStreamOptions as v, type GaugesAsContextOptions as w, type GoogleAdapterOptions as x, type GoogleSdkLike as y, type GoogleSdkRequestConfig as z };