@graphrefly/graphrefly 0.36.0 → 0.38.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 (249) hide show
  1. package/dist/{chunk-J6TGRQUP.js → chunk-2YFDSYEF.js} +1 -1
  2. package/dist/{chunk-JUJEPZOI.js → chunk-4BDQXBXE.js} +1 -1
  3. package/dist/chunk-5BGFS2XH.js +1 -0
  4. package/dist/chunk-6773HURD.js +1 -0
  5. package/dist/{chunk-AQC53OWG.js → chunk-6KZZ6XQE.js} +1 -1
  6. package/dist/{chunk-5CPPC75H.js → chunk-6VFC334U.js} +1 -1
  7. package/dist/{chunk-KUVDFOJH.js → chunk-7KZZLWZ6.js} +1 -1
  8. package/dist/{chunk-Q7EUZ6NN.js → chunk-B5S7KTGP.js} +1 -1
  9. package/dist/chunk-CMTN3KPT.js +80 -0
  10. package/dist/chunk-DQJLC6YY.js +1 -0
  11. package/dist/chunk-DSOVKKTI.js +1 -0
  12. package/dist/chunk-FAYEMS5M.js +1 -0
  13. package/dist/chunk-FWGIZP3W.js +1 -0
  14. package/dist/{chunk-5Z3AFBN7.js → chunk-G7JN6LCB.js} +1 -1
  15. package/dist/{chunk-PCD2MU7X.js → chunk-IBGE62GZ.js} +1 -1
  16. package/dist/{chunk-MYFR67PY.js → chunk-K5C67OGE.js} +1 -1
  17. package/dist/chunk-KJEAIIIY.js +43 -0
  18. package/dist/chunk-LV3ACS5J.js +1 -0
  19. package/dist/{chunk-7LYIKMW5.js → chunk-NBGPXQSP.js} +1 -1
  20. package/dist/chunk-NN3QPJ6U.js +1 -0
  21. package/dist/{chunk-T6RPUERH.js → chunk-NSAZ6PR6.js} +1 -1
  22. package/dist/{chunk-KCE6WWJE.js → chunk-NV63VQHI.js} +1 -1
  23. package/dist/{chunk-PYEIPRSZ.js → chunk-O245YLM5.js} +1 -1
  24. package/dist/{chunk-K5ZXJPWU.js → chunk-O2BLVQU4.js} +1 -1
  25. package/dist/chunk-PHXZRR6C.js +1 -0
  26. package/dist/{chunk-I57VSGRB.js → chunk-POCWFIJ7.js} +1 -1
  27. package/dist/{chunk-TQSTS3BY.js → chunk-QEVSIVSF.js} +1 -1
  28. package/dist/chunk-QMC2PLNM.js +7 -0
  29. package/dist/chunk-QOJFR6GS.js +1 -0
  30. package/dist/{chunk-MQZWA3DF.js → chunk-RZ5HKPGI.js} +1 -1
  31. package/dist/{chunk-XINLP35X.js → chunk-SFK7MN7S.js} +1 -1
  32. package/dist/{chunk-YOUAVGHJ.js → chunk-SP5O2MIX.js} +1 -1
  33. package/dist/chunk-TB7JKSVS.js +61 -0
  34. package/dist/{chunk-6G5YD37E.js → chunk-TMVY7OWG.js} +1 -1
  35. package/dist/{chunk-F36TA3ET.js → chunk-UAXFKMAG.js} +1 -1
  36. package/dist/{chunk-AACJX2L7.js → chunk-UVLZX2OU.js} +1 -1
  37. package/dist/chunk-XIMFHEKV.js +1 -0
  38. package/dist/{chunk-LO3LO2TO.js → chunk-XLMYQB6F.js} +1 -1
  39. package/dist/{chunk-44QWWUA3.js → chunk-XLYF4LBH.js} +1 -1
  40. package/dist/compat/index.cjs +9 -9
  41. package/dist/compat/index.d.cts +7 -7
  42. package/dist/compat/index.d.ts +7 -7
  43. package/dist/compat/index.js +1 -1
  44. package/dist/compat/nestjs/index.cjs +9 -9
  45. package/dist/compat/nestjs/index.d.cts +5 -5
  46. package/dist/compat/nestjs/index.d.ts +5 -5
  47. package/dist/compat/nestjs/index.js +1 -1
  48. package/dist/compat/zustand/index.cjs +7 -7
  49. package/dist/compat/zustand/index.d.cts +3 -3
  50. package/dist/compat/zustand/index.d.ts +3 -3
  51. package/dist/compat/zustand/index.js +1 -1
  52. package/dist/{composite-_XckYx2e.d.cts → composite-CgG0MqHm.d.cts} +8 -1
  53. package/dist/{composite-CT_mApQD.d.ts → composite-DTOlDuch.d.ts} +8 -1
  54. package/dist/core/index.cjs +1 -1
  55. package/dist/core/index.d.cts +2 -2
  56. package/dist/core/index.d.ts +2 -2
  57. package/dist/core/index.js +1 -1
  58. package/dist/extra/index.cjs +19 -19
  59. package/dist/extra/index.d.cts +5 -5
  60. package/dist/extra/index.d.ts +5 -5
  61. package/dist/extra/index.js +1 -1
  62. package/dist/extra/node.cjs +2 -2
  63. package/dist/extra/node.d.cts +107 -1
  64. package/dist/extra/node.d.ts +107 -1
  65. package/dist/extra/node.js +2 -2
  66. package/dist/extra/operators.cjs +1 -1
  67. package/dist/extra/operators.js +1 -1
  68. package/dist/extra/reactive.d.cts +1 -1
  69. package/dist/extra/reactive.d.ts +1 -1
  70. package/dist/extra/reactive.js +1 -1
  71. package/dist/extra/sources.cjs +1 -1
  72. package/dist/extra/sources.js +1 -1
  73. package/dist/extra/storage-tiers-browser.d.cts +76 -5
  74. package/dist/extra/storage-tiers-browser.d.ts +76 -5
  75. package/dist/extra/storage-tiers-node.d.cts +137 -13
  76. package/dist/extra/storage-tiers-node.d.ts +137 -13
  77. package/dist/extra/storage-tiers.d.cts +151 -23
  78. package/dist/extra/storage-tiers.d.ts +151 -23
  79. package/dist/graph/index.cjs +7 -7
  80. package/dist/graph/index.d.cts +4 -4
  81. package/dist/graph/index.d.ts +4 -4
  82. package/dist/graph/index.js +1 -1
  83. package/dist/{graph-Cv-8x0ZI.d.ts → graph-BjW1taJl.d.ts} +243 -11
  84. package/dist/{graph-kTltt95s.d.cts → graph-CHsVwf9S.d.cts} +243 -11
  85. package/dist/{index-CZAixNU3.d.ts → index-5dNRlW7J.d.ts} +3 -3
  86. package/dist/{index-DtSVSKnd.d.ts → index-AUqWe_fX.d.ts} +7 -4
  87. package/dist/{index-DLyQC5Ww.d.ts → index-B-ORMr3k.d.ts} +2 -2
  88. package/dist/{index-C4ig7whw.d.cts → index-B2IUcH13.d.cts} +2 -2
  89. package/dist/{index-KeBhbNg3.d.ts → index-BFaALJxR.d.ts} +2 -2
  90. package/dist/{index-CsD0fqnO.d.ts → index-BI1wMfyc.d.ts} +2 -2
  91. package/dist/{index-DxxvGTXp.d.ts → index-BUFCHvOR.d.ts} +2 -2
  92. package/dist/{index-HCp5ua_i.d.cts → index-BWUMIt7J.d.cts} +3 -3
  93. package/dist/{index-DHv2M7s8.d.cts → index-BaSy4L6w.d.cts} +37 -17
  94. package/dist/{index-BhkPzu-Z.d.cts → index-BgzPO43H.d.cts} +2 -2
  95. package/dist/{index-BsZlbHM5.d.cts → index-BhzwpIJc.d.cts} +1 -1
  96. package/dist/{index-BC-xjOrd.d.cts → index-BkQqf1EF.d.cts} +80 -7
  97. package/dist/{index-BBdwz2BW.d.ts → index-BmWuVdER.d.ts} +2 -2
  98. package/dist/{index-CVhBdCMf.d.ts → index-Bn0uZEL4.d.ts} +2 -2
  99. package/dist/{index-33mF4XyU.d.cts → index-BpMZzX9P.d.cts} +2 -2
  100. package/dist/{index-ZhKyR8co.d.cts → index-Bpr0Pwgl.d.cts} +2 -2
  101. package/dist/{index-2URa-V4S.d.cts → index-BqcgiSQg.d.cts} +2 -2
  102. package/dist/{index-DzYTXMBz.d.ts → index-BsZk9T8y.d.ts} +1 -1
  103. package/dist/{index-CvUrRb4m.d.cts → index-BsgxnHN8.d.cts} +2 -2
  104. package/dist/index-Bub6x_D4.d.cts +427 -0
  105. package/dist/{index-BZ1V5GzX.d.ts → index-BwOsJfLJ.d.ts} +2 -2
  106. package/dist/{index-BuMzxRO2.d.ts → index-Byp771zP.d.ts} +1 -1
  107. package/dist/{index-DKp1CIbG.d.cts → index-C-3UXnHT.d.cts} +1 -1
  108. package/dist/{index-GaW6Welt.d.cts → index-C56XZiDe.d.cts} +2 -2
  109. package/dist/{index-k67aNfqC.d.cts → index-CAV-3RpJ.d.cts} +2 -2
  110. package/dist/{index-DmtWMP0X.d.cts → index-CAbHN_rP.d.cts} +1 -1
  111. package/dist/{index-BTJxM-wZ.d.ts → index-CEVzBWeB.d.ts} +2 -2
  112. package/dist/{index-BVNGEX7d.d.cts → index-CM-i58FY.d.cts} +2 -2
  113. package/dist/{index-EfPb77rT.d.cts → index-CQsqqEVz.d.cts} +1 -1
  114. package/dist/{index-Cot94_82.d.ts → index-CijfwEWx.d.ts} +2 -2
  115. package/dist/{index-PluovH45.d.cts → index-Ckil6miL.d.cts} +2 -2
  116. package/dist/{index-XxSeddWP.d.cts → index-CpdnP-0y.d.cts} +1 -1
  117. package/dist/{index-Pu1Wa7en.d.ts → index-CrlHFsiT.d.ts} +37 -17
  118. package/dist/{index-BWH17rK_.d.cts → index-Czk3r0yA.d.cts} +37 -3
  119. package/dist/{index-BlRVj-7Q.d.cts → index-D-B7U42V.d.cts} +2 -2
  120. package/dist/{index-B4s70vYf.d.ts → index-D-HZ7sP4.d.ts} +2 -2
  121. package/dist/{index-Cjrpx2Mg.d.cts → index-D7-RSD93.d.cts} +2 -2
  122. package/dist/{index-kBUQj-rT.d.ts → index-D9vBTuzo.d.ts} +2 -2
  123. package/dist/{index-DzCQt2FJ.d.cts → index-DJNAWzcH.d.cts} +2 -2
  124. package/dist/{index-DSSsxS7B.d.ts → index-DJVQ-t07.d.ts} +2 -2
  125. package/dist/{index-BwYGLgmI.d.ts → index-DKrIuF-r.d.ts} +2 -2
  126. package/dist/{index-DXSLMoma.d.ts → index-DOU1Ee_k.d.ts} +1 -1
  127. package/dist/{index-DlccEIi3.d.ts → index-DTDVDzhA.d.ts} +37 -3
  128. package/dist/{index-B5UR87KG.d.ts → index-DY2f2b9z.d.ts} +4 -2
  129. package/dist/{index-D8IyqHvT.d.cts → index-DeSsvHDD.d.cts} +4 -2
  130. package/dist/index-Di7OdwlO.d.ts +427 -0
  131. package/dist/{index-isdlyeeO.d.ts → index-DqICM_I7.d.ts} +80 -7
  132. package/dist/{index-DFe2Pk2u.d.ts → index-ML6vHKXK.d.ts} +1 -1
  133. package/dist/{index-RJIY7QVW.d.cts → index-UsU9ptzs.d.cts} +7 -4
  134. package/dist/{index-jA_OwwNg.d.ts → index-Vz7KPfgz.d.ts} +1 -1
  135. package/dist/index.cjs +50 -50
  136. package/dist/index.d.cts +32 -32
  137. package/dist/index.d.ts +32 -32
  138. package/dist/index.js +1 -1
  139. package/dist/meta-BYqlATmg.d.ts +98 -0
  140. package/dist/meta-DreaEM_a.d.cts +98 -0
  141. package/dist/patterns/ai/browser.cjs +2 -2
  142. package/dist/patterns/ai/browser.js +1 -1
  143. package/dist/patterns/ai/index.cjs +21 -21
  144. package/dist/patterns/ai/index.d.cts +9 -9
  145. package/dist/patterns/ai/index.d.ts +9 -9
  146. package/dist/patterns/ai/index.js +1 -1
  147. package/dist/patterns/ai/node.js +1 -1
  148. package/dist/patterns/audit/index.cjs +7 -7
  149. package/dist/patterns/audit/index.d.cts +5 -5
  150. package/dist/patterns/audit/index.d.ts +5 -5
  151. package/dist/patterns/audit/index.js +1 -1
  152. package/dist/patterns/cqrs/index.cjs +7 -7
  153. package/dist/patterns/cqrs/index.d.cts +4 -4
  154. package/dist/patterns/cqrs/index.d.ts +4 -4
  155. package/dist/patterns/cqrs/index.js +1 -1
  156. package/dist/patterns/demo-shell/index.cjs +8 -8
  157. package/dist/patterns/demo-shell/index.d.cts +4 -4
  158. package/dist/patterns/demo-shell/index.d.ts +4 -4
  159. package/dist/patterns/demo-shell/index.js +1 -1
  160. package/dist/patterns/domain-templates/index.cjs +7 -7
  161. package/dist/patterns/domain-templates/index.d.cts +3 -3
  162. package/dist/patterns/domain-templates/index.d.ts +3 -3
  163. package/dist/patterns/domain-templates/index.js +1 -1
  164. package/dist/patterns/graphspec/index.cjs +21 -21
  165. package/dist/patterns/graphspec/index.d.cts +3 -3
  166. package/dist/patterns/graphspec/index.d.ts +3 -3
  167. package/dist/patterns/graphspec/index.js +1 -1
  168. package/dist/patterns/guarded-execution/index.cjs +7 -7
  169. package/dist/patterns/guarded-execution/index.d.cts +6 -6
  170. package/dist/patterns/guarded-execution/index.d.ts +6 -6
  171. package/dist/patterns/guarded-execution/index.js +1 -1
  172. package/dist/patterns/harness/index.cjs +12 -12
  173. package/dist/patterns/harness/index.d.cts +8 -8
  174. package/dist/patterns/harness/index.d.ts +8 -8
  175. package/dist/patterns/harness/index.js +1 -1
  176. package/dist/patterns/job-queue/index.cjs +7 -7
  177. package/dist/patterns/job-queue/index.d.cts +4 -4
  178. package/dist/patterns/job-queue/index.d.ts +4 -4
  179. package/dist/patterns/job-queue/index.js +1 -1
  180. package/dist/patterns/lens/index.cjs +7 -7
  181. package/dist/patterns/lens/index.d.cts +4 -4
  182. package/dist/patterns/lens/index.d.ts +4 -4
  183. package/dist/patterns/lens/index.js +1 -1
  184. package/dist/patterns/memory/index.cjs +7 -7
  185. package/dist/patterns/memory/index.d.cts +6 -4
  186. package/dist/patterns/memory/index.d.ts +6 -4
  187. package/dist/patterns/memory/index.js +1 -1
  188. package/dist/patterns/messaging/index.cjs +7 -7
  189. package/dist/patterns/messaging/index.d.cts +4 -4
  190. package/dist/patterns/messaging/index.d.ts +4 -4
  191. package/dist/patterns/messaging/index.js +1 -1
  192. package/dist/patterns/orchestration/index.cjs +7 -7
  193. package/dist/patterns/orchestration/index.d.cts +4 -4
  194. package/dist/patterns/orchestration/index.d.ts +4 -4
  195. package/dist/patterns/orchestration/index.js +1 -1
  196. package/dist/patterns/process/index.cjs +1 -1
  197. package/dist/patterns/process/index.d.cts +5 -5
  198. package/dist/patterns/process/index.d.ts +5 -5
  199. package/dist/patterns/process/index.js +1 -1
  200. package/dist/patterns/reactive-layout/index.cjs +8 -8
  201. package/dist/patterns/reactive-layout/index.d.cts +4 -4
  202. package/dist/patterns/reactive-layout/index.d.ts +4 -4
  203. package/dist/patterns/reactive-layout/index.js +1 -1
  204. package/dist/patterns/reduction/index.cjs +7 -7
  205. package/dist/patterns/reduction/index.d.cts +3 -3
  206. package/dist/patterns/reduction/index.d.ts +3 -3
  207. package/dist/patterns/reduction/index.js +1 -1
  208. package/dist/patterns/refine-loop/index.cjs +8 -8
  209. package/dist/patterns/refine-loop/index.d.cts +5 -5
  210. package/dist/patterns/refine-loop/index.d.ts +5 -5
  211. package/dist/patterns/refine-loop/index.js +1 -1
  212. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  213. package/dist/patterns/resilient-pipeline/index.d.cts +4 -4
  214. package/dist/patterns/resilient-pipeline/index.d.ts +4 -4
  215. package/dist/patterns/resilient-pipeline/index.js +1 -1
  216. package/dist/patterns/surface/index.cjs +14 -14
  217. package/dist/patterns/surface/index.d.cts +4 -4
  218. package/dist/patterns/surface/index.d.ts +4 -4
  219. package/dist/patterns/surface/index.js +1 -1
  220. package/dist/{pipeline-graph-DdBoRu37.d.ts → pipeline-graph-9JBbmRxA.d.ts} +2 -2
  221. package/dist/{pipeline-graph-BlLBWSZ2.d.cts → pipeline-graph-DuHpXSOn.d.cts} +2 -2
  222. package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-BMLDB4Vd.d.cts} +1 -1
  223. package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-D-tRiNhg.d.ts} +1 -1
  224. package/dist/{reactive-log-jirQsxMY.d.ts → reactive-log-BgWSA1fg.d.ts} +28 -1
  225. package/dist/{reactive-log-ScpWyqny.d.cts → reactive-log-C3IMAGpT.d.cts} +28 -1
  226. package/dist/resilience-LGBK236C.js +1 -0
  227. package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-D47-nI6Z.d.ts} +1 -1
  228. package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-jrZue3ao.d.cts} +1 -1
  229. package/package.json +1 -1
  230. package/dist/chunk-3U7IIQB2.js +0 -1
  231. package/dist/chunk-533RQFF6.js +0 -1
  232. package/dist/chunk-5CZ3KIRJ.js +0 -1
  233. package/dist/chunk-5KPIYVCC.js +0 -7
  234. package/dist/chunk-5RTZ6DXG.js +0 -1
  235. package/dist/chunk-A5HZZYRK.js +0 -1
  236. package/dist/chunk-CGA5RXO6.js +0 -1
  237. package/dist/chunk-DBPFMCVH.js +0 -1
  238. package/dist/chunk-GWOKTENT.js +0 -1
  239. package/dist/chunk-JJTF75VS.js +0 -1
  240. package/dist/chunk-KL7CILPL.js +0 -1
  241. package/dist/chunk-M27MVZCP.js +0 -1
  242. package/dist/chunk-N2GCKKKH.js +0 -43
  243. package/dist/chunk-QKUWS7CO.js +0 -80
  244. package/dist/chunk-YBA5N4XY.js +0 -61
  245. package/dist/index-CI_yjtua.d.ts +0 -139
  246. package/dist/index-D9qoEOj_.d.cts +0 -139
  247. package/dist/meta-BGO6C7K9.d.cts +0 -41
  248. package/dist/meta-CC6EPdpK.d.ts +0 -41
  249. package/dist/resilience-OBU472D2.js +0 -1
@@ -1,9 +1,9 @@
1
- "use strict";var wt=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var Yn=Object.getOwnPropertyNames;var Jn=Object.prototype.hasOwnProperty;var re=(t,e)=>()=>(t&&(e=t(t=0)),e);var Xn=(t,e)=>{for(var n in e)wt(t,n,{get:e[n],enumerable:!0})},Zn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yn(e))!Jn.call(t,s)&&s!==n&&wt(t,s,{get:()=>e[s],enumerable:!(r=Kn(e,s))||r.enumerable});return t};var Qn=t=>Zn(wt({},"__esModule",{value:!0}),t);function He(){return Ie>0||ze}function Ut(){return Ie>0}function je(t){Ie>0?Be.push(t):t()}function le(t){Ie+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ie-=1,Ie===0)if(e){if(!ze){let n=Be.splice(0);for(let r of n)try{r()}catch{}ke.length=0,Re.length=0,Le.length=0}}else er()}}function er(){let t=!ze;t&&(ze=!0);let e=[],n=0;try{for(;ke.length>0||Re.length>0||Le.length>0||t&&Be.length>0;){if(t&&Be.length>0){let o=Be.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw ke.length=0,Re.length=0,Le.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(ke.length>0?ke:Re.length>0?Re:Le).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(ze=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ue(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!He()){t(e);return}(u>=5?Le:u===4?Re:ke).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=He();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?ke.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?Re.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Le.push(()=>t(u)):t(u)}}var Ie,ze,ke,Re,Le,Be,Pe=re(()=>{"use strict";Ie=0,ze=!1,ke=[],Re=[],Le=[],Be=[]});function oe(){return Math.trunc(performance.now()*1e6)}function Ze(){return Date.now()*1e6}var Qe=re(()=>{"use strict"});var fe,P,K,Y,se,de,pe,Q,$,I,Se,et,Wt,tt,qt,Kt,nt,_t,xt,Nt,rt,he=re(()=>{"use strict";fe=Symbol.for("graphrefly/START"),P=Symbol.for("graphrefly/DATA"),K=Symbol.for("graphrefly/DIRTY"),Y=Symbol.for("graphrefly/RESOLVED"),se=Symbol.for("graphrefly/INVALIDATE"),de=Symbol.for("graphrefly/PAUSE"),pe=Symbol.for("graphrefly/RESUME"),Q=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Se=Object.freeze([K]),et=Object.freeze([Y]),Wt=Object.freeze([se]),tt=Object.freeze([fe]),qt=Object.freeze([$]),Kt=Object.freeze([Q]),nt=Object.freeze([Se]),_t=Object.freeze([et]),xt=Object.freeze([Wt]),Nt=Object.freeze([qt]),rt=Object.freeze([Kt])});function Jt(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 s=2+n.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=Et,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function Xt(t,e){if(t.length<Yt)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Yt})`);let n=0,r=t[n++];if(r!==Et)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Et})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Zt(t){t.registerCodec(tr)}var tr,Et,Yt,Ot=re(()=>{"use strict";tr={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)}},Et=1,Yt=4});function ot(t){if(t==null)return $e;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var $e,st=re(()=>{"use strict";$e={type:"system",id:""}});function Qt(t){t.registerMessageType(fe,{tier:0,wireCrossing:!1}),t.registerMessageType(K,{tier:1,wireCrossing:!1}),t.registerMessageType(se,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(de,{tier:2,wireCrossing:!1}),t.registerMessageType(pe,{tier:2,wireCrossing:!1}),t.registerMessageType(P,{tier:3,wireCrossing:!0}),t.registerMessageType(Y,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(Q,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var it,en=re(()=>{"use strict";he();it=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 kt(t){let e=nr.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 ie,nr,We=re(()=>{"use strict";ie=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}},nr=["human","llm","wallet","system"]});function Rt(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(Rt);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Rt(t[n]);return e}return null}function sr(t){let e=or.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,l=2773480762,f=1359893119,h=2600822924,p=528734635,c=1541459225,g=new Uint32Array(64),v=(x,b)=>x>>>b|x<<32-b;for(let x=0;x<s;x+=64){for(let E=0;E<16;E++)g[E]=i.getUint32(x+E*4,!1);for(let E=16;E<64;E++){let k=g[E-15],S=g[E-2],C=v(k,7)^v(k,18)^k>>>3,U=v(S,17)^v(S,19)^S>>>10;g[E]=g[E-16]+C+g[E-7]+U>>>0}let b=a,T=d,O=u,N=l,m=f,y=h,_=p,R=c;for(let E=0;E<64;E++){let k=v(m,6)^v(m,11)^v(m,25),S=m&y^~m&_,C=R+k+S+rr[E]+g[E]>>>0,U=v(b,2)^v(b,13)^v(b,22),B=b&T^b&O^T&O,ue=U+B>>>0;R=_,_=y,y=m,m=N+C>>>0,N=O,O=T,T=b,b=C+ue>>>0}a=a+b>>>0,d=d+T>>>0,u=u+O>>>0,l=l+N>>>0,f=f+m>>>0,h=h+y>>>0,p=p+_>>>0,c=c+R>>>0}let w=x=>x.toString(16).padStart(8,"0");return w(a)+w(d)+w(u)+w(l)+w(f)+w(h)+w(p)+w(c)}function St(t){let e=Rt(t??null),n=JSON.stringify(e);return sr(n).slice(0,16)}function ir(){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 Dt(t,e,n){let r=n?.id??ir();if(t===0)return{id:r,version:0};let o=(n?.hash??St)(e);return{id:r,version:0,cid:o,prev:null}}function tn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var rr,or,nn=re(()=>{"use strict";rr=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]),or=new TextEncoder});function sn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function At(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function at(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function te(t,e,n){let r=an(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return an(t)?o=(Ct(e)?e:n)??{}:Ct(t)?o=t:o=(Ct(e)?e:n)??{},new H(r,s,o)}var rn,on,ar,ur,Fe,H,an,Ct,me=re(()=>{"use strict";Ot();st();Pe();Qe();en();We();he();nn();rn=()=>{},on=100;ar=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},ur=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[tt]:[tt,[P,o]];s._status==="dirty"&&i.push(Se),Ue(e,i,s._config.tierOf)},Fe=new it({onMessage:ar,onSubscribe:ur});Qt(Fe);Zt(Fe);H=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??Fe,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??St;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Dt(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(sn);let o={};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),o[a]=new t([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[P,a]])},down(a){i._emit(at(a))},up(a){i._emitUp(at(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 s=n?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Dt(e,o,{id:a,hash:s});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=ot(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 s=ot(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new ie({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new ie({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:Ze()}}down(e,n){let r=at(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[P,e]])}up(e,n){if(this._deps.length===0)return;let r=at(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_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 s=n(r[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} 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=ot(n);if(!this._guard(d,"observe"))throw new ie({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){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)At(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 o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},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 o=="function")try{o()}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 o=="function"&&o(),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 s=r,o=this._deps[r];o.unsub=rn,o.unsub=o.node.subscribe(i=>{if(o.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:s},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}At(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=sn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(nt),r.unsub=rn;try{r.unsub=e.subscribe(s=>{if(r.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[I,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[I,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}At(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],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==fe){if(s===K){this._depDirtied(r);return}if(s===se){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(xt);return}if(s===de||s===pe){this._emit([n]);return}if(s===Q){this._emit(rt);return}if(s===P)this._depSettledAsData(r,n[1]);else if(s===Y)this._depSettledAsResolved(r);else if(s===$)this._depSettledAsTerminal(r,!0);else if(s===I)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===P||s===Y)&&this._emit([n]),(s===$||s===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(nt))}_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(_t),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([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Nt)}_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([[I,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([[I,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 s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,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,o);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([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>on?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${on} \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"?[Se,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===K&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,l)=>({m:u,i:l,tier:n(u[0])}));d.sort((u,l)=>u.tier-l.tier||u.i-l.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Se,...a]:[...a.slice(0,d),Se,...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]===I&&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]===Q||d[0]===se);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==de&&u!==pe){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===de?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let l=!0;if(this._pausable!==!1){let f=d[1];if(u===de)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(f),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(f))l=!1;else if(this._pauseLocks.delete(f),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let h=this._pauseBuffer;this._pauseBuffer=[],this._emit(h)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}l?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===Q))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(rt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[I,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let l of e)n(l[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let l=e.length-1;l>=0;l--)if(e[l][0]===P){d=l;break}}for(let l=0;l<e.length;l++){let f=e[l],h=f[0];if(h===P){if(f.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,f[1])}catch(c){s=this._wrapFnError("equals threw",c),o=l;break}if(p){r==null&&(r=e.slice(0,l)),r.push(et),this._status="resolved";continue}this._cached=f[1],this._versioning!=null&&(d<0||l===d)&&tn(this._versioning,f[1],this._hashFn)}this._status="settled",r?.push(f)}else if(r?.push(f),h===K)this._status="dirty";else if(h===Y)this._status="resolved";else if(h===$){this._status="completed";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(h===I){this._status="errored";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(h===se){if(this._cached!==void 0){let c=this._config.rigorRecorder;if(c!=null)try{c.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let c=p.invalidate;if(typeof c=="function")try{c()}catch{}}}else h===Q&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??e;return s!=null?{finalMessages:u,equalsError:s}:{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(Ut()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],je(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ue(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);Ue(this._deliverToSinks,n,this._config.tierOf)}},an=t=>Array.isArray(t),Ct=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function z(t,e){return te([],{...e,initial:t})}function De(t,e){return te((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function F(t,e,n){return te(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...n})}function _e(t,e,n){return te(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...n})}var Ve=re(()=>{"use strict";me()});function Mt(t){return{describeKind:"producer",...t}}function un(t,e){return De(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[$]])}catch(s){r||n.down([[I,s]])}return()=>{r=!0}},Mt(e))}function dr(t){return t!=null&&typeof t.then=="function"}function lr(t,e){let{signal:n,...r}=e??{};return De(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[I,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[$]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[I,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},Mt(r))}function cr(t,e){let{signal:n,...r}=e??{};return De(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),l=()=>{d||a.aborted||Promise.resolve(u.next()).then(f=>{if(!(d||a.aborted)){if(f.done){s.down([[$]]);return}s.emit(f.value),l()}},f=>{!d&&!a.aborted&&s.down([[I,f]])})};return l(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},Mt(r))}function fr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function dn(t,e){if(fr(t))return t;if(dr(t))return lr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return cr(t,e);if(typeof n[Symbol.iterator]=="function")return un(t,e)}return pr(t)}function pr(...t){return un(t,void 0)}function ge(t){return t.subscribe(()=>{})}var ut=re(()=>{"use strict";he();Ve()});var lt,cn=re(()=>{"use strict";lt=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 vo={};Xn(vo,{blindVariation:()=>mo,errorCritique:()=>yo,refineLoop:()=>ho});module.exports=Qn(vo);Pe();Qe();he();me();Ve();he();me();ut();function hr(t){return{describeKind:"derived",...t}}function mr(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==fe&&(u[0]===P?e.emit(u[1]):u[0]===$?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===K||u[0]===Y)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function ln(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return te([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[$]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=mr(dn(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{...hr(n),completeWhenDepsComplete:!1})}st();Pe();Qe();We();he();We();me();function dt(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;default:return new Set(["type","deps"])}}function gr(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function br(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Gt(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof H&&(o=gr(t),i=t._deps.map(u=>u.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof H?t._guard:void 0;if(s){let u={...br(t)};if(d!=null&&u.access===void 0&&(u.access=kt(d)),r!=null&&r.length>0&&!e.has("meta")){let l={};for(let f of r)f in u&&(l[f]=u[f]);a.meta=l}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=kt(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}me();Ve();ut();cn();var qe=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}};Ot();function It(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 ct(t){let e=0;for(let n of t)e+=It(n.codePointAt(0));return e}function fn(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=It(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=It(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var yr={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"},vr={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function gn(t,e){let n=e.charset==="ascii"?vr:yr,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)wr(o,i,n,a);for(let a of t.boxes)Tr(o,i,n,a,e.labelOf(a.id));return o.map(a=>Er(a.join(""))).join(`
2
- `)}function Tr(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&pn(t,e,o,i,a,s);return}xe(t,e,o,i,n.boxTL);for(let l=o+1;l<o+a-1;l+=1)xe(t,e,l,i,n.boxH);xe(t,e,o+a-1,i,n.boxTR);for(let l=i+1;l<i+d-1;l+=1){xe(t,e,o,l,n.boxV);for(let f=o+1;f<o+a-1;f+=1)bn(t,e,f,l," ","empty");xe(t,e,o+a-1,l,n.boxV)}xe(t,e,o,i+d-1,n.boxBL);for(let l=o+1;l<o+a-1;l+=1)xe(t,e,l,i+d-1,n.boxH);xe(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);pn(t,e,o+1,u,a-2,s)}function xe(t,e,n,r,s){bn(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function bn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function pn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=ct(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 wr(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)_r(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],l=s[d],f=s[d+1],h=xr(u,l,f,n);h&&mn(t,e,l.x,l.y,h,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Nr(i,o,n);a&&mn(t,e,o.x,o.y,a,"arrow")}function _r(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)hn(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)hn(t,e,o,d,n,"v")}}}function hn(t,e,n,r,s,o){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]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function mn(t,e,n,r,s,o){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]=s,e[r][n]=o)}function xr(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){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 Nr(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 Er(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Tn(t){let e=Or(t);kr(e),Rr(e),Sr(e),Dr(e,t);let n=Mr(e,t),{width:r,height:s}=Ir(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function Or(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function kr(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function Rr(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(f=>f!==o),a.in=a.in.filter(f=>f!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(f=>f!==o),a.in=a.in.filter(f=>f!==o);let u=i;for(let f=1;f<d;f+=1){let h=`__virt_${s++}__`,p={id:h,isVirtual:!0,layer:i.layer+f,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(h,p),n[p.layer].push(p);let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:h,hopIndex:f-1,chainLen:d};u.out.push(c),p.in.push(c),r.push(c),u=p}let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(l),a.in.push(l),r.push(l)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function Sr(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)yn(t,t.layers[r],"in"),ft(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)yn(t,t.layers[r],"out"),ft(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=vn(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],ft(o),vn(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],ft(o))}}if(!r)break}}function yn(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function ft(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function vn(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,l=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>l||e.order>n.order&&u<l)&&(i+=1)}return i}function Dr(t,e){e.direction==="LR"?Ar(t,e):Cr(t,e)}function Ar(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}wn(t,e,"y")}function Cr(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}wn(t,e,"x")}function wn(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let l of a){let f=o===0?l.in:l.out;if(f.length===0)continue;let h=[];for(let c of f){let g=t.nodes.get(o===0?c.fromId:c.toId);if(!g)continue;let v=n==="y"?g.y:g.x;h.push(v+Math.floor(r(g)/2))}if(h.length===0)continue;h.sort((c,g)=>c-g);let p=h[Math.floor(h.length/2)];d.set(l.id,p-Math.floor(r(l)/2))}let u=0;for(let l of a){let f=d.get(l.id),h=n==="y"?l.y:l.x,c=Math.max(f??h,u);n==="y"?l.y=c:l.x=c,u=c+r(l)+s}}}}function Mr(t,e){let n=new Map;for(let u of t.hops){let l=n.get(u.chainId);l?l.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((l,f)=>l.hopIndex-f.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=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 l=t.layers[u],f=t.layers[u+1],h=0;for(let y of l)h=Math.max(h,s(y)+o(y));let p=Number.POSITIVE_INFINITY;for(let y of f)p=Math.min(p,s(y));let c=Number.isFinite(p)?p-1:h,g=Math.max(1,c-h+1),v=[];for(let y of l)for(let _ of y.out)v.push(_);v.sort((y,_)=>{let R=i(t.nodes.get(y.fromId)),E=i(t.nodes.get(_.fromId));if(R!==E)return R-E;let k=i(t.nodes.get(y.toId)),S=i(t.nodes.get(_.toId));return k-S});let w=[],x=new Map;for(let y of v){let _=i(t.nodes.get(y.fromId)),R=i(t.nodes.get(y.toId)),E=Math.min(_,R),k=Math.max(_,R),S=-1;for(let C=0;C<w.length;C+=1){let U=w[C],B=!0;for(let ue of U)if(ue.lo<=k&&E<=ue.hi){B=!1;break}if(B){U.push({lo:E,hi:k}),S=C;break}}S<0&&(w.push([{lo:E,hi:k}]),S=w.length-1),x.set(y,S)}let b=w.length,T=g>=Math.max(3,b+2),O=T?h+1:h,N=T?c-1:c,m=Math.max(1,N-O+1);for(let y of v){let _=x.get(y),R;if(b<=1)R=O+Math.floor(m/2);else{let E=(m-1)/(b-1);R=O+Math.floor(_*E)}a.set(y,Math.max(h,Math.min(c,R)))}}let d=[];for(let[,u]of n){let l=[];for(let h=0;h<u.length;h+=1){let p=u[h],c=t.nodes.get(p.fromId),g=t.nodes.get(p.toId),v=a.get(p),w=c.isVirtual?s(c):s(c)+o(c),x=g.isVirtual?s(g):s(g)-1,b=i(c),T=i(g);h===0&&pt(l,r,w,b),b!==T&&(pt(l,r,v,b),pt(l,r,v,T)),pt(l,r,x,T)}let f=u[0];d.push({from:f.chainFrom,to:f.chainTo,points:Gr(l)})}return d}function pt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Gr(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 Ir(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var Lr=24,Pr=4,$r=1,Fr=3;function _n(t,e){let n=Vr(e.direction),r=Math.max(3,e.maxLabelWidth??Lr),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),d=new Map,u=new Map;for(let p of o){let c=fn(p,r);d.set(p,c),u.set(p,ct(c)+4)}let l=Tn({nodes:o,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>Fr,layerGap:Pr,nodeGap:$r,direction:n}),f=gn(l,{charset:s,labelOf:p=>d.get(p)??p}),h=e.logger;return h&&h(f),f}function Vr(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)}`)}function xn(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return ht(e,n,"no-such-from");if(!o)return ht(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=zr(t,e,r);if(u!=null)return u}let d=mt(e,t.nodes[e],0,r);return gt(e,n,[d])}if(i===0)return ht(e,n,"no-path");let a=Nn(t,e,n,i);return a.found?gt(e,n,En(t,a.pathOrder,r)):ht(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Nn(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let f=o[a++];if(f.path===e)break;if(r!=null&&f.depth>=r){let g=t.nodes[f.path];g?.deps&&g.deps.length>0&&(d=!0);continue}let h=t.nodes[f.path];if(h==null)continue;let p=h.deps??[],c=new Map;for(let g=0;g<p.length;g++){let v=p[g];if(!v)continue;let w=c.get(v);w==null&&(w=[],c.set(v,w)),w.push(g)}for(let[g,v]of c)i.has(g)||(i.add(g),s.set(g,{from:f.path,depIndices:v}),o.push({path:g,depth:f.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],l=e;for(;l!==n;){let f=s.get(l);if(f==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=f.depIndices,u.push({path:f.from}),l=f.from}return{found:!0,pathOrder:u,truncated:!1}}function zr(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=mt(e,r,0,n);a.dep_index=o[0];let d=mt(e,r,1,n);return gt(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=Nn(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:gt(e,e,En(t,i.pathOrder,n))}function En(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=mt(r.path,o,s,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 mt(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function gt(t,e,n){return On(t,e,!0,"ok",n)}function ht(t,e,n){return On(t,e,!1,n,[])}function On(t,e,n,r,s){let o=Br(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function Br(t,e,n,r,s){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 o=[`Causal path: ${t} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Hr(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
3
- `)}function Hr(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)}}me();var j={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},jr=Symbol.for("sizeof");function kn(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=Ur(o,e,n,r)}return s}function Ur(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return j.number;case"boolean":return j.boolean;case"string":return j.string+t.length*2;case"bigint":return j.bigint+Wr(t);case"symbol":return j.symbol;case"function":return e.has(t)?0:(e.add(t),j.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[jr];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return j.date;if(o instanceof RegExp)return j.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,l=o.stack?o.stack.length*2:0;return j.error+u+l}if(typeof URL<"u"&&o instanceof URL)return j.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return j.promise;if(o instanceof WeakMap)return j.weakmap;if(o instanceof WeakSet)return j.weakset;if(o instanceof Map){let u=j.map;for(let[l,f]of o)u+=j.mapEntry,r.push(l),r.push(f);return u}if(o instanceof Set){let u=j.set;for(let l of o)u+=j.setEntry,r.push(l);return u}if(Array.isArray(o)){let u=j.array+o.length*8;for(let l of o)r.push(l);return u}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=j.object,d=Object.keys(o);for(let u of d){a+=j.string+u.length*2;try{r.push(o[u])}catch{}}return a}function Wr(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function Rn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[h,p]of s)i.set(h,p);let a=[];for(let[h,p]of Object.entries(r.nodes)){let c=i.get(h),g=c instanceof H?c:null,v=g?kn(g.cache):0,w=g?g._sinkCount:0,x=p.deps?.length??0,b=p.type==="effect"&&w===0,T=w===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:h,type:p.type,status:p.status??"unknown",valueSizeBytes:v,subscriberCount:w,depCount:x,isOrphanEffect:b,orphanKind:T})}let d=a.reduce((h,p)=>h+p.valueSizeBytes,0),u=(h,p)=>[...a].sort(p??((c,g)=>g[h]-c[h])).slice(0,n),l=a.filter(h=>h.orphanKind!=null),f=a.filter(h=>h.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:l,orphanEffects:f}}var V="::",ae="__meta__",Ae=1;function Sn(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 s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function qr(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(`
4
- `)}function Dn(t){if(t.version!==Ae)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${Ae})`);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 Kr(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let h=o;if(s.length!==h.length)return!1;for(let p=0;p<s.length;p++)if(!r(s[p],h[p]))return!1;return!0}if(s instanceof Map){let h=o;if(s.size!==h.size)return!1;for(let[p,c]of s)if(!h.has(p)||!r(c,h.get(p)))return!1;return!0}if(s instanceof Set){let h=o;if(s.size!==h.size)return!1;for(let p of s){let c=!1;for(let g of h)if(r(p,g)){c=!0;break}if(!c)return!1}return!0}if(ArrayBuffer.isView(s)){let h=s,p=o;if(h.length!==p.length)return!1;for(let c=0;c<h.length;c++)if(h[c]!==p[c])return!1;return!0}let u=Object.keys(s),l=Object.keys(o);if(u.length!==l.length)return!1;let f=new Set(l);for(let h of u)if(!f.has(h)||!r(s[h],o[h]))return!1;return!0};return r(t,e)}function Pt(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Pt);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=Pt(e[s]);return r}function Yr(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Jr(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Xr(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Cn(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function Mn(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 Zr(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Pt(i),null,e.indent??2);return e.logger?.(a),a}function Qr(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${yt(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
5
- `);return e.logger?.(o),o}function Gn(t,e){let n=Mn(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${Yr(i)}"]`)}for(let[i,a]of Cn(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
6
- `)}function eo(t,e){let n=Gn(t,e);return In(n)}function In(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),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 to(t,e){let n=Mn(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${Xr(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${Jr(i)}"`)}for(let[i,a]of Cn(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
7
- `)}function no(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(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 s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=no(r)}return e+="$",new RegExp(e)}var ro={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"},oo={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function yt(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 so(t){return t==="none"?oo:t==="ansi"||t==null?ro:{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 An(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 io(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function Lt(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(V))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${V}' (path separator)`);if(t===ae)throw new Error(`Graph "${e}": ${n} name "${ae}" is reserved for meta companion paths`);io(t,e,n)}function ao(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(V);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function uo(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function Ln(t){for(let e of t._mounts.values())Ln(e);for(let e of t._nodes.values())try{e.down([[Q]],{internal:!0})}catch{}}var ce=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;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(V))throw new Error(`Graph name must not contain '${V}' (got "${e}")`);if(e===ae)throw new Error(`Graph name "${ae}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Fe,this._traceRing=new qe(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}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=De(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,s=n?.name??r;if(s==null||s==="")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 o=s,i=n?.annotation;if(Lt(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" 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(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:oe()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof H&&n._applyVersioning(e)}remove(e){Lt(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${V}${ae}${V}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${V}`)),this._mounts.delete(e),n._parent=void 0,Ln(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}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([[Q]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=bt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);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 s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(V))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 s=r?.internal===!0;this.node(e).down([[P,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);le(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[se]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[$]],{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 H)for(let l of u._deps){let f=r.get(l.node);f!=null&&a.push([f,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 s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof H)for(let u of d._deps){let l=o.get(u.node);l!=null&&i.push([l,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 s=new t(e);return this.mount(e,s)}if(typeof n=="function"){let s=new t(e);return n(s),this.mount(e,s)}let r=n;if(Lt(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 s=this;s!=null;s=s._parent)if(s===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=ao(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],s=n.slice(1);if(s.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 o=this._nodes.get(r);if(o&&s.length>0&&s[0]===ae)return this._resolveMetaChainFromNode(o,s,n.join(V));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(V)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(V))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==ae)throw new Error(`Graph "${this.name}": expected ${ae} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ae} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.internal!==!0){for(let s of e)if(this.config.messageTier(s[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,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=uo(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(l){if(l instanceof ie)throw l;s.push(l)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){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,s)}catch(d){if(d instanceof ie)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,s=dt(e?.detail,e?.fields),o=e?.format==="spec",i=o?dt("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[N,m]of a)d.set(m,N);let u=[];{let N=a.map(([,_])=>_),m=new Set(d.values()),y=0;for(;N.length>0;){let _=N.shift();if(_ instanceof H)for(let R of _._deps){let E=R.node;if(d.has(E))continue;let k=E.name??"",S=k;if(!S||m.has(S))if(k){let C=2;for(;m.has(`${k}#${C}`);)C++;S=`${k}#${C}`}else for(S=`__internal__/${y++}`;m.has(S);)S=`__internal__/${y++}`;d.set(E,S),m.add(S),u.push([S,E]),N.push(E)}}}let l=[...a,...u],f={};for(let[N,m]of l){if(n!=null&&!m.allowsObserve(n))continue;let y=Gt(m,i),_=m instanceof H?m._deps.map(S=>d.get(S.node)??S.node.name??""):[],{name:R,...E}=y,k={...E,deps:_};if(!o){let S=this._annotations.get(N);S!=null&&(k.annotation=S)}if(r!=null)if(typeof r=="function"){let S=r;if(!(S.length>=2?S(N,k):S(k)))continue}else{let S=!0;for(let[C,U]of Object.entries(r)){let B=C==="deps_includes"?"depsIncludes":C==="meta_has"?"metaHas":C;if(B==="depsIncludes"){if(!k.deps.includes(String(U))){S=!1;break}continue}if(B==="metaHas"){if(!Object.hasOwn(k.meta??{},String(U))){S=!1;break}continue}if(k[B]!==U){S=!1;break}}if(!S)continue}f[N]=k}let h=new Set(Object.keys(f)),p=[];for(let[N,m]of l)if(m instanceof H)for(let y of m._deps){let _=d.get(y.node);_!=null&&p.push([_,N])}p.sort((N,m)=>N[0]<m[0]?-1:N[0]>m[0]?1:N[1]<m[1]?-1:N[1]>m[1]?1:0);let c=p.map(([N,m])=>({from:N,to:m}));(n!=null||r!=null)&&(c=c.filter(N=>h.has(N.from)&&h.has(N.to)));let g=this._collectSubgraphs(""),v=n!=null||r!=null?g.filter(N=>{let m=`${N}${V}`;return[...h].some(y=>y===N||y.startsWith(m))}):g,w=this,x=e,b={name:this.name,nodes:f,edges:c,subgraphs:v,expand(N){let m={...x,format:void 0};return Array.isArray(N)?(m.fields=N,m.detail=void 0):(m.detail=N,m.fields=void 0),w.describe(m)}},T=e??{},O=T.format;return O==="json"?Zr(b,T):O==="pretty"?Qr(b,T):O==="mermaid"?Gn(b,T):O==="mermaid-url"?eo(b,T):O==="d2"?to(b,T):O==="ascii"?_n(b,T):b}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${V}`))}return n}resourceProfile(e){return Rn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?$t(this.describe(),e,n,{...r,withDetail:!0}):$t(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return xn(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=z(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,je(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},l=i.onEvent(v=>{let w=v.type;w!=="data"&&w!=="error"&&w!=="complete"&&w!=="teardown"||u()}),f=[],h=new WeakSet,p=v=>{if(h.has(v)||d)return;h.add(v);let w=v.topology.subscribe(x=>{for(let b of x){if(b[0]!==P)continue;let T=b[1];if(u(),T.kind==="added"&&T.nodeKind==="mount"){let O=v._mounts.get(T.name);O!=null&&p(O)}}});f.push(w);for(let x of v._mounts.keys()){let b=v._mounts.get(x);b!=null&&p(b)}};p(this);let c;try{c=F([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,w)=>v===w})}catch(v){l();for(let w of f)w();throw i.dispose(),v}let g=ge(c);return{node:c,dispose(){d=!0,l();for(let v of f)v();f.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let s=0,o=z(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(p=>{let c=p.type;c!=="data"&&c!=="error"&&c!=="complete"&&c!=="teardown"||a||d||(a=!0,je(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),l={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},f;try{f=F([o],()=>this._explainStatic(e,n,l),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,c)=>p.found===c.found&&p.reason===c.reason&&p.steps.length===c.steps.length&&lo(p.steps,c.steps)})}catch(p){throw u(),i.dispose(),p}let h=ge(f);return{node:f,dispose(){d=!0,u(),i.dispose(),h()}}}_pathsMatching(e){let n=bt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${V}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${V}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${V}${ae}${V}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=An(r?n:e),i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let l=e,f=this.resolve(l);if(a!=null&&!f.allowsObserve(a))throw new ie({actor:a,action:"observe",nodeName:l});return i?this._buildStructuredObserver([[l,f]],o,"one"):{subscribe(h){return f.subscribe(h)},up(h){try{f.up?.(h)}catch(p){if(p instanceof ie)return;throw p}}}}let d=[];this._collectObserveTargets("",d),d.sort((l,f)=>l[0]<f[0]?-1:l[0]>f[0]?1:0);let u=a==null?d:d.filter(([,l])=>l.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:l=>{let f=u.map(([h,p])=>p.subscribe(c=>{l(h,c)}));return()=>{for(let h of f)h()}},up:(l,f)=>{try{this.resolve(l).up?.(f)}catch(h){if(h instanceof ie)return;throw h}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let l=this.resolve(s);return this._buildStructuredObserver([[s,l]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((l,f)=>l[0]<f[0]?-1:l[0]>f[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,l])=>l.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,l=n.maxEvents,f=l!=null&&l>0?new qe(l):null,h=[],p=new Set,c={},g=new Set,v=0,w=0,x=0,b=0,T=0,O=0,N=!1,m=!1,y=0,_=new Map,R=new Map,E=new Map,k=D=>{f?f.push(D):h.push(D);for(let L of p)L(D)},S=()=>s?{timestamp_ns:oe(),in_batch:He(),batch_id:y}:{},C=(D,L)=>{if(!(!u||!(D instanceof H)))return D._setInspectorHook(J=>{if(J.kind==="dep_message")_.set(D,J.depIndex);else if(J.kind==="run"){let ye=J.batchData.map((G,Z)=>G!=null&&G.length>0?G.at(-1):J.prevData[Z]);R.set(D,ye);let X=J.batchData.map(G=>G!=null?[...G]:void 0);E.set(D,X),i&&k({type:"derived",path:L,dep_values:ye,dep_batches:X,...S()})}})},U=D=>{let L=_.get(D),J=R.get(D);if(!o||J==null)return{};let X=(L!=null&&L>=0&&D instanceof H?D._deps[L]:void 0)?.node,G=X?.v,Z=E.get(D);return{trigger_dep_index:L,trigger_dep_name:X?.name,...G!=null?{trigger_version:{id:G.id,version:G.version}}:{},dep_values:[...J],...Z!=null?{dep_batches:Z}:{}}},B=[],ue=[];for(let[D,L]of e){let J=C(L,D);J&&B.push(J),ue.push(L.subscribe(ye=>{y++;for(let X of ye){let G=X[0],Z=S();if(G===P){c[D]=X[1];let A=L instanceof H?L.lastMutation?.actor??$e:$e;k({type:"data",path:D,data:X[1],actor:A,...Z,...U(L)})}else if(a)G===K?v++:G===Y?w++:G===se?x++:G===de?b++:G===pe?T++:G===Q?O++:G===$&&!g.has(D)?N=!0:G===I&&(m=!0,g.add(D));else if(G===K)v++,k({type:"dirty",path:D,...Z});else if(G===Y)w++,k({type:"resolved",path:D,...Z,...U(L)});else if(G===se)x++,k({type:"invalidate",path:D,...Z});else if(G===de)b++,k({type:"pause",path:D,lockId:X[1],...Z});else if(G===pe)T++,k({type:"resume",path:D,lockId:X[1],...Z});else if(G===$)g.has(D)||(N=!0),k({type:"complete",path:D,...Z});else if(G===I){m=!0,g.add(D);let A=L instanceof H?L.lastMutation?.actor??$e:$e;k({type:"error",path:D,data:X[1],actor:A,...Z})}else G===Q&&(O++,k({type:"teardown",path:D,...Z}))}}))}let Ne=!1,Ce=()=>{if(!Ne){Ne=!0;for(let D of ue)D();for(let D of B)D();for(let D of be)D({value:void 0,done:!0});be.length=0}},Ee=[],be=[];p.add(D=>{let L=be.shift();L?L({value:D,done:!1}):Ee.push(D)});let Me={get values(){return c},get dirtyCount(){return v},get resolvedCount(){return w},get invalidateCount(){return x},get pauseCount(){return b},get resumeCount(){return T},get teardownCount(){return O},get events(){return f?f.toArray():[...h]},get anyCompletedCleanly(){return N},get anyErrored(){return m},get completedWithoutErrors(){return N&&!m},onEvent(D){return p.add(D),()=>p.delete(D)},dispose:Ce,expand(D){Ce();let L={...n};return typeof D=="string"?L.detail=D:Object.assign(L,D),r(An(L))},[Symbol.asyncIterator](){return{next(){return Ee.length>0?Promise.resolve({value:Ee.shift(),done:!1}):Ne?Promise.resolve({value:void 0,done:!0}):new Promise(D=>be.push(D))},return(){return Ce(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(Me,n),Me}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(c=>console.log(c)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:c=>(o==null||o.has(c))&&(i==null||!i.has(c)),d=so(n.theme),u=r==="stage-log"?oe():0,l=c=>c==null?"":n.stageLabels?.[c]??c,f=(c,g)=>c.length>g?`${c.slice(0,g-1)}\u2026`:c,h=c=>c.type==="data"||c.type==="error"?f(yt(c.data),120):"",p=c=>{if(r==="stage-log"){let m=(oe()-u)/1e9,y=l(c.path).padEnd(9);if(c.type==="data"){let _=h(c);return`[${m.toFixed(3)}s] ${y} \u2190${_?` ${_}`:""}`}if(c.type==="error"){let _=h(c);return`[${m.toFixed(3)}s] ${y} \u2717${_?` ${_}`:""}`}return c.type==="complete"?`[${m.toFixed(3)}s] ${y} \u25A0 complete`:`[${m.toFixed(3)}s] ${y} ${c.type}`}if(r==="json")try{return JSON.stringify(c)}catch{return JSON.stringify({type:c.type,path:c.path,data:"[unserializable]"})}let g=d[c.type]??"",v=c.path?`${d.path}${c.path}${d.reset} `:"",w=c.type==="data"||c.type==="error",x=c.type==="pause"||c.type==="resume",b=w?` ${yt(c.data)}`:x?` ${yt(c.lockId)}`:"",T=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,O=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",N=c.in_batch?" [batch]":"";return`${v}${g}${c.type.toUpperCase()}${d.reset}${b}${O}${N}`};e.onEvent(c=>{a(c.type)&&s(p(c),c)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Sn(this._disposers,this.name),this.signal([[Q]],{internal:!0}),Sn(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"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...l}=r.nodes[a];s[a]=l}let o=[...r.subgraphs].sort(),i={...r,version:1,nodes:s,subgraphs:o};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 Jt(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Fe,{codec:s,codecVersion:o,payload:i}=Xt(e,r);return s.decode(i,o)}restore(e,n){if(Dn(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(o=>bt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){Dn(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let p of[...e.subgraphs].sort((c,g)=>{let v=c.split(V).length,w=g.split(V).length;return v!==w?v-w:c<g?-1:c>g?1:0})){let c=p.split(V),g=o;for(let v of c)g._mounts.has(v)||g.mount(v,new t(v)),g=g._mounts.get(v)}let i=s?Object.entries(s).map(([p,c])=>({re:bt(p),factory:c})):[],a=p=>{for(let c of i)if(c.re.test(p))return c.factory},d=p=>{let c=p.split(V),g=c.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${p}"`);let v=o;for(let w of c){let x=v._mounts.get(w);if(!x)throw new Error(`unknown mount "${w}" in path "${p}"`);v=x}return[v,g]},u=Object.entries(e.nodes).filter(([p])=>!p.includes(`${V}${ae}${V}`)).sort((p,c)=>p[0]<c[0]?-1:p[0]>c[0]?1:0),l=new Map(u),f=new Map,h=!0;for(;l.size>0&&h;){h=!1;for(let[p,c]of[...l.entries()]){let g=c?.deps??[];if(!g.every(O=>f.has(O)))continue;let[v,w]=d(p),x={...c?.meta??{}},b=a(p),T;if(c?.type==="state")T=z(c.value,{meta:x});else{if(b==null)continue;T=b(w,{path:p,type:c.type,value:c.value,meta:x,deps:g,resolvedDeps:g.map(O=>f.get(O))})}v.add(T,{name:w}),f.set(p,T),l.delete(p),h=!0}}if(l.size>0){let p=[...l.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}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 s=(u,l)=>{if(u.disposed)return;let f=qr(l.nodes);if(u.lastSnapshot!=null&&f!==""&&f===u.lastFingerprint)return;let h=u.seq+1,p=Ze(),v=u.lastSnapshot==null||h%u.compactEvery===0?{name:this.name,mode:"full",snapshot:l,seq:h,timestamp_ns:p,format_version:Ae}:{name:this.name,mode:"diff",diff:Pn(u.lastSnapshot,l),seq:h,timestamp_ns:p,format_version:Ae};if(u.tier.filter&&!u.tier.filter(v))return;let w;try{w=u.tier.save(v)}catch(x){n.onError?.(x,u.tier);return}if(w&&typeof w.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>w,()=>w).then(()=>{u.disposed||(u.seq=h,u.lastSnapshot=l,u.lastFingerprint=f)},O=>{n.onError?.(O,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=h,u.lastSnapshot=l,u.lastFingerprint=f},o=(u,l)=>{try{s(u,l)}catch(f){n.onError?.(f,u.tier)}},i=(u,l)=>{if(!l.some(c=>{let g=this.config.messageTier(c[0]);return g>=3&&g<5}))return;if(n.filter){let c=this.tryResolve(u);if(c==null)return;let g=Gt(c,dt("standard"));if(!n.filter(u,g))return}let h,p=()=>(h==null&&(h=this.snapshot()),h);for(let c of r)c.disposed||(c.debounceMs===0?o(c,p()):(c.timer==null&&(c.timer=new lt),c.timer.start(c.debounceMs,()=>{c.disposed||o(c,this.snapshot())})))},a;if(n.paths!=null){let l=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(f=>{let h=this.tryResolve(f);return h==null?()=>{}:h.subscribe(p=>i(f,p))});a=()=>{for(let f of l)f()}}else a=this.observe().subscribe((u,l)=>i(u,l));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 s;try{s=await r.load?.()}catch(i){n?.(i,r);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Ae&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load?.()}catch(d){r?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Ae&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}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 s={path:e,annotation:n,timestamp_ns:oe(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(s)}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(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(x=>!r.has(x)).sort(),i=[...r].filter(x=>!s.has(x)).sort(),a=[],d=[];for(let x of r){if(!s.has(x))continue;let b=e.nodes[x],T=n.nodes[x],O=b.v,N=T.v;O!=null&&N!=null&&O.id===N.id&&O.version!==N.version&&d.push({path:x,id:O.id,from:O.version,to:N.version});let m=O!=null&&N!=null&&O.id===N.id&&O.version===N.version;for(let y of["type","status","sentinel"]){let _=b[y],R=T[y];_!==R&&a.push({path:x,field:y,from:_,to:R})}if(!m)for(let y of["value","meta"]){let _=b[y],R=T[y];Kr(_,R)||a.push({path:x,field:y,from:_,to:R})}}let u=x=>`${x.from} ${x.to}`,l=new Set(e.edges.map(u)),f=new Set(n.edges.map(u)),h=n.edges.filter(x=>!l.has(u(x))),p=e.edges.filter(x=>!f.has(u(x))),c=new Set(e.subgraphs),g=new Set(n.subgraphs),v=[...g].filter(x=>!c.has(x)).sort(),w=[...c].filter(x=>!g.has(x)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:h,edgesRemoved:p,subgraphsAdded:v,subgraphsRemoved:w}}};function Pn(t,e){let n=ce.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function $t(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,l=new Set;for(let[b,T]of Object.entries(t.nodes)){if(!b)continue;l.add(b);let O=T.deps??[];i.set(b,O);for(let N of O)N&&(l.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(b))}for(let b of t.edges){if(b==null||typeof b!="object")continue;let T=typeof b.from=="string"?b.from:"",O=typeof b.to=="string"?b.to:"";!T||!O||(l.add(T),l.add(O),u.has(T)||u.set(T,new Set),u.get(T).add(O),d.has(O)||d.set(O,new Set),d.get(O).add(T))}if(!l.has(e))return r.withDetail?s:[];let f=r.both===!0,h=b=>{if(f){let m=i.get(b)??[],y=d.get(b),_=a.get(b),R=u.get(b),E=[...m];return y&&E.push(...y),_&&E.push(..._),R&&E.push(...R),E}if(n==="upstream"){let m=i.get(b)??[],y=d.get(b);return y?[...m,...y]:m}let T=a.get(b),O=u.get(b),N=T?[...T]:[];return O&&N.push(...O),N},p=new Set([e]),c=new Map,g=[{path:e,depth:0}],v=0,w=!1;for(;v<g.length;){let b=g[v++];if(o!=null&&b.depth>=o){h(b.path).length>0&&(w=!0);continue}for(let T of h(b.path))!T||p.has(T)||(p.add(T),c.set(T,b.depth+1),g.push({path:T,depth:b.depth+1}))}let x=[...c.keys()].sort((b,T)=>b<T?-1:b>T?1:0);return r.withDetail?{paths:x,depths:c,truncated:w}:x}function lo(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}st();Pe();We();he();Ve();me();Pe();he();me();Ve();var Ft=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),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];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),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+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 o=0;o<n;o++)this._buf[o]=void 0;this._head=0;let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];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 Ke(t){return t.subscribe(()=>{})}var co=64;function $n(t,e={}){let{name:n,maxSize:r,versioning:s,guard:o,backend:i}=e,a=i??new Ft(t,r),d=z(a.toArray(),{name:n,describeKind:"state",equals:(m,y)=>m===y,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let m=a.toArray();le(()=>{d.down([[K]],{internal:!0}),d.down([[P,m]],{internal:!0})})}let l=new Map,f=new Map,h=new Map;function p(m,y){return`${m}:${y===void 0?"END":y}`}function c(m){if(m.size<co)return;let y=m.keys().next();if(y.done)return;let _=m.get(y.value);_!==void 0&&_.dispose(),m.delete(y.value)}function g(m){let y=a.version;try{return m()}finally{a.version!==y&&u()}}function v(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let y=l.get(m);if(y!==void 0)return l.delete(m),l.set(m,y),y.node;c(l);let _=F([d],([E])=>{let k=E;return m===0||k.length===0?[]:k.slice(Math.max(0,k.length-m))},{initial:a.tail(m),describeKind:"derived"}),R=Ke(_);return l.set(m,{node:_,dispose:R}),_}function w(m,y){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(y!==void 0&&(!Number.isInteger(y)||y<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${y})`);let _=p(m,y),R=f.get(_);if(R!==void 0)return f.delete(_),f.set(_,R),R.node;c(f);let E=F([d],([S])=>{let C=S;return y===void 0?C.slice(m):C.slice(m,y)},{initial:a.slice(m,y),describeKind:"derived"}),k=Ke(E);return f.set(_,{node:E,dispose:k}),E}function x(m){let y=h.get(m);if(y!==void 0)return y.node;let _=F([d,m],([E,k])=>{let S=E,C=Math.max(0,Math.trunc(k??0));return S.slice(C)},{initial:[],describeKind:"derived"}),R=Ke(_);return h.set(m,{node:_,dispose:R}),_}let b,T;function O(){b===void 0&&(b=te([d],(m,y,_)=>{let R=m[0],k=R!=null&&R.length>0?R.at(-1):_.prevData[0];if(k==null||k.length===0){y.down([[Y]]);return}y.emit(k[k.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=F([d],([m])=>m.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Ke(b),Ke(T))}let N={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){g(()=>a.append(m))},appendMany(m){m.length!==0&&g(()=>a.appendMany(m))},clear(){g(()=>a.clear())},trimHead(m){g(()=>a.trimHead(m))},withLatest(){return O(),d},get lastValue(){return O(),b},get hasLatest(){return O(),T},view(m){switch(m.kind){case"tail":return v(m.n);case"slice":return w(m.start,m.stop);case"fromCursor":return x(m.cursor)}},attach(m){let y=m.subscribe(_=>{for(let R of _)R[0]===P&&N.append(R[1])});return()=>y()},attachStorage(m){if(m.length===0)return()=>{};let y=new Map;for(let R of m)y.set(R,a.size);(async()=>{for(let R of m)if(typeof R.loadEntries=="function")try{let E=await Promise.resolve(R.loadEntries());E.entries.length>0&&a.size===0&&(a.restore(E.entries),y.set(R,E.entries.length),u());break}catch{}})();let _=d.subscribe(R=>{for(let E of R){if(E[0]!==P)continue;let k=E[1];for(let S of m){let C=y.get(S)??0;if(k.length<C){try{let B=S.appendEntries(k);B instanceof Promise&&B.catch(()=>{})}catch{}y.set(S,k.length);continue}if(k.length===C)continue;let U=k.slice(C);y.set(S,k.length);try{let B=S.appendEntries(U);B instanceof Promise&&B.catch(()=>{})}catch{}}}});return()=>_()},disposeAllViews(){for(let m of l.values())m.dispose();l.clear();for(let m of f.values())m.dispose();f.clear();for(let m of h.values())m.dispose();h.clear()},dispose(){for(let m of l.values())m.dispose();l.clear();for(let m of f.values())m.dispose();f.clear();for(let m of h.values())m.dispose();h.clear()}};return N}ut();function Fn(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Ye(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Je(t,e){return Fn("messaging",t,e)}var fo=1024,Vt=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=$n([],{name:"events",maxSize:n.retainedLimit??fo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=F([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:Je("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(ge(this.latest)),this.hasLatest=F([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Je("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(ge(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},zt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let s;if(r.from!==void 0?r.from==="retained"?s=0:r.from==="now"?s=n.events.cache.length:s=Ye(r.from,"subscription from"):s=Ye(r.cursor??0,"subscription cursor"),this.cursor=z(s,{name:"cursor",describeKind:"state",meta:Je("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(ge(this.available)),r.advanceOn!==void 0){let o=r.advanceOn,i=!1,a=te([o],()=>{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:Je("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(ge(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:Ye(e,"subscription ack count"),s=Math.min(r,n.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:Ye(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:Ye(e,"subscription pullAndAck limit"),s=n.slice(0,r);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[$]]),this.destroy())}};var Bt=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()}},Ht=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=z(0,{name:"version",describeKind:"state",meta:Je("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new Bt(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}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 s={...this._defaultTopicOptions,...n??{}};r=new Vt(e,s),this._registry.set(e,r),this.mount(e,r);let o=this.version.cache??0;this.version.emit(o+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){le(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new zt(e,s,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function Vn(t,e){return new Ht(t,e)}function po(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 zn(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=jt(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function jt(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 ho(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=po(r.dataset)?r.dataset:z(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=z(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=z(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=z(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let l=z([],{name:"prevCandidates"});o.add(l,{name:"prevCandidates"});let f=z(!1,{name:"paused"});o.add(f,{name:"paused"});let h=z("running",{name:"status"});o.add(h,{name:"status"});let p=z([],{name:"history",equals:()=>!1});o.add(p,{name:"history"});let c=z(null,{name:"best"});o.add(c,{name:"best"});let g=z(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let v=z(0,{name:"budget-used"});o.add(v,{name:"budget-used"});let w=Vn("stages");o.mount("stages",w);let x=w.topic("generate"),b=w.topic("evaluate"),T=w.topic("analyze"),O=w.topic("decide"),N=n,m=null,y=[];o.addDisposer(d.subscribe(A=>{for(let M of A)M[0]===P&&(N=M[1])})),o.addDisposer(u.subscribe(A=>{for(let M of A)M[0]===P&&(m=M[1])})),o.addDisposer(l.subscribe(A=>{for(let M of A)M[0]===P&&(y=M[1])}));let _=ln(a,A=>{let M=N,W=A===0||m==null;return te([],(q,ee)=>{let ve=!1;try{let Te=W?M.seed(t):M.generate(m,y);if(Te instanceof Promise)return Te.then(Ge=>{ve||ee.emit(Ge)},Ge=>{ve||ee.down([[I,Ge]])}),()=>{ve=!0};ee.emit(Te)}catch(Te){ve=!0,ee.down([[I,Te]])}},{describeKind:"producer"})},{name:"candidates"});o.add(_,{name:"candidates"});let R=_e([_],(A,M,W)=>{let q=W.terminalDeps[0];q!==void 0&&q!==!0&&h.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(R,{name:"error-watcher"}),o.addDisposer(R.subscribe(()=>{}));let E=F([_,a],([A,M])=>({iteration:M,candidates:A,timestamp_ns:oe()}),{name:"generate-event"});o.add(E,{name:"generate-event"}),o.addDisposer(E.subscribe(()=>{}));let k=_e([E],([A])=>{x.publish(A)},{name:"generate-publish"});o.add(k,{name:"generate-publish"}),o.addDisposer(k.subscribe(()=>{}));let S=_e([_],([A])=>{l.emit(A)},{name:"generate-mirror"});o.add(S,{name:"generate-mirror"}),o.addDisposer(S.subscribe(()=>{}));let C=e(_,i);o.add(C,{name:"scores"});let U=F([C,_,a],([A,M,W])=>({iteration:W,candidates:M,scores:A,timestamp_ns:oe()}),{name:"evaluate-event"});o.add(U,{name:"evaluate-event"}),o.addDisposer(U.subscribe(()=>{}));let B=_e([U],([A])=>{b.publish(A)},{name:"evaluate-publish"});o.add(B,{name:"evaluate-publish"}),o.addDisposer(B.subscribe(()=>{}));let ue=F([C,_],([A,M])=>N.analyze(A,M),{name:"feedback"});o.add(ue,{name:"feedback"});let Ne=F([ue,_,a],([A,M,W])=>({iteration:W,candidates:M,feedback:A,timestamp_ns:oe()}),{name:"analyze-event"});o.add(Ne,{name:"analyze-event"}),o.addDisposer(Ne.subscribe(()=>{}));let Ce=_e([Ne],([A])=>{T.publish(A)},{name:"analyze-publish"});o.add(Ce,{name:"analyze-publish"}),o.addDisposer(Ce.subscribe(()=>{}));let Ee=F([p],([A])=>{let M=A;if(r.patience==null||M.length<=r.patience)return!1;let W=M.slice(-(r.patience+1)),q=W[0].bestScore;return W.slice(1).every(ee=>ee.bestScore<=q)},{name:"patience-check"});o.add(Ee,{name:"patience-check"});let be=F([g],([A])=>r.minScore!=null&&A>=r.minScore,{name:"min-score-check"});o.add(be,{name:"min-score-check"});let Me=F([p],([A])=>{let M=A;if(r.minDelta==null||M.length<2)return!1;let W=M[M.length-2].bestScore,q=M[M.length-1].bestScore;return Math.abs(q-W)<r.minDelta},{name:"min-delta-check"});o.add(Me,{name:"min-delta-check"});let D=F([v],([A])=>r.maxEvaluations!=null&&A>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(D,{name:"max-evaluations-check"});let L=F([a],([A])=>r.maxIterations!=null&&A>=r.maxIterations,{name:"max-iterations-check"});o.add(L,{name:"max-iterations-check"});let J=F([v],([A])=>r.budget!=null&&A>=r.budget,{name:"budget-exhausted-check"});o.add(J,{name:"budget-exhausted-check"}),o.addDisposer(Ee.subscribe(()=>{})),o.addDisposer(be.subscribe(()=>{})),o.addDisposer(Me.subscribe(()=>{})),o.addDisposer(D.subscribe(()=>{})),o.addDisposer(L.subscribe(()=>{})),o.addDisposer(J.subscribe(()=>{}));let ye=F([Ee,be,Me,D,L],([A,M,W,q,ee])=>A?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:W?{converged:!0,reason:"min-delta"}:q?{converged:!0,reason:"max-evaluations"}:ee?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(ye,{name:"converged"}),o.addDisposer(ye.subscribe(()=>{}));let X=-1,G=_e([ue,C,_],([A,M,W])=>{let q=a.cache,ee=A,ve=W,Te=M;if(q<=X)return;X=q;let{best:Ge,bestScore:Bn}=zn(ve,Te),Hn=p.cache,jn={n:q,candidates:ve,scores:Te,feedback:ee,best:Ge,bestScore:Bn,timestamp_ns:oe()},we=[...Hn,jn],vt=v.cache+ve.length,ne="continue",Oe,Un=r.budget!=null&&vt>=r.budget,Wn=f.cache;if(Un)ne="budget",Oe="budget";else if(r.minScore!=null&&ee.score>=r.minScore)ne="converged",Oe="min-score";else if(r.maxIterations!=null&&q>=r.maxIterations)ne="converged",Oe="max-iterations";else if(r.maxEvaluations!=null&&vt>=r.maxEvaluations)ne="converged",Oe="max-evaluations";else if(r.minDelta!=null&&we.length>=2){let Xe=we[we.length-2].bestScore,Tt=we[we.length-1].bestScore;Math.abs(Tt-Xe)<r.minDelta&&(ne="converged",Oe="min-delta")}else if(r.patience!=null&&we.length>r.patience){let Xe=we.slice(-(r.patience+1)),Tt=Xe[0].bestScore;Xe.slice(1).every(qn=>qn.bestScore<=Tt)&&(ne="converged",Oe="patience")}ne==="continue"&&Wn&&(ne="paused"),le(()=>{c.emit(Ge),g.emit(ee.score),p.emit(we),v.emit(vt),u.emit(ee),O.publish({iteration:q,decision:ne,reason:Oe,timestamp_ns:oe()}),ne==="continue"?a.emit(q+1):h.emit(ne==="converged"?"converged":ne==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(G,{name:"decide-bridge"}),o.addDisposer(G.subscribe(()=>{})),Object.assign(o,{best:c,score:g,status:h,history:p,strategy:d,iteration:a,generate:x,evaluate:b,analyze:T,decide:O,setStrategy(A){d.emit(A)},pause(){f.emit(!0)},resume(){h.cache==="paused"&&le(()=>{f.emit(!1),h.emit("running"),a.emit(a.cache+1)})}})}function mo(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,s){let o=jt(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${o.toFixed(3)}, n=${r.length}`,score:o,weakTasks:i?[i.taskId]:[]}},async generate(r,s){if(s.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=s[s.length-1],i=0,d={prior:o,reportCost:u=>{i+=u}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(d)));let u=[];for(let l=0;l<e;l++)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 go(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function bo(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
1
+ "use strict";var wt=Object.defineProperty;var er=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var nr=Object.prototype.hasOwnProperty;var ee=(t,e)=>()=>(t&&(e=t(t=0)),e);var rr=(t,e)=>{for(var n in e)wt(t,n,{get:e[n],enumerable:!0})},or=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tr(e))!nr.call(t,s)&&s!==n&&wt(t,s,{get:()=>e[s],enumerable:!(r=er(e,s))||r.enumerable});return t};var sr=t=>or(wt({},"__esModule",{value:!0}),t);function je(){return Ge>0||Be}function qt(){return Ge>0}function Le(t){Ge>0?He.push(t):t()}function ue(t){Ge+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ge-=1,Ge===0)if(e){if(!Be){let n=He.splice(0);for(let r of n)try{r()}catch{}ke.length=0,Re.length=0,Ie.length=0}}else ir()}}function ir(){let t=!Be;t&&(Be=!0);let e=[],n=0;try{for(;ke.length>0||Re.length>0||Ie.length>0||t&&He.length>0;){if(t&&He.length>0){let o=He.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw ke.length=0,Re.length=0,Ie.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(ke.length>0?ke:Re.length>0?Re:Ie).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(Be=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ue(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!je()){t(e);return}(u>=5?Ie:u===4?Re:ke).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=je();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?ke.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?Re.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Ie.push(()=>t(u)):t(u)}}var Ge,Be,ke,Re,Ie,He,Pe=ee(()=>{"use strict";Ge=0,Be=!1,ke=[],Re=[],Ie=[],He=[]});function X(){return Math.trunc(performance.now()*1e6)}function Qe(){return Date.now()*1e6}var We=ee(()=>{"use strict"});var le,I,q,Y,re,ae,fe,W,P,G,Se,et,Yt,tt,Jt,Xt,nt,_t,xt,Nt,rt,pe=ee(()=>{"use strict";le=Symbol.for("graphrefly/START"),I=Symbol.for("graphrefly/DATA"),q=Symbol.for("graphrefly/DIRTY"),Y=Symbol.for("graphrefly/RESOLVED"),re=Symbol.for("graphrefly/INVALIDATE"),ae=Symbol.for("graphrefly/PAUSE"),fe=Symbol.for("graphrefly/RESUME"),W=Symbol.for("graphrefly/TEARDOWN"),P=Symbol.for("graphrefly/COMPLETE"),G=Symbol.for("graphrefly/ERROR"),Se=Object.freeze([q]),et=Object.freeze([Y]),Yt=Object.freeze([re]),tt=Object.freeze([le]),Jt=Object.freeze([P]),Xt=Object.freeze([W]),nt=Object.freeze([Se]),_t=Object.freeze([et]),xt=Object.freeze([Yt]),Nt=Object.freeze([Jt]),rt=Object.freeze([Xt])});function Qt(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 s=2+n.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=Ot,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function en(t,e){if(t.length<Zt)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Zt})`);let n=0,r=t[n++];if(r!==Ot)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Ot})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function tn(t){t.registerCodec(ar)}var ar,Ot,Zt,Et=ee(()=>{"use strict";ar={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)}},Ot=1,Zt=4});function ot(t){if(t==null)return $e;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var $e,st=ee(()=>{"use strict";$e={type:"system",id:""}});function nn(t){t.registerMessageType(le,{tier:0,wireCrossing:!1}),t.registerMessageType(q,{tier:1,wireCrossing:!1}),t.registerMessageType(re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(ae,{tier:2,wireCrossing:!1}),t.registerMessageType(fe,{tier:2,wireCrossing:!1}),t.registerMessageType(I,{tier:3,wireCrossing:!0}),t.registerMessageType(Y,{tier:3,wireCrossing:!0}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(W,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var it,rn=ee(()=>{"use strict";pe();it=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 kt(t){let e=ur.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 oe,ur,Ke=ee(()=>{"use strict";oe=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}},ur=["human","llm","wallet","system"]});function Rt(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(Rt);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Rt(t[n]);return e}return null}function lr(t){let e=cr.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,h=2600822924,f=528734635,l=1541459225,b=new Uint32Array(64),m=(T,y)=>T>>>y|T<<32-y;for(let T=0;T<s;T+=64){for(let k=0;k<16;k++)b[k]=i.getUint32(T+k*4,!1);for(let k=16;k<64;k++){let A=b[k-15],R=b[k-2],C=m(A,7)^m(A,18)^A>>>3,j=m(R,17)^m(R,19)^R>>>10;b[k]=b[k-16]+C+b[k-7]+j>>>0}let y=a,_=d,E=u,N=c,g=p,v=h,x=f,D=l;for(let k=0;k<64;k++){let A=m(g,6)^m(g,11)^m(g,25),R=g&v^~g&x,C=D+A+R+dr[k]+b[k]>>>0,j=m(y,2)^m(y,13)^m(y,22),U=y&_^y&E^_&E,ie=j+U>>>0;D=x,x=v,v=g,g=N+C>>>0,N=E,E=_,_=y,y=C+ie>>>0}a=a+y>>>0,d=d+_>>>0,u=u+E>>>0,c=c+N>>>0,p=p+g>>>0,h=h+v>>>0,f=f+x>>>0,l=l+D>>>0}let w=T=>T.toString(16).padStart(8,"0");return w(a)+w(d)+w(u)+w(c)+w(p)+w(h)+w(f)+w(l)}function St(t){let e=Rt(t??null),n=JSON.stringify(e);return lr(n).slice(0,16)}function fr(){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 Dt(t,e,n){let r=n?.id??fr();if(t===0)return{id:r,version:0};let o=(n?.hash??St)(e);return{id:r,version:0,cid:o,prev:null}}function on(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var dr,cr,sn=ee(()=>{"use strict";dr=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]),cr=new TextEncoder});function dn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function At(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function at(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function te(t,e,n){let r=cn(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return cn(t)?o=(Ct(e)?e:n)??{}:Ct(t)?o=t:o=(Ct(e)?e:n)??{},new B(r,s,o)}var an,un,pr,hr,Fe,B,cn,Ct,he=ee(()=>{"use strict";Et();st();Pe();We();rn();Ke();pe();sn();an=()=>{},un=100;pr=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},hr=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[tt]:[tt,[I,o]];s._status==="dirty"&&i.push(Se),Ue(e,i,s._config.tierOf)},Fe=new it({onMessage:pr,onSubscribe:hr});nn(Fe);tn(Fe);B=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??Fe,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??St;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Dt(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(dn);let o={};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),o[a]=new t([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[I,a]])},down(a){i._emit(at(a))},up(a){i._emitUp(at(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 s=n?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Dt(e,o,{id:a,hash:s});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=ot(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 s=ot(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new oe({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new oe({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:Qe()}}down(e,n){let r=at(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[I,e]])}up(e,n){if(this._deps.length===0)return;let r=at(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_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 s=n(r[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} 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=ot(n);if(!this._guard(d,"observe"))throw new oe({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){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)At(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 o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},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 o=="function")try{o()}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 o=="function"&&o(),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 s=r,o=this._deps[r];o.unsub=an,o.unsub=o.node.subscribe(i=>{if(o.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:s},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}At(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=dn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(nt),r.unsub=an;try{r.unsub=e.subscribe(s=>{if(r.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[G,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[G,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}At(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],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==le){if(s===q){this._depDirtied(r);return}if(s===re){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(xt);return}if(s===ae||s===fe){this._emit([n]);return}if(s===W){this._emit(rt);return}if(s===I)this._depSettledAsData(r,n[1]);else if(s===Y)this._depSettledAsResolved(r);else if(s===P)this._depSettledAsTerminal(r,!0);else if(s===G)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===I||s===Y)&&this._emit([n]),(s===P||s===G)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(nt))}_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(_t),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([[G,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Nt)}_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([[G,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([[G,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 s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,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,o);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([[G,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>un?(this._rerunDepth=0,this._emit([[G,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${un} \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"?[Se,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===q&&(o=!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(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Se,...a]:[...a.slice(0,d),Se,...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]===G&&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]===W||d[0]===re);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==ae&&u!==fe){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===ae?"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 p=d[1];if(u===ae)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let h=this._pauseBuffer;this._pauseBuffer=[],this._emit(h)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===W))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(rt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[G,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-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]===I){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],h=p[0];if(h===I){if(p.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,p[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(et),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&on(this._versioning,p[1],this._hashFn)}this._status="settled",r?.push(p)}else if(r?.push(p),h===q)this._status="dirty";else if(h===Y)this._status="resolved";else if(h===P){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(h===G){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(h===re){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.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 l=f.invalidate;if(typeof l=="function")try{l()}catch{}}}else h===W&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??e;return s!=null?{finalMessages:u,equalsError:s}:{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(qt()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Le(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ue(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);Ue(this._deliverToSinks,n,this._config.tierOf)}},cn=t=>Array.isArray(t),Ct=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function $(t,e){return te([],{...e,initial:t})}function Te(t,e){return te((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function F(t,e,n){return te(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...n})}function we(t,e,n){return te(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...n})}var Ve=ee(()=>{"use strict";he()});function ut(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"]);default:return new Set(["type","deps"])}}function gr(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function ln(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function mr(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Mt(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof B&&(o=gr(t),i=t._deps.map(u=>u.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof B?t._guard:void 0;if(s){let u={...mr(t)};if(d!=null&&u.access===void 0&&(u.access=kt(d)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let p of r)p in u&&(c[p]=u[p]);a.meta=c}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=kt(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}var Gt=ee(()=>{"use strict";Ke();he()});function It(t){return{describeKind:"producer",...t}}function fn(t,e){return Te(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[P]])}catch(s){r||n.down([[G,s]])}return()=>{r=!0}},It(e))}function br(t){return t!=null&&typeof t.then=="function"}function yr(t,e){let{signal:n,...r}=e??{};return Te(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[G,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[P]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[G,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},It(r))}function vr(t,e){let{signal:n,...r}=e??{};return Te(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(p=>{if(!(d||a.aborted)){if(p.done){s.down([[P]]);return}s.emit(p.value),c()}},p=>{!d&&!a.aborted&&s.down([[G,p]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},It(r))}function Tr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function pn(t,e){if(Tr(t))return t;if(br(t))return yr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return vr(t,e);if(typeof n[Symbol.iterator]=="function")return fn(t,e)}return wr(t)}function wr(...t){return fn(t,void 0)}function de(t){return t.subscribe(()=>{})}var dt=ee(()=>{"use strict";pe();Ve()});var ct,mn=ee(()=>{"use strict";ct=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 Eo={};rr(Eo,{blindVariation:()=>_o,errorCritique:()=>Oo,refineLoop:()=>wo});module.exports=sr(Eo);Pe();We();pe();he();Ve();pe();Gt();he();dt();function _r(t){return{describeKind:"derived",...t}}function xr(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==le&&(u[0]===I?e.emit(u[1]):u[0]===P?a=!0:u[0]===G?(d=!0,e.down([u])):(u[0]===q||u[0]===Y)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function hn(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return te([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[P]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=xr(pn(e(u[u.length-1])),a,()=>{o(),s&&a.down([[P]])}),{deactivate:()=>{o(),s=!1}}},{..._r(n),completeWhenDepsComplete:!1,meta:{...ln("switchMap"),...n?.meta??{}}})}st();Pe();We();Ke();pe();Gt();he();Ve();We();function Lt(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 o=0;o<t.length;o++)if(!Lt(t[o],e[o]))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 s=new Set(r);for(let o of n)if(!s.has(o)||!Lt(t[o],e[o]))return!1;return!0}function gn(t,e){return`${t}\0${e}`}function Pt(t,e){let n=[],r=new Set(t.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)r.has(m)||o.push(m);o.sort();for(let m of o)n.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(t.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let m of a)i.has(m)||d.push(m);d.sort();for(let m of d)n.push({type:"node-added",path:m,node:{...e.nodes[m]}});let u=[];for(let m of a){if(!i.has(m))continue;let w=t.nodes[m]?.meta,T=e.nodes[m]?.meta;w==null&&T==null||Lt(w??{},T??{})||u.push(m)}u.sort();for(let m of u)n.push({type:"node-meta-changed",path:m,prevMeta:t.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of t.edges)c.set(gn(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(gn(m.from,m.to),m);let h=[];for(let[m,w]of p)c.has(m)||h.push(w);h.sort((m,w)=>m.from<w.from?-1:m.from>w.from?1:m.to<w.to?-1:m.to>w.to?1:0);for(let m of h)n.push({type:"edge-added",from:m.from,to:m.to});let f=[];for(let[m,w]of c)p.has(m)||f.push(w);f.sort((m,w)=>m.from<w.from?-1:m.from>w.from?1:m.to<w.to?-1:m.to>w.to?1:0);for(let m of f)n.push({type:"edge-removed",from:m.from,to:m.to});let l=[];for(let m of i)a.has(m)||l.push(m);l.sort();for(let m of l)n.push({type:"node-removed",path:m});let b=[];for(let m of r)s.has(m)||b.push(m);b.sort();for(let m of b)n.push({type:"subgraph-unmounted",path:m});return{events:n,flushedAt_ns:X()}}dt();mn();var qe=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}};Et();function $t(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 lt(t){let e=0;for(let n of t)e+=$t(n.codePointAt(0));return e}function bn(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=$t(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=$t(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var Nr={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"},Or={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function wn(t,e){let n=e.charset==="ascii"?Or:Nr,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)kr(o,i,n,a);for(let a of t.boxes)Er(o,i,n,a,e.labelOf(a.id));return o.map(a=>Ar(a.join(""))).join(`
2
+ `)}function Er(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&yn(t,e,o,i,a,s);return}_e(t,e,o,i,n.boxTL);for(let c=o+1;c<o+a-1;c+=1)_e(t,e,c,i,n.boxH);_e(t,e,o+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){_e(t,e,o,c,n.boxV);for(let p=o+1;p<o+a-1;p+=1)_n(t,e,p,c," ","empty");_e(t,e,o+a-1,c,n.boxV)}_e(t,e,o,i+d-1,n.boxBL);for(let c=o+1;c<o+a-1;c+=1)_e(t,e,c,i+d-1,n.boxH);_e(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);yn(t,e,o+1,u,a-2,s)}function _e(t,e,n,r,s){_n(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function _n(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function yn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=lt(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 kr(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)Rr(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],c=s[d],p=s[d+1],h=Sr(u,c,p,n);h&&Tn(t,e,c.x,c.y,h,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Dr(i,o,n);a&&Tn(t,e,o.x,o.y,a,"arrow")}function Rr(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)vn(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)vn(t,e,o,d,n,"v")}}}function vn(t,e,n,r,s,o){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]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function Tn(t,e,n,r,s,o){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]=s,e[r][n]=o)}function Sr(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){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 Dr(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 Ar(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function On(t){let e=Cr(t);Mr(e),Gr(e),Ir(e),Lr(e,t);let n=Fr(e,t),{width:r,height:s}=zr(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function Cr(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function Mr(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function Gr(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);let u=i;for(let p=1;p<d;p+=1){let h=`__virt_${s++}__`,f={id:h,isVirtual:!0,layer:i.layer+p,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(h,f),n[f.layer].push(f);let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:h,hopIndex:p-1,chainLen:d};u.out.push(l),f.in.push(l),r.push(l),u=f}let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.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 o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function Ir(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)xn(t,t.layers[r],"in"),ft(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)xn(t,t.layers[r],"out"),ft(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=Nn(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],ft(o),Nn(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],ft(o))}}if(!r)break}}function xn(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function ft(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Nn(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){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 Lr(t,e){e.direction==="LR"?Pr(t,e):$r(t,e)}function Pr(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}En(t,e,"y")}function $r(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}En(t,e,"x")}function En(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===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 p=o===0?c.in:c.out;if(p.length===0)continue;let h=[];for(let l of p){let b=t.nodes.get(o===0?l.fromId:l.toId);if(!b)continue;let m=n==="y"?b.y:b.x;h.push(m+Math.floor(r(b)/2))}if(h.length===0)continue;h.sort((l,b)=>l-b);let f=h[Math.floor(h.length/2)];d.set(c.id,f-Math.floor(r(c)/2))}let u=0;for(let c of a){let p=d.get(c.id),h=n==="y"?c.y:c.x,l=Math.max(p??h,u);n==="y"?c.y=l:c.x=l,u=l+r(c)+s}}}}function Fr(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,p)=>c.hopIndex-p.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=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],p=t.layers[u+1],h=0;for(let v of c)h=Math.max(h,s(v)+o(v));let f=Number.POSITIVE_INFINITY;for(let v of p)f=Math.min(f,s(v));let l=Number.isFinite(f)?f-1:h,b=Math.max(1,l-h+1),m=[];for(let v of c)for(let x of v.out)m.push(x);m.sort((v,x)=>{let D=i(t.nodes.get(v.fromId)),k=i(t.nodes.get(x.fromId));if(D!==k)return D-k;let A=i(t.nodes.get(v.toId)),R=i(t.nodes.get(x.toId));return A-R});let w=[],T=new Map;for(let v of m){let x=i(t.nodes.get(v.fromId)),D=i(t.nodes.get(v.toId)),k=Math.min(x,D),A=Math.max(x,D),R=-1;for(let C=0;C<w.length;C+=1){let j=w[C],U=!0;for(let ie of j)if(ie.lo<=A&&k<=ie.hi){U=!1;break}if(U){j.push({lo:k,hi:A}),R=C;break}}R<0&&(w.push([{lo:k,hi:A}]),R=w.length-1),T.set(v,R)}let y=w.length,_=b>=Math.max(3,y+2),E=_?h+1:h,N=_?l-1:l,g=Math.max(1,N-E+1);for(let v of m){let x=T.get(v),D;if(y<=1)D=E+Math.floor(g/2);else{let k=(g-1)/(y-1);D=E+Math.floor(x*k)}a.set(v,Math.max(h,Math.min(l,D)))}}let d=[];for(let[,u]of n){let c=[];for(let h=0;h<u.length;h+=1){let f=u[h],l=t.nodes.get(f.fromId),b=t.nodes.get(f.toId),m=a.get(f),w=l.isVirtual?s(l):s(l)+o(l),T=b.isVirtual?s(b):s(b)-1,y=i(l),_=i(b);h===0&&pt(c,r,w,y),y!==_&&(pt(c,r,m,y),pt(c,r,m,_)),pt(c,r,T,_)}let p=u[0];d.push({from:p.chainFrom,to:p.chainTo,points:Vr(c)})}return d}function pt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Vr(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 zr(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var Br=24,Hr=4,jr=1,Ur=3;function kn(t,e){let n=Wr(e.direction),r=Math.max(3,e.maxLabelWidth??Br),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),d=new Map,u=new Map;for(let f of o){let l=bn(f,r);d.set(f,l),u.set(f,lt(l)+4)}let c=On({nodes:o,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>Ur,layerGap:Hr,nodeGap:jr,direction:n}),p=wn(c,{charset:s,labelOf:f=>d.get(f)??f}),h=e.logger;return h&&h(p),p}function Wr(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)}`)}function Rn(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return ht(e,n,"no-such-from");if(!o)return ht(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=Kr(t,e,r);if(u!=null)return u}let d=gt(e,t.nodes[e],0,r);return mt(e,n,[d])}if(i===0)return ht(e,n,"no-path");let a=Sn(t,e,n,i);return a.found?mt(e,n,Dn(t,a.pathOrder,r)):ht(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Sn(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(r!=null&&p.depth>=r){let b=t.nodes[p.path];b?.deps&&b.deps.length>0&&(d=!0);continue}let h=t.nodes[p.path];if(h==null)continue;let f=h.deps??[],l=new Map;for(let b=0;b<f.length;b++){let m=f[b];if(!m)continue;let w=l.get(m);w==null&&(w=[],l.set(m,w)),w.push(b)}for(let[b,m]of l)i.has(b)||(i.add(b),s.set(b,{from:p.path,depIndices:m}),o.push({path:b,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=p.depIndices,u.push({path:p.from}),c=p.from}return{found:!0,pathOrder:u,truncated:!1}}function Kr(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=gt(e,r,0,n);a.dep_index=o[0];let d=gt(e,r,1,n);return mt(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=Sn(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:mt(e,e,Dn(t,i.pathOrder,n))}function Dn(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=gt(r.path,o,s,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 gt(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function mt(t,e,n){return An(t,e,!0,"ok",n)}function ht(t,e,n){return An(t,e,!1,n,[])}function An(t,e,n,r,s){let o=qr(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function qr(t,e,n,r,s){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 o=[`Causal path: ${t} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Yr(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
3
+ `)}function Yr(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)}}he();var H={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},Jr=Symbol.for("sizeof");function Cn(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=Xr(o,e,n,r)}return s}function Xr(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return H.number;case"boolean":return H.boolean;case"string":return H.string+t.length*2;case"bigint":return H.bigint+Zr(t);case"symbol":return H.symbol;case"function":return e.has(t)?0:(e.add(t),H.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[Jr];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return H.date;if(o instanceof RegExp)return H.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return H.error+u+c}if(typeof URL<"u"&&o instanceof URL)return H.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return H.promise;if(o instanceof WeakMap)return H.weakmap;if(o instanceof WeakSet)return H.weakset;if(o instanceof Map){let u=H.map;for(let[c,p]of o)u+=H.mapEntry,r.push(c),r.push(p);return u}if(o instanceof Set){let u=H.set;for(let c of o)u+=H.setEntry,r.push(c);return u}if(Array.isArray(o)){let u=H.array+o.length*8;for(let c of o)r.push(c);return u}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=H.object,d=Object.keys(o);for(let u of d){a+=H.string+u.length*2;try{r.push(o[u])}catch{}}return a}function Zr(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function Mn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[h,f]of s)i.set(h,f);let a=[];for(let[h,f]of Object.entries(r.nodes)){let l=i.get(h),b=l instanceof B?l:null,m=b?Cn(b.cache):0,w=b?b._sinkCount:0,T=f.deps?.length??0,y=f.type==="effect"&&w===0,_=w===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:h,type:f.type,status:f.status??"unknown",valueSizeBytes:m,subscriberCount:w,depCount:T,isOrphanEffect:y,orphanKind:_})}let d=a.reduce((h,f)=>h+f.valueSizeBytes,0),u=(h,f)=>[...a].sort(f??((l,b)=>b[h]-l[h])).slice(0,n),c=a.filter(h=>h.orphanKind!=null),p=a.filter(h=>h.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:p}}var V="::",se="__meta__",De=1;function Gn(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 s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Pn(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Qr(t){if(t!=null)return Pn(t)?t.cache:t}function eo(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(`
4
+ `)}function In(t){if(t.version!==De)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${De})`);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 to(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let h=o;if(s.length!==h.length)return!1;for(let f=0;f<s.length;f++)if(!r(s[f],h[f]))return!1;return!0}if(s instanceof Map){let h=o;if(s.size!==h.size)return!1;for(let[f,l]of s)if(!h.has(f)||!r(l,h.get(f)))return!1;return!0}if(s instanceof Set){let h=o;if(s.size!==h.size)return!1;for(let f of s){let l=!1;for(let b of h)if(r(f,b)){l=!0;break}if(!l)return!1}return!0}if(ArrayBuffer.isView(s)){let h=s,f=o;if(h.length!==f.length)return!1;for(let l=0;l<h.length;l++)if(h[l]!==f[l])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let p=new Set(c);for(let h of u)if(!p.has(h)||!r(s[h],o[h]))return!1;return!0};return r(t,e)}function Vt(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Vt);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=Vt(e[s]);return r}function no(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ro(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function oo(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function $n(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function Fn(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 so(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Vt(i),null,e.indent??2);return e.logger?.(a),a}function io(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${yt(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
5
+ `);return e.logger?.(o),o}function Vn(t,e){let n=Fn(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${no(i)}"]`)}for(let[i,a]of $n(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
6
+ `)}function ao(t,e){let n=Vn(t,e);return zn(n)}function zn(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),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 uo(t,e){let n=Fn(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${oo(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${ro(i)}"`)}for(let[i,a]of $n(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
7
+ `)}function co(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(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 s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=co(r)}return e+="$",new RegExp(e)}var lo={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"},fo={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function yt(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 po(t){return t==="none"?fo:t==="ansi"||t==null?lo:{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 Ln(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 ho(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function Ft(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(V))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${V}' (path separator)`);if(t===se)throw new Error(`Graph "${e}": ${n} name "${se}" is reserved for meta companion paths`);ho(t,e,n)}function go(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(V);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function mo(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function Bn(t){for(let e of t._mounts.values())Bn(e);for(let e of t._nodes.values())try{e.down([[W]],{internal:!0})}catch{}}var ce=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(V))throw new Error(`Graph name must not contain '${V}' (got "${e}")`);if(e===se)throw new Error(`Graph name "${se}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Fe,this._traceRing=new qe(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=Te(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,s=n?.name??r;if(s==null||s==="")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 o=s,i=n?.annotation;if(Ft(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" 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(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:X()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof B&&n._applyVersioning(e)}remove(e){Ft(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${V}${se}${V}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${V}`)),this._mounts.delete(e),n._parent=void 0,Bn(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}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([[W]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=bt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);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 s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(V))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 s=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);ue(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[re]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[G,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[P]],{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 B)for(let c of u._deps){let p=r.get(c.node);p!=null&&a.push([p,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 s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof B)for(let u of d._deps){let c=o.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 s=new t(e);return this.mount(e,s)}if(typeof n=="function"){let s=new t(e);return n(s),this.mount(e,s)}let r=n;if(Ft(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 s=this;s!=null;s=s._parent)if(s===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=go(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],s=n.slice(1);if(s.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 o=this._nodes.get(r);if(o&&s.length>0&&s[0]===se)return this._resolveMetaChainFromNode(o,s,n.join(V));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(V)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(V))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==se)throw new Error(`Graph "${this.name}": expected ${se} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${se} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.internal!==!0){for(let s of e)if(this.config.messageTier(s[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,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=mo(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 oe)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){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,s)}catch(d){if(d instanceof oe)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=Qr(e?.actor),r=e?.filter,s=ut(e?.detail,e?.fields),o=e?.format==="spec",i=o?ut("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[N,g]of a)d.set(g,N);let u=[];{let N=a.map(([,x])=>x),g=new Set(d.values()),v=0;for(;N.length>0;){let x=N.shift();if(x instanceof B)for(let D of x._deps){let k=D.node;if(d.has(k))continue;let A=k.name??"",R=A;if(!R||g.has(R))if(A){let C=2;for(;g.has(`${A}#${C}`);)C++;R=`${A}#${C}`}else for(R=`__internal__/${v++}`;g.has(R);)R=`__internal__/${v++}`;d.set(k,R),g.add(R),u.push([R,k]),N.push(k)}}}let c=[...a,...u],p={};for(let[N,g]of c){if(n!=null&&!g.allowsObserve(n))continue;let v=Mt(g,i),x=g instanceof B?g._deps.map(R=>d.get(R.node)??R.node.name??""):[],{name:D,...k}=v,A={...k,deps:x};if(!o){let R=this._annotations.get(N);R!=null&&(A.annotation=R)}if(r!=null)if(typeof r=="function"){let R=r;if(!(R.length>=2?R(N,A):R(A)))continue}else{let R=!0;for(let[C,j]of Object.entries(r)){let U=C==="deps_includes"?"depsIncludes":C==="meta_has"?"metaHas":C;if(U==="depsIncludes"){if(!A.deps.includes(String(j))){R=!1;break}continue}if(U==="metaHas"){if(!Object.hasOwn(A.meta??{},String(j))){R=!1;break}continue}if(A[U]!==j){R=!1;break}}if(!R)continue}p[N]=A}let h=new Set(Object.keys(p)),f=[];for(let[N,g]of c)if(g instanceof B)for(let v of g._deps){let x=d.get(v.node);x!=null&&f.push([x,N])}f.sort((N,g)=>N[0]<g[0]?-1:N[0]>g[0]?1:N[1]<g[1]?-1:N[1]>g[1]?1:0);let l=f.map(([N,g])=>({from:N,to:g}));(n!=null||r!=null)&&(l=l.filter(N=>h.has(N.from)&&h.has(N.to)));let b=this._collectSubgraphs(""),m=n!=null||r!=null?b.filter(N=>{let g=`${N}${V}`;return[...h].some(v=>v===N||v.startsWith(g))}):b,w=this,T=e,y={name:this.name,nodes:p,edges:l,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(N){let g={...T,format:void 0};return Array.isArray(N)?(g.fields=N,g.detail=void 0):(g.detail=N,g.fields=void 0),w.describe(g)}},_=e??{},E=_.format;return E==="json"?so(y,_):E==="pretty"?io(y,_):E==="mermaid"?Vn(y,_):E==="mermaid-url"?ao(y,_):E==="d2"?uo(y,_):E==="ascii"?kn(y,_):y}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${V}`))}return n}resourceProfile(e){return Mn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?zt(this.describe(),e,n,{...r,withDetail:!0}):zt(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return Rn(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=$(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Le(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(T=>{let y=T.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),p=[],h=new WeakSet,f=T=>{if(h.has(T)||d)return;h.add(T);let y=T.topology.subscribe(_=>{for(let E of _){if(E[0]!==I)continue;let N=E[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let g=T._mounts.get(N.name);g!=null&&f(g)}}});p.push(y);for(let _ of T._mounts.keys()){let E=T._mounts.get(_);E!=null&&f(E)}};f(this);let l,b=e.actor;Pn(b)&&(l=b.subscribe(T=>{let y=!1,_=!1;for(let E of T){let N=E[0];N===I?y=!0:(N===P||N===G||N===W)&&(_=!0)}y&&u(),_&&(l?.(),l=void 0,u())}));let m;try{m=F([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(T,y)=>T===y})}catch(T){c(),l?.();for(let y of p)y();throw i.dispose(),T}let w=de(m);return{node:m,dispose(){d=!0,c(),l?.();for(let T of p)T();p.length=0,i.dispose(),w()}}}_describeReactiveDiff(e){let n={...e,format:void 0,reactive:!1},r=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(n),i=Pt(s,o),a=$(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(h,f)=>h===f}),d=this._describeReactive({...e,format:void 0,reactiveName:void 0}),u=!1,c=d.node.subscribe(h=>{if(!u)for(let f of h){if(f[0]!==I)continue;let l=f[1],b=Pt(o,l);o=l,b.events.length!==0&&a.emit(b)}}),p=de(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[W,"describe-diff disposed"]]),p()}}}_explainReactive(e,n,r){let s=0,o=$(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(f=>{let l=f.type;l!=="data"&&l!=="error"&&l!=="complete"&&l!=="teardown"||a||d||(a=!0,Le(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},p;try{p=F([o],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,l)=>f.found===l.found&&f.reason===l.reason&&f.steps.length===l.steps.length&&bo(f.steps,l.steps)})}catch(f){throw u(),i.dispose(),f}let h=de(p);return{node:p,dispose(){d=!0,u(),i.dispose(),h()}}}_pathsMatching(e){let n=bt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${V}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${V}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${V}${se}${V}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=Ln(r?n:e);if(o.reactive===!0)return this._observeReactive(r?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new oe({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(h){return p.subscribe(h)},up(h){try{p.up?.(h)}catch(f){if(f instanceof oe)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let p=u.map(([h,f])=>f.subscribe(l=>{c(h,l)}));return()=>{for(let h of p)h()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(h){if(h instanceof oe)return;throw h}}}}_observeReactive(e,n){let r=n.tiers,s=r!=null?new Set(r):null,o=n.reactiveName??"observe";return Te(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let b={events:a.slice(),flushedAt_ns:X()};a.length=0,i.emit(b)},p={...n,reactive:!1,structured:!0,timeline:!0},h=e!=null?this.observe(e,p):this.observe(p),f=b=>{u||(a.push(b),!d&&(d=!0,Le(()=>{d=!1,c()})))};for(let b of h.events)f(b);let l=h.onEvent(f);return()=>{u=!0,l(),h.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[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,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=n.maxEvents,p=c!=null&&c>0?new qe(c):null,h=[],f=new Set,l=n.tiers!=null?new Set(n.tiers):null,b={},m=new Set,w=0,T=0,y=0,_=0,E=0,N=0,g=!1,v=!1,x=0,D=new Map,k=new Map,A=new Map,R=S=>{if(!(l!=null&&!l.has(S.type))){p?p.push(S):h.push(S);for(let L of f)L(S)}},C=S=>l==null||l.has(S),j=()=>s?{timestamp_ns:X(),in_batch:je(),batch_id:x}:{},U=(S,L)=>{if(!(!u||!(S instanceof B)))return S._setInspectorHook(J=>{if(J.kind==="dep_message")D.set(S,J.depIndex);else if(J.kind==="run"){let me=J.batchData.map((O,M)=>O!=null&&O.length>0?O.at(-1):J.prevData[M]);k.set(S,me);let Z=J.batchData.map(O=>O!=null?[...O]:void 0);A.set(S,Z),i&&R({type:"derived",path:L,dep_values:me,dep_batches:Z,...j()})}})},ie=S=>{let L=D.get(S),J=k.get(S);if(!o||J==null)return{};let Z=(L!=null&&L>=0&&S instanceof B?S._deps[L]:void 0)?.node,O=Z?.v,M=A.get(S);return{trigger_dep_index:L,trigger_dep_name:Z?.name,...O!=null?{trigger_version:{id:O.id,version:O.version}}:{},dep_values:[...J],...M!=null?{dep_batches:M}:{}}},Ae=[],ze=[];for(let[S,L]of e){let J=U(L,S);J&&Ae.push(J),ze.push(L.subscribe(me=>{x++;for(let Z of me){let O=Z[0],M=j();if(O===I){b[S]=Z[1];let z=L instanceof B?L.lastMutation?.actor??$e:$e;R({type:"data",path:S,data:Z[1],actor:z,...M,...ie(L)})}else if(a)O===q?C("dirty")&&w++:O===Y?C("resolved")&&T++:O===re?C("invalidate")&&y++:O===ae?C("pause")&&_++:O===fe?C("resume")&&E++:O===W?C("teardown")&&N++:O===P&&!m.has(S)?C("complete")&&(g=!0):O===G&&C("error")&&(v=!0,m.add(S));else if(O===q)C("dirty")&&w++,R({type:"dirty",path:S,...M});else if(O===Y)C("resolved")&&T++,R({type:"resolved",path:S,...M,...ie(L)});else if(O===re)C("invalidate")&&y++,R({type:"invalidate",path:S,...M});else if(O===ae)C("pause")&&_++,R({type:"pause",path:S,lockId:Z[1],...M});else if(O===fe)C("resume")&&E++,R({type:"resume",path:S,lockId:Z[1],...M});else if(O===P)C("complete")&&!m.has(S)&&(g=!0),R({type:"complete",path:S,...M});else if(O===G){C("error")&&(v=!0,m.add(S));let z=L instanceof B?L.lastMutation?.actor??$e:$e;R({type:"error",path:S,data:Z[1],actor:z,...M})}else O===W&&(C("teardown")&&N++,R({type:"teardown",path:S,...M}))}}))}let xe=!1,Ne=()=>{if(!xe){xe=!0;for(let S of ze)S();for(let S of Ae)S();for(let S of ge)S({value:void 0,done:!0});ge.length=0}},Oe=[],ge=[];f.add(S=>{let L=ge.shift();L?L({value:S,done:!1}):Oe.push(S)});let Ce={get values(){return b},get dirtyCount(){return w},get resolvedCount(){return T},get invalidateCount(){return y},get pauseCount(){return _},get resumeCount(){return E},get teardownCount(){return N},get events(){return p?p.toArray():[...h]},get anyCompletedCleanly(){return g},get anyErrored(){return v},get completedWithoutErrors(){return g&&!v},onEvent(S){return f.add(S),()=>f.delete(S)},dispose:Ne,expand(S){Ne();let L={...n};return typeof S=="string"?L.detail=S:Object.assign(L,S),r(Ln(L))},[Symbol.asyncIterator](){return{next(){return Oe.length>0?Promise.resolve({value:Oe.shift(),done:!1}):xe?Promise.resolve({value:void 0,done:!0}):new Promise(S=>ge.push(S))},return(){return Ne(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(Ce,n),Ce}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(l=>console.log(l)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=po(n.theme),u=r==="stage-log"?X():0,c=l=>l==null?"":n.stageLabels?.[l]??l,p=(l,b)=>l.length>b?`${l.slice(0,b-1)}\u2026`:l,h=l=>l.type==="data"||l.type==="error"?p(yt(l.data),120):"",f=l=>{if(r==="stage-log"){let g=(X()-u)/1e9,v=c(l.path).padEnd(9);if(l.type==="data"){let x=h(l);return`[${g.toFixed(3)}s] ${v} \u2190${x?` ${x}`:""}`}if(l.type==="error"){let x=h(l);return`[${g.toFixed(3)}s] ${v} \u2717${x?` ${x}`:""}`}return l.type==="complete"?`[${g.toFixed(3)}s] ${v} \u25A0 complete`:`[${g.toFixed(3)}s] ${v} ${l.type}`}if(r==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let b=d[l.type]??"",m=l.path?`${d.path}${l.path}${d.reset} `:"",w=l.type==="data"||l.type==="error",T=l.type==="pause"||l.type==="resume",y=w?` ${yt(l.data)}`:T?` ${yt(l.lockId)}`:"",_=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,E=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",N=l.in_batch?" [batch]":"";return`${m}${b}${l.type.toUpperCase()}${d.reset}${y}${E}${N}`};e.onEvent(l=>{a(l.type)&&s(f(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Gn(this._disposers,this.name),this.signal([[W]],{internal:!0}),Gn(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"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];s[a]=c}let o=[...r.subgraphs].sort(),i={...r,version:1,nodes:s,subgraphs:o};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 Qt(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Fe,{codec:s,codecVersion:o,payload:i}=en(e,r);return s.decode(i,o)}restore(e,n){if(In(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(o=>bt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){In(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let f of[...e.subgraphs].sort((l,b)=>{let m=l.split(V).length,w=b.split(V).length;return m!==w?m-w:l<b?-1:l>b?1:0})){let l=f.split(V),b=o;for(let m of l)b._mounts.has(m)||b.mount(m,new t(m)),b=b._mounts.get(m)}let i=s?Object.entries(s).map(([f,l])=>({re:bt(f),factory:l})):[],a=f=>{for(let l of i)if(l.re.test(f))return l.factory},d=f=>{let l=f.split(V),b=l.pop();if(b==null||b.length===0)throw new Error(`invalid snapshot path "${f}"`);let m=o;for(let w of l){let T=m._mounts.get(w);if(!T)throw new Error(`unknown mount "${w}" in path "${f}"`);m=T}return[m,b]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${V}${se}${V}`)).sort((f,l)=>f[0]<l[0]?-1:f[0]>l[0]?1:0),c=new Map(u),p=new Map,h=!0;for(;c.size>0&&h;){h=!1;for(let[f,l]of[...c.entries()]){let b=l?.deps??[];if(!b.every(E=>p.has(E)))continue;let[m,w]=d(f),T={...l?.meta??{}},y=a(f),_;if(l?.type==="state")_=$(l.value,{meta:T});else{if(y==null)continue;_=y(w,{path:f,type:l.type,value:l.value,meta:T,deps:b,resolvedDeps:b.map(E=>p.get(E))})}m.add(_,{name:w}),p.set(f,_),c.delete(f),h=!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 o.restore(e),o}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 s=(u,c)=>{if(u.disposed)return;let p=eo(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let h=u.seq+1,f=Qe(),m=u.lastSnapshot==null||h%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:h,timestamp_ns:f,format_version:De}:{name:this.name,mode:"diff",diff:Hn(u.lastSnapshot,c),seq:h,timestamp_ns:f,format_version:De};if(u.tier.filter&&!u.tier.filter(m))return;let w;try{w=u.tier.save(m)}catch(T){n.onError?.(T,u.tier);return}if(w&&typeof w.then=="function"){let _=(u.savePending??Promise.resolve()).then(()=>w,()=>w).then(()=>{u.disposed||(u.seq=h,u.lastSnapshot=c,u.lastFingerprint=p)},E=>{n.onError?.(E,u.tier)});u.savePending=_.finally(()=>{u.savePending===_&&(u.savePending=void 0)})}else u.seq=h,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){n.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let b=this.config.messageTier(l[0]);return b>=3&&b<5}))return;if(n.filter){let l=this.tryResolve(u);if(l==null)return;let b=Mt(l,ut("standard"));if(!n.filter(u,b))return}let h,f=()=>(h==null&&(h=this.snapshot()),h);for(let l of r)l.disposed||(l.debounceMs===0?o(l,f()):(l.timer==null&&(l.timer=new ct),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(p=>{let h=this.tryResolve(p);return h==null?()=>{}:h.subscribe(f=>i(p,f))});a=()=>{for(let p of c)p()}}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 s;try{s=await r.load?.()}catch(i){n?.(i,r);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===De&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load?.()}catch(d){r?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===De&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}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 s={path:e,annotation:n,timestamp_ns:X(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(s)}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(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(T=>!r.has(T)).sort(),i=[...r].filter(T=>!s.has(T)).sort(),a=[],d=[];for(let T of r){if(!s.has(T))continue;let y=e.nodes[T],_=n.nodes[T],E=y.v,N=_.v;E!=null&&N!=null&&E.id===N.id&&E.version!==N.version&&d.push({path:T,id:E.id,from:E.version,to:N.version});let g=E!=null&&N!=null&&E.id===N.id&&E.version===N.version;for(let v of["type","status","sentinel"]){let x=y[v],D=_[v];x!==D&&a.push({path:T,field:v,from:x,to:D})}if(!g)for(let v of["value","meta"]){let x=y[v],D=_[v];to(x,D)||a.push({path:T,field:v,from:x,to:D})}}let u=T=>`${T.from} ${T.to}`,c=new Set(e.edges.map(u)),p=new Set(n.edges.map(u)),h=n.edges.filter(T=>!c.has(u(T))),f=e.edges.filter(T=>!p.has(u(T))),l=new Set(e.subgraphs),b=new Set(n.subgraphs),m=[...b].filter(T=>!l.has(T)).sort(),w=[...l].filter(T=>!b.has(T)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:h,edgesRemoved:f,subgraphsAdded:m,subgraphsRemoved:w}}};function Hn(t,e){let n=ce.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function zt(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[y,_]of Object.entries(t.nodes)){if(!y)continue;c.add(y);let E=_.deps??[];i.set(y,E);for(let N of E)N&&(c.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(y))}for(let y of t.edges){if(y==null||typeof y!="object")continue;let _=typeof y.from=="string"?y.from:"",E=typeof y.to=="string"?y.to:"";!_||!E||(c.add(_),c.add(E),u.has(_)||u.set(_,new Set),u.get(_).add(E),d.has(E)||d.set(E,new Set),d.get(E).add(_))}if(!c.has(e))return r.withDetail?s:[];let p=r.both===!0,h=y=>{if(p){let g=i.get(y)??[],v=d.get(y),x=a.get(y),D=u.get(y),k=[...g];return v&&k.push(...v),x&&k.push(...x),D&&k.push(...D),k}if(n==="upstream"){let g=i.get(y)??[],v=d.get(y);return v?[...g,...v]:g}let _=a.get(y),E=u.get(y),N=_?[..._]:[];return E&&N.push(...E),N},f=new Set([e]),l=new Map,b=[{path:e,depth:0}],m=0,w=!1;for(;m<b.length;){let y=b[m++];if(o!=null&&y.depth>=o){h(y.path).length>0&&(w=!0);continue}for(let _ of h(y.path))!_||f.has(_)||(f.add(_),l.set(_,y.depth+1),b.push({path:_,depth:y.depth+1}))}let T=[...l.keys()].sort((y,_)=>y<_?-1:y>_?1:0);return r.withDetail?{paths:T,depths:l,truncated:w}:T}function bo(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}st();Pe();Ke();pe();Ve();he();Pe();pe();he();Ve();var Bt=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),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];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),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+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 o=0;o<n;o++)this._buf[o]=void 0;this._head=0;let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];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 Ye(t){return t.subscribe(()=>{})}var yo=64;function jn(t,e={}){let{name:n,maxSize:r,versioning:s,guard:o,backend:i}=e,a=i??new Bt(t,r),d=$(a.toArray(),{name:n,describeKind:"state",equals:(g,v)=>g===v,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let g=a.toArray();ue(()=>{d.down([[q]],{internal:!0}),d.down([[I,g]],{internal:!0})})}let c=new Map,p=new Map,h=new Map;function f(g,v){return`${g}:${v===void 0?"END":v}`}function l(g){if(g.size<yo)return;let v=g.keys().next();if(v.done)return;let x=g.get(v.value);x!==void 0&&x.dispose(),g.delete(v.value)}function b(g){let v=a.version;try{return g()}finally{a.version!==v&&u()}}function m(g){if(!Number.isInteger(g)||g<0)throw new RangeError(`tail: n must be a non-negative integer (got ${g})`);let v=c.get(g);if(v!==void 0)return c.delete(g),c.set(g,v),v.node;l(c);let x=F([d],([k])=>{let A=k;return g===0||A.length===0?[]:A.slice(Math.max(0,A.length-g))},{initial:a.tail(g),describeKind:"derived"}),D=Ye(x);return c.set(g,{node:x,dispose:D}),x}function w(g,v){if(!Number.isInteger(g)||g<0)throw new RangeError(`slice: start must be a non-negative integer (got ${g})`);if(v!==void 0&&(!Number.isInteger(v)||v<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${v})`);let x=f(g,v),D=p.get(x);if(D!==void 0)return p.delete(x),p.set(x,D),D.node;l(p);let k=F([d],([R])=>{let C=R;return v===void 0?C.slice(g):C.slice(g,v)},{initial:a.slice(g,v),describeKind:"derived"}),A=Ye(k);return p.set(x,{node:k,dispose:A}),k}function T(g){let v=h.get(g);if(v!==void 0)return v.node;let x=F([d,g],([k,A])=>{let R=k,C=Math.max(0,Math.trunc(A??0));return R.slice(C)},{initial:[],describeKind:"derived"}),D=Ye(x);return h.set(g,{node:x,dispose:D}),x}let y,_;function E(){y===void 0&&(y=te([d],(g,v,x)=>{let D=g[0],A=D!=null&&D.length>0?D.at(-1):x.prevData[0];if(A==null||A.length===0){v.down([[Y]]);return}v.emit(A[A.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=F([d],([g])=>g.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Ye(y),Ye(_))}let N={entries:d,get size(){return a.size},at(g){return a.at(g)},append(g){b(()=>a.append(g))},appendMany(g){g.length!==0&&b(()=>a.appendMany(g))},clear(){b(()=>a.clear())},trimHead(g){b(()=>a.trimHead(g))},withLatest(){return E(),d},get lastValue(){return E(),y},get hasLatest(){return E(),_},view(g){switch(g.kind){case"tail":return m(g.n);case"slice":return w(g.start,g.stop);case"fromCursor":return T(g.cursor)}},attach(g){let v=g.subscribe(x=>{for(let D of x)D[0]===I&&N.append(D[1])});return()=>v()},attachStorage(g){if(g.length===0)return()=>{};let v=new Map;for(let D of g)v.set(D,a.size);(async()=>{for(let D of g)if(typeof D.loadEntries=="function")try{let k=await Promise.resolve(D.loadEntries());k.entries.length>0&&a.size===0&&(a.restore(k.entries),v.set(D,k.entries.length),u());break}catch{}})();let x=d.subscribe(D=>{for(let k of D){if(k[0]!==I)continue;let A=k[1];for(let R of g){let C=v.get(R)??0;if(A.length<C){try{let U=R.appendEntries(A);U instanceof Promise&&U.catch(()=>{})}catch{}v.set(R,A.length);continue}if(A.length===C)continue;let j=A.slice(C);v.set(R,A.length);try{let U=R.appendEntries(j);U instanceof Promise&&U.catch(()=>{})}catch{}}}});return()=>x()},disposeAllViews(){for(let g of c.values())g.dispose();c.clear();for(let g of p.values())g.dispose();p.clear();for(let g of h.values())g.dispose();h.clear()},dispose(){for(let g of c.values())g.dispose();c.clear();for(let g of p.values())g.dispose();p.clear();for(let g of h.values())g.dispose();h.clear()}};return N}dt();function Un(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Je(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Xe(t,e){return Un("messaging",t,e)}var vo=1024,Ht=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=jn([],{name:"events",maxSize:n.retainedLimit??vo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=F([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:Xe("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(de(this.latest)),this.hasLatest=F([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Xe("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(de(this.hasLatest)),this.addDisposer(()=>{this.events.down([[P]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},jt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let s;if(r.from!==void 0?r.from==="retained"?s=0:r.from==="now"?s=n.events.cache.length:s=Je(r.from,"subscription from"):s=Je(r.cursor??0,"subscription cursor"),this.cursor=$(s,{name:"cursor",describeKind:"state",meta:Xe("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(de(this.available)),r.advanceOn!==void 0){let o=r.advanceOn,i=!1,a=te([o],()=>{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:Xe("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(de(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:Je(e,"subscription ack count"),s=Math.min(r,n.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:Je(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:Je(e,"subscription pullAndAck limit"),s=n.slice(0,r);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[P]]),this.destroy())}};var Ut=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()}},Wt=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=$(0,{name:"version",describeKind:"state",meta:Xe("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new Ut(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}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 s={...this._defaultTopicOptions,...n??{}};r=new Ht(e,s),this._registry.set(e,r),this.mount(e,r);let o=this.version.cache??0;this.version.emit(o+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){ue(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new jt(e,s,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function Wn(t,e){return new Wt(t,e)}function To(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 Kn(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=Kt(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function Kt(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 wo(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=To(r.dataset)?r.dataset:$(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=$(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=$(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=$(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=$([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=$(!1,{name:"paused"});o.add(p,{name:"paused"});let h=$("running",{name:"status"});o.add(h,{name:"status"});let f=$([],{name:"history",equals:()=>!1});o.add(f,{name:"history"});let l=$(null,{name:"best"});o.add(l,{name:"best"});let b=$(Number.NEGATIVE_INFINITY,{name:"score"});o.add(b,{name:"score"});let m=$(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let w=Wn("stages");o.mount("stages",w);let T=w.topic("generate"),y=w.topic("evaluate"),_=w.topic("analyze"),E=w.topic("decide"),N=n,g=null,v=[];o.addDisposer(d.subscribe(O=>{for(let M of O)M[0]===I&&(N=M[1])})),o.addDisposer(u.subscribe(O=>{for(let M of O)M[0]===I&&(g=M[1])})),o.addDisposer(c.subscribe(O=>{for(let M of O)M[0]===I&&(v=M[1])}));let x=hn(a,O=>{let M=N,z=O===0||g==null;return te([],(K,Q)=>{let be=!1;try{let ye=z?M.seed(t):M.generate(g,v);if(ye instanceof Promise)return ye.then(Me=>{be||Q.emit(Me)},Me=>{be||Q.down([[G,Me]])}),()=>{be=!0};Q.emit(ye)}catch(ye){be=!0,Q.down([[G,ye]])}},{describeKind:"producer"})},{name:"candidates"});o.add(x,{name:"candidates"});let D=we([x],(O,M,z)=>{let K=z.terminalDeps[0];K!==void 0&&K!==!0&&h.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(D,{name:"error-watcher"}),o.addDisposer(D.subscribe(()=>{}));let k=F([x,a],([O,M])=>({iteration:M,candidates:O,timestamp_ns:X()}),{name:"generate-event"});o.add(k,{name:"generate-event"}),o.addDisposer(k.subscribe(()=>{}));let A=we([k],([O])=>{T.publish(O)},{name:"generate-publish"});o.add(A,{name:"generate-publish"}),o.addDisposer(A.subscribe(()=>{}));let R=we([x],([O])=>{c.emit(O)},{name:"generate-mirror"});o.add(R,{name:"generate-mirror"}),o.addDisposer(R.subscribe(()=>{}));let C=e(x,i);o.add(C,{name:"scores"});let j=F([C,x,a],([O,M,z])=>({iteration:z,candidates:M,scores:O,timestamp_ns:X()}),{name:"evaluate-event"});o.add(j,{name:"evaluate-event"}),o.addDisposer(j.subscribe(()=>{}));let U=we([j],([O])=>{y.publish(O)},{name:"evaluate-publish"});o.add(U,{name:"evaluate-publish"}),o.addDisposer(U.subscribe(()=>{}));let ie=F([C,x],([O,M])=>N.analyze(O,M),{name:"feedback"});o.add(ie,{name:"feedback"});let Ae=F([ie,x,a],([O,M,z])=>({iteration:z,candidates:M,feedback:O,timestamp_ns:X()}),{name:"analyze-event"});o.add(Ae,{name:"analyze-event"}),o.addDisposer(Ae.subscribe(()=>{}));let ze=we([Ae],([O])=>{_.publish(O)},{name:"analyze-publish"});o.add(ze,{name:"analyze-publish"}),o.addDisposer(ze.subscribe(()=>{}));let xe=F([f],([O])=>{let M=O;if(r.patience==null||M.length<=r.patience)return!1;let z=M.slice(-(r.patience+1)),K=z[0].bestScore;return z.slice(1).every(Q=>Q.bestScore<=K)},{name:"patience-check"});o.add(xe,{name:"patience-check"});let Ne=F([b],([O])=>r.minScore!=null&&O>=r.minScore,{name:"min-score-check"});o.add(Ne,{name:"min-score-check"});let Oe=F([f],([O])=>{let M=O;if(r.minDelta==null||M.length<2)return!1;let z=M[M.length-2].bestScore,K=M[M.length-1].bestScore;return Math.abs(K-z)<r.minDelta},{name:"min-delta-check"});o.add(Oe,{name:"min-delta-check"});let ge=F([m],([O])=>r.maxEvaluations!=null&&O>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(ge,{name:"max-evaluations-check"});let Ce=F([a],([O])=>r.maxIterations!=null&&O>=r.maxIterations,{name:"max-iterations-check"});o.add(Ce,{name:"max-iterations-check"});let S=F([m],([O])=>r.budget!=null&&O>=r.budget,{name:"budget-exhausted-check"});o.add(S,{name:"budget-exhausted-check"}),o.addDisposer(xe.subscribe(()=>{})),o.addDisposer(Ne.subscribe(()=>{})),o.addDisposer(Oe.subscribe(()=>{})),o.addDisposer(ge.subscribe(()=>{})),o.addDisposer(Ce.subscribe(()=>{})),o.addDisposer(S.subscribe(()=>{}));let L=F([xe,Ne,Oe,ge,Ce],([O,M,z,K,Q])=>O?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:z?{converged:!0,reason:"min-delta"}:K?{converged:!0,reason:"max-evaluations"}:Q?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(L,{name:"converged"}),o.addDisposer(L.subscribe(()=>{}));let J=-1,me=we([ie,C,x],([O,M,z])=>{let K=a.cache,Q=O,be=z,ye=M;if(K<=J)return;J=K;let{best:Me,bestScore:qn}=Kn(be,ye),Yn=f.cache,Jn={n:K,candidates:be,scores:ye,feedback:Q,best:Me,bestScore:qn,timestamp_ns:X()},ve=[...Yn,Jn],vt=m.cache+be.length,ne="continue",Ee,Xn=r.budget!=null&&vt>=r.budget,Zn=p.cache;if(Xn)ne="budget",Ee="budget";else if(r.minScore!=null&&Q.score>=r.minScore)ne="converged",Ee="min-score";else if(r.maxIterations!=null&&K>=r.maxIterations)ne="converged",Ee="max-iterations";else if(r.maxEvaluations!=null&&vt>=r.maxEvaluations)ne="converged",Ee="max-evaluations";else if(r.minDelta!=null&&ve.length>=2){let Ze=ve[ve.length-2].bestScore,Tt=ve[ve.length-1].bestScore;Math.abs(Tt-Ze)<r.minDelta&&(ne="converged",Ee="min-delta")}else if(r.patience!=null&&ve.length>r.patience){let Ze=ve.slice(-(r.patience+1)),Tt=Ze[0].bestScore;Ze.slice(1).every(Qn=>Qn.bestScore<=Tt)&&(ne="converged",Ee="patience")}ne==="continue"&&Zn&&(ne="paused"),ue(()=>{l.emit(Me),b.emit(Q.score),f.emit(ve),m.emit(vt),u.emit(Q),E.publish({iteration:K,decision:ne,reason:Ee,timestamp_ns:X()}),ne==="continue"?a.emit(K+1):h.emit(ne==="converged"?"converged":ne==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(me,{name:"decide-bridge"}),o.addDisposer(me.subscribe(()=>{})),Object.assign(o,{best:l,score:b,status:h,history:f,strategy:d,iteration:a,generate:T,evaluate:y,analyze:_,decide:E,setStrategy(O){d.emit(O)},pause(){p.emit(!0)},resume(){h.cache==="paused"&&ue(()=>{p.emit(!1),h.emit("running"),a.emit(a.cache+1)})}})}function _o(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,s){let o=Kt(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${o.toFixed(3)}, n=${r.length}`,score:o,weakTasks:i?[i.taskId]:[]}},async generate(r,s){if(s.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=s[s.length-1],i=0,d={prior:o,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 xo(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function No(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
8
8
  ${t.map(r=>{let s=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${s}`}).join(`
9
- `)}`}function yo(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,s=t.formatCritique??bo;return{name:n,seed(o){return[o]},analyze(o,i){let a=jt(o),d=typeof t.failureThreshold=="function"?t.failureThreshold(o):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),l=d??a,f=u?[...o].sort((b,T)=>b.score-T.score):o.filter(b=>b.score<l).slice().sort((b,T)=>b.score-T.score),h=f.slice(0,r),{best:p,bestScore:c}=zn(i,o),g={summary:"",score:a,weakTasks:h.map(b=>b.taskId)},v=s(h,g),w={kind:"errorCritique",best:p,failures:h,critiqueText:v},x=f.length>h.length?` (top ${h.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${f.length}${x}/${o.length}, bestScore=${c.toFixed(3)}`,critique:w,weakTasks:h.map(b=>b.taskId),score:a}},async generate(o,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=go(o.critique)?o.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??o.summary,l=a?.failures??[],f=0,p={prior:d,critique:u,failures:l,reportCost:c=>{f+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(p)));let c=[];for(let g=0;g<e;g++)c.push(await t.teacher(p));return c}finally{if(t.tokens!=null&&f>0){let c=t.tokens.cache??0;t.tokens.emit(c+f)}}}}}0&&(module.exports={blindVariation,errorCritique,refineLoop});
9
+ `)}`}function Oo(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,s=t.formatCritique??No;return{name:n,seed(o){return[o]},analyze(o,i){let a=Kt(o),d=typeof t.failureThreshold=="function"?t.failureThreshold(o):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,p=u?[...o].sort((y,_)=>y.score-_.score):o.filter(y=>y.score<c).slice().sort((y,_)=>y.score-_.score),h=p.slice(0,r),{best:f,bestScore:l}=Kn(i,o),b={summary:"",score:a,weakTasks:h.map(y=>y.taskId)},m=s(h,b),w={kind:"errorCritique",best:f,failures:h,critiqueText:m},T=p.length>h.length?` (top ${h.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${p.length}${T}/${o.length}, bestScore=${l.toFixed(3)}`,critique:w,weakTasks:h.map(y=>y.taskId),score:a}},async generate(o,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=xo(o.critique)?o.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??o.summary,c=a?.failures??[],p=0,f={prior:d,critique:u,failures:c,reportCost:l=>{p+=l}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let l=[];for(let b=0;b<e;b++)l.push(await t.teacher(f));return l}finally{if(t.tokens!=null&&p>0){let l=t.tokens.cache??0;t.tokens.emit(l+p)}}}}}0&&(module.exports={blindVariation,errorCritique,refineLoop});