@graphrefly/graphrefly 0.43.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 (422) 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 -4
  59. package/dist/core/index.d.ts +1 -4
  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 -950
  83. package/dist/extra/operators.d.ts +1 -950
  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 -96
  155. package/dist/index.d.ts +45 -96
  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 -21
  167. package/dist/patterns/ai/index.d.ts +1 -21
  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 -14
  203. package/dist/patterns/harness/index.d.ts +1 -14
  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 -9
  233. package/dist/patterns/orchestration/index.d.ts +1 -9
  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 -1
  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-CH-_VwG9.d.cts +0 -199
  275. package/dist/cascading-OgKQZjsa.d.ts +0 -199
  276. package/dist/chunk-35JTVPOX.js +0 -1
  277. package/dist/chunk-3G5U5QNE.js +0 -5
  278. package/dist/chunk-3XDYJRYU.js +0 -1
  279. package/dist/chunk-4I45FVQS.js +0 -1
  280. package/dist/chunk-4VVTGLXJ.js +0 -1
  281. package/dist/chunk-4YAN45KM.js +0 -1
  282. package/dist/chunk-5QDBSZBV.js +0 -1
  283. package/dist/chunk-626TESAC.js +0 -3
  284. package/dist/chunk-6HOSXQKF.js +0 -1
  285. package/dist/chunk-6QZNQS5B.js +0 -1
  286. package/dist/chunk-C72GO4IZ.js +0 -1
  287. package/dist/chunk-CE72X3WO.js +0 -1
  288. package/dist/chunk-CK2E7BTU.js +0 -1
  289. package/dist/chunk-CLD3F4R5.js +0 -1
  290. package/dist/chunk-CUNIRONA.js +0 -1
  291. package/dist/chunk-D27JNOLZ.js +0 -1
  292. package/dist/chunk-D5RFJOZ2.js +0 -1
  293. package/dist/chunk-EBW4V6JN.js +0 -1
  294. package/dist/chunk-ESMPEKEV.js +0 -1
  295. package/dist/chunk-F3IGTWCQ.js +0 -1
  296. package/dist/chunk-F672GV32.js +0 -1
  297. package/dist/chunk-FDQGFWLF.js +0 -1
  298. package/dist/chunk-FG4TKHMC.js +0 -1
  299. package/dist/chunk-GPW2V3RE.js +0 -1
  300. package/dist/chunk-I7IGYPSL.js +0 -1
  301. package/dist/chunk-INQD2KRQ.js +0 -1
  302. package/dist/chunk-JNWRYDJN.js +0 -1
  303. package/dist/chunk-JQFH2DV6.js +0 -1
  304. package/dist/chunk-K2Q24F5T.js +0 -1
  305. package/dist/chunk-KGKJCHEK.js +0 -1
  306. package/dist/chunk-KRH66M4O.js +0 -1
  307. package/dist/chunk-KVV66NN2.js +0 -1
  308. package/dist/chunk-L6NSJVJZ.js +0 -1
  309. package/dist/chunk-LYCLF26R.js +0 -1
  310. package/dist/chunk-NNKJUORL.js +0 -1
  311. package/dist/chunk-NON4NLIC.js +0 -45
  312. package/dist/chunk-O2BLLH7M.js +0 -18
  313. package/dist/chunk-OCKEEPRJ.js +0 -2
  314. package/dist/chunk-OFZG3TB3.js +0 -9
  315. package/dist/chunk-OYJKFY7V.js +0 -1
  316. package/dist/chunk-P6C4WHZO.js +0 -5
  317. package/dist/chunk-PT7W5FCD.js +0 -5
  318. package/dist/chunk-Q4U3A3L5.js +0 -1
  319. package/dist/chunk-QE4IGY7I.js +0 -61
  320. package/dist/chunk-QYADASLV.js +0 -1
  321. package/dist/chunk-QYVXF7GW.js +0 -1
  322. package/dist/chunk-S3EEIPO7.js +0 -1
  323. package/dist/chunk-SUWT3ZON.js +0 -1
  324. package/dist/chunk-TPKQW72B.js +0 -1
  325. package/dist/chunk-TSOYJ743.js +0 -1
  326. package/dist/chunk-TZQPPQEQ.js +0 -1
  327. package/dist/chunk-V5A7M7RJ.js +0 -1
  328. package/dist/chunk-VIMF6LGM.js +0 -1
  329. package/dist/chunk-VJLMUKOI.js +0 -1
  330. package/dist/chunk-VN6RDSK2.js +0 -1
  331. package/dist/chunk-VNC3TMVY.js +0 -1
  332. package/dist/chunk-VOPGGIL7.js +0 -1
  333. package/dist/chunk-VQ4A6T2A.js +0 -1
  334. package/dist/chunk-XG62INFA.js +0 -1
  335. package/dist/chunk-Y4NI3X7O.js +0 -84
  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-2ZukgQ4o.d.cts +0 -112
  339. package/dist/decay-CdEBmDIs.d.ts +0 -112
  340. package/dist/fallback-CqYVLL6X.d.ts +0 -250
  341. package/dist/fallback-Ctlj2tMY.d.cts +0 -250
  342. package/dist/graph-7VguS7a4.d.ts +0 -1668
  343. package/dist/graph-C4SHb3Ly.d.cts +0 -1668
  344. package/dist/index-0rKFCVFp.d.cts +0 -557
  345. package/dist/index-B-i4_g3k.d.ts +0 -651
  346. package/dist/index-B5iz82A3.d.cts +0 -2655
  347. package/dist/index-BAOD98JD.d.cts +0 -754
  348. package/dist/index-BG0BN3PB.d.ts +0 -44
  349. package/dist/index-BJX94aud.d.cts +0 -34
  350. package/dist/index-BP8a88zx.d.ts +0 -385
  351. package/dist/index-BTQtTb_H.d.cts +0 -301
  352. package/dist/index-BVpm6noz.d.cts +0 -36
  353. package/dist/index-Bc41FuHp.d.cts +0 -291
  354. package/dist/index-BdGtBX-X.d.cts +0 -515
  355. package/dist/index-Bf7eqeSF.d.ts +0 -113
  356. package/dist/index-BiX1Nkgx.d.cts +0 -1844
  357. package/dist/index-BoLv_OfD.d.cts +0 -651
  358. package/dist/index-BojK2fwH.d.cts +0 -299
  359. package/dist/index-BsT7F2et.d.ts +0 -291
  360. package/dist/index-BwLvVVsy.d.cts +0 -189
  361. package/dist/index-C59mYFKp.d.ts +0 -121
  362. package/dist/index-C7O6r5fV.d.ts +0 -37
  363. package/dist/index-C9kSENB4.d.cts +0 -127
  364. package/dist/index-C9pjcz3l.d.cts +0 -209
  365. package/dist/index-CAC_rNzm.d.ts +0 -189
  366. package/dist/index-CCq87F7t.d.ts +0 -127
  367. package/dist/index-CDXc9zKM.d.cts +0 -26
  368. package/dist/index-CJK1JkYy.d.ts +0 -36
  369. package/dist/index-CLon-IWF.d.cts +0 -374
  370. package/dist/index-COD1kVoS.d.cts +0 -468
  371. package/dist/index-CPT7C_f1.d.ts +0 -374
  372. package/dist/index-CQG3D1cp.d.ts +0 -468
  373. package/dist/index-CZQXo5tH.d.ts +0 -209
  374. package/dist/index-CZjOhcBy.d.cts +0 -113
  375. package/dist/index-ChOyVLKm.d.cts +0 -86
  376. package/dist/index-CvrqGfNS.d.ts +0 -34
  377. package/dist/index-D-AEQVLo.d.ts +0 -2655
  378. package/dist/index-D4Y1cMG0.d.ts +0 -26
  379. package/dist/index-DBHK8O6H.d.ts +0 -301
  380. package/dist/index-DBevwHj_.d.ts +0 -515
  381. package/dist/index-DIOoAZUX.d.ts +0 -45
  382. package/dist/index-DSZ3ZCHF.d.ts +0 -3402
  383. package/dist/index-Dgs8zcj7.d.ts +0 -102
  384. package/dist/index-Dh_HJ82K.d.ts +0 -299
  385. package/dist/index-Dhc7a7Xo.d.cts +0 -102
  386. package/dist/index-Dmqp7KjD.d.ts +0 -86
  387. package/dist/index-Dn-wI9g4.d.ts +0 -231
  388. package/dist/index-Du7u1lSf.d.cts +0 -385
  389. package/dist/index-DwigL4lY.d.ts +0 -1844
  390. package/dist/index-DyR7eU5S.d.cts +0 -779
  391. package/dist/index-JZUPJIJy.d.ts +0 -779
  392. package/dist/index-K0_0eR8g.d.ts +0 -557
  393. package/dist/index-O16yXPK4.d.cts +0 -3402
  394. package/dist/index-O7fucFrU.d.cts +0 -121
  395. package/dist/index-RV_yDjOX.d.cts +0 -198
  396. package/dist/index-cm1GNcWE.d.ts +0 -754
  397. package/dist/index-f5IivDUX.d.cts +0 -37
  398. package/dist/index-hHcaFlJX.d.cts +0 -45
  399. package/dist/index-tJoTcnHh.d.cts +0 -231
  400. package/dist/index-wAzD9yVj.d.ts +0 -198
  401. package/dist/index-z96luz5O.d.cts +0 -44
  402. package/dist/meta-BgVAsg9j.d.ts +0 -102
  403. package/dist/meta-vE8bxW1E.d.cts +0 -102
  404. package/dist/node-ClS5yC-B.d.cts +0 -1347
  405. package/dist/node-ClS5yC-B.d.ts +0 -1347
  406. package/dist/observable-BsBzUrcI.d.ts +0 -36
  407. package/dist/observable-DLGPPtb8.d.cts +0 -36
  408. package/dist/pipeline-graph-DPqKDk59.d.cts +0 -137
  409. package/dist/pipeline-graph-loP57TBA.d.ts +0 -137
  410. package/dist/reactive-layout-Dsvob4zD.d.cts +0 -183
  411. package/dist/reactive-layout-v7KPvxoc.d.ts +0 -183
  412. package/dist/reactive-log-B00laMSQ.d.cts +0 -223
  413. package/dist/reactive-log-BezYsbA_.d.ts +0 -223
  414. package/dist/reactive-map-48mnZ-nu.d.cts +0 -296
  415. package/dist/reactive-map-BVVPdvmi.d.ts +0 -296
  416. package/dist/resilience-YIWPK4YC.js +0 -1
  417. package/dist/sugar-DLwvMr3F.d.ts +0 -223
  418. package/dist/sugar-DyVGtczU.d.cts +0 -223
  419. package/dist/topology-tree-BNGvuG82.d.ts +0 -25
  420. package/dist/topology-tree-BSdfSwMi.d.cts +0 -25
  421. package/dist/types-B1jDWVsM.d.cts +0 -442
  422. package/dist/types-DkzUUs0H.d.ts +0 -442
package/dist/index.cjs CHANGED
@@ -1,228 +1,21 @@
1
- "use strict";var Jm=Object.create;var Wn=Object.defineProperty;var Hu=Object.getOwnPropertyDescriptor;var Ym=Object.getOwnPropertyNames;var Qm=Object.prototype.hasOwnProperty;var zu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ar=t=>{throw TypeError(t)};var Xm=(t,e,n)=>e in t?Wn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Vu=(t,e)=>Wn(t,"name",{value:e,configurable:!0});var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{for(var n in e)Wn(t,n,{get:e[n],enumerable:!0})},Zm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ym(e))!Qm.call(t,o)&&o!==n&&Wn(t,o,{get:()=>e[o],enumerable:!(r=Hu(e,o))||r.enumerable});return t};var eg=t=>Zm(Wn({},"__esModule",{value:!0}),t);var Wu=t=>[,,,Jm(t?.[zu("metadata")]??null)],Uu=["class","method","getter","setter","accessor","field","value","get","set"],Or=t=>t!==void 0&&typeof t!="function"?Ar("Function expected"):t,tg=(t,e,n,r,o)=>({kind:Uu[t],name:e,metadata:r,addInitializer:s=>n._?Ar("Already initialized"):o.push(Or(s||null))}),ng=(t,e)=>Xm(e,zu("metadata"),t[3]),Ju=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},Yu=(t,e,n,r,o,s)=>{var i,a,d,u,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=Uu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&Hu(l<4?o:{get[n](){return Ku(this,s)},set[n](T){return qu(this,s,T)}},n));l?f&&l<4&&Vu(s,(l>2?"set ":l>1?"get ":"")+n):Vu(o,n);for(var v=r.length-1;v>=0;v--)u=tg(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>rg(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Ku:og)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>qu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,u),d._=1,l^4||a===void 0?Or(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?Ar("Object expected"):(Or(i=a.get)&&(b.get=i),Or(i=a.set)&&(b.set=i),Or(i=a.init)&&g.unshift(i));return l||ng(t,o),b&&Wn(o,n,b),f?l^4?s:b:o};var ya=(t,e,n)=>e.has(t)||Ar("Cannot "+n),rg=(t,e)=>Object(e)!==e?Ar('Cannot use the "in" operator on this value'):t.has(e),Ku=(t,e,n)=>(ya(t,e,"read from private field"),n?n.call(t):e.get(t));var qu=(t,e,n,r)=>(ya(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),og=(t,e,n)=>(ya(t,e,"access private method"),n);var mt,_,oe,z,nt,qe,Je,fe,I,L,Dt,Un,Jo,Jn,Yo,Qo,Yn,Cr,Lr,Ir,Qn,se=be(()=>{"use strict";mt=Symbol.for("graphrefly/START"),_=Symbol.for("graphrefly/DATA"),oe=Symbol.for("graphrefly/DIRTY"),z=Symbol.for("graphrefly/RESOLVED"),nt=Symbol.for("graphrefly/INVALIDATE"),qe=Symbol.for("graphrefly/PAUSE"),Je=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),I=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),Dt=Object.freeze([oe]),Un=Object.freeze([z]),Jo=Object.freeze([nt]),Jn=Object.freeze([mt]),Yo=Object.freeze([I]),Qo=Object.freeze([fe]),Yn=Object.freeze([Dt]),Cr=Object.freeze([Un]),Lr=Object.freeze([Jo]),Ir=Object.freeze([Yo]),Qn=Object.freeze([Qo])});function ba(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function va(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function Pr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Xn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Dr(t,e){if(t.length<Qu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Qu})`);let n=0,r=t[n++];if(r!==Xn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Xn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Gr(t){t.registerCodec(Xo)}function Ta(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let d of i.nodesRemoved)delete n.nodes[d];let a=i.nodesAddedFull;if(a!=null)for(let[d,u]of Object.entries(a))n.nodes[d]=JSON.parse(JSON.stringify(u));for(let d of i.nodesChanged){let u=n.nodes[d.path];u!=null&&(u[d.field]=d.to)}r=s.seq}return n}var Xo,Xn,Qu,Zo=be(()=>{"use strict";Xo={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}};Xn=1,Qu=4});function Gt(t){if(t==null)return Ot;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Ot,Fr=be(()=>{"use strict";Ot={type:"system",id:""}});function vn(){return Zn>0||$r}function Xu(){return Zn>0}function tr(t){Zn>0?jr.push(t):t()}function Z(t){Zn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Zn-=1,Zn===0)if(e){if(!$r){let n=jr.splice(0);for(let r of n)try{r()}catch{}yn.length=0,bn.length=0,er.length=0}}else sg()}}function sg(){let t=!$r;t&&($r=!0);let e=[],n=0;try{for(;yn.length>0||bn.length>0||er.length>0||t&&jr.length>0;){if(t&&jr.length>0){let s=jr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw yn.length=0,bn.length=0,er.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(yn.length>0?yn:bn.length>0?bn:er).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&($r=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ft(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!vn()){t(e);return}(u>=5?er:u===4?bn:yn).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=vn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?yn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?bn.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?er.push(()=>t(u)):t(u)}}var Zn,$r,yn,bn,er,jr,Oe=be(()=>{"use strict";Zn=0,$r=!1,yn=[],bn=[],er=[],jr=[]});function W(){return Math.trunc(performance.now()*1e6)}function ie(){return Date.now()*1e6}var Re=be(()=>{"use strict"});function Br(t){t.registerMessageType(mt,{tier:0,wireCrossing:!1}),t.registerMessageType(oe,{tier:1,wireCrossing:!1}),t.registerMessageType(nt,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(qe,{tier:2,wireCrossing:!1}),t.registerMessageType(Je,{tier:2,wireCrossing:!1}),t.registerMessageType(_,{tier:3,wireCrossing:!0}),t.registerMessageType(z,{tier:3,wireCrossing:!0}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Tn,wa=be(()=>{"use strict";se();Tn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Zu(t){return Array.isArray(t)?[...t]:[t]}function ig(t,e){return t.has(e)||t.has("*")}function $t(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Zu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Zu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)ig(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Vr(t){return $t((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=d=>{if(o!==null&&!o.has(String(d.type))||s!==null&&!s.has(String(d.id??"")))return!1;for(let[u,c]of i)if(d[u]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Kr(t){let e=ag.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var ct,ag,Jt=be(()=>{"use strict";ct=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};ag=["human","llm","wallet","system"]});function ka(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(ka);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=ka(t[n]);return e}return null}function cg(t){let e=ug.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let E=0;E<16;E++)h[E]=i.getUint32(b+E*4,!1);for(let E=16;E<64;E++){let P=h[E-15],M=h[E-2],C=g(P,7)^g(P,18)^P>>>3,$=g(M,17)^g(M,19)^M>>>10;h[E]=h[E-16]+C+h[E-7]+$>>>0}let v=a,T=d,w=u,k=c,R=l,S=p,x=f,N=m;for(let E=0;E<64;E++){let P=g(R,6)^g(R,11)^g(R,25),M=R&S^~R&x,C=N+P+M+dg[E]+h[E]>>>0,$=g(v,2)^g(v,13)^g(v,22),V=v&T^v&w^T&w,G=$+V>>>0;N=x,x=S,S=R,R=k+C>>>0,k=w,w=T,T=v,v=C+G>>>0}a=a+v>>>0,d=d+T>>>0,u=u+w>>>0,c=c+k>>>0,l=l+R>>>0,p=p+S>>>0,f=f+x>>>0,m=m+N>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(c)+y(l)+y(p)+y(f)+y(m)}function Yt(t){let e=ka(t??null),n=JSON.stringify(e);return cg(n).slice(0,16)}function lg(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function nr(t,e,n){let r=n?.id??lg();if(t===0)return{id:r,version:0};let s=(n?.hash??Yt)(e);return{id:r,version:0,cid:s,prev:null}}function qr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function xa(t){return"cid"in t}var dg,ug,es=be(()=>{"use strict";dg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ug=new TextEncoder});function nc(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ra(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function ts(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function Na(t){if(je._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t(je)}function J(t,e,n){let r=rc(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return rc(t)?s=(Sa(e)?e:n)??{}:Sa(t)?s=t:s=(Sa(e)?e:n)??{},new Ae(r,o,s)}var ec,tc,pg,fg,je,Ae,rc,Sa,Me=be(()=>{"use strict";Zo();Fr();Oe();Re();wa();Jt();se();es();ec=()=>{},tc=100;pg=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},fg=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Jn]:[Jn,[_,s]];o._status==="dirty"&&i.push(Dt),Ft(e,i,o._config.tierOf)},je=new Tn({onMessage:pg,onSubscribe:fg});Br(je);Gr(je);Ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??je,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Yt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?nr(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(nc);let s={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[_,a]])},down(a){i._emit(ts(a))},up(a){i._emitUp(ts(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=nr(e,s,{id:a,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Gt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Gt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new ct({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new ct({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ie()}}down(e,n){let r=ts(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[_,e]])}up(e,n){if(this._deps.length===0)return;let r=ts(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=Gt(n);if(!this._guard(d,"observe"))throw new ct({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)Ra(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=ec,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Ra(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=nc(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Yn),r.unsub=ec;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[L,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Ra(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==mt){if(o===oe){this._depDirtied(r);return}if(o===nt){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Lr);return}if(o===qe||o===Je){this._emit([n]);return}if(o===fe){this._emit(Qn);return}if(o===_)this._depSettledAsData(r,n[1]);else if(o===z)this._depSettledAsResolved(r);else if(o===I)this._depSettledAsTerminal(r,!0);else if(o===L)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===_||o===z)&&this._emit([n]),(o===I||o===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Yn))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Cr),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Ir)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>tc?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${tc} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Dt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(o=!0),d[0]===oe&&(s=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Dt,...a]:[...a.slice(0,d),Dt,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===fe||d[0]===nt);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==qe&&u!==Je){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===qe?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=d[1];if(u===qe)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(d):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===fe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Qn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[L,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===_){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===_){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Un),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&qr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===oe)this._status="dirty";else if(p===z)this._status="resolved";else if(p===I){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===L){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===nt){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===fe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Xu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],tr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ft(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Ft(this._deliverToSinks,n,this._config.tierOf)}},rc=t=>Array.isArray(t),Sa=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function A(t,e){return J([],{...e,initial:t})}function H(t,e){return J((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function O(t,e,n){return J(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function he(t,e,n){return J(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Hr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),O(t,(o,s)=>e(a=>{let d=r.get(a);if(d==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[d]},s),n)}function wn(t,e){let n,r=new Map,o=(s,i,a)=>{let d=!1,u=c=>{let l=r.get(c);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}d=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(u,a);d||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ae([],o,{describeKind:"derived",...e}),n}function Ea(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=be(()=>{"use strict";Me()});function Ur(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let d,u;if(s==="*")d=e,u=n;else if(s.includes("-")){let[c,l]=s.split("-");d=Number.parseInt(c,10),u=Number.parseInt(l,10)}else d=Number.parseInt(s,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${t}`);if(d<e||u>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${t}`);for(let c=d;c<=u;c+=a)r.add(c)}return r}function ds(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Ur(e[0],0,59),hours:Ur(e[1],0,23),daysOfMonth:Ur(e[2],1,31),months:Ur(e[3],1,12),daysOfWeek:Ur(e[4],0,6)}}function us(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Oa=be(()=>{"use strict"});function we(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var ut=be(()=>{"use strict"});function Qt(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=new Aa,i=!1,a=!1,d=Symbol("budget-gate"),u=new Array(e.length);function c(){return e.every((f,m)=>f.check(u[m]))}function l(f){for(;s.size>0&&c();){let m=s.shift();f.emit(m)}s.size===0&&a&&(a=!1,f.down([[z]]))}return J([],(f,m)=>{for(let g=0;g<e.length;g++)u[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)p(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:we("resilience","budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===_)return c()&&s.size===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[qe,d]]))),!0;if(g===oe)return h.down([[oe]]),!0;if(g===z)return s.size===0?h.down([[z]]):a=!0,!0;if(g===I||g===L){for(;s.size>0;)h.emit(s.shift());return a=!1,i&&(i=!1,h.up([[Je,d]])),h.down([f]),!0}return!1}if(g===_&&(u[m-1]=f[1]),g===_||g===z){let y=c();return y&&s.size>0?(l(h),s.size===0&&i&&(i=!1,h.up([[Je,d]]))):!y&&!i&&s.size>0&&(i=!0,h.up([[qe,d]])),!0}return g===oe?!0:g===L?(h.down([f]),!0):g===I}}var Aa,vc=be(()=>{"use strict";se();Me();ut();Aa=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(e){this.buf.push(e)}shift(){if(this.head>=this.buf.length)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head++,this.head>32&&this.head*2>this.buf.length&&(this.buf=this.buf.slice(this.head),this.head=0),e}clear(){this.buf=[],this.head=0}}});function Xt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function kg(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function He(t){let e=new WeakSet,n={};for(let[r,o]of Tc(t))n[r]=Ca(o,e);return n}function Ca(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>Ca(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,i]of Tc(r))o[s]=Ca(i,e);return o}return"<unserializable>"}function Tc(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function Te(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function xg(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Jr(t,e,n){let r=e==null,o=!r&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,s=r||e.has("meta")||o!=null&&o.length>0,i="state",a=[];t instanceof Ae&&(i=kg(t),a=t._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(r||e.has("status"))&&(d.status=t.status);let u=t instanceof Ae?t._guard:void 0;if(s){let c={...xg(t)};if(u!=null&&c.access===void 0&&(c.access=Kr(u)),o!=null&&o.length>0&&!e.has("meta")){let l={};for(let p of o)p in c&&(l[p]=c[p]);d.meta=l}else d.meta=c}if(t.name!=null&&(d.name=t.name),(r||e.has("value"))&&(!n||i==="state")){t.status==="sentinel"&&(d.sentinel=!0);try{d.value=t.cache}catch{}}if((r||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),d.v=c}return(r||e.has("guard"))&&u!=null&&(d.guard=Kr(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var Ze=be(()=>{"use strict";Jt();Me()});function Yr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Rg(s,e,n,r)}return o}function Rg(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Be.number;case"boolean":return Be.boolean;case"string":return Be.string+t.length*2;case"bigint":return Be.bigint+Sg(t);case"symbol":return Be.symbol;case"function":return e.has(t)?0:(e.add(t),Be.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[cs];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return Be.date;if(s instanceof RegExp)return Be.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return Be.error+u+c}if(typeof URL<"u"&&s instanceof URL)return Be.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Be.promise;if(s instanceof WeakMap)return Be.weakmap;if(s instanceof WeakSet)return Be.weakset;if(s instanceof Map){let u=Be.map;for(let[c,l]of s)u+=Be.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=Be.set;for(let c of s)u+=Be.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=Be.array+s.length*8;for(let c of s)r.push(c);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=Be.object,d=Object.keys(s);for(let u of d){a+=Be.string+u.length*2;try{r.push(s[u])}catch{}}return a}function Sg(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}var Be,cs,La=be(()=>{"use strict";Be={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},cs=Symbol.for("sizeof")});function Qr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return ls(e,n,"no-such-from");if(!s)return ls(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Ng(t,e,r);if(u!=null)return u}let d=ps(e,t.nodes[e],0,r);return fs(e,n,[d])}if(i===0)return ls(e,n,"no-path");let a=wc(t,e,n,i);return a.found?fs(e,n,kc(t,a.pathOrder,r)):ls(e,n,a.truncated?"max-depth-exceeded":"no-path")}function wc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function Ng(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=ps(e,r,0,n);a.dep_index=s[0];let d=ps(e,r,1,n);return fs(e,e,[a,d])}let i=null;for(let a=0;a<o.length;a++){let d=o[a];if(!d||d===e)continue;let u=wc(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:fs(e,e,kc(t,i.pathOrder,n))}function kc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=ps(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function ps(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function fs(t,e,n){return xc(t,e,!0,"ok",n)}function ls(t,e,n){return xc(t,e,!1,n,[])}function xc(t,e,n,r,o){let s=Eg(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Eg(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(d),"value"in i&&s.push(` value: ${_g(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
2
- `)}function _g(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}var Ia=be(()=>{"use strict"});function Pa(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Pa(t[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let o=new Set(r);for(let s of n)if(!o.has(s)||!Pa(t[s],e[s]))return!1;return!0}function Rc(t,e){return`${t}\0${e}`}function cr(t,e){let n=[],r=new Set(t.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)r.has(g)||s.push(g);s.sort();for(let g of s)n.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(t.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let y=t.nodes[g]?.meta,b=e.nodes[g]?.meta;y==null&&b==null||Pa(y??{},b??{})||u.push(g)}u.sort();for(let g of u)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of t.edges)c.set(Rc(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Rc(g.from,g.to),g);let p=[];for(let[g,y]of l)c.has(g)||p.push(y);p.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of p)n.push({type:"edge-added",from:g.from,to:g.to});let f=[];for(let[g,y]of c)l.has(g)||f.push(y);f.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of f)n.push({type:"edge-removed",from:g.from,to:g.to});let m=[];for(let g of i)a.has(g)||m.push(g);m.sort();for(let g of m)n.push({type:"node-removed",path:g});let h=[];for(let g of r)o.has(g)||h.push(g);h.sort();for(let g of h)n.push({type:"subgraph-unmounted",path:g});return{events:n,flushedAt_ns:W()}}var Da=be(()=>{"use strict";Re()});var Ie,At=be(()=>{"use strict";Ie=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var jt,ms=be(()=>{"use strict";jt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function xn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof Ae?m:null,g=h?Yr(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let d=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var gs=be(()=>{"use strict";Me();La()});function Sc(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Oc(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Mg(t){if(t!=null)return Oc(t)?t.cache:t}function Rn(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Zt(t){return Rn(t)?t.cache??"":t}function Nc(t){return Rn(t)?t.cache??0:t}function Ec(t){return Rn(t)?t.cache??!1:t}function Og(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
3
- `)}function _c(t){if(t.version!==vt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${vt})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Ag(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,d=s.constructor;if(a!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function Cg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hs(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Cg(r)}return e+="$",new RegExp(e)}function Ga(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Pg(t){return t==="none"?Ig:t==="ansi"||t==null?Lg:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Mc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Dg(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function Fa(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ge))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ge}' (path separator)`);if(t===ot)throw new Error(`Graph "${e}": ${n} name "${ot}" is reserved for meta companion paths`);Dg(t,e,n)}function Gg(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ge);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Fg(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Ac(t){for(let e of t._mounts.values())Ac(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}function ys(t,e){let n=Y.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function Sn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(c.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),u.has(T)||u.set(T,new Set),u.get(T).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let R=i.get(v)??[],S=d.get(v),x=a.get(v),N=u.get(v),E=[...R];return S&&E.push(...S),x&&E.push(...x),N&&E.push(...N),E}if(n==="upstream"){let R=i.get(v)??[],S=d.get(v);return S?[...R,...S]:R}let T=a.get(v),w=u.get(v),k=T?[...T]:[];return w&&k.push(...w),k},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function $g(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Ge,ot,vt,Lg,Ig,Y,Fe=be(()=>{"use strict";Fr();Oe();Re();Jt();se();Ze();Me();ne();Da();ce();At();ms();Zo();Ia();gs();Ge="::",ot="__meta__",vt=1;Lg={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Ig={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};Y=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ge))throw new Error(`Graph name must not contain '${Ge}' (got "${e}")`);if(e===ot)throw new Error(`Graph name "${ot}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??je,this._traceRing=new jt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=H(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(Fa(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:W()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){Fa(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${Ge}${ot}${Ge}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ge}`)),this._mounts.delete(e),n._parent=void 0,Ac(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[fe]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=hs(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Ge))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[_,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Z(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[nt]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[I]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Ae)for(let c of u._deps){let l=r.get(c.node);l!=null&&a.push([l,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,d]of o)s.set(d,a);let i=[];for(let[a,d]of o)if(d instanceof Ae)for(let u of d._deps){let c=s.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(Fa(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=Gg(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===ot)return this._resolveMetaChainFromNode(s,o,n.join(Ge));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(Ge)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ge))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==ot)throw new Error(`Graph "${this.name}": expected ${ot} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ot} in "${r}"`);let a=i[s+1],d=o.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Fg(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof ct)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(d){if(d instanceof ct)throw d;s.push(d)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=Mg(e?.actor),r=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let o=Xt(e?.detail,e?.fields),s=e?.detail==="spec",i=o,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[T,w]of a)d.set(w,T);let u=[];{let T=a.map(([,R])=>R),w=new Set(d.values()),k=0;for(;T.length>0;){let R=T.shift();if(R instanceof Ae)for(let S of R._deps){let x=S.node;if(d.has(x))continue;let N=x.name??"",E=N;if(!E||w.has(E))if(N){let P=2;for(;w.has(`${N}#${P}`);)P++;E=`${N}#${P}`}else for(E=`__internal__/${k++}`;w.has(E);)E=`__internal__/${k++}`;d.set(x,E),w.add(E),u.push([E,x]),T.push(x)}}}let c=[...a,...u],l={};for(let[T,w]of c){if(n!=null&&!w.allowsObserve(n))continue;let k=Jr(w,i,s),R=w instanceof Ae?w._deps.map(E=>d.get(E.node)??E.node.name??""):[],{name:S,...x}=k,N={...x,deps:R};if(!s){let E=this._annotations.get(T);E!=null&&(N.annotation=E)}if(r!=null)if(typeof r=="function"){let E=r;if(!(E.length>=2?E(T,N):E(N)))continue}else{let E=!0;for(let[P,M]of Object.entries(r)){let C=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(C==="depsIncludes"){if(!N.deps.includes(String(M))){E=!1;break}continue}if(C==="metaHas"){if(!Object.hasOwn(N.meta??{},String(M))){E=!1;break}continue}if(N[C]!==M){E=!1;break}}if(!E)continue}l[T]=N}let p=new Set(Object.keys(l)),f=[];for(let[T,w]of c)if(w instanceof Ae)for(let k of w._deps){let R=d.get(k.node);R!=null&&f.push([R,T])}f.sort((T,w)=>T[0]<w[0]?-1:T[0]>w[0]?1:T[1]<w[1]?-1:T[1]>w[1]?1:0);let m=f.map(([T,w])=>({from:T,to:w}));(n!=null||r!=null)&&(m=m.filter(T=>p.has(T.from)&&p.has(T.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(T=>{let w=`${T}${Ge}`;return[...p].some(k=>k===T||k.startsWith(w))}):h,y=this,b=e;return{name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(T){let w={...b};return Array.isArray(T)?(w.fields=T,w.detail=void 0):(w.detail=T,w.fields=void 0),y.describe(w)}}}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Ge}`))}return n}resourceProfile(e){return xn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Sn(this.describe(),e,n,{...r,withDetail:!0}):Sn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(Zt(e),Zt(n),{...r?.maxDepth!==void 0?{maxDepth:Nc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ec(r.findCycle)}:{}})}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(o.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return Qr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=A(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,tr(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||d)return;p.add(b);let v=b.topology.subscribe(T=>{for(let w of T){if(w[0]!==_)continue;let k=w[1];if(u(),k.kind==="added"&&k.nodeKind==="mount"){let R=b._mounts.get(k.name);R!=null&&f(R)}}});l.push(v);for(let T of b._mounts.keys()){let w=b._mounts.get(T);w!=null&&f(w)}};f(this);let m,h=e.actor;Oc(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let k=w[0];k===_?v=!0:(k===I||k===L||k===fe)&&(T=!0)}v&&u(),T&&(m?.(),m=void 0,u())}));let g;try{g=O([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){c(),m?.();for(let v of l)v();throw i.dispose(),b}let y=te(g);return{node:g,dispose(){d=!0,c(),m?.();for(let b of l)b();l.length=0,i.dispose(),y()}}}_describeReactiveDiff(e){let n={...e,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),i=cr(o,s),a=A(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==_)continue;let m=f[1],h=cr(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=te(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[fe,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=A(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,tr(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[];e!=null&&Rn(e)&&l.push(e),n!=null&&Rn(n)&&l.push(n),r?.maxDepth!=null&&Rn(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&Rn(r.findCycle)&&l.push(r.findCycle);let p=()=>{for(let b of l)if(b.cache===void 0)return!1;return!0},f=()=>{let b=Zt(e),v=Zt(n);return{from:b,to:v,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:b,to:v,found:!1,reason:"pending",steps:[]})}},m;try{m=O([s],()=>{if(!p())return f();let b=Zt(e),v=Zt(n),T={...r?.maxDepth!==void 0?{maxDepth:Nc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ec(r.findCycle)}:{}};return this._explainStatic(b,v,T)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:Zt(e),to:Zt(n)},equals:(b,v)=>b.found===v.found&&b.reason===v.reason&&b.steps.length===v.steps.length&&$g(b.steps,v.steps)})}catch(b){throw c(),i.dispose(),b}let h=te(m),g=[],y=b=>{let v;return v=b.subscribe(T=>{let w=!1,k=!1;for(let R of T){let S=R[0];S===_?w=!0:(S===I||S===L||S===fe)&&(k=!0)}(w||k)&&u(),k&&v&&(v(),v=void 0)}),()=>{v&&(v(),v=void 0)}};for(let b of l)g.push(y(b));return{node:m,dispose(){d=!0,c();for(let b of g)b?.();g.length=0,i.dispose(),h()}}}_pathsMatching(e){let n=hs(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${Ge}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${Ge}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${Ge}${ot}${Ge}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Mc(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new ct({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof ct)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof ct)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return H(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let h={events:a.slice(),flushedAt_ns:W()};a.length=0,i.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(a.push(h),!d&&(d=!0,tr(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||i)&&d,c=n.maxEvents,l=c!=null&&c>0?new jt(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,b=0,v=0,T=0,w=0,k=0,R=!1,S=!1,x=0,N=new Map,E=new Map,P=new Map,M=ee=>{if(!(m!=null&&!m.has(ee.type))){l?l.push(ee):p.push(ee);for(let me of f)me(ee)}},C=ee=>m==null||m.has(ee),$=()=>o?{timestamp_ns:W(),in_batch:vn(),batch_id:x}:{},V=(ee,me)=>{if(!(!u||!(ee instanceof Ae)))return ee._setInspectorHook(Le=>{if(Le.kind==="dep_message")N.set(ee,Le.depIndex);else if(Le.kind==="run"){let rt=Le.batchData.map((U,de)=>U!=null&&U.length>0?U.at(-1):Le.prevData[de]);E.set(ee,rt);let Qe=Le.batchData.map(U=>U!=null?[...U]:void 0);P.set(ee,Qe),i&&M({type:"derived",path:me,dep_values:rt,dep_batches:Qe,...$()})}})},G=ee=>{let me=N.get(ee),Le=E.get(ee);if(!s||Le==null)return{};let Qe=(me!=null&&me>=0&&ee instanceof Ae?ee._deps[me]:void 0)?.node,U=Qe?.v,de=P.get(ee);return{trigger_dep_index:me,trigger_dep_name:Qe?.name,...U!=null?{trigger_version:{id:U.id,version:U.version}}:{},dep_values:[...Le],...de!=null?{dep_batches:de}:{}}},K=[],F=[];for(let[ee,me]of e){let Le=V(me,ee);Le&&K.push(Le),F.push(me.subscribe(rt=>{x++;for(let Qe of rt){let U=Qe[0],de=$();if(U===_){h[ee]=Qe[1];let De=me instanceof Ae?me.lastMutation?.actor??Ot:Ot;M({type:"data",path:ee,data:Qe[1],actor:De,...de,...G(me)})}else if(a)U===oe?C("dirty")&&y++:U===z?C("resolved")&&b++:U===nt?C("invalidate")&&v++:U===qe?C("pause")&&T++:U===Je?C("resume")&&w++:U===fe?C("teardown")&&k++:U===I&&!g.has(ee)?C("complete")&&(R=!0):U===L&&C("error")&&(S=!0,g.add(ee));else if(U===oe)C("dirty")&&y++,M({type:"dirty",path:ee,...de});else if(U===z)C("resolved")&&b++,M({type:"resolved",path:ee,...de,...G(me)});else if(U===nt)C("invalidate")&&v++,M({type:"invalidate",path:ee,...de});else if(U===qe)C("pause")&&T++,M({type:"pause",path:ee,lockId:Qe[1],...de});else if(U===Je)C("resume")&&w++,M({type:"resume",path:ee,lockId:Qe[1],...de});else if(U===I)C("complete")&&!g.has(ee)&&(R=!0),M({type:"complete",path:ee,...de});else if(U===L){C("error")&&(S=!0,g.add(ee));let De=me instanceof Ae?me.lastMutation?.actor??Ot:Ot;M({type:"error",path:ee,data:Qe[1],actor:De,...de})}else U===fe&&(C("teardown")&&k++,M({type:"teardown",path:ee,...de}))}}))}let q=!1,D=()=>{if(!q){q=!0;for(let ee of F)ee();for(let ee of K)ee();for(let ee of re)ee({value:void 0,done:!0});re.length=0}},B=[],re=[];f.add(ee=>{let me=re.shift();me?me({value:ee,done:!1}):B.push(ee)});let ye={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return T},get resumeCount(){return w},get teardownCount(){return k},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return R},get anyErrored(){return S},get completedWithoutErrors(){return R&&!S},onEvent(ee){return f.add(ee),()=>f.delete(ee)},dispose:D,expand(ee){D();let me={...n};return typeof ee=="string"?me.detail=ee:Object.assign(me,ee),r(Mc(me))},[Symbol.asyncIterator](){return{next(){return B.length>0?Promise.resolve({value:B.shift(),done:!1}):q?Promise.resolve({value:void 0,done:!0}):new Promise(ee=>re.push(ee))},return(){return D(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ye,n),ye}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),d=Pg(n.theme),u=r==="stage-log"?W():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(Ga(m.data),120):"",f=m=>{if(r==="stage-log"){let R=(W()-u)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let x=p(m);return`[${R.toFixed(3)}s] ${S} \u2190${x?` ${x}`:""}`}if(m.type==="error"){let x=p(m);return`[${R.toFixed(3)}s] ${S} \u2717${x?` ${x}`:""}`}return m.type==="complete"?`[${R.toFixed(3)}s] ${S} \u25A0 complete`:`[${R.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${Ga(m.data)}`:b?` ${Ga(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Sc(this._disposers,this.name),this.signal([[fe]],{internal:!0}),Sc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];o[a]=c}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Pr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??je,{codec:o,codecVersion:s,payload:i}=Dr(e,r);return o.decode(i,s)}restore(e,n){if(_c(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>hs(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){_c(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ge).length,y=h.split(Ge).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(Ge),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:hs(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(Ge),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Ge}${ot}${Ge}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=d(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=A(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=Og(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=ie(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:vt}:{name:this.name,mode:"diff",diff:ys(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:vt};if(u.tier.filter&&!u.tier.filter(g))return;let y;try{y=u.tier.save(g)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},w=>{n.onError?.(w,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},i=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=Jr(m,Xt("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Ie),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===vt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===vt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:W(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],d=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&d.push({path:b,id:w.id,from:w.version,to:k.version});let R=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let S of["type","status","sentinel"]){let x=v[S],N=T[S];x!==N&&a.push({path:b,field:S,from:x,to:N})}if(!R)for(let S of["value","meta"]){let x=v[S],N=T[S];Ag(x,N)||a.push({path:b,field:S,from:x,to:N})}}let u=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(b=>!c.has(u(b))),f=e.edges.filter(b=>!l.has(u(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}}});function Nn(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(d=>{for(let u of d){if(u[0]!==_)continue;let c=u[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Y){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[d,u]of o._mounts)if(u instanceof Y){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}var Cc=be(()=>{"use strict";se();Fe()});function $a(t){let e=t.describe({detail:"minimal"}),n=Object.keys(e.nodes),r=new Set;for(let s of n){let i=e.nodes[s];if(!i)continue;let a=i.deps??[];for(let d of a)r.add(d)}let o=[];for(let s of n){let i=e.nodes[s];if(!i||s.startsWith("__internal__/"))continue;let d=(i.deps??[]).length,u=r.has(s);if(d===0&&!u){let c=i.type??"unknown";o.push({path:s,kind:c})}}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),{ok:o.length===0,orphans:o,summary(){if(o.length===0)return"validateNoIslands: ok (no islands)";let s=o.slice(0,3).map(i=>`${i.path} (${i.kind})`).join(", ");return`validateNoIslands: ${o.length} island node(s) \u2014 ${s}${o.length>3?", \u2026":""}`}}}var Lc=be(()=>{"use strict"});function ja(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function lr(t){let e=0;for(let n of t)e+=ja(n.codePointAt(0));return e}function Ic(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=ja(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=ja(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var bs=be(()=>{"use strict"});function Fc(t,e){let n=e.charset==="ascii"?Bg:jg,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Kg(s,i,n,a);for(let a of t.boxes)Vg(s,i,n,a,e.labelOf(a.id));return s.map(a=>Wg(a.join(""))).join(`
4
- `)}function Vg(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&Pc(t,e,s,i,a,o);return}en(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)en(t,e,c,i,n.boxH);en(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){en(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)$c(t,e,l,c," ","empty");en(t,e,s+a-1,c,n.boxV)}en(t,e,s,i+d-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)en(t,e,c,i+d-1,n.boxH);en(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);Pc(t,e,s+1,u,a-2,o)}function en(t,e,n,r,o){$c(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function $c(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function Pc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let d of s){let u=lr(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Kg(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)qg(t,e,n,o[d],o[d+1]);for(let d=1;d+1<o.length;d+=1){let u=o[d-1],c=o[d],l=o[d+1],p=Hg(u,c,l,n);p&&Gc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=zg(i,s,n);a&&Gc(t,e,s.x,s.y,a,"arrow")}function qg(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let d=i;d<=a;d+=1)Dc(t,e,d,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let d=i;d<=a;d+=1)Dc(t,e,s,d,n,"v")}}}function Dc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function Gc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Hg(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function zg(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Wg(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}var jg,Bg,jc=be(()=>{"use strict";bs();jg={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},Bg={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"}});function Kc(t){let e=Ug(t);Jg(e),Yg(e),Qg(e),Xg(e,t);let n=th(e,t),{width:r,height:o}=rh(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function Ug(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function Jg(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Yg(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(d===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let u=i;for(let l=1;l<d;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:l-1,chainLen:d};u.out.push(m),f.in.push(m),r.push(m),u=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Qg(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Bc(t,t.layers[r],"in"),vs(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Bc(t,t.layers[r],"out"),vs(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Vc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],vs(s),Vc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],vs(s))}}if(!r)break}}function Bc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let d of s){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function vs(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Vc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let d of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Xg(t,e){e.direction==="LR"?Zg(t,e):eh(t,e)}function Zg(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}qc(t,e,"y")}function eh(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}qc(t,e,"x")}function qc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];d.set(c.id,f-Math.floor(r(c)/2))}let u=0;for(let c of a){let l=d.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,u);n==="y"?c.y=m:c.x=m,u=m+r(c)+o}}}}function th(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],l=t.layers[u+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let x of S.out)g.push(x);g.sort((S,x)=>{let N=i(t.nodes.get(S.fromId)),E=i(t.nodes.get(x.fromId));if(N!==E)return N-E;let P=i(t.nodes.get(S.toId)),M=i(t.nodes.get(x.toId));return P-M});let y=[],b=new Map;for(let S of g){let x=i(t.nodes.get(S.fromId)),N=i(t.nodes.get(S.toId)),E=Math.min(x,N),P=Math.max(x,N),M=-1;for(let C=0;C<y.length;C+=1){let $=y[C],V=!0;for(let G of $)if(G.lo<=P&&E<=G.hi){V=!1;break}if(V){$.push({lo:E,hi:P}),M=C;break}}M<0&&(y.push([{lo:E,hi:P}]),M=y.length-1),b.set(S,M)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,R=Math.max(1,k-w+1);for(let S of g){let x=b.get(S),N;if(v<=1)N=w+Math.floor(R/2);else{let E=(R-1)/(v-1);N=w+Math.floor(x*E)}a.set(S,Math.max(p,Math.min(m,N)))}}let d=[];for(let[,u]of n){let c=[];for(let p=0;p<u.length;p+=1){let f=u[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&Ts(c,r,y,v),v!==T&&(Ts(c,r,g,v),Ts(c,r,g,T)),Ts(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:nh(c)})}return d}function Ts(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function nh(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function rh(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Hc=be(()=>{"use strict"});function Ba(t,e){let n=dh(e?.direction),r=Math.max(3,e?.maxLabelWidth??oh),o=e?.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),d=new Map,u=new Map;for(let p of s){let f=Ic(p,r);d.set(p,f),u.set(p,lr(f)+4)}let c=Kc({nodes:s,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>ah,layerGap:sh,nodeGap:ih,direction:n}),l=Fc(c,{charset:o,labelOf:p=>d.get(p)??p});return e?.logger?.(l),l}function dh(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}var oh,sh,ih,ah,zc=be(()=>{"use strict";jc();bs();Hc();oh=24,sh=4,ih=1,ah=3});function ws(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ws);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ws(e[o]);return r}function Wc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Uc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Jc(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function ks(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function xs(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Yc(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}var Xr=be(()=>{"use strict"});function Va(t,e){let n=xs(e?.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Jc(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Uc(i)}"`)}for(let[i,a]of ks(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
5
- `)}var Qc=be(()=>{"use strict";Xr()});function Ka(t,e){let n=e?.includeEdges??!0,r=e?.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(ws(i),null,e?.indent??2);return e?.logger?.(a),a}var Xc=be(()=>{"use strict";Xr()});function tn(t,e){let n=xs(e?.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${Wc(i)}"]`)}for(let[i,a]of ks(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(` ${d} --> ${u}`)}return s.join(`
6
- `)}var qa=be(()=>{"use strict";Xr()});function Zc(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function Ha(t,e){let n=tn(t,e);return Zc(n,e)}var el=be(()=>{"use strict";qa()});function za(t,e){let n=e?.includeEdges??!0,r=e?.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${Yc(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
7
- `);return e?.logger?.(s),s}var tl=be(()=>{"use strict";Xr()});var Wa=be(()=>{"use strict";zc();Qc();Xc();qa();el();tl()});function Ua(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let u=t.describe(),c=new Set(Object.keys(u.nodes)),l=[];for(let[p,f]of Object.entries(u.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of u.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:u.edges.length})}catch(u){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${u instanceof Error?u.message:String(u)}`})}if((e.formats?.length??0)>0){let u=t.describe();for(let c of e.formats)try{let l=uh[c](u);typeof l!="string"||l.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`${c} renderer returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:l.length})}catch(l){n.push({kind:"describe-format",ok:!1,format:c,reason:l instanceof Error?l.message:String(l)})}}for(let u of e.paths??[])try{t.resolve(u),n.push({kind:"observe",ok:!0,path:u})}catch(c){n.push({kind:"observe",ok:!1,path:u,reason:c instanceof Error?c.message:String(c)})}for(let[u,c]of e.pairs??[])try{let l=t.explain(u,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:u,to:c,reason:`explain(${u} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:u,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:u,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(u=>!u.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,d=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let u=[e.skipDescribe===!0?null:"describe",d>0?`${d} format${d===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=u.length>0?u.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var uh,nl=be(()=>{"use strict";Wa();uh={json:t=>Ka(t),pretty:t=>za(t),mermaid:t=>tn(t),"mermaid-url":t=>Ha(t),d2:t=>Va(t),ascii:t=>Ba(t)}});var Ja={};Ee(Ja,{ENVELOPE_VERSION:()=>Xn,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,JsonCodec:()=>Xo,SIZEOF_OVERHEAD:()=>Be,SIZEOF_SYMBOL:()=>cs,SNAPSHOT_VERSION:()=>vt,createDagCborCodec:()=>ba,createDagCborZstdCodec:()=>va,decodeEnvelope:()=>Dr,diffForWAL:()=>ys,encodeEnvelope:()=>Pr,explainPath:()=>Qr,graphProfile:()=>xn,reachable:()=>Sn,registerBuiltinCodecs:()=>Gr,replayWAL:()=>Ta,sizeof:()=>Yr,validateGraphObservability:()=>Ua,validateNoIslands:()=>$a,watchTopologyTree:()=>Nn});var Tt=be(()=>{"use strict";La();Zo();Ia();Fe();gs();Cc();Lc();nl()});var rl={};Ee(rl,{NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,constant:()=>Rs,decorrelatedJitter:()=>_s,exponential:()=>Ns,fibonacci:()=>Es,linear:()=>Ss,resolveBackoffPreset:()=>_n,withMaxAttempts:()=>Ya});function En(t){return t<0?0:t}function ch(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function lh(t,e){return t+Math.random()*(e-t)}function Rs(t){let e=En(t);return()=>e}function Ss(t,e){let n=En(t),r=e===void 0?n:En(e);return o=>n+r*Math.max(0,o)}function Ns(t){let e=En(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=En(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=a){d=a;break}d*=n}i=e*d,i>r&&(i=r)}return ch(i,o)}}function Es(t=100*1e6,e=30*1e9){let n=En(t),r=En(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let d=1;d<s;d++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function _s(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return lh(t,i)}}function Ya(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function _n(t){if(t==="constant")return Rs(1*1e9);if(t==="linear")return Ss(1*1e9);if(t==="exponential")return Ns();if(t==="fibonacci")return Es();if(t==="decorrelatedJitter")return _s();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var et,wt,Zr=be(()=>{"use strict";et=1e6,wt=1e9});function ge(t){return{describeKind:"derived",...t}}function ol(t){return{describeKind:"derived",partial:!0,...t}}function eo(t,e,n){return J([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[z]]);return}for(let i of s)o.emit(e(i))},{...ge(n),meta:{...Te("map"),...n?.meta??{}}})}function kt(t,e,n){return J([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[z]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[z]])},{...ge(n),meta:{...Te("filter"),...n?.meta??{}}})}function sl(t,e,n,r){return J([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[z]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...ge(r),initial:n,resetOnTeardown:!0,meta:{...Te("scan",{initial:n}),...r?.meta??{}}})}function il(t,e,n,r){return J([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[I]]);return}let a=o[0];if(a==null||a.length===0){s.down([[z]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...ge(r),completeWhenDepsComplete:!1,meta:{...Te("reduce",{initial:n}),...r?.meta??{}}})}function to(t,e,n){return e<=0?J([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[I]]))},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}}):J([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[z]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[I]]);return}let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[I]]);return}},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}})}function Qa(t,e,n){return J([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[z]])},ge(n))}function al(t,e,n){return J([t],(r,o,s)=>{if(s.store.done){o.down([[z]]);return}let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[I]]);return}o.emit(a)}},{...ge(n),completeWhenDepsComplete:!1})}function dl(t,e,n){let r=n?.predicate??(i=>i[0]===_),{predicate:o,...s}=n??{};return H(i=>{let a=!1,d=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===_?i.emit(l[1]):(l[0]===I||l[0]===L)&&(a=!0,i.down([l]))}}),u=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[I]]);return}}});return()=>{d(),u()}},ge(s))}function Ms(t,e){return to(t,1,e)}function ul(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return J([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[I]]);return}let d=s[0];if(d==null||d.length===0){i.down([[z]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...ge(r),completeWhenDepsComplete:!1})}function cl(t,e,n){return to(kt(t,e,n),1,n)}function ll(t,e,n){return to(Qa(t,e,n),1,n)}function pl(t,e,n){if(typeof e=="function")return J([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[z]]);return}for(let a of i)e(a),s.emit(a)},{...ge(n),meta:{...Te("tap"),...n?.meta??{}}});let r=e;return J([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[I]])):(r.error?.(i.terminalDeps[0]),s.down([[L,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[z]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("tap"),...n?.meta??{}}})}function no(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return J([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[z]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},ge(n))}function ml(t,e=Object.is,n){return J([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}let a=!1;for(let d of i)s.store.hasPrev&&e(s.store.prev,d)||(s.store.prev=d,s.store.hasPrev=!0,o.emit(d),a=!0);a||o.down([[z]])},{...ge(n),meta:{...Te("distinctUntilChanged"),...n?.meta??{}}})}function gl(t,e){return J([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[z]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let d=[o.store.prev,a];o.store.prev=a,r.emit(d),i=!0}i||r.down([[z]])},ge(e))}function Xa(...t){let e=[...t];return O(e,n=>n,{...ge(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function Mn(t,e,n){return J([t,e],(r,o,s)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[z]]);return}for(let u of i)o.emit([u,d])}else o.down([[z]])},{...ol(n),meta:{...Te("withLatestFrom"),...n?.meta??{}}})}function Ct(...t){return t.length===0?H(e=>{e.down([[I]])},{...ge(),meta:{...Te("merge")}}):H(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let d of a)d[0]===_?e.emit(d[1]):d[0]===I?(r+=1,r>=n&&e.down([[I]])):d[0]===L&&e.down([d])});o.push(i)}return()=>{for(let s of o)s()}},{...ge(),meta:{...Te("merge")}})}function hl(...t){let e=t.length;return e===0?H(n=>{n.emit([]),n.down([[I]])},ge()):H(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(d=>d.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let d=a,u=t[a].subscribe(c=>{for(let l of c)l[0]===_?(r[d].push(l[1]),s()):l[0]===I?(o-=1,(o===0||r[d].length===0)&&n.down([[I]])):l[0]===L&&n.down([l])});i.push(u)}return()=>{for(let a of i)a()}},ge())}function yl(t,e,n){return H(r=>{let o=0,s=[],i,a;return a=e.subscribe(d=>{for(let u of d)o===0?u[0]===_?s.push(u[1]):u[0]===L&&r.down([u]):u[0]===_?r.emit(u[1]):(u[0]===I||u[0]===L)&&r.down([u])}),i=t.subscribe(d=>{for(let u of d)if(o===0)if(u[0]===_)r.emit(u[1]);else if(u[0]===I){o=1;for(let c of s)r.emit(c);s.length=0}else u[0]===L&&r.down([u])}),()=>{i?.(),a?.()}},ge(n))}function bl(...t){return t.length===0?H(e=>{e.down([[I]])},ge()):t.length===1?J([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[z]]);return}for(let o of r)n.emit(o)},ge()):H(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let d of a){if(n!==null&&s!==n)return;d[0]===_?(n===null&&(n=s),e.emit(d[1])):(d[0]===I||d[0]===L)&&(n===null||s===n)&&e.down([d])}});r.push(i)}return()=>{for(let o of r)o()}},ge())}function Os(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==mt&&(u[0]===_?e.emit(u[1]):u[0]===I?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===oe||u[0]===z)&&e.down([u]));d?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ke(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return J([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[I]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=Os(Q(e(u[u.length-1])),a,()=>{s(),o&&a.down([[I]])}),{deactivate:()=>{s(),o=!1}}},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("switchMap"),...n?.meta??{}}})}function vl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return J([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[I]]);return}let u=i[0];if(!(u==null||u.length===0))return r===void 0?r=Os(Q(e(u[0])),a,()=>{s(),o&&a.down([[I]])}):a.down([[z]]),{deactivate:()=>{s(),o=!1}}},{...ge(n),completeWhenDepsComplete:!1})}function Tl(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,d;function u(){i?.(),i=void 0}function c(){if(!d||i!==void 0)return;if(s.length===0){a&&d.down([[I]]);return}let p=s.shift();i=Os(Q(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return J([t],(p,f,m)=>{if(d=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){u(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{u(),s.length=0,a=!1}}}},{...ge(o),completeWhenDepsComplete:!1})}function Za(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,d=new Set,u=[],c;function l(){a&&i===0&&u.length===0&&c&&c.down([[I]])}function p(g){if(!c)return;i++;let y;y=Os(Q(e(g)),c,()=>{y&&d.delete(y),i--,f(),l()}),d.add(y)}function f(){for(;u.length>0&&i<s;)p(u.shift())}function m(g){i<s?p(g):u.push(g)}function h(){for(let g of d)g();d.clear(),i=0,u.length=0}return J([t],(g,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ge(o),completeWhenDepsComplete:!1})}function kl(t,e,n){return H(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let d of a)if(d[0]===_){let u=setTimeout(()=>{o.delete(u),r.emit(d[1])},e);o.add(u)}else if(d[0]===I){let u=setTimeout(()=>{o.delete(u),r.down([[I]])},e);o.add(u)}else d[0]===L&&(s(),r.down([d]))});return()=>{i(),s()}},ge(n))}function ed(t,e,n){return H(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(d=>{for(let u of d)u[0]===_?(i(),s=u[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):u[0]===I?(o!==void 0&&(i(),r.emit(s)),r.down([[I]])):u[0]===L&&(i(),r.down([u]))});return()=>{a(),i()}},{...ge(n),meta:{...Te("debounce",{ms:e}),...n?.meta??{}}})}function td(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,d=e*1e6;return H(u=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===_){let b=y[1],v=W();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=W(),u.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=W(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===I||y[0]===L)&&(m(),u.down([y]))});return()=>{h(),m()}},{...ge(s),meta:{...Te("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function xl(t,e,n){return H(r=>{let o,s=!1,i=!1,a=t.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===_?o={v:c[1]}:c[0]===L?(s=!0,r.down([c])):c[0]===I&&(i=!0,o=void 0)}}),d=e.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===_?o!==void 0&&!i&&r.emit(o.v):c[0]===L?(s=!0,r.down([c])):c[0]===I&&(s=!0,r.down([[I]]))}});return()=>{a(),d()}},ge(n))}function Rl(t,e,n){return H(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let d=t.subscribe(u=>{for(let c of u)c[0]===_?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===I||c[0]===L)&&(a(),r.down([c]))});return()=>{d(),a()}},ge(n))}function Sl(t,e,n){return H(r=>{let o=[],s=t.subscribe(a=>{for(let d of a)d[0]===_?o.push(d[1]):d[0]===I?(o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):d[0]===L&&r.down([d])}),i=e.subscribe(a=>{for(let d of a)d[0]===_?o.length>0&&(r.emit([...o]),o.length=0):d[0]===I?r.down([[I]]):d[0]===L&&r.down([d])});return()=>{s(),i(),o.length=0}},ge(n))}function Nl(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return H(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===_?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===I?(o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):a[0]===L&&r.down([a])});return()=>{s(),o.length=0}},ge(n))}function El(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return H(r=>{let o,s=0;function i(){let d=H(u=>(o=u.down.bind(u),()=>{o=void 0}),ge());s=0,r.emit(d)}let a=t.subscribe(d=>{for(let u of d)u[0]===_?(o||i(),o?.([[_,u[1]]]),s+=1,s>=e&&(o?.([[I]]),o=void 0)):u[0]===I?(o?.([[I]]),o=void 0,r.down([[I]])):u[0]===L&&(o?.([u]),o=void 0,r.down([u]))});return()=>{a(),o?.([[I]]),o=void 0}},ge(n))}function _l(t,e,n){return H(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let d of a)d[0]===_?o.push(d[1]):d[0]===I?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):d[0]===L&&(clearInterval(s),r.down([d]))});return()=>{i(),clearInterval(s),o.length=0}},{...ge(n),meta:{...Te("bufferTime",{ms:e}),...n?.meta??{}}})}function Ml(t,e,n){return H(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),ge());r.emit(u)}i();let a=setInterval(()=>{s(),i()},e),d=t.subscribe(u=>{for(let c of u)c[0]===_?o?.([[_,c[1]]]):c[0]===I?(clearInterval(a),s(),r.down([[I]])):c[0]===L&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{d(),clearInterval(a),s()}},ge(n))}function Ol(t,e,n){return H(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),ge());r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===_?(o||i(),o?.([[_,c[1]]])):c[0]===I?(s(),r.down([[I]])):c[0]===L&&(o?.([c]),o=void 0,r.down([c]))}),d=e.subscribe(u=>{for(let c of u)c[0]===_&&(s(),i())});return()=>{a(),d(),s()}},ge(n))}function Al(t,e){return H((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ge(e))}function Cl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return H(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let d=!1,u=[];for(let c of a)c[0]===I?d=!0:u.push(c);u.length>0&&r.down(u),d&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[I]]))})};return i(),()=>{s?.()}},ge(n))}function Ll(t,e){return J([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[z]]);return}for(let s of o)r.emit(s)},ge(e))}function ro(t,e,n){return H(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===_)r.emit(i[1]);else if(i[0]===L)try{r.emit(e(i[1]))}catch(a){r.down([[L,a]])}else i[0]===I&&r.down([[I]])});return()=>{o()}},ge(n))}function Il(t,e,n){return J([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[z]]);return}let d=r[0];if(d!=null&&d.length>0){for(let u of d)o.emit(u);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[z]])},ol(n))}var fl,wl,Pl,Dl,Gl,Fl,$l=be(()=>{"use strict";Re();se();Ze();Me();ne();ce();fl=no;wl=Za;Pl=Xa,Dl=ed,Gl=td,Fl=ro});var ze=be(()=>{"use strict";$l()});function oo(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function jl(t){if(t<=0)throw new RangeError("timeoutMs must be > 0");if(t>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic")}function Bl(t,e={}){let n=new so(t,e);return n.tagFactory("resilientPipeline",He(e)),n}var so,Vl=be(()=>{"use strict";Ze();Tt();ut();ze();nd();so=class extends Y{output;status;lastError;breakerState;droppedCount;rateLimitState;constructor(e,n={}){super(n.name??"resilient_pipeline",n.graph);let r=e,o,s,i;if(n.rateLimit!=null)if(oo(n.rateLimit)){let d=r,u=n.rateLimit;r=ke(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:we("resilient","rate-limit")};return An(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:we("resilient","rate-limit")},u=An(r,d);r=u.node,o=u.droppedCount,s=u.rateLimitState,this.add(r,{name:"rateLimited"}),this.add(o,{name:"droppedCount"}),this.add(s,{name:"rateLimitState"})}if(n.budget!=null)if(oo(n.budget)){let d=r,u=n.budget;r=ke(u,c=>c.length>0?Qt(d,c,{meta:we("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Qt(r,n.budget,{meta:we("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(oo(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=ke(u,l=>{let p=Rt(l);return On(p,{onOpen:c,meta:we("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=Rt(n.breaker),u=n.breakerOnOpen??"skip",c=On(d,{onOpen:u,meta:we("resilient","breaker")})(r);r=c.node,i=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(i,{name:"breakerState"})}if(n.timeoutMs!=null)if(oo(n.timeoutMs)){let d=r,u=n.timeoutMs;r=ke(u,c=>(jl(c),Cn(d,c*1e6,{meta:we("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else jl(n.timeoutMs),r=Cn(r,n.timeoutMs*1e6,{meta:we("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(oo(n.retry)){let d=r,u=n.retry;r=ke(u,c=>xt(d,{...c,meta:we("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=xt(r,{...n.retry,meta:we("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=pr(r,n.fallback,{meta:we("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let a=nn(r,{initialStatus:n.initialStatus??"pending",meta:we("resilient","status")});this.output=a.node,this.status=a.status,this.lastError=a.error,this.breakerState=i,this.droppedCount=o,this.rateLimitState=s,this.add(this.output,{name:"output"}),this.add(this.status,{name:"status"}),this.add(this.lastError,{name:"lastError"})}}});function Pn(t){return{describeKind:"derived",...t}}function ph(t){return t<0?0:t}function rd(t){return t[1]}function fh(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Kl(t){let e=t?.count,n=t?.backoff;if(n!==void 0&&e===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=e!==void 0?e:0;if(r<0)throw new RangeError("retry count must be >= 0");let o=n===void 0?null:typeof n=="string"?_n(n):n;return{maxRetries:r,strategy:o}}function ql(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function Hl(t,e,n){let r=0,o=!1,s=null,i,a=new Ie;function d(){i?.(),i=void 0}function u(l){if(o)return;if(r>=t.maxRetries){d(),n.down([[L,l]]);return}let p=t.strategy===null?0:t.strategy(r,l,s);if(p==null){d(),n.down([[L,l]]);return}let f;try{f=fh(p)}catch{d(),n.down([[L,l]]);return}s=f,r+=1,d();let m=f>0?f/1e6:1;a.start(m,()=>{o||c()})}function c(){a.cancel(),d();let l;try{l=e()}catch(p){u(p);return}i=l.subscribe(p=>{if(!o)for(let f of p){let m=f[0];if(m===oe)n.down([[oe]]);else if(m===_)r=0,s=null,n.emit(f[1]);else if(m===z)n.down([[z]]);else if(m===I)d(),n.down([[I]]);else if(m===L){u(rd(f));return}else n.down([f])}})}return c(),()=>{o=!0,a.cancel(),d()}}function xt(t,e){return typeof t=="function"?gh(t,e):mh(t,e)}function mh(t,e){let n=Kl(e);return H(r=>Hl(n,()=>t,r),{...Pn(),initial:t.cache,meta:{...e?.meta??{},...Te("retry",ql(e))}})}function gh(t,e){let n=Kl(e);return H(r=>Hl(n,t,r),{...Pn(),initial:e?.initial,meta:{...e?.meta??{},...Te("retry",ql(e))}})}function Rt(t){let e=Math.max(1,t?.failureThreshold??5),n=ph(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??W,i="closed",a=0,d=0,u=0,c=n,l=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){i="open",c=p(),u=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=c?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,d=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){d++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,d=0,l=0}}}function On(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=J([],(i,a)=>{function d(){s.meta.breakerState.down([[_,t.state]])}let u=o.subscribe(c=>{for(let l of c){let p=l[0];p===oe?a.down([[oe]]):p===_?t.canExecute()?(d(),a.emit(l[1])):(d(),n==="error"?a.down([[L,new St]]):a.down([[z]])):p===z?a.down([[z]]):p===I?(t.recordSuccess(),d(),a.down([[I]])):p===L?(t.recordFailure(rd(l)),d(),a.down([l])):a.down([l])}});return d(),u},{...Pn(),meta:{...r??{},breakerState:t.state,...Te("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function rn(t,e,n){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??W,o=t,s=r();function i(a){if(e>0){let d=a-s;o=Math.min(t,o+d/1e9*e)}s=a}return{available(){return i(r()),o},tryConsume(a=1){if(a<=0)return!0;let d=r();return i(d),o>=a?(o-=a,!0):!1},putBack(a=1){a<=0||(i(r()),o=Math.min(t,o+a))}}}function hh(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function An(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");let s=o===1/0;if(!s&&(!Number.isInteger(o)||o<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)");let i=e.onOverflow??"drop-newest",a=n*1e9/r,d=H(u=>{let c=rn(n,a),l=s?bh():yh(o),p=new Ie,f=!1,m=0,h=1e9/a,g=d.meta.droppedCount,y=d.meta.rateLimitState,b=As;function v(){g.emit(m);let S={droppedCount:m,pendingCount:l.size,paused:l.size>0};hh(b,S)||(b=S,y.emit(S))}b=As,g.emit(0),y.emit(As);function T(){for(;l.size>0;)if(c.tryConsume(1))u.emit(l.shift()),v();else{p.start(Math.max(1,h/1e6),T);return}}function w(){m+=1,v()}function k(){for(f=!0,p.cancel();l.size>0;)l.shift();m=0}let R=t.subscribe(S=>{for(let x of S){if(f)return;let N=x[0];if(N===oe)u.down([[oe]]);else if(N===_){if(!s&&l.size>=o)if(i==="drop-newest")w();else if(i==="drop-oldest")l.shift(),l.push(x[1]),w();else{w(),k(),u.down([[L,new Ln(o)]]);return}else l.push(x[1]),v();T()}else if(N===z)u.down([[z]]);else if(N===I)k(),u.down([[I]]);else if(N===L)k(),u.down([x]);else if(N===fe){k(),u.down([x]);return}else u.down([x])}});return()=>{f=!0,p.cancel(),R()}},{...Pn(),initial:t.cache,meta:{...e.meta??{},droppedCount:0,rateLimitState:As,...Te("rateLimiter",e)}});return{node:d,droppedCount:d.meta.droppedCount,rateLimitState:d.meta.rateLimitState}}function yh(t){let e=new jt(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function bh(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function nn(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=J([],(s,i)=>{let a=n;return o.meta.status.down([[_,n]]),o.meta.error.down([[_,null]]),t.subscribe(u=>{for(let c of u){let l=c[0];if(l===oe)i.down([[oe]]);else if(l===_)a==="errored"?Z(()=>{o.meta.error.down([[_,null]]),o.meta.status.down([[_,"running"]])}):o.meta.status.down([[_,"running"]]),a="running",i.emit(c[1]);else if(l===z)i.down([[z]]);else if(l===I)o.meta.status.down([[_,"completed"]]),a="completed",i.down([[I]]);else if(l===L){let p=rd(c);Z(()=>{o.meta.error.down([[_,p]]),o.meta.status.down([[_,"errored"]])}),a="errored",i.down([c])}else i.down([c])}})},{...Pn(),meta:{...r??{},status:n,error:null,...Te("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function vh(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Th(t){return t!=null&&typeof t.then=="function"}function wh(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function pr(t,e,n){let r=n?.meta;return H(o=>{let s,i;function a(){i?.(),i=void 0,vh(e)||Th(e)||wh(e)?s=Q(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===I||l===L||l===fe){s=void 0;return}}}):(o.emit(e),o.down([[I]]))}return i=t.subscribe(d=>{for(let u of d){let c=u[0];if(c===oe)o.down([[oe]]);else if(c===_)o.emit(u[1]);else if(c===z)o.down([[z]]);else if(c===I)o.down([[I]]);else if(c===L){a();return}else if(c===fe){s?.(),o.down([u]);return}else o.down([u])}}),()=>{i?.(),s?.()}},{...Pn(),initial:t.cache,meta:{...r??{},...Te("fallback")}})}function Cn(t,e,n){if(e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta;return H(o=>{let s=!1,i=new Ie;function a(){let u=e/1e6;i.start(u,()=>{s||(s=!0,d(),o.down([[L,new In(e)]]))})}let d=t.subscribe(u=>{for(let c of u){if(s)return;let l=c[0];if(l===oe)o.down([[oe]]);else if(l===_)a(),o.emit(c[1]);else if(l===z)o.down([[z]]);else if(l===I){i.cancel(),s=!0,o.down([[I]]);return}else if(l===L){i.cancel(),s=!0,o.down([c]);return}else if(l===fe){i.cancel(),s=!0,o.down([c]);return}else o.down([c])}});return a(),()=>{s=!0,i.cancel(),d()}},{...Pn(),initial:t.cache,meta:{...r??{},...Te("timeout",{timeoutNs:e})}})}var St,Ln,As,In,nd=be(()=>{"use strict";vc();Vl();Oe();Re();se();Ze();Me();ne();Zr();ce();At();ms();St=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};Ln=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};As=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});In=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var zl={};Ee(zl,{CircuitOpenError:()=>St,RateLimiterOverflowError:()=>Ln,ResilientPipelineGraph:()=>so,TimeoutError:()=>In,budgetGate:()=>Qt,circuitBreaker:()=>Rt,fallback:()=>pr,rateLimiter:()=>An,resilientPipeline:()=>Bl,retry:()=>xt,timeout:()=>Cn,tokenBucket:()=>rn,withBreaker:()=>On,withStatus:()=>nn});var on=be(()=>{"use strict";nd()});function ft(t){return{describeKind:"producer",...t}}function sd(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Ul(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=sd(r)}return e+="$",new RegExp(e)}function Jl(t,e){for(let n of e)if(n.test(t))return!0;return!1}function kh(t,e){let n=J([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[z]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function st(t,e){let{signal:n,period:r,...o}=e??{};return H(s=>{let i=!1,a=0,d,u,c=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[I]])))},p=()=>{i||(c(),s.down([[L,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ft(o))}function Yl(t){let{signal:e,...n}=t??{};return H(r=>{let o=!1,s,i,a=!1,d=!1,u=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),d&&l&&(l.removeEventListener("visibilitychange",y),d=!1)},m=()=>{o||(f(),r.down([[L,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(u&&(!l||l.visibilityState!=="hidden")?s=u(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&u&&(l.addEventListener("visibilitychange",y),d=!0),g(),f)},ft(n))}function Ls(t,e){let n=ds(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return H(d=>{let u=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==u&&us(n,p)&&(u=f,d.emit(a?p:ie()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ft(s),name:s.name??`cron:${t}`})}function Ql(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return H(a=>{let d=c=>{a.emit(c)},u={capture:r,passive:o,once:s};return t.addEventListener(e,d,u),()=>t.removeEventListener(e,d,u)},ft(i))}function Is(t,e){return H(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[I]])}catch(o){r||n.down([[L,o]])}return()=>{r=!0}},ft(e))}function xh(t){return t!=null&&typeof t.then=="function"}function fr(t,e){let{signal:n,...r}=e??{};return H(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[L,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[I]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[L,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ft(r))}function io(t,e){let{signal:n,...r}=e??{};return H(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||a.aborted)){if(l.done){o.down([[I]]);return}o.emit(l.value),c()}},l=>{!d&&!a.aborted&&o.down([[L,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},ft(r))}function Rh(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Q(t,e){if(Rh(t))return t;if(xh(t))return fr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return io(t,e);if(typeof n[Symbol.iterator]=="function")return Is(t,e)}return id(t)}function id(...t){return Is(t,void 0)}function Xl(t){return H(e=>{e.down([[I]])},ft(t))}function Zl(t){return H(()=>{},ft(t))}function ep(t,e){return H(n=>{n.down([[L,t]])},ft(e))}function tp(t,e){let{signal:n,...r}=e??{},o=ft(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return H(i=>{let a,d=!1;try{let u=t();a=Q(u,e).subscribe(l=>{if(!d)for(let p of l){let f=p[0];if(f!==mt)if(f===_)i.emit(p[1]);else if(f===I){d=!0,i.down([[I]]);break}else if(f===L){d=!0,i.down([[L,p[1]]]);break}else i.down([p])}})}catch(u){let c=u===void 0?new Error("defer: thunk threw undefined"):u;i.down([[L,c]])}return()=>{d=!0,a?.()}},s)}function sn(t,e,n){return J([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function np(t,e){return J([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[I]]);return}(i==null||i.length===0)&&r.down([[z]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function rp(t,e){return H(n=>t.subscribe(r=>{n.down(r)}),{...ft(e),initial:t.cache})}function Ps(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=H(s=>t.subscribe(i=>{for(let a of i)a[0]===_&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ft(n),initial:t.cache});return kh(o,s=>{for(let i of r)s([[_,i]])})}function op(t,e){return Ps(t,1,e)}function it(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===_){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===L){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===I){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Cs(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,d=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===_)){if(c[0]===_){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===L){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===I){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),d=!1,i&&(a?.(),a=void 0)})}async function Ds(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Cs(t,n,{skipCurrent:r});if(od===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(on(),zl)),Promise.resolve().then(()=>(Zr(),rl))]);od=s.timeout,Wl=i.NS_PER_MS}let o=od(t,e.timeoutMs*Wl);return await Cs(o,n,{skipCurrent:r})}function Gs(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===_&&d[1]===!0){n.abort(r),i();return}if(d[0]===L){n.abort(d[1]),i();return}if(d[0]===I){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function te(t){return t.subscribe(()=>{})}function ip(t){let e=A(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[oe],[_,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var od,Wl,sp,ap=be(()=>{"use strict";Re();se();Me();ne();Oa();sp=Ps});var ce=be(()=>{"use strict";ap()});var Qv={};Ee(Qv,{COMPLETE:()=>I,COMPLETE_MSG:()=>Yo,COMPLETE_ONLY_BATCH:()=>Ir,CircuitOpenError:()=>St,ContentAddressedMissError:()=>bo,DATA:()=>_,DEFAULT_ACTOR:()=>Ot,DEFAULT_AUDIT_GUARD:()=>pd,DIRTY:()=>oe,DIRTY_MSG:()=>Dt,DIRTY_ONLY_BATCH:()=>Yn,ENVELOPE_VERSION:()=>Xn,ERROR:()=>L,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,GraphReFlyConfig:()=>Tn,GuardDenied:()=>ct,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Jo,INVALIDATE_ONLY_BATCH:()=>Lr,JsonCodec:()=>Xo,NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,NativeIndexBackend:()=>wo,NativeListBackend:()=>ko,NativeLogBackend:()=>co,NativeMapBackend:()=>ho,NativePubSubBackend:()=>To,NodeImpl:()=>Ae,PAUSE:()=>qe,RESOLVED:()=>z,RESOLVED_MSG:()=>Un,RESOLVED_ONLY_BATCH:()=>Cr,RESUME:()=>Je,RateLimiterOverflowError:()=>Ln,ResettableTimer:()=>Ie,SIZEOF_OVERHEAD:()=>Be,SIZEOF_SYMBOL:()=>cs,SNAPSHOT_VERSION:()=>vt,SNAPSHOT_WIRE_VERSION:()=>Wo,START:()=>mt,START_MSG:()=>Jn,SurfaceError:()=>_e,TEARDOWN:()=>fe,TEARDOWN_MSG:()=>Qo,TEARDOWN_ONLY_BATCH:()=>Qn,TimeoutError:()=>In,accessHintForGuard:()=>Kr,advanceVersion:()=>qr,ai:()=>Bi,appendAudit:()=>gr,appendLogStorage:()=>_d,asSurfaceError:()=>aa,audit:()=>Rl,autoTrackNode:()=>wn,awaitSettled:()=>Ds,batch:()=>Z,budgetGate:()=>Qt,buffer:()=>Sl,bufferCount:()=>Nl,bufferTime:()=>_l,bumpCursor:()=>Bt,cached:()=>op,canonicalJson:()=>vo,cascadingCache:()=>wf,catchError:()=>Fl,checkpointToRedis:()=>ff,checkpointToS3:()=>pf,circuitBreaker:()=>Rt,combine:()=>Xa,combineLatest:()=>Pl,compat:()=>Td,concat:()=>yl,concatMap:()=>Tl,configure:()=>Na,constant:()=>Rs,contentAddressedStorage:()=>si,core:()=>cd,cqrs:()=>zs,createAuditLog:()=>at,createDagCborCodec:()=>ba,createDagCborZstdCodec:()=>va,createGraph:()=>Mr,createTransport:()=>cn,createVersioning:()=>nr,createWatermarkController:()=>mr,csvRows:()=>Wp,debounce:()=>ed,debounceTime:()=>Dl,decay:()=>It,decodeEnvelope:()=>Dr,decorrelatedJitter:()=>_s,defaultConfig:()=>je,defaultHash:()=>Yt,defer:()=>tp,delay:()=>kl,deleteSnapshot:()=>ma,demoShell:()=>Ki,derived:()=>O,deserializeError:()=>Bn,dictKv:()=>If,dictSnapshot:()=>Pf,diffForWAL:()=>ys,diffSnapshots:()=>pa,distill:()=>ri,distinctUntilChanged:()=>ml,domainMeta:()=>we,domainTemplates:()=>qi,downWithBatch:()=>Ft,dynamicNode:()=>Hr,effect:()=>he,elementAt:()=>ll,empty:()=>Xl,encodeEnvelope:()=>Pr,escapeRegexChar:()=>sd,exhaustMap:()=>vl,explainPath:()=>Qr,exponential:()=>Ns,externalBundle:()=>ni,externalProducer:()=>Fn,extra:()=>Ad,factoryTag:()=>Te,fallback:()=>pr,fibonacci:()=>Es,filter:()=>kt,find:()=>cl,first:()=>Ms,firstValueFrom:()=>it,firstWhere:()=>Cs,flatMap:()=>wl,forEach:()=>sn,fromAny:()=>Q,fromAsyncIter:()=>io,fromCSV:()=>zp,fromClickHouseWatch:()=>Qp,fromCron:()=>Ls,fromDrizzle:()=>bf,fromEvent:()=>Ql,fromHTTP:()=>Rd,fromHTTPPoll:()=>Cp,fromHTTPStream:()=>Ap,fromIter:()=>Is,fromKafka:()=>Vp,fromKysely:()=>vf,fromMCP:()=>Pp,fromNATS:()=>ef,fromNDJSON:()=>Yp,fromOTel:()=>Dp,fromPrisma:()=>yf,fromPrometheus:()=>Bp,fromPromise:()=>fr,fromPulsar:()=>Xp,fromRabbitMQ:()=>nf,fromRaf:()=>Yl,fromRedisStream:()=>qp,fromSSE:()=>Op,fromSqlite:()=>mf,fromSqliteCursor:()=>gf,fromStatsD:()=>$p,fromSyslog:()=>Gp,fromTimer:()=>st,fromWebSocket:()=>xd,fromWebSocketReconnect:()=>Ip,fromWebhook:()=>xp,globToRegExp:()=>Ul,graph:()=>Ja,graphProfile:()=>xn,graphspec:()=>ji,harness:()=>Zi,inspect:()=>oa,interval:()=>Al,isBatching:()=>vn,isV1:()=>xa,jobQueue:()=>Qi,jotai:()=>ns,jsonCodec:()=>Tr,jsonCodecFor:()=>Af,keepalive:()=>te,kvStorage:()=>ci,last:()=>ul,layout:()=>ia,lightMutation:()=>Ce,linear:()=>Ss,listSnapshots:()=>fa,lru:()=>Ed,makeHttpError:()=>Et,map:()=>eo,matchesAnyPattern:()=>Jl,matchesCron:()=>us,memory:()=>Pi,memoryAppendLog:()=>Lf,memoryBackend:()=>Ro,memoryKv:()=>So,memorySnapshot:()=>Cf,merge:()=>Ct,mergeMap:()=>Za,mergeReactiveLogs:()=>mp,messaging:()=>Mi,monotonicNs:()=>W,nameToSignal:()=>$n,nanostores:()=>is,ndjsonRows:()=>Up,nestjs:()=>Us,never:()=>Zl,node:()=>J,nodeSignal:()=>Gs,normalizeActor:()=>Gt,of:()=>id,onFirstData:()=>no,orchestration:()=>Oi,pairwise:()=>gl,parseCron:()=>ds,parsePrometheusText:()=>Sd,parseSSEStream:()=>qt,parseStatsD:()=>jp,parseSyslog:()=>Fp,patterns:()=>Bu,pausable:()=>Ll,pipe:()=>Ea,placeholderArgs:()=>He,policy:()=>$t,policyFromRules:()=>Vr,process:()=>sa,producer:()=>H,pubsub:()=>Nf,race:()=>bl,rateLimiter:()=>An,reachable:()=>Sn,react:()=>Js,reactiveCounter:()=>ip,reactiveIndex:()=>Mf,reactiveList:()=>ii,reactiveLog:()=>We,reactiveMap:()=>Xe,reactiveSink:()=>Ye,reduce:()=>il,reduction:()=>Gi,registerBuiltinCodecs:()=>Gr,registerBuiltins:()=>Br,registerCursor:()=>ht,registerCursorMap:()=>js,repeat:()=>Cl,replay:()=>Ps,replayWAL:()=>Ta,rescue:()=>ro,resolveBackoffPreset:()=>_n,resolveDescribeFields:()=>Xt,restoreSnapshot:()=>la,retry:()=>xt,runReduction:()=>da,sample:()=>xl,saveSnapshot:()=>ca,scan:()=>sl,serializeError:()=>jn,share:()=>rp,shareReplay:()=>sp,signalToName:()=>un,signals:()=>Qs,singleFromAny:()=>ai,singleNodeFromAny:()=>Of,sizeof:()=>Yr,skip:()=>Qa,snapshotStorage:()=>ui,solid:()=>Xs,sortJsonValue:()=>xo,stableJsonString:()=>di,state:()=>A,stratify:()=>No,surface:()=>ga,svelte:()=>Zs,switchMap:()=>ke,take:()=>to,takeUntil:()=>dl,takeWhile:()=>al,tap:()=>pl,tapFirst:()=>fl,throttle:()=>td,throttleTime:()=>Gl,throwError:()=>ep,timeout:()=>Cn,toArray:()=>np,toCSV:()=>of,toClickHouse:()=>sf,toFile:()=>Nd,toHTTP:()=>Rp,toKafka:()=>Kp,toLoki:()=>cf,toMongo:()=>uf,toNATS:()=>tf,toObservable:()=>as,toPostgres:()=>df,toPulsar:()=>Zp,toRabbitMQ:()=>rf,toReadableStream:()=>Mp,toRedisStream:()=>Hp,toS3:()=>af,toSSE:()=>Ep,toSSEBytes:()=>_p,toSqlite:()=>hf,toTempo:()=>lf,toWebSocket:()=>Lp,tokenBucket:()=>rn,topologyDiff:()=>cr,tryIncrementBounded:()=>Gn,validateGraphObservability:()=>Ua,validateNoIslands:()=>$a,valve:()=>Il,verifiable:()=>Rf,version:()=>Yv,vue:()=>ei,wallClockNs:()=>ie,watchTopologyTree:()=>Nn,window:()=>Ol,windowCount:()=>El,windowTime:()=>Ml,withBreaker:()=>On,withLatestFrom:()=>Mn,withMaxAttempts:()=>Ya,withStatus:()=>nn,workerBridge:()=>Md,workerSelf:()=>Od,wrapMutation:()=>Lt,zip:()=>hl,zustand:()=>ti});module.exports=eg(Qv);var Td={};Ee(Td,{jotai:()=>ns,nanostores:()=>is,nestjs:()=>Us,react:()=>Js,signals:()=>Qs,solid:()=>Xs,svelte:()=>Zs,vue:()=>ei,zustand:()=>ti});var ns={};Ee(ns,{atom:()=>mg});se();ne();function mg(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?oc(r,e,n):oc(r,void 0,e)}return gg(t,e)}function zr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===_&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function gg(t,e){let n=A(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?zr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?zr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===_){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function oc(t,e,n){let r=wn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&zr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?zr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[d,u]of a)if(d===_){if(i){i=!1;continue}s(u)}})},meta:r.meta,_node:r};if(e){let s=d=>d.get(),i=(d,u)=>d.set(u),a=o;return a.set=d=>e(s,i,d),a.update=d=>{let u=r.status==="sentinel"?zr(r):r.cache;return e(s,i,d(u))},a}return o}var is={};Ee(is,{action:()=>wg,atom:()=>hg,computed:()=>yg,getValue:()=>vg,map:()=>bg,onMount:()=>Tg,onStart:()=>ac,onStop:()=>dc});Oe();se();ne();var os=new WeakMap,ss=new WeakMap;function rs(t,e){let n=e.get(t);if(n)for(let r of n)r()}function _a(t,e={}){let n=0;return{...e,get:()=>ic(t),subscribe:o=>{n===0&&rs(t,os),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===_&&o(d)});return()=>{s(),n--,n===0&&rs(t,ss)}},listen:o=>{n===0&&rs(t,os),n++;let s=!0,i=t.subscribe(a=>{for(let[d,u]of a)if(d===_){if(s){s=!1;continue}o(u)}});return()=>{i(),n--,n===0&&rs(t,ss)}},_node:t}}function sc(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===_&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function ic(t){return t.status==="sentinel"?sc(t):t.cache}function hg(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0});return _a(e,{set:n=>e.emit(n)})}function yg(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Hr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&sc(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return _a(o)}function bg(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return _a(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=ic(e);e.emit({...o,[n]:r})}})}function vg(t){return t.get()}function ac(t,e){let n=t._node,r=os.get(n);r||(r=new Set,os.set(n,r)),r.add(e)}function dc(t,e){let n=t._node,r=ss.get(n);r||(r=new Set,ss.set(n,r)),r.add(e)}function Tg(t,e){ac(t,()=>{let n=e();typeof n=="function"&&dc(t,n)})}function wg(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var Us={};Ee(Us,{ACTOR_KEY:()=>$s,COMMAND_HANDLERS:()=>ir,CQRS_EVENT_HANDLERS:()=>ar,CRON_HANDLERS:()=>sr,CommandHandler:()=>gc,EVENT_HANDLERS:()=>rr,EventHandler:()=>hc,GRAPHREFLY_REQUEST_GRAPH:()=>kn,GRAPHREFLY_ROOT_GRAPH:()=>gt,GraphCron:()=>mc,GraphInterval:()=>fc,GraphReflyEventExplorer:()=>Dn,GraphReflyGuard:()=>fp,GraphReflyGuardImpl:()=>ao,GraphReflyModule:()=>Ws,INTERVAL_HANDLERS:()=>or,InjectCqrsGraph:()=>cc,InjectGraph:()=>uc,InjectNode:()=>lc,ObserveGateway:()=>Fs,OnGraphEvent:()=>pc,QUERY_HANDLERS:()=>dr,QueryHandler:()=>yc,SAGA_HANDLERS:()=>ur,SagaHandler:()=>bc,fromHeader:()=>lp,fromJwtPayload:()=>ud,getActor:()=>pp,getGraphToken:()=>lt,getNodeToken:()=>bt,observeSSE:()=>up,observeSubscription:()=>cp,toObservable:()=>as});var Ma=require("rxjs");se();function as(t,e){return e?.raw?new Ma.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===L){n.error(s[1]);return}if(s[0]===I){n.complete();return}}}})):new Ma.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===_)n.next(s[1]);else if(s[0]===L){n.error(s[1]);return}else if(s[0]===I){n.complete();return}}}))}var Wr=require("@nestjs/common");var gt=Symbol.for("graphrefly:root-graph");var kn=Symbol.for("graphrefly:request-graph");function lt(t){return Symbol.for(`graphrefly:graph:${t}`)}function bt(t){return Symbol.for(`graphrefly:node:${t}`)}var rr=new Map,or=new Map,sr=new Map,ir=new Map,ar=new Map,dr=new Map,ur=new Map;function uc(t){return t==="request"?(0,Wr.Inject)(kn):(0,Wr.Inject)(t?lt(t):gt)}function cc(t){return(0,Wr.Inject)(lt(t))}function lc(t){return(0,Wr.Inject)(bt(t))}function pc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=rr.get(o)??[];s.push({nodeName:t,methodKey:r}),rr.set(o,s)})}}function fc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=or.get(o)??[];s.push({ms:t,methodKey:r}),or.set(o,s)})}}function mc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=sr.get(o)??[];s.push({expr:t,methodKey:r}),sr.set(o,s)})}}function gc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ir.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),ir.set(s,i)})}}function hc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ar.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),ar.set(s,i)})}}function yc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=dr.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),dr.set(s,i)})}}function bc(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=ur.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),ur.set(i,a)})}}se();ce();var dp=0,Dn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of rr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let d of a)d[0]===_&&o(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of or){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${dp++}`,d=st(r.ms,{period:r.ms,name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===_&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of sr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${dp++}`,d=Ls(r.expr,{name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===_&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of ir){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of ar){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,d=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===_){let f=p[1];for(let m of f)m.seq>d&&(o(m),d=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of dr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(d=>{for(let u of d)u[0]===_&&o(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of ur){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(lt(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};se();se();var Sh=0;function mr(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++Sh}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[qe,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Je,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Je,n]]))}}}function up(t,e,n){let{actor:r,serialize:o=Nh,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,d,u=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};d=y;let b=()=>y(),v=t.observe(e,{actor:r});u&&(c=mr(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(f)return;let k=w[0];if(k===_){let R=a.encode(ad("data",o(w[1])));u?(p.push({frame:R,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(R)}else if(k===L){let R=a.encode(ad("error",o(w[1])));u?(p.push({frame:R,counted:!1}),l?.(),l=void 0):m.enqueue(R),y();return}else if(k===I||k===fe){if(k===I){let R=a.encode(ad("complete"));u?(p.push({frame:R,counted:!1}),l?.(),l=void 0):m.enqueue(R)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(u?(p.push({frame:a.encode(`: keepalive
8
-
9
- `),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
10
-
11
- `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(u&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{d?.()}catch{}}})}function cp(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,d=t.observe(e,{actor:r}),u=n?.highWaterMark!=null?mr(m=>d.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,u?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||u?.onEnqueue()},p=d.subscribe(m=>{for(let h of m){let g=h[0];if(g===_){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===L){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),c();return}else if(g===I||g===fe){l({done:!0}),c();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||u?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){c();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var Fs=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Eh,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??_h.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?mr(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,d=()=>{a?.dispose(),u(),o.delete(n)},u=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===_)a?.onEnqueue(),dd(r,{type:"data",path:n,value:l[1]});else if(p===L){let f=l[1]instanceof Error?l[1].message:String(l[1]);dd(r,{type:"error",path:n,error:f}),d();return}else if(p===I||p===fe){dd(r,{type:"complete",path:n}),d();return}}});o.set(n,{unsub:u,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function Nh(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function ad(t,e){let n=`event: ${t}
12
- `;if(e!==void 0)for(let r of e.split(`
13
- `))n+=`data: ${r}
14
- `;return n+=`
15
- `,n}function Eh(t){return JSON.parse(t)}function _h(t,e){try{t.send(JSON.stringify(e))}catch{}}function dd(t,e){try{t(e)}catch{}}Fr();var $s="graphReflyActor";function ud(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function lp(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function pp(t){let e=t?.[$s];return e!=null?Gt(e):Ot}var ao=class{constructor(e){this.extractor=e}canActivate(e){let n=Gt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[$s]=n),!0}};function fp(t){return new ao(t??ud())}var mo=require("@nestjs/common"),vp=require("@nestjs/core");Fe();var zs={};Ee(zs,{CqrsGraph:()=>Hs,cqrs:()=>md,cqrsEventKeyOf:()=>Ch,dispatchKeyOf:()=>Lh,sagaInvocationKeyOf:()=>Ih});Re();Jt();var cd={};Ee(cd,{COMPLETE:()=>I,COMPLETE_MSG:()=>Yo,COMPLETE_ONLY_BATCH:()=>Ir,DATA:()=>_,DEFAULT_ACTOR:()=>Ot,DIRTY:()=>oe,DIRTY_MSG:()=>Dt,DIRTY_ONLY_BATCH:()=>Yn,ERROR:()=>L,GraphReFlyConfig:()=>Tn,GuardDenied:()=>ct,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Jo,INVALIDATE_ONLY_BATCH:()=>Lr,NodeImpl:()=>Ae,PAUSE:()=>qe,RESOLVED:()=>z,RESOLVED_MSG:()=>Un,RESOLVED_ONLY_BATCH:()=>Cr,RESUME:()=>Je,START:()=>mt,START_MSG:()=>Jn,TEARDOWN:()=>fe,TEARDOWN_MSG:()=>Qo,TEARDOWN_ONLY_BATCH:()=>Qn,accessHintForGuard:()=>Kr,advanceVersion:()=>qr,autoTrackNode:()=>wn,batch:()=>Z,configure:()=>Na,createVersioning:()=>nr,defaultConfig:()=>je,defaultHash:()=>Yt,derived:()=>O,downWithBatch:()=>Ft,dynamicNode:()=>Hr,effect:()=>he,factoryTag:()=>Te,isBatching:()=>vn,isV1:()=>xa,monotonicNs:()=>W,node:()=>J,normalizeActor:()=>Gt,pipe:()=>Ea,placeholderArgs:()=>He,policy:()=>$t,policyFromRules:()=>Vr,producer:()=>H,registerBuiltins:()=>Br,resolveDescribeFields:()=>Xt,state:()=>A,wallClockNs:()=>ie});Fr();Oe();Re();wa();Jt();se();Ze();Me();ne();es();Oe();Re();Jt();se();ne();Fe();Oe();se();Me();ne();ce();var co=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function uo(t){return t.subscribe(()=>{})}var Mh=64;function We(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new co(t,r),d=A(a.toArray(),{name:n,describeKind:"state",equals:(R,S)=>R===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let R=a.toArray();Z(()=>{d.down([[oe]],{internal:!0}),d.down([[_,R]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(R,S){return`${R}:${S===void 0?"END":S}`}function m(R){if(R.size<Mh)return;let S=R.keys().next();if(S.done)return;let x=R.get(S.value);x!==void 0&&x.dispose(),R.delete(S.value)}function h(R){let S=a.version;try{return R()}finally{a.version!==S&&u()}}function g(R){if(!Number.isInteger(R)||R<0)throw new RangeError(`tail: n must be a non-negative integer (got ${R})`);let S=c.get(R);if(S!==void 0)return c.delete(R),c.set(R,S),S.node;m(c);let x=O([d],([E])=>{let P=E;return R===0||P.length===0?[]:P.slice(Math.max(0,P.length-R))},{initial:a.tail(R),describeKind:"derived"}),N=uo(x);return c.set(R,{node:x,dispose:N}),x}function y(R,S){if(!Number.isInteger(R)||R<0)throw new RangeError(`slice: start must be a non-negative integer (got ${R})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let x=f(R,S),N=l.get(x);if(N!==void 0)return l.delete(x),l.set(x,N),N.node;m(l);let E=O([d],([M])=>{let C=M;return S===void 0?C.slice(R):C.slice(R,S)},{initial:a.slice(R,S),describeKind:"derived"}),P=uo(E);return l.set(x,{node:E,dispose:P}),E}function b(R){let S=p.get(R);if(S!==void 0)return S.node;let x=O([d,R],([E,P])=>{let M=E,C=Math.max(0,Math.trunc(P??0));return M.slice(C)},{initial:[],describeKind:"derived"}),N=uo(x);return p.set(R,{node:x,dispose:N}),x}let v,T;function w(){v===void 0&&(v=J([d],(R,S,x)=>{let N=R[0],P=N!=null&&N.length>0?N.at(-1):x.prevData[0];if(P==null||P.length===0){S.down([[z]]);return}S.emit(P[P.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=O([d],([R])=>R.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),uo(v),uo(T))}let k={entries:d,get size(){return a.size},at(R){return a.at(R)},append(R){h(()=>a.append(R))},appendMany(R){R.length!==0&&h(()=>a.appendMany(R))},clear(){h(()=>a.clear())},trimHead(R){h(()=>a.trimHead(R))},withLatest(){return w(),d},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(R){switch(R.kind){case"tail":return g(R.n);case"slice":return y(R.start,R.stop);case"fromCursor":return b(R.cursor)}},attach(R){let S=R.subscribe(x=>{for(let N of x)N[0]===_&&k.append(N[1])});return()=>S()},attachStorage(R){if(R.length===0)return()=>{};let S=new Map;for(let N of R)S.set(N,a.size);(async()=>{for(let N of R)if(typeof N.loadEntries=="function")try{let E=await Promise.resolve(N.loadEntries());E.entries.length>0&&a.size===0&&(a.restore(E.entries),S.set(N,E.entries.length),u());break}catch{}})();let x=d.subscribe(N=>{for(let E of N){if(E[0]!==_)continue;let P=E[1];for(let M of R){let C=S.get(M)??0;if(P.length<C){try{let V=M.appendEntries(P);V instanceof Promise&&V.catch(()=>{})}catch{}S.set(M,P.length);continue}if(P.length===C)continue;let $=P.slice(C);S.set(M,P.length);try{let V=M.appendEntries($);V instanceof Promise&&V.catch(()=>{})}catch{}}}});return()=>x()},disposeAllViews(){for(let R of c.values())R.dispose();c.clear();for(let R of l.values())R.dispose();l.clear();for(let R of p.values())R.dispose();p.clear()},dispose(){for(let R of c.values())R.dispose();c.clear();for(let R of l.values())R.dispose();l.clear();for(let R of p.values())R.dispose();p.clear()}};return k}var ld=new WeakMap;function mp(t){let e=ld.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=A(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===_)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===I){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===L&&o.down([[L,m[1]]])});i.push(p)}let a=te(o),d=!1,u={node:o,dispose(){if(!d){d=!0;for(let c of i)c?.();i.length=0,a(),ld.delete(t)}}};return ld.set(t,u),u}function Gn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[oe],[_,n+1]]),!0)}var pd=$t((t,e)=>{t("observe"),t("signal"),e("write")});function at(t){let e=We([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??pd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function fd(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))fd(t[e]);return Object.freeze(t)}var gp=new WeakSet;function Bt(t){let e=t.cache,n=typeof e=="number"&&Number.isFinite(e);!n&&e!==void 0&&!gp.has(t)&&(gp.add(t),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let o=(n?e:0)+1;return t.down([[oe],[_,o]]),o}function gr(t,e,n,r,o,s){let i=e(n,r,o);if(i===void 0)return;let a=s!=null?{...i,handlerVersion:s}:i;t.append(a)}function Ce(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(fd):o,i=ie(),a=e.seq?Bt(e.seq):void 0;try{let d=t(...s);return e.audit&&e.onSuccess&&gr(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;gr(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function Lt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(fd):o,i=ie(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=Bt(e.seq));try{a=t(...s),e.audit&&e.onSuccess&&gr(e.audit,e.onSuccess,s,a,{t_ns:i,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;gr(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function ht(t,e,n=0){let r=A(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function js(t,e,n,r=0){let o={},s=new Y(e);for(let i of n){let a=A(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Tt();var an=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},Bs=class extends an{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},Vs=class extends an{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},Ks=class extends an{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},qs=class extends an{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},lo=class extends an{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var po=class extends an{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};ut();ce();var Oh=$t((t,e)=>{t("write"),t("signal"),e("observe")}),Ah=$t((t,e)=>{t("observe"),t("signal"),e("write")}),hp=$t((t,e)=>{t("observe"),t("signal"),e("write")});function fo(t,e){return we("cqrs",t,e)}function yp(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))yp(t[e]);return Object.freeze(t)}var Ch=t=>`${t.type}::${t.aggregateId??"__default__"}`,Lh=t=>t.commandName,Ih=t=>t.eventType,Hs=class extends Y{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=at({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=at({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=ht(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:ie()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=We([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=O([s],([a])=>a,{name:e,describeKind:"state",meta:fo("event",{event_name:e}),guard:hp,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(te(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=We([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=O([d],([f])=>f,{name:i,describeKind:"state",meta:fo("event_aggregate",{event_name:e,aggregate_id:n}),guard:hp,initial:d.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(te(u));let p={log:a,node:u};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,d=this._freezeEventPayload?yp(n):n,u={type:e,payload:d,timestampNs:ie(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(u),i&&i.log.append(u),u}command(e,n){if(this._commandRegs.has(e))throw new Bs("command",e);let r=typeof n=="function"?{handler:n}:n,o=A(void 0,{name:e,describeKind:"state",meta:{...fo("command",{command_name:e}),error:null},guard:Oh});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new qs(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let u=0;for(let c of o.emits){let l=this._aggregateVersions.get(`${c}::${r.aggregateId}`);l!==void 0&&l>u&&(u=l)}if(u!==r.expectedAggregateVersion)throw new Ks(r.aggregateId,r.expectedAggregateVersion,u)}let s=this.resolve(e),i=[],a=!1,d=u=>{s.emit(u,{internal:!0});try{o.handler(u,{emit:(c,l)=>{if(o.emits!==void 0&&!o.emits.includes(c))throw new Vs(e,c,o.emits);i.push(c),this._appendEvent(c,l,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0})}catch(c){throw a=!0,c}};try{Lt(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:l,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),onFailure:([u],c,{t_ns:l,seq:p,errorType:f})=>{let m=c instanceof lo?c:new lo(e,c);return{commandName:e,payload:u,outcome:"failure",error:m,errorType:f,emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}}})(n)}catch(u){throw a&&s.meta.error.emit(u,{internal:!0}),u}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=r.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((E,P)=>E.timestampNs-P.timestampNs||E.seq-P.seq||(E.aggregateId??"").localeCompare(P.aggregateId??""))}function l(N){let E=[];for(let P of N)E.push(...P);return c(E),E}let p=u.map(N=>N.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=d?.saveDebounceMs??1e3,v=d?.saveEvery??1e3,T,w=0;function k(N){if(d?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let E=d.save(N);E instanceof Promise&&E.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let E=d.save(N);E instanceof Promise&&E.catch(()=>{})},b)}}let R=O(u,N=>{let E=l(N),P;if(i==="replay"){let M=a?Object.freeze(E):E;P=o(s,M)}else{let M=E.slice(h);h=E.length;let C=a?Object.freeze(M):M;P=o(g,C),g=P}return k(P),P},{name:n,describeKind:"derived",meta:fo("projection",{projection_name:n,source_events:r}),guard:Ah,initial:y});return this.add(R,{name:n}),this._keepaliveDisposers.push(te(R)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:R,rebuild:async N=>{try{let E=N?.pageSize??1e3,P=N?.fromTier??this._attachedEventTiers[0]?.[0],M=l(u.map($=>$.cache??[])).length,C=s;if(d?.load){let $=await d.load();$!==void 0&&(C=$)}if(!P||!P.loadEntries){let $=l(u.map(G=>G.cache??[])),V=a?Object.freeze($):$;C=o(C,V)}else{let $=new Set(r),V,G=!1;for(;!G;){let K=await P.loadEntries({cursor:V,pageSize:E}),F=[...K.entries].filter(D=>$.has(D.type));c(F);let q=a?Object.freeze(F):F;C=o(C,q),V=K.cursor,G=!V||K.entries.length===0}}if(i==="scan"){let $=l(u.map(G=>G.cache??[])),V=$.slice(M);if(V.length>0){let G=a?Object.freeze(V):V;C=o(C,G)}g=C,h=$.length}return R.emit(C,{internal:!0}),C}catch(E){throw new po(n,E)}},reset:async()=>{try{let N=s;if(d?.load){let C=await d.load();C!==void 0&&(N=C)}let E=l(u.map(C=>C.cache??[])),P=a?Object.freeze(E):E,M=o(N,P);return i==="scan"&&(g=M,h=E.length),R.emit(M,{internal:!0}),M}catch(N){throw new po(n,N)}}}}saga(e,n,r,o={}){let s=n.map(m=>(this._eventLogs.has(m)||this.event(m),this._eventLogs.get(m).node)),i=js(this,`${e}_cursor`,n,0),a=at({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=o.aggregateId,u=o.errorPolicy??"advance",c=new Map;for(let m of n){let h=i[m];c.set(m,h.cache??0);let g=h.subscribe(y=>{for(let b of y)b[0]===_&&c.set(m,b[1])});this._keepaliveDisposers.push(g)}let l=Ce((m,h)=>{r(m)},{audit:a,freeze:!1,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{},onSuccess:([m,h],g,{t_ns:y})=>({eventType:h,outcome:"success",aggregateId:m.aggregateId,event:m,t_ns:y}),onFailure:([m,h],g,{t_ns:y,errorType:b})=>({eventType:h,outcome:"failure",error:g,errorType:b,aggregateId:m.aggregateId,event:m,t_ns:y})}),p={},f=J(s,(m,h)=>{let g=p.n.meta.error;for(let y=0;y<m.length;y++){let b=m[y];if(b==null||b.length===0)continue;let v=b.at(-1);if(!v)continue;let T=n[y],w=i[T],k=c.get(T)??0;if(v.length>k){let R=v.slice(k),S=k;for(let x of R){let N=x;if(d!==void 0&&N.aggregateId!==d){S+=1;continue}try{l(N,T),g.emit(null,{internal:!0}),S+=1}catch(E){if(g.emit(E,{internal:!0}),u==="hold")break;S+=1}}w.emit(S)}}},{name:e,describeKind:"effect",meta:{...fo("saga",{saga_name:e,source_events:n}),error:null}});return p.n=f,this.add(f,{name:e}),this._keepaliveDisposers.push(te(f)),this._sagas.add(e),{node:f,invocations:a,audit:a,cursors:i}}};function md(t,e){let n=new Hs(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",He(s)),n}var hd=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},yd=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},bp,gd;bp=[(0,mo.Module)({})];var dn=class dn{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:gt,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new hd(s),inject:[gt]},{provide:Dn,useFactory:(s,i)=>new Dn(s,i),inject:[gt,vp.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:bt(s),useFactory:i=>i.resolve(s),inject:[gt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new yd,scope:mo.Scope.REQUEST},{provide:kn,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:mo.Scope.REQUEST}),{module:dn,global:!0,providers:o,exports:[gt,...(n.nodes??[]).map(bt),...n.requestScope?[kn]:[]]}}static forFeature(e){let n=[{provide:lt(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[gt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:bt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[lt(e.name)]});return{module:dn,providers:n,exports:[lt(e.name),...(e.nodes??[]).map(r=>bt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:lt(e.name),useFactory:r=>{let o=md(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[gt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:bt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[lt(e.name)]});return{module:dn,providers:n,exports:[lt(e.name),...(e.nodes??[]).map(r=>bt(`${e.name}::${r}`))]}}};gd=Wu(null),dn=Yu(gd,0,"GraphReflyModule",bp,dn),Ju(gd,1,dn);var Ws=dn;var Js={};Ee(Js,{useStore:()=>Ph,useSubscribe:()=>Tp,useSubscribeRecord:()=>Dh});var Vt=require("react");se();function Tp(t){return(0,Vt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function Ph(t){let e=Tp(t),n=(0,Vt.useCallback)(r=>{t.down([[oe],[_,r]])},[t]);return[e,n]}function Dh(t,e){let n=(0,Vt.useRef)(e);n.current=e;let r=(0,Vt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let d of a){let u=n.current(d),c={};for(let l of Object.keys(u))c[l]=u[l].cache;i[d]=c}return i},s=o();return{subscribe:i=>{let a=!1,d=[],u=()=>{for(let p of d)p();d=[]},c=p=>{u();for(let f of p){let m=n.current(f);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});d.push(g)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===_||m[0]===z);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,Vt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Qs={};Ee(Qs,{Signal:()=>Gh});Oe();se();ne();var hr=[];function Ys(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===_&&(e=s)})(),e}var bd=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=A(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=hr[hr.length-1];return e?(this._node.status==="sentinel"&&Ys(this._node),e(this._node)):this._node.status==="sentinel"?Ys(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[oe],[_,e]])})}},vd=class{_node;constructor(e,n){this._node=wn(r=>{hr.push(r);try{return e()}finally{hr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=hr[hr.length-1];return e?(this._node.status==="sentinel"&&Ys(this._node),e(this._node)):this._node.status==="sentinel"?Ys(this._node):this._node.cache}},Gh={State:bd,Computed:vd,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===_){if(r){r=!1;continue}n.data?.(i)}s===L&&n.error?.(i),s===I&&n.complete?.()}})}};var Xs={};Ee(Xs,{useStore:()=>Fh,useSubscribe:()=>wp,useSubscribeRecord:()=>$h});var Kt=require("solid-js");se();function wp(t){let[e,n]=(0,Kt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Kt.getOwner)()?(0,Kt.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function Fh(t){return[wp(t),r=>{t.down([[oe],[_,r]])}]}function $h(t,e){let[n,r]=(0,Kt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let u of o)u();o=[]},i=()=>{let u={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;u[c]=p}return u},a=u=>{s();for(let c of u){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},d=t.subscribe(u=>{u.some(c=>c[0]===_||c[0]===z)&&a(t.cache??[])});return a(t.cache??[]),(0,Kt.getOwner)()?(0,Kt.onCleanup)(()=>{d(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Zs={};Ee(Zs,{useStore:()=>Bh,useSubscribe:()=>jh,useSubscribeRecord:()=>Vh});se();function jh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Bh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[oe],[_,e]])},update(e){let n=e(t.cache);t.down([[oe],[_,n]])}}}function Vh(t,e){return{subscribe(n){let r=[],o=()=>{for(let d of r)d();r=[]},s=()=>{let d={};for(let u of t.cache??[]){let c=e(u),l={};for(let p of Object.keys(c))l[p]=c[p].cache;d[u]=l}return d},i=d=>{o();for(let u of d){let c=e(u);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(d=>{d.some(u=>u[0]===_||u[0]===z)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var ei={};Ee(ei,{useStore:()=>qh,useSubscribe:()=>Kh,useSubscribeRecord:()=>Hh});var Ue=require("vue");se();function Kh(t){let e=(0,Ue.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ue.getCurrentScope)()?(0,Ue.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ue.readonly)(e)}function qh(t){let e=(0,Ue.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ue.getCurrentScope)()?(0,Ue.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ue.computed)({get:()=>e.value,set:r=>{t.down([[oe],[_,r]])}})}function Hh(t,e){let n=(0,Ue.shallowRef)({}),r=new Map;function o(){let a={};for(let[d,u]of r)a[d]={...u.values};n.value=a}function s(a){for(let u of r.values())for(let c of u.subs)c();r.clear();for(let u of a){let c=e(u),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(u,{subs:f,values:p})}let d={};for(let[u,c]of r)d[u]={...c.values};n.value=d}return(0,Ue.watch)(()=>[...(typeof t=="function"?t():(0,Ue.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ue.getCurrentScope)()?(0,Ue.onScopeDispose)(()=>{for(let a of r.values())for(let d of a.subs)d();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ue.readonly)(n)}var ti={};Ee(ti,{create:()=>Wh});se();ne();Fe();var zh=()=>!1;function Wh(t){let e=new Y("zustand"),n=A(void 0,{name:"state",equals:zh});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,d)=>{let u=n.cache,c=typeof a=="function"?a(u):a;n.emit(d?c:{...u,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let d=!0,u=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===_){if(d){d=!1;continue}a(p,u),u=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Ad={};Ee(Ad,{CircuitOpenError:()=>St,ContentAddressedMissError:()=>bo,DEFAULT_AUDIT_GUARD:()=>pd,NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,NativeIndexBackend:()=>wo,NativeListBackend:()=>ko,NativeLogBackend:()=>co,NativeMapBackend:()=>ho,NativePubSubBackend:()=>To,RateLimiterOverflowError:()=>Ln,ResettableTimer:()=>Ie,TimeoutError:()=>In,appendAudit:()=>gr,appendLogStorage:()=>_d,audit:()=>Rl,awaitSettled:()=>Ds,budgetGate:()=>Qt,buffer:()=>Sl,bufferCount:()=>Nl,bufferTime:()=>_l,bumpCursor:()=>Bt,cached:()=>op,canonicalJson:()=>vo,cascadingCache:()=>wf,catchError:()=>Fl,checkpointToRedis:()=>ff,checkpointToS3:()=>pf,circuitBreaker:()=>Rt,combine:()=>Xa,combineLatest:()=>Pl,concat:()=>yl,concatMap:()=>Tl,constant:()=>Rs,contentAddressedStorage:()=>si,createAuditLog:()=>at,createTransport:()=>cn,createWatermarkController:()=>mr,csvRows:()=>Wp,debounce:()=>ed,debounceTime:()=>Dl,decay:()=>It,decorrelatedJitter:()=>_s,defer:()=>tp,delay:()=>kl,deserializeError:()=>Bn,dictKv:()=>If,dictSnapshot:()=>Pf,distill:()=>ri,distinctUntilChanged:()=>ml,domainMeta:()=>we,elementAt:()=>ll,empty:()=>Xl,escapeRegexChar:()=>sd,exhaustMap:()=>vl,exponential:()=>Ns,externalBundle:()=>ni,externalProducer:()=>Fn,fallback:()=>pr,fibonacci:()=>Es,filter:()=>kt,find:()=>cl,first:()=>Ms,firstValueFrom:()=>it,firstWhere:()=>Cs,flatMap:()=>wl,forEach:()=>sn,fromAny:()=>Q,fromAsyncIter:()=>io,fromCSV:()=>zp,fromClickHouseWatch:()=>Qp,fromCron:()=>Ls,fromDrizzle:()=>bf,fromEvent:()=>Ql,fromHTTP:()=>Rd,fromHTTPPoll:()=>Cp,fromHTTPStream:()=>Ap,fromIter:()=>Is,fromKafka:()=>Vp,fromKysely:()=>vf,fromMCP:()=>Pp,fromNATS:()=>ef,fromNDJSON:()=>Yp,fromOTel:()=>Dp,fromPrisma:()=>yf,fromPrometheus:()=>Bp,fromPromise:()=>fr,fromPulsar:()=>Xp,fromRabbitMQ:()=>nf,fromRaf:()=>Yl,fromRedisStream:()=>qp,fromSSE:()=>Op,fromSqlite:()=>mf,fromSqliteCursor:()=>gf,fromStatsD:()=>$p,fromSyslog:()=>Gp,fromTimer:()=>st,fromWebSocket:()=>xd,fromWebSocketReconnect:()=>Ip,fromWebhook:()=>xp,globToRegExp:()=>Ul,interval:()=>Al,jsonCodec:()=>Tr,jsonCodecFor:()=>Af,keepalive:()=>te,kvStorage:()=>ci,last:()=>ul,lightMutation:()=>Ce,linear:()=>Ss,lru:()=>Ed,makeHttpError:()=>Et,map:()=>eo,matchesAnyPattern:()=>Jl,matchesCron:()=>us,memoryAppendLog:()=>Lf,memoryBackend:()=>Ro,memoryKv:()=>So,memorySnapshot:()=>Cf,merge:()=>Ct,mergeMap:()=>Za,mergeReactiveLogs:()=>mp,nameToSignal:()=>$n,ndjsonRows:()=>Up,never:()=>Zl,nodeSignal:()=>Gs,of:()=>id,onFirstData:()=>no,pairwise:()=>gl,parseCron:()=>ds,parsePrometheusText:()=>Sd,parseSSEStream:()=>qt,parseStatsD:()=>jp,parseSyslog:()=>Fp,pausable:()=>Ll,pubsub:()=>Nf,race:()=>bl,rateLimiter:()=>An,reactiveCounter:()=>ip,reactiveIndex:()=>Mf,reactiveList:()=>ii,reactiveLog:()=>We,reactiveMap:()=>Xe,reactiveSink:()=>Ye,reduce:()=>il,registerCursor:()=>ht,registerCursorMap:()=>js,repeat:()=>Cl,replay:()=>Ps,rescue:()=>ro,resolveBackoffPreset:()=>_n,retry:()=>xt,sample:()=>xl,scan:()=>sl,serializeError:()=>jn,share:()=>rp,shareReplay:()=>sp,signalToName:()=>un,singleFromAny:()=>ai,singleNodeFromAny:()=>Of,skip:()=>Qa,snapshotStorage:()=>ui,sortJsonValue:()=>xo,stableJsonString:()=>di,stratify:()=>No,switchMap:()=>ke,take:()=>to,takeUntil:()=>dl,takeWhile:()=>al,tap:()=>pl,tapFirst:()=>fl,throttle:()=>td,throttleTime:()=>Gl,throwError:()=>ep,timeout:()=>Cn,toArray:()=>np,toCSV:()=>of,toClickHouse:()=>sf,toFile:()=>Nd,toHTTP:()=>Rp,toKafka:()=>Kp,toLoki:()=>cf,toMongo:()=>uf,toNATS:()=>tf,toObservable:()=>as,toPostgres:()=>df,toPulsar:()=>Zp,toRabbitMQ:()=>rf,toReadableStream:()=>Mp,toRedisStream:()=>Hp,toS3:()=>af,toSSE:()=>Ep,toSSEBytes:()=>_p,toSqlite:()=>hf,toTempo:()=>lf,toWebSocket:()=>Lp,tokenBucket:()=>rn,topologyDiff:()=>cr,tryIncrementBounded:()=>Gn,valve:()=>Il,verifiable:()=>Rf,window:()=>Ol,windowCount:()=>El,windowTime:()=>Ml,withBreaker:()=>On,withLatestFrom:()=>Mn,withMaxAttempts:()=>Ya,withStatus:()=>nn,workerBridge:()=>Md,workerSelf:()=>Od,wrapMutation:()=>Lt,zip:()=>hl});Oe();Re();se();Me();ne();Oe();se();ne();function kp(t){return{describeKind:"producer",...t}}function Fn(t,e){return H(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[L,i]]))},complete(){r&&(r=!1,n.down([[I]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},kp(e))}function ni(t,e,n){let r=!0,o,s=0,i=0,a={},d=[],u=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=H(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&u()}),kp({...h,name:m}));a[f]=g,d.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[_,m]])};c.error=f=>{r&&(r=!1,Z(()=>{for(let m of d)m.down([[L,f]])}),u())},c.complete=()=>{r&&(r=!1,Z(()=>{for(let f of d)f.down([[I]])}),u())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Z(()=>{for(let f of d)try{f.down([[I]])}catch{}}),u())}})}ze();se();Me();ne();Zr();ms();var wd=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new jt(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function go(t){return t instanceof Error?t:new Error(String(t))}function Uh(t){return t===void 0?null:typeof t=="string"?_n(t):t}function Ye(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:d,stopOn:u,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Uh(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=j=>n?`${n}::${j}`:void 0,w=A(void 0,{equals:()=>!1,name:T("sent")}),k=A(null,{name:T("failed")}),R=A(0,{name:T("inFlight")}),S=A(null,{name:T("errors")}),x=v?A(0,{name:T("buffered")}):void 0,N=s?A(!1,{name:T("paused")}):void 0,E=0,P=j=>{E+=j,R.down([[_,E]])},M=j=>{try{r?.(j)}catch{}try{S.down([[_,j]])}catch{}},C=new Set,$=j=>{C.add(j);let ae=()=>C.delete(j);j.then(ae,ae)},V=(j,ae,le)=>{let Ne=y?y(ae-1,le,null):0,xe=Ne==null?0:typeof Ne=="number"&&Ne>0?Ne:0,Ke=Math.max(1,Math.ceil(xe/1e6));return new Promise(pe=>{setTimeout(()=>pe(j()),Ke)})},G=j=>j!=null&&typeof j=="object"&&typeof j.then=="function",K=j=>{let ae;try{ae=d?d(j):j}catch(pe){let ue=go(pe);return M({stage:"serialize",error:ue,value:j}),k.down([[_,{value:j,error:ue,attempts:0}]]),Promise.resolve()}let le=0,Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j,attempt:le}),!(le<g&&b(ue,le))){k.down([[_,{value:j,error:ue,attempts:le}]]);return}return V(Ke,le,ue)},xe=()=>{P(-1),w.down([[_,j]])};function Ke(){le+=1,P(1);let pe;try{pe=p(ae,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,q=new wd(F),D,B=!1,re=()=>{x?.down([[_,q.length]])},ye=j=>{N&&N.down([[_,j]])},ee=s?.strategy??"drop-oldest",me=(j,ae)=>{let le={value:j,payload:ae};if(q.length<F)return q.push(le),re(),!0;if(ee==="drop-oldest"){let xe=q.shift();return q.push(le),re(),ye(!0),k.down([[_,{value:xe.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ee==="drop-newest")return ye(!0),k.down([[_,{value:j,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ne=new Error("backpressure: buffer overflow");return M({stage:"send",error:Ne,value:j}),k.down([[_,{value:j,error:Ne,attempts:0}]]),ye(!0),!1},Le=j=>{let ae=0,le=j.map(pe=>pe.payload),Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j.map(hn=>hn.value),attempt:ae}),!(ae<g&&b(ue,ae))){for(let{value:hn}of j)k.down([[_,{value:hn,error:ue,attempts:ae}]]);return}return V(Ke,ae,ue)},xe=()=>{P(-1);for(let{value:pe}of j)w.down([[_,pe]])};function Ke(){ae+=1,P(1);let pe;try{pe=f(le,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},rt=async j=>{for(let ae of j)await Qe(ae.value,ae.payload)},Qe=(j,ae)=>{let le=0,Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j,attempt:le}),!(le<g&&b(ue,le))){k.down([[_,{value:j,error:ue,attempts:le}]]);return}return V(Ke,le,ue)},xe=()=>{P(-1),w.down([[_,j]])};function Ke(){le+=1,P(1);let pe;try{pe=p(ae,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},U=()=>{if(B||q.length===0)return Promise.resolve();let j=q.drain();if(re(),ye(!1),f!==void 0){let le=Le(j);return $(le),le}let ae=rt(j);return $(ae),ae},de=()=>{D!==void 0||B||a<=0||(D=setTimeout(()=>{D=void 0,U()},a))},De=t.subscribe(j=>{for(let ae of j){let le=ae[0];if(le!==_)try{c?.(ae)}catch{}if(le===_){let Ne=ae[1];if(v){let xe;if(d)try{xe=d(Ne)}catch(pe){let ue=go(pe);M({stage:"serialize",error:ue,value:Ne}),k.down([[_,{value:Ne,error:ue,attempts:0}]]);continue}else xe=Ne;if(!me(Ne,xe))continue;q.length>=i?U():de()}else{let xe=K(Ne);$(xe)}}else je.messageTier(le)>=3&&v&&(D!==void 0&&(clearTimeout(D),D=void 0),U())}}),$e;if(u){let j=!1;$e=u.subscribe(ae=>{if(!j){j=!0;return}ae.length>0&&!Ve&&Se()})}let Ve=!1,Se=()=>{if(Ve)return;Ve=!0,D!==void 0&&(clearTimeout(D),D=void 0),v&&U(),B=!0,$e?.(),De();let j=ae=>{try{ae.down([[fe]])}catch{}};j(S),j(k),j(w),j(R),x&&j(x),N&&j(N);try{l?.()}catch{}},X={dispose:Se,sent:w,failed:k,inFlight:R,errors:S};return v&&(X.buffered=x,X.flush=async()=>{B||(await U(),await Promise.all(C))}),N&&(X.paused=N),X}on();ce();function Nt(t){return{describeKind:"producer",...t}}function xd(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return H(s=>{let i=!0,a,d=()=>{let y=a;a=void 0,y?.()},u=y=>{i&&(i=!1,s.down([y]),d())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){u([L,v])}},l=y=>{u([L,y])},p=()=>{u([I])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){u([L,y])}return()=>{i=!1,d()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,d()}},Nt(o))}function xp(t,e){return Fn(t,e)}function Rd(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:d=!1,refetchOnSubscribe:u=!1,...c}=e??{},l=A(0,{name:`${c.name??"http"}/fetchCount`}),p=A(0,{name:`${c.name??"http"}/lastUpdated`}),f=A(!1,{name:`${c.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[L,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async R=>{if(clearTimeout(k),!w)return;if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);let S=await s(R);w&&(Z(()=>{m+=1,l.down([[_,m]]),p.down([[_,ie()]]),f.down([[_,!0]]),v.emit(S)}),d&&v.down([[I]]))}).catch(R=>{clearTimeout(k),w&&(R&&R.name==="AbortError"||v.down([[L,R]]))}),()=>{w=!1,T.abort()}},y=H(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...Nt(c),resubscribable:u});return{...nn(y),fetchCount:l,lastUpdated:p,fetched:f}}function Rp(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:d,flushIntervalMs:u,retry:c,onTransportError:l}=n??{},p=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return d!==void 0||u!==void 0?Ye(t,{onTransportError:l,retry:c,batchSize:d,flushIntervalMs:u,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
- `):h=JSON.stringify(m),await p(h)}}):Ye(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function Sp(t){return Symbol.keyFor(t)??t.description??"message"}function yr(t,e){return typeof t=="string"?t:e(t)}function Np(t,e){let n=`event: ${t}
17
- `;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
18
- `}return`${n}
19
- `}function Ep(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:d,signal:u,eventNameResolver:c=Sp}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),u?.removeEventListener("abort",v),g(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(Np(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(je.isLocalOnly(k)&&!(k===oe&&a))){if(k===_){b(r,yr(w[1],n));continue}if(k===L){b(o,yr(w[1],n)),y();return}if(k===I){b(s),y();return}!i&&k===z||b(c(k),w.length>1?yr(w[1],n):void 0)}}}),d!==void 0&&d>0&&(h=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
20
-
21
- `))},d)),u?.aborted?v():u?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function _p(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:d,signal:u,eventNameResolver:c=Sp}=e??{},l=new TextEncoder;return H(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(Np(b,v)))},g=()=>{f&&(f=!1,p.down([[I]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!(je.isLocalOnly(T)&&!(T===oe&&a))){if(T===_){h(r,yr(v[1],n));continue}if(T===L){h(o,yr(v[1],n)),f=!1,p.down([[I]]);return}if(T===I){h(s),f=!1,p.down([[I]]);return}!i&&T===z||h(c(T),v.length>1?yr(v[1],n):void 0)}}});return d!==void 0&&d>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
22
-
23
- `))},d)),u?.aborted?g():u?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),u?.removeEventListener("abort",g),y()}})}function Mp(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===_)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===L){n=!0;try{r.error(s[1])}catch{}return}else if(i===I){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*qt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],d,u,c=[],l=()=>{if(a.length===0&&i==="message"&&d===void 0){a=[];return}let w=a.join(`
24
- `);c.push({event:i,data:n(w),id:d,retry:u}),i="message",a=[],d=void 0,u=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),R=k<0?w:w.slice(0,k),S=k<0?"":w.slice(k+1);switch(S.startsWith(" ")&&(S=S.slice(1)),R){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(d=S);break;case"retry":{let x=Number(S);Number.isFinite(x)&&(u=x);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let R=s.split(/\r?\n/);s=R.pop()??"";for(let S of R)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:k}=await g.read();if(k)break;for(f(w,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(f(k.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Op(t,e){let{parse:n,...r}=e??{};return H(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let d of qt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(d)}s&&o.down([[I]])}catch(d){s&&o.down([[L,d]])}})(),()=>{s=!1,i.abort()}},Nt(r))}function Ap(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return H(a=>{let d=!0,u=new AbortController;if(s?.aborted)return a.down([[L,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>u.abort(s.reason),{once:!0});let c=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let p=await fetch(t,{method:n,headers:r,body:c,signal:u.signal});if(!d)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;d;){let{value:m,done:h}=await f.read();if(h)break;m&&a.emit(m)}d&&a.down([[I]])}catch(p){if(!d||p&&p.name==="AbortError")return;a.down([[L,p]])}})(),()=>{d=!1,u.abort()}},Nt(i))}function Cp(t,e){let{intervalMs:n=5e3,...r}=e??{};return ke(st(n,{period:n}),()=>Rd(t,{...r,completeAfterFetch:!0}).node)}function Lp(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:d,retry:u,backpressure:c,stopOn:l}=n??{},p=!1,f=y=>{if(!p){p=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{d?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=Ye(t,{onTransportError:d,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:u,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===I&&o||y[0]===L&&s)&&f(y)}});return m=()=>{p=!0,g.dispose()},e.addEventListener("close",m),g}function Ip(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return xt(()=>xd(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Pp(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return Fn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Dp(t,e){return ni(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{Z(()=>{for(let d of a)r(d)})},onMetrics:a=>{Z(()=>{for(let d of a)o(d)})},onLogs:a=>{Z(()=>{for(let d of a)s(d)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Gp(t,e){return Fn(t,e)}function Fp(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=ie();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:ie()}}function $p(t,e){return Fn(t,e)}var Jh={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function jp(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=Jh[o]??"counter",i=s==="set"?0:Number(r),a,d={};for(let u=2;u<e.length;u++){let c=e[u].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.slice(1).split(",")){let[p,f]=l.split(":");p&&(d[p]=f??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:d,timestampNs:ie()}}function Bp(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),d=0;return ke(st(0,{period:a,signal:s}),()=>H(u=>{let c=!0,l=new AbortController,p=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(p),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!c)return;let g=Sd(h);for(let y of g)u.emit(y);d=0,u.down([[I]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;d+=1,d>=i&&u.down([[L,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function Sd(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
25
- `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},d,u,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=Yh(f);let m=s.slice(p+1).trim().split(/\s+/);d=m[0]??"",u=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",d=p[1]??"",u=p[2]}if(!i||!d)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(d),timestampMs:u?Number(u):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:ie()})}return e}function Yh(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function Vp(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return H(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:u,partition:c,message:l})=>{if(!a)return;let p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:u,partition:c,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:ie()})}})}catch(u){a&&i.down([[L,u]])}})(),()=>{a=!1}},Nt(s))}function Kp(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Ye(t,{onTransportError:i,send:async a=>{let d=s?.(a)??null,u=o(a);await e.send({topic:n,messages:[{key:d,value:Buffer.from(u)}]})}})}function qp(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let u=0;u<a.length;u+=2)if(a[u]==="data")try{return JSON.parse(a[u+1])}catch{return a[u+1]}let d={};for(let u=0;u<a.length;u+=2)d[a[u]]=a[u+1];return d},...i}=n??{};return H(a=>{let d=!0,u=o;return(async()=>{for(;d;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,u);if(!d)return;if(l)for(let[p,f]of l)for(let[m,h]of f)u=m,a.emit({id:m,key:e,data:s(h),timestampNs:ie()})}catch(l){if(!d)return;a.down([[L,l]]);return}})(),()=>{d=!1}},Nt(i))}function Hp(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Ye(t,{onTransportError:i,send:async a=>{let d=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...d):e.xadd(n,"*",...d))}})}function zp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>Jp(d,n));return H(d=>{let u=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(u)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let h of m){if(u)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";d.emit(y)}}if(!u&&p.trim()){let f=a(p);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=f[h]??"";d.emit(m)}}u||d.down([[I]])}catch(l){u||d.down([[L,l]])}})(),()=>{u=!0}},Nt(i))}function Wp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>Jp(d,n));return J([t],(d,u,c)=>{let l=d[0];if(l==null||l.length===0)return;let p=c.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&o&&(p.headers=o.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!p.headers&&r){p.headers=g;continue}p.headers||(p.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=g[b]??"";u.emit(y)}}},{describeKind:"derived",...i})}function Up(t,e){return J([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let d=i.buffer.split(/\r?\n/);i.buffer=d.pop()??"";for(let u of d)if(u.trim())try{r.emit(JSON.parse(u))}catch(c){r.down([[L,c]]);return}}},{describeKind:"derived",...e??{}})}function Jp(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function Yp(t,e){return H(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let d of a){if(r)return;let u=d.trim();u&&n.emit(JSON.parse(u))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[I]])}catch(s){r||n.down([[L,s]])}})(),()=>{r=!0}},Nt(e))}function Qp(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),d=0;return ke(st(0,{period:a,signal:s}),()=>H(u=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)u.emit(m);d=0,u.down([[I]])}catch(p){if(!c)return;d+=1,d>=i&&u.down([[L,p]])}})(),()=>{c=!1}}))}function Xp(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return H(a=>{let d=!0;return(async()=>{for(;d;)try{let c=await t.receive();if(!d)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:ie()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let h=t;try{let g=h.negativeAcknowledge?.(c);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(f)}}catch(c){d&&a.down([[L,c]]);return}})(),()=>{d=!1}},Nt(s))}function Zp(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Ye(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function ef(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let d=r.decode(a);try{return JSON.parse(d)}catch{return d}},...i}=n??{};return H(a=>{let d=!0,u=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of u){if(!d)return;let p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:s(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:ie()})}d&&a.down([[I]])}catch(l){d&&a.down([[L,l]])}})(),()=>{d=!1}},Nt(i))}function tf(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Ye(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function nf(t,e,n){let{autoAck:r=!0,deserialize:o=d=>{try{return JSON.parse(d.toString())}catch{return d.toString()}},onAckError:s,...i}=n??{},a=d=>{if(s)try{s(d instanceof Error?d:new Error(String(d)))}catch{}};return H(d=>{let u=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!u)return;if(f===null){u&&d.down([[L,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:o(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:ie()};if(r){d.emit(m);try{t.ack(f)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(f,!1,v)}catch(T){a(T)}}};d.emit(y)}},{noAck:!1})).consumerTag}catch(p){u&&d.down([[L,p]])}})(),()=>{u=!1,c!==void 0&&t.cancel(c)}},Nt(i))}function rf(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Ye(t,{onTransportError:i,send:a=>{let d=s(a),u=o(a);e.publish(n,d,u)}})}function Nd(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
- `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},u=o>0||s<Number.POSITIVE_INFINITY?Ye(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Ye(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=u.dispose;return u.dispose=()=>{c();try{e.end()}catch{}},u}function kd(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
- `)?`"${t.replace(/"/g,'""')}"`:t}function of(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:d=Number.POSITIVE_INFINITY,onTransportError:u,...c}=n,l=!1;return Nd(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>kd(g,o)).join(o),h=r.map(g=>kd(i(f,g),o)).join(o);return`${m}
28
- ${h}
29
- `}return`${r.map(m=>kd(i(f,m),o)).join(o)}
30
- `},flushIntervalMs:a,batchSize:d,onTransportError:u,...c})}function sf(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=u=>u,onTransportError:d}=r??{};return Ye(t,{onTransportError:d,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async u=>{await e.insert({table:n,values:u,format:i})}})}function af(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:d=p=>p,onTransportError:u}=r??{},c=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return Ye(t,{onTransportError:u,batchSize:i,flushIntervalMs:a,serialize:d,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(h=>JSON.stringify(h)).join(`
31
- `)}
32
- `:JSON.stringify(p),m=s(l,ie());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function df(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return Ye(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function uf(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ye(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function cf(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ye(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${ie()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function lf(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ye(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function pf(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},d={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(u){let c=Math.floor(ie()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(u)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([d],{onError:u=>a?.(u)})}function ff(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,d={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(u){let c;try{c=JSON.stringify(u)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let u=await e.get(a);if(u!=null)try{return JSON.parse(u)}catch{return}}};return t.attachSnapshotStorage([d],{onError:u=>i?.(u)})}function mf(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let d=t.query(e,o).map(r);i.emit(d),i.down([[I]])}catch(a){i.down([[L,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function gf(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let a=t.iterate(e,o);Z(()=>{for(let d of a)i.emit(r(d));i.down([[I]])})}catch(a){i.down([[L,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function hf(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(M,C)=>({sql:`INSERT INTO "${C.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(M)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:d=0}=r??{},u=M=>o(M,n);if(!i)return Ye(t,{onTransportError:s,serialize:u,send:M=>{let C=M;e.query(C.sql,C.params)}});let c=A(null),l=A(void 0,{equals:()=>!1}),p=A(null),f=A(0),m=A(0),h=M=>{try{s?.(M)}catch{}try{c.down([[_,M]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[_,g.length]]),w=M=>{v||l.down([[_,M]])},k=M=>{v||p.down([[_,M]])},R=M=>{v||f.down([[_,M]])},S=M=>{v||h(M)},x=()=>{if(g.length===0||y)return;y=!0,R(1);try{e.query("BEGIN",[])}catch(V){y=!1,R(0),S({stage:"send",error:V instanceof Error?V:new Error(String(V)),value:void 0});return}let M=g;g=[],T();let C,$=0;for(let V of M)try{e.query(V.query.sql,V.query.params),$+=1}catch(G){C=G instanceof Error?G:new Error(String(G));break}if(C){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:C,value:void 0});for(let V of M)k({value:V.value,error:C,attempts:1})}else try{e.query("COMMIT",[]);for(let V of M)w(V.value)}catch(V){let G=V instanceof Error?V:new Error(String(V));S({stage:"send",error:G,value:void 0});for(let K=0;K<$;K++)k({value:M[K].value,error:G,attempts:1})}y=!1,R(0)},N=()=>{d>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,x()},d))},E=t.subscribe(M=>{for(let C of M){let $=C[0];if($===_){let V=C[1],G;try{G=u(V)}catch(K){let F=K instanceof Error?K:new Error(String(K));h({stage:"serialize",error:F,value:V}),p.down([[_,{value:V,error:F,attempts:0}]]);continue}g.push({value:V,query:G}),T(),g.length>=a?x():N()}else je.messageTier($)>=3&&x()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),x(),v=!0,E();for(let M of[c,l,p,f,m])try{M.down([[fe]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||x()}}}function yf(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return H(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[I]]))}).catch(a=>{if(i)try{s.down([[L,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function bf(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[I]]))}).catch(i=>{if(s)try{o.down([[L,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function vf(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[I]]))}).catch(i=>{if(s)try{o.down([[L,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Zr();se();ne();function Ed(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let d=n;i.push(d.key),r(d),t.delete(d.key)}return i},size(){return t.size}}}function Tf(t){return t!=null&&typeof t.then=="function"}function br(t){Tf(t)&&t.catch(()=>{})}function wf(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Ed():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{br(t[p].save(u,c))}catch{}}function a(u,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(u)}catch{continue}if(Tf(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[_,h]]),i(u,h,m)):a(u,c,m+1)},()=>{a(u,c,m+1)});return}if(f!==void 0){c.down([[_,f]]),i(u,f,p);return}}}function d(){if(!(!o||r<=0))for(;o.size()>=r;){let u=o.evict(1);if(u.length===0)break;for(let c of u){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{br(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&br(h.call(t[m],c))}catch{}}l.down([[fe]])}n.delete(c)}}}return{load(u){let c=n.get(u);if(c)return o?.touch(u),c;o&&r>0&&o.size()>=r&&d();let l=A(void 0);return n.set(u,l),o?.insert(u),a(u,l),l},save(u,c){if(s)for(let p of t)try{br(p.save(u,c))}catch{}else if(t[0])try{br(t[0].save(u,c))}catch{}let l=n.get(u);if(l)l.down([[_,c]]),o?.touch(u);else{o&&r>0&&o.size()>=r&&d();let p=A(c);n.set(u,p),o?.insert(u)}},invalidate(u){let c=n.get(u);c&&a(u,c)},delete(u){o?.delete(u);let c=n.get(u);c&&c.down([[fe]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&br(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Oe();se();Ze();ne();ze();Oe();Re();se();ne();var ho=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=W(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=W(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return W()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??W())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Xe(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new ho({maxSize:n,defaultTtl:r}),d=A(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=a.toMap();Z(()=>{d.down([[oe]]),d.down([[_,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}ce();function Qh(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Rf(t,e,n){let r=Q(t),o=r.v!=null,s=A(n?.initialVerified??null,{meta:{...Te("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=Ct(Q(n.trigger),r):i?a=Q(n.trigger):n?.autoVerify&&(a=r),a!==null){let d;if(a===r)d=ke(r,u=>e(u));else{let u=r.cache;r.subscribe(c=>{for(let l of c)l[0]===_&&(u=l[1])}),d=ke(a,()=>e(u))}sn(d,u=>{Z(()=>{if(s.down([[_,u]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[_,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function kf(t){t.subscribe(()=>{})}function yo(t){return t instanceof Map?t:new Map}function xf(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Z(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function ri(t,e,n){let r=Q(t),o=Xe(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?Q(n.context):A(null),d=yo(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===_&&(d=yo(m[1]))});let u=Q(e(r,o.entries));if(sn(u,f=>{xf(o,f)}),n.evict){let f=new Map,m=O([o.entries],([h])=>{let g=[],y=yo(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(Qh(T)){if(!f.has(b)){let w=sn(T,k=>{k===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});sn(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=Q(n.consolidateTrigger),m=ke(f,()=>n.consolidate(d));sn(m,h=>{xf(o,h)})}let l=O([o.entries,a],([f,m])=>{let g=[...yo(f).entries()].map(([v,T])=>({key:v,value:T,score:n.score(T,m),cost:n.cost(T)}));g.sort((v,T)=>T.score-v.score);let y=[],b=s;for(let v of g)v.cost<=b&&(y.push({key:v.key,value:v.value,score:v.score}),b-=v.cost);return y},{meta:{...Te("distill",{budget:s})}}),p=O([o.entries],([f])=>yo(f).size);return kf(l),kf(p),{store:o,compact:l,size:p}}Da();async function oi(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=Sf[r[s]];return o}var Sf=new Array(256);for(let t=0;t<256;t++)Sf[t]=t.toString(16).padStart(2,"0");var bo=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function vo(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function si(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=vo(s(a)),u=await oi(d);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let d=await i(a),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new bo(d,a);return}return u},async store(a,d){if(o==="read")return;let u=await i(a);await e.save(u,d)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let d=await i(a);await e.delete(d)}}}Oa();async function Et(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}ut();ze();Oe();se();Me();var To=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function Nf(t={}){let{backend:e}=t,n=e??new To,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=J({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){Z(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[fe]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Oe();se();ne();function Ef(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function Xh(t,e){let n=Ef(t[0],e[0]);return n!==0?n:Ef(t[1],e[1])}function _f(t){return[t.secondary,t.primary]}function vr(t,e){let n=_f(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Xh(n,_f(t[s]))>0?r=s+1:o=s}return r}var wo=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let d=vr(this._buf,s);this._buf.splice(d,1)}let a=vr(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let d=vr(this._buf,s);this._buf.splice(d,1)}let a=vr(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=vr(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=vr(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Zh(t){return t.subscribe(()=>{})}function Mf(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new wo;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=A([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),d=O([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),u=Zh(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[oe]]),a.down([[_,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:d,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){c||(c=!0,u())}}}Oe();se();ne();var ko=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function ii(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new ko(t),i=A(s.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=s.toArray();Z(()=>{i.down([[oe]]),i.down([[_,u]])})}function d(u){let c=s.version;try{return u()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(u){return s.at(u)},append(u){d(()=>s.append(u))},appendMany(u){d(()=>s.appendMany(u))},insert(u,c){d(()=>s.insert(u,c))},insertMany(u,c){d(()=>s.insertMany(u,c))},pop(u=-1){return d(()=>s.pop(u))},clear(){d(()=>s.clear())},dispose(){}}}on();se();ce();function ai(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),d;a!=null&&typeof a.then=="function"?d=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?d=it(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?d=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?d=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(a);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}function Of(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=Q(t(o));r.set(s,a);let d=a.subscribe(u=>{for(let c of u)if(c[0]===L||c[0]===I){r.get(s)===a&&r.delete(s),d();return}});return a}}ce();function xo(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(xo);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=xo(e[o]);return r}function di(t){return JSON.stringify(xo(t),void 0,0)}var ey=new TextEncoder,ty=new TextDecoder("utf-8",{fatal:!0}),Tr={name:"json",version:1,encode(t){return ey.encode(di(t))},decode(t){return JSON.parse(ty.decode(t))}};function Af(){return Tr}function Ro(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function ui(t,e={}){let n=e.codec??Tr,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,d,u={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=d??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{d=p});d=p}return u}function _d(t,e={}){let n=e.codec??Tr,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,d,u={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(d??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return d=f.finally(()=>{d===f&&(d=void 0)}),d}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return u}function ci(t,e={}){let n=e.codec??Tr,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function Cf(t){return ui(Ro(),t)}function Lf(t){return _d(Ro(),t)}function So(t){return ci(Ro(),t)}function If(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return ci(n,e)}function Pf(t,e){return ui({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}se();Me();ne();Fe();function No(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=A(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)ny(o,e,s,i);return o}function ny(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,d=!1,u=s,c=!1,l=n.cache??[];function p(h){if(d){d=!1;let g=u;if(u=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[oe],[z]]))}else c?(c=!1,h.down([[oe],[z]])):h.down([[z]])}}let f=J([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===oe?(g===0?(i=!0,c=!0):a=!0,!0):b===_||b===z?(g===0?(i=!1,d=!0,u=b===_?h[1]:s):(b===_&&(l=h[1]),a=!1),i||a||p(y),!0):b===I||b===L||b===fe?(i=!1,a=!1,d=!1,u=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}At();var li=Math.LN2/604800;function It(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}Oe();se();Me();ne();ze();ce();se();var ry=new Map([[nt,"INVALIDATE"],[qe,"PAUSE"],[Je,"RESUME"],[fe,"TEARDOWN"],[I,"COMPLETE"],[L,"ERROR"]]),oy=new Map([["INVALIDATE",nt],["PAUSE",qe],["RESUME",Je],["TEARDOWN",fe],["COMPLETE",I],["ERROR",L]]);function un(t){let e=ry.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function $n(t){let e=oy.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function jn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function Bn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function cn(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return cn(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function sy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Md(t,e){let n=sy(t)?t:cn(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=A("connecting",{name:`${r}::meta::status`}),d=A(null,{name:`${r}::meta::error`}),u=new Map,c=new Map;for(let b of s){let v=A(void 0,{name:`${r}::${b}`});u.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=J(b,(w,k)=>{let R={};for(let S=0;S<o.length;S++){let[x]=o[S],N=w[S];N!=null&&N.length>0&&(R[x]=N.at(-1))}Object.keys(R).length!==0&&k.emit(R)},{name:`${r}::aggregated`,partial:!0});l=he([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let R=[];for(let N of Object.keys(k)){let E=i[N];E&&R.push(...E(k[N]))}let S;for(let[N,E]of o)N in k&&E.v!=null&&(S==null&&(S={}),S[N]=E.v.version);let x={t:"b",u:k,...S?{v:S}:{}};try{n.post(x,R.length>0?R:void 0)}catch(N){d.down([[_,N instanceof Error?N:new Error(String(N))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Z(()=>{for(let[w,k]of Object.entries(v.stores)){let R=u.get(w);R&&R.down([[_,k]])}}),a.down([[_,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=u.get(v.s);T&&T.down([[_,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let S=c.get(T);if(S!=null&&k<=S)continue;c.set(T,k)}let R=u.get(T);R&&R.down([[_,w]])}});break}case"e":{let T=u.get(v.s);T&&T.down([[L,Bn(v.err)]]);break}case"s":{let T=$n(v.sig);if(!T)break;let w=v.s==="*"?[...u.values()]:u.has(v.s)?[u.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let k of w){let R=k[0];R!==_&&(je.isLocalOnly(R)||(R===L?n.post({t:"e",s:b,err:jn(k[1])}):n.post({t:"s",s:b,sig:un(R),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=kt(a,w=>w==="connected");h=Ms(Ct(eo(b,()=>"timeout"),eo(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===_&&k[1]==="timeout"&&(d.down([[_,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:un(fe)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[_,"closed"]]),c.clear(),u.clear()}}let y={meta:{status:a,error:d},destroy:g};for(let[b,v]of u)y[b]=v;return y}Oe();se();Me();ne();function iy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Od(t,e){let n=iy(t)?t:cn(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=A(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let d=e.expose(a),u=Object.entries(d),c,l=!1;if(u.length>0){let g=u.map(([,v])=>v),y=J(g,(v,T)=>{let w={};for(let k=0;k<u.length;k++){let[R]=u[k],S=v[k];S!=null&&S.length>0&&(w[R]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=he([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let x=o[S];x&&w.push(...x(T[S]))}let k;for(let[S,x]of u)S in T&&x.v!=null&&(k==null&&(k={}),k[S]=x.v.version);let R={t:"b",u:T,...k?{v:k}:{}};try{n.post(R,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of u){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==_&&(je.isLocalOnly(w)||(w===L?n.post({t:"e",s:g,err:jn(T[1])}):n.post({t:"s",s:g,sig:un(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{Z(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[_,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[_,y.d]]);break}case"b":{Z(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[_,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[L,Bn(y.err)]]);break}case"s":{let b=$n(y.sig);if(!b)break;if(b===fe&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of u)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}Tt();Tt();var Bu={};Ee(Bu,{SNAPSHOT_WIRE_VERSION:()=>Wo,SurfaceError:()=>_e,ai:()=>Bi,asSurfaceError:()=>aa,cqrs:()=>zs,createGraph:()=>Mr,deleteSnapshot:()=>ma,demoShell:()=>Ki,diffSnapshots:()=>pa,domainTemplates:()=>qi,graphspec:()=>ji,harness:()=>Zi,inspect:()=>oa,jobQueue:()=>Qi,layout:()=>ia,listSnapshots:()=>fa,memory:()=>Pi,messaging:()=>Mi,orchestration:()=>Oi,process:()=>sa,reduction:()=>Gi,restoreSnapshot:()=>la,runReduction:()=>da,saveSnapshot:()=>ca,surface:()=>ga});var Bi={};Ee(Bi,{AgentLoopGraph:()=>Di,AllTiersExhaustedError:()=>Mo,BudgetExhaustedError:()=>Ti,ChatStreamGraph:()=>Ai,CircuitOpenError:()=>St,DEFAULT_DECAY_RATE:()=>li,FallbackMissError:()=>my,LLMTimeoutError:()=>kr,ReplayCacheMissError:()=>qn,ToolRegistryGraph:()=>Ci,admissionFilter3D:()=>yb,admissionScored:()=>im,agentLoop:()=>kb,agentMemory:()=>xb,anthropicAdapter:()=>Cd,canonicalJson:()=>Id,cascadingLlmAdapter:()=>Wd,chatStream:()=>tu,composePricing:()=>Ly,computePrice:()=>jd,contentGate:()=>lb,costMeterExtractor:()=>sb,createAdapter:()=>_y,createCapabilitiesRegistry:()=>ay,createPricingRegistry:()=>Ay,dryRunAdapter:()=>Vn,fallbackAdapter:()=>Pd,frozenContext:()=>Yy,gatedStream:()=>nb,gaugesAsContext:()=>Rb,googleAdapter:()=>Dd,graphFromSpec:()=>Tm,graphFromSpecReactive:()=>Ib,handoff:()=>fb,keywordFlagExtractor:()=>ab,knobsAsTools:()=>Db,llmConsolidator:()=>eu,llmExtractor:()=>Zd,memoryRetrieval:()=>cu,memoryWithKG:()=>du,memoryWithTiers:()=>uu,memoryWithVectors:()=>au,observableAdapter:()=>My,openAICompatAdapter:()=>Fd,parseRateLimitFromError:()=>qd,pricingFor:()=>Iy,promptCall:()=>Xd,promptNode:()=>Ao,redactor:()=>pb,registryPricing:()=>Cy,resilientAdapter:()=>zy,streamExtractor:()=>db,streamingPromptNode:()=>tb,suggestStrategy:()=>wm,suggestStrategyReactive:()=>Fb,systemPromptBuilder:()=>rb,tier:()=>qy,toolCallExtractor:()=>cb,toolExecution:()=>nu,toolRegistry:()=>ru,toolSelector:()=>hb,validateGraphDef:()=>$b,withBreaker:()=>Bd,withBudgetGate:()=>Kd,withDryRun:()=>Dy,withRateLimiter:()=>zd,withReplayCache:()=>_o,withRetry:()=>Ud,withTimeout:()=>Jd,zeroPrice:()=>vi});ne();function Eo(t,e){return`${t}::${e}`}function ay(t){let e=Xe({name:"capabilitiesRegistry"}),n=u=>{e.set(Eo(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(Eo(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=O([e.entries],([u])=>u instanceof Map?Array.from(u.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(Eo(u,c));return l&&e.delete(Eo(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=Eo(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=O([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:d,byProvider(u){let c=i.get(u);if(c)return i.delete(u),i.set(u,c),c;let l=O([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}Re();function Cd(t={}){return t.sdk?py(t):ly(t)}function pi(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=dy(t,e?.systemPrompt),a={model:o,messages:i.map(uy),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(cy)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function dy(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
33
-
34
- `):void 0,chat:r}}function uy(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function cy(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function fi(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Ld(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function Df(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Ld(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function ly(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let d=pi(i,a,t.model,!1),u=W(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await Et(c,"Anthropic");let l=await c.json(),p=Math.max(0,(W()-u)/1e6);return Df(l,p)},async*stream(i,a){let d=pi(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:a?.signal});if(!u.ok)throw await Et(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of qt(u.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=fi(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=fi(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ld(c)}),yield{type:"finish",reason:l??"stop"}}}}function py(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=pi(n,r,t.model,!1),s=W(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(W()-s)/1e6);return Df(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=pi(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=fi(s,a.message.usage);break;case"content_block_delta":{let d=a.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=a;d.delta.stop_reason&&(i=d.delta.stop_reason),d.delta.usage&&(s=fi(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Ld(s)}),yield{type:"finish",reason:i??"stop"}}}}At();function mi(){let t=new Error("aborted");return t.name="AbortError",t}function Gf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(mi()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(mi())},e.addEventListener("abort",s,{once:!0}))})}function Vn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let d=[...a].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),i=t.usage??((a,d)=>{let u=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(a,d){if(await Gf(r,d?.signal),d?.signal?.aborted)throw mi();let u=s(a,d),c=i(a,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(a,d){let u=s(a,d),c=i(a,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw mi();await Gf(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Re();Re();ce();At();function Ff(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=si({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function a(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return i.keyFor({messages:d,opts:u})}return{keyFor:a,async lookup(d,u){if(n!=="write"){if(r){let c=await a(d,u),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await a(d,u);await e.save(l,c);return}await i.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(d,u);await e.delete(c);return}await i.forget({messages:d,opts:u})}}}}Re();se();ne();ze();ce();function dt(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function gi(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=Q(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===L&&(u=!0,r(l[1]))}})}let i,a=!1,d=no(s,u=>{i=n(u),a=!0});return O([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function Kn(t){let e=t.endNs??W();return{timestamp:e,wallClock:t.startWallClockNs??ie(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Pt(){return{input:{regular:0},output:{regular:0}}}var $f=Symbol.for("graphrefly.adapter.middlewareLayers");function tt(t,e,n){let o=[...n?fy(n):[],e];return Object.defineProperty(t,$f,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function fy(t){let e=t[$f];return Array.isArray(e)?e:[]}var qn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function _o(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",d=Ff({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new Ie().start(p,()=>f())}),c=ai(async({messages:p,invokeOpts:f})=>await it(Q(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=dt(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new qn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:ie()}),g},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let k=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let R=0;R<h.streamChunks.length;R++){let S=h.streamCadenceMs[R]??0,x=s>0?S/s:0;x>0&&await u(x),yield{type:"token",delta:h.streamChunks[R]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new qn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(g+=k.delta,o)){let R=W(),S=w===void 0?0:(R-w)/1e6;T.push(S),w=R,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||y)&&!a){let R={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ie(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,R)}}});return tt(l,"withReplayCache",t),l}var Id=vo;var my=qn;function jf(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function Bf(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function gy(t,e){if("key"in t)return t.key;let n=Id({messages:t.messages,opts:t.invokeOpts??{}}),r=await oi(n);return`${e}:${r}`}function hy(t){let e={response:t.response,storedAtNs:ie()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function yy(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=So(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await gy(i,e);await r.save(a,hy(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Pd(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?Vn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):jf(e,n);return Bf(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):jf(e,n),f=Bf(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=yy(t,o);i=c.tier??So(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=_o(s,{storage:i,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await a,u.invoke(c,l)},async*stream(c,l){await a;for await(let p of u.stream(c,l))yield p}}}Re();function Dd(t={}){return t.sdk?wy(t):Ty(t)}function hi(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let d of i.toolCalls)a.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
35
-
36
- `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(by)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function by(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Vf(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Gd(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Kf(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Gd(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function vy(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Ty(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=vy(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),d=hi(s,i),u=W(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!l.ok)throw await Et(l,"Google");let p=await l.json(),f=Math.max(0,(W()-u)/1e6);return Kf(p,f)},async*stream(s,i){let a=r(i),d=hi(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await Et(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of qt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Gd(l)}),yield{type:"finish",reason:p??"stop"}}}}function wy(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=hi(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Vf(o,s,r?.signal),a=W(),d=await e.models.generateContent(i),u=Math.max(0,(W()-a)/1e6);return Kf(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=hi(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Vf(o,s,r?.signal),a,d,u=await e.models.generateContentStream(i);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:Gd(a)}),yield{type:"finish",reason:d??"stop"}}}}Re();var ky={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Fd(t={}){return t.sdk?Ey(t):Ny(t)}function yi(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(xy);e?.systemPrompt&&!t.some(d=>d.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Ry)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function xy(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function Ry(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function $d(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function qf(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Sy(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:$d(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Sy(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Hf(t){let e=t.preset??"openai",n=ky[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Ny(t){let{provider:e,baseURL:n,apiKey:r}=Hf(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,d){let u=yi(a,d,t.model,!1,t.bodyExtras),c=W(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await Et(l,e);let p=await l.json(),f=Math.max(0,(W()-c)/1e6);return qf(p,f,e)},async*stream(a,d){let u=yi(a,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await Et(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of qt(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:$d(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ey(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Hf(t);return{provider:n,model:t.model,async invoke(r,o){let s=yi(r,o,t.model,!1,t.bodyExtras),i=W(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(W()-i)/1e6);return qf(a,d,n)},async*stream(r,o){let s=yi(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,d;for await(let u of i){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(a=l,yield{type:"usage",usage:$d(l)})}yield{type:"finish",reason:d??"stop"}}}}function _y(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Cd(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Dd(e)}case"dry-run":{let e={model:t.model,...t.extras};return Vn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Pd(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Fd(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Re();ne();ce();function _t(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Ht(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function zf(){return{input:{regular:0},output:{regular:0}}}function My(t,e){let n=e?.logMax??1e3,r=We(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=A(null,{name:"adapterStats/lastCall"}),s=O([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=O([r.entries],([h])=>h.reduce((g,y)=>g+_t(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=O([r.entries],([h])=>h.reduce((g,y)=>g+Ht(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[te(s),te(i),te(a)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=dt(t,{invoke(h,g){let y=W(),b=ie(),v=t.model??g?.model??"",T=k=>(u(Kn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??Pt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let R=k;u(Kn({provider:t.provider,model:v,tier:g?.tier,usage:Pt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:R?.name??"Error",message:R?.message??String(k)}}))};return gi(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=W(),b=ie(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;u(Kn({provider:t.provider,model:v,tier:g?.tier,usage:T??Pt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw u(Kn({provider:t.provider,model:v,tier:g?.tier,usage:T??Pt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});tt(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function Oy(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function vi(t="USD"){return{total:0,currency:t}}function jd(t,e,n){let r=_t(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,d=(g,y,b)=>{if(!y||b==null)return;let v=Oy(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function bi(t,e){return`${t}::${e}`}function Ay(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(bi(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(bi(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let d;for(let u of a)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(bi(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(bi(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function Cy(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?jd(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):vi(e)}}function Ly(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):vi()}}function Iy(t,e,n){return t?.pricing?jd(e,t.pricing,n):vi()}on();ce();function Bd(t,e={}){let n=e.breaker??Rt(e),r=dt(t,{async invoke(o,s){if(!n.canExecute())throw new St;try{let i=await it(Q(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new St;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return tt(r,"withBreaker",t),{adapter:r,breaker:n}}Re();se();ne();ce();var Ti=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Vd=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Wf=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Kd(t,e){let n=We(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=A(Wf(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=O([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(te(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===_){let m=f[1];if(c&&l&&m===!1){let h=Uf(r.cache??Vd,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Vd,c=Uf(u,e.caps);return new Ti(c??"budget",e.caps[c??"calls"]??0,Py(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=Kn({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??Vd,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+_t(u),outputTokens:f.outputTokens+Ht(u),usd:m})},a=()=>{n.clear(),r.emit(Wf())},d=dt(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=W(),f=t.model??c?.model??"",m=g=>(i(g.usage??Pt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Pt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return gi(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=W(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Pt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Pt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return tt(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Uf(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function Py(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ce();function Dy(t,e){let n=e.mock??Vn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?Q(e.enabled):void 0,s;o&&(s=te(o));let i=()=>r!==void 0?r:!!o?.cache,a=dt(t,{invoke(u,c){return i()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return i()?n.stream(u,c):t.stream(u,c)}});return tt(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function qd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Gy(e.headers);if(n!==429&&n!==503&&!Ky(e.message))return;let o={},s=r("retry-after"),i=$y(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Jf(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=Jf(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=wi(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=wi(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=wi(r,"x-ratelimit-remaining-requests"),p=wi(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=By(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Fy(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Gy(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function Fy(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function wi(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function $y(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function Jf(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var jy=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function By(t){let e=jy.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Vy=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Ky(t){return!!t&&Vy.test(t)}Re();se();ne();on();ce();At();function Hd(t){let e=new Error(t);return e.name="AbortError",e}function Qf(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?Q(t.rpm):A(Number.POSITIVE_INFINITY),o=t.tpm!=null?Q(t.tpm):A(Number.POSITIVE_INFINITY),s=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=A({},{name:"adaptiveRateLimiter/lastSignal"}),d=O([r,s],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=O([o,i],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=wr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=wr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(M=>{for(let C of M)if(C[0]===_){let $=Number(C[1]);Number.isFinite($)&&$>0?(c=wr($,e),p=!1):$===1/0?(c=wr(1/0,e),p=!1):$<=0&&(p=!0)}}),h=u.subscribe(M=>{for(let C of M)if(C[0]===_){let $=Number(C[1]);Number.isFinite($)&&$>0?(l=wr($,e),f=!1):$===1/0?(l=wr(1/0,e),f=!1):$<=0&&(f=!0)}}),g=0,y=new Ie,b=new Ie,v;t.adaptation!=null&&(v=Q(t.adaptation).subscribe(C=>{for(let $ of C)$[0]===_&&T($[1])}));function T(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let C=W()+M.retryAfterMs*1e6;C>g&&(g=C)}}let w=A(0,{name:"adaptiveRateLimiter/pending"}),k=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),R=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=M=>{w.emit((w.cache??0)+M)},x=()=>{k.emit(c.available()),R.emit(l.available())};async function N(M={}){let C=M.requestCost??1,$=M.tokenCost??0,V=M.signal;S(1);try{for(;;){if(V?.aborted)throw Hd("AdaptiveRateLimiter.acquire aborted");let G=W();if(g>G){let B=Math.ceil((g-G)/1e6);await ki(B,V);continue}if(C>0&&p||$>0&&f){await ki(250,V);continue}let K=c,F=l;if(!K.tryConsume(C)){await ki(Yf(K,C),V);continue}if(!($>0?F.tryConsume($):!0)){K.putBack(C),await ki(Yf(F,$),V);continue}x();return}}finally{S(-1)}}function E(M){M>0?l.tryConsume(M):M<0&&l.putBack(-M),x()}function P(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:R,acquire:N,recordUsage:E,recordSignal:T,dispose:P}}function wr(t,e){if(!Number.isFinite(t)||t===1/0)return rn(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return rn(n,r)}function Yf(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function ki(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Hd("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Hd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ce();function zd(t,e={}){let n=e.limiter??Qf({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=qd(i);a&&n.recordSignal(a)},s=dt(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await it(Q(t.invoke(i,a))),c=u.usage??zf(),p=_t(c)+Ht(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=0;for await(let l of t.stream(i,a))l.type==="usage"&&(u=_t(l.usage)+Ht(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return tt(s,"withRateLimiter",t),{adapter:s,limiter:n}}on();ce();var Mo=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Wd(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Rt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await it(Q(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new Mo(u)},async*stream(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new Mo(u)}};return tt(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function qy(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ce();At();function xi(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Xf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(xi()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(xi())},e.addEventListener("abort",s,{once:!0}))})}function Ud(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Hy,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=dt(t,{async invoke(l,p){if(p?.signal?.aborted)throw xi();let f,m=r;for(let h=1;h<=n;h++)try{return await it(Q(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await Xf(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw xi();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=u(h,m);m=b,await Xf(b,p?.signal)}}throw f}});return tt(c,"withRetry",t),c}function Hy(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}ce();At();var kr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function Jd(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,d,u=new Ie;return s&&(s.aborted?i.abort(s.reason):(d=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new kr(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof kr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new kr(e);throw u.cause=s,u}throw s},o=dt(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await it(Q(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,u())}finally{d()}}});return tt(o,"withTimeout",t),o}function zy(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=zd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Kd(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Bd(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Jd(r,e.timeoutMs)),e.retry&&(r=Ud(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=Wd([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=_o(r,e.cache)),n.adapter=r,n}Ze();Me();ce();se();ne();ut();ce();At();function ve(t,e){return we("ai",t,e)}function Wy(t){return t!=null&&typeof t.then=="function"}function Yd(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Uy(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Jy=3e4;function Zf(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Jy;return new Promise((r,o)=>{let s=new Ie,i=t.subscribe(a=>{for(let d of a){if(d[0]===_){s.cancel(),i(),r(d[1]);return}if(d[0]===L){s.cancel(),i(),o(d[1]);return}if(d[0]===I){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function Oo(t){return Wy(t)?Oo(await t):Yd(t)?Zf(t):Uy(t)?Zf(Q(t)):t}function zt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Qd(t,e,n){return H(r=>{let o=new AbortController,s=!1,i=null,a=c=>{s||(s=!0,r.down([[_,c],[I]]),i?.(),i=null)},d;try{d=t.invoke(e,{...n.invokeOpts,signal:o.signal})}catch(c){return a(n.onFailure("throw",c)),()=>o.abort()}return i=Q(d,{signal:o.signal}).subscribe(c=>{for(let l of c){if(s)return;if(l[0]===_){try{a(n.onSuccess(l[1]))}catch(p){a(n.onFailure("onSuccess-threw",p))}return}if(l[0]===L){a(n.onFailure("error",l[1]));return}if(l[0]===I){a(n.onFailure("complete",void 0));return}}}),s&&i&&(i(),i=null),()=>{o.abort(),i?.(),i=null}})}function Yy(t,e){let n=Q(t),r=e?.refreshTrigger!=null?Q(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=Te("frozenContext",o);return r==null?J([n],(i,a,d)=>{if(d.store.emitted===!0)return;let c=i[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,a.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ve("frozen_context",{...s})}):J([n,r],(i,a,d)=>{let u=i[1];if(!(u!=null&&u.length>0))return;let l=i[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];a.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ve("frozen_context",{...s})})}ne();se();ne();ze();ce();function em(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Qy(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ao(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node";r?.tools!==void 0&&o!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=e.length,a=r?.tools!==void 0?[...e,r.tools]:e,d=O(a,c=>{let l=c.slice(0,i),p=r?.tools!==void 0?c[i]:void 0;if(l.some(m=>m==null))return{messages:[],tools:p};let f=typeof n=="string"?n:n(...l);return f?{messages:[{role:"user",content:f}],tools:p}:{messages:[],tools:p}},{name:`${s}::messages`,meta:ve("prompt_node")});return ke(d,c=>{let{messages:l,tools:p}=c;return!l||l.length===0?A(null):H(f=>{let m=!1,h=!1,g,y={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...p!==void 0?{tools:p}:{}};if(r?.abort){let w=Gs(r.abort);y.signal=w.signal,g=w.dispose}let b;try{b=t.invoke(l,y)}catch(w){return m=!0,f.down([[L,w]]),()=>{g?.()}}let T=Q(b).subscribe(w=>{if(!(h||m))for(let k of w){if(m)return;if(k[0]===_){let R=k[1];if(o==="raw")f.emit(R);else try{let S=em(R),x=o==="json"?JSON.parse(zt(S)):S;f.emit(x)}catch(S){let x=em(R),N=new Error(`promptNode: failed to parse LLM response as JSON: ${S.message}
37
- Raw content (first 200 chars): ${Qy(x)}`);m=!0,f.down([[L,N]]);return}}else if(k[0]===L){m=!0,f.down([[L,k[1]]]);return}else if(k[0]===I){m=!0,f.down([[I]]);return}else f.down([k])}});return()=>{h=!0,T(),g?.()}},{name:`${s}::call`,meta:ve("prompt_node::call")})},{name:`${s}::output`,meta:r?.meta?{...ve("prompt_node::output"),...r.meta}:ve("prompt_node::output")})}function Xd(t,e,n,r){let o=n.name??r;return s=>{let i=A(s);return Ao(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Zd(t,e){let n=e.maxExistingKeys??100,r=Xd(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function eu(t,e){let n=Xd(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Oe();Re();Ze();ne();ze();ce();var Mi={};Ee(Mi,{MessagingHubGraph:()=>Ni,SubscriptionGraph:()=>Co,TopicBridgeGraph:()=>Ri,TopicGraph:()=>Wt,TopicRegistry:()=>Si,messagingHub:()=>Lo,subscription:()=>tm,topic:()=>Ei,topicBridge:()=>_i});Me();ut();ce();Tt();var Xy=256;function xr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ln(t,e){return we("messaging",t,e)}var Zy=1024,Wt=class extends Y{_log;_publishImpl;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"events",maxSize:n.retainedLimit??Zy}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=O([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ln("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.hasLatest=O([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ln("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[I]])}),this.addDisposer(()=>this._log.disposeAllViews()),this._publishImpl=Ce(r=>{this._log.append(r)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Co=class extends Y{cursor;available;topic;_disposed=!1;_ackImpl;_pullAndAckImpl;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=xr(r.from,"subscription from"):o=xr(r.cursor??0,"subscription cursor"),this.cursor=A(o,{name:"cursor",describeKind:"state",meta:ln("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(te(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=J([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:ln("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(te(a))}this._ackImpl=Ce(s=>{let i=this.available.cache,a=s===void 0?i.length:xr(s,"subscription ack count"),d=Math.min(a,i.length);if(d<=0)return this.cursor.cache;let u=this.cursor.cache+d;return this.cursor.emit(u),u},{freeze:!1}),this._pullAndAckImpl=Ce(s=>{let i=this.available.cache,a=s===void 0?i.length:xr(s,"subscription pullAndAck limit"),d=i.slice(0,a);if(d.length===0)return{items:d,cursor:this.cursor.cache};let u=this.cursor.cache+d.length;return this.cursor.emit(u),{items:d,cursor:u}},{freeze:!1})}ack(e){return this._disposed?this.cursor.cache:this._ackImpl(e)}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:xr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){return this._disposed?{items:[],cursor:this.cursor.cache}:this._pullAndAckImpl(e)}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[I]]),this.destroy())}},Ri=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=tm(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,xr(o.maxPerPump??Xy,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=O([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:ln("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(te(this.output)),this.bridgedCount=A(0,{name:"bridgedCount",describeKind:"state",meta:ln("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=J([a],()=>{let p=a.cache;if(p.length===0)return;let f=d.available.cache.length,m=Math.min(f,s);if(m>0){d.ack(m);let h=u.cache??0;u.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:ln("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(te(c));let l=eb(this.output,r);this.addDisposer(l)}};function eb(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==_)continue;let o=r[1];o.length!==0&&Z(()=>{for(let s of o)e.publish(s)})}})}var Si=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},Ni=class extends Y{_registry;version;_defaultTopicOptions;_removeTopicImpl;constructor(e,n={}){super(e,n.graph);let r=A(0,{name:"version",describeKind:"state",meta:ln("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new Si(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}},this._removeTopicImpl=Ce(o=>{try{this.remove(o)}finally{this._registry.delete(o);let s=this.version.cache??0;this.version.emit(s+1)}},{freeze:!1})}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new Wt(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Z(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new Co(e,o,r)}removeTopic(e){return this._registry.has(e)?(this._removeTopicImpl(e),!0):!1}};function Ei(t,e){return new Wt(t,e)}function Lo(t,e){return new Ni(t,e)}function tm(t,e,n){return new Co(t,e,n)}function _i(t,e,n,r){return new Ri(t,e,n,r)}var Oi={};Ee(Oi,{PipelineGraph:()=>Po,decisionKeyOf:()=>nm,pipelineGraph:()=>Rr});Oe();Re();se();Ze();Me();ne();ut();Fe();function Io(t,e){return we("orchestration",t,e)}var nm=t=>t.action,Po=class extends Y{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=O(o,n,{name:e,describeKind:"derived",meta:Io("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=O([s],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:Io("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=O(s,a=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=a[u];return d},{name:e,describeKind:"derived",meta:Io("combine",r.meta)});return this.add(i,{name:e}),i}approvalGate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Y(`${e}_state`),d=A([],{name:"pending",equals:()=>!1}),u=A(s,{name:"isOpen"}),c=O([d],([F])=>F.length,{name:"count"}),l=A(0,{name:"droppedCount"}),p=at({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=u.subscribe(F=>{for(let q of F)q[0]===_&&(g=q[1])});this.addDisposer(y);function b(){d.emit([...f])}function v(F,q,D){p.append({action:F,t_ns:ie(),...q!==void 0?{items:q,count:q.length}:{},...D!==void 0?{unflushed:D}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let q=f.shift();l.emit(l.cache+1),v("drop",[q])}b()}function w(F){let q=f.splice(0,F);return b(),q}let k=J([i],(F,q,D)=>{let B=D.terminalDeps[0];if(B!==void 0){m=!0;let ye=f.length;f=[],b(),v("teardown",void 0,ye),q.down(B===!0?[[I]]:[[L,B]]);return}let re=F[0];if(re==null||re.length===0){q.down([[z]]);return}for(let ye of re)g?q.emit(ye):(T(ye),q.down([[z]]))},{name:e,describeKind:"derived",meta:Io("approval_gate",r.meta)});if(this.add(k,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let q=r.approver.subscribe(D=>{for(let B of D){if(B[0]!==_)continue;let re=!!B[1];if(re&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let ye=w(f.length);v("open",ye);for(let ee of ye){if(m)break;k.emit(ee)}})}else if(!re&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(q)}let R=F=>{if(m)throw new Error(`approvalGate: ${F}() called after the gate was torn down`)},S=(F=1)=>{R("approve");let q=w(F);for(let D of q){if(m)break;k.emit(D)}},x=(F=1)=>{R("reject"),w(F)},N=(F,q=1)=>{R("modify");let D=[...f],B=w(q);for(let re=0;re<B.length&&!m;re++)k.emit(F(B[re],re,D))},E=()=>{R("open"),u.emit(!0);let F=w(f.length);for(let q of F){if(m)break;k.emit(q)}},P=()=>{R("close"),!(r.onceOnly&&h)&&u.emit(!1)},M=Lt(S,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"approve",count:F[0]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),C=Lt(x,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"reject",count:F[0]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=Lt(N,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"modify",count:F[1]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),V=Lt(E,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"open",t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),G=Lt(P,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"close",t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:k,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:M,reject:C,modify:$,open:V,close:G}}approval(e,n,r,o={}){return this.approvalGate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"errored",a=J([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"completed"}:{kind:"errored",error:l};if(i==="terminal"||i===f.kind){u.emit(r(f,u));return}u.down(f.kind==="completed"?[[I]]:[[L,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[z]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:Io("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function Rr(t,e){let n=new Po(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",He(s)),n}async function rm(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:ie()}),i.type==="token"&&(o+=i.delta);return o}function om(t,e){if(e==="json")try{return JSON.parse(zt(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function sm(t,e){return O([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:ve("accumulated_text"),initial:""})}function tb(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Ei(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=O(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:ve("prompt_node::messages"),initial:[]}),d=ke(a,l=>{let p=l;if(!p||p.length===0)return A(null);let f=new AbortController;async function*m(){try{let h=await rm(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield om(h,s)}finally{f.abort()}}return Q(m())},{meta:Te("streamingPromptNode")}),u=sm(i,`${o}::accumulatedText`),c=te(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function nb(t,e,n,r,o,s){let i=A(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,c=s?.format??"text",l=Ei(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=O(d,R=>{let S=R.slice(0,-1);if(S.some(N=>N==null))return[];let x=typeof o=="string"?o:o(...S);return x?[{role:"user",content:x}]:[]},{name:`${u}::messages`,meta:ve("prompt_node::messages"),initial:[]}),f=ke(p,R=>{let S=R;if(!S||S.length===0)return A(null);let x=new AbortController;async function*N(){try{let E=await rm(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:x.signal},l);yield om(E,c)}finally{x.abort()}}return Q(N())},{meta:Te("gatedStream")}),m=sm(l,`${u}::accumulatedText`),h=kt(f,R=>R!=null);t.add(h,{name:`${e}/raw`});let g=Rr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.approvalGate(`${e}/gate`,`${e}/raw`,s?.gate),b=te(f),v=te(y.node),T=te(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),k={...y,reject(R=1){Z(()=>{w(R),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:k,dispose:()=>{b(),v(),T(),l.destroy()}}}ne();ce();function rb(t,e){let n=e?.separator??`
38
-
39
- `,r=t.map(i=>typeof i=="string"?A(i):Q(i)),o=O(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ve("system_prompt"),initial:""}),s=te(o);return Object.assign(o,{dispose:s})}ne();var ob=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function sb(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return O([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=_t(i.usage)+Ht(i.usage));let d=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:d,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:ve("cost_meter_extractor"),equals:ob})}ne();var ib=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function ab(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return O([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=i.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ve("keyword_flag_extractor"),equals:ib})}ne();function db(t,e,n){return O([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ve("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var ub=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function cb(t,e){return O([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let d=o.indexOf("{",i);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ve("tool_call_extractor"),equals:ub})}ne();function lb(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),O(i,a=>{let d=a[0]??"";if(d.length===0)return"allow";let u=s?a[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function pb(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);a=a.replace(u,c=>o(c,d))}return a}return O([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}ne();ce();Fe();var Ai=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=O([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ve("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.messageCount=O([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ve("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(te(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function tu(t,e){return new Ai(t,e)}Ze();ne();ze();ce();function fb(t,e,n){let r=Q(t),o=n?.condition!=null?Q(n.condition):null,s=A(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ke(r,a=>{if(a==null)return s;let d=A(a);return e(d)},{meta:Te("handoff")});let i=O([r,o],([a,d])=>({v:a,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ke(i,({v:a,open:d})=>{if(a==null)return s;if(!d)return A(a);let u=A(a);return e(u)},{meta:Te("handoff")})}ne();ze();on();function nu(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let d=0;d<i.length;d++){let u=i[d],c=a[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return ke(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(d=>mb(d,n,r,o));return O(a,d=>d,{name:"toolExecution::batch",equals:s})})}function mb(t,e,n,r){let o=xt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=O([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:ro(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}se();ne();ce();Fe();var Ci=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Xe({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=O([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ve("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(te(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return H(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=gb(d,s.signal)}catch(d){return o.down([[L,d]]),()=>{s.abort()}}let a=i.subscribe(d=>{o.down(d)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:ve("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ru(t,e){return new Ci(t,e)}function gb(t,e){return Yd(t)?t:t!=null&&typeof t.then=="function"?fr(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?io(t,{signal:e}):fr(Promise.resolve(t),{signal:e})}Ze();ne();ce();function hb(t,e,n){let r=Q(t),o=e.map(i=>Q(i)),s=[r,...o];return O(s,i=>{let a=i[0]??[],d=i.slice(1);return a.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...ve("tool_selector"),...Te("toolSelector")},equals:(i,a)=>{let d=i,u=a;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function im(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function yb(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=im({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Oe();Re();ne();ce();var Pi={};Ee(Pi,{collection:()=>ou,cosineSimilarity:()=>Ii,knowledgeGraph:()=>iu,vectorIndex:()=>su});Re();Me();ne();ut();ce();Fe();var bb=1e9;function yt(t,e){return we("memory",t,e)}function Do(t,e){return t instanceof Ae?t:A(t,e?{name:e}:void 0)}function am(t,e){return(t-e)/bb}function Ii(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let a=0;a<n;a+=1){let d=t[a]??0,u=e[a]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let i=r/Math.sqrt(o*s);return Number.isFinite(i)?i:0}function vb(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function Tb(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function ou(t,e={}){let n=e.maxSize,r=e.ranked??!0,o=r?e.decayRate??0:0,s=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let i=()=>r?1:0,a=e.score??i,d=r&&a instanceof Ae?a:void 0,u=()=>d?d.cache??i:a,c=new Y(t),p=Xe({name:"items",...n!==void 0?{retention:{score:(M,C)=>r?It(C.baseScore,am(W(),C.lastAccessNs),o,s):C.lastAccessNs,maxSize:n}}:{}});c.add(p.entries,{name:"items"});let f;if(r&&o>0){let M=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*o)),C=st(M,{period:M});f=O([C],()=>W(),{name:"refresh_tick_ns",describeKind:"derived",initial:W(),meta:yt("clock")}),c.add(f,{name:"refresh_tick_ns"})}let m;if(r){let M=[p.entries];f&&M.push(f),d&&M.push(d),m=O(M,C=>{let $=C[0],V;if(f){let K=C[1];V=typeof K=="number"?K:W()}else V=W();if(!$||$.size===0)return[];let G=[];for(let K of $.values())G.push({...K,score:It(K.baseScore,am(V,K.lastAccessNs),o,s)});return G.sort((K,F)=>F.score-K.score||F.lastAccessNs-K.lastAccessNs),G},{name:"ranked",describeKind:"derived",equals:Tb,meta:yt("ranked")}),c.add(m,{name:"ranked"})}else m=A([],{name:"ranked",describeKind:"state",meta:yt("ranked_disabled")}),c.add(m,{name:"ranked"});let h=O([p.entries],([M])=>(M??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:yt("size")});c.add(h,{name:"size"}),c.addDisposer(te(h));let g=at({name:"events",retainedLimit:1024,graph:c}),y=ht(c,"seq",0),b=(M,C,$)=>{let V=W(),G=p.get(M),K=$?.score??u()(C);p.set(M,{id:M,value:C,baseScore:K,createdAtNs:G?.createdAtNs??V,lastAccessNs:V})},v=M=>{p.has(M)&&p.delete(M)},T=()=>{p.size!==0&&p.clear()},w=()=>{if(!r)return;let M=u(),C=p.entries.cache;if(!C||C.size===0)return;let $=[];for(let V of C.values())$.push([V.id,{...V,baseScore:M(V.value)}]);p.setMany($)},k=Ce(b,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"upsert",id:M,t_ns:$.t_ns,seq:$.seq})}),R=Ce(v,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"remove",id:M,t_ns:$.t_ns,seq:$.seq})}),S=Ce(T,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"clear",t_ns:$.t_ns,seq:$.seq})}),x=Ce(w,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"rescore",t_ns:$.t_ns,seq:$.seq})});function N(M){let C=Do(M,"id");return O([p.entries,C],([$,V])=>$?.get(V),{describeKind:"derived",meta:yt("collection_item")})}function E(M){let C=Do(M,"id");return O([p.entries,C],([$,V])=>$?.has(V)??!1,{describeKind:"derived",meta:yt("collection_has")})}return Object.assign(c,{events:g,items:p.entries,ranked:m,size:h,upsert:k,remove:R,clear:S,rescore:x,itemNode:N,hasNode:E})}function su(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,i;if(e==="hnsw"&&(i=t.hnswFactory?.(),!i))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let a=new Y(t.name??"vector_index"),d;function u(x){if(n!==void 0){if(x.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${x.length}`);return}if(r){if(d===void 0){d=x.length;return}if(x.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${x.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(x=>x.upsertedAtNs),l=!1,p=at({name:"events",retainedLimit:1024,graph:a}),f=ht(a,"seq",0),m=Xe({name:"entries",...o!==void 0?{retention:{score:(x,N)=>c(N),maxSize:o,onArchive:x=>{l||(e==="hnsw"&&i.remove(x),p.append({action:"evict",id:x,t_ns:ie(),seq:Bt(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(te(m.entries)),i?.dispose){let x=i.dispose.bind(i);a.addDisposer(()=>x())}let h=(x,N,E)=>{u(N),e==="hnsw"&&i.upsert(x,N,E);let P=(()=>{if(E!==void 0)return E===null||typeof E!="object"?E:Array.isArray(E)?[...E]:{...E}})(),M={id:x,vector:[...N],...P!==void 0?{meta:P}:{},upsertedAtNs:W()};m.set(x,M)},g=x=>{m.has(x)&&(e==="hnsw"&&i.remove(x),m.delete(x))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&i.clear()}finally{l=!1}d=void 0}},b=()=>{if(e!=="hnsw")return;let x=m.entries.cache;if(x){i.clear();for(let N of x.values())i.upsert(N.id,N.vector,N.meta)}},v=Ce(h,{audit:p,freeze:!1,seq:f,onSuccess:([x],N,E)=>({action:"upsert",id:x,t_ns:E.t_ns,seq:E.seq})}),T=Ce(g,{audit:p,seq:f,onSuccess:([x],N,E)=>({action:"remove",id:x,t_ns:E.t_ns,seq:E.seq})}),w=Ce(y,{audit:p,seq:f,onSuccess:(x,N,E)=>({action:"clear",t_ns:E.t_ns,seq:E.seq})}),k=Ce(b,{audit:p,seq:f,onSuccess:(x,N,E)=>({action:"reindex",t_ns:E.t_ns,seq:E.seq})});function R(x,N=5){let E=Do(N,"k");return O([m.entries,x,E],P=>{let M=P[0],C=P[1],$=P[2],V=Number.isFinite($)?Math.max(0,Math.floor($)):0;if(!M||M.size===0||V<=0)return[];if(C==null||C.length===0)return[];let G=n??(r?d:void 0);return G!==void 0&&C.length!==G?[]:e==="hnsw"?[...i.search(C,V)]:[...M.values()].map(F=>({id:F.id,score:Ii(C,F.vector),...F.meta!==void 0?{meta:F.meta}:{}})).sort((F,q)=>q.score-F.score).slice(0,V)},{describeKind:"derived",equals:(P,M)=>vb(P,M),meta:yt("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:k,searchNode:R})}var dm="\0";function Li(t,e,n){return`${t}${dm}${e}${dm}${n}`}function um(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,i=n.get(s);i||(i=[],n.set(s,i)),i.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function cm(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let i=r[s],a=o[s];if(i.from!==a.from||i.to!==a.to||i.relation!==a.relation||i.weight!==a.weight)return!1}}return!0}function iu(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new Y(t),o=Xe({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Xe({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let i=O([s.entries],([S])=>um(S,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:cm,meta:yt("adjacency_out")}),a=O([s.entries],([S])=>um(S,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:cm,meta:yt("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(te(i)),r.addDisposer(te(a));let d=O([o.entries],([S])=>(S??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:yt("entity_count")}),u=O([s.entries],([S])=>(S??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:yt("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(te(d)),r.addDisposer(te(u));let c=at({name:"events",retainedLimit:1024,graph:r}),l=ht(r,"seq",0);function p(S){let x=i.cache,N=a.cache;return(x?.get(S)?.length??0)>0||(N?.get(S)?.length??0)>0}function f(S){if(n==="remove")for(let x of S)o.has(x)&&(p(x)||(o.delete(x),c.append({action:"orphanRemove",id:x,t_ns:ie(),seq:Bt(l)})))}let m=(S,x)=>{o.set(S,x)},h=S=>{let x=s.entries.cache,N=new Set;if(x){let E=[];for(let[P,M]of x)(M.from===S||M.to===S)&&(E.push(P),M.from!==S&&N.add(M.from),M.to!==S&&N.add(M.to));E.length>0&&s.deleteMany(E)}o.has(S)&&o.delete(S),f([...N])},g=(S,x,N,E=1)=>{s.set(Li(S,x,N),{from:S,to:x,relation:N,weight:E})},y=(S,x,N)=>{if(N!==void 0)s.delete(Li(S,x,N));else{let E=s.entries.cache;if(!E)return;let P=[];for(let[M,C]of E)C.from===S&&C.to===x&&P.push(M);P.length>0&&s.deleteMany(P)}f([S,x])},b=Ce(m,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"upsertEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),v=Ce(h,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"removeEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),T=Ce(g,{audit:c,seq:l,onSuccess:([S,x,N,E],P,M)=>({action:"link",from:S,to:x,relation:N,weight:E??1,t_ns:M.t_ns,seq:M.seq})}),w=Ce(y,{audit:c,seq:l,onSuccess:([S,x,N],E,P)=>({action:"unlink",from:S,to:x,...N!==void 0?{relation:N}:{},t_ns:P.t_ns,seq:P.seq})});function k(S,x){let N=Do(S,"id"),E=x!==void 0?Do(x,"relation"):void 0;return O(E?[i,a,N,E]:[i,a,N],M=>{let C=M[0],$=M[1],V=M[2],G=E?M[3]:void 0,K=C.get(V)??[],F=$.get(V)??[],q=new Set,D=[];for(let B of K){let re=Li(B.from,B.to,B.relation);q.has(re)||G!==void 0&&B.relation!==G||(q.add(re),D.push(B))}for(let B of F){let re=Li(B.from,B.to,B.relation);q.has(re)||G!==void 0&&B.relation!==G||(q.add(re),D.push(B))}return D},{describeKind:"derived",equals:(M,C)=>{let $=M,V=C;if($===V)return!0;if($==null||V==null||$.length!==V.length)return!1;for(let G=0;G<$.length;G+=1){let K=$[G],F=V[G];if(K.from!==F.from||K.to!==F.to||K.relation!==F.relation||K.weight!==F.weight)return!1}return!0},meta:yt("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:i,adjacencyIn:a,entityCount:d,edgeCount:u,upsertEntity:b,removeEntity:v,link:T,unlink:w,relatedNode:k})}function au(t,e,n){let r=su({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=he([e.store.entries],([i])=>{let a=i??new Map;for(let[d,u]of a){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function du(t,e,n,r){let o=r.mountPath??n,s=iu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=he([e.store.entries],([u])=>{let c=u??new Map;for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function uu(t,e,n){let r=n.decayRate??li,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=ou("permanent",{ranked:!1});t.mount("permanent",a);let d=new Set,u=b=>d.has(b)?"permanent":(e.store.entries.cache??new Map).has(b)?"active":"archived",c=(b,v)=>{d.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?Q(n.context):A(null),h=he([p,f],([b,v])=>{let T=b??new Map,w=W(),k=[],R=[];for(let[x,N]of T){if(l.has(x)||l.set(x,w),i(x,N)){R.push({key:x,value:N});continue}let E=n.score(N,v),P=l.get(x)??w,M=Number(w-P)/1e9;It(E,M,r)<s&&k.push(x)}for(let x of l.keys())T.has(x)||l.delete(x);for(let{key:x,value:N}of R)d.has(x)||c(x,N);let S=T.size-d.size;if(S>o){let x=[...T.entries()].filter(([E])=>!d.has(E)).map(([E,P])=>({key:E,score:n.score(P,v)})).sort((E,P)=>E.score-P.score),N=S-o;for(let E=0;E<N&&E<x.length;E++){let P=x[E].key;k.includes(P)||k.push(P)}}k.length>0&&Z(()=>{for(let x of k)e.store.delete(x)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:c},dispose:y}}function wb(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function cu(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,d=o.contextWeight??0,u=o.context?Q(o.context):A(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){let N=b.vector,E=n.entries.cache;if(E&&E.size>0&&s>0){T=[...E.values()].map(M=>({id:M.id,score:Ii(N,M.vector),...M.meta!==void 0?{meta:M.meta}:{}})).sort((M,C)=>C.score-M.score).slice(0,s);for(let M of T){let C=g.get(M.id);C&&v.set(M.id,{value:C,sources:new Set(["vector"])})}}}let w=[];if(r){let N=r.adjacencyOut.cache,E=r.adjacencyIn.cache,P=[...b.entityIds??[],...v.keys()],M=new Set,C=P;for(let $=0;$<i;$++){let V=[];for(let G of C){if(M.has(G))continue;M.add(G);let K=N?.get(G)??[],F=E?.get(G)??[];for(let q of K){let D=q.to;if(!M.has(D)){V.push(D);let B=g.get(D);if(B){let re=v.get(D);re?re.sources.add("graph"):v.set(D,{value:B,sources:new Set(["graph"])}),w.push(D)}}}for(let q of F){let D=q.from;if(!M.has(D)){V.push(D);let B=g.get(D);if(B){let re=v.get(D);re?re.sources.add("graph"):v.set(D,{value:B,sources:new Set(["graph"])}),w.push(D)}}}}C=V}}for(let[N,E]of g)v.has(N)||v.set(N,{value:E,sources:new Set(["store"])});let k=b.context?.length??0,R=[];for(let[N,{value:E,sources:P}]of v){let M=o.contextOf?o.contextOf(E):void 0,C=o.score(E,y);if(d>0&&k>0){let V=wb(b.context,M);V>0&&(C=C*(1+d*V/k))}let $=M?{key:N,value:E,score:C,sources:[...P],context:M}:{key:N,value:E,score:C,sources:[...P]};R.push($)}R.sort((N,E)=>E.score-N.score);let S=[],x=0;for(let N of R){let E=o.cost(N.value);if(x+E>a&&S.length>0)break;S.push(N),x+=E}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:R,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=A([],{name:"retrieval",describeKind:"state",meta:ve("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=A(null,{name:"retrievalTrace",describeKind:"state",meta:ve("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=e.store.entries.cache??new Map,{packed:b,trace:v}=c(y,u.cache,g);return Z(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=Q(g),b=O([e.store.entries,u,y],([w,k,R])=>{if(R==null)return{packed:[],trace:null};let S=w??new Map,{packed:x,trace:N}=c(S,k,R);return{packed:x,trace:N}},{name:"retrievalReactive::result",describeKind:"derived",meta:ve("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=he([b],([w])=>{let k=w;Z(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),O([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:ve("retrieval_reactive"),initial:[],equals:l})}}}Oe();se();Ze();Me();ne();ze();ce();Fe();var Di=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=tu(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=ru(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let D of n.tools)this.tools.register(D);this.status=A("idle",{name:"status",describeKind:"state",meta:ve("agent_status")}),this.add(this.status,{name:"status"}),this.turn=A(0,{name:"turn",describeKind:"state",meta:ve("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=A(!1,{name:"aborted",describeKind:"state",meta:ve("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(D=>{for(let B of D)B[0]===_&&(r=B[1])}),s=!1,i=this.aborted.subscribe(D=>{for(let B of D)B[0]===_&&(s=B[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(D=>{for(let B of D)B[0]===_&&(a=B[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(D=>{for(let B of D)B[0]===_&&(u=B[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,k=this.aborted,R=J([T],(D,B,re)=>{if(Go(D,re.prevData,0,"idle")!=="thinking"||s||r>=g){B.down([[z]]);return}if(a.length===0){B.down([[z]]);return}B.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:ve("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=ke(R,D=>{let B=new AbortController;return this._currentAbortController=B,s&&B.abort(new Error("agentLoop: aborted")),Q(l.invoke(D.messages,{tools:D.tools.length>0?D.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:B.signal}),{signal:B.signal})},{equals:()=>!1}),x=A(null,{name:"lastResponse",describeKind:"state",meta:ve("agent_last_response")});this.lastResponse=x;let N=J([x,T],(D,B,re)=>{let ye=Go(D,re.prevData,0,null);if(Go(D,re.prevData,1,"idle")!=="acting"){B.down([[z]]);return}let me=ye?.toolCalls;if(me==null||me.length===0){B.down([[z]]);return}B.emit(me)},{name:"toolCallsRaw",describeKind:"derived",meta:ve("agent_tool_calls_raw")}),E=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=E;let P=nu({toolCalls:E,tools:v,retryCount:1});this.toolResults=P;let M=he([S],([D])=>{if(s)return;let B=D,re=r+1,ye=B.toolCalls!=null&&B.toolCalls.length>0,ee=B.finishReason==="end_turn"&&(!B.toolCalls||B.toolCalls.length===0),me=y?.(B)===!0,Le=re>=g,rt=me||ee||!ye||Le?"done":"acting";Z(()=>{x.emit(B),T.emit(rt),w.emit(re),b.append("assistant",B.content,{toolCalls:B.toolCalls})})}),C=he([P],([D])=>{if(s)return;let B=D;if(B.length===0)return;let re=r>=g?"done":"thinking";Z(()=>{T.emit(re);for(let ye of B)b.appendToolResult(ye.id,ye.content)})}),$=T.cache??"idle",V=T.subscribe(D=>{for(let B of D)B[0]===_&&($=B[1])}),G=he([k],([D])=>{D===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),$!=="done"&&T.emit("done"))}),K=te(M),F=te(C),q=te(G);this._terminalResult=J([T,x],(D,B,re)=>{let ye=Go(D,re.prevData,0,"idle"),ee=Go(D,re.prevData,1,null);if(ye==="done"){if(ee!=null){B.emit(ee);return}let me=new Error("agentLoop: aborted");me.name="AbortError",B.down([[L,me]]);return}if(ye==="error"){B.down([[L,new Error("agentLoop: errored")]]);return}B.down([[z]])},{name:"terminalResult",describeKind:"derived",meta:ve("agent_terminal_result")}),this.add(R,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===N?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(N,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(P,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(V),this.addDisposer(d),this.addDisposer(c),this.addDisposer(K),this.addDisposer(F),this.addDisposer(q),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=Ds(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Go(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function kb(t,e){let n=new Di(t,e);return n.tagFactory("agentLoop",He(e)),n}se();Ze();ne();ze();ce();Fe();function xb(t,e,n){let r=new Y(t,n.graph);r.tagFactory("agentMemory",He(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Zd(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>{let T=v.cache??new Map,w=v.subscribe(k=>{for(let R of k)R[0]===_&&(T=R[1])});return r.addDisposer(w),ke(b,k=>k==null?{upsert:[]}:o(k,T))},i=e;if(n.admissionFilter){let b=Q(e),v=n.admissionFilter;i=O([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=eu(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=st(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c=ri(i,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=au(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=du(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=uu(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=cu(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Rb(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
40
- `,i=[],a=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&u.v!=null){let y=a.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:d,description:f,formatted:g})}if(i.length===0)return"";if(o){let d=new Map,u=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}se();ne();ze();ce();var ji={};Ee(ji,{compileSpec:()=>Bo,decompileSpec:()=>Ab,extractFnFactory:()=>fm,extractSourceFactory:()=>mm,generateCatalogPrompt:()=>gm,isRichFnEntry:()=>$o,isRichSourceEntry:()=>$i,llmCompose:()=>Lb,llmRefine:()=>bm,specDiff:()=>Cb,validateSpec:()=>Sr,validateSpecAgainstCatalog:()=>jo});ne();Fe();var Gi={};Ee(Gi,{feedback:()=>pn,funnel:()=>Sb,scorer:()=>Fo});Oe();se();Me();ne();ze();Fe();ut();ce();function lu(t,e){return we("reduction",t,e)}function Sb(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new Y(t,r),s=e.length===1?e[0]:Ct(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let d=n[a],u=new Y(d.name);d.build(u);try{u.resolve("input")}catch{throw new Error(`funnel stage "${d.name}" must define an "input" node`)}try{u.resolve("output")}catch{throw new Error(`funnel stage "${d.name}" must define an "output" node`)}o.mount(d.name,u);let c=o.resolve(i),l=`${d.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${d.name}_input`,m=he([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(te(m)),i=`${d.name}::output`}return o}function pn(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=A(0,{meta:lu("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,c=J([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===_){let y=h[1];if(y==null)return;Z(()=>{Gn(i,o)&&d.emit(y)})}else if(g===I||g===L){let y=g===L&&h.length>1?[L,h[1]]:[g];i.down([y])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...lu("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(te(c)),t}function Fo(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return O(r,i=>{let a=i.slice(0,o),d=i.slice(o),u=[],c=0;for(let l=0;l<o;l++){let p=a[l]??0,f=d[l]??0,h=(s?.[l]?s[l](p):p)*f;u.push(h),c+=h}return{value:a,score:c,breakdown:u}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:lu("scorer",n?.meta)})}function fn(t){let e=t.meta?.factory;return typeof e=="string"?e:void 0}function mn(t){let e=t.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function lm(t){let e=mn(t);return"initial"in e?e.initial:t.value}function $o(t){return typeof t=="object"&&t!==null&&"factory"in t}function $i(t){return typeof t=="object"&&t!==null&&"factory"in t}function fm(t){return $o(t)?t.factory:t}function mm(t){return $i(t)?t.factory:t}function gm(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=$o(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Nb(r,o))}for(let[r,o]of n)e.push(`${r}:
41
- ${o.join(`
42
- `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Eb(r,o));n.length>0&&e.push(`Sources:
43
- ${n.join(`
44
- `)}`)}return e.join(`
45
-
46
- `)}function Nb(t,e){if(!$o(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Eb(t,e){if(!$i(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function jo(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i,d=fn(a);if(d==null)continue;let u=a.type==="producer";if(a.type==="state"&&d==="state")continue;if(u){let l=o.has(d),p=r.has(d);if(!l&&!p&&(o.size>0||r.size>0)){let f=Fi(d,o)??Fi(d,r);n.push(`Node "${s}": source "${d}" not found in catalog`+(f?`. Did you mean "${f}"?`:""))}}else if(r.size>0&&!r.has(d))if(o.has(d))n.push(`Node "${s}": fn "${d}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let l=Fi(d,r);n.push(`Node "${s}": fn "${d}" not found in catalog`+(l?`. Did you mean "${l}"?`:""))}let c=mn(a);if(!u&&e.fns?.[d]){let l=e.fns[d];if($o(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}if(u&&e.sources?.[d]){let l=e.sources[d];if($i(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}}if(t.templates)for(let[s,i]of Object.entries(t.templates))for(let[a,d]of Object.entries(i.nodes)){let u=fn(d);if(u!=null&&!(d.type==="state"&&u==="state")&&d.type!=="producer"&&r.size>0&&!r.has(u)){let c=Fi(u,r);n.push(`Template "${s}" node "${a}": fn "${u}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Fi(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=_b(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function _b(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,d)=>i===0?d:d===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var pm=new Set(["state","producer","derived","effect","operator","template"]),Mb=new Set(["state","producer","derived","effect","operator"]);function Sr(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;i.set(a,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${a}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${a}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),l=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Mb.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${a}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${a}": output "${u.output}" is not a declared node`)}}for(let[a,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${a}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!pm.has(u.type)){e.push(`Node "${a}": invalid type "${String(u.type)}" (expected: ${[...pm].join(", ")})`);continue}if(s.set(a,u.type),u.type==="template")if(typeof u.template!="string"||!i.has(u.template))e.push(`Node "${a}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(u.template),l=u.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===a?e.push(`Node "${a}": self-referencing dep`):o.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${a}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let d=r.feedback[a];if(d==null||typeof d!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${a}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${a}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function Bo(t,e){let n=Sr(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
47
- ${n.errors.join(`
48
- `)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let v=e?.catalog?.graphFactories?.[r];if(v)return v(o)}let s=e?.catalog??{},i=e?.onMissing??"placeholder",a=new Y(t.name),d=t.templates??{},u=jo(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
49
- ${u.errors.join(`
50
- `)}`);let c=[],l=(v,T,w)=>{c.push({path:v,kind:T,name:w})},p=v=>{let T=s.fns?.[v];return T?fm(T):void 0},f=v=>{let T=s.sources?.[v];return T?mm(T):void 0},m=v=>{if(!v)return;let T={};for(let[w,k]of Object.entries(v))w==="factory"||w==="factoryArgs"||(T[w]=k);return Object.keys(T).length>0?T:void 0},h=new Map,g=[];for(let[v,T]of Object.entries(t.nodes)){if(T.type==="template")continue;let w=T,k=fn(w),R=mn(w);if(w.type==="state"){let S=lm(w),x=A(S,{name:v,meta:m(w.meta)});a.add(x,{name:v}),h.set(v,x)}else if(w.type==="producer"){let S=k?f(k):void 0,x=k?p(k):void 0;if(S){let N=S(R);a.add(N,{name:v}),h.set(v,N)}else if(x){let N=x([],R);a.add(N,{name:v}),h.set(v,N)}else{k&&l(v,"source",k);let N=H(()=>{},{name:v,meta:{...m(w.meta),_specSource:k}});a.add(N,{name:v}),h.set(v,N)}}else g.push([v,w])}let y=!0,b=new Map(g);for(;b.size>0&&y;){y=!1;for(let[v,T]of[...b.entries()]){let w=T.deps??[];if(!w.every(E=>h.has(E)))continue;let k=w.map(E=>h.get(E)),R=fn(T),S=mn(T),x=R?p(R):void 0,N;x?N=x(k,S):T.type==="effect"?(R&&l(v,"fn",R),N=he(k,()=>{})):(R&&l(v,"fn",R),N=O(k,E=>E[0])),a.add(N,{name:v}),h.set(v,N),b.delete(v),y=!0}}if(b.size>0){let v=[...b.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${v}`)}for(let[v,T]of Object.entries(t.nodes)){if(T.type!=="template")continue;let w=T,k=d[w.template],R=new Y(v),S=new Map,x=[];for(let[M,C]of Object.entries(k.nodes)){let $=(C.deps??[]).map(F=>F.startsWith("$")&&w.bind[F]?w.bind[F]:F),V={...C,deps:$},G=fn(C),K=mn(C);if(C.type==="state"){let F=lm(C),q=A(F,{name:M,meta:m(C.meta)});R.add(q,{name:M}),S.set(M,q)}else if(C.type==="producer"){let F=G?f(G):void 0,q=G?p(G):void 0;if(F){let D=F(K);R.add(D,{name:M}),S.set(M,D)}else if(q){let D=q([],K);R.add(D,{name:M}),S.set(M,D)}else{G&&l(`${v}.${M}`,"source",G);let D=H(()=>{},{name:M,meta:{...m(C.meta),_specSource:G}});R.add(D,{name:M}),S.set(M,D)}}else x.push([M,V])}let N=!0,E=new Map(x);for(;E.size>0&&N;){N=!1;for(let[M,C]of[...E.entries()]){let $=C.deps??[];if(!$.every(B=>S.has(B)||h.has(B)))continue;let G=$.map(B=>S.get(B)??h.get(B)),K=fn(C),F=mn(C),q=K?p(K):void 0,D;q?D=q(G,F):C.type==="effect"?(K&&l(`${v}.${M}`,"fn",K),D=he(G,()=>{})):(K&&l(`${v}.${M}`,"fn",K),D=O(G,B=>B[0])),R.add(D,{name:M}),S.set(M,D),E.delete(M),N=!0}}if(E.size>0){let M=[...E.keys()].sort().join(", ");throw new Error(`compileSpec: template "${w.template}" has unresolvable deps: ${M}`)}a.mount(v,R);let P=`${v}::${k.output}`;h.set(v,a.resolve(P));try{let M=a.resolve(P);M.meta._templateName?.emit(w.template),M.meta._templateBind?.emit(w.bind)}catch{}}for(let v of t.feedback??[])pn(a,v.from,v.to,{maxIterations:v.maxIterations});if(c.length>0){if(i==="error"){let v=c.map(T=>` - ${T.path}: missing ${T.kind} "${T.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
51
- ${v.join(`
52
- `)}`)}if(i==="warn"){let v=e?.onWarn??(T=>console.warn(T));for(let T of c)v(`compileSpec: ${T.path} references missing ${T.kind} "${T.name}" \u2014 substituted placeholder`)}}return a}var Ob=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Ab(t){let e=t.describe({detail:"spec"}),n=`::${ot}::`,r=/^__feedback_(?!effect_)(.+)$/,o=[],s=new Set;for(let[d,u]of Object.entries(e.nodes))u.meta?.factory!=null&&!d.includes("::")&&s.add(d);let i={};for(let[d,u]of Object.entries(e.nodes)){if(d.includes(n))continue;let c=d.indexOf("::");if(c>0&&s.has(d.slice(0,c)))continue;if(r.exec(d)){let h=u.meta;h?.feedbackFrom&&h?.feedbackTo&&o.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}});continue}if(u.meta?._internal||d.startsWith("__feedback_effect_")||d.startsWith("__bridge_"))continue;let p=u.meta,f=p;if(p&&Object.keys(p).length>0){let h={};for(let[g,y]of Object.entries(p))Ob.has(g)||(h[g]=y);h.factory==="withStatus"?(delete h.status,delete h.error):h.factory==="withBreaker"?delete h.breakerState:h.factory==="verifiable"&&delete h.sourceVersion,f=Object.keys(h).length>0?h:void 0}let m={...u};f===void 0?delete m.meta:m.meta=f,i[d]=m}let a={...e,nodes:i};return delete a.expand,o.length>0&&(a.feedback=o),a}function Cb(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed");let k=v.type==="template"?void 0:fn(v),R=T.type==="template"?void 0:fn(T);k!==R&&w.push(`fn: ${k} \u2192 ${R}`);let S=v.type==="template"?void 0:mn(v),x=T.type==="template"?void 0:mn(T);JSON.stringify(S)!==JSON.stringify(x)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),d=new Set(Object.keys(i));for(let b of d)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)d.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)d.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let u=t.feedback??[],c=e.feedback??[],l=new Set(u.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of u){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of u){let v=`${b.from}->${b.to}`,T=c.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];f&&g.push(`${f} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var hm=`You are a graph architect for GraphReFly, a reactive graph protocol.
53
-
54
- Given a natural-language description, produce a JSON GraphSpec with this structure:
55
-
56
- {
57
- "name": "<graph_name>",
58
- "nodes": {
59
- "<node_name>": {
60
- "type": "state" | "derived" | "producer" | "effect",
61
- "deps": ["<dep_node_name>", ...],
62
- "value": <initial_value>,
63
- "meta": {
64
- "factory": "<catalog_factory_name>",
65
- "factoryArgs": { ... },
66
- "description": "<purpose>"
67
- }
68
- },
69
- "<template_instance>": {
70
- "type": "template",
71
- "template": "<template_name>",
72
- "bind": { "$param": "node_name" }
73
- }
74
- },
75
- "templates": {
76
- "<template_name>": {
77
- "params": ["$param1", "$param2"],
78
- "nodes": { ... },
79
- "output": "<output_node>"
80
- }
81
- },
82
- "feedback": [
83
- { "from": "<condition_node>", "to": "<state_node>", "maxIterations": 10 }
84
- ]
85
- }
86
-
87
- Rules:
88
- - "state" nodes hold user/LLM-writable values (knobs). Stamp the initial value
89
- in "meta.factoryArgs.initial" (or as the top-level "value" field \u2014 both work).
90
- - "derived" nodes compute from deps using a catalog function named in
91
- "meta.factory"; pass any config via "meta.factoryArgs".
92
- - "effect" nodes produce side effects from deps; same meta.factory shape as derived.
93
- - "producer" nodes generate values from a catalog source named in "meta.factory";
94
- pass any config via "meta.factoryArgs".
95
- - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
96
- - Use "feedback" for bounded cycles where a derived value writes back to a state node.
97
- - meta.description is required for every node.
98
- - Return ONLY valid JSON, no markdown fences or commentary.`;function ym(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Lb(t,e,n){let r=hm,o=n?.catalogDescription??(n?.catalog?gm(n.catalog):void 0);o&&(r+=`
99
-
100
- Available catalog (use ONLY these names):
101
- ${o}`),n?.systemPromptExtra&&(r+=`
102
-
103
- ${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],d=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();d.startsWith("```")&&(d=ym(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=Sr(u);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
104
- ${c.errors.join(`
105
- `)}`);let l=u;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=jo(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
106
- ${m.errors.join(`
107
- `)}`);l=await bm(l,`Fix these catalog errors:
108
- ${m.errors.join(`
109
- `)}
110
-
111
- Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function bm(t,e,n,r){let o=hm;r?.catalogDescription&&(o+=`
112
-
113
- Available catalog:
114
- ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
115
-
116
- ${r.systemPromptExtra}`);let s=[{role:"system",content:o},{role:"user",content:`Current GraphSpec:
117
- ${JSON.stringify(t,null,2)}
118
-
119
- Modification request: ${e}
120
-
121
- Return the complete modified GraphSpec as JSON.`}],d=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();d.startsWith("```")&&(d=ym(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=Sr(u);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
122
- ${c.errors.join(`
123
- `)}`);return u}var vm=`You are a graph architect for GraphReFly, a reactive graph protocol.
124
-
125
- Given a natural-language description, produce a JSON graph specification with this structure:
126
-
127
- {
128
- "name": "<graph_name>",
129
- "nodes": {
130
- "<node_name>": {
131
- "type": "state" | "derived" | "producer" | "effect" | "operator",
132
- "initial": <initial_value_for_state_nodes>,
133
- "deps": ["<dep_node_name>", ...],
134
- "meta": {
135
- "description": "<human-readable purpose>",
136
- "type": "string" | "number" | "boolean" | "integer" | "enum",
137
- "range": [min, max],
138
- "values": ["a", "b"],
139
- "format": "currency" | "percentage" | "status",
140
- "access": "human" | "llm" | "both" | "system",
141
- "unit": "<unit>",
142
- "tags": ["<tag>"]
143
- }
144
- }
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
145
11
  }
146
- }
147
-
148
- Rules:
149
- - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
150
- - "derived" nodes have deps and compute from them (pure, no side effects).
151
- - "effect" nodes have deps but produce side effects (no return value).
152
- - "producer" nodes have no deps but generate values asynchronously.
153
- - "operator" nodes are parameterized transformations with deps.
154
- - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
155
- - meta.description is required for every node.
156
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Tm(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${vm}
157
-
158
- ${n.systemPromptExtra}`:vm},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await Oo(s)).content.trim();a.startsWith("```")&&(a=zt(a));let d;try{d=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return Bo(d,{catalog:n?.catalog})}function Ib(t,e,n){let r=Q(t);return ke(r,o=>!o||typeof o!="string"||o.trim().length===0?A(null):H(s=>{let i=new AbortController,a=!1;return Tm(o,e,{...n,signal:i.signal}).then(d=>{if(a){d.destroy();return}s.emit(d),s.down([[I]])}).catch(d=>{a||s.down([[L,d]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function Pb(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Db(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let d=a.meta??{},u=d.access;if(u==="human"||u==="system")continue;let c=d.description??`Set the value of ${i}`,l=Pb(d),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:i,description:c,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:c,parameters:p,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}se();ne();ze();ce();var Gb=`You are a reactive graph optimizer for GraphReFly.
159
-
160
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
161
-
162
- Return ONLY valid JSON with this structure:
163
- {
164
- "summary": "<one-line summary of the strategy>",
165
- "reasoning": "<explanation of why these changes help>",
166
- "operations": [
167
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
168
- { "type": "remove_node", "name": "<name>" },
169
- { "type": "connect", "from": "<source>", "to": "<target>" },
170
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
171
- { "type": "set_value", "name": "<name>", "value": <new_value> },
172
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
173
- ]
174
- }
175
-
176
- Rules:
177
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
178
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
179
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function wm(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Gb},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await Oo(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Fb(t,e,n,r){let o=Q(e),s=Mn(o,t);return ke(s,i=>{if(i==null)return A(null);let[a,d]=i;return!d||!a||typeof a!="string"||a.trim().length===0?A(null):d.destroyed?A(null):H(u=>{let c=new AbortController,l=!1;return wm(d,a,n,{...r,signal:c.signal}).then(p=>{l||(u.emit(p),u.down([[I]]))}).catch(p=>{l||u.down([[L,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var km=new Set(["state","derived","producer","operator","effect"]);function $b(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!km.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...km].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let d=`${a.from}->${a.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}var Ki={};Ee(Ki,{demoShell:()=>Wb});Oe();Ze();ne();Wa();Fe();Re();Me();ne();Fe();Oe();se();Me();function Mt(t,e){t!=null&&Ft(n=>t.down(n),[[_,e]],je.tierOf)}function Vo(t){return t.relatedTo?.[0]??t.summary}function jb(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var xm=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),Bb=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Vb(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Kb(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],d=[],u="",c=null;for(let l of o){let p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
180
- `?p="hard-break":p="text",c!==null&&p===c?u+=l:(c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),u=l,c=p)}c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),n.push({texts:i,isWordLike:a,kinds:d})}return n}function Ut(t,e,n,r,o){let s=Vb(t);if(s.length===0)return[];let i=Kb(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),d=[],u=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)d.push(y.texts[b]),u.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<d.length;y++){let b=d[y],v=u[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(Bb.has(b)||xm.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(jb(b)){let k="";for(let R of a.segment(b)){let S=R.segment;if(k.length>0&&xm.has(S)){k+=S;continue}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}k=S}if(k.length>0){let R=h(k);g.push({text:k,width:R,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let k=[];for(let R of a.segment(b))k.push(h(R.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Hn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,d=0,u=0,c=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=c,k=l,R=i){let S="";for(let x=d;x<w;x++){let N=t[x];if(!(N.kind==="soft-hyphen"||N.kind==="hard-break"))if(x===d&&u>0&&N.graphemeWidths){let P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(M=>M.segment);S+=P.slice(u).join("")}else S+=N.text}if(k>0&&w<t.length){let x=t[w],E=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(x.text)].map(M=>M.segment),P=d===w?u:0;S+=E.slice(P,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(d===w&&u>0)&&(S+="-"),s.push({text:S,width:R,startSegment:d,startGrapheme:u,endSegment:w,endGrapheme:k}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,R){a=!0,d=w,u=k,c=w+1,l=0,i=R}function v(w,k,R){a=!0,d=w,u=k,c=w,l=k+1,i=R}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),d=w+1,u=0;continue}let R=k.width;if(!a){R>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,R),y(k.kind)&&(p=w+1,f=k.kind==="space"?i-R:i);continue}let S=i+R;if(S>e+.005){if(y(k.kind)){i+=R,c=w+1,l=0,g(w+1,0,k.kind==="space"?i-R:i);continue}if(p>=0){g(p,0,f),w--;continue}if(R>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-R:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,R){for(let S=k;S<R.length;S++){let x=R[S];if(!a){v(w,S,x);continue}i+x>e+.005?(g(),v(w,S,x)):(i+=x,c=w,l=S+1)}a&&c===w&&l===R.length&&(c=w+1,l=0)}}function pu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var fu=null;function qb(){return fu===null&&(fu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),fu}function Rm(t,e,n){if(e===0&&n<0)return t.text;let r=[...qb().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function gn(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let d=t[a];d.kind==="soft-hyphen"||d.kind==="hard-break"||(a===e&&n>0?i+=Rm(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=Rm(a,e===r?n:0,o)}return s&&(i+="-"),i}function Hb(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function mu(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=Hb(r),a=o,d=o===e.segmentIndex?s:0,u=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,k,R,S)=>{f=w,m=k,h=R,g=S==="soft-hyphen"},b=(w,k,R)=>{for(let S=k;S<R.length;S++){let x=R[S];if(!p){u=x,c=w,l=S+1,p=!0;continue}if(u+x>n+.005)return!0;u+=x,c=w,l=S+1}return c===w&&l===R.length&&(c=w+1,l=0),!1};if(d>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,d,w.graphemeWidths))return{text:gn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:gn(t,a,d,c,l,S),width:u+(S?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!p){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:gn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}u=k,c=o+1,l=0,p=!0,pu(w.kind)&&y(o+1,0,w.kind==="space"?u-k:u,w.kind),o+=1;continue}let R=u+k;if(R>n+.005){if(pu(w.kind)){c=o+1,l=0;let x=w.kind==="soft-hyphen",N=w.kind==="space"?u:u+(x?i:0);return{text:gn(t,a,d,c,l,x),width:N,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:gn(t,a,d,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:gn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:gn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}u=R,c=o+1,l=0,pu(w.kind)&&y(o+1,0,w.kind==="space"?u-k:u,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:gn(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function gu(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let d=r[a];if(s.right<=d.left||s.left>=d.right){i.push(d);continue}s.left>d.left&&i.push({left:d.left,right:s.left}),s.right<d.right&&i.push({left:s.right,right:d.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Vi(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,d=0;for(let u=i.startSegment;u<e.length;u++){let c=e[u];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(u>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=u===i.startSegment?i.startGrapheme:0,f;if(u<i.endSegment)f=l.length;else if(u===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:d,y:a,width:h,height:n,line:s}),d+=h}}}return r}function zb(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=A(t.text??"",{name:"text"}),i=A(t.font??"16px sans-serif",{name:"font"}),a=A(t.lineHeight??20,{name:"line-height"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"});function u(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let c=J([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=W(),k={hits:0,misses:0},R=Ut(b,T,e,o,k),S=W()-w,x=k.hits+k.misses,N=x===0?1:k.hits/x,E=c.meta;E&&(Mt(E["cache-hit-rate"],N),Mt(E["segment-count"],R.length),Mt(E["layout-time-ns"],S)),h.emit(R);let P=()=>{o.clear(),e.clearCache?.()};return{deactivate:P,invalidate:P}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!u(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=O([c,d,i],([m,h,g])=>Hn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=O([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=O([l,c,a],([m,h,g])=>Vi(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(d,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function Ko(t){return Math.max(0,Math.min(1,t))}function Wb(t){let e=Ko(t?.mainRatio??.65),n=Ko(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,d=new Y("demo-shell"),u=A(e,{name:"pane/main-ratio"}),c=A(n,{name:"pane/side-split"}),l=A(null,{name:"pane/fullscreen"}),p=A(r,{name:"viewport/width"});d.add(u,{name:"pane/main-ratio"}),d.add(c,{name:"pane/side-split"}),d.add(l,{name:"pane/fullscreen"}),d.add(p,{name:"viewport/width"});let f=O([u,p,l],([G,K,F])=>{let q=G,D=K,B=F;return B==="main"?D:B==="graph"||B==="code"?0:Math.round(D*q)},{name:"pane/main-width"}),m=O([f,p,l],([G,K,F])=>{let q=F,D=K;return q==="main"?0:q==="graph"||q==="code"?D:D-G},{name:"pane/side-width"}),h=O([c,l],([G,K])=>{let F=K;return F==="graph"?1:F==="code"||F==="main"?0:Ko(G)},{name:"pane/graph-height-ratio"}),g=O([h,l],([G,K])=>{let F=K;return F==="code"?1:F==="graph"||F==="main"?0:1-G},{name:"pane/code-height-ratio"});d.add(f,{name:"pane/main-width"}),d.add(m,{name:"pane/side-width"}),d.add(h,{name:"pane/graph-height-ratio"}),d.add(g,{name:"pane/code-height-ratio"});let y=A(null,{name:"demo/graph-ref"}),b=A(0,{name:"demo/graph-tick"});d.add(y,{name:"demo/graph-ref"}),d.add(b,{name:"demo/graph-tick"});let v=O([y,b],([G,K])=>{let F=G;return F?tn(F.describe()):""},{name:"graph/mermaid"}),T=O([y,b],([G,K])=>{let F=G;if(!F)return null;let{expand:q,...D}=F.describe({detail:"standard"});return D},{name:"graph/describe"});d.add(v,{name:"graph/mermaid"}),d.add(T,{name:"graph/describe"});let w=A(null,{name:"hover/target"});d.add(w,{name:"hover/target"});let k=O([w],([G])=>{let K=G;if(!K)return null;let F=o.get(K.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),R=O([w],([G])=>{let K=G;if(!K)return null;let F=o.get(K.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=O([w],([G])=>{let K=G;return K?K.id:null},{name:"highlight/graph"});if(d.add(k,{name:"highlight/code-scroll"}),d.add(R,{name:"highlight/visual"}),d.add(S,{name:"highlight/graph"}),a?.codeScroll){let G=a.codeScroll,K=he([k],([F])=>{G(F)});d.add(K,{name:"highlight/apply-code-scroll"})}if(a?.visual){let G=a.visual,K=he([R],([F])=>{G(F)});d.add(K,{name:"highlight/apply-visual"})}if(a?.graph){let G=a.graph,K=he([S],([F])=>{G(F)});d.add(K,{name:"highlight/apply-graph"})}let x=A(null,{name:"inspect/selected-node"});d.add(x,{name:"inspect/selected-node"});let N=Xt("standard"),E=O([x,y,b],([G,K,F])=>{let q=K,D=G;if(!q||!D)return null;try{let B=q.resolve(D),re=Jr(B,N);return{path:D,...re,value:B.cache}}catch{return null}},{name:"inspect/node-detail"}),P=O([y,b],([G,K])=>{let F=G;return F?F.trace():[]},{name:"inspect/trace-log"});d.add(E,{name:"inspect/node-detail"}),d.add(P,{name:"inspect/trace-log"});let M=A(!1,{name:"meta/debug"});d.add(M,{name:"meta/debug"});let C=O([M,b],([G,K])=>G?tn(d.describe()):"",{name:"meta/shell-mermaid"});d.add(C,{name:"meta/shell-mermaid"});let $=A("",{name:"layout/code-text"});if(d.add($,{name:"layout/code-text"}),s){let G=new Map,K=O([T],([D])=>{let B=D;if(!B)return new Map;let re=new Map;for(let[ye]of Object.entries(B.nodes)){let ee=Ut(ye,i,s,G),me=Hn(ee,1/0,s,i,G),Le=me.lines.reduce((Qe,U)=>Math.max(Qe,U.width),0),rt=me.lineCount*20;re.set(ye,{width:Le,height:rt})}return re},{name:"layout/graph-labels",equals:(D,B)=>{if(D===B)return!0;let re=D,ye=B;if(re.size!==ye.size)return!1;for(let[ee,me]of re){let Le=ye.get(ee);if(!Le||Le.width!==me.width||Le.height!==me.height)return!1}return!0}}),F=O([$,m],([D,B])=>{let re=D;if(!re)return{lineCount:0,lines:[]};let ye=Ut(re,i,s,G),ee=B-40;return Hn(ye,Math.max(100,ee),s,i,G)},{name:"layout/code-lines"}),q=O([K],([D])=>{let B=D;if(B.size===0)return 200;let re=0;for(let{width:ye}of B.values())ye>re&&(re=ye);return Math.max(200,Math.round(re+80))},{name:"layout/side-width-hint"});d.add(K,{name:"layout/graph-labels"}),d.add(F,{name:"layout/code-lines"}),d.add(q,{name:"layout/side-width-hint"})}let V=0;return{graph:d,setMainRatio(G){d.set("pane/main-ratio",Ko(G))},setSideSplit(G){d.set("pane/side-split",Ko(G))},setFullscreen(G){d.set("pane/fullscreen",G)},setViewportWidth(G){d.set("viewport/width",Math.max(0,G))},setHoverTarget(G){d.set("hover/target",G)},setDemoGraph(G){d.set("demo/graph-ref",G)},bumpGraphTick(){d.set("demo/graph-tick",++V)},selectNode(G){d.set("inspect/selected-node",G)},setMetaDebug(G){d.set("meta/debug",G)},setCodeText(G){d.set("layout/code-text",G)},batch(G){Z(G)},destroy(){d.destroy()}}}var qi={};Ee(qi,{contentModerationGraph:()=>Yb,dataQualityGraph:()=>Qb,issueTrackerGraph:()=>Jb,observabilityGraph:()=>Ub});Oe();ne();Fe();ut();ce();function Pe(t,e){return we("domain_template",t,e)}function Ub(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>hu(T,"error")},{name:"traces",classify:T=>hu(T,"trace")},{name:"metrics",classify:T=>hu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=No("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return O([w],([k])=>k,{initial:null})}catch{return A(null)}}),d=e.correlate??(T=>T),u=O(a,T=>d(T),{meta:Pe("observability",{stage:"correlate"})});n.add(u,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=O([u],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=O([l],T=>c(T[0]),{meta:Pe("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>O([T],w=>w[0]!=null?1:0)),h=f.map(T=>A(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=Fo(m,h);n.add(g,{name:"alerts"});let y=O([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Pe("observability",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Pe("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),pn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Jb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=O([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),d=O([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Pe("issue_tracker",{stage:"verify"})});n.add(d,{name:"verify"});let u=A([],{meta:Pe("issue_tracker",{stage:"known_patterns"})});n.add(u,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=O([i,u],T=>{let w=T[0],k=T[1];return{issue:w,regression:c(w,k)}},{meta:Pe("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=O([i],T=>T[0]?.severity??0),f=O([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=A(1),h=A(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=Fo([p,f],[m,h]);n.add(g,{name:"priority"});let y=O([d,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Pe("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([d],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Pe("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),pn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Yb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=O([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=No("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=We([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let d;try{d=n.resolve("stratify::branch/review")}catch{d=A(null),n.add(d,{name:"__review_fallback"})}let u=he([d],v=>{let T=v[0];T&&a.append(T)});n.add(u,{name:"__review_accumulator"}),n.addDisposer(te(u));let c=A({},{meta:Pe("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=O([s],v=>v[0]?.confidence??0),f=O([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=A(1),h=A(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=Fo([p,f],[m,h]);n.add(g,{name:"priority"});let y=O([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=O([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Pe("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),pn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Qb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=O([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Pe("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=O([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Pe("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=A(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let d=he([o],g=>{let y=g[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(d,{name:"__baseline_updater"}),te(d);let u=e.detectDrift??(()=>({drift:!1})),c=O([e.source,a],g=>u(g[0],g[1]),{meta:Pe("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=O([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=O([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Pe("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=A([],{meta:Pe("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=O([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Pe("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),pn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function hu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Zi={};Ee(Zi,{DEFAULT_DECAY_RATE:()=>Er,DEFAULT_EXECUTE_PROMPT:()=>bu,DEFAULT_QUEUE_CONFIGS:()=>Hi,DEFAULT_SEVERITY_WEIGHTS:()=>Nr,DEFAULT_TRIAGE_PROMPT:()=>yu,DEFAULT_VERIFY_PROMPT:()=>vu,HarnessGraph:()=>Xi,QUEUE_NAMES:()=>pt,actuatorExecutor:()=>Sm,affectedTaskFilter:()=>dv,autoSolidify:()=>rv,beforeAfterCompare:()=>av,blindVariation:()=>mv,codeChangeBridge:()=>uv,createIntakeBridge:()=>ov,defaultErrorClassifier:()=>zi,defaultLlmExecutor:()=>Cm,defaultLlmVerifier:()=>Lm,dispatchActuator:()=>nv,effectivenessTracker:()=>pv,errorCritique:()=>yv,evalIntakeBridge:()=>sv,evalSource:()=>iv,evalVerifier:()=>Em,harnessEvalPair:()=>kv,harnessLoop:()=>_v,harnessProfile:()=>Ov,harnessTrace:()=>Cv,notifyEffect:()=>cv,priorityScore:()=>Nv,refineExecutor:()=>ku,refineLoop:()=>wu,resolvePromptFn:()=>qo,strategyKey:()=>_r,strategyModel:()=>Su});se();ne();ce();function Xb(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${tv(e.summary)}`,artifact:t}}function Zb(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function ev(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function tv(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Sm(t){let e=t.name??"actuator-executor",n=t.toOutput??Xb,r=t.onError??Zb,o=t.skipDetail??ev;return s=>{let i=s.payload.item;return t.shouldApply&&!t.shouldApply(i)?{...s.payload,execution:{item:i,outcome:"failure",detail:o(i)}}:H(a=>{let d=new AbortController,u=!1,c=null,l=f=>{u||(u=!0,a.down([[_,{...s.payload,execution:{item:i,...f}}],[I]]),c?.(),c=null)},p;try{let f=t.apply(i,{signal:d.signal});p=Q(f,{signal:d.signal})}catch(f){return l(r(f,i)),()=>{d.abort()}}return c=p.subscribe(f=>{for(let m of f){if(u)return;if(m[0]===_){l(n(m[1],i));return}if(m[0]===L){l(r(m[1],i));return}if(m[0]===I){l(r(new Error("actuator inner completed without emitting DATA"),i));return}}}),u&&c&&(c(),c=null),()=>{d.abort(),c?.(),c=null}},{name:`${e}/inner`})}}function nv(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return Sm({apply:(o,s)=>{let i=Object.hasOwn(t.routes,o.intervention)?t.routes[o.intervention]:n;if(!i)throw new Error(`dispatchActuator: no route for intervention '${o.intervention}'`);return i(o,s)},shouldApply:o=>Object.hasOwn(t.routes,o.intervention)||r,skipDetail:o=>`no route for intervention '${o.intervention}'`,name:e})}se();ne();function rv(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return H(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},d=u=>{i||(o.down([[L,u]]),a())};return s=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==_){if(c[0]===I){o.down([[I]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){d(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){d(m);return}if(f!=null){try{t.write(f,l)}catch(m){d(m);return}o.down([[_,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ne();ze();ce();function ov(t,e,n,r){return he([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function sv(t,e,n){let r=n?.defaultSeverity??"medium";return he([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function iv(t,e){return ke(t,()=>Q(e()))}function av(t,e){return O([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],l=[];for(let p of d){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;u.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:u,overallImproved:l.length>c.length}},{name:"eval-delta"})}function dv(t,e){let n=e==null?null:Array.isArray(e)?A(e):e,r=[t];return n&&r.push(n),O(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let d of s)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function uv(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:o});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:o});return d}let i=n??s;return he([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function cv(t,e,n){return he([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var pt=["auto-fix","needs-decision","investigation","backlog"],Hi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},Nr={critical:100,high:70,medium:40,low:10},Er=Math.LN2/(168*3600);function _r(t,e){return`${t}\u2192${e}`}var lv=/\b(parse|json|config|validation|syntax)\b/i,zi=t=>lv.test(t.detail)?"self-correctable":"structural",yu=`You are a triage classifier for a reactive collaboration harness.
181
-
182
- Given an intake item, classify it and output JSON:
183
- {
184
- "rootCause": "composition" | "missing-fn" | "bad-docs" | "schema-gap" | "regression" | "unknown",
185
- "intervention": "template" | "catalog-fn" | "docs" | "wrapper" | "schema-change" | "investigate",
186
- "route": "auto-fix" | "needs-decision" | "investigation" | "backlog",
187
- "priority": <number 0-100>,
188
- "triageReasoning": "<one sentence>"
189
- }
190
-
191
- Strategy model (past effectiveness):
192
- {{strategy}}
193
-
194
- Intake item:
195
- {{item}}`,bu=`You are an implementation agent.
196
-
197
- Given a triaged issue with root cause and intervention type, produce a fix.
198
-
199
- Issue:
200
- {{item}}
201
-
202
- Output JSON:
203
- {
204
- "outcome": "success" | "failure" | "partial",
205
- "detail": "<description of what was done or what failed>"
206
- }`,vu=`You are a QA reviewer.
207
-
208
- Given an execution result, verify whether the fix is correct.
209
-
210
- Execution:
211
- {{execution}}
212
-
213
- Original issue:
214
- {{item}}
215
-
216
- Output JSON:
217
- {
218
- "verified": true/false,
219
- "findings": ["<finding1>", ...],
220
- "errorClass": "self-correctable" | "structural" // only if verified=false
221
- }`;function qo(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ne();ce();function pv(t){let e=Xe({name:t?.name??"effectiveness-entries"}),n=O([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function o(i){return e.get(i)}let s=te(n);return{node:n,record:r,lookup:o,dispose:()=>{s(),e.dispose()}}}Oe();ne();ze();ne();ze();Oe();Re();se();Me();ne();ze();Fe();function fv(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Nm(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=Tu(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let d=0;d<t.length;d++)s[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(s[u].sum+=d.score,s[u].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=s[d].count>0?s[d].sum/s[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function Tu(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function wu(t,e,n,r){let o=r.name??"refine-loop",s=new Y(o,r.graph),i=fv(r.dataset)?r.dataset:A(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=A(0,{name:"iteration"});s.add(a,{name:"iteration"});let d=A(n,{name:"strategy",equals:()=>!1});s.add(d,{name:"strategy"});let u=A(null,{name:"lastFeedback"});s.add(u,{name:"lastFeedback"});let c=A([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=A(!1,{name:"paused"});s.add(l,{name:"paused"});let p=A("running",{name:"status"});s.add(p,{name:"status"});let f=A([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=A(null,{name:"best"});s.add(m,{name:"best"});let h=A(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=A(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Lo("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,R=null,S=[];s.addDisposer(d.subscribe(U=>{for(let de of U)de[0]===_&&(k=de[1])})),s.addDisposer(u.subscribe(U=>{for(let de of U)de[0]===_&&(R=de[1])})),s.addDisposer(c.subscribe(U=>{for(let de of U)de[0]===_&&(S=de[1])}));let x=ke(a,U=>{let de=k,De=U===0||R==null;return J([],($e,Ve)=>{let Se=!1;try{let X=De?de.seed(t):de.generate(R,S);if(X instanceof Promise)return X.then(j=>{Se||Ve.emit(j)},j=>{Se||Ve.down([[L,j]])}),()=>{Se=!0};Ve.emit(X)}catch(X){Se=!0,Ve.down([[L,X]])}},{describeKind:"producer"})},{name:"candidates"});s.add(x,{name:"candidates"});let N=he([x],(U,de,De)=>{let $e=De.terminalDeps[0];$e!==void 0&&$e!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(N,{name:"error-watcher"}),s.addDisposer(N.subscribe(()=>{}));let E=O([x,a],([U,de])=>({iteration:de,candidates:U,timestamp_ns:W()}),{name:"generate-event"});s.add(E,{name:"generate-event"}),s.addDisposer(E.subscribe(()=>{}));let P=he([E],([U])=>{b.publish(U)},{name:"generate-publish"});s.add(P,{name:"generate-publish"}),s.addDisposer(P.subscribe(()=>{}));let M=he([x],([U])=>{c.emit(U)},{name:"generate-mirror"});s.add(M,{name:"generate-mirror"}),s.addDisposer(M.subscribe(()=>{}));let C=e(x,i);s.add(C,{name:"scores"});let $=O([C,x,a],([U,de,De])=>({iteration:De,candidates:de,scores:U,timestamp_ns:W()}),{name:"evaluate-event"});s.add($,{name:"evaluate-event"}),s.addDisposer($.subscribe(()=>{}));let V=he([$],([U])=>{v.publish(U)},{name:"evaluate-publish"});s.add(V,{name:"evaluate-publish"}),s.addDisposer(V.subscribe(()=>{}));let G=O([C,x],([U,de])=>k.analyze(U,de),{name:"feedback"});s.add(G,{name:"feedback"});let K=O([G,x,a],([U,de,De])=>({iteration:De,candidates:de,feedback:U,timestamp_ns:W()}),{name:"analyze-event"});s.add(K,{name:"analyze-event"}),s.addDisposer(K.subscribe(()=>{}));let F=he([K],([U])=>{T.publish(U)},{name:"analyze-publish"});s.add(F,{name:"analyze-publish"}),s.addDisposer(F.subscribe(()=>{}));let q=O([f],([U])=>{let de=U;if(r.patience==null||de.length<=r.patience)return!1;let De=de.slice(-(r.patience+1)),$e=De[0].bestScore;return De.slice(1).every(Ve=>Ve.bestScore<=$e)},{name:"patience-check"});s.add(q,{name:"patience-check"});let D=O([h],([U])=>r.minScore!=null&&U>=r.minScore,{name:"min-score-check"});s.add(D,{name:"min-score-check"});let B=O([f],([U])=>{let de=U;if(r.minDelta==null||de.length<2)return!1;let De=de[de.length-2].bestScore,$e=de[de.length-1].bestScore;return Math.abs($e-De)<r.minDelta},{name:"min-delta-check"});s.add(B,{name:"min-delta-check"});let re=O([g],([U])=>r.maxEvaluations!=null&&U>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(re,{name:"max-evaluations-check"});let ye=O([a],([U])=>r.maxIterations!=null&&U>=r.maxIterations,{name:"max-iterations-check"});s.add(ye,{name:"max-iterations-check"});let ee=O([g],([U])=>r.budget!=null&&U>=r.budget,{name:"budget-exhausted-check"});s.add(ee,{name:"budget-exhausted-check"}),s.addDisposer(q.subscribe(()=>{})),s.addDisposer(D.subscribe(()=>{})),s.addDisposer(B.subscribe(()=>{})),s.addDisposer(re.subscribe(()=>{})),s.addDisposer(ye.subscribe(()=>{})),s.addDisposer(ee.subscribe(()=>{}));let me=O([q,D,B,re,ye],([U,de,De,$e,Ve])=>U?{converged:!0,reason:"patience"}:de?{converged:!0,reason:"min-score"}:De?{converged:!0,reason:"min-delta"}:$e?{converged:!0,reason:"max-evaluations"}:Ve?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(me,{name:"converged"}),s.addDisposer(me.subscribe(()=>{}));let Le=-1,rt=he([G,C,x],([U,de,De])=>{let $e=a.cache,Ve=U,Se=De,X=de;if($e<=Le)return;Le=$e;let{best:j,bestScore:ae}=Nm(Se,X),le=f.cache,Ne={n:$e,candidates:Se,scores:X,feedback:Ve,best:j,bestScore:ae,timestamp_ns:W()},xe=[...le,Ne],Ke=g.cache+Se.length,pe="continue",ue,zn=r.budget!=null&&Ke>=r.budget,hn=l.cache;if(zn)pe="budget",ue="budget";else if(r.minScore!=null&&Ve.score>=r.minScore)pe="converged",ue="min-score";else if(r.maxIterations!=null&&$e>=r.maxIterations)pe="converged",ue="max-iterations";else if(r.maxEvaluations!=null&&Ke>=r.maxEvaluations)pe="converged",ue="max-evaluations";else if(r.minDelta!=null&&xe.length>=2){let Uo=xe[xe.length-2].bestScore,ha=xe[xe.length-1].bestScore;Math.abs(ha-Uo)<r.minDelta&&(pe="converged",ue="min-delta")}else if(r.patience!=null&&xe.length>r.patience){let Uo=xe.slice(-(r.patience+1)),ha=Uo[0].bestScore;Uo.slice(1).every(Um=>Um.bestScore<=ha)&&(pe="converged",ue="patience")}pe==="continue"&&hn&&(pe="paused"),Z(()=>{m.emit(j),h.emit(Ve.score),f.emit(xe),g.emit(Ke),u.emit(Ve),w.publish({iteration:$e,decision:pe,reason:ue,timestamp_ns:W()}),pe==="continue"?a.emit($e+1):p.emit(pe==="converged"?"converged":pe==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(rt,{name:"decide-bridge"}),s.addDisposer(rt.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:p,history:f,strategy:d,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(U){d.emit(U)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Z(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function mv(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=Tu(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,d={prior:s,reportCost:u=>{i+=u}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(d)));let u=[];for(let c=0;c<e;c++)u.push(await t.teacher(d));return u}finally{if(t.tokens!=null&&i>0){let u=t.tokens.cache??0;t.tokens.emit(u+i)}}}}}function gv(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function hv(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
222
- ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
223
- `)}`}function yv(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??hv;return{name:n,seed(s){return[s]},analyze(s,i){let a=Tu(s),d=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,l=u?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Nm(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=gv(s.critique)?s.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:d,critique:u,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function bv(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function ku(t){let e=t.name??"refine-executor",n=t.toOutput??bv;return r=>{let o=r.payload.item,s=wu(t.seedFrom(o),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(o),name:`${e}/inner`}),i=O([s.status,s.best,s.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let l=n({best:d,score:u,status:c});return{...r.payload,execution:{item:o,...l}}},{name:`${e}/output`});return kt(i,a=>a!=null,{name:`${e}/gate-out`})}}function vv(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Tv(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,d=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function wv(t){return t.artifact??null}function Em(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Tv,o=t.extractArtifact??wv;return s=>{let{item:i,execution:a}=s.payload;if(a==null)return{...s.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=o(a,i);if(d==null)return{...s.payload,verify:r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0})};let u=A([d],{name:`${e}/candidates`}),c=A(t.datasetFor(i),{name:`${e}/dataset`}),l;Z(()=>{l=t.evaluator(u,c)});let p=O([l],([f])=>{let m=f;if(m==null)return null;let h=vv(m),g=m.filter(y=>y.score>=n).length;return{...s.payload,verify:r({scores:m,meanScore:h,passCount:g,total:m.length,threshold:n})}},{name:`${e}/output`});return kt(p,f=>f!=null,{name:`${e}/gate-out`})}}function kv(t){let e=t.name??"harness-pair",n=ku({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Em({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Re();Ze();ne();ze();Fe();var Qi={};Ee(Qi,{JobFlowGraph:()=>Ji,JobQueueGraph:()=>Ui,jobEventKeyOf:()=>Sv,jobFlow:()=>Ru,jobQueue:()=>Yi});Re();Me();ut();ce();Tt();var xv=256,Rv=1024;function xu(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Wi(t,e){return we("job_queue",t,e)}var Sv=t=>t.action,Ui=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;_enqueueImpl;_ackImpl;_nackImpl;_removeByIdImpl;constructor(e,n={}){super(e,n.graph),this._pending=ii([],{name:"pending"}),this._jobs=Xe({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=O([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Wi("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(te(this.depth)),this.events=at({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=ht(this,"seq",0),this._enqueueImpl=Ce((r,o)=>{let s=this._seqCursor.cache,i=o.id??`${this.name}-${s}`;if(this._jobs.get(i)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${i}"`);let a={id:i,payload:r,attempts:0,metadata:Object.freeze({...o.metadata??{}}),state:"queued"};return this._jobs.set(i,a),this._pending.append(i),i},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r],o,{t_ns:s,seq:i})=>({action:"enqueue",id:o,payload:r,t_ns:s,seq:i??0})}),this._ackImpl=Ce((r,o)=>{this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"ack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._nackImpl=Ce((r,o,s)=>{s?(this._jobs.set(r,{...o,state:"queued"}),this._pending.append(r)):this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"nack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._removeByIdImpl=Ce((r,o)=>{if(o.state==="queued"){let i=this.pending.cache.indexOf(r);i>=0&&this._pending.pop(i)}this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"remove",id:r,attempts:o.attempts,t_ns:i,seq:a??0})})}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){return this._enqueueImpl(e,n)}claim(e=1){let n=xu(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:ie(),seq:Bt(this._seqCursor)})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._ackImpl(e,n),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:(this._nackImpl(e,r,n.requeue??!0),!0)}removeById(e){let n=this._jobs.get(e);return n?(this._removeByIdImpl(e,n),!0):!1}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==_)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},Ji=class extends Y{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map,i=new Map;for(let u of r){let c=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&s.set(c,u.work),typeof u!="string"&&u.maxPerPump!=null&&i.set(c,Math.max(1,xu(u.maxPerPump,`job flow stage "${c}" maxPerPump`))),o.push(c)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let u of this._stageNames){let c=Yi(`${e}-${u}`);this._queues.set(u,c),this.mount(u,c)}this._completed=We([],{name:"completed",maxSize:Rv}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=O([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Wi("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(te(this.completedCount));let d=Math.max(1,xu(n.maxPerPump??xv,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let c=this._stageNames[u],l=this.queue(c),p=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,f=this._stageWorkFns.get(c),m=i.get(c)??d,h=p===null;if(f){let g=J([l.pending],()=>{let y=0;for(;y<m;){let b=l.claim(1);if(b.length===0)break;let v=b[0];if(!v)break;let w=[...v.metadata.job_flow_path??[],c],k;try{k=f(v)}catch{l.nack(v.id,{requeue:!1}),y+=1;continue}let R=Q(k),S=!1,x;x=R.subscribe(N=>{if(!S){for(let E of N)if(E[0]===_){S=!0,x?x():Promise.resolve().then(()=>x?.());let P=E[1],M={...v.metadata,job_flow_path:w};if(h){let C={...v,payload:P,metadata:Object.freeze(M)};Z(()=>{l.ack(v.id),this._completed.append(C)})}else Z(()=>{l.ack(v.id),p.enqueue(P,{metadata:M})});return}else if(E[0]===L){S=!0,x?x():Promise.resolve().then(()=>x?.()),l.nack(v.id,{requeue:!1});return}}}),y+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wi("job_flow_pump",{stage:c,has_work:!0})});this.add(g,{name:`pump_${c}`}),this.addDisposer(te(g))}else{let g=J([l.pending],()=>{let y=0;for(;y<m;){let b=l.claim(1);if(b.length===0)break;let v=b[0];if(!v)break;let w=[...v.metadata.job_flow_path??[],c],k={...v.metadata,job_flow_path:w};if(h){let R={...v,metadata:Object.freeze(k)};Z(()=>{l.ack(v.id),this._completed.append(R)})}else Z(()=>{l.ack(v.id),p.enqueue(v.payload,{metadata:k})});y+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wi("job_flow_pump",{stage:c,has_work:!1})});this.add(g,{name:`pump_${c}`}),this.addDisposer(te(g))}}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Yi(t,e){return new Ui(t,e)}function Ru(t,e){let n=new Ji(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",He(s)),n}Re();ne();function Su(){let t=Xe({name:"strategy-entries"}),e=O([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,d){let u=_r(i,a),c=t.get(u),l=(c?.attempts??0)+1,p=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(_r(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function Nv(t,e,n,r,o){let s={...Nr,...o?.severityWeights},i=o?.decayRate??Er,a=o?.effectivenessThreshold??.7,d=o?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),O(u,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(W()-f)/1e9,y=It(h,g,i,0),b=_r(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var _m="intake",Ev="triage-output",Mm="retry",Om="verify-results",Am="__unrouted";function Cm(t,e){let n=qo(e,bu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>{let o=r.payload.item,s=[{role:"user",content:n(o)}],i=d=>({...r.payload,execution:{item:o,outcome:"failure",detail:d}}),a=d=>d instanceof Error?d.message:String(d);return Qd(t,s,{onSuccess:d=>{let u;try{u=JSON.parse(zt(String(d.content)))}catch(l){return i(`execute parse error: ${a(l)}`)}if(u==null||typeof u!="object"||Array.isArray(u))return i(`execute parse error: non-object response: ${JSON.stringify(u)}`);let c=u;return{...r.payload,execution:{item:o,outcome:c.outcome??"failure",detail:c.detail??"unknown",artifact:c.artifact}}},onFailure:(d,u)=>i(d==="complete"?"adapter completed without emitting DATA":`executor failed: ${a(u)}`)})}}function Lm(t,e){let n=qo(e,vu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>{let{item:o,execution:s}=r.payload;if(s==null)return{...r.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let i=[{role:"user",content:n([s,o])}],a=u=>({...r.payload,verify:{verified:!1,findings:[u],errorClass:"self-correctable"}}),d=u=>u instanceof Error?u.message:String(u);return Qd(t,i,{onSuccess:u=>{let c;try{c=JSON.parse(zt(String(u.content)))}catch(p){return a(`verify parse error: ${d(p)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`verify parse error: non-object response: ${JSON.stringify(c)}`);let l=c;return{...r.payload,verify:{verified:l.verified===!0,findings:l.findings??[],errorClass:l.errorClass}}},onFailure:(u,c)=>a(u==="complete"?"verifier completed without emitting DATA":`verifier failed: ${d(c)}`)})}}var Xi=class extends Y{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;reflect;constructor(e,n,r,o,s,i,a,d,u,c,l){super(e),this.queues=n,this.executeFlow=r,this.queueTopics=o,this.jobs=s,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.reflect=c,this.priorityScores=l}get intake(){return this.queues.topic(_m)}get verifyResults(){return this.queues.topic(Om)}get retry(){return this.queues.topic(Mm)}get unrouted(){return this.queues.topic(Am)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=pt.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function _v(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??zi,i=new Map;for(let X of pt)i.set(X,{...Hi[X],...e.queues?.[X]});let a=Lo(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(_m),u=a.topic(Ev),c=a.topic(Mm),l=a.topic(Om),p=new Map;for(let X of pt)p.set(X,a.topic(X));let f=a.topic(Am),m=Su(),h=Mn(d.latest,m.node),g=qo(e.triagePrompt,yu,(X,j)=>{let[ae,le]=j;return X.replace("{{strategy}}",JSON.stringify(Array.from(le.entries()))).replace("{{item}}",JSON.stringify(ae))}),y=Ao(n,[h],X=>{let j=X;return!j||!j[0]?"":g(j)},{name:"triage",format:"json"}),b=Mn(y,h),T=he([b],([X])=>{if(X==null)return;let[j,ae]=X;if(!j?.route)return;let le=ae?.[0],Ne={...j,...le};u.publish(Ne)}).subscribe(()=>{}),w=new Set(pt);for(let X of pt)_i(`bridge/${X}`,u,p.get(X),{map:j=>j.route===X?j:void 0});_i("bridge/__unrouted",u,f,{map:X=>w.has(X.route)?void 0:X});let k=new Map,R=new Map;for(let X of pt)k.set(X,Yi(`jobs/${X}`));let S=[];for(let X of pt){let j=p.get(X),ae=k.get(X),le=new WeakSet,Ne=he([j.events],([xe])=>{let Ke=xe??[];for(let pe of Ke){if(le.has(pe))continue;le.add(pe);let ue=ae.enqueue(pe);R.set(Vo(pe),{route:X,id:ue})}},{name:`jobs/${X}-mirror`});S.push(Ne.subscribe(()=>{}))}function x(X){let j=Vo(X),ae=R.get(j);ae&&(k.get(ae.route)?.removeById(ae.id),R.delete(j))}let N=Rr("gates"),E=new Map;for(let X of pt){let j=i.get(X);if(!j.gated)continue;let ae=p.get(X),le=N.approvalGate(`${X}/gate`,ae.latest,{maxPending:j.maxPending,startOpen:j.startOpen});E.set(X,le)}let P=[];for(let X of pt)i.get(X).gated&&E.has(X)?P.push(E.get(X).node):P.push(p.get(X).latest);P.push(c.latest);let M=Ct(...P),C=e.executor??Cm(n,e.executePrompt),$=e.verifier??Lm(n,e.verifyPrompt),V=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,G=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,K=Ru(`${t}/executeFlow`,{stages:[{name:"execute",work:X=>C(X),maxPerPump:V},{name:"verify",work:X=>$(X),maxPerPump:G}]}),F=he([M],([X])=>{X!=null&&K.enqueue({item:X})},{name:"execute-enqueue"}),q=F.subscribe(()=>{}),D=e.maxReingestions??1,B=Math.min(e.maxTotalRetries??r*10,100),re=Math.min(e.maxTotalReingestions??D*10,100),ye=A(0),ee=A(0);function me(X,j,ae){return{item:ae,execution:X,verified:j.verified,findings:j.findings??[],errorClass:j.errorClass}}function Le(X,j){m.record(j.rootCause,j.intervention,!0),l.publish(X),x(j)}function rt(X,j){let ae=Vo(j),le=j.$retries??0,Ne={...j,$retries:le+1,summary:`[RETRY ${le+1}/${r}] ${ae} \u2014 Previous attempt failed: ${X.findings.join("; ")}`,relatedTo:[ae]};c.publish(Ne)}function Qe(X,j){m.record(j.rootCause,j.intervention,!1),l.publish(X),x(j);let ae=Vo(j),le=j.$reingestions??0;le<D&&Gn(ee,re)&&d.publish({source:j.source,summary:`Verification failed for: ${ae}`,evidence:X.findings.join(`
224
- `),affectsAreas:j.affectsAreas,affectsEvalTasks:j.affectsEvalTasks,severity:j.severity??"high",relatedTo:[ae],$reingestions:le+1})}let U=0,de=he([K.completed],([X])=>{let j=X??[];U>j.length&&(U=j.length);let ae=U;U=j.length;for(let le=ae;le<j.length;le++){let Ne=j[le],{item:xe,execution:Ke,verify:pe}=Ne.payload;if(Ke==null||pe==null){x(xe);continue}let ue=me(Ke,pe,xe);if(ue.verified){Le(ue,xe);continue}let zn=ue.errorClass??s({item:xe,outcome:Ke.outcome,detail:ue.findings.join("; ")}),hn=xe.$retries??0;zn==="self-correctable"&&hn<r&&Gn(ye,B)?rt(ue,xe):Qe(ue,xe)}},{name:"verify-dispatch"}),De=de.subscribe(()=>{}),$e=O([K.completed],()=>null,{name:"reflect",equals:()=>!1}),Ve;e.priority&&(Ve=Mv(p,m,e));let Se=new Xi(t,a,K,p,k,E,m,ye,ee,$e,Ve);Se.addDisposer(T),Se.addDisposer(q),Se.addDisposer(De),Se.addDisposer(m.dispose);for(let X of S)Se.addDisposer(X);if(Se.add(h,{name:"triage-input"}),Se.add(y,{name:"triage"}),Se.add(b,{name:"router-input"}),Se.add(M,{name:"execute-input"}),Se.add(F,{name:"execute-enqueue"}),Se.add(de,{name:"verify-dispatch"}),Se.add($e,{name:"reflect"}),Se.add(m.node,{name:"strategy"}),Se.addDisposer($e.subscribe(()=>{})),Ve)for(let[X,j]of Ve)Se.add(j,{name:`priority/${X}`}),Se.addDisposer(j.subscribe(()=>{}));Se.mount("queues",a),Se.mount("gates",N),Se.mount("executeFlow",K);for(let[X,j]of k)Se.mount(`jobs/${X}`,j);return Se.tagFactory("harnessLoop",He(e)),Se}function Mv(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...Nr,...o.severityWeights},i=o.decayRate??Er,a=o.effectivenessThreshold??.7,d=o.effectivenessBoost??15,u=new Map;for(let[c,l]of t){let p=O([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(W()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=d),y},{name:`priority/${c}`});u.set(c,p)}return u}gs();function Ov(t,e){let n=xn(t,e),r={};for(let o of pt){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Re();function Av(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Cv(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=W(),s=[],i=[],a=Av(t);function d(){return(W()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=Lv(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?u(l,"data",f.data):f.type==="error"?u(l,"error",f.data):f.type==="complete"&&u(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);u(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${d().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Lv(t){if(t==null)return"null";if(typeof t=="string")return Im(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Im(e,120)}catch{return String(t)}}function Im(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var oa={};Ee(oa,{AuditTrailGraph:()=>ea,GuardedExecutionGraph:()=>na,InspectGraph:()=>ra,PolicyGateGraph:()=>ta,auditTrail:()=>Eu,complianceSnapshot:()=>Mu,computeHealthReport:()=>Fm,graphLens:()=>Au,guardedExecution:()=>$v,healthReportEqual:()=>$m,inspect:()=>jv,policyGate:()=>_u,watchTopologyTree:()=>Nn});Oe();Re();Jt();se();Ze();Me();ne();es();ut();ce();Tt();function Gm(t,e){return we("audit",t,e)}var Iv=new Set(["data","error","complete","teardown"]),ea=class extends Y{entries;count;includeTypes;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=We([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=O([this.entries],([d])=>d.length,{name:"count",describeKind:"derived",meta:Gm("count")}),this.add(this.count,{name:"count"}),this.addDisposer(te(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):new Set(Iv);this.includeTypes=r;let o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(d=>{if(d.type==="derived")return;let u=d.type;if(!r.has(u))return;let c=d.path??"",l={seq:s++,timestamp_ns:d.timestamp_ns??W(),wall_clock_ns:ie(),path:c,type:u},f=(c?Nu(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),u==="data"&&(l.value=d.data),u==="error"&&(l.error=d.data);let m=c?Pv(e,c):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function Eu(t,e={}){return new ea(t,e)}var ta=class extends Y{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=Pm(n)?n:A(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Wt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=O([this.violations.events],([m])=>m.length,{name:"violationCount",describeKind:"derived",meta:Gm("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(te(this.violationCount));let i=o.cache??[];this._currentGuard=Vr(i);let a=o.subscribe(m=>{for(let h of m)h[0]===_&&(i=h[1]??[],this._currentGuard=Vr(i))});this.addDisposer(a);let d=r.paths,u=Pm(d)?d:void 0,c=d!=null,p=u!=null?u.cache??[]:c?[...d]:void 0,f=p??Dm(e);if(this._mode!=="enforce"&&u!=null){let m=u.subscribe(h=>{for(let g of h)g[0]===_&&(p=g[1]??[])});this.addDisposer(m)}if(this._mode==="enforce"){let m=new Map,h=g=>{if(m.has(g))return;let y=Nu(e,g);if(!(y instanceof Ae))return;let b=(v,T)=>{let w=this._currentGuard(v,T);return w||this._publishViolation(v,T,g,"blocked"),w};m.set(g,y._pushGuard(b))};for(let g of f)h(g);if(u!=null){let g=u.subscribe(y=>{for(let b of y){if(b[0]!==_)continue;let v=b[1]??[],T=new Set(v),w=new Set(p??[]);Z(()=>{for(let k of w){if(T.has(k))continue;let R=m.get(k);R!=null&&(R(),m.delete(k))}for(let k of T)w.has(k)||h(k);p=v})}});this.addDisposer(g)}if(c){let g=e.topology.subscribe(y=>{for(let b of y){if(b[0]!==_)continue;let v=b[1];if(v.kind!=="removed"||v.nodeKind!=="node")continue;let T=m.get(v.name);T!=null&&(T(),m.delete(v.name))}});this.addDisposer(g)}else{let g=Nn(e,(y,b,v)=>{if(y.kind==="added")if(y.nodeKind==="node")h(`${v}${y.name}`);else{let T=b._mounts.get(y.name);if(!(T instanceof Y))return;let w=`${v}${y.name}::`,k=Dm(T);for(let R of k)h(R===""?`${v}${y.name}`:`${w}${R}`)}else if(y.kind==="removed")if(y.nodeKind==="node"){let T=`${v}${y.name}`,w=m.get(T);w!=null&&(w(),m.delete(T))}else{let T=`${v}${y.name}`,w=`${T}::`;for(let[k,R]of m)(k===T||k.startsWith(w))&&(R(),m.delete(k))}});this.addDisposer(g)}this.addDisposer(()=>{for(let g of m.values())g();m.clear()})}else{let m=e.observe({timeline:!0,structured:!0}),h=m.onEvent(g=>{if(g.type!=="data"&&g.type!=="error")return;let y=g.path??"";if(!y||p!=null&&!p.includes(y))return;let b=g.actor??Nu(e,y)?.lastMutation?.actor;if(b==null)return;let v="write";this._currentGuard(b,v)||this._publishViolation(b,v,y,"observed")});this.addDisposer(()=>{h(),m.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:W(),wall_clock_ns:ie(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function _u(t,e,n={}){let r=new ta(t,e,n);return r.tagFactory("policyGate",He(n)),r}function Mu(t,e={}){let n={format_version:1,timestamp_ns:W(),wall_clock_ns:ie(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=Dv(n);return{...n,fingerprint:r}}function Pm(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Nu(t,e){try{return t.node(e)}catch{return}}function Pv(t,e){try{return t.annotation(e)}catch{return}}function Dm(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Dv(t){return Yt(JSON.stringify(Gv(t)))}function Gv(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([d,u])=>[n(d),n(u)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,d=new Array(a.length);for(let u=0;u<a.length;u++)d[u]=a[u]??0;return{__typed_array:{ctor:s.constructor.name,data:d}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}Re();se();ne();ut();ce();Tt();function Ou(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function Fv(t){return we("guarded",t)}var na=class extends Y{enforcer;violations;lints;scope;scopedDescribe;_target;_actorNode;_mode;_firedLintKinds=new Set;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._mode=n.mode??"enforce";let r=n.policies,o=Ou(r);if(!o&&this._mode==="enforce"&&r.length===0)throw new RangeError('guardedExecution: empty `policies` in `mode: "enforce"` denies every action. Pass at least `{ effect: "allow", action: "*" }` and layer deny rules on top.');this.lints=new Wt("lints",{retainedLimit:n.lintsLimit??64}),this.mount("lints",this.lints);let s=n.actor;s==null?this._actorNode=A(null,{name:"actor"}):Ou(s)?this._actorNode=O([s],([d])=>d??null,{name:"actor",initial:null}):this._actorNode=A(s,{name:"actor"});let i={mode:this._mode,name:"enforcer"};if(n.violationsLimit!=null&&(i.violationsLimit=n.violationsLimit),this.enforcer=_u(e,n.policies,i),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer),o&&this._mode==="enforce"){let d=r,u=d.cache;u!=null&&u.length===0&&this._fireLint("empty-policies",'`policies` Node cached an empty array in `mode: "enforce"` \u2014 every action will be denied. Add at least one allow rule.');let c=d.subscribe(l=>{for(let p of l){if(p[0]!==_)continue;let f=p[1];(f==null||f.length===0)&&this._fireLint("empty-policies",'`policies` Node emitted an empty array in `mode: "enforce"` \u2014 every action will be denied. Add at least one allow rule.')}});this.addDisposer(c)}if(this._mode==="audit"){let d=e.describe({detail:"full"});Object.values(d.nodes).some(c=>c.guard!=null)||this._fireLint("audit-no-effect",'`mode: "audit"` + target has no per-node guards \u2014 `scopedDescribeNode` filters by per-node guards only, so policy rules will not affect describe() visibility. Policies still populate the `violations` topic on writes.')}s==null&&this._fireLint("no-actor","no actor configured \u2014 `wrapper.scopedDescribe` and `scopedDescribeNode()` will return an unscoped describe (full visibility) unless a per-call actor is supplied."),this.scope=O([this._actorNode,this.enforcer.policies],([d,u])=>({actor:d??null,mode:this._mode,policiesCount:u.length}),{name:"scope",describeKind:"derived",meta:Fv("scope")}),this.add(this.scope,{name:"scope"}),this.addDisposer(te(this.scope));let a=e.describe({reactive:!0,actor:this._actorNode,reactiveName:"scopedDescribe"});this.scopedDescribe=a.node,this.add(this.scopedDescribe,{name:"scopedDescribe"}),this.addDisposer(a.dispose)}_fireLint(e,n){this._firedLintKinds.has(e)||(this._firedLintKinds.add(e),this.lints.publish({kind:e,message:n,timestamp_ns:W()}))}scopedDescribeNode(e,n){let r=e==null?this._actorNode:Ou(e)?e:A(e,{name:"actor_override"}),o=this._target.describe({reactive:!0,actor:r,...n??{}});return this.addDisposer(o.dispose),{node:o.node,dispose:o.dispose}}get target(){return this._target}};function $v(t,e){return new na(t,e)}ne();ut();ce();Tt();Tt();function Fm(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=Sn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function $m(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function Au(t){let e=t.describe({reactive:!0,detail:"standard",reactiveName:"graphLens.topology"}),n=e.node,r=O([n],([l])=>Fm(l),{name:"graphLens.health",describeKind:"derived",equals:$m,meta:we("lens","health")}),o=te(r),s=new Map,i=-1,a=t.observe({reactive:!0,tiers:["data"]}),d=O([a,n],([l,p])=>{let f=l,m=p;if(f!=null&&f.flushedAt_ns>i){i=f.flushedAt_ns;for(let h of f.events){if(h.type!=="data")continue;let g=h.path;if(g==null||g==="")continue;let y=s.get(g);s.set(g,{path:g,count:(y?.count??0)+1,lastUpdate_ns:f.flushedAt_ns})}}if(m!=null&&s.size>0){let h=new Set(Object.keys(m.nodes));for(let g of[...s.keys()])h.has(g)||s.delete(g)}return new Map(s)},{name:"graphLens.flow",describeKind:"derived",meta:we("lens","flow")}),u=te(d),c=!1;return{topology:n,health:r,flow:d,dispose(){c||(c=!0,u(),o(),e.dispose())}}}Ze();Fe();var Cu=class extends Y{view;constructor(e){super("lens"),this.view=Au(e),this.add(this.view.topology,{name:"topology"}),this.add(this.view.health,{name:"health"}),this.add(this.view.flow,{name:"flow"})}},ra=class extends Y{target;lens;audit;_defaultActor;_lensSubgraph;constructor(e,n={}){super(n.name??`inspect(${e.name})`),this.target=e,this._defaultActor=n.actor,this._lensSubgraph=new Cu(e),this.lens=this._lensSubgraph.view,this.mount("lens",this._lensSubgraph),this.audit=Eu(e,n.audit??{}),this.mount("audit",this.audit),this.addDisposer(()=>this.lens.dispose())}explainTarget(e,n,r){return this.target.explain(e,n,r)}complianceSnapshot(e){let n=e?.actor??this._defaultActor;return Mu(this.target,{audit:this.audit,...n!=null?{actor:n}:{},...e?.policies!=null?{policies:e.policies}:{}})}};function jv(t,e={}){let n=new ra(t,e);return n.tagFactory("inspect",He(e)),n}var sa={};Ee(sa,{processInstanceKeyOf:()=>Bv,processManager:()=>Kv});Re();se();ce();var Bv=t=>t.correlationId;function jm(t){if(t==null)return Promise.resolve(void 0);let e=Q(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let d of a){if(d[0]===_){o=!0,Promise.resolve().then(i),n(d[1]);return}if(d[0]===L){o=!0,Promise.resolve().then(i),r(d[1]);return}if(d[0]===I){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function Vv(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(d=>setTimeout(d,a))}try{return await jm(t(e,n))}catch(a){s=a}}return{outcome:"failure",error:s}}function Kv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=`${e}_process_instances`,c=`${e}_process_seq`;if(t.tryResolve(u)!==void 0||t.tryResolve(c)!==void 0)throw new Error(`processManager: name "${e}" is already in use on this CQRS graph (collides on "${u}" / "${c}"). Pick a different name or destroy the previous CQRS graph before re-creating the manager.`);let l=at({name:u,retainedLimit:s,graph:t}),p=ht(t,c,0),f=Ce(()=>{},{audit:l,seq:p,freeze:!0,...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},onSuccess:([x,N,E,P],M,{t_ns:C,seq:$})=>({correlationId:x,state:N,status:E,startedAt:d.get(x)??C,updatedAt:C,t_ns:C,seq:$??0,...P!==void 0?{reason:P}:{}})}),m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(x,N,E,P){if(a.delete(x),i.delete(x),d.delete(x),n.compensate)try{await jm(n.compensate(N,E)),f(x,N,"compensated",P)}catch{f(x,N,"errored",void 0)}else f(x,N,"errored",void 0)}async function g(x,N){if(a.has(x)){if(N.outcome==="failure"){let E=i.get(x)??n.initial;await h(x,E,N.error);return}if(N.outcome==="success"){if(i.set(x,N.state),N.emit)for(let E of N.emit)try{t._appendEvent(E.type,E.payload,{correlationId:x,aggregateId:x})}catch{}if(f(x,N.state,"running",void 0),n.isTerminal?.(N.state)){a.delete(x),i.delete(x),d.delete(x),f(x,N.state,"terminated",void 0);return}if(N.schedule){let{afterMs:E,eventType:P}=N.schedule,M,C=st(E),$=V=>{for(let G of V)if(G[0]===_){if(M?M():queueMicrotask(()=>M?.()),!a.has(x))return;let K=i.get(x);if(K===void 0)return;let F=n.steps[P];if(!F)return;let q={type:P,payload:null,timestampNs:ie(),seq:Number.NaN,correlationId:x,aggregateId:x};b(x,F,K,q)}};M=C.subscribe($)}return}if(N.outcome==="terminate"){if(i.set(x,N.state),N.emit)for(let E of N.emit)try{t._appendEvent(E.type,E.payload,{correlationId:x,aggregateId:x})}catch{}a.delete(x),i.delete(x),d.delete(x),f(x,N.state,"terminated",void 0)}}}let y=new Map;function b(x,N,E,P){let C=(y.get(x)??Promise.resolve()).then(async()=>{let $=i.get(x);if($===void 0||!a.has(x))return;let V;try{V=await Vv(N,$,P,r,o)}catch(G){await h(x,i.get(x)??n.initial,G);return}await g(x,V)});y.set(x,C),C.finally(()=>{y.get(x)===C&&y.delete(x)})}let v=!1,T=[];for(let x of n.watching){let N=t.event(x),E=0;E=(N.cache??[]).length;let M=N.subscribe(C=>{for(let $ of C){if($[0]!==_)continue;let V=$[1];if(V.length<=E)continue;let G=V.slice(E);E=V.length;for(let K of G){let F=K.correlationId;if(F===void 0||!a.has(F))continue;let q=n.steps[x];if(!q)continue;let D=i.get(F);D!==void 0&&b(F,q,D,K)}}});T.push(M)}function w(x,N){if(v||a.has(x))return;let E=ie();d.set(x,E),i.set(x,n.initial),a.add(x);try{t._appendEvent(m,N??null,{correlationId:x,aggregateId:x})}catch{}f(x,n.initial,"running",void 0)}function k(x,N){if(v||!a.has(x))return;let E=i.get(x)??n.initial;h(x,E,new Error(`cancelled: ${N??"no reason given"}`),N)}function R(x){return i.get(x)}function S(){if(!v){v=!0;for(let x of T)try{x()}catch{}T.length=0}}return{instances:l,audit:l,start:w,cancel:k,getState:R,dispose:S}}var ia={};Ee(ia,{CanvasMeasureAdapter:()=>Du,CliMeasureAdapter:()=>Lu,ImageSizeAdapter:()=>$u,NodeCanvasMeasureAdapter:()=>Gu,PrecomputedAdapter:()=>Pu,SvgBoundsAdapter:()=>Fu,analyzeAndMeasure:()=>Ut,carveTextLineSlots:()=>gu,circleIntervalForBand:()=>Hm,computeBlockFlow:()=>Km,computeCharPositions:()=>Vi,computeFlowLines:()=>Wm,computeLineBreaks:()=>Hn,computeTotalHeight:()=>qm,layoutNextLine:()=>mu,measureBlock:()=>Bm,measureBlocks:()=>Vm,reactiveBlockLayout:()=>qv,reactiveFlowLayout:()=>zv,reactiveLayout:()=>zb,rectIntervalForBand:()=>zm});bs();var Lu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:lr(e)*this.cellPx}}},Iu=class extends Error{name="KeyError"},Pu=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new Iu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},Du=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},Gu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},Fu=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},$u=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};Re();Me();ne();Fe();function Bm(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=Ut(t.text,a,n.text,r),c=Hn(u,e,n.text,a,r),l=Vi(c,u,d),p=c.lineCount*d,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:u,textLineBreaks:c,textCharPositions:l}}case"image":{let a,d;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,d=t.naturalHeight;else if(n.image){let u=n.image.measureImage(t.src);a=u.width,d=u.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"image",width:a,height:d}}case"svg":{let a,d;if(t.viewBox)a=t.viewBox.width,d=t.viewBox.height;else if(n.svg){let u=n.svg.measureSvg(t.content);a=u.width,d=u.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"svg",width:a,height:d}}}}function Vm(t,e,n,r,o,s){return t.map((i,a)=>Bm(i,e,n,r,o,s,a))}function Km(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function qm(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function qv(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=A(t.blocks??[],{name:"blocks"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"}),u=A(t.gap??0,{name:"gap"}),c=J([a,d],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=W(),v=Vm(g,y,e,i,r,o),T=W()-b,w=c.meta;w&&(Mt(w["block-count"],v.length),Mt(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=O([c,u],([f,m])=>Km(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=O([l],([f])=>qm(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(d,{name:"max-width"}),s.add(u,{name:"gap"}),s.add(c,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}Re();Me();ne();Fe();function Hm(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let d=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-d-r,right:t.cx+d+r}}function zm(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Hv(t,e,n){return t.kind==="circle"?Hm(t,e,n):zm(t,e,n)}function Wm(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,d=[],u={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:d,cursor:u};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:d,cursor:u};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let x=Hv(r[S],v,T);x!==null&&w.push(x)}let k=gu({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let R=!1;for(let S=0;S<k.length;S++){let x=k[S],N=x.right-x.left,E=mu(t,u,N);if(E===null)return{lines:d,cursor:u};if(E.text.length===0&&E.width===0){u=E.end,R=!0;break}d.push({x:x.left,y:v,width:E.width,slotWidth:N,text:E.text,columnIndex:g,flushToRight:x.right<b-.5}),u=E.end}if(R){v+=a;continue}if(v+=o,u.segmentIndex>=t.length)break e}if(u.segmentIndex>=t.length)break}return{lines:d,cursor:u}}function zv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=A(t.text??"",{name:"text"}),a=A(t.font??"16px sans-serif",{name:"font"}),d=A(t.lineHeight??20,{name:"line-height"}),u=A(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=A(t.columns??{count:1,gap:0},{name:"columns"}),l=A(t.obstacles??[],{name:"obstacles"}),p=A(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=J([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Ut(v,w,e,s);g.emit(k);let R=()=>{s.clear(),e.clearCache?.()};return{deactivate:R,invalidate:R}},{name:"segments",describeKind:"derived"}),m=O([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,k=W(),R=T??v,{lines:S,cursor:x}=Wm(w,g,y,b,v,r,{paragraphSpacing:R}),N=W()-k,E=Math.max(0,w.length-x.segmentIndex),P=m.meta;return P&&(Mt(P["line-count"],S.length),Mt(P["layout-time-ns"],N),Mt(P["overflow-segments"],E)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(d,{name:"line-height"}),o.add(u,{name:"container"}),o.add(c,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:f,flowLines:m}}var ga={};Ee(ga,{SNAPSHOT_WIRE_VERSION:()=>Wo,SurfaceError:()=>_e,asSurfaceError:()=>aa,createGraph:()=>Mr,deleteSnapshot:()=>ma,diffSnapshots:()=>pa,listSnapshots:()=>fa,restoreSnapshot:()=>la,runReduction:()=>da,saveSnapshot:()=>ca});var _e=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=Wv(this.details);n!==void 0&&(e.details=n)}return e}};function Wv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function aa(t,e="internal-error"){if(t instanceof _e)return t;let n=t instanceof Error?t.message:String(t);return new _e(e,n)}function Mr(t,e){let n=Sr(t);if(!n.valid)throw new _e("invalid-spec",`GraphSpec validation failed:
225
- ${n.errors.join(`
226
- `)}`,{errors:n.errors});let r=e?.catalog??{},o=jo(t,r);if(!o.valid)throw new _e("catalog-error",`Catalog validation failed:
227
- ${o.errors.join(`
228
- `)}`,{errors:o.errors});try{return Bo(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("catalog-error",i)}}se();var Uv=3e4;async function da(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??Uv,i=Mr(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new _e("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new _e("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((d,u)=>{let c=!1,l=!1,p,f,m=!1,h=g=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,g())};f=a.subscribe(g=>{for(let y of g){if(l)return;if(c){if(y[0]===_){h(()=>d(y[1]));return}if(y[0]===z){let b=a.cache;h(()=>d(b));return}if(y[0]===L){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>u(new _e("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===I){h(()=>u(new _e("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>u(new _e("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(p=setTimeout(()=>{h(()=>u(new _e("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}Re();Fe();var Wo=vt,Ho="snapshot:";function zo(t){if(t.startsWith(Ho))throw new _e("snapshot-failed",`snapshot id must not start with "${Ho}" (reserved); got "${t}"`,{snapshotId:t})}function ua(t){return`${Ho}${t}`}function Jv(t){return t.startsWith(Ho)?t.slice(Ho.length):void 0}function ju(t,e){if(t==null||typeof t!="object")throw new _e("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new _e("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new _e("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new _e("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function ca(t,e,n){zo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:ie(),format_version:Wo,snapshot:r};try{await n.save(ua(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function la(t,e,n){zo(t);let r=ua(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=ju(o,t);try{return Y.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new _e("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function pa(t,e,n){zo(t),zo(e);let r=async d=>{let u=ua(d),c=await n.load(u);return c===void 0&&(c=await n.load(d)),c},[o,s]=await Promise.all([r(t),r(e)]),i=ju(o,t),a=ju(s,e);return Y.diff(i,a)}async function fa(t,e){if(typeof t.list!="function")throw new _e("tier-no-list","KvStorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=Jv(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function ma(t,e){if(zo(t),typeof e.delete!="function")throw new _e("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(ua(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new _e("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Yv="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DEFAULT_AUDIT_GUARD,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,advanceVersion,ai,appendAudit,appendLogStorage,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,budgetGate,buffer,bufferCount,bufferTime,bumpCursor,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createAuditLog,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decay,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,defer,delay,deleteSnapshot,demoShell,derived,deserializeError,dictKv,dictSnapshot,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainMeta,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,factoryTag,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,harness,inspect,interval,isBatching,isV1,jobQueue,jotai,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,lightMutation,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryAppendLog,memoryBackend,memoryKv,memorySnapshot,merge,mergeMap,mergeReactiveLogs,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,placeholderArgs,policy,policyFromRules,process,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,registerBuiltinCodecs,registerBuiltins,registerCursor,registerCursorMap,repeat,replay,replayWAL,rescue,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,snapshotStorage,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,topologyDiff,tryIncrementBounded,validateGraphObservability,validateNoIslands,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,wrapMutation,zip,zustand});
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+
17
+ // src/index.ts
18
+ var index_exports = {};
19
+ module.exports = __toCommonJS(index_exports);
20
+ __reExport(index_exports, require("@graphrefly/pure-ts"), module.exports);
21
+ //# sourceMappingURL=index.cjs.map