@graphrefly/graphrefly 0.30.0 → 0.32.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 (253) hide show
  1. package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
  2. package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
  3. package/dist/chunk-2JNT5NDF.js +61 -0
  4. package/dist/{chunk-DDPYNMGG.js → chunk-2RH4QNDQ.js} +1 -1
  5. package/dist/chunk-4JBKKUCJ.js +7 -0
  6. package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
  7. package/dist/chunk-4VXL3UZK.js +1 -0
  8. package/dist/{chunk-SHYH5SXV.js → chunk-4YGJ7KZ6.js} +1 -1
  9. package/dist/{chunk-GJR3P6JG.js → chunk-5PBXUVHI.js} +1 -1
  10. package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
  11. package/dist/{chunk-XQAXYVXX.js → chunk-7EMUF2RY.js} +1 -1
  12. package/dist/chunk-7JZ3YORY.js +80 -0
  13. package/dist/chunk-7QMVU3IX.js +1 -0
  14. package/dist/{chunk-WANIEEKV.js → chunk-7QS77X6G.js} +1 -1
  15. package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
  16. package/dist/{chunk-Y36UZ5VS.js → chunk-BU4SUZSA.js} +1 -1
  17. package/dist/{chunk-P7JXGKDO.js → chunk-CNXUW2CU.js} +1 -1
  18. package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
  19. package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
  20. package/dist/chunk-EIFHFDFD.js +1 -0
  21. package/dist/chunk-FTA5TB2A.js +1 -0
  22. package/dist/{chunk-T5SHIKJD.js → chunk-JAHAJU4G.js} +1 -1
  23. package/dist/{chunk-AV3PIDFQ.js → chunk-JYMNVEH6.js} +1 -1
  24. package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
  25. package/dist/chunk-KD3IYBTD.js +3 -0
  26. package/dist/{chunk-3NEPQO2E.js → chunk-LG73TUF4.js} +2 -2
  27. package/dist/chunk-LJGPOJHS.js +1 -0
  28. package/dist/chunk-LWGLBCMU.js +1 -0
  29. package/dist/{chunk-BKPLTBL5.js → chunk-M2VFLRPJ.js} +1 -1
  30. package/dist/{chunk-GNCBXARM.js → chunk-MFNOZ5E6.js} +1 -1
  31. package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
  32. package/dist/chunk-PNTBXOQ6.js +5 -0
  33. package/dist/{chunk-73Z3W2RN.js → chunk-PWKLZ2XU.js} +1 -1
  34. package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
  35. package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
  36. package/dist/chunk-SGS4OJGS.js +1 -0
  37. package/dist/{chunk-4OFIQ66T.js → chunk-TOCCHQI6.js} +1 -1
  38. package/dist/chunk-UMH3HSP7.js +1 -0
  39. package/dist/{chunk-XHVB6G6M.js → chunk-UXEB35L4.js} +1 -1
  40. package/dist/{chunk-33FA6V4B.js → chunk-VXJX3ZZP.js} +1 -1
  41. package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
  42. package/dist/{chunk-RD52SNH2.js → chunk-WE32AFFA.js} +1 -1
  43. package/dist/{chunk-KA6MMXIY.js → chunk-WF3V5X2L.js} +1 -1
  44. package/dist/chunk-WQ7I7JVU.js +1 -0
  45. package/dist/{chunk-4JJCCD5S.js → chunk-X4OOM6QU.js} +1 -1
  46. package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
  47. package/dist/chunk-Y26UN6J5.js +18 -0
  48. package/dist/{chunk-VWPRPPKR.js → chunk-ZWETYYQG.js} +1 -1
  49. package/dist/compat/index.cjs +2 -2
  50. package/dist/compat/index.d.cts +5 -5
  51. package/dist/compat/index.d.ts +5 -5
  52. package/dist/compat/index.js +1 -1
  53. package/dist/compat/jotai/index.cjs +1 -1
  54. package/dist/compat/jotai/index.js +1 -1
  55. package/dist/compat/nanostores/index.cjs +1 -1
  56. package/dist/compat/nanostores/index.js +1 -1
  57. package/dist/compat/nestjs/index.cjs +5 -5
  58. package/dist/compat/nestjs/index.d.cts +3 -3
  59. package/dist/compat/nestjs/index.d.ts +3 -3
  60. package/dist/compat/nestjs/index.js +1 -1
  61. package/dist/compat/zustand/index.cjs +2 -2
  62. package/dist/compat/zustand/index.d.cts +2 -2
  63. package/dist/compat/zustand/index.d.ts +2 -2
  64. package/dist/compat/zustand/index.js +1 -1
  65. package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
  66. package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
  67. package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
  68. package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
  69. package/dist/core/index.cjs +1 -1
  70. package/dist/core/index.js +1 -1
  71. package/dist/extra/browser.cjs +1 -1
  72. package/dist/extra/browser.js +1 -1
  73. package/dist/extra/index.cjs +18 -18
  74. package/dist/extra/index.d.cts +7 -6
  75. package/dist/extra/index.d.ts +7 -6
  76. package/dist/extra/index.js +1 -1
  77. package/dist/extra/node.cjs +2 -2
  78. package/dist/extra/node.js +1 -1
  79. package/dist/extra/operators.cjs +1 -1
  80. package/dist/extra/operators.d.cts +41 -1
  81. package/dist/extra/operators.d.ts +41 -1
  82. package/dist/extra/operators.js +1 -1
  83. package/dist/extra/reactive.cjs +1 -1
  84. package/dist/extra/reactive.d.cts +1 -1
  85. package/dist/extra/reactive.d.ts +1 -1
  86. package/dist/extra/reactive.js +1 -1
  87. package/dist/extra/sources.cjs +1 -1
  88. package/dist/extra/sources.d.cts +62 -2
  89. package/dist/extra/sources.d.ts +62 -2
  90. package/dist/extra/sources.js +1 -1
  91. package/dist/extra/storage-browser.cjs +1 -1
  92. package/dist/extra/storage-browser.js +1 -1
  93. package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
  94. package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
  95. package/dist/graph/index.cjs +4 -4
  96. package/dist/graph/index.d.cts +3 -3
  97. package/dist/graph/index.d.ts +3 -3
  98. package/dist/graph/index.js +1 -1
  99. package/dist/{graph-CWeI0aHd.d.ts → graph-BOhEGJ6E.d.ts} +10 -0
  100. package/dist/{graph-C4Uxwv0T.d.cts → graph-CdJeX7O7.d.cts} +10 -0
  101. package/dist/{index-B-z8WaSd.d.cts → index-BDLy6CQ9.d.cts} +1 -1
  102. package/dist/{index-iBp74eGU.d.cts → index-BJDXj9Wf.d.cts} +2 -2
  103. package/dist/{index-BBINVimG.d.ts → index-BUZPTPSQ.d.ts} +2 -2
  104. package/dist/{index-DnrZghBB.d.ts → index-BbcSZCAG.d.ts} +1 -1
  105. package/dist/{index-lKuLYmHO.d.cts → index-BiGeETJs.d.cts} +1 -1
  106. package/dist/{index-BHu_Wba0.d.cts → index-BmZb8fNF.d.cts} +3 -3
  107. package/dist/{index-Docdiu9a.d.ts → index-Bnmttu35.d.ts} +1 -1
  108. package/dist/{index-D6ajK8Mh.d.cts → index-BuN2wGJs.d.cts} +517 -134
  109. package/dist/{index-Cy7eFeIX.d.cts → index-BwdPDWI4.d.cts} +1 -1
  110. package/dist/{index-DylQCKEL.d.cts → index-BzxU4yhV.d.cts} +11 -2
  111. package/dist/{index-D9Y_u6BG.d.cts → index-C-Gsh-0a.d.cts} +2 -2
  112. package/dist/{index-ybtSyjWB.d.cts → index-C22aTC1X.d.cts} +5 -5
  113. package/dist/{index-yIdWFo2b.d.cts → index-C4QTaDli.d.cts} +2 -2
  114. package/dist/{index-BJHQUCZx.d.ts → index-C7RqYbOZ.d.ts} +82 -7
  115. package/dist/{index-C5Ghnp5B.d.ts → index-C9qCLIN4.d.ts} +2 -2
  116. package/dist/{index-DVNLe3pS.d.cts → index-CCdg0JLX.d.cts} +1 -1
  117. package/dist/{index-B5iVOD7w.d.ts → index-CEoU-r-g.d.ts} +2 -2
  118. package/dist/{index-CfFYyLR8.d.ts → index-CHfBm51k.d.ts} +11 -2
  119. package/dist/{index-Dljd76bC.d.ts → index-CNyiYQWF.d.ts} +5 -5
  120. package/dist/{index-C6NBfXj-.d.ts → index-CVevMZ0n.d.ts} +2 -2
  121. package/dist/{index-DGb1awva.d.ts → index-CZUzi6Dy.d.ts} +2 -2
  122. package/dist/{index-FrYrV-Vf.d.ts → index-Ckl03Q0s.d.ts} +1 -1
  123. package/dist/{index-Bvi5uJxX.d.ts → index-CmSjld-4.d.ts} +1 -1
  124. package/dist/{index-9iguV3bF.d.cts → index-CnjUhRbs.d.cts} +2 -2
  125. package/dist/{index-C98oJsEs.d.cts → index-D3HcdZ4d.d.cts} +1 -1
  126. package/dist/{index-IZ3l_vQ9.d.ts → index-DD1czHj3.d.ts} +1 -1
  127. package/dist/{index-BS220yqj.d.cts → index-DNhTQReY.d.cts} +82 -7
  128. package/dist/{index-UZO988ox.d.cts → index-DSawGt8n.d.cts} +2 -2
  129. package/dist/{index-CcpEvuPl.d.cts → index-DUkuH3jP.d.cts} +1 -1
  130. package/dist/{index-CRAkoq-y.d.cts → index-DY2QbdoP.d.cts} +1 -1
  131. package/dist/{index-CvS9IuTG.d.ts → index-Dbmj0iYR.d.ts} +1 -1
  132. package/dist/{index-ClgKmOHe.d.ts → index-DhlAMlm9.d.ts} +517 -134
  133. package/dist/{index-ClB7TCfL.d.cts → index-DlGaEBW5.d.cts} +2 -2
  134. package/dist/{index-CotRMjtJ.d.ts → index-Dp_pS7Bw.d.ts} +1 -1
  135. package/dist/{index-Cc8VQIgL.d.ts → index-Dxk-pUQI.d.ts} +2 -2
  136. package/dist/{index-DBQUKh59.d.cts → index-EGjF6iSY.d.cts} +3 -3
  137. package/dist/{index-D9HrBx2J.d.ts → index-LGzAYqdR.d.ts} +1 -1
  138. package/dist/{index-DR3gf_DG.d.cts → index-LzCJ0kMT.d.cts} +2 -2
  139. package/dist/{index-RQg6lTrN.d.ts → index-MV2yGIAq.d.ts} +2 -2
  140. package/dist/{index-Bs3-LC83.d.cts → index-_BXz9K7b.d.cts} +1 -1
  141. package/dist/{index-SSGqF8mI.d.cts → index-aBqZUx3B.d.cts} +1 -1
  142. package/dist/{index-CFW32Dy1.d.ts → index-eYHRkoK-.d.ts} +1 -1
  143. package/dist/{index-B2HBxvMb.d.ts → index-gXTVbSax.d.ts} +3 -3
  144. package/dist/{index-B8Aj_z8S.d.cts → index-j33Lfb1G.d.cts} +23 -2
  145. package/dist/{index-BEpRsvhg.d.ts → index-lpGUhTBn.d.ts} +3 -3
  146. package/dist/{index-BXbQUn4n.d.ts → index-zMQIQuDu.d.ts} +23 -2
  147. package/dist/index.cjs +106 -125
  148. package/dist/index.d.cts +34 -33
  149. package/dist/index.d.ts +34 -33
  150. package/dist/index.js +1 -1
  151. package/dist/patterns/ai/browser.cjs +5 -22
  152. package/dist/patterns/ai/browser.d.cts +3 -3
  153. package/dist/patterns/ai/browser.d.ts +3 -3
  154. package/dist/patterns/ai/browser.js +1 -1
  155. package/dist/patterns/ai/index.cjs +30 -44
  156. package/dist/patterns/ai/index.d.cts +13 -11
  157. package/dist/patterns/ai/index.d.ts +13 -11
  158. package/dist/patterns/ai/index.js +1 -1
  159. package/dist/patterns/ai/node.cjs +2 -2
  160. package/dist/patterns/ai/node.d.cts +5 -4
  161. package/dist/patterns/ai/node.d.ts +5 -4
  162. package/dist/patterns/ai/node.js +1 -1
  163. package/dist/patterns/audit/index.cjs +3 -3
  164. package/dist/patterns/audit/index.d.cts +3 -3
  165. package/dist/patterns/audit/index.d.ts +3 -3
  166. package/dist/patterns/audit/index.js +1 -1
  167. package/dist/patterns/cqrs/index.cjs +6 -6
  168. package/dist/patterns/cqrs/index.d.cts +2 -2
  169. package/dist/patterns/cqrs/index.d.ts +2 -2
  170. package/dist/patterns/cqrs/index.js +1 -1
  171. package/dist/patterns/demo-shell/index.cjs +2 -2
  172. package/dist/patterns/demo-shell/index.d.cts +3 -3
  173. package/dist/patterns/demo-shell/index.d.ts +3 -3
  174. package/dist/patterns/demo-shell/index.js +1 -1
  175. package/dist/patterns/domain-templates/index.cjs +6 -6
  176. package/dist/patterns/domain-templates/index.d.cts +2 -2
  177. package/dist/patterns/domain-templates/index.d.ts +2 -2
  178. package/dist/patterns/domain-templates/index.js +1 -1
  179. package/dist/patterns/graphspec/index.cjs +27 -25
  180. package/dist/patterns/graphspec/index.d.cts +3 -3
  181. package/dist/patterns/graphspec/index.d.ts +3 -3
  182. package/dist/patterns/graphspec/index.js +1 -1
  183. package/dist/patterns/guarded-execution/index.cjs +7 -7
  184. package/dist/patterns/guarded-execution/index.d.cts +4 -4
  185. package/dist/patterns/guarded-execution/index.d.ts +4 -4
  186. package/dist/patterns/guarded-execution/index.js +1 -1
  187. package/dist/patterns/harness/index.cjs +12 -11
  188. package/dist/patterns/harness/index.d.cts +6 -6
  189. package/dist/patterns/harness/index.d.ts +6 -6
  190. package/dist/patterns/harness/index.js +1 -1
  191. package/dist/patterns/job-queue/index.cjs +5 -5
  192. package/dist/patterns/job-queue/index.d.cts +2 -2
  193. package/dist/patterns/job-queue/index.d.ts +2 -2
  194. package/dist/patterns/job-queue/index.js +1 -1
  195. package/dist/patterns/lens/index.cjs +5 -5
  196. package/dist/patterns/lens/index.d.cts +4 -4
  197. package/dist/patterns/lens/index.d.ts +4 -4
  198. package/dist/patterns/lens/index.js +1 -1
  199. package/dist/patterns/memory/index.cjs +4 -4
  200. package/dist/patterns/memory/index.d.cts +2 -2
  201. package/dist/patterns/memory/index.d.ts +2 -2
  202. package/dist/patterns/memory/index.js +1 -1
  203. package/dist/patterns/messaging/index.cjs +5 -5
  204. package/dist/patterns/messaging/index.d.cts +2 -2
  205. package/dist/patterns/messaging/index.d.ts +2 -2
  206. package/dist/patterns/messaging/index.js +1 -1
  207. package/dist/patterns/orchestration/index.cjs +7 -7
  208. package/dist/patterns/orchestration/index.d.cts +2 -2
  209. package/dist/patterns/orchestration/index.d.ts +2 -2
  210. package/dist/patterns/orchestration/index.js +1 -1
  211. package/dist/patterns/reactive-layout/index.cjs +2 -2
  212. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  213. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  214. package/dist/patterns/reactive-layout/index.js +1 -1
  215. package/dist/patterns/reduction/index.cjs +5 -5
  216. package/dist/patterns/reduction/index.d.cts +2 -2
  217. package/dist/patterns/reduction/index.d.ts +2 -2
  218. package/dist/patterns/reduction/index.js +1 -1
  219. package/dist/patterns/refine-loop/index.cjs +8 -8
  220. package/dist/patterns/refine-loop/index.d.cts +3 -3
  221. package/dist/patterns/refine-loop/index.d.ts +3 -3
  222. package/dist/patterns/refine-loop/index.js +1 -1
  223. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  224. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  225. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  226. package/dist/patterns/resilient-pipeline/index.js +1 -1
  227. package/dist/patterns/surface/index.cjs +15 -13
  228. package/dist/patterns/surface/index.d.cts +4 -4
  229. package/dist/patterns/surface/index.d.ts +4 -4
  230. package/dist/patterns/surface/index.js +1 -1
  231. package/dist/{reactive-layout-BAr6-_o5.d.ts → reactive-layout-Bq0rA2Wb.d.ts} +1 -1
  232. package/dist/{reactive-layout-5oEn8lHM.d.cts → reactive-layout-Dhhe54Oj.d.cts} +1 -1
  233. package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
  234. package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
  235. package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
  236. package/dist/{topology-tree-CVREibAc.d.cts → topology-tree-CpSjvIXp.d.cts} +1 -1
  237. package/dist/{topology-tree-CkjojcB6.d.ts → topology-tree-DAbCV2Yw.d.ts} +1 -1
  238. package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
  239. package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
  240. package/package.json +1 -1
  241. package/dist/chunk-2GQREQ6C.js +0 -1
  242. package/dist/chunk-4C2OR2GH.js +0 -18
  243. package/dist/chunk-5JDE5JHE.js +0 -1
  244. package/dist/chunk-7JDLFI6N.js +0 -1
  245. package/dist/chunk-AMBYCIOH.js +0 -3
  246. package/dist/chunk-GLSM33ZM.js +0 -78
  247. package/dist/chunk-ISCENNXS.js +0 -1
  248. package/dist/chunk-IUK4EFCE.js +0 -1
  249. package/dist/chunk-KASHOCF5.js +0 -1
  250. package/dist/chunk-LI3E75VE.js +0 -64
  251. package/dist/chunk-MGKAO4EK.js +0 -7
  252. package/dist/chunk-NSG4C6BF.js +0 -23
  253. package/dist/chunk-VIEUJSTT.js +0 -1
@@ -1 +1 @@
1
- import{a as Y,b as m,c as M,d as S,e as C,f as N,g as L,h as k,i as D,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var De={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(De)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var Oe={type:"system",id:""};function J(n){if(n==null)return Oe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var O=0,U=!1,A=[],E=[],R=[],W=[];function me(){return O>0||U}function be(){return O>0}function ve(n){O>0?W.push(n):n()}function Xe(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,R.length=0}}else Re()}}function Re(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||R.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,R.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:R).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?R:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?R.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.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}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.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 xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(C,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(m,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`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}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=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]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,p=2600822924,h=528734635,b=1541459225,T=new Uint32Array(64),y=(w,g)=>w>>>g|w<<32-g;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=y(H,7)^y(H,18)^H>>>3,ne=y(V,17)^y(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let g=o,G=d,I=l,ee=c,x=u,z=p,q=h,te=b;for(let f=0;f<64;f++){let H=y(x,6)^y(x,11)^y(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=y(g,2)^y(g,13)^y(g,22),Se=g&G^g&I^G&I,Ce=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=g,g=K+Ce>>>0}o=o+g>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,u=u+x>>>0,p=p+z>>>0,h=h+q>>>0,b=b+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(u)+v(p)+v(h)+v(b)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[m,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_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,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[m,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},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,t){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 s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,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 t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[m,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} 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,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){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)ce(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 r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},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 a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),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[t]=this._sinks;this._sinks=t}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,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}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,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===C){this._depInvalidated(s),this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===m)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===D)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===m||i===S)&&this._emit([t]),(i===D||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,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 t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_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(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \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,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&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 t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===C);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===m){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],p=u[0];if(p===m){if(u.length>=2){let h=!1;if(o&&this._cached!==void 0)try{h=this._equals(this._cached,u[1])}catch(b){i=this._wrapFnError("equals threw",b),r=c;break}if(h){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===D)this._status="completed";else if(p===_)this._status="errored";else if(p===C){this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let b=h.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<r.length){let h=r[u];return h!=null&&h.length>0?h.at(-1):o.prevData[u]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{De as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,Oe as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
1
+ import{a as Y,b as m,c as M,d as S,e as C,f as N,g as L,h as k,i as D,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var De={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(De)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var Oe={type:"system",id:""};function J(n){if(n==null)return Oe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var O=0,U=!1,A=[],E=[],R=[],W=[];function me(){return O>0||U}function be(){return O>0}function ve(n){O>0?W.push(n):n()}function Xe(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,R.length=0}}else Re()}}function Re(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||R.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,R.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:R).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?R:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?R.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.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}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.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 xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(C,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(m,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`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}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=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]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,p=2600822924,h=528734635,b=1541459225,T=new Uint32Array(64),y=(w,g)=>w>>>g|w<<32-g;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=y(H,7)^y(H,18)^H>>>3,ne=y(V,17)^y(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let g=o,G=d,I=l,ee=c,x=u,z=p,q=h,te=b;for(let f=0;f<64;f++){let H=y(x,6)^y(x,11)^y(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=y(g,2)^y(g,13)^y(g,22),Se=g&G^g&I^G&I,Ce=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=g,g=K+Ce>>>0}o=o+g>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,u=u+x>>>0,p=p+z>>>0,h=h+q>>>0,b=b+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(u)+v(p)+v(h)+v(b)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[m,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_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,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[m,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},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,t){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 s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,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 t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[m,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} 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,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){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)ce(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 r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},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 a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),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[t]=this._sinks;this._sinks=t}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,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}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,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===C){if(this._depInvalidated(s),this._cached===void 0)return;this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===m)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===D)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===m||i===S)&&this._emit([t]),(i===D||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,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 t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_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(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \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,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&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 t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===C);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===m){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],p=u[0];if(p===m){if(u.length>=2){let h=!1;if(o&&this._cached!==void 0)try{h=this._equals(this._cached,u[1])}catch(b){i=this._wrapFnError("equals threw",b),r=c;break}if(h){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===D)this._status="completed";else if(p===_)this._status="errored";else if(p===C){this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let b=h.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<r.length){let h=r[u];return h!=null&&h.length>0?h.at(-1):o.prevData[u]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{De as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,Oe as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
@@ -1,4 +1,4 @@
1
- import{f as F,g as j,h as A}from"./chunk-GLSM33ZM.js";import{i as b,k as x}from"./chunk-MGKAO4EK.js";import{p as _}from"./chunk-W4TSQ6RJ.js";import{b as $,d as T,i as v,j as N}from"./chunk-CK2E7BTU.js";import{b as K}from"./chunk-QYADASLV.js";var Y={};K(Y,{SNAPSHOT_WIRE_VERSION:()=>k,SurfaceError:()=>o,asSurfaceError:()=>D,createGraph:()=>R,deleteSnapshot:()=>H,diffSnapshots:()=>W,listSnapshots:()=>L,restoreSnapshot:()=>V,runReduction:()=>M,saveSnapshot:()=>U});var o=class extends Error{code;details;constructor(t,r,n){super(r),this.name="SurfaceError",this.code=t,n!==void 0&&(this.details=n)}toJSON(){let t={code:this.code,message:this.message};if(this.details!==void 0){let r=q(this.details);r!==void 0&&(t.details=r)}return t}};function q(e){try{return JSON.parse(JSON.stringify(e))}catch{return}}function D(e,t="internal-error"){if(e instanceof o)return e;let r=e instanceof Error?e.message:String(e);return new o(t,r)}function R(e,t){let r=j(e);if(!r.valid)throw new o("invalid-spec",`GraphSpec validation failed:
1
+ import{f as F,g as j,h as A}from"./chunk-7JZ3YORY.js";import{h as b,j as x}from"./chunk-4JBKKUCJ.js";import{p as _}from"./chunk-7AJKUA36.js";import{b as $,d as T,i as v,j as N}from"./chunk-CK2E7BTU.js";import{b as K}from"./chunk-QYADASLV.js";var Y={};K(Y,{SNAPSHOT_WIRE_VERSION:()=>k,SurfaceError:()=>o,asSurfaceError:()=>D,createGraph:()=>R,deleteSnapshot:()=>H,diffSnapshots:()=>W,listSnapshots:()=>L,restoreSnapshot:()=>V,runReduction:()=>M,saveSnapshot:()=>U});var o=class extends Error{code;details;constructor(t,r,n){super(r),this.name="SurfaceError",this.code=t,n!==void 0&&(this.details=n)}toJSON(){let t={code:this.code,message:this.message};if(this.details!==void 0){let r=q(this.details);r!==void 0&&(t.details=r)}return t}};function q(e){try{return JSON.parse(JSON.stringify(e))}catch{return}}function D(e,t="internal-error"){if(e instanceof o)return e;let r=e instanceof Error?e.message:String(e);return new o(t,r)}function R(e,t){let r=j(e);if(!r.valid)throw new o("invalid-spec",`GraphSpec validation failed:
2
2
  ${r.errors.join(`
3
3
  `)}`,{errors:r.errors});let n=t?.catalog??{},s=F(e,n);if(!s.valid)throw new o("catalog-error",`Catalog validation failed:
4
4
  ${s.errors.join(`
@@ -0,0 +1,80 @@
1
+ import{b as z}from"./chunk-WF3V5X2L.js";import{g as Y,j as J}from"./chunk-4JBKKUCJ.js";import{E as L,F as T,G as D,H as P}from"./chunk-7AJKUA36.js";import{b as Z}from"./chunk-QYADASLV.js";var pe={};Z(pe,{compileSpec:()=>se,decompileGraph:()=>ae,extractFnFactory:()=>V,extractSourceFactory:()=>B,generateCatalogPrompt:()=>K,isRichFnEntry:()=>M,isRichSourceEntry:()=>W,llmCompose:()=>ce,llmRefine:()=>X,specDiff:()=>ie,validateSpec:()=>A,validateSpecAgainstCatalog:()=>q});function M(i){return typeof i=="object"&&i!==null&&"factory"in i}function W(i){return typeof i=="object"&&i!==null&&"factory"in i}function V(i){return M(i)?i.factory:i}function B(i){return W(i)?i.factory:i}function K(i){let n=[];if(i.fns){let o=new Map;for(let[r,d]of Object.entries(i.fns)){let p=M(d)?d.tags?.[0]??"Other":"Other";o.has(p)||o.set(p,[]),o.get(p).push(ee(r,d))}for(let[r,d]of o)n.push(`${r}:
2
+ ${d.join(`
3
+ `)}`)}if(i.sources){let o=[];for(let[r,d]of Object.entries(i.sources))o.push(te(r,d));o.length>0&&n.push(`Sources:
4
+ ${o.join(`
5
+ `)}`)}return n.join(`
6
+
7
+ `)}function ee(i,n){if(!M(n))return`- ${i}`;let o=`- ${i}: ${n.description}`;if(n.configSchema){let r=Object.entries(n.configSchema).map(([d,p])=>{let l=`${d}: ${p.type}`;return p.enum&&(l+=` (${p.enum.join("|")})`),p.required===!1&&(l+="?"),l});o+=`. Config: { ${r.join(", ")} }`}return o}function te(i,n){if(!W(n))return`- ${i}`;let o=`- ${i}: ${n.description}`;if(n.configSchema){let r=Object.entries(n.configSchema).map(([d,p])=>{let l=`${d}: ${p.type}`;return p.required===!1&&(l+="?"),l});o+=`. Config: { ${r.join(", ")} }`}return o}function q(i,n){let o=[],r=new Set(Object.keys(n.fns??{})),d=new Set(Object.keys(n.sources??{}));for(let[p,l]of Object.entries(i.nodes)){if(l.type==="template")continue;let s=l;if(s.fn&&r.size>0&&!r.has(s.fn))if(d.has(s.fn))o.push(`Node "${p}": fn "${s.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let c=I(s.fn,r);o.push(`Node "${p}": fn "${s.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}if(s.source&&d.size>0&&!d.has(s.source))if(r.has(s.source))o.push(`Node "${p}": source "${s.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...d].join(", ")}`);else{let c=I(s.source,d);o.push(`Node "${p}": source "${s.source}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}if(s.fn&&s.config&&n.fns?.[s.fn]){let c=n.fns[s.fn];if(M(c)&&c.configSchema){for(let[t,$]of Object.entries(c.configSchema))if($.required!==!1&&!(t in s.config)&&o.push(`Node "${p}": config missing required field "${t}"`),t in s.config&&$.enum){let O=s.config[t];$.enum.includes(O)||o.push(`Node "${p}": config.${t} = ${JSON.stringify(O)}, expected one of: ${$.enum.join(", ")}`)}}}}if(i.templates){for(let[p,l]of Object.entries(i.templates))for(let[s,c]of Object.entries(l.nodes))if(c.fn&&r.size>0&&!r.has(c.fn)){let t=I(c.fn,r);o.push(`Template "${p}" node "${s}": fn "${c.fn}" not found in catalog`+(t?`. Did you mean "${t}"?`:""))}}return{valid:o.length===0,errors:o,warnings:[]}}function I(i,n){let o=null,r=1/0,d=i.toLowerCase();for(let p of n){let l=ne(d,p.toLowerCase());l<r&&l<=Math.max(3,Math.floor(i.length/2))&&(r=l,o=p)}return o}function ne(i,n){let o=i.length,r=n.length,d=Array.from({length:o+1},(p,l)=>Array.from({length:r+1},(s,c)=>l===0?c:c===0?l:0));for(let p=1;p<=o;p++)for(let l=1;l<=r;l++)d[p][l]=i[p-1]===n[l-1]?d[p-1][l-1]:1+Math.min(d[p-1][l],d[p][l-1],d[p-1][l-1]);return d[o][r]}var U=new Set(["state","producer","derived","effect","operator","template"]),oe=new Set(["state","producer","derived","effect","operator"]);function A(i){let n=[],o=[];if(i==null||typeof i!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:o};let r=i;if((typeof r.name!="string"||r.name.length===0)&&n.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return n.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:n,warnings:o};let d=new Set(Object.keys(r.nodes)),p=new Map,l=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[s,c]of Object.entries(r.templates))if(c!=null&&typeof c=="object"){let t=c;l.set(s,{params:Array.isArray(t.params)?t.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))n.push("'templates' must be an object");else for(let[s,c]of Object.entries(r.templates)){if(c==null||typeof c!="object"){n.push(`Template "${s}": must be an object`);continue}let t=c;if(Array.isArray(t.params)||n.push(`Template "${s}": missing 'params' array`),t.nodes==null||typeof t.nodes!="object"||Array.isArray(t.nodes))n.push(`Template "${s}": missing or invalid 'nodes' object`);else{let $=new Set(Array.isArray(t.params)?t.params:[]),O=new Set(Object.keys(t.nodes));for(let[w,m]of Object.entries(t.nodes)){if(m==null||typeof m!="object"){n.push(`Template "${s}" node "${w}": must be an object`);continue}let g=m;if((typeof g.type!="string"||!oe.has(g.type))&&n.push(`Template "${s}" node "${w}": invalid type`),Array.isArray(g.deps))for(let y of g.deps)!O.has(y)&&!$.has(y)&&n.push(`Template "${s}" node "${w}": dep "${y}" is not an inner node or param`)}typeof t.output!="string"?n.push(`Template "${s}": missing 'output' string`):t.nodes[t.output]||n.push(`Template "${s}": output "${t.output}" is not a declared node`)}}for(let[s,c]of Object.entries(r.nodes)){if(c==null||typeof c!="object"){n.push(`Node "${s}": must be an object`);continue}let t=c;if(typeof t.type!="string"||!U.has(t.type)){n.push(`Node "${s}": invalid type "${String(t.type)}" (expected: ${[...U].join(", ")})`);continue}if(p.set(s,t.type),t.type==="template")if(typeof t.template!="string"||!l.has(t.template))n.push(`Node "${s}": template "${String(t.template)}" not found in templates`);else if(t.bind==null||typeof t.bind!="object"||Array.isArray(t.bind))n.push(`Node "${s}": template ref requires 'bind' object`);else{let $=l.get(t.template),O=t.bind;for(let w of $.params)w in O||n.push(`Node "${s}": template param "${w}" is not bound (template "${t.template}")`);for(let[,w]of Object.entries(O))typeof w=="string"&&!d.has(w)&&n.push(`Node "${s}": bind target "${w}" does not reference an existing node`)}else{if(Array.isArray(t.deps))for(let $ of t.deps)$===s?n.push(`Node "${s}": self-referencing dep`):d.has($)||n.push(`Node "${s}": dep "${$}" does not reference an existing node`);(t.type==="derived"||t.type==="effect"||t.type==="operator")&&!Array.isArray(t.deps)&&n.push(`Node "${s}": ${t.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))n.push("'feedback' must be an array");else for(let s=0;s<r.feedback.length;s++){let c=r.feedback[s];if(c==null||typeof c!="object"){n.push(`Feedback [${s}]: must be an object`);continue}let t=c;typeof t.from!="string"||!d.has(t.from)?n.push(`Feedback [${s}]: 'from' "${String(t.from)}" does not reference an existing node`):p.get(t.from)==="effect"&&o.push(`Feedback [${s}]: 'from' "${t.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof t.from=="string"&&t.from===t.to&&n.push(`Feedback [${s}]: 'from' and 'to' must be different nodes`),typeof t.to!="string"||!d.has(t.to)?n.push(`Feedback [${s}]: 'to' "${String(t.to)}" does not reference an existing node`):typeof t.to=="string"&&p.get(t.to)!=="state"&&n.push(`Feedback [${s}]: 'to' node "${t.to}" must be a state node (got "${p.get(t.to)??"unknown"}")`)}return{valid:n.length===0,errors:n,warnings:o}}function se(i,n){let o=A(i);if(!o.valid)throw new Error(`compileSpec: invalid GraphSpec:
8
+ ${o.errors.join(`
9
+ `)}`);let r=n?.catalog??{},d=n?.onMissing??"placeholder",p=new J(i.name),l=i.templates??{},s=q(i,r);if(!s.valid)throw new Error(`compileSpec: catalog validation errors:
10
+ ${s.errors.join(`
11
+ `)}`);let c=[],t=(a,f,e)=>{if(e){c.push({path:a,kind:"source",name:e});return}f&&c.push({path:a,kind:"fn",name:f})},$=a=>{let f=r.fns?.[a];return f?V(f):void 0},O=a=>{let f=r.sources?.[a];return f?B(f):void 0},w=new Map,m=[];for(let[a,f]of Object.entries(i.nodes)){if(f.type==="template")continue;let e=f;if(e.type==="state"){let h=L(e.initial,{name:a,meta:e.meta?{...e.meta}:void 0});p.add(h,{name:a}),w.set(a,h)}else if(e.type==="producer"){let h=e.source?O(e.source):void 0,b=e.fn?$(e.fn):void 0;if(h){let u=h(e.config??{});p.add(u,{name:a}),w.set(a,u)}else if(b){let u=b([],e.config??{});p.add(u,{name:a}),w.set(a,u)}else{t(a,e.fn,e.source);let u=T(()=>{},{name:a,meta:{...e.meta,_specFn:e.fn,_specSource:e.source}});p.add(u,{name:a}),w.set(a,u)}}else m.push([a,e])}let g=!0,y=new Map(m);for(;y.size>0&&g;){g=!1;for(let[a,f]of[...y.entries()]){let e=f.deps??[];if(!e.every(x=>w.has(x)))continue;let h=e.map(x=>w.get(x)),b=f.fn?$(f.fn):void 0,u;b?u=b(h,f.config??{}):f.type==="effect"?(f.fn&&t(a,f.fn,void 0),u=P(h,()=>{})):(f.fn&&t(a,f.fn,void 0),u=D(h,x=>x[0])),p.add(u,{name:a}),w.set(a,u),y.delete(a),g=!0}}if(y.size>0){let a=[...y.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${a}`)}for(let[a,f]of Object.entries(i.nodes)){if(f.type!=="template")continue;let e=f,h=l[e.template],b=new J(a),u=new Map,x=[];for(let[k,S]of Object.entries(h.nodes)){let v=(S.deps??[]).map(j=>j.startsWith("$")&&e.bind[j]?e.bind[j]:j),G={...S,deps:v};if(S.type==="state"){let j=L(S.initial,{name:k,meta:S.meta?{...S.meta}:void 0});b.add(j,{name:k}),u.set(k,j)}else if(S.type==="producer"){let j=S.source?O(S.source):void 0,E=S.fn?$(S.fn):void 0;if(j){let F=j(S.config??{});b.add(F,{name:k}),u.set(k,F)}else if(E){let F=E([],S.config??{});b.add(F,{name:k}),u.set(k,F)}else{t(`${a}.${k}`,S.fn,S.source);let F=T(()=>{},{name:k,meta:{...S.meta,_specFn:S.fn,_specSource:S.source}});b.add(F,{name:k}),u.set(k,F)}}else x.push([k,G])}let R=!0,N=new Map(x);for(;N.size>0&&R;){R=!1;for(let[k,S]of[...N.entries()]){let v=S.deps??[];if(!v.every(C=>u.has(C)||w.has(C)))continue;let j=v.map(C=>u.get(C)??w.get(C)),E=S.fn?$(S.fn):void 0,F;E?F=E(j,S.config??{}):S.type==="effect"?(S.fn&&t(`${a}.${k}`,S.fn,void 0),F=P(j,()=>{})):(S.fn&&t(`${a}.${k}`,S.fn,void 0),F=D(j,C=>C[0])),b.add(F,{name:k}),u.set(k,F),N.delete(k),R=!0}}if(N.size>0){let k=[...N.keys()].sort().join(", ");throw new Error(`compileSpec: template "${e.template}" has unresolvable deps: ${k}`)}p.mount(a,b);let _=`${a}::${h.output}`;w.set(a,p.resolve(_));try{let k=p.resolve(_);k.meta._templateName?.emit(e.template),k.meta._templateBind?.emit(e.bind)}catch{}}for(let a of i.feedback??[])z(p,a.from,a.to,{maxIterations:a.maxIterations});if(c.length>0){if(d==="error"){let a=c.map(f=>` - ${f.path}: missing ${f.kind} "${f.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
12
+ ${a.join(`
13
+ `)}`)}if(d==="warn"){let a=n?.onWarn??(f=>console.warn(f));for(let f of c)a(`compileSpec: ${f.path} references missing ${f.kind} "${f.name}" \u2014 substituted placeholder`)}}return p}var re=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function ae(i){let n=i.describe({detail:"standard"}),o={},r=[],d=`::${Y}::`,p=/^__feedback_(?!effect_)(.+)$/,l=new Set;for(let m of Object.keys(n.nodes)){if(m.includes(d))continue;let g=p.exec(m);if(g){l.add(g[1]);let y=n.nodes[m]?.meta;y?.feedbackFrom&&y?.feedbackTo&&r.push({from:y.feedbackFrom,to:y.feedbackTo,...y.maxIterations?{maxIterations:y.maxIterations}:{}})}}for(let[m,g]of Object.entries(n.nodes)){if(m.includes(d)||p.test(m)||g.meta?._internal||m.startsWith("__feedback_effect_")||m.startsWith("__bridge_")||m.includes("::"))continue;let y={type:g.type};if(g.deps.length>0&&(y.deps=g.deps.filter(a=>!a.includes("::"))),g.type==="state"&&g.value!==void 0&&(y.initial=g.value),g.meta&&Object.keys(g.meta).length>0){let a={};for(let[f,e]of Object.entries(g.meta))re.has(f)||(a[f]=e);Object.keys(a).length>0&&(y.meta=a)}o[m]=y}let s={},c={},t=new Set;for(let m of n.subgraphs){let g=`${m}::`;for(let[y,a]of Object.entries(n.nodes)){if(!y.startsWith(g)||y.includes(d))continue;let f=a.meta;if(f?._templateName&&f?._templateBind){let e=f._templateName,h=f._templateBind;if(!s[e]){let b={},u=new Set,x=`${m}::`;for(let[v,G]of Object.entries(n.nodes)){if(!v.startsWith(x)||v.includes(d))continue;let j=v.slice(x.length);j.includes("::")||(u.add(j),b[j]={type:G.type,...G.deps.length>0?{deps:G.deps.map(E=>E.startsWith(x)?E.slice(x.length):E)}:{}})}let R=[],N=new Map;for(let v of Object.values(b))for(let G of v.deps??[])if(!u.has(G)&&!N.has(G)){let j=`$${G}`;R.push(j),N.set(G,j)}for(let v of Object.values(b))v.deps&&(v.deps=v.deps.map(G=>N.get(G)??G));let _=new Set;for(let v of Object.values(b))for(let G of v.deps??[])u.has(G)&&_.add(G);let S=[...u].filter(v=>!_.has(v))[0]??[...u].pop();s[e]={params:R,nodes:b,output:S}}delete o[m],c[m]={type:"template",template:e,bind:h},t.add(m);break}}}let $=new Map;for(let m of n.subgraphs){if(t.has(m))continue;let g={},y=`${m}::`;for(let[f,e]of Object.entries(n.nodes)){if(f.includes(d)||!f.startsWith(y))continue;let h=f.slice(y.length);h.includes("::")||(g[h]={type:e.type,...e.deps.length>0?{deps:e.deps.map(b=>b.startsWith(y)?b.slice(y.length):b)}:{}})}let a=JSON.stringify(Object.fromEntries(Object.entries(g).sort(([f],[e])=>f.localeCompare(e)).map(([f,e])=>[f,{type:e.type,deps:e.deps??[]}])));$.has(a)||$.set(a,[]),$.get(a).push({name:m,nodes:g})}for(let[,m]of $){if(m.length<2)continue;let g=`${m[0].name}_template`,y=m[0].nodes,a=new Set(Object.keys(y)),f=[],e=new Map;for(let R of Object.values(y))for(let N of R.deps??[])if(!a.has(N)&&!e.has(N)){let _=`$${N}`;f.push(_),e.set(N,_)}let h=new Set;for(let R of Object.values(y))for(let N of R.deps??[])a.has(N)&&h.add(N);let u=[...a].filter(R=>!h.has(R))[0]??[...a].pop(),x={};for(let[R,N]of Object.entries(y))x[R]={...N,deps:N.deps?.map(_=>e.get(_)??_)};s[g]={params:f,nodes:x,output:u};for(let R of m){delete o[R.name];let N={},_=new Set(Object.keys(R.nodes));for(let k of Object.values(R.nodes))for(let S of k.deps??[])if(!_.has(S)){let v=e.get(S)??`$${S}`;N[v]=S}c[R.name]={type:"template",template:g,bind:N}}}let O={...o,...c},w={name:n.name,nodes:O};return Object.keys(s).length>0&&(w.templates=s),r.length>0&&(w.feedback=r),w}function ie(i,n){let o=[];i.name!==n.name&&o.push({type:"changed",path:"name",detail:`"${i.name}" \u2192 "${n.name}"`});let r=new Set(Object.keys(i.nodes)),d=new Set(Object.keys(n.nodes));for(let e of d)if(!r.has(e)){let h=n.nodes[e];o.push({type:"added",path:`nodes.${e}`,detail:`type: ${h.type}`})}for(let e of r)d.has(e)||o.push({type:"removed",path:`nodes.${e}`});for(let e of r){if(!d.has(e))continue;let h=i.nodes[e],b=n.nodes[e];if(JSON.stringify(h)!==JSON.stringify(b)){let u=[];h.type!==b.type&&u.push(`type: ${h.type} \u2192 ${b.type}`),JSON.stringify(h.deps)!==JSON.stringify(b.deps)&&u.push("deps changed"),h.fn!==b.fn&&u.push(`fn: ${h.fn} \u2192 ${b.fn}`),JSON.stringify(h.config)!==JSON.stringify(b.config)&&u.push("config changed"),o.push({type:"changed",path:`nodes.${e}`,detail:u.join("; ")||"modified"})}}let p=i.templates??{},l=n.templates??{},s=new Set(Object.keys(p)),c=new Set(Object.keys(l));for(let e of c)s.has(e)||o.push({type:"added",path:`templates.${e}`});for(let e of s)c.has(e)||o.push({type:"removed",path:`templates.${e}`});for(let e of s)c.has(e)&&JSON.stringify(p[e])!==JSON.stringify(l[e])&&o.push({type:"changed",path:`templates.${e}`,detail:"template definition changed"});let t=i.feedback??[],$=n.feedback??[],O=new Set(t.map(e=>`${e.from}->${e.to}`)),w=new Set($.map(e=>`${e.from}->${e.to}`));for(let e of $){let h=`${e.from}->${e.to}`;O.has(h)||o.push({type:"added",path:`feedback.${h}`,detail:`maxIterations: ${e.maxIterations??10}`})}for(let e of t){let h=`${e.from}->${e.to}`;w.has(h)||o.push({type:"removed",path:`feedback.${h}`})}for(let e of t){let h=`${e.from}->${e.to}`,b=$.find(u=>u.from===e.from&&u.to===e.to);b&&JSON.stringify(e)!==JSON.stringify(b)&&o.push({type:"changed",path:`feedback.${h}`,detail:`maxIterations: ${e.maxIterations??10} \u2192 ${b.maxIterations??10}`})}let m=o.filter(e=>e.type==="added").length,g=o.filter(e=>e.type==="removed").length,y=o.filter(e=>e.type==="changed").length,a=[];m&&a.push(`${m} added`),g&&a.push(`${g} removed`),y&&a.push(`${y} changed`);let f=a.length>0?a.join(", "):"no changes";return{entries:o,summary:f}}var H=`You are a graph architect for GraphReFly, a reactive graph protocol.
14
+
15
+ Given a natural-language description, produce a JSON GraphSpec with this structure:
16
+
17
+ {
18
+ "name": "<graph_name>",
19
+ "nodes": {
20
+ "<node_name>": {
21
+ "type": "state" | "derived" | "producer" | "effect" | "operator",
22
+ "deps": ["<dep_node_name>", ...],
23
+ "fn": "<catalog_function_name>",
24
+ "source": "<catalog_source_name>",
25
+ "config": { ... },
26
+ "initial": <value>,
27
+ "meta": { "description": "<purpose>" }
28
+ },
29
+ "<template_instance>": {
30
+ "type": "template",
31
+ "template": "<template_name>",
32
+ "bind": { "$param": "node_name" }
33
+ }
34
+ },
35
+ "templates": {
36
+ "<template_name>": {
37
+ "params": ["$param1", "$param2"],
38
+ "nodes": { ... },
39
+ "output": "<output_node>"
40
+ }
41
+ },
42
+ "feedback": [
43
+ { "from": "<condition_node>", "to": "<state_node>", "maxIterations": 10 }
44
+ ]
45
+ }
46
+
47
+ Rules:
48
+ - "state" nodes hold user/LLM-writable values (knobs). Use "initial" for default values.
49
+ - "derived" nodes compute from deps using a named "fn".
50
+ - "effect" nodes produce side effects from deps.
51
+ - "producer" nodes generate values from a named "source".
52
+ - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
53
+ - Use "feedback" for bounded cycles where a derived value writes back to a state node.
54
+ - meta.description is required for every node.
55
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function Q(i){let n=i.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return n?n[1]:i}async function ce(i,n,o){let r=H,d=o?.catalogDescription??(o?.catalog?K(o.catalog):void 0);d&&(r+=`
56
+
57
+ Available catalog (use ONLY these names):
58
+ ${d}`),o?.systemPromptExtra&&(r+=`
59
+
60
+ ${o.systemPromptExtra}`);let p=[{role:"system",content:r},{role:"user",content:i}],c=(await n.invoke(p,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens})).content.trim();c.startsWith("```")&&(c=Q(c));let t;try{t=JSON.parse(c)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${c.slice(0,200)}`)}let $=A(t);if(!$.valid)throw new Error(`llmCompose: invalid GraphSpec:
61
+ ${$.errors.join(`
62
+ `)}`);let O=t;if(o?.catalog){let w=o.maxAutoRefine??0;for(let m=0;m<=w;m++){let g=q(O,o.catalog);if(g.valid)break;if(m===w)throw new Error(`llmCompose: catalog validation failed after ${w} refine attempts:
63
+ ${g.errors.join(`
64
+ `)}`);O=await X(O,`Fix these catalog errors:
65
+ ${g.errors.join(`
66
+ `)}
67
+
68
+ Use ONLY functions and sources from the catalog.`,n,{...o,catalogDescription:d})}}return O}async function X(i,n,o,r){let d=H;r?.catalogDescription&&(d+=`
69
+
70
+ Available catalog:
71
+ ${r.catalogDescription}`),r?.systemPromptExtra&&(d+=`
72
+
73
+ ${r.systemPromptExtra}`);let p=[{role:"system",content:d},{role:"user",content:`Current GraphSpec:
74
+ ${JSON.stringify(i,null,2)}
75
+
76
+ Modification request: ${n}
77
+
78
+ Return the complete modified GraphSpec as JSON.`}],c=(await o.invoke(p,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();c.startsWith("```")&&(c=Q(c));let t;try{t=JSON.parse(c)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${c.slice(0,200)}`)}let $=A(t);if(!$.valid)throw new Error(`llmRefine: invalid GraphSpec:
79
+ ${$.errors.join(`
80
+ `)}`);return t}export{M as a,W as b,V as c,B as d,K as e,q as f,A as g,se as h,ae as i,ie as j,ce as k,X as l,pe as m};
@@ -0,0 +1 @@
1
+ import{b as I}from"./chunk-LWGLBCMU.js";import{t as A,x as v}from"./chunk-WQ7I7JVU.js";import{m as p,r as y}from"./chunk-UMH3HSP7.js";import{E as R,G as w,m as h}from"./chunk-7AJKUA36.js";import{b}from"./chunk-CK2E7BTU.js";function z(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function F(t,a,e){let r=p(t),i=r.v!=null,g=R(e?.initialVerified??null,{...i?{meta:{sourceVersion:null}}:{}}),x=e?.trigger!==void 0&&e.trigger!==null,s=null;if(x&&e?.autoVerify?s=A(p(e.trigger),r):x?s=p(e.trigger):e?.autoVerify&&(s=r),s!==null){let d;if(s===r)d=v(r,c=>a(c));else{let c=r.cache;r.subscribe(f=>{for(let M of f)M[0]===b&&(c=M[1])}),d=v(s,()=>a(c))}y(d,c=>{h(()=>{if(g.down([[b,c]]),i){let f=r.v;f!=null&&g.meta.sourceVersion.down([[b,{id:f.id,version:f.version}]])}})})}return{node:r,verified:g,trigger:s}}function E(t){t.subscribe(()=>{})}function k(t){return t instanceof Map?t:new Map}function B(t,a){if(!Array.isArray(a.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");h(()=>{for(let{key:e,value:r}of a.upsert)t.set(e,r);for(let e of a.remove??[])t.delete(e)})}function G(t,a,e){let r=p(t),i=I(e.mapOptions??{}),g=e.budget??2e3,s=e.context!==void 0&&e.context!==null?p(e.context):R(null),d=k(i.entries.cache);i.entries.subscribe(o=>{for(let u of o)u[0]===b&&(d=k(u[1]))});let c=v(r,o=>a(o,d));if(y(c,o=>{B(i,o)}),e.evict){let o=new Map,u=w([i.entries],([l])=>{let m=[],N=k(l);for(let n of o.keys())N.has(n)||(o.get(n)(),o.delete(n));for(let[n,T]of N){let V=e.evict(n,T);if(z(V)){if(!o.has(n)){let S=y(V,D=>{D===!0&&i.has(n)&&i.delete(n)});o.set(n,S)}continue}if(typeof V=="boolean"){V&&m.push(n);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return m});y(u,l=>{for(let m of l)i.delete(m)})}let f=e.consolidateTrigger!==void 0&&e.consolidateTrigger!==null;if(e.consolidate&&f){let o=p(e.consolidateTrigger),u=v(o,()=>e.consolidate(d));y(u,l=>{B(i,l)})}let M=w([i.entries,s],([o,u])=>{let l=[...k(o).entries()].map(([n,T])=>({key:n,value:T,score:e.score(T,u),cost:e.cost(T)}));l.sort((n,T)=>T.score-n.score);let m=[],N=g;for(let n of l)n.cost<=N&&(m.push({key:n.key,value:n.value,score:n.score}),N-=n.cost);return m}),O=w([i.entries],([o])=>k(o).size);return E(M),E(O),{store:i,compact:M,size:O}}export{F as a,G as b};
@@ -1 +1 @@
1
- import{d as S}from"./chunk-VJLMUKOI.js";import{d as O}from"./chunk-VIMF6LGM.js";import{d as k}from"./chunk-6QZNQS5B.js";import{d as A}from"./chunk-GPW2V3RE.js";import{b as N}from"./chunk-AV3PIDFQ.js";import{b as v}from"./chunk-BA5URFYW.js";import{i as y}from"./chunk-BZP5T4X6.js";import{G as x}from"./chunk-P7JXGKDO.js";import{E as b,J as g,m as _}from"./chunk-W4TSQ6RJ.js";import{b as a,c as p,i as h,j as m}from"./chunk-CK2E7BTU.js";import{b as f}from"./chunk-QYADASLV.js";var j={};f(j,{jotai:()=>v,nanostores:()=>y,nestjs:()=>x,react:()=>S,signals:()=>T,solid:()=>O,svelte:()=>k,vue:()=>A,zustand:()=>N});var T={};f(T,{Signal:()=>q});var s=[];function i(n){let e=n.cache;return n.subscribe(o=>{for(let[d,r]of o)d===a&&(e=r)})(),e}var u=class{_node;_equals;constructor(e,t){this._equals=t?.equals??Object.is,this._node=b(e,{...t,resubscribable:!0,resetOnTeardown:!0})}get(){let e=s[s.length-1];return e?(this._node.status==="sentinel"&&i(this._node),e(this._node)):this._node.status==="sentinel"?i(this._node):this._node.cache}set(e){this._equals(this.get(),e)||_(()=>{this._node.down([[p],[a,e]])})}},l=class{_node;constructor(e,t){this._node=g(o=>{s.push(o);try{return e()}finally{s.pop()}},{...t,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=s[s.length-1];return e?(this._node.status==="sentinel"&&i(this._node),e(this._node)):this._node.status==="sentinel"?i(this._node):this._node.cache}},q={State:u,Computed:l,sub:(n,e)=>{let t=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,o=!0;return n._node.subscribe(d=>{for(let[r,c]of d){if(r===a){if(o){o=!1;continue}t.data?.(c)}r===m&&t.error?.(c),r===h&&t.complete?.()}})}};export{T as a,j as b};
1
+ import{d as S}from"./chunk-VJLMUKOI.js";import{d as O}from"./chunk-VIMF6LGM.js";import{d as k}from"./chunk-6QZNQS5B.js";import{d as A}from"./chunk-GPW2V3RE.js";import{b as N}from"./chunk-JYMNVEH6.js";import{b as v}from"./chunk-A4JT4SAD.js";import{i as y}from"./chunk-W6FQIFVE.js";import{G as x}from"./chunk-CNXUW2CU.js";import{E as b,J as g,m as _}from"./chunk-7AJKUA36.js";import{b as a,c as p,i as h,j as m}from"./chunk-CK2E7BTU.js";import{b as f}from"./chunk-QYADASLV.js";var j={};f(j,{jotai:()=>v,nanostores:()=>y,nestjs:()=>x,react:()=>S,signals:()=>T,solid:()=>O,svelte:()=>k,vue:()=>A,zustand:()=>N});var T={};f(T,{Signal:()=>q});var s=[];function i(n){let e=n.cache;return n.subscribe(o=>{for(let[d,r]of o)d===a&&(e=r)})(),e}var u=class{_node;_equals;constructor(e,t){this._equals=t?.equals??Object.is,this._node=b(e,{...t,resubscribable:!0,resetOnTeardown:!0})}get(){let e=s[s.length-1];return e?(this._node.status==="sentinel"&&i(this._node),e(this._node)):this._node.status==="sentinel"?i(this._node):this._node.cache}set(e){this._equals(this.get(),e)||_(()=>{this._node.down([[p],[a,e]])})}},l=class{_node;constructor(e,t){this._node=g(o=>{s.push(o);try{return e()}finally{s.pop()}},{...t,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=s[s.length-1];return e?(this._node.status==="sentinel"&&i(this._node),e(this._node)):this._node.status==="sentinel"?i(this._node):this._node.cache}},q={State:u,Computed:l,sub:(n,e)=>{let t=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,o=!0;return n._node.subscribe(d=>{for(let[r,c]of d){if(r===a){if(o){o=!1;continue}t.data?.(c)}r===m&&t.error?.(c),r===h&&t.complete?.()}})}};export{T as a,j as b};
@@ -1 +1 @@
1
- import{E as l,J as f}from"./chunk-W4TSQ6RJ.js";import{b as m,j as d}from"./chunk-CK2E7BTU.js";import{b as p}from"./chunk-QYADASLV.js";var F={};p(F,{atom:()=>A});function A(s,n,e){if(typeof s=="function"){let t=s;return typeof n=="function"?b(t,n,e):b(t,void 0,n)}return v(s,n)}function c(s){let n=s.cache,e;if(s.subscribe(i=>{for(let[r,o]of i)r===m&&(n=o),r===d&&(e=o)})(),e)throw e;return n}function v(s,n){let e=l(s,{...n,resubscribable:!0,resetOnTeardown:!0});return{get:()=>e.status==="sentinel"?c(e):e.cache,set:t=>e.emit(t),update:t=>{let i=e.status==="sentinel"?c(e):e.cache;e.emit(t(i))},subscribe:t=>{let i=!0;return e.subscribe(r=>{for(let[o,a]of r)if(o===m){if(i){i=!1;continue}t(a)}})},meta:e.meta,_node:e}}function b(s,n,e){let t=f(r=>s(o=>{let a=o._node;return a.status==="sentinel"&&c(a),r(a)}),{...e,resubscribable:!0,resetOnTeardown:!0}),i={get:()=>t.status==="sentinel"?c(t):t.cache,subscribe:r=>{let o=!0;return t.subscribe(a=>{for(let[u,T]of a)if(u===m){if(o){o=!1;continue}r(T)}})},meta:t.meta,_node:t};if(n){let r=u=>u.get(),o=(u,T)=>u.set(T),a=i;return a.set=u=>n(r,o,u),a.update=u=>{let T=t.status==="sentinel"?c(t):t.cache;return n(r,o,u(T))},a}return i}export{A as a,F as b};
1
+ import{E as l,J as f}from"./chunk-7AJKUA36.js";import{b as m,j as d}from"./chunk-CK2E7BTU.js";import{b as p}from"./chunk-QYADASLV.js";var F={};p(F,{atom:()=>A});function A(s,n,e){if(typeof s=="function"){let t=s;return typeof n=="function"?b(t,n,e):b(t,void 0,n)}return v(s,n)}function c(s){let n=s.cache,e;if(s.subscribe(i=>{for(let[r,o]of i)r===m&&(n=o),r===d&&(e=o)})(),e)throw e;return n}function v(s,n){let e=l(s,{...n,resubscribable:!0,resetOnTeardown:!0});return{get:()=>e.status==="sentinel"?c(e):e.cache,set:t=>e.emit(t),update:t=>{let i=e.status==="sentinel"?c(e):e.cache;e.emit(t(i))},subscribe:t=>{let i=!0;return e.subscribe(r=>{for(let[o,a]of r)if(o===m){if(i){i=!1;continue}t(a)}})},meta:e.meta,_node:e}}function b(s,n,e){let t=f(r=>s(o=>{let a=o._node;return a.status==="sentinel"&&c(a),r(a)}),{...e,resubscribable:!0,resetOnTeardown:!0}),i={get:()=>t.status==="sentinel"?c(t):t.cache,subscribe:r=>{let o=!0;return t.subscribe(a=>{for(let[u,T]of a)if(u===m){if(o){o=!1;continue}r(T)}})},meta:t.meta,_node:t};if(n){let r=u=>u.get(),o=(u,T)=>u.set(T),a=i;return a.set=u=>n(r,o,u),a.update=u=>{let T=t.status==="sentinel"?c(t):t.cache;return n(r,o,u(T))},a}return i}export{A as a,F as b};
@@ -1 +1 @@
1
- import{c as f}from"./chunk-KA6MMXIY.js";import{a as l,d as o,e as d,h as s,i as m,k as b,l as c}from"./chunk-OL33ZI6R.js";import{a as r,b as u}from"./chunk-4VVTGLXJ.js";import{b as y}from"./chunk-QYADASLV.js";var R={};y(R,{NS_PER_MS:()=>r,NS_PER_SEC:()=>u,resilientPipeline:()=>O});function O(p,e={}){let t=p;e.rateLimit!=null&&(t=s(t,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(t=f(t,e.budget));let n;if(e.breaker!=null){let k=o(e.breaker),S=e.breakerOnOpen??"skip",a=d(k,{onOpen:S})(t);t=a.node,n=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");t=c(t,e.timeoutMs*1e6)}e.retry!=null&&(t=l(t,e.retry)),e.fallback!==void 0&&(t=b(t,e.fallback));let i=m(t,{initialStatus:e.initialStatus??"pending"});return{node:i.node,status:i.status,error:i.error,breakerState:n}}export{O as a,R as b};
1
+ import{c as f}from"./chunk-WF3V5X2L.js";import{a as l,d as o,e as d,h as s,i as m,k as b,l as c}from"./chunk-RWGJQQLT.js";import{a as r,b as u}from"./chunk-4VVTGLXJ.js";import{b as y}from"./chunk-QYADASLV.js";var R={};y(R,{NS_PER_MS:()=>r,NS_PER_SEC:()=>u,resilientPipeline:()=>O});function O(p,e={}){let t=p;e.rateLimit!=null&&(t=s(t,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(t=f(t,e.budget));let n;if(e.breaker!=null){let k=o(e.breaker),S=e.breakerOnOpen??"skip",a=d(k,{onOpen:S})(t);t=a.node,n=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");t=c(t,e.timeoutMs*1e6)}e.retry!=null&&(t=l(t,e.retry)),e.fallback!==void 0&&(t=b(t,e.fallback));let i=m(t,{initialStatus:e.initialStatus??"pending"});return{node:i.node,status:i.status,error:i.error,breakerState:n}}export{O as a,R as b};
@@ -1,4 +1,4 @@
1
- import{c as ce}from"./chunk-VIEUJSTT.js";import{a as se,b as P}from"./chunk-5QDBSZBV.js";import{k as L}from"./chunk-MGKAO4EK.js";import{f as ae,h as ie}from"./chunk-KASHOCF5.js";import{i as ne,j as U}from"./chunk-W4TSQ6RJ.js";import{b,h as _,i as T,j as W}from"./chunk-CK2E7BTU.js";import{b as Oe,c as re,d as te,e as oe}from"./chunk-QYADASLV.js";var ke={};Oe(ke,{ACTOR_KEY:()=>F,COMMAND_HANDLERS:()=>A,CQRS_EVENT_HANDLERS:()=>S,CRON_HANDLERS:()=>D,CommandHandler:()=>me,EVENT_HANDLERS:()=>G,EventHandler:()=>ve,GRAPHREFLY_REQUEST_GRAPH:()=>R,GRAPHREFLY_ROOT_GRAPH:()=>v,GraphCron:()=>fe,GraphInterval:()=>he,GraphReflyEventExplorer:()=>x,GraphReflyGuard:()=>Re,GraphReflyGuardImpl:()=>I,GraphReflyModule:()=>Q,INTERVAL_HANDLERS:()=>O,InjectCqrsGraph:()=>de,InjectGraph:()=>ue,InjectNode:()=>pe,ObserveGateway:()=>B,OnGraphEvent:()=>le,QUERY_HANDLERS:()=>H,QueryHandler:()=>ye,SAGA_HANDLERS:()=>N,SagaHandler:()=>ge,fromHeader:()=>Ee,fromJwtPayload:()=>V,getActor:()=>we,getGraphToken:()=>m,getNodeToken:()=>y,observeSSE:()=>Me,observeSubscription:()=>Ce,toObservable:()=>se});import{Inject as j}from"@nestjs/common";var v=Symbol.for("graphrefly:root-graph");var R=Symbol.for("graphrefly:request-graph");function m(s){return Symbol.for(`graphrefly:graph:${s}`)}function y(s){return Symbol.for(`graphrefly:node:${s}`)}var G=new Map,O=new Map,D=new Map,A=new Map,S=new Map,H=new Map,N=new Map;function ue(s){return s==="request"?j(R):j(s?m(s):v)}function de(s){return j(m(s))}function pe(s){return j(y(s))}function le(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=G.get(o)??[];n.push({nodeName:s,methodKey:t}),G.set(o,n)})}}function he(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=O.get(o)??[];n.push({ms:s,methodKey:t}),O.set(o,n)})}}function fe(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=D.get(o)??[];n.push({expr:s,methodKey:t}),D.set(o,n)})}}function me(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=A.get(n)??[];a.push({cqrsName:s,commandName:e,methodKey:o}),A.set(n,a)})}}function ve(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=S.get(n)??[];a.push({cqrsName:s,eventName:e,methodKey:o}),S.set(n,a)})}}function ye(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=H.get(n)??[];a.push({cqrsName:s,projectionName:e,methodKey:o}),H.set(n,a)})}}function ge(s,e,r){return(t,o)=>{let n=o.name;o.addInitializer(function(){let a=this.constructor,c=N.get(a)??[];c.push({cqrsName:s,eventNames:r,sagaName:e,methodKey:n}),N.set(a,c)})}}var be=0,x=class{constructor(e,r){this.graph=e;this.moduleRef=r}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,r]of G){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireEventHandler(t,o)}}wireEventHandler(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),a=this.observeNode(r.nodeName).subscribe(c=>{for(let l of c)l[0]===b&&o(l[1])});this.disposers.push(a)}wireIntervals(){for(let[e,r]of O){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireIntervalHandler(t,e,o)}}wireIntervalHandler(e,r,t){let o=e[t.methodKey];if(typeof o!="function")return;let n=o.bind(e),c=`__schedule__.${r.name??"anonymous"}.${String(t.methodKey)}.${be++}`,l=ae(t.ms,{period:t.ms,name:c});this.graph.add(l),this.scheduleNodeNames.push(c);let p=this.observeNode(c).subscribe(u=>{for(let d of u)d[0]===b&&n(d[1])});this.disposers.push(p)}wireCrons(){for(let[e,r]of D){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCronHandler(t,e,o)}}wireCronHandler(e,r,t){let o=e[t.methodKey];if(typeof o!="function")return;let n=o.bind(e),c=`__schedule__.${r.name??"anonymous"}.${String(t.methodKey)}.${be++}`,l=ie(t.expr,{name:c});this.graph.add(l),this.scheduleNodeNames.push(c);let p=this.observeNode(c).subscribe(u=>{for(let d of u)d[0]===b&&n(d[1])});this.disposers.push(p)}wireCqrsCommands(){for(let[e,r]of A){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsCommand(t,o)}}wireCqrsCommand(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);n&&n.command(r.commandName,o)}wireCqrsEvents(){for(let[e,r]of S){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsEventHandler(t,o)}}wireCqrsEventHandler(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);if(!n)return;n.event(r.eventName);let c=n.resolve(r.eventName).cache,l=c&&c.length>0?c[c.length-1].seq:0,p=this.observeNodeOn(n,r.eventName).subscribe(u=>{for(let d of u)if(d[0]===b){let g=d[1];for(let i of g)i.seq>l&&(o(i),l=i.seq)}});this.disposers.push(p)}wireCqrsQueries(){for(let[e,r]of H){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsQuery(t,o)}}wireCqrsQuery(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);if(!n)return;let c=this.observeNodeOn(n,r.projectionName).subscribe(l=>{for(let f of l)f[0]===b&&o(f[1])});this.disposers.push(c)}wireCqrsSagas(){for(let[e,r]of N){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsSaga(t,o)}}wireCqrsSaga(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);n&&n.saga(r.sagaName,r.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,r){return e.observe(r)}resolveCqrsGraph(e){try{return this.moduleRef.get(m(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};function Me(s,e,r){let{actor:t,serialize:o=De,keepAliveMs:n,signal:a}=r??{},c=new TextEncoder,l,f=r?.highWaterMark!=null,p,u,d=[],g=!1;return new ReadableStream({start(i){let h,w=()=>{},M=()=>{if(!g){g=!0,h!==void 0&&clearInterval(h),a?.removeEventListener("abort",K),w(),p?.dispose(),u?.(),u=void 0;for(let k of d)i.enqueue(k.frame);d.length=0,i.close()}};l=M;let K=()=>M(),ee=s.observe(e,{actor:t});f&&(p=P(k=>ee.up(k),{highWaterMark:r.highWaterMark,lowWaterMark:r.lowWaterMark??Math.floor(r.highWaterMark/2)})),w=ee.subscribe(k=>{for(let $ of k){if(g)return;let q=$[0];if(q===b){let C=c.encode(Y("data",o($[1])));f?(d.push({frame:C,counted:!0}),p.onEnqueue(),u?.(),u=void 0):i.enqueue(C)}else if(q===W){let C=c.encode(Y("error",o($[1])));f?(d.push({frame:C,counted:!1}),u?.(),u=void 0):i.enqueue(C),M();return}else if(q===T||q===_){if(q===T){let C=c.encode(Y("complete"));f?(d.push({frame:C,counted:!1}),u?.(),u=void 0):i.enqueue(C)}M();return}}}),n!==void 0&&n>0&&(h=setInterval(()=>{g||(f?(d.push({frame:c.encode(`: keepalive
1
+ import{c as ce}from"./chunk-EIFHFDFD.js";import{a as se,b as P}from"./chunk-5QDBSZBV.js";import{j as L}from"./chunk-4JBKKUCJ.js";import{f as ae,h as ie}from"./chunk-UMH3HSP7.js";import{i as ne,j as U}from"./chunk-7AJKUA36.js";import{b,h as _,i as T,j as W}from"./chunk-CK2E7BTU.js";import{b as Oe,c as re,d as te,e as oe}from"./chunk-QYADASLV.js";var ke={};Oe(ke,{ACTOR_KEY:()=>F,COMMAND_HANDLERS:()=>A,CQRS_EVENT_HANDLERS:()=>S,CRON_HANDLERS:()=>D,CommandHandler:()=>me,EVENT_HANDLERS:()=>G,EventHandler:()=>ve,GRAPHREFLY_REQUEST_GRAPH:()=>R,GRAPHREFLY_ROOT_GRAPH:()=>v,GraphCron:()=>fe,GraphInterval:()=>he,GraphReflyEventExplorer:()=>x,GraphReflyGuard:()=>Re,GraphReflyGuardImpl:()=>I,GraphReflyModule:()=>Q,INTERVAL_HANDLERS:()=>O,InjectCqrsGraph:()=>de,InjectGraph:()=>ue,InjectNode:()=>pe,ObserveGateway:()=>B,OnGraphEvent:()=>le,QUERY_HANDLERS:()=>H,QueryHandler:()=>ye,SAGA_HANDLERS:()=>N,SagaHandler:()=>ge,fromHeader:()=>Ee,fromJwtPayload:()=>V,getActor:()=>we,getGraphToken:()=>m,getNodeToken:()=>y,observeSSE:()=>Me,observeSubscription:()=>Ce,toObservable:()=>se});import{Inject as j}from"@nestjs/common";var v=Symbol.for("graphrefly:root-graph");var R=Symbol.for("graphrefly:request-graph");function m(s){return Symbol.for(`graphrefly:graph:${s}`)}function y(s){return Symbol.for(`graphrefly:node:${s}`)}var G=new Map,O=new Map,D=new Map,A=new Map,S=new Map,H=new Map,N=new Map;function ue(s){return s==="request"?j(R):j(s?m(s):v)}function de(s){return j(m(s))}function pe(s){return j(y(s))}function le(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=G.get(o)??[];n.push({nodeName:s,methodKey:t}),G.set(o,n)})}}function he(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=O.get(o)??[];n.push({ms:s,methodKey:t}),O.set(o,n)})}}function fe(s){return(e,r)=>{let t=r.name;r.addInitializer(function(){let o=this.constructor,n=D.get(o)??[];n.push({expr:s,methodKey:t}),D.set(o,n)})}}function me(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=A.get(n)??[];a.push({cqrsName:s,commandName:e,methodKey:o}),A.set(n,a)})}}function ve(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=S.get(n)??[];a.push({cqrsName:s,eventName:e,methodKey:o}),S.set(n,a)})}}function ye(s,e){return(r,t)=>{let o=t.name;t.addInitializer(function(){let n=this.constructor,a=H.get(n)??[];a.push({cqrsName:s,projectionName:e,methodKey:o}),H.set(n,a)})}}function ge(s,e,r){return(t,o)=>{let n=o.name;o.addInitializer(function(){let a=this.constructor,c=N.get(a)??[];c.push({cqrsName:s,eventNames:r,sagaName:e,methodKey:n}),N.set(a,c)})}}var be=0,x=class{constructor(e,r){this.graph=e;this.moduleRef=r}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,r]of G){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireEventHandler(t,o)}}wireEventHandler(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),a=this.observeNode(r.nodeName).subscribe(c=>{for(let l of c)l[0]===b&&o(l[1])});this.disposers.push(a)}wireIntervals(){for(let[e,r]of O){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireIntervalHandler(t,e,o)}}wireIntervalHandler(e,r,t){let o=e[t.methodKey];if(typeof o!="function")return;let n=o.bind(e),c=`__schedule__.${r.name??"anonymous"}.${String(t.methodKey)}.${be++}`,l=ae(t.ms,{period:t.ms,name:c});this.graph.add(l),this.scheduleNodeNames.push(c);let p=this.observeNode(c).subscribe(u=>{for(let d of u)d[0]===b&&n(d[1])});this.disposers.push(p)}wireCrons(){for(let[e,r]of D){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCronHandler(t,e,o)}}wireCronHandler(e,r,t){let o=e[t.methodKey];if(typeof o!="function")return;let n=o.bind(e),c=`__schedule__.${r.name??"anonymous"}.${String(t.methodKey)}.${be++}`,l=ie(t.expr,{name:c});this.graph.add(l),this.scheduleNodeNames.push(c);let p=this.observeNode(c).subscribe(u=>{for(let d of u)d[0]===b&&n(d[1])});this.disposers.push(p)}wireCqrsCommands(){for(let[e,r]of A){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsCommand(t,o)}}wireCqrsCommand(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);n&&n.command(r.commandName,o)}wireCqrsEvents(){for(let[e,r]of S){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsEventHandler(t,o)}}wireCqrsEventHandler(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);if(!n)return;n.event(r.eventName);let c=n.resolve(r.eventName).cache,l=c&&c.length>0?c[c.length-1].seq:0,p=this.observeNodeOn(n,r.eventName).subscribe(u=>{for(let d of u)if(d[0]===b){let g=d[1];for(let i of g)i.seq>l&&(o(i),l=i.seq)}});this.disposers.push(p)}wireCqrsQueries(){for(let[e,r]of H){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsQuery(t,o)}}wireCqrsQuery(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);if(!n)return;let c=this.observeNodeOn(n,r.projectionName).subscribe(l=>{for(let f of l)f[0]===b&&o(f[1])});this.disposers.push(c)}wireCqrsSagas(){for(let[e,r]of N){let t=this.resolveInstance(e);if(t)for(let o of r)this.wireCqrsSaga(t,o)}}wireCqrsSaga(e,r){let t=e[r.methodKey];if(typeof t!="function")return;let o=t.bind(e),n=this.resolveCqrsGraph(r.cqrsName);n&&n.saga(r.sagaName,r.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,r){return e.observe(r)}resolveCqrsGraph(e){try{return this.moduleRef.get(m(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};function Me(s,e,r){let{actor:t,serialize:o=De,keepAliveMs:n,signal:a}=r??{},c=new TextEncoder,l,f=r?.highWaterMark!=null,p,u,d=[],g=!1;return new ReadableStream({start(i){let h,w=()=>{},M=()=>{if(!g){g=!0,h!==void 0&&clearInterval(h),a?.removeEventListener("abort",K),w(),p?.dispose(),u?.(),u=void 0;for(let k of d)i.enqueue(k.frame);d.length=0,i.close()}};l=M;let K=()=>M(),ee=s.observe(e,{actor:t});f&&(p=P(k=>ee.up(k),{highWaterMark:r.highWaterMark,lowWaterMark:r.lowWaterMark??Math.floor(r.highWaterMark/2)})),w=ee.subscribe(k=>{for(let $ of k){if(g)return;let q=$[0];if(q===b){let C=c.encode(Y("data",o($[1])));f?(d.push({frame:C,counted:!0}),p.onEnqueue(),u?.(),u=void 0):i.enqueue(C)}else if(q===W){let C=c.encode(Y("error",o($[1])));f?(d.push({frame:C,counted:!1}),u?.(),u=void 0):i.enqueue(C),M();return}else if(q===T||q===_){if(q===T){let C=c.encode(Y("complete"));f?(d.push({frame:C,counted:!1}),u?.(),u=void 0):i.enqueue(C)}M();return}}}),n!==void 0&&n>0&&(h=setInterval(()=>{g||(f?(d.push({frame:c.encode(`: keepalive
2
2
 
3
3
  `),counted:!1}),u?.(),u=void 0):i.enqueue(c.encode(`: keepalive
4
4
 
@@ -1 +1 @@
1
- import{a as w}from"./chunk-TWMEGG45.js";import{A as b,B as F,C as H,D as G,E as k,F as B,G as Y,H as h,I as v,J as P,K as W,i as K,j,k as S,m as g,n as C,o as I,p as M,q as _,r as u,s as q,t as z,u as J,v as Q,w as L,x as m,y as x,z as V}from"./chunk-W4TSQ6RJ.js";import{a as e,b as t,c as o,d as p,e as r,f as n,g as s,h as i,i as y,j as a,k as d,l as c,m as N,n as T,o as E,p as O,q as D,r as A,s as f,t as l,u as R}from"./chunk-CK2E7BTU.js";import{b as U}from"./chunk-QYADASLV.js";var X={};U(X,{COMPLETE:()=>y,COMPLETE_MSG:()=>E,COMPLETE_ONLY_BATCH:()=>l,DATA:()=>t,DEFAULT_ACTOR:()=>K,DIRTY:()=>o,DIRTY_MSG:()=>d,DIRTY_ONLY_BATCH:()=>D,ERROR:()=>a,GraphReFlyConfig:()=>_,GuardDenied:()=>q,INVALIDATE:()=>r,INVALIDATE_MSG:()=>N,INVALIDATE_ONLY_BATCH:()=>f,NodeImpl:()=>H,PAUSE:()=>n,RESOLVED:()=>p,RESOLVED_MSG:()=>c,RESOLVED_ONLY_BATCH:()=>A,RESUME:()=>s,START:()=>e,START_MSG:()=>T,TEARDOWN:()=>i,TEARDOWN_MSG:()=>O,TEARDOWN_ONLY_BATCH:()=>R,accessHintForGuard:()=>Q,advanceVersion:()=>x,autoTrackNode:()=>P,batch:()=>g,configure:()=>F,createVersioning:()=>m,defaultConfig:()=>b,defaultHash:()=>L,derived:()=>Y,downWithBatch:()=>C,dynamicNode:()=>v,effect:()=>h,isBatching:()=>S,isV1:()=>V,monotonicNs:()=>I,node:()=>G,normalizeActor:()=>j,pipe:()=>W,policy:()=>z,policyFromRules:()=>J,producer:()=>B,registerBuiltins:()=>u,resolveDescribeFields:()=>w,state:()=>k,wallClockNs:()=>M});export{X as a};
1
+ import{a as w}from"./chunk-N2KKISCE.js";import{A as b,B as F,C as H,D as G,E as k,F as B,G as Y,H as h,I as v,J as P,K as W,i as K,j,k as S,m as g,n as C,o as I,p as M,q as _,r as u,s as q,t as z,u as J,v as Q,w as L,x as m,y as x,z as V}from"./chunk-7AJKUA36.js";import{a as e,b as t,c as o,d as p,e as r,f as n,g as s,h as i,i as y,j as a,k as d,l as c,m as N,n as T,o as E,p as O,q as D,r as A,s as f,t as l,u as R}from"./chunk-CK2E7BTU.js";import{b as U}from"./chunk-QYADASLV.js";var X={};U(X,{COMPLETE:()=>y,COMPLETE_MSG:()=>E,COMPLETE_ONLY_BATCH:()=>l,DATA:()=>t,DEFAULT_ACTOR:()=>K,DIRTY:()=>o,DIRTY_MSG:()=>d,DIRTY_ONLY_BATCH:()=>D,ERROR:()=>a,GraphReFlyConfig:()=>_,GuardDenied:()=>q,INVALIDATE:()=>r,INVALIDATE_MSG:()=>N,INVALIDATE_ONLY_BATCH:()=>f,NodeImpl:()=>H,PAUSE:()=>n,RESOLVED:()=>p,RESOLVED_MSG:()=>c,RESOLVED_ONLY_BATCH:()=>A,RESUME:()=>s,START:()=>e,START_MSG:()=>T,TEARDOWN:()=>i,TEARDOWN_MSG:()=>O,TEARDOWN_ONLY_BATCH:()=>R,accessHintForGuard:()=>Q,advanceVersion:()=>x,autoTrackNode:()=>P,batch:()=>g,configure:()=>F,createVersioning:()=>m,defaultConfig:()=>b,defaultHash:()=>L,derived:()=>Y,downWithBatch:()=>C,dynamicNode:()=>v,effect:()=>h,isBatching:()=>S,isV1:()=>V,monotonicNs:()=>I,node:()=>G,normalizeActor:()=>j,pipe:()=>W,policy:()=>z,policyFromRules:()=>J,producer:()=>B,registerBuiltins:()=>u,resolveDescribeFields:()=>w,state:()=>k,wallClockNs:()=>M});export{X as a};
@@ -1 +1 @@
1
- import{E as v,G as w,m as h}from"./chunk-W4TSQ6RJ.js";import{b as m,c as V}from"./chunk-CK2E7BTU.js";function x(s,e){if(s===e)return 0;let r=typeof s;if(r===typeof e&&(r==="number"||r==="string"||r==="boolean"||r==="bigint")){let i=s,n=e;return i<n?-1:i>n?1:0}return String(s).localeCompare(String(e))}function k(s,e){let r=x(s[0],e[0]);return r!==0?r:x(s[1],e[1])}function g(s){return[s.secondary,s.primary]}function y(s,e){let r=g(e),o=0,i=s.length;for(;o<i;){let n=o+i>>1;k(r,g(s[n]))>0?o=n+1:i=n}return o}var b=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,r,o,i){let n=this._byPrimary.get(e),a={primary:e,secondary:r,value:o};if(n!==void 0&&i?.equals?.(n,a))return!1;if(n!==void 0){let p=y(this._buf,n);this._buf.splice(p,1)}let d=y(this._buf,a);return this._buf.splice(d,0,a),this._byPrimary.set(e,a),this._version+=1,n===void 0}upsertMany(e,r){let o=0;try{for(let i of e){let n=this._byPrimary.get(i.primary),a={primary:i.primary,secondary:i.secondary,value:i.value};if(n!==void 0&&r?.equals?.(n,a))continue;if(n!==void 0){let p=y(this._buf,n);this._buf.splice(p,1)}let d=y(this._buf,a);this._buf.splice(d,0,a),this._byPrimary.set(i.primary,a),o+=1}}finally{o>0&&(this._version+=1)}return o}delete(e){let r=this._byPrimary.get(e);if(r===void 0)return!1;let o=y(this._buf,r);return this._buf.splice(o,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let r=0;try{for(let o of e){let i=this._byPrimary.get(o);if(i===void 0)continue;let n=y(this._buf,i);this._buf.splice(n,1),this._byPrimary.delete(o),r+=1}}finally{r>0&&(this._version+=1)}return r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let r of this._buf)e.set(r.primary,r.value);return e}};function R(s){return s.subscribe(()=>{})}function U(s={}){let{name:e,versioning:r,equals:o,backend:i}=s,n=i??new b;function a(t){return t?.equals!==void 0||o===void 0?t:{...t,equals:o}}let d=v([],{name:e,describeKind:"state",equals:(t,u)=>t===u,...r!=null?{versioning:r}:{}}),p=w([d],([t])=>{let u=t,l=new Map;for(let f of u)l.set(f.primary,f.value);return l},{initial:n.toPrimaryMap(),describeKind:"derived"}),_=R(p),K=!1;function I(){let t=n.toArray();h(()=>{d.down([[V]]),d.down([[m,t]])})}function c(t){let u=n.version;try{return t()}finally{n.version!==u&&I()}}return{ordered:d,byPrimary:p,has(t){return n.has(t)},get(t){return n.get(t)},get size(){return n.size},upsert(t,u,l,f){return c(()=>n.upsert(t,u,l,a(f)))},upsertMany(t,u){let l=[...t];l.length!==0&&c(()=>n.upsertMany(l,a(u)))},delete(t){c(()=>n.delete(t))},deleteMany(t){let u=[...t];u.length!==0&&c(()=>n.deleteMany(u))},clear(){c(()=>n.clear())},dispose(){K||(K=!0,_())}}}export{b as a,U as b};
1
+ import{E as v,G as w,m as h}from"./chunk-7AJKUA36.js";import{b as m,c as V}from"./chunk-CK2E7BTU.js";function x(s,e){if(s===e)return 0;let r=typeof s;if(r===typeof e&&(r==="number"||r==="string"||r==="boolean"||r==="bigint")){let i=s,n=e;return i<n?-1:i>n?1:0}return String(s).localeCompare(String(e))}function k(s,e){let r=x(s[0],e[0]);return r!==0?r:x(s[1],e[1])}function g(s){return[s.secondary,s.primary]}function y(s,e){let r=g(e),o=0,i=s.length;for(;o<i;){let n=o+i>>1;k(r,g(s[n]))>0?o=n+1:i=n}return o}var b=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,r,o,i){let n=this._byPrimary.get(e),a={primary:e,secondary:r,value:o};if(n!==void 0&&i?.equals?.(n,a))return!1;if(n!==void 0){let p=y(this._buf,n);this._buf.splice(p,1)}let d=y(this._buf,a);return this._buf.splice(d,0,a),this._byPrimary.set(e,a),this._version+=1,n===void 0}upsertMany(e,r){let o=0;try{for(let i of e){let n=this._byPrimary.get(i.primary),a={primary:i.primary,secondary:i.secondary,value:i.value};if(n!==void 0&&r?.equals?.(n,a))continue;if(n!==void 0){let p=y(this._buf,n);this._buf.splice(p,1)}let d=y(this._buf,a);this._buf.splice(d,0,a),this._byPrimary.set(i.primary,a),o+=1}}finally{o>0&&(this._version+=1)}return o}delete(e){let r=this._byPrimary.get(e);if(r===void 0)return!1;let o=y(this._buf,r);return this._buf.splice(o,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let r=0;try{for(let o of e){let i=this._byPrimary.get(o);if(i===void 0)continue;let n=y(this._buf,i);this._buf.splice(n,1),this._byPrimary.delete(o),r+=1}}finally{r>0&&(this._version+=1)}return r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let r of this._buf)e.set(r.primary,r.value);return e}};function R(s){return s.subscribe(()=>{})}function U(s={}){let{name:e,versioning:r,equals:o,backend:i}=s,n=i??new b;function a(t){return t?.equals!==void 0||o===void 0?t:{...t,equals:o}}let d=v([],{name:e,describeKind:"state",equals:(t,u)=>t===u,...r!=null?{versioning:r}:{}}),p=w([d],([t])=>{let u=t,l=new Map;for(let f of u)l.set(f.primary,f.value);return l},{initial:n.toPrimaryMap(),describeKind:"derived"}),_=R(p),K=!1;function I(){let t=n.toArray();h(()=>{d.down([[V]]),d.down([[m,t]])})}function c(t){let u=n.version;try{return t()}finally{n.version!==u&&I()}}return{ordered:d,byPrimary:p,has(t){return n.has(t)},get(t){return n.get(t)},get size(){return n.size},upsert(t,u,l,f){return c(()=>n.upsert(t,u,l,a(f)))},upsertMany(t,u){let l=[...t];l.length!==0&&c(()=>n.upsertMany(l,a(u)))},delete(t){c(()=>n.delete(t))},deleteMany(t){let u=[...t];u.length!==0&&c(()=>n.deleteMany(u))},clear(){c(()=>n.clear())},dispose(){K||(K=!0,_())}}}export{b as a,U as b};
@@ -0,0 +1 @@
1
+ import{c as R}from"./chunk-K54OKWNY.js";import{b as N}from"./chunk-XRSHMHEG.js";import{j as k}from"./chunk-4JBKKUCJ.js";import{B as g}from"./chunk-UMH3HSP7.js";import{D as T,E as S,G as y,m as q,p as w,t as u}from"./chunk-7AJKUA36.js";import{b as A}from"./chunk-QYADASLV.js";var P={};A(P,{CqrsGraph:()=>h,MemoryEventStore:()=>_,cqrs:()=>O});var j=u((i,e)=>{i("write"),i("signal"),e("observe")}),D=u((i,e)=>{i("observe"),i("signal"),e("write")}),H=u((i,e)=>{i("observe"),i("signal"),e("write")});function m(i,e){return R("cqrs",i,e)}var _=class{_store=new Map;persist(e){let t=this._store.get(e.type);t||(t=[],this._store.set(e.type,t)),t.push(e)}loadEvents(e,t){let n=this._store.get(e)??[],r=t?.timestampNs,s=t?.seq,o=r==null?[...n]:n.filter(d=>d.timestampNs>r||d.timestampNs===r&&d.seq>(s??-1)),a=o.length>0?o[o.length-1]:void 0;return{events:o,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:t}}clear(){this._store.clear()}},h=class extends k{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,t={}){super(e,t.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let t=this._eventLogs.get(e);if(t)return t.node;let n=N([],{name:e,versioning:0}),r=n.entries,s=y([r],([o])=>o,{name:e,describeKind:"state",meta:m("event",{event_name:e}),guard:H,initial:r.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(g(s)),this._eventLogs.set(e,{log:n,node:s}),s}_appendEvent(e,t){let n=this._eventLogs.get(e);if(n||(this.event(e),n=this._eventLogs.get(e)),n.node.status==="completed"||n.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${n.node.status}).`);let r=n.log.entries.v,s={type:e,payload:t,timestampNs:w(),seq:++this._seq,...r!=null?{v0:{id:r.id,version:r.version}}:{}};n.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,t){let n=S(void 0,{name:e,describeKind:"state",meta:{...m("command",{command_name:e}),error:null},guard:j});return this.add(n,{name:e}),this._commandHandlers.set(e,t),n}dispatch(e,t){let n=this._commandHandlers.get(e);if(!n)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let r=this.resolve(e);q(()=>{r.emit(t,{internal:!0});try{n(t,{emit:(s,o)=>this._appendEvent(s,o)}),r.meta.error.emit(null,{internal:!0})}catch(s){throw r.meta.error.emit(s,{internal:!0}),s}})}projection(e,t,n,r){let s=t.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),o=y(s,a=>{let d=[];for(let v of a){let p=v;d.push(...p)}return d.sort((v,p)=>v.timestampNs-p.timestampNs||v.seq-p.seq),n(r,d)},{name:e,describeKind:"derived",meta:m("projection",{projection_name:e,source_events:t}),guard:D,initial:r});return this.add(o,{name:e}),this._keepaliveDisposers.push(g(o)),this._projections.add(e),o}saga(e,t,n){let r=t.map(d=>(this._eventLogs.has(d)||this.event(d),this._eventLogs.get(d).node)),s=new Map,o={},a=T(r,(d,v)=>{let p=o.n.meta.error;for(let c=0;c<d.length;c++){let E=d[c];if(E==null||E.length===0)continue;let l=E.at(-1);if(!l)continue;let f=t[c],C=s.get(f)??0;if(l.length>C){let b=l.slice(C);for(let L of b)try{n(L),p.emit(null,{internal:!0})}catch(x){p.emit(x,{internal:!0})}s.set(f,l.length)}}},{name:e,describeKind:"effect",meta:{...m("saga",{saga_name:e,source_events:t}),error:null}});return o.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(g(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,t,n){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let r=[];for(let s of e){let o=await this._eventStore.loadEvents(s);r.push(...o.events)}return r.sort((s,o)=>s.timestampNs-o.timestampNs||s.seq-o.seq),t(n,r)}};function O(i,e){return new h(i,e)}export{_ as a,h as b,O as c,P as d};
@@ -0,0 +1 @@
1
+ import{a as j,c as K,d as V,e as $}from"./chunk-4VXL3UZK.js";import{a as R}from"./chunk-ESMPEKEV.js";import{c as S}from"./chunk-I6VIH3VA.js";import{n as D}from"./chunk-WQ7I7JVU.js";import{m as w,w as T}from"./chunk-UMH3HSP7.js";import{G as N,o as b,p as L}from"./chunk-7AJKUA36.js";import{j as O}from"./chunk-CK2E7BTU.js";function v(){let e=new Error("aborted");return e.name="AbortError",e}function W(e,r){return e<=0?Promise.resolve():r?.aborted?Promise.reject(v()):new Promise((t,a)=>{let p=new R,u,y=()=>{p.cancel(),r&&u&&r.removeEventListener("abort",u)};p.start(e,()=>{y(),t()}),r&&(u=()=>{y(),a(v())},r.addEventListener("abort",u,{once:!0}))})}function U(e={}){let r=e.provider??"dry-run",t=e.model??"dry-run-v1",a=e.latencyMs??0,p=Math.max(1,e.streamChunkSize??16),u=e.respond??(d=>{let o=[...d].reverse().find(n=>n.role==="user");return o?`echo: ${o.content}`:"dry-run: no user message"}),y=e.usage??((d,o)=>{let n=d.reduce((s,l)=>s+l.content.length,0);return{input:{regular:Math.ceil(n/4)},output:{regular:Math.ceil(o.length/4)}}});return{provider:r,model:t,async invoke(d,o){if(await W(a,o?.signal),o?.signal?.aborted)throw v();let n=u(d,o),s=y(d,n);return{content:n,usage:s,finishReason:"stop",model:o?.model??t,provider:r,tier:o?.tier,metadata:{dryRun:!0}}},async*stream(d,o){let n=u(d,o),s=y(d,n),l=Math.ceil(n.length/p)||1,i=a>0?a/l:0;for(let c=0;c<n.length;c+=p){if(o?.signal?.aborted)throw v();await W(i,o?.signal),yield{type:"token",delta:n.slice(c,c+p)}}yield{type:"usage",usage:s},yield{type:"finish",reason:"stop"}}}}function _(e){let{storage:r,mode:t="read-write",keyFn:a,keyPrefix:p="llm-replay"}=e,y=V({storage:r,keyPrefix:p,mode:t==="read-strict"?"read":t,keyContext:({messages:o,opts:n})=>{let{signal:s,keyContext:l,...i}=n??{};return{messages:o,opts:i}}});async function d(o,n){if(a){if(a.length<=1){let l={messages:o,opts:n,context:n?.keyContext},i=await a(l);return`${p}:${i}`}let s=await a(o,n);return`${p}:${s}`}return y.keyFor({messages:o,opts:n})}return{keyFor:d,async lookup(o,n){if(t!=="write"){if(a){let s=await d(o,n),l=await r.load(s);return l??void 0}return y.lookup({messages:o,opts:n})}},async store(o,n,s){if(t!=="read"){if(a){let l=await d(o,n);await r.save(l,s);return}await y.store({messages:o,opts:n},s)}},async forget(o,n){if(!(t==="read"||t==="write")&&r.clear){if(a){let s=await d(o,n);await r.clear(s);return}await y.forget({messages:o,opts:n})}}}}function z(e,r,t){return{provider:t?.provider??e.provider,model:t?.model??e.model,capabilities:t?.capabilities??e.capabilities?.bind(e),invoke:r.invoke,stream:r.stream}}function ce(e,r){let{onResp:t,onError:a,name:p}=r;if(e!=null&&typeof e.then=="function"){let n=e;return a?n.then(t).catch(s=>{throw a(s),s}):n.then(t)}if(e!=null&&typeof e=="object"&&"content"in e)return t(e);let u=w(e);if(a){let n=!1;u.subscribe(s=>{for(let l of s){if(n)return;l[0]===O&&(n=!0,a(l[1]))}})}let y,d=!1,o=D(u,n=>{y=t(n),d=!0});return N([o],([n])=>n==null?null:d?y:t(n),{name:p??"adapt/invokeTap"})}function pe(e){let r=e.endNs??b();return{timestamp:r,wallClock:e.startWallClockNs??L(),provider:e.provider,model:e.model,tier:e.tier,usage:e.usage,latencyMs:Math.max(0,(r-e.startNs)/1e6),method:e.method,...e.error?{error:e.error}:{}}}function ye(){return{input:{regular:0},output:{regular:0}}}var G=Symbol.for("graphrefly.adapter.middlewareLayers");function J(e,r,t){let p=[...t?Q(t):[],r];return Object.defineProperty(e,G,{value:Object.freeze(p),enumerable:!1,writable:!1,configurable:!1}),e}function Q(e){let r=e[G];return Array.isArray(r)?r:[]}var M=class extends Error{constructor(t,a){super(`withReplayCache: no cached response for ${a} (key=${t}, mode=read-strict)`);this.key=t;this.method=a}name="ReplayCacheMissError"};function q(e,r){let t=r.mode??"read-write",a=r.cacheStreaming??!1,p=r.captureStreamCadence??!1,u=r.replaySpeed??1,y=r.keyPrefix??"llm-replay",d=t==="read"||t==="read-strict",o=_({storage:r.storage,mode:t==="write-only"?"write":t,keyFn:r.keyFn,keyPrefix:y}),n=i=>i<=0?Promise.resolve():new Promise(c=>{new R().start(i,()=>c())}),s=$(async({messages:i,invokeOpts:c})=>await T(w(e.invoke(i,c))),{keyFn:({_precomputedKey:i})=>i}),l=z(e,{async invoke(i,c){let C=await o.keyFor(i,c),f=await o.lookup(i,c);if(f?.response){let k=f.response;return{...k,metadata:{...k.metadata??{},replayCache:"hit"}}}if(t==="read-strict")throw new M(C,"invoke");let h=await s({messages:i,invokeOpts:c,_precomputedKey:C});return d||await o.store(i,c,{response:h,storedAtNs:L()}),h},async*stream(i,c){if(!a){for await(let m of e.stream(i,c))yield m;return}let C=await o.keyFor(i,c),f=await o.lookup(i,c);if(f){let m=f.response;if(f.streamChunks&&f.streamCadenceMs)for(let g=0;g<f.streamChunks.length;g++){let A=f.streamCadenceMs[g]??0,E=u>0?A/u:0;E>0&&await n(E),yield{type:"token",delta:f.streamChunks[g]?.delta??""}}else m.content&&(yield{type:"token",delta:m.content});m.usage&&(yield{type:"usage",usage:m.usage}),yield{type:"finish",reason:m.finishReason??"stop"};return}if(t==="read-strict")throw new M(C,"stream");let h="",k,P,F=[],I=[],x;for await(let m of e.stream(i,c)){if(m.type==="token"&&(h+=m.delta,p)){let g=b(),A=x===void 0?0:(g-x)/1e6;I.push(A),x=g,F.push({delta:m.delta})}m.type==="usage"&&(k=m.usage),m.type==="finish"&&(P=m.reason),yield m}if((h||k)&&!d){let g={response:{content:h,usage:k??{input:{regular:0},output:{regular:0}},finishReason:P,model:e.model??c?.model??"",provider:e.provider},storedAtNs:L(),...p?{streamChunks:F,streamCadenceMs:I}:{}};await o.store(i,c,g)}}});return J(l,"withReplayCache",e),l}var B=K;var Ae=M;function H(e,r){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:r,provider:e,metadata:{degraded:!0,reason:"no-fixture"}}}function Y(e,r,t){return typeof e=="string"?{content:e,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:t,provider:r,metadata:{degraded:!0,reason:"respond"}}:e}async function X(e,r){if("key"in e)return e.key;let t=B({messages:e.messages,opts:e.invokeOpts??{}}),a=await j(t);return`${r}:${a}`}function Z(e){let r={response:e.response,storedAtNs:L()};if("key"in e&&e.stream){let t=e.stream.chunks.filter(a=>a.type==="token");return{...r,streamChunks:t.map(a=>({delta:a.delta})),streamCadenceMs:e.stream.delaysMs??t.map(()=>0)}}return r}function ee(e,r){let t=[];if(e.fixtures!=null&&t.push("fixtures"),e.fixturesStorage!=null&&t.push("fixturesStorage"),t.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${t.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(e.fixtures){let a=S(),p=e.fixtures,u=(async()=>{for(let y of p){let d=await X(y,r);await a.save(d,Z(y))}})();return u.catch(()=>{}),{tier:a,seedReady:u}}return e.fixturesStorage?{tier:e.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Se(e={}){let r=e.provider??"fallback",t=e.model??"fallback",a=e.onMiss??"respond",p=e.keyPrefix??"fallback",u=e.record?e.record.adapter:a==="throw"?U({provider:r,model:t,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:r,model:t,async invoke(s,l){let i=e.respond?e.respond(s,l):H(r,t);return Y(i,r,t)},async*stream(s,l){let i=e.respond?e.respond(s,l):H(r,t),c=Y(i,r,t);yield{type:"token",delta:c.content},c.usage&&(yield{type:"usage",usage:c.usage}),yield{type:"finish",reason:c.finishReason??"stop"}}},y,d=Promise.resolve();if(e.record){if(!e.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");y=e.record.storage}else{let s=ee(e,p);y=s.tier??S(),d=s.seedReady}let o=e.record?"read-write":a==="throw"?"read-strict":"read",n=q(u,{storage:y,mode:o,keyPrefix:p,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:e.replaySpeed,...e.keyFn?{keyFn:e.keyFn}:{}});return{provider:r,model:t,capabilities:n.capabilities?.bind(n),async invoke(s,l){return await d,n.invoke(s,l)},async*stream(s,l){await d;for await(let i of n.stream(s,l))yield i}}}export{U as a,z as b,ce as c,pe as d,ye as e,J as f,M as g,q as h,B as i,Ae as j,Se as k};
@@ -1 +1 @@
1
- import{d as n}from"./chunk-73Z3W2RN.js";import{k as a}from"./chunk-MGKAO4EK.js";import{b as c}from"./chunk-QYADASLV.js";var s={};c(s,{GuardedExecutionGraph:()=>o,guardedExecution:()=>p});var o=class extends a{enforcer;violations;_target;_defaultActor;constructor(r,e){super(e.name??`${r.name}_guarded`,e.graph),this._target=r,this._defaultActor=e.actor;let t={mode:e.mode??"enforce",name:"enforcer"};e.violationsLimit!=null&&(t.violationsLimit=e.violationsLimit),this.enforcer=n(r,e.policies,t),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(r){let e=r?.actor??this._defaultActor,t={...r,...e!=null?{actor:e}:{}};return this._target.describe(t)}get target(){return this._target}};function p(i,r){return new o(i,r)}export{o as a,p as b,s as c};
1
+ import{d as n}from"./chunk-PWKLZ2XU.js";import{j as a}from"./chunk-4JBKKUCJ.js";import{b as c}from"./chunk-QYADASLV.js";var s={};c(s,{GuardedExecutionGraph:()=>o,guardedExecution:()=>p});var o=class extends a{enforcer;violations;_target;_defaultActor;constructor(r,e){super(e.name??`${r.name}_guarded`,e.graph),this._target=r,this._defaultActor=e.actor;let t={mode:e.mode??"enforce",name:"enforcer"};e.violationsLimit!=null&&(t.violationsLimit=e.violationsLimit),this.enforcer=n(r,e.policies,t),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(r){let e=r?.actor??this._defaultActor,t={...r,...e!=null?{actor:e}:{}};return this._target.describe(t)}get target(){return this._target}};function p(i,r){return new o(i,r)}export{o as a,p as b,s as c};
@@ -1 +1 @@
1
- import{k as f}from"./chunk-MGKAO4EK.js";import{E as d}from"./chunk-W4TSQ6RJ.js";import{b as S}from"./chunk-CK2E7BTU.js";import{b}from"./chunk-QYADASLV.js";var g={};b(g,{create:()=>v});var m=()=>!1;function v(l){let o=new f("zustand"),t=d(void 0,{name:"state",equals:m});o.add(t,{name:"state"});let r=()=>t.cache,n=(e,s)=>{let a=t.cache,i=typeof e=="function"?e(a):e;t.emit(s?i:{...a,...i})},c={getState:r,setState:n,getInitialState:()=>T,subscribe:e=>{let s=!0,a=t.cache;return t.subscribe(i=>{for(let[u,p]of i)if(u===S){if(s){s=!1;continue}e(p,a),a=p}})},destroy:o.destroy.bind(o)},T=l(n,r,c);return t.emit(T),Object.assign(o,c)}export{v as a,g as b};
1
+ import{j as f}from"./chunk-4JBKKUCJ.js";import{E as d}from"./chunk-7AJKUA36.js";import{b as S}from"./chunk-CK2E7BTU.js";import{b}from"./chunk-QYADASLV.js";var g={};b(g,{create:()=>v});var m=()=>!1;function v(l){let o=new f("zustand"),t=d(void 0,{name:"state",equals:m});o.add(t,{name:"state"});let r=()=>t.cache,n=(e,s)=>{let a=t.cache,i=typeof e=="function"?e(a):e;t.emit(s?i:{...a,...i})},c={getState:r,setState:n,getInitialState:()=>T,subscribe:e=>{let s=!0,a=t.cache;return t.subscribe(i=>{for(let[u,p]of i)if(u===S){if(s){s=!1;continue}e(p,a),a=p}})},destroy:o.destroy.bind(o)},T=l(n,r,c);return t.emit(T),Object.assign(o,c)}export{v as a,g as b};
@@ -1 +1 @@
1
- import{A as u,n as i}from"./chunk-W4TSQ6RJ.js";import{b as t,c as o}from"./chunk-CK2E7BTU.js";function s(r,n){r!=null&&i(e=>r.down(e),[[t,n]],u.tierOf)}function p(r,n){let e=r.cache??0;return e>=n?!1:(r.down([[o],[t,e+1]]),!0)}function g(r,n,e){return{[r]:!0,[`${r}_type`]:n,...e??{}}}function l(r){return r.relatedTo?.[0]??r.summary}export{s as a,p as b,g as c,l as d};
1
+ import{A as u,n as i}from"./chunk-7AJKUA36.js";import{b as t,c as o}from"./chunk-CK2E7BTU.js";function s(r,n){r!=null&&i(e=>r.down(e),[[t,n]],u.tierOf)}function p(r,n){let e=r.cache??0;return e>=n?!1:(r.down([[o],[t,e+1]]),!0)}function g(r,n,e){return{[r]:!0,[`${r}_type`]:n,...e??{}}}function l(r){return r.relatedTo?.[0]??r.summary}export{s as a,p as b,g as c,l as d};
@@ -0,0 +1,3 @@
1
+ import{f as he}from"./chunk-VXJX3ZZP.js";import{j as fe}from"./chunk-4JBKKUCJ.js";import{x as ye}from"./chunk-WQ7I7JVU.js";import{D as be,E as T,G as v,H as q,m as ee,o as z}from"./chunk-7AJKUA36.js";import{b as P,j as Z}from"./chunk-CK2E7BTU.js";import{b as Ne}from"./chunk-QYADASLV.js";var we={};Ne(we,{blindVariation:()=>De,errorCritique:()=>Re,refineLoop:()=>Se});function Ie(n){if(typeof n!="object"||n===null)return!1;let l=n;return typeof l.subscribe=="function"&&typeof l.down=="function"&&typeof l.emit=="function"}function pe(n,l){if(n.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(n.length===1){let e=ne(l);return{best:n[0],bestScore:e}}if(l.some(e=>typeof e.candidateIndex=="number")){let e=new Array(n.length);for(let i=0;i<n.length;i++)e[i]={sum:0,count:0};for(let i of l){let d=i.candidateIndex;typeof d=="number"&&d>=0&&d<n.length&&(e[d].sum+=i.score,e[d].count+=1)}let s=n[0],o=e[0].count>0?e[0].sum/e[0].count:Number.NEGATIVE_INFINITY;for(let i=1;i<n.length;i++){let d=e[i].count>0?e[i].sum/e[i].count:Number.NEGATIVE_INFINITY;d>o&&(o=d,s=n[i])}return{best:s,bestScore:o}}let t=n[0],m=l[0]?.score??Number.NEGATIVE_INFINITY;for(let e=1;e<n.length;e++){let s=l[e]?.score??Number.NEGATIVE_INFINITY;s>m&&(m=s,t=n[e])}return{best:t,bestScore:m}}function ne(n){if(n.length===0)return Number.NEGATIVE_INFINITY;let l=0;for(let x of n)l+=x.score;return l/n.length}function Se(n,l,x,t){let m=t.name??"refine-loop",e=new fe(m,t.graph),s=Ie(t.dataset)?t.dataset:T(t.dataset,{name:"dataset"});e.add(s,{name:"dataset"});let o=T(0,{name:"iteration"});e.add(o,{name:"iteration"});let i=T(x,{name:"strategy",equals:()=>!1});e.add(i,{name:"strategy"});let d=T(null,{name:"lastFeedback"});e.add(d,{name:"lastFeedback"});let k=T([],{name:"prevCandidates"});e.add(k,{name:"prevCandidates"});let y=T(!1,{name:"paused"});e.add(y,{name:"paused"});let b=T("running",{name:"status"});e.add(b,{name:"status"});let E=T([],{name:"history",equals:()=>!1});e.add(E,{name:"history"});let h=T(null,{name:"best"});e.add(h,{name:"best"});let N=T(Number.NEGATIVE_INFINITY,{name:"score"});e.add(N,{name:"score"});let C=T(0,{name:"budget-used"});e.add(C,{name:"budget-used"});let R=he("stages");e.mount("stages",R);let A=R.topic("generate"),p=R.topic("evaluate"),G=R.topic("analyze"),te=R.topic("decide"),$=x,B=null,re=[];e.addDisposer(i.subscribe(r=>{for(let a of r)a[0]===P&&($=a[1])})),e.addDisposer(d.subscribe(r=>{for(let a of r)a[0]===P&&(B=a[1])})),e.addDisposer(k.subscribe(r=>{for(let a of r)a[0]===P&&(re=a[1])}));let I=ye(o,r=>{let a=$,c=r===0||B==null;return be([],(u,f)=>{let S=!1;try{let D=c?a.seed(n):a.generate(B,re);if(D instanceof Promise)return D.then(_=>{S||f.emit(_)},_=>{S||f.down([[Z,_]])}),()=>{S=!0};f.emit(D)}catch(D){S=!0,f.down([[Z,D]])}},{describeKind:"producer"})},{name:"candidates"});e.add(I,{name:"candidates"});let ae=q([I],(r,a,c)=>{let u=c.terminalDeps[0];u!==void 0&&u!==!0&&b.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});e.add(ae,{name:"error-watcher"}),e.addDisposer(ae.subscribe(()=>{}));let Y=v([I,o],([r,a])=>({iteration:a,candidates:r,timestamp_ns:z()}),{name:"generate-event"});e.add(Y,{name:"generate-event"}),e.addDisposer(Y.subscribe(()=>{}));let oe=q([Y],([r])=>{A.publish(r)},{name:"generate-publish"});e.add(oe,{name:"generate-publish"}),e.addDisposer(oe.subscribe(()=>{}));let ie=q([I],([r])=>{k.emit(r)},{name:"generate-mirror"});e.add(ie,{name:"generate-mirror"}),e.addDisposer(ie.subscribe(()=>{}));let V=l(I,s);e.add(V,{name:"scores"});let j=v([V,I,o],([r,a,c])=>({iteration:c,candidates:a,scores:r,timestamp_ns:z()}),{name:"evaluate-event"});e.add(j,{name:"evaluate-event"}),e.addDisposer(j.subscribe(()=>{}));let se=q([j],([r])=>{p.publish(r)},{name:"evaluate-publish"});e.add(se,{name:"evaluate-publish"}),e.addDisposer(se.subscribe(()=>{}));let L=v([V,I],([r,a])=>$.analyze(r,a),{name:"feedback"});e.add(L,{name:"feedback"});let M=v([L,I,o],([r,a,c])=>({iteration:c,candidates:a,feedback:r,timestamp_ns:z()}),{name:"analyze-event"});e.add(M,{name:"analyze-event"}),e.addDisposer(M.subscribe(()=>{}));let de=q([M],([r])=>{G.publish(r)},{name:"analyze-publish"});e.add(de,{name:"analyze-publish"}),e.addDisposer(de.subscribe(()=>{}));let H=v([E],([r])=>{let a=r;if(t.patience==null||a.length<=t.patience)return!1;let c=a.slice(-(t.patience+1)),u=c[0].bestScore;return c.slice(1).every(f=>f.bestScore<=u)},{name:"patience-check"});e.add(H,{name:"patience-check"});let W=v([N],([r])=>t.minScore!=null&&r>=t.minScore,{name:"min-score-check"});e.add(W,{name:"min-score-check"});let K=v([E],([r])=>{let a=r;if(t.minDelta==null||a.length<2)return!1;let c=a[a.length-2].bestScore,u=a[a.length-1].bestScore;return Math.abs(u-c)<t.minDelta},{name:"min-delta-check"});e.add(K,{name:"min-delta-check"});let U=v([C],([r])=>t.maxEvaluations!=null&&r>=t.maxEvaluations,{name:"max-evaluations-check"});e.add(U,{name:"max-evaluations-check"});let J=v([o],([r])=>t.maxIterations!=null&&r>=t.maxIterations,{name:"max-iterations-check"});e.add(J,{name:"max-iterations-check"});let le=v([C],([r])=>t.budget!=null&&r>=t.budget,{name:"budget-exhausted-check"});e.add(le,{name:"budget-exhausted-check"}),e.addDisposer(H.subscribe(()=>{})),e.addDisposer(W.subscribe(()=>{})),e.addDisposer(K.subscribe(()=>{})),e.addDisposer(U.subscribe(()=>{})),e.addDisposer(J.subscribe(()=>{})),e.addDisposer(le.subscribe(()=>{}));let ce=v([H,W,K,U,J],([r,a,c,u,f])=>r?{converged:!0,reason:"patience"}:a?{converged:!0,reason:"min-score"}:c?{converged:!0,reason:"min-delta"}:u?{converged:!0,reason:"max-evaluations"}:f?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});e.add(ce,{name:"converged"}),e.addDisposer(ce.subscribe(()=>{}));let ue=-1,me=q([L,V,I],([r,a,c])=>{let u=o.cache,f=r,S=c,D=a;if(u<=ue)return;ue=u;let{best:_,bestScore:ge}=pe(S,D),Te=E.cache,ve={n:u,candidates:S,scores:D,feedback:f,best:_,bestScore:ge,timestamp_ns:z()},F=[...Te,ve],Q=C.cache+S.length,g="continue",w,Ee=t.budget!=null&&Q>=t.budget,ke=y.cache;if(Ee)g="budget",w="budget";else if(t.minScore!=null&&f.score>=t.minScore)g="converged",w="min-score";else if(t.maxIterations!=null&&u>=t.maxIterations)g="converged",w="max-iterations";else if(t.maxEvaluations!=null&&Q>=t.maxEvaluations)g="converged",w="max-evaluations";else if(t.minDelta!=null&&F.length>=2){let O=F[F.length-2].bestScore,X=F[F.length-1].bestScore;Math.abs(X-O)<t.minDelta&&(g="converged",w="min-delta")}else if(t.patience!=null&&F.length>t.patience){let O=F.slice(-(t.patience+1)),X=O[0].bestScore;O.slice(1).every(xe=>xe.bestScore<=X)&&(g="converged",w="patience")}g==="continue"&&ke&&(g="paused"),ee(()=>{h.emit(_),N.emit(f.score),E.emit(F),C.emit(Q),d.emit(f),te.publish({iteration:u,decision:g,reason:w,timestamp_ns:z()}),g==="continue"?o.emit(u+1):b.emit(g==="converged"?"converged":g==="budget"?"budget":"paused")})},{name:"decide-bridge"});return e.add(me,{name:"decide-bridge"}),e.addDisposer(me.subscribe(()=>{})),Object.assign(e,{best:h,score:N,status:b,history:E,strategy:i,iteration:o,generate:A,evaluate:p,analyze:G,decide:te,setStrategy(r){i.emit(r)},pause(){y.emit(!0)},resume(){b.cache==="paused"&&ee(()=>{y.emit(!1),b.emit("running"),o.emit(o.cache+1)})}})}function De(n){let l=n.width??4;return{name:n.name??"blindVariation",seed(t){return[t]},analyze(t,m){let e=ne(t),s=null;for(let o of t)(!s||o.score<s.score)&&(s=o);return{summary:`blindVariation iteration: mean=${e.toFixed(3)}, n=${t.length}`,score:e,weakTasks:s?[s.taskId]:[]}},async generate(t,m){if(m.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let e=m[m.length-1],s=0,i={prior:e,reportCost:d=>{s+=d}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(i)));let d=[];for(let k=0;k<l;k++)d.push(await n.teacher(i));return d}finally{if(n.tokens!=null&&s>0){let d=n.tokens.cache??0;n.tokens.emit(d+s)}}}}}function Fe(n){return typeof n=="object"&&n!==null&&n.kind==="errorCritique"}function Ce(n,l){return n.length===0?`No task scored below the batch mean (${l.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
2
+ ${n.map(t=>{let m=t.error!=null?` | error: ${t.error}`:"";return`- ${t.taskId} (score=${t.score.toFixed(3)})${m}`}).join(`
3
+ `)}`}function Re(n){let l=n.width??4,x=n.name??"errorCritique",t=n.maxFailureSamples??5,m=n.formatCritique??Ce;return{name:x,seed(e){return[e]},analyze(e,s){let o=ne(e),i=typeof n.failureThreshold=="function"?n.failureThreshold(e):n.failureThreshold,d=i===void 0&&!Number.isFinite(o),k=i??o,y=d?[...e].sort((p,G)=>p.score-G.score):e.filter(p=>p.score<k).slice().sort((p,G)=>p.score-G.score),b=y.slice(0,t),{best:E,bestScore:h}=pe(s,e),N={summary:"",score:o,weakTasks:b.map(p=>p.taskId)},C=m(b,N),R={kind:"errorCritique",best:E,failures:b,critiqueText:C},A=y.length>b.length?` (top ${b.length} retained)`:"";return{summary:`errorCritique iteration: mean=${o.toFixed(3)}, failures=${y.length}${A}/${e.length}, bestScore=${h.toFixed(3)}`,critique:R,weakTasks:b.map(p=>p.taskId),score:o}},async generate(e,s){if(s.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=Fe(e.critique)?e.critique:void 0,i=o!==void 0?o.best:s[s.length-1],d=o?.critiqueText??e.summary,k=o?.failures??[],y=0,E={prior:i,critique:d,failures:k,reportCost:h=>{y+=h}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(E)));let h=[];for(let N=0;N<l;N++)h.push(await n.teacher(E));return h}finally{if(n.tokens!=null&&y>0){let h=n.tokens.cache??0;n.tokens.emit(h+y)}}}}}export{Se as a,De as b,Re as c,we as d};
@@ -1,4 +1,4 @@
1
- import{a as me}from"./chunk-AMBYCIOH.js";import{u as Q}from"./chunk-LI3E75VE.js";import{a as pe}from"./chunk-4OFIQ66T.js";import{e as fe}from"./chunk-VWPRPPKR.js";import{a as M}from"./chunk-33FA6V4B.js";import{b as J,d as K}from"./chunk-5Z4HDCO6.js";import{g as le,k as Y}from"./chunk-MGKAO4EK.js";import{b as A,q as G,r as ce,v as $}from"./chunk-5JDE5JHE.js";import{b as de}from"./chunk-2GQREQ6C.js";import{m as ue}from"./chunk-KASHOCF5.js";import{D as ie,E as b,G as k,H as C,o as L}from"./chunk-W4TSQ6RJ.js";import{b as Ie}from"./chunk-QYADASLV.js";var Ye={};Ie(Ye,{DEFAULT_DECAY_RATE:()=>X,DEFAULT_QUEUE_CONFIGS:()=>Z,DEFAULT_SEVERITY_WEIGHTS:()=>z,HarnessGraph:()=>U,QUEUE_NAMES:()=>N,affectedTaskFilter:()=>Oe,beforeAfterCompare:()=>we,codeChangeBridge:()=>Ce,createIntakeBridge:()=>be,defaultErrorClassifier:()=>W,defaultLlmExecutor:()=>ge,defaultLlmVerifier:()=>ye,evalIntakeBridge:()=>Ne,evalSource:()=>Se,evalVerifier:()=>Le,harnessLoop:()=>Fe,harnessProfile:()=>De,harnessTrace:()=>Be,notifyEffect:()=>_e,priorityScore:()=>Ge,refineExecutor:()=>Qe,strategyKey:()=>P,strategyModel:()=>ee});function be(t,e,r,n){return C([t],([a])=>{if(a==null)return;let d=r(a);for(let i of d)e.publish(i)},{name:n?.name??"intake-bridge"})}function Ne(t,e,r){let n=r?.defaultSeverity??"medium";return C([t],([a])=>{if(a==null)return;let d=Array.isArray(a)?a:[a];for(let i of d)for(let o of i.tasks)if(!(o.valid&&o.judge_scores?.every(s=>s.pass))){if(!o.valid&&(!o.judge_scores||o.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${o.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n});continue}if(o.judge_scores)for(let s of o.judge_scores)s.pass||e.publish({source:"eval",summary:`${o.task_id}: ${s.claim} (model: ${i.model})`,evidence:s.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n})}},{name:r?.name??"eval-intake-bridge"})}function Se(t,e){return $(t,()=>ue(e()))}function we(t,e){return k([t,e],([r,n])=>{let a=r,d=n,i=new Map(a.tasks.map(c=>[c.task_id,c])),o=new Map(d.tasks.map(c=>[c.task_id,c])),s=new Set([...i.keys(),...o.keys()]),u=[],f=[],l=[];for(let c of s){let m=i.get(c),I=o.get(c),g=m?.valid??!1,E=I?.valid??!1,T=m?.judge_scores?m.judge_scores.filter(j=>j.pass).length:void 0,h=I?.judge_scores?I.judge_scores.filter(j=>j.pass).length:void 0,S=T!==void 0&&h!==void 0?h-T:void 0;u.push({taskId:c,before:g,after:E,scoreDiff:S}),g&&!E&&f.push(c),!g&&E&&l.push(c)}return{newFailures:f,resolved:l,taskDeltas:u,overallImproved:l.length>f.length}},{name:"eval-delta"})}function Oe(t,e){let r=e==null?null:Array.isArray(e)?b(e):e,n=[t];return r&&n.push(r),k(n,a=>{let d=a[0],i=r?new Set(a[1]):null,o=new Set;for(let s of d)for(let u of s.affectsEvalTasks??[])(i==null||i.has(u))&&o.add(u);return[...o].sort()},{name:"affected-task-filter"})}function Ce(t,e,r,n){let a=n?.defaultSeverity??"high";function d(o){let s=[];for(let u of o.lintErrors??[])s.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:a});for(let u of o.testFailures??[])s.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:a});return s}let i=r??d;return C([t],([o])=>{if(o!=null)for(let s of i(o))e.publish(s)},{name:n?.name??"code-change-bridge"})}function _e(t,e,r){return C([t.latest],([n])=>{n!=null&&e(n)},{name:r?.name??"notify-effect"})}function Ae(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let r of t)e+=r.score;return e/t.length}function $e(t){let{passCount:e,total:r,meanScore:n,threshold:a,missingArtifact:d}=t,i=Number.isFinite(n)?n.toFixed(3):String(n),o=!d&&r>0&&n>=a,s=d?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:o?[`${e}/${r} eval tasks passed; mean score ${i} \u2265 ${a}`]:r===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${r} eval tasks passed; mean score ${i} < threshold ${a}`];return o?{verified:!0,findings:s}:{verified:!1,findings:s,errorClass:"structural"}}function Ve(t){return t.artifact}function Le(t){let e=t.name??"eval-verifier",r=t.threshold??.5,n=t.toOutput??$e,a=t.extractArtifact??Ve;return d=>{let i=A(d,s=>s!=null&&s[0]!=null&&s[1]!=null),o=$(i,([s,u])=>{let f=a(s,u);if(f==null)return b(n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:r,missingArtifact:!0}));let l=b([f],{name:`${e}/candidates`}),c=b(t.datasetFor(u),{name:`${e}/dataset`}),m=t.evaluator(l,c);return k([m],([I])=>{let g=I;if(g==null)return null;let E=Ae(g),T=g.filter(h=>h.score>=r).length;return n({scores:g,meanScore:E,passCount:T,total:g.length,threshold:r})},{name:`${e}/output`})},{name:e});return A(o,s=>s!=null)}}var N=["auto-fix","needs-decision","investigation","backlog"];function P(t,e){return`${t}\u2192${e}`}function W(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var z={critical:100,high:70,medium:40,low:10},X=Math.LN2/(168*3600),Z={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function ee(){let t=de({name:"strategy-entries"}),e=k([t.entries],([i])=>{let o=i;return new Map(o)},{name:"strategy-model",equals:(i,o)=>{let s=i,u=o;if(s.size!==u.size)return!1;for(let[f,l]of s){let c=u.get(f);if(!c||l.attempts!==c.attempts||l.successes!==c.successes)return!1}return!0}});function r(i,o,s){let u=P(i,o),f=t.get(u),l=(f?.attempts??0)+1,c=(f?.successes??0)+(s?1:0);t.set(u,{rootCause:i,intervention:o,attempts:l,successes:c,successRate:c/l})}function n(i,o){return t.get(P(i,o))}let a=e.subscribe(()=>{});function d(){a()}return{node:e,record:r,lookup:n,dispose:d}}function Ge(t,e,r,n,a){let d={...z,...a?.severityWeights},i=a?.decayRate??X,o=a?.effectivenessThreshold??.7,s=a?.effectivenessBoost??15,u=[t,e,r];return n&&u.push(n),k(u,f=>{let l=f[0],c=f[1],m=f[2],I=n?f[3]:0,g=d[l.severity??"medium"],E=(L()-m)/1e9,T=pe(g,E,i,0),h=P(l.rootCause,l.intervention),S=c.get(h);return S&&S.successRate>=o&&(T+=s),T+=I*20,T},{name:"priority-score"})}var Me=`You are a triage classifier for a reactive collaboration harness.
1
+ import{a as me}from"./chunk-KD3IYBTD.js";import{u as Q}from"./chunk-2JNT5NDF.js";import{a as pe}from"./chunk-TOCCHQI6.js";import{e as fe}from"./chunk-ZWETYYQG.js";import{a as M}from"./chunk-VXJX3ZZP.js";import{b as J,d as K}from"./chunk-K54OKWNY.js";import{b as de}from"./chunk-LWGLBCMU.js";import{f as le,j as Y}from"./chunk-4JBKKUCJ.js";import{b as A,s as G,t as ce,x as $}from"./chunk-WQ7I7JVU.js";import{m as ue}from"./chunk-UMH3HSP7.js";import{D as ie,E as b,G as k,H as C,o as L}from"./chunk-7AJKUA36.js";import{b as Ie}from"./chunk-QYADASLV.js";var Ye={};Ie(Ye,{DEFAULT_DECAY_RATE:()=>X,DEFAULT_QUEUE_CONFIGS:()=>Z,DEFAULT_SEVERITY_WEIGHTS:()=>z,HarnessGraph:()=>U,QUEUE_NAMES:()=>N,affectedTaskFilter:()=>Oe,beforeAfterCompare:()=>we,codeChangeBridge:()=>Ce,createIntakeBridge:()=>be,defaultErrorClassifier:()=>W,defaultLlmExecutor:()=>ge,defaultLlmVerifier:()=>ye,evalIntakeBridge:()=>Ne,evalSource:()=>Se,evalVerifier:()=>Le,harnessLoop:()=>Fe,harnessProfile:()=>De,harnessTrace:()=>Be,notifyEffect:()=>_e,priorityScore:()=>Ge,refineExecutor:()=>Qe,strategyKey:()=>P,strategyModel:()=>ee});function be(t,e,r,n){return C([t],([a])=>{if(a==null)return;let d=r(a);for(let i of d)e.publish(i)},{name:n?.name??"intake-bridge"})}function Ne(t,e,r){let n=r?.defaultSeverity??"medium";return C([t],([a])=>{if(a==null)return;let d=Array.isArray(a)?a:[a];for(let i of d)for(let o of i.tasks)if(!(o.valid&&o.judge_scores?.every(s=>s.pass))){if(!o.valid&&(!o.judge_scores||o.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${o.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n});continue}if(o.judge_scores)for(let s of o.judge_scores)s.pass||e.publish({source:"eval",summary:`${o.task_id}: ${s.claim} (model: ${i.model})`,evidence:s.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n})}},{name:r?.name??"eval-intake-bridge"})}function Se(t,e){return $(t,()=>ue(e()))}function we(t,e){return k([t,e],([r,n])=>{let a=r,d=n,i=new Map(a.tasks.map(c=>[c.task_id,c])),o=new Map(d.tasks.map(c=>[c.task_id,c])),s=new Set([...i.keys(),...o.keys()]),u=[],f=[],l=[];for(let c of s){let m=i.get(c),I=o.get(c),g=m?.valid??!1,E=I?.valid??!1,T=m?.judge_scores?m.judge_scores.filter(j=>j.pass).length:void 0,h=I?.judge_scores?I.judge_scores.filter(j=>j.pass).length:void 0,S=T!==void 0&&h!==void 0?h-T:void 0;u.push({taskId:c,before:g,after:E,scoreDiff:S}),g&&!E&&f.push(c),!g&&E&&l.push(c)}return{newFailures:f,resolved:l,taskDeltas:u,overallImproved:l.length>f.length}},{name:"eval-delta"})}function Oe(t,e){let r=e==null?null:Array.isArray(e)?b(e):e,n=[t];return r&&n.push(r),k(n,a=>{let d=a[0],i=r?new Set(a[1]):null,o=new Set;for(let s of d)for(let u of s.affectsEvalTasks??[])(i==null||i.has(u))&&o.add(u);return[...o].sort()},{name:"affected-task-filter"})}function Ce(t,e,r,n){let a=n?.defaultSeverity??"high";function d(o){let s=[];for(let u of o.lintErrors??[])s.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:a});for(let u of o.testFailures??[])s.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:a});return s}let i=r??d;return C([t],([o])=>{if(o!=null)for(let s of i(o))e.publish(s)},{name:n?.name??"code-change-bridge"})}function _e(t,e,r){return C([t.latest],([n])=>{n!=null&&e(n)},{name:r?.name??"notify-effect"})}function Ae(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let r of t)e+=r.score;return e/t.length}function $e(t){let{passCount:e,total:r,meanScore:n,threshold:a,missingArtifact:d}=t,i=Number.isFinite(n)?n.toFixed(3):String(n),o=!d&&r>0&&n>=a,s=d?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:o?[`${e}/${r} eval tasks passed; mean score ${i} \u2265 ${a}`]:r===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${r} eval tasks passed; mean score ${i} < threshold ${a}`];return o?{verified:!0,findings:s}:{verified:!1,findings:s,errorClass:"structural"}}function Ve(t){return t.artifact}function Le(t){let e=t.name??"eval-verifier",r=t.threshold??.5,n=t.toOutput??$e,a=t.extractArtifact??Ve;return d=>{let i=A(d,s=>s!=null&&s[0]!=null&&s[1]!=null),o=$(i,([s,u])=>{let f=a(s,u);if(f==null)return b(n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:r,missingArtifact:!0}));let l=b([f],{name:`${e}/candidates`}),c=b(t.datasetFor(u),{name:`${e}/dataset`}),m=t.evaluator(l,c);return k([m],([I])=>{let g=I;if(g==null)return null;let E=Ae(g),T=g.filter(h=>h.score>=r).length;return n({scores:g,meanScore:E,passCount:T,total:g.length,threshold:r})},{name:`${e}/output`})},{name:e});return A(o,s=>s!=null)}}var N=["auto-fix","needs-decision","investigation","backlog"];function P(t,e){return`${t}\u2192${e}`}function W(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var z={critical:100,high:70,medium:40,low:10},X=Math.LN2/(168*3600),Z={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function ee(){let t=de({name:"strategy-entries"}),e=k([t.entries],([i])=>{let o=i;return new Map(o)},{name:"strategy-model",equals:(i,o)=>{let s=i,u=o;if(s.size!==u.size)return!1;for(let[f,l]of s){let c=u.get(f);if(!c||l.attempts!==c.attempts||l.successes!==c.successes)return!1}return!0}});function r(i,o,s){let u=P(i,o),f=t.get(u),l=(f?.attempts??0)+1,c=(f?.successes??0)+(s?1:0);t.set(u,{rootCause:i,intervention:o,attempts:l,successes:c,successRate:c/l})}function n(i,o){return t.get(P(i,o))}let a=e.subscribe(()=>{});function d(){a()}return{node:e,record:r,lookup:n,dispose:d}}function Ge(t,e,r,n,a){let d={...z,...a?.severityWeights},i=a?.decayRate??X,o=a?.effectivenessThreshold??.7,s=a?.effectivenessBoost??15,u=[t,e,r];return n&&u.push(n),k(u,f=>{let l=f[0],c=f[1],m=f[2],I=n?f[3]:0,g=d[l.severity??"medium"],E=(L()-m)/1e9,T=pe(g,E,i,0),h=P(l.rootCause,l.intervention),S=c.get(h);return S&&S.successRate>=o&&(T+=s),T+=I*20,T},{name:"priority-score"})}var Me=`You are a triage classifier for a reactive collaboration harness.
2
2
 
3
3
  Given an intake item, classify it and output JSON:
4
4
  {
@@ -39,5 +39,5 @@ Output JSON:
39
39
  "verified": true/false,
40
40
  "findings": ["<finding1>", ...],
41
41
  "errorClass": "self-correctable" | "structural" // only if verified=false
42
- }`;function ge(t,e){let r=e??(n=>Pe.replace("{{item}}",JSON.stringify(n)));return n=>Q(t,[n],r,{name:"execute",format:"json",retries:1})}function ye(t,e){let r=e??(n=>{let[a,d]=n;return je.replace("{{execution}}",JSON.stringify(a)).replace("{{item}}",JSON.stringify(d))});return n=>Q(t,[n],r,{name:"verify",format:"json",retries:1})}var U=class extends Y{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,r,n,a,d,i,o,s){super(e),this.intake=r,this.queues=n,this.gates=a,this.strategy=d,this.verifyResults=i,this.totalRetries=o,this.totalReingestions=s}};function Fe(t,e){let r=e.adapter,n=e.maxRetries??2,a=e.retainedLimit??1e3,d=e.errorClassifier??W,i=new Map;for(let p of N)i.set(p,{...Z[p],...e.queues?.[p]});let o=new M("intake",{retainedLimit:a}),s=ee(),u=G(o.latest,s.node),f=Q(r,[u],e.triagePrompt??(p=>{let[x,R]=p;return x?Me.replace("{{strategy}}",JSON.stringify(Array.from(R.entries()))).replace("{{item}}",JSON.stringify(x)):""}),{name:"triage",format:"json",retries:1}),l=new Map;for(let p of N)l.set(p,new M(`queue/${p}`,{retainedLimit:a}));let c=G(f,u),I=C([c],([p])=>{if(p==null)return;let[x,R]=p;if(!x?.route)return;let _=R?.[0],w={...x,..._},D=l.get(w.route);D&&D.publish(w)}).subscribe(()=>{}),g=new Y("gates"),E=new Map;for(let p of N){let x=i.get(p),R=l.get(p);if(x.gated){g.add(R.latest,{name:`${p}/source`});let _=fe(g,`${p}/gate`,`${p}/source`,{maxPending:x.maxPending,startOpen:x.startOpen});E.set(p,_)}}let T=new M("retry-input",{retainedLimit:a}),h=[];for(let p of N)i.get(p).gated&&E.has(p)?h.push(E.get(p).node):h.push(l.get(p).latest);h.push(T.latest);let S=ce(...h),te=(e.executor??ge(r,e.executePrompt))(S),re=G(te,S),F=new M("verify-results",{retainedLimit:a}),ne=(e.verifier??ye(r,e.verifyPrompt))(re),xe=G(ne,re),oe=e.maxReingestions??1,Ee=Math.min(e.maxTotalRetries??n*10,100),Te=Math.min(e.maxTotalReingestions??oe*10,100),se=b(0),ae=b(0),he=ie([xe],(p,x)=>{let R=p[0];if(R==null||R.length===0)return;let _=R[R.length-1];if(_==null)return;let[w,D]=_,[B,y]=D??[null,null];if(!w||!y)return;let Re={item:y,outcome:B?.outcome??"failure",detail:B?.detail??"unknown",artifact:B?.artifact},O={item:y,execution:Re,verified:w.verified,findings:w.findings??[],errorClass:w.errorClass};if(O.verified){s.record(y.rootCause,y.intervention,!0),F.publish(O);return}let ke=O.errorClass??d({item:y,outcome:"failure",detail:O.findings.join("; ")}),q=y._retries??0;if(ke==="self-correctable"&&q<n&&J(se,Ee)){let V=K(y),H={...y,_retries:q+1,summary:`[RETRY ${q+1}/${n}] ${V} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[V]};T.publish(H)}else{s.record(y.rootCause,y.intervention,!1),F.publish(O);let V=K(y),H=y._reingestions??0;H<oe&&J(ae,Te)&&o.publish({source:"eval",summary:`Verification failed for: ${V}`,evidence:O.findings.join(`
42
+ }`;function ge(t,e){let r=e??(n=>Pe.replace("{{item}}",JSON.stringify(n)));return n=>Q(t,[n],r,{name:"execute",format:"json"})}function ye(t,e){let r=e??(n=>{let[a,d]=n;return je.replace("{{execution}}",JSON.stringify(a)).replace("{{item}}",JSON.stringify(d))});return n=>Q(t,[n],r,{name:"verify",format:"json"})}var U=class extends Y{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,r,n,a,d,i,o,s){super(e),this.intake=r,this.queues=n,this.gates=a,this.strategy=d,this.verifyResults=i,this.totalRetries=o,this.totalReingestions=s}};function Fe(t,e){let r=e.adapter,n=e.maxRetries??2,a=e.retainedLimit??1e3,d=e.errorClassifier??W,i=new Map;for(let p of N)i.set(p,{...Z[p],...e.queues?.[p]});let o=new M("intake",{retainedLimit:a}),s=ee(),u=G(o.latest,s.node),f=Q(r,[u],e.triagePrompt??(p=>{let[x,R]=p;return x?Me.replace("{{strategy}}",JSON.stringify(Array.from(R.entries()))).replace("{{item}}",JSON.stringify(x)):""}),{name:"triage",format:"json"}),l=new Map;for(let p of N)l.set(p,new M(`queue/${p}`,{retainedLimit:a}));let c=G(f,u),I=C([c],([p])=>{if(p==null)return;let[x,R]=p;if(!x?.route)return;let _=R?.[0],w={...x,..._},D=l.get(w.route);D&&D.publish(w)}).subscribe(()=>{}),g=new Y("gates"),E=new Map;for(let p of N){let x=i.get(p),R=l.get(p);if(x.gated){g.add(R.latest,{name:`${p}/source`});let _=fe(g,`${p}/gate`,`${p}/source`,{maxPending:x.maxPending,startOpen:x.startOpen});E.set(p,_)}}let T=new M("retry-input",{retainedLimit:a}),h=[];for(let p of N)i.get(p).gated&&E.has(p)?h.push(E.get(p).node):h.push(l.get(p).latest);h.push(T.latest);let S=ce(...h),te=(e.executor??ge(r,e.executePrompt))(S),re=G(te,S),F=new M("verify-results",{retainedLimit:a}),ne=(e.verifier??ye(r,e.verifyPrompt))(re),xe=G(ne,re),oe=e.maxReingestions??1,Ee=Math.min(e.maxTotalRetries??n*10,100),Te=Math.min(e.maxTotalReingestions??oe*10,100),se=b(0),ae=b(0),he=ie([xe],(p,x)=>{let R=p[0];if(R==null||R.length===0)return;let _=R[R.length-1];if(_==null)return;let[w,D]=_,[B,y]=D??[null,null];if(!w||!y)return;let Re={item:y,outcome:B?.outcome??"failure",detail:B?.detail??"unknown",artifact:B?.artifact},O={item:y,execution:Re,verified:w.verified,findings:w.findings??[],errorClass:w.errorClass};if(O.verified){s.record(y.rootCause,y.intervention,!0),F.publish(O);return}let ke=O.errorClass??d({item:y,outcome:"failure",detail:O.findings.join("; ")}),q=y._retries??0;if(ke==="self-correctable"&&q<n&&J(se,Ee)){let V=K(y),H={...y,_retries:q+1,summary:`[RETRY ${q+1}/${n}] ${V} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[V]};T.publish(H)}else{s.record(y.rootCause,y.intervention,!1),F.publish(O);let V=K(y),H=y._reingestions??0;H<oe&&J(ae,Te)&&o.publish({source:"eval",summary:`Verification failed for: ${V}`,evidence:O.findings.join(`
43
43
  `),affectsAreas:y.affectsAreas,affectsEvalTasks:y.affectsEvalTasks,severity:"high",relatedTo:[V],_reingestions:H+1})}}).subscribe(()=>{}),v=new U(t,o,l,E,s,F,se,ae);v.addDisposer(I),v.addDisposer(he),v.addDisposer(s.dispose),v.add(f,{name:"triage"}),v.add(te,{name:"execute"}),v.add(ne,{name:"verify"}),v.add(s.node,{name:"strategy"}),v.mount("intake",o);for(let[p,x]of l)v.mount(`queue/${p}`,x);return v.mount("gates",g),v.mount("retry-input",T),v.mount("verify-results",F),v}function De(t,e){let r=le(t,e),n={};for(let[a,d]of t.queues)n[a]=d.retained().length;return{...r,queueDepths:n,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}function He(t){let{best:e,score:r,status:n}=t,a=Number.isFinite(r)?r.toFixed(3):String(r);return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${a}`,artifact:e}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${a}`,artifact:e}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:e}}function Qe(t){let e=t.name??"refine-executor",r=t.toOutput??He;return n=>{let a=A(n,i=>i!=null),d=$(a,i=>{let o=me(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return k([o.status,o.best,o.score],([s,u,f])=>{let l=s;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:r({best:u,score:f,status:l})},{name:`${e}/output`})},{name:e});return A(d,i=>i!=null)}}function Ue(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let r of N)e[`queue/${r}::latest`]="QUEUE";for(let[r]of t.gates)e[`gates::${r}/gate`]="GATE";return e}function Be(t,e){let r=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",a=L(),d=[],i=[],o=Ue(t);function s(){return(L()-a)/1e9}function u(f,l,c){let m={elapsed:s(),stage:f,type:l};n!=="summary"&&(m.summary=qe(c)),n==="full"&&(m.data=c),i.push(m)}for(let[f,l]of Object.entries(o))try{let c=t.observe(f,{format:"stage-log",stageLabels:o,logger:r?m=>r(m):()=>{},includeTypes:["data","error","complete"]});c.onEvent(m=>{m.type==="data"?u(l,"data",m.data):m.type==="error"?u(l,"error",m.data):m.type==="complete"&&u(l,"complete",void 0)}),d.push(c)}catch(c){let m=c instanceof Error?c.message:String(c);u(l,"error",`observe-unavailable: ${f} \u2014 ${m}`),r&&r(`[${s().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${m}`)}return{get events(){return i},dispose(){for(let f of d)f.dispose();d.length=0}}}function qe(t){if(t==null)return"null";if(typeof t=="string")return ve(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return ve(e,120)}catch{return String(t)}}function ve(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}export{be as a,Ne as b,Se as c,we as d,Oe as e,Ce as f,_e as g,Le as h,N as i,P as j,W as k,z as l,X as m,Z as n,ee as o,Ge as p,ge as q,ye as r,U as s,Fe as t,De as u,Qe as v,Be as w,Ye as x};