@graphrefly/graphrefly 0.35.0 → 0.37.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 (193) hide show
  1. package/dist/{chunk-EUE7ELFQ.js → chunk-2C4NESZE.js} +1 -1
  2. package/dist/{chunk-PIIUJIF7.js → chunk-4EATTNAE.js} +1 -1
  3. package/dist/chunk-B4L5X2QO.js +7 -0
  4. package/dist/{chunk-YV2A2VWG.js → chunk-C5CBVOCB.js} +1 -1
  5. package/dist/{chunk-J6TGRQUP.js → chunk-CZIQ6JCE.js} +1 -1
  6. package/dist/chunk-FJ6IEMOS.js +1 -0
  7. package/dist/{chunk-T7GWBGOO.js → chunk-FMI4CWFL.js} +1 -1
  8. package/dist/{chunk-RRFOCAH6.js → chunk-G6Q3DUMJ.js} +1 -1
  9. package/dist/{chunk-CD4CB6S7.js → chunk-GDDPCDLG.js} +1 -1
  10. package/dist/{chunk-3OT7K33Q.js → chunk-GFOT6UBB.js} +1 -1
  11. package/dist/{chunk-53XJ2S6D.js → chunk-K2WYIVHM.js} +1 -1
  12. package/dist/{chunk-5XZRCS2M.js → chunk-K6ZFJ473.js} +1 -1
  13. package/dist/{chunk-E5YSBQSF.js → chunk-KTWBUJO5.js} +1 -1
  14. package/dist/{chunk-RLMYS3XZ.js → chunk-KUVDFOJH.js} +1 -1
  15. package/dist/{chunk-XMDNNSMK.js → chunk-LOQRPP4Y.js} +1 -1
  16. package/dist/{chunk-2Y3DKIZL.js → chunk-MC5LZG3U.js} +1 -1
  17. package/dist/{chunk-M5UC63ZI.js → chunk-NKKUUKPD.js} +1 -1
  18. package/dist/{chunk-GWOKTENT.js → chunk-QKBCTKH7.js} +1 -1
  19. package/dist/{chunk-YOUAVGHJ.js → chunk-QP5TH523.js} +1 -1
  20. package/dist/{chunk-T6RPUERH.js → chunk-QWVQIL3T.js} +1 -1
  21. package/dist/{chunk-6G5YD37E.js → chunk-T4U24DXX.js} +1 -1
  22. package/dist/{chunk-W2ZU226Q.js → chunk-TFK4P4CX.js} +1 -1
  23. package/dist/{chunk-PVUTRA5K.js → chunk-TLS7M7H4.js} +1 -1
  24. package/dist/{chunk-BGEY3PXH.js → chunk-U3COB5WU.js} +1 -1
  25. package/dist/{chunk-UAMWD4GG.js → chunk-UODQF4EY.js} +1 -1
  26. package/dist/{chunk-U347KVM4.js → chunk-WGST56ZH.js} +1 -1
  27. package/dist/{chunk-XINLP35X.js → chunk-WSLN4JFO.js} +1 -1
  28. package/dist/{chunk-ZGVA2SR5.js → chunk-XIJKEXWR.js} +1 -1
  29. package/dist/{chunk-JUJEPZOI.js → chunk-YVYSO5CW.js} +1 -1
  30. package/dist/compat/index.cjs +9 -9
  31. package/dist/compat/index.d.cts +6 -6
  32. package/dist/compat/index.d.ts +6 -6
  33. package/dist/compat/index.js +1 -1
  34. package/dist/compat/nestjs/index.cjs +11 -11
  35. package/dist/compat/nestjs/index.d.cts +4 -4
  36. package/dist/compat/nestjs/index.d.ts +4 -4
  37. package/dist/compat/nestjs/index.js +1 -1
  38. package/dist/compat/zustand/index.cjs +7 -7
  39. package/dist/compat/zustand/index.d.cts +2 -2
  40. package/dist/compat/zustand/index.d.ts +2 -2
  41. package/dist/compat/zustand/index.js +1 -1
  42. package/dist/extra/index.cjs +17 -17
  43. package/dist/extra/index.d.cts +3 -3
  44. package/dist/extra/index.d.ts +3 -3
  45. package/dist/extra/index.js +1 -1
  46. package/dist/extra/reactive.cjs +1 -1
  47. package/dist/extra/reactive.d.cts +1 -1
  48. package/dist/extra/reactive.d.ts +1 -1
  49. package/dist/extra/reactive.js +1 -1
  50. package/dist/graph/index.cjs +7 -7
  51. package/dist/graph/index.d.cts +3 -3
  52. package/dist/graph/index.d.ts +3 -3
  53. package/dist/graph/index.js +1 -1
  54. package/dist/{graph-kTltt95s.d.cts → graph-CaNXUc3c.d.cts} +26 -1
  55. package/dist/{graph-Cv-8x0ZI.d.ts → graph-YQXDndFy.d.ts} +26 -1
  56. package/dist/{index-KNAMYngu.d.ts → index-0qOD-421.d.ts} +2 -2
  57. package/dist/{index-CfOSES72.d.cts → index-4IwO4mH2.d.cts} +5 -5
  58. package/dist/{index-CAIhFfws.d.ts → index-9mbs_PIG.d.ts} +2 -2
  59. package/dist/{index-Bilohojo.d.ts → index-Ae6L8liv.d.ts} +2 -2
  60. package/dist/{index-BhkPzu-Z.d.cts → index-B1IcU--K.d.cts} +2 -2
  61. package/dist/{index-DzgS5uYi.d.ts → index-B46GWgk3.d.ts} +1 -1
  62. package/dist/{index-BpFwRAf9.d.cts → index-B9qJmmv3.d.cts} +1 -1
  63. package/dist/{index-CI_yjtua.d.ts → index-BCq12BqB.d.ts} +1 -1
  64. package/dist/{index-zK_mN1D-.d.cts → index-BECJ8M0T.d.cts} +2 -2
  65. package/dist/{index-DFe2Pk2u.d.ts → index-BOfHwQc1.d.ts} +1 -1
  66. package/dist/{index-hXKhbfh-.d.ts → index-BhLA9feT.d.ts} +12 -7
  67. package/dist/{index-Dp69u0ym.d.ts → index-BmLkcDlj.d.ts} +6 -6
  68. package/dist/{index-XxSeddWP.d.cts → index-BokynmA4.d.cts} +1 -1
  69. package/dist/{index-BEvsFlfH.d.ts → index-Bpzw8hx3.d.ts} +2 -2
  70. package/dist/{index-PluovH45.d.cts → index-BwtIbzSV.d.cts} +2 -2
  71. package/dist/{index-BZ1V5GzX.d.ts → index-C-pFD_FV.d.ts} +2 -2
  72. package/dist/{index-Cot94_82.d.ts → index-C0tga1_x.d.ts} +2 -2
  73. package/dist/{index-BlRVj-7Q.d.cts → index-C4N-dg5U.d.cts} +2 -2
  74. package/dist/{index-B4s70vYf.d.ts → index-CKcnuQ2c.d.ts} +2 -2
  75. package/dist/{index-D7r_vd0b.d.cts → index-CLPQyYY5.d.cts} +3 -3
  76. package/dist/{index-BuMzxRO2.d.ts → index-CRycrNfn.d.ts} +1 -1
  77. package/dist/{index-DeyzuqAi.d.cts → index-CU3z8Cel.d.cts} +2 -2
  78. package/dist/{index-DwNNufVa.d.ts → index-CUTHDZ7Q.d.ts} +3 -3
  79. package/dist/{index-CGKs5ixV.d.cts → index-C_qi0WlF.d.cts} +12 -7
  80. package/dist/{index-BBdwz2BW.d.ts → index-CajEOoAN.d.ts} +2 -2
  81. package/dist/{index-CzC0G0C3.d.cts → index-Ci358GSC.d.cts} +2 -2
  82. package/dist/{index-BkbawFkI.d.cts → index-CkN8CZlT.d.cts} +6 -6
  83. package/dist/{index-ZhKyR8co.d.cts → index-CrpjECS6.d.cts} +2 -2
  84. package/dist/{index-C40wA8zt.d.ts → index-CzIWlnPp.d.ts} +5 -5
  85. package/dist/{index-C9xF16gc.d.ts → index-D0ZxFXYl.d.ts} +2 -2
  86. package/dist/{index-BtY2QVDf.d.cts → index-D11pGlaI.d.cts} +2 -2
  87. package/dist/{index-DlccEIi3.d.ts → index-D1E1tqHT.d.ts} +1 -1
  88. package/dist/{index-Qq-G9B6g.d.cts → index-D6pwWiOc.d.cts} +2 -2
  89. package/dist/{index-BsZlbHM5.d.cts → index-D6tRNEKz.d.cts} +1 -1
  90. package/dist/{index-B3Dfl5sS.d.cts → index-DAKm44My.d.cts} +2 -2
  91. package/dist/{index-BWH17rK_.d.cts → index-DCAuN9u5.d.cts} +1 -1
  92. package/dist/{index-BF-ssbJB.d.ts → index-DPqR3wdW.d.ts} +2 -2
  93. package/dist/{index-GaW6Welt.d.cts → index-DTYIRT_v.d.cts} +2 -2
  94. package/dist/{index-DXSLMoma.d.ts → index-DXz9uwcs.d.ts} +1 -1
  95. package/dist/{index-DmtWMP0X.d.cts → index-D_DThl_J.d.cts} +1 -1
  96. package/dist/{index-BwYGLgmI.d.ts → index-D_d1erkR.d.ts} +2 -2
  97. package/dist/{index-D9qoEOj_.d.cts → index-DbWwMWiB.d.cts} +1 -1
  98. package/dist/{index-D6JRP-1_.d.cts → index-DcWbx58m.d.cts} +2 -2
  99. package/dist/{index-DzYTXMBz.d.ts → index-DfAo9WKr.d.ts} +1 -1
  100. package/dist/{index-DXZsXxtU.d.cts → index-DqtXA3yX.d.cts} +2 -2
  101. package/dist/{index-DBmBtqAN.d.ts → index-DuhOdNyg.d.ts} +2 -2
  102. package/dist/{index-DKp1CIbG.d.cts → index-e1m3ZHgc.d.cts} +1 -1
  103. package/dist/{index-DSD6xnbT.d.ts → index-fHKHdAso.d.ts} +2 -2
  104. package/dist/index.cjs +41 -41
  105. package/dist/index.d.cts +29 -29
  106. package/dist/index.d.ts +29 -29
  107. package/dist/index.js +1 -1
  108. package/dist/patterns/ai/index.cjs +19 -19
  109. package/dist/patterns/ai/index.d.cts +7 -7
  110. package/dist/patterns/ai/index.d.ts +7 -7
  111. package/dist/patterns/ai/index.js +1 -1
  112. package/dist/patterns/audit/index.cjs +7 -7
  113. package/dist/patterns/audit/index.d.cts +4 -4
  114. package/dist/patterns/audit/index.d.ts +4 -4
  115. package/dist/patterns/audit/index.js +1 -1
  116. package/dist/patterns/cqrs/index.cjs +7 -7
  117. package/dist/patterns/cqrs/index.d.cts +3 -3
  118. package/dist/patterns/cqrs/index.d.ts +3 -3
  119. package/dist/patterns/cqrs/index.js +1 -1
  120. package/dist/patterns/demo-shell/index.cjs +8 -8
  121. package/dist/patterns/demo-shell/index.d.cts +3 -3
  122. package/dist/patterns/demo-shell/index.d.ts +3 -3
  123. package/dist/patterns/demo-shell/index.js +1 -1
  124. package/dist/patterns/domain-templates/index.cjs +7 -7
  125. package/dist/patterns/domain-templates/index.d.cts +2 -2
  126. package/dist/patterns/domain-templates/index.d.ts +2 -2
  127. package/dist/patterns/domain-templates/index.js +1 -1
  128. package/dist/patterns/graphspec/index.cjs +17 -17
  129. package/dist/patterns/graphspec/index.d.cts +2 -2
  130. package/dist/patterns/graphspec/index.d.ts +2 -2
  131. package/dist/patterns/graphspec/index.js +1 -1
  132. package/dist/patterns/guarded-execution/index.cjs +7 -7
  133. package/dist/patterns/guarded-execution/index.d.cts +5 -5
  134. package/dist/patterns/guarded-execution/index.d.ts +5 -5
  135. package/dist/patterns/guarded-execution/index.js +1 -1
  136. package/dist/patterns/harness/index.cjs +10 -10
  137. package/dist/patterns/harness/index.d.cts +7 -7
  138. package/dist/patterns/harness/index.d.ts +7 -7
  139. package/dist/patterns/harness/index.js +1 -1
  140. package/dist/patterns/job-queue/index.cjs +7 -7
  141. package/dist/patterns/job-queue/index.d.cts +3 -3
  142. package/dist/patterns/job-queue/index.d.ts +3 -3
  143. package/dist/patterns/job-queue/index.js +1 -1
  144. package/dist/patterns/lens/index.cjs +7 -7
  145. package/dist/patterns/lens/index.d.cts +3 -3
  146. package/dist/patterns/lens/index.d.ts +3 -3
  147. package/dist/patterns/lens/index.js +1 -1
  148. package/dist/patterns/memory/index.cjs +7 -7
  149. package/dist/patterns/memory/index.d.cts +2 -2
  150. package/dist/patterns/memory/index.d.ts +2 -2
  151. package/dist/patterns/memory/index.js +1 -1
  152. package/dist/patterns/messaging/index.cjs +7 -7
  153. package/dist/patterns/messaging/index.d.cts +3 -3
  154. package/dist/patterns/messaging/index.d.ts +3 -3
  155. package/dist/patterns/messaging/index.js +1 -1
  156. package/dist/patterns/orchestration/index.cjs +7 -7
  157. package/dist/patterns/orchestration/index.d.cts +3 -3
  158. package/dist/patterns/orchestration/index.d.ts +3 -3
  159. package/dist/patterns/orchestration/index.js +1 -1
  160. package/dist/patterns/process/index.cjs +1 -1
  161. package/dist/patterns/process/index.d.cts +4 -4
  162. package/dist/patterns/process/index.d.ts +4 -4
  163. package/dist/patterns/process/index.js +1 -1
  164. package/dist/patterns/reactive-layout/index.cjs +8 -8
  165. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  166. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  167. package/dist/patterns/reactive-layout/index.js +1 -1
  168. package/dist/patterns/reduction/index.cjs +7 -7
  169. package/dist/patterns/reduction/index.d.cts +2 -2
  170. package/dist/patterns/reduction/index.d.ts +2 -2
  171. package/dist/patterns/reduction/index.js +1 -1
  172. package/dist/patterns/refine-loop/index.cjs +8 -8
  173. package/dist/patterns/refine-loop/index.d.cts +4 -4
  174. package/dist/patterns/refine-loop/index.d.ts +4 -4
  175. package/dist/patterns/refine-loop/index.js +1 -1
  176. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  177. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  178. package/dist/patterns/resilient-pipeline/index.js +1 -1
  179. package/dist/patterns/surface/index.cjs +10 -10
  180. package/dist/patterns/surface/index.d.cts +3 -3
  181. package/dist/patterns/surface/index.d.ts +3 -3
  182. package/dist/patterns/surface/index.js +1 -1
  183. package/dist/{pipeline-graph-B85HUrWg.d.cts → pipeline-graph-BrrYGjuZ.d.cts} +2 -2
  184. package/dist/{pipeline-graph-HOTU4UG0.d.ts → pipeline-graph-DX2Twdj-.d.ts} +2 -2
  185. package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-BDdngW56.d.ts} +1 -1
  186. package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-DrGjuwyC.d.cts} +1 -1
  187. package/dist/{reactive-log-CgbNqksB.d.cts → reactive-log-ScpWyqny.d.cts} +11 -3
  188. package/dist/{reactive-log-ByBb8g6A.d.ts → reactive-log-jirQsxMY.d.ts} +11 -3
  189. package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-BI665P0L.d.ts} +1 -1
  190. package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-BkhmMg2a.d.cts} +1 -1
  191. package/package.json +1 -1
  192. package/dist/chunk-5KPIYVCC.js +0 -7
  193. package/dist/chunk-CUQFO6MT.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 Yn=Object.getOwnPropertyDescriptor;var Jn=Object.getOwnPropertyNames;var Xn=Object.prototype.hasOwnProperty;var re=(t,e)=>()=>(t&&(e=t(t=0)),e);var Zn=(t,e)=>{for(var n in e)wt(t,n,{get:e[n],enumerable:!0})},Qn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jn(e))!Xn.call(t,s)&&s!==n&&wt(t,s,{get:()=>e[s],enumerable:!(r=Yn(e,s))||r.enumerable});return t};var er=t=>Qn(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 tr()}}function tr(){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,J,$,G,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"),J=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),G=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([J]),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(nr)}var nr,Et,Yt,Ot=re(()=>{"use strict";nr={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(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(J,{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=rr.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,rr,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}},rr=["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 ir(t){let e=sr.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,b=new Uint32Array(64),x=(T,g)=>T>>>g|T<<32-g;for(let T=0;T<s;T+=64){for(let O=0;O<16;O++)b[O]=i.getUint32(T+O*4,!1);for(let O=16;O<64;O++){let k=b[O-15],S=b[O-2],C=x(k,7)^x(k,18)^k>>>3,U=x(S,17)^x(S,19)^S>>>10;b[O]=b[O-16]+C+b[O-7]+U>>>0}let g=a,v=d,E=u,w=l,m=f,y=h,_=p,R=c;for(let O=0;O<64;O++){let k=x(m,6)^x(m,11)^x(m,25),S=m&y^~m&_,C=R+k+S+or[O]+b[O]>>>0,U=x(g,2)^x(g,13)^x(g,22),B=g&v^g&E^v&E,ue=U+B>>>0;R=_,_=y,y=m,m=w+C>>>0,w=E,E=v,v=g,g=C+ue>>>0}a=a+g>>>0,d=d+v>>>0,u=u+E>>>0,l=l+w>>>0,f=f+m>>>0,h=h+y>>>0,p=p+_>>>0,c=c+R>>>0}let N=T=>T.toString(16).padStart(8,"0");return N(a)+N(d)+N(u)+N(l)+N(f)+N(h)+N(p)+N(c)}function St(t){let e=Rt(t??null),n=JSON.stringify(e);return ir(n).slice(0,16)}function ar(){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??ar();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 or,sr,nn=re(()=>{"use strict";or=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]),sr=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,ur,dr,Fe,H,an,Ct,me=re(()=>{"use strict";Ot();st();Pe();Qe();en();We();he();nn();rn=()=>{},on=100;ur=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},dr=(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:ur,onSubscribe:dr});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([[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!==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===J){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===G)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===P||s===Y)&&this._emit([n]),(s===$||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>on?(this._rerunDepth=0,this._emit([[G,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]===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]===J||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]===J))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 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===G){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===J&&(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([[G,s]])}return()=>{r=!0}},Mt(e))}function lr(t){return t!=null&&typeof t.then=="function"}function cr(t,e){let{signal:n,...r}=e??{};return De(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([[$]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[G,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},Mt(r))}function fr(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([[G,f]])})};return l(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},Mt(r))}function pr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function dn(t,e){if(pr(t))return t;if(lr(t))return cr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return fr(t,e);if(typeof n[Symbol.iterator]=="function")return un(t,e)}return hr(t)}function hr(...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 wo={};Zn(wo,{blindVariation:()=>bo,errorCritique:()=>To,refineLoop:()=>go});module.exports=er(wo);Pe();Qe();he();me();Ve();he();me();ut();function mr(t){return{describeKind:"derived",...t}}function gr(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]===G?(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=gr(dn(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{...mr(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 br(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function yr(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=br(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={...yr(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 vr={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"},Tr={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"?Tr:vr,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)_r(o,i,n,a);for(let a of t.boxes)wr(o,i,n,a,e.labelOf(a.id));return o.map(a=>Or(a.join(""))).join(`
2
+ `)}function wr(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 _r(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)xr(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=Nr(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=Er(i,o,n);a&&mn(t,e,o.x,o.y,a,"arrow")}function xr(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 Nr(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 Er(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 Or(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=kr(t);Rr(e),Sr(e),Dr(e),Ar(e,t);let n=Gr(e,t),{width:r,height:s}=Lr(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 kr(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 Rr(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 Sr(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 Dr(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 Ar(t,e){e.direction==="LR"?Cr(t,e):Mr(t,e)}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.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 Mr(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 b=t.nodes.get(o===0?c.fromId:c.toId);if(!b)continue;let x=n==="y"?b.y:b.x;h.push(x+Math.floor(r(b)/2))}if(h.length===0)continue;h.sort((c,b)=>c-b);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 Gr(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,b=Math.max(1,c-h+1),x=[];for(let y of l)for(let _ of y.out)x.push(_);x.sort((y,_)=>{let R=i(t.nodes.get(y.fromId)),O=i(t.nodes.get(_.fromId));if(R!==O)return R-O;let k=i(t.nodes.get(y.toId)),S=i(t.nodes.get(_.toId));return k-S});let N=[],T=new Map;for(let y of x){let _=i(t.nodes.get(y.fromId)),R=i(t.nodes.get(y.toId)),O=Math.min(_,R),k=Math.max(_,R),S=-1;for(let C=0;C<N.length;C+=1){let U=N[C],B=!0;for(let ue of U)if(ue.lo<=k&&O<=ue.hi){B=!1;break}if(B){U.push({lo:O,hi:k}),S=C;break}}S<0&&(N.push([{lo:O,hi:k}]),S=N.length-1),T.set(y,S)}let g=N.length,v=b>=Math.max(3,g+2),E=v?h+1:h,w=v?c-1:c,m=Math.max(1,w-E+1);for(let y of x){let _=T.get(y),R;if(g<=1)R=E+Math.floor(m/2);else{let O=(m-1)/(g-1);R=E+Math.floor(_*O)}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),b=t.nodes.get(p.toId),x=a.get(p),N=c.isVirtual?s(c):s(c)+o(c),T=b.isVirtual?s(b):s(b)-1,g=i(c),v=i(b);h===0&&pt(l,r,N,g),g!==v&&(pt(l,r,x,g),pt(l,r,x,v)),pt(l,r,T,v)}let f=u[0];d.push({from:f.chainFrom,to:f.chainTo,points:Ir(l)})}return d}function pt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Ir(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 Lr(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 Pr=24,$r=4,Fr=1,Vr=3;function _n(t,e){let n=zr(e.direction),r=Math.max(3,e.maxLabelWidth??Pr),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:()=>Vr,layerGap:$r,nodeGap:Fr,direction:n}),f=gn(l,{charset:s,labelOf:p=>d.get(p)??p}),h=e.logger;return h&&h(f),f}function zr(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=Br(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 b=t.nodes[f.path];b?.deps&&b.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 b=0;b<p.length;b++){let x=p[b];if(!x)continue;let N=c.get(x);N==null&&(N=[],c.set(x,N)),N.push(b)}for(let[b,x]of c)i.has(b)||(i.add(b),s.set(b,{from:f.path,depIndices:x}),o.push({path:b,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 Br(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=Hr(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 Hr(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: ${jr(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 jr(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},Ur=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+=Wr(o,e,n,r)}return s}function Wr(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+qr(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[Ur];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 qr(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),b=c instanceof H?c:null,x=b?kn(b.cache):0,N=b?b._sinkCount:0,T=p.deps?.length??0,g=p.type==="effect"&&N===0,v=N===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:x,subscriberCount:N,depCount:T,isOrphanEffect:g,orphanKind:v})}let d=a.reduce((h,p)=>h+p.valueSizeBytes,0),u=(h,p)=>[...a].sort(p??((c,b)=>b[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 Cn(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Kr(t){if(t!=null)return Cn(t)?t.cache:t}function Yr(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 Jr(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 b of h)if(r(p,b)){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 Xr(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Zr(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Qr(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Mn(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 Gn(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 eo(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 to(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 In(t,e){let n=Gn(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}["${Xr(i)}"]`)}for(let[i,a]of Mn(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
6
+ `)}function no(t,e){let n=In(t,e);return Ln(n)}function Ln(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 ro(t,e){let n=Gn(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: ${Qr(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${Zr(i)}"`)}for(let[i,a]of Mn(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
7
+ `)}function oo(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+=oo(r)}return e+="$",new RegExp(e)}var so={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"},io={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 ao(t){return t==="none"?io:t==="ansi"||t==null?so:{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 uo(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`);uo(t,e,n)}function lo(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 co(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 Pn(t){for(let e of t._mounts.values())Pn(e);for(let e of t._nodes.values())try{e.down([[J]],{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,Pn(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([[J]],{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([[G,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=lo(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=co(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=Kr(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[w,m]of a)d.set(m,w);let u=[];{let w=a.map(([,_])=>_),m=new Set(d.values()),y=0;for(;w.length>0;){let _=w.shift();if(_ instanceof H)for(let R of _._deps){let O=R.node;if(d.has(O))continue;let k=O.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(O,S),m.add(S),u.push([S,O]),w.push(O)}}}let l=[...a,...u],f={};for(let[w,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,...O}=y,k={...O,deps:_};if(!o){let S=this._annotations.get(w);S!=null&&(k.annotation=S)}if(r!=null)if(typeof r=="function"){let S=r;if(!(S.length>=2?S(w,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[w]=k}let h=new Set(Object.keys(f)),p=[];for(let[w,m]of l)if(m instanceof H)for(let y of m._deps){let _=d.get(y.node);_!=null&&p.push([_,w])}p.sort((w,m)=>w[0]<m[0]?-1:w[0]>m[0]?1:w[1]<m[1]?-1:w[1]>m[1]?1:0);let c=p.map(([w,m])=>({from:w,to:m}));(n!=null||r!=null)&&(c=c.filter(w=>h.has(w.from)&&h.has(w.to)));let b=this._collectSubgraphs(""),x=n!=null||r!=null?b.filter(w=>{let m=`${w}${V}`;return[...h].some(y=>y===w||y.startsWith(m))}):b,N=this,T=e,g={name:this.name,nodes:f,edges:c,subgraphs:x,expand(w){let m={...T,format:void 0};return Array.isArray(w)?(m.fields=w,m.detail=void 0):(m.detail=w,m.fields=void 0),N.describe(m)}},v=e??{},E=v.format;return E==="json"?eo(g,v):E==="pretty"?to(g,v):E==="mermaid"?In(g,v):E==="mermaid-url"?no(g,v):E==="d2"?ro(g,v):E==="ascii"?_n(g,v):g}_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(T=>{let g=T.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),f=[],h=new WeakSet,p=T=>{if(h.has(T)||d)return;h.add(T);let g=T.topology.subscribe(v=>{for(let E of v){if(E[0]!==P)continue;let w=E[1];if(u(),w.kind==="added"&&w.nodeKind==="mount"){let m=T._mounts.get(w.name);m!=null&&p(m)}}});f.push(g);for(let v of T._mounts.keys()){let E=T._mounts.get(v);E!=null&&p(E)}};p(this);let c,b=e.actor;Cn(b)&&(c=b.subscribe(T=>{let g=!1,v=!1;for(let E of T){let w=E[0];w===P?g=!0:(w===$||w===G||w===J)&&(v=!0)}g&&u(),v&&(c?.(),c=void 0,u())}));let x;try{x=F([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(T,g)=>T===g})}catch(T){l(),c?.();for(let g of f)g();throw i.dispose(),T}let N=ge(x);return{node:x,dispose(){d=!0,l(),c?.();for(let T of f)T();f.length=0,i.dispose(),N()}}}_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&&fo(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={},b=new Set,x=0,N=0,T=0,g=0,v=0,E=0,w=!1,m=!1,y=0,_=new Map,R=new Map,O=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(X=>{if(X.kind==="dep_message")_.set(D,X.depIndex);else if(X.kind==="run"){let ye=X.batchData.map((I,Q)=>I!=null&&I.length>0?I.at(-1):X.prevData[Q]);R.set(D,ye);let Z=X.batchData.map(I=>I!=null?[...I]:void 0);O.set(D,Z),i&&k({type:"derived",path:L,dep_values:ye,dep_batches:Z,...S()})}})},U=D=>{let L=_.get(D),X=R.get(D);if(!o||X==null)return{};let Z=(L!=null&&L>=0&&D instanceof H?D._deps[L]:void 0)?.node,I=Z?.v,Q=O.get(D);return{trigger_dep_index:L,trigger_dep_name:Z?.name,...I!=null?{trigger_version:{id:I.id,version:I.version}}:{},dep_values:[...X],...Q!=null?{dep_batches:Q}:{}}},B=[],ue=[];for(let[D,L]of e){let X=C(L,D);X&&B.push(X),ue.push(L.subscribe(ye=>{y++;for(let Z of ye){let I=Z[0],Q=S();if(I===P){c[D]=Z[1];let A=L instanceof H?L.lastMutation?.actor??$e:$e;k({type:"data",path:D,data:Z[1],actor:A,...Q,...U(L)})}else if(a)I===K?x++:I===Y?N++:I===se?T++:I===de?g++:I===pe?v++:I===J?E++:I===$&&!b.has(D)?w=!0:I===G&&(m=!0,b.add(D));else if(I===K)x++,k({type:"dirty",path:D,...Q});else if(I===Y)N++,k({type:"resolved",path:D,...Q,...U(L)});else if(I===se)T++,k({type:"invalidate",path:D,...Q});else if(I===de)g++,k({type:"pause",path:D,lockId:Z[1],...Q});else if(I===pe)v++,k({type:"resume",path:D,lockId:Z[1],...Q});else if(I===$)b.has(D)||(w=!0),k({type:"complete",path:D,...Q});else if(I===G){m=!0,b.add(D);let A=L instanceof H?L.lastMutation?.actor??$e:$e;k({type:"error",path:D,data:Z[1],actor:A,...Q})}else I===J&&(E++,k({type:"teardown",path:D,...Q}))}}))}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 x},get resolvedCount(){return N},get invalidateCount(){return T},get pauseCount(){return g},get resumeCount(){return v},get teardownCount(){return E},get events(){return f?f.toArray():[...h]},get anyCompletedCleanly(){return w},get anyErrored(){return m},get completedWithoutErrors(){return w&&!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=ao(n.theme),u=r==="stage-log"?oe():0,l=c=>c==null?"":n.stageLabels?.[c]??c,f=(c,b)=>c.length>b?`${c.slice(0,b-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 b=d[c.type]??"",x=c.path?`${d.path}${c.path}${d.reset} `:"",N=c.type==="data"||c.type==="error",T=c.type==="pause"||c.type==="resume",g=N?` ${yt(c.data)}`:T?` ${yt(c.lockId)}`:"",v=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,E=v?.trigger_dep_name!=null?` <- ${v.trigger_dep_name}`:v?.trigger_dep_index!=null?` <- #${v.trigger_dep_index}`:"",w=c.in_batch?" [batch]":"";return`${x}${b}${c.type.toUpperCase()}${d.reset}${g}${E}${w}`};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([[J]],{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,b)=>{let x=c.split(V).length,N=b.split(V).length;return x!==N?x-N:c<b?-1:c>b?1:0})){let c=p.split(V),b=o;for(let x of c)b._mounts.has(x)||b.mount(x,new t(x)),b=b._mounts.get(x)}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),b=c.pop();if(b==null||b.length===0)throw new Error(`invalid snapshot path "${p}"`);let x=o;for(let N of c){let T=x._mounts.get(N);if(!T)throw new Error(`unknown mount "${N}" in path "${p}"`);x=T}return[x,b]},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 b=c?.deps??[];if(!b.every(E=>f.has(E)))continue;let[x,N]=d(p),T={...c?.meta??{}},g=a(p),v;if(c?.type==="state")v=z(c.value,{meta:T});else{if(g==null)continue;v=g(N,{path:p,type:c.type,value:c.value,meta:T,deps:b,resolvedDeps:b.map(E=>f.get(E))})}x.add(v,{name:N}),f.set(p,v),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=Yr(l.nodes);if(u.lastSnapshot!=null&&f!==""&&f===u.lastFingerprint)return;let h=u.seq+1,p=Ze(),x=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:$n(u.lastSnapshot,l),seq:h,timestamp_ns:p,format_version:Ae};if(u.tier.filter&&!u.tier.filter(x))return;let N;try{N=u.tier.save(x)}catch(T){n.onError?.(T,u.tier);return}if(N&&typeof N.then=="function"){let v=(u.savePending??Promise.resolve()).then(()=>N,()=>N).then(()=>{u.disposed||(u.seq=h,u.lastSnapshot=l,u.lastFingerprint=f)},E=>{n.onError?.(E,u.tier)});u.savePending=v.finally(()=>{u.savePending===v&&(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 b=this.config.messageTier(c[0]);return b>=3&&b<5}))return;if(n.filter){let c=this.tryResolve(u);if(c==null)return;let b=Gt(c,dt("standard"));if(!n.filter(u,b))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(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 g=e.nodes[T],v=n.nodes[T],E=g.v,w=v.v;E!=null&&w!=null&&E.id===w.id&&E.version!==w.version&&d.push({path:T,id:E.id,from:E.version,to:w.version});let m=E!=null&&w!=null&&E.id===w.id&&E.version===w.version;for(let y of["type","status","sentinel"]){let _=g[y],R=v[y];_!==R&&a.push({path:T,field:y,from:_,to:R})}if(!m)for(let y of["value","meta"]){let _=g[y],R=v[y];Jr(_,R)||a.push({path:T,field:y,from:_,to:R})}}let u=T=>`${T.from} ${T.to}`,l=new Set(e.edges.map(u)),f=new Set(n.edges.map(u)),h=n.edges.filter(T=>!l.has(u(T))),p=e.edges.filter(T=>!f.has(u(T))),c=new Set(e.subgraphs),b=new Set(n.subgraphs),x=[...b].filter(T=>!c.has(T)).sort(),N=[...c].filter(T=>!b.has(T)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:h,edgesRemoved:p,subgraphsAdded:x,subgraphsRemoved:N}}};function $n(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[g,v]of Object.entries(t.nodes)){if(!g)continue;l.add(g);let E=v.deps??[];i.set(g,E);for(let w of E)w&&(l.add(w),a.has(w)||a.set(w,new Set),a.get(w).add(g))}for(let g of t.edges){if(g==null||typeof g!="object")continue;let v=typeof g.from=="string"?g.from:"",E=typeof g.to=="string"?g.to:"";!v||!E||(l.add(v),l.add(E),u.has(v)||u.set(v,new Set),u.get(v).add(E),d.has(E)||d.set(E,new Set),d.get(E).add(v))}if(!l.has(e))return r.withDetail?s:[];let f=r.both===!0,h=g=>{if(f){let m=i.get(g)??[],y=d.get(g),_=a.get(g),R=u.get(g),O=[...m];return y&&O.push(...y),_&&O.push(..._),R&&O.push(...R),O}if(n==="upstream"){let m=i.get(g)??[],y=d.get(g);return y?[...m,...y]:m}let v=a.get(g),E=u.get(g),w=v?[...v]:[];return E&&w.push(...E),w},p=new Set([e]),c=new Map,b=[{path:e,depth:0}],x=0,N=!1;for(;x<b.length;){let g=b[x++];if(o!=null&&g.depth>=o){h(g.path).length>0&&(N=!0);continue}for(let v of h(g.path))!v||p.has(v)||(p.add(v),c.set(v,g.depth+1),b.push({path:v,depth:g.depth+1}))}let T=[...c.keys()].sort((g,v)=>g<v?-1:g>v?1:0);return r.withDetail?{paths:T,depths:c,truncated:N}:T}function fo(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 po=64;function Fn(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<po)return;let y=m.keys().next();if(y.done)return;let _=m.get(y.value);_!==void 0&&_.dispose(),m.delete(y.value)}function b(m){let y=a.version;try{return m()}finally{a.version!==y&&u()}}function x(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],([O])=>{let k=O;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 N(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 O=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(O);return f.set(_,{node:O,dispose:k}),O}function T(m){let y=h.get(m);if(y!==void 0)return y.node;let _=F([d,m],([O,k])=>{let S=O,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 g,v;function E(){g===void 0&&(g=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)}),v=F([d],([m])=>m.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Ke(g),Ke(v))}let w={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){b(()=>a.append(m))},appendMany(m){m.length!==0&&b(()=>a.appendMany(m))},clear(){b(()=>a.clear())},trimHead(m){b(()=>a.trimHead(m))},withLatest(){return E(),d},get lastValue(){return E(),g},get hasLatest(){return E(),v},view(m){switch(m.kind){case"tail":return x(m.n);case"slice":return N(m.start,m.stop);case"fromCursor":return T(m.cursor)}},attach(m){let y=m.subscribe(_=>{for(let R of _)R[0]===P&&w.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 O=await Promise.resolve(R.loadEntries());O.entries.length>0&&a.size===0&&(a.restore(O.entries),y.set(R,O.entries.length),u());break}catch{}})();let _=d.subscribe(R=>{for(let O of R){if(O[0]!==P)continue;let k=O[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 w}ut();function Vn(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 Vn("messaging",t,e)}var ho=1024,Vt=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Fn([],{name:"events",maxSize:n.retainedLimit??ho}),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 zn(t,e){return new Ht(t,e)}function mo(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 Bn(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 go(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=mo(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 b=z(Number.NEGATIVE_INFINITY,{name:"score"});o.add(b,{name:"score"});let x=z(0,{name:"budget-used"});o.add(x,{name:"budget-used"});let N=zn("stages");o.mount("stages",N);let T=N.topic("generate"),g=N.topic("evaluate"),v=N.topic("analyze"),E=N.topic("decide"),w=n,m=null,y=[];o.addDisposer(d.subscribe(A=>{for(let M of A)M[0]===P&&(w=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=w,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([[G,Ge]])}),()=>{ve=!0};ee.emit(Te)}catch(Te){ve=!0,ee.down([[G,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 O=F([_,a],([A,M])=>({iteration:M,candidates:A,timestamp_ns:oe()}),{name:"generate-event"});o.add(O,{name:"generate-event"}),o.addDisposer(O.subscribe(()=>{}));let k=_e([O],([A])=>{T.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])=>{g.publish(A)},{name:"evaluate-publish"});o.add(B,{name:"evaluate-publish"}),o.addDisposer(B.subscribe(()=>{}));let ue=F([C,_],([A,M])=>w.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])=>{v.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([b],([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([x],([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 X=F([x],([A])=>r.budget!=null&&A>=r.budget,{name:"budget-exhausted-check"});o.add(X,{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(X.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 Z=-1,I=_e([ue,C,_],([A,M,W])=>{let q=a.cache,ee=A,ve=W,Te=M;if(q<=Z)return;Z=q;let{best:Ge,bestScore:Hn}=Bn(ve,Te),jn=p.cache,Un={n:q,candidates:ve,scores:Te,feedback:ee,best:Ge,bestScore:Hn,timestamp_ns:oe()},we=[...jn,Un],vt=x.cache+ve.length,ne="continue",Oe,Wn=r.budget!=null&&vt>=r.budget,qn=f.cache;if(Wn)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(Kn=>Kn.bestScore<=Tt)&&(ne="converged",Oe="patience")}ne==="continue"&&qn&&(ne="paused"),le(()=>{c.emit(Ge),b.emit(ee.score),p.emit(we),x.emit(vt),u.emit(ee),E.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(I,{name:"decide-bridge"}),o.addDisposer(I.subscribe(()=>{})),Object.assign(o,{best:c,score:b,status:h,history:p,strategy:d,iteration:a,generate:T,evaluate:g,analyze:v,decide:E,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 bo(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 yo(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function vo(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 To(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,s=t.formatCritique??vo;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((g,v)=>g.score-v.score):o.filter(g=>g.score<l).slice().sort((g,v)=>g.score-v.score),h=f.slice(0,r),{best:p,bestScore:c}=Bn(i,o),b={summary:"",score:a,weakTasks:h.map(g=>g.taskId)},x=s(h,b),N={kind:"errorCritique",best:p,failures:h,critiqueText:x},T=f.length>h.length?` (top ${h.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${f.length}${T}/${o.length}, bestScore=${c.toFixed(3)}`,critique:N,weakTasks:h.map(g=>g.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=yo(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 b=0;b<e;b++)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});