@graphrefly/graphrefly 0.30.0 → 0.31.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 (178) 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-T5SHIKJD.js → chunk-3JRKP4BH.js} +1 -1
  4. package/dist/{chunk-GJR3P6JG.js → chunk-3Q2WXM6X.js} +1 -1
  5. package/dist/chunk-4KAUNEKV.js +3 -0
  6. package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
  7. package/dist/chunk-4VXL3UZK.js +1 -0
  8. package/dist/{chunk-AV3PIDFQ.js → chunk-4ZPO2EL5.js} +1 -1
  9. package/dist/{chunk-VWPRPPKR.js → chunk-5LJAQTSS.js} +1 -1
  10. package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
  11. package/dist/{chunk-RD52SNH2.js → chunk-7EJTWGKW.js} +1 -1
  12. package/dist/{chunk-GNCBXARM.js → chunk-7EQPXQ7H.js} +1 -1
  13. package/dist/chunk-7QMVU3IX.js +1 -0
  14. package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
  15. package/dist/chunk-ASDKRNOJ.js +60 -0
  16. package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
  17. package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
  18. package/dist/{chunk-33FA6V4B.js → chunk-EBQ6FXKW.js} +1 -1
  19. package/dist/chunk-FTA5TB2A.js +1 -0
  20. package/dist/{chunk-P7JXGKDO.js → chunk-GF5T7PGC.js} +1 -1
  21. package/dist/{chunk-WANIEEKV.js → chunk-I4U3TPK2.js} +1 -1
  22. package/dist/{chunk-KA6MMXIY.js → chunk-JMGGCSIC.js} +1 -1
  23. package/dist/chunk-JXRZXP3N.js +1 -0
  24. package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
  25. package/dist/{chunk-DDPYNMGG.js → chunk-KN4Q5MQO.js} +1 -1
  26. package/dist/chunk-LWGLBCMU.js +1 -0
  27. package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
  28. package/dist/{chunk-4OFIQ66T.js → chunk-OKQUPJRY.js} +1 -1
  29. package/dist/chunk-PNTBXOQ6.js +5 -0
  30. package/dist/chunk-PSQNYY72.js +7 -0
  31. package/dist/{chunk-XHVB6G6M.js → chunk-PZP4MEXK.js} +1 -1
  32. package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
  33. package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
  34. package/dist/chunk-SGS4OJGS.js +1 -0
  35. package/dist/chunk-UMH3HSP7.js +1 -0
  36. package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
  37. package/dist/{chunk-SHYH5SXV.js → chunk-WLPVGXQ6.js} +1 -1
  38. package/dist/chunk-WQ7I7JVU.js +1 -0
  39. package/dist/{chunk-XQAXYVXX.js → chunk-WYJTXYWX.js} +1 -1
  40. package/dist/{chunk-3NEPQO2E.js → chunk-X2VHDT26.js} +1 -1
  41. package/dist/{chunk-GLSM33ZM.js → chunk-XEFAMCEA.js} +1 -1
  42. package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
  43. package/dist/chunk-Y26UN6J5.js +18 -0
  44. package/dist/{chunk-BKPLTBL5.js → chunk-YQJPYEAL.js} +1 -1
  45. package/dist/{chunk-73Z3W2RN.js → chunk-YZ6VYLFD.js} +1 -1
  46. package/dist/{chunk-4JJCCD5S.js → chunk-YZKGGMPT.js} +1 -1
  47. package/dist/chunk-Z3UWIJ3A.js +1 -0
  48. package/dist/{chunk-Y36UZ5VS.js → chunk-ZM7C2FUM.js} +1 -1
  49. package/dist/compat/index.cjs +1 -1
  50. package/dist/compat/index.js +1 -1
  51. package/dist/compat/jotai/index.cjs +1 -1
  52. package/dist/compat/jotai/index.js +1 -1
  53. package/dist/compat/nanostores/index.cjs +1 -1
  54. package/dist/compat/nanostores/index.js +1 -1
  55. package/dist/compat/nestjs/index.cjs +5 -5
  56. package/dist/compat/nestjs/index.js +1 -1
  57. package/dist/compat/zustand/index.cjs +1 -1
  58. package/dist/compat/zustand/index.js +1 -1
  59. package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
  60. package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
  61. package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
  62. package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
  63. package/dist/core/index.cjs +1 -1
  64. package/dist/core/index.js +1 -1
  65. package/dist/extra/browser.cjs +1 -1
  66. package/dist/extra/browser.js +1 -1
  67. package/dist/extra/index.cjs +18 -18
  68. package/dist/extra/index.d.cts +6 -5
  69. package/dist/extra/index.d.ts +6 -5
  70. package/dist/extra/index.js +1 -1
  71. package/dist/extra/node.cjs +2 -2
  72. package/dist/extra/node.js +1 -1
  73. package/dist/extra/operators.cjs +1 -1
  74. package/dist/extra/operators.d.cts +41 -1
  75. package/dist/extra/operators.d.ts +41 -1
  76. package/dist/extra/operators.js +1 -1
  77. package/dist/extra/reactive.cjs +1 -1
  78. package/dist/extra/reactive.d.cts +1 -1
  79. package/dist/extra/reactive.d.ts +1 -1
  80. package/dist/extra/reactive.js +1 -1
  81. package/dist/extra/sources.cjs +1 -1
  82. package/dist/extra/sources.d.cts +62 -2
  83. package/dist/extra/sources.d.ts +62 -2
  84. package/dist/extra/sources.js +1 -1
  85. package/dist/extra/storage-browser.cjs +1 -1
  86. package/dist/extra/storage-browser.js +1 -1
  87. package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
  88. package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
  89. package/dist/graph/index.cjs +4 -4
  90. package/dist/graph/index.js +1 -1
  91. package/dist/{index-ClB7TCfL.d.cts → index-BMe3pCom.d.cts} +1 -1
  92. package/dist/{index-Dljd76bC.d.ts → index-BXzl1NDD.d.ts} +1 -1
  93. package/dist/{index-ClgKmOHe.d.ts → index-Bd6oFZqO.d.ts} +223 -115
  94. package/dist/{index-BJHQUCZx.d.ts → index-CJymKyzT.d.ts} +81 -6
  95. package/dist/{index-D6ajK8Mh.d.cts → index-CZChc85Q.d.cts} +223 -115
  96. package/dist/{index-BXbQUn4n.d.ts → index-CcS0t-l2.d.ts} +1 -1
  97. package/dist/{index-B2HBxvMb.d.ts → index-CwhcFzTA.d.ts} +1 -1
  98. package/dist/{index-B8Aj_z8S.d.cts → index-D-kHVedZ.d.cts} +1 -1
  99. package/dist/{index-ybtSyjWB.d.cts → index-DD7RhHNJ.d.cts} +1 -1
  100. package/dist/{index-BHu_Wba0.d.cts → index-Dm3_D5Ta.d.cts} +1 -1
  101. package/dist/{index-Cc8VQIgL.d.ts → index-DxMS0cHM.d.ts} +1 -1
  102. package/dist/{index-BS220yqj.d.cts → index-gJQqJTKx.d.cts} +81 -6
  103. package/dist/index.cjs +99 -121
  104. package/dist/index.d.cts +14 -13
  105. package/dist/index.d.ts +14 -13
  106. package/dist/index.js +1 -1
  107. package/dist/patterns/ai/browser.cjs +5 -22
  108. package/dist/patterns/ai/browser.d.cts +3 -3
  109. package/dist/patterns/ai/browser.d.ts +3 -3
  110. package/dist/patterns/ai/browser.js +1 -1
  111. package/dist/patterns/ai/index.cjs +27 -44
  112. package/dist/patterns/ai/index.d.cts +9 -7
  113. package/dist/patterns/ai/index.d.ts +9 -7
  114. package/dist/patterns/ai/index.js +1 -1
  115. package/dist/patterns/ai/node.cjs +2 -2
  116. package/dist/patterns/ai/node.d.cts +5 -4
  117. package/dist/patterns/ai/node.d.ts +5 -4
  118. package/dist/patterns/ai/node.js +1 -1
  119. package/dist/patterns/audit/index.cjs +3 -3
  120. package/dist/patterns/audit/index.js +1 -1
  121. package/dist/patterns/cqrs/index.cjs +6 -6
  122. package/dist/patterns/cqrs/index.js +1 -1
  123. package/dist/patterns/demo-shell/index.cjs +1 -1
  124. package/dist/patterns/demo-shell/index.js +1 -1
  125. package/dist/patterns/domain-templates/index.cjs +4 -4
  126. package/dist/patterns/domain-templates/index.js +1 -1
  127. package/dist/patterns/graphspec/index.cjs +6 -6
  128. package/dist/patterns/graphspec/index.d.cts +2 -2
  129. package/dist/patterns/graphspec/index.d.ts +2 -2
  130. package/dist/patterns/graphspec/index.js +1 -1
  131. package/dist/patterns/guarded-execution/index.cjs +7 -7
  132. package/dist/patterns/guarded-execution/index.js +1 -1
  133. package/dist/patterns/harness/index.cjs +11 -11
  134. package/dist/patterns/harness/index.d.cts +2 -2
  135. package/dist/patterns/harness/index.d.ts +2 -2
  136. package/dist/patterns/harness/index.js +1 -1
  137. package/dist/patterns/job-queue/index.cjs +5 -5
  138. package/dist/patterns/job-queue/index.js +1 -1
  139. package/dist/patterns/lens/index.cjs +5 -5
  140. package/dist/patterns/lens/index.d.cts +2 -2
  141. package/dist/patterns/lens/index.d.ts +2 -2
  142. package/dist/patterns/lens/index.js +1 -1
  143. package/dist/patterns/memory/index.cjs +4 -4
  144. package/dist/patterns/memory/index.js +1 -1
  145. package/dist/patterns/messaging/index.cjs +5 -5
  146. package/dist/patterns/messaging/index.js +1 -1
  147. package/dist/patterns/orchestration/index.cjs +1 -1
  148. package/dist/patterns/orchestration/index.js +1 -1
  149. package/dist/patterns/reactive-layout/index.cjs +1 -1
  150. package/dist/patterns/reactive-layout/index.js +1 -1
  151. package/dist/patterns/reduction/index.cjs +5 -5
  152. package/dist/patterns/reduction/index.js +1 -1
  153. package/dist/patterns/refine-loop/index.cjs +8 -8
  154. package/dist/patterns/refine-loop/index.js +1 -1
  155. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  156. package/dist/patterns/resilient-pipeline/index.js +1 -1
  157. package/dist/patterns/surface/index.cjs +7 -7
  158. package/dist/patterns/surface/index.d.cts +3 -3
  159. package/dist/patterns/surface/index.d.ts +3 -3
  160. package/dist/patterns/surface/index.js +1 -1
  161. package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
  162. package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
  163. package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
  164. package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
  165. package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
  166. package/package.json +1 -1
  167. package/dist/chunk-2GQREQ6C.js +0 -1
  168. package/dist/chunk-4C2OR2GH.js +0 -18
  169. package/dist/chunk-5JDE5JHE.js +0 -1
  170. package/dist/chunk-7JDLFI6N.js +0 -1
  171. package/dist/chunk-AMBYCIOH.js +0 -3
  172. package/dist/chunk-ISCENNXS.js +0 -1
  173. package/dist/chunk-IUK4EFCE.js +0 -1
  174. package/dist/chunk-KASHOCF5.js +0 -1
  175. package/dist/chunk-LI3E75VE.js +0 -64
  176. package/dist/chunk-MGKAO4EK.js +0 -7
  177. package/dist/chunk-NSG4C6BF.js +0 -23
  178. package/dist/chunk-VIEUJSTT.js +0 -1
@@ -1,44 +1,31 @@
1
- "use strict";var ln=Object.defineProperty;var Qo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var es=Object.prototype.hasOwnProperty;var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var un=(t,e)=>{for(var n in e)ln(t,n,{get:e[n],enumerable:!0})},ts=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Zo(e))!es.call(t,o)&&o!==n&&ln(t,o,{get:()=>e[o],enumerable:!(r=Qo(e,o))||r.enumerable});return t};var ns=t=>ts(ln({},"__esModule",{value:!0}),t);function G(){return Math.trunc(performance.now()*1e6)}function be(){return Date.now()*1e6}var he=ge(()=>{"use strict"});var ne,Ne=ge(()=>{"use strict";ne=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Oe,L,Y,H,Te,xe,Ae,ce,F,O,Ge,_t,fr,Rt,mr,hr,Mt,fn,mn,hn,Nt,fe=ge(()=>{"use strict";Oe=Symbol.for("graphrefly/START"),L=Symbol.for("graphrefly/DATA"),Y=Symbol.for("graphrefly/DIRTY"),H=Symbol.for("graphrefly/RESOLVED"),Te=Symbol.for("graphrefly/INVALIDATE"),xe=Symbol.for("graphrefly/PAUSE"),Ae=Symbol.for("graphrefly/RESUME"),ce=Symbol.for("graphrefly/TEARDOWN"),F=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),Ge=Object.freeze([Y]),_t=Object.freeze([H]),fr=Object.freeze([Te]),Rt=Object.freeze([Oe]),mr=Object.freeze([F]),hr=Object.freeze([ce]),Mt=Object.freeze([Ge]),fn=Object.freeze([_t]),mn=Object.freeze([fr]),hn=Object.freeze([mr]),Nt=Object.freeze([hr])});function yr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=gn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function br(t,e){if(t.length<gr)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${gr})`);let n=0,r=t[n++];if(r!==gn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${gn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),l=e.lookupCodec(s);if(l==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:l,codecVersion:i,payload:a}}function vr(t){t.registerCodec(ds)}var ds,gn,gr,yn=ge(()=>{"use strict";ds={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},gn=1,gr=4});function Et(t){if(t==null)return Ye;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Ye,At=ge(()=>{"use strict";Ye={type:"system",id:""}});function St(){return Xe>0||it}function Tr(){return Xe>0}function lt(t){Xe>0?at.push(t):t()}function se(t){Xe+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Xe-=1,Xe===0)if(e){if(!it){let n=at.splice(0);for(let r of n)try{r()}catch{}Fe.length=0,$e.length=0,Qe.length=0}}else cs()}}function cs(){let t=!it;t&&(it=!0);let e=[],n=0;try{for(;Fe.length>0||$e.length>0||Qe.length>0||t&&at.length>0;){if(t&&at.length>0){let s=at.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Fe.length=0,$e.length=0,Qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Fe.length>0?Fe:$e.length>0?$e:Qe).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(it=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ot(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!St()){t(e);return}(u>=5?Qe:u===4?$e:Fe).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let l=St();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);l?Fe.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);l?$e.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);l?Qe.push(()=>t(u)):t(u)}}var Xe,it,Fe,$e,Qe,at,Me=ge(()=>{"use strict";Xe=0,it=!1,Fe=[],$e=[],Qe=[],at=[]});function wr(t){t.registerMessageType(Oe,{tier:0,wireCrossing:!1}),t.registerMessageType(Y,{tier:1,wireCrossing:!1}),t.registerMessageType(Te,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(xe,{tier:2,wireCrossing:!1}),t.registerMessageType(Ae,{tier:2,wireCrossing:!1}),t.registerMessageType(L,{tier:3,wireCrossing:!0}),t.registerMessageType(H,{tier:3,wireCrossing:!0}),t.registerMessageType(F,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ce,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ct,xr=ge(()=>{"use strict";fe();Ct=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=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function bn(t){let e=ps.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var we,ps,ut=ge(()=>{"use strict";we=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},ps=["human","llm","wallet","system"]});function vn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(vn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=vn(t[n]);return e}return null}function hs(t){let e=ms.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,l=3144134277,u=1013904242,d=2773480762,c=1359893119,m=2600822924,f=528734635,p=1541459225,g=new Uint32Array(64),h=(v,b)=>v>>>b|v<<32-b;for(let v=0;v<o;v+=64){for(let A=0;A<16;A++)g[A]=i.getUint32(v+A*4,!1);for(let A=16;A<64;A++){let D=g[A-15],M=g[A-2],j=h(D,7)^h(D,18)^D>>>3,z=h(M,17)^h(M,19)^M>>>10;g[A]=g[A-16]+j+g[A-7]+z>>>0}let b=a,T=l,w=u,x=d,_=c,R=m,k=f,P=p;for(let A=0;A<64;A++){let D=h(_,6)^h(_,11)^h(_,25),M=_&R^~_&k,j=P+D+M+fs[A]+g[A]>>>0,z=h(b,2)^h(b,13)^h(b,22),E=b&T^b&w^T&w,N=z+E>>>0;P=k,k=R,R=_,_=x+j>>>0,x=w,w=T,T=b,b=j+N>>>0}a=a+b>>>0,l=l+T>>>0,u=u+w>>>0,d=d+x>>>0,c=c+_>>>0,m=m+R>>>0,f=f+k>>>0,p=p+P>>>0}let y=v=>v.toString(16).padStart(8,"0");return y(a)+y(l)+y(u)+y(d)+y(c)+y(m)+y(f)+y(p)}function Tn(t){let e=vn(t??null),n=JSON.stringify(e);return hs(n).slice(0,16)}function gs(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function wn(t,e,n){let r=n?.id??gs();if(t===0)return{id:r,version:0};let s=(n?.hash??Tn)(e);return{id:r,version:0,cid:s,prev:null}}function kr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var fs,ms,_r=ge(()=>{"use strict";fs=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]),ms=new TextEncoder});function Nr(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function xn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Lt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ie(t,e,n){let r=Er(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Er(t)?s=(kn(e)?e:n)??{}:kn(t)?s=t:s=(kn(e)?e:n)??{},new ae(r,o,s)}var Rr,Mr,ys,bs,Ze,ae,Er,kn,ke=ge(()=>{"use strict";yn();At();Me();he();xr();ut();fe();_r();Rr=()=>{},Mr=100;ys=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},bs=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Rt]:[Rt,[L,s]];o._status==="dirty"&&i.push(Ge),Ot(e,i,o._config.tierOf)},Ze=new Ct({onMessage:ys,onSubscribe:bs});wr(Ze);vr(Ze);ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Ze,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Tn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?wn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Nr);let s={};for(let[a,l]of Object.entries(r.meta??{})){let u={initial:l,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[L,a]])},down(a){i._emit(Lt(a))},up(a){i._emitUp(Lt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,l=i?.version??0,u=wn(e,s,{id:a,hash:o});u.version=l,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Et(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Et(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new we({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new we({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:be()}}down(e,n){let r=Lt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[L,e]])}up(e,n){if(this._deps.length===0)return;let r=Lt(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let l=Et(n);if(!this._guard(l,"observe"))throw new we({actor:l,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let l of this._deps)xn(l);if(this._partial===!1){for(let l of this._deps)if(l.prevData!==void 0||l.dataBatch.length!==0||l.terminal!==void 0||l.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(l){throw this._sinkCount-=1,l}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(l){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw l}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Rr,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,l=!1;for(let u of i)a(u[0])>=3&&(l=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);l&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}xn(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=Nr(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mt),r.unsub=Rr;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[O,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[O,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}xn(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==Oe){if(o===Y){this._depDirtied(r);return}if(o===Te){this._depInvalidated(r),this._emit(mn);return}if(o===xe||o===Ae){this._emit([n]);return}if(o===ce){this._emit(Nt);return}if(o===L)this._depSettledAsData(r,n[1]);else if(o===H)this._depSettledAsResolved(r);else if(o===F)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===L||o===H)&&this._emit([n]),(o===F||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[O,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(hn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[O,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[O,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[O,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Mr?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Mr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Ge,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let l of e){let u=n(l[0]);u<i&&(r=!1),u===3&&(o=!0),l[0]===Y&&(s=!0),i=u}let a=e;if(!r){let l=e.map((u,d)=>({m:u,i:d,tier:n(u[0])}));l.sort((u,d)=>u.tier-d.tier||u.i-d.i),a=l.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let l=0;for(;l<a.length&&n(a[l][0])===0;)l++;return l===0?[Ge,...a]:[...a.slice(0,l),Ge,...a.slice(l)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let l=e[a];if(l[0]===O&&l[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(l=>l[0]===ce||l[0]===Te);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let l=n[a],u=l[0];if(u!==xe&&u!==Ae){o?.push(l);continue}if(l.length<2)throw new Error(`Node "${this.name}": [[${u===xe?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let c=l[1];if(u===xe)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(c),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(c))d=!1;else if(this._pauseLocks.delete(c),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let m=this._pauseBuffer;this._pauseBuffer=[],this._emit(m)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(l):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===ce))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Nt)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,l=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):l.push(u);l.length>0&&this._dispatchOrAccumulate(l)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,l=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===L){l=d;break}}for(let d=0;d<e.length;d++){let c=e[d],m=c[0];if(m===L){if(c.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,c[1])}catch(p){o=this._wrapFnError("equals threw",p),s=d;break}if(f){r==null&&(r=e.slice(0,d)),r.push(_t),this._status="resolved";continue}this._cached=c[1],this._versioning!=null&&(l<0||d===l)&&kr(this._versioning,c[1],this._hashFn)}this._status="settled",r?.push(c)}else if(r?.push(c),m===Y)this._status="dirty";else if(m===H)this._status="resolved";else if(m===F)this._status="completed";else if(m===O)this._status="errored";else if(m===Te){this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let p=f.invalidate;if(typeof p=="function")try{p()}catch{}}}else m===ce&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Tr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],lt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ot(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Ot(this._deliverToSinks,n,this._config.tierOf)}},Er=t=>Array.isArray(t),kn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function S(t,e){return ie([],{...e,initial:t})}function pe(t,e){return ie((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return ie(t,(o,s,i)=>{let a=o.map((l,u)=>l!=null&&l.length>0?l.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function Ce(t,e,n){return ie(t,(o,s,i)=>{let a=o.map((l,u)=>l!=null&&l.length>0?l.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var X=ge(()=>{"use strict";ke()});var Dr={};un(Dr,{NS_PER_MS:()=>je,NS_PER_SEC:()=>et,constant:()=>Ar,decorrelatedJitter:()=>Lr,exponential:()=>Or,fibonacci:()=>Cr,linear:()=>Sr,resolveBackoffPreset:()=>Dt,withMaxAttempts:()=>ws});function Be(t){return t<0?0:t}function vs(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Ts(t,e){return t+Math.random()*(e-t)}function Ar(t){let e=Be(t);return()=>e}function Sr(t,e){let n=Be(t),r=e===void 0?n:Be(e);return o=>n+r*Math.max(0,o)}function Or(t){let e=Be(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=Be(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,l=1;for(let u=0;u<Math.max(0,s);u++){if(l>=a){l=a;break}l*=n}i=e*l,i>r&&(i=r)}return vs(i,o)}}function Cr(t=100*1e6,e=30*1e9){let n=Be(t),r=Be(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let l=1;l<s;l++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Lr(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Ts(t,i)}}function ws(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Dt(t){if(t==="constant")return Ar(1*1e9);if(t==="linear")return Sr(1*1e9);if(t==="exponential")return Or();if(t==="fibonacci")return Cr();if(t==="decorrelatedJitter")return Lr();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var je,et,_n=ge(()=>{"use strict";je=1e6,et=1e9});var Pr={};un(Pr,{CircuitOpenError:()=>Le,RateLimiterOverflowError:()=>It,TimeoutError:()=>Pt,circuitBreaker:()=>dt,fallback:()=>Ss,rateLimiter:()=>Rs,retry:()=>ks,retrySource:()=>Rn,timeout:()=>Os,tokenBucket:()=>ct,withBreaker:()=>_s,withStatus:()=>Ms});function Ve(t){return{describeKind:"derived",...t}}function xs(t){return t<0?0:t}function Gt(t){return t[1]}function Ir(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function ks(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Dt(r):r;return pe(i=>{let a=0,l=!1,u=null,d,c=new ne;function m(){d?.(),d=void 0}function f(g){if(l)return;if(a>=o){m(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,u);if(h==null){m(),i.down([[O,g]]);return}let y;try{y=Ir(h)}catch{m(),i.down([[O,g]]);return}u=y,a+=1,m();let v=y>0?y/1e6:1;c.start(v,()=>{l||p()})}function p(){c.cancel(),m(),d=t.subscribe(g=>{if(!l)for(let h of g){let y=h[0];if(y===Y)i.down([[Y]]);else if(y===L)a=0,u=null,i.emit(h[1]);else if(y===H)i.down([[H]]);else if(y===F)m(),i.down([[F]]);else if(y===O){f(Gt(h));return}else i.down([h])}})}return p(),()=>{l=!0,c.cancel(),m()}},{...Ve(),initial:t.cache})}function Rn(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Dt(r):r;return pe(i=>{let a=0,l=!1,u=null,d,c=new ne;function m(){d?.(),d=void 0}function f(g){if(l)return;if(a>=o){m(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,u);if(h==null){m(),i.down([[O,g]]);return}let y;try{y=Ir(h)}catch{m(),i.down([[O,g]]);return}u=y,a+=1,m();let v=y>0?y/1e6:1;c.start(v,()=>{l||p()})}function p(){c.cancel(),m();let g;try{g=t()}catch(h){f(h);return}d=g.subscribe(h=>{if(!l)for(let y of h){let v=y[0];if(v===Y)i.down([[Y]]);else if(v===L)a=0,u=null,i.emit(y[1]);else if(v===H)i.down([[H]]);else if(v===F)m(),i.down([[F]]);else if(v===O){f(Gt(y));return}else i.down([y])}})}return p(),()=>{l=!0,c.cancel(),m()}},{...Ve(),initial:e?.initial})}function dt(t){let e=Math.max(1,t?.failureThreshold??5),n=xs(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??G,i="closed",a=0,l=0,u=0,d=n,c=0;function m(){if(!r)return n;let g=r(l);return g!==null?g:n}function f(){i="open",d=m(),u=s(),c=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=d?(i="half-open",c=1,!0):!1:c<o?(c++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,l=0):i==="closed"&&(a=0)},recordFailure(g){if(i==="half-open"){l++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,l=0,c=0}}}function _s(t,e){let n=e?.onOpen??"skip";return r=>{let o=ie([],(s,i)=>{function a(){o.meta.breakerState.down([[L,t.state]])}let l=r.subscribe(u=>{for(let d of u){let c=d[0];c===Y?i.down([[Y]]):c===L?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[O,new Le]]):i.down([[H]])):c===H?i.down([[H]]):c===F?(t.recordSuccess(),a(),i.down([[F]])):c===O?(t.recordFailure(Gt(d)),a(),i.down([d])):i.down([d])}});return a(),l},{...Ve(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function ct(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=G();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(G()),n},tryConsume(s=1){if(s<=0)return!0;let i=G();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(G()),n=Math.min(t,n+s))}}}function Rs(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return pe(a=>{let l=ct(n,i),u=[],d=new ne,c=!1,m=1e9/i;function f(){for(;u.length>0;)if(l.tryConsume(1))a.emit(u.shift());else{d.start(Math.max(1,m/1e6),f);return}}let p=t.subscribe(g=>{for(let h of g){if(c)return;let y=h[0];if(y===Y)a.down([[Y]]);else if(y===L){if(o!==void 0&&u.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")u.shift(),u.push(h[1]);else{c=!0,d.cancel(),u.length=0,a.down([[O,new It(o)]]);return}}else u.push(h[1]);f()}else if(y===H)a.down([[H]]);else if(y===F)c=!0,d.cancel(),u.length=0,a.down([[F]]);else if(y===O)c=!0,d.cancel(),u.length=0,a.down([h]);else if(y===ce){c=!0,d.cancel(),u.length=0,a.down([h]);return}else a.down([h])}});return()=>{c=!0,d.cancel(),p()}},{...Ve(),initial:t.cache})}function Ms(t,e){let n=e?.initialStatus??"pending",r=ie([],(o,s)=>{let i=n;return r.meta.status.down([[L,n]]),r.meta.error.down([[L,null]]),t.subscribe(l=>{for(let u of l){let d=u[0];if(d===Y)s.down([[Y]]);else if(d===L)i==="errored"?se(()=>{r.meta.error.down([[L,null]]),r.meta.status.down([[L,"active"]])}):r.meta.status.down([[L,"active"]]),i="active",s.emit(u[1]);else if(d===H)s.down([[H]]);else if(d===F)r.meta.status.down([[L,"completed"]]),i="completed",s.down([[F]]);else if(d===O){let c=Gt(u);se(()=>{r.meta.error.down([[L,c]]),r.meta.status.down([[L,"errored"]])}),i="errored",s.down([u])}else s.down([u])}})},{...Ve(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Ns(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Es(t){return t!=null&&typeof t.then=="function"}function As(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Ss(t,e){return pe(n=>{let r,o;function s(){o?.(),o=void 0,Ns(e)||Es(e)||As(e)?r=$(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[F]]))}return o=t.subscribe(i=>{for(let a of i){let l=a[0];if(l===Y)n.down([[Y]]);else if(l===L)n.emit(a[1]);else if(l===H)n.down([[H]]);else if(l===F)n.down([[F]]);else if(l===O){s();return}else if(l===ce){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...Ve(),initial:t.cache})}function Os(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return pe(n=>{let r=!1,o=new ne;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new Pt(e)]]))})}let i=t.subscribe(a=>{for(let l of a){if(r)return;let u=l[0];if(u===Y)n.down([[Y]]);else if(u===L)s(),n.emit(l[1]);else if(u===H)n.down([[H]]);else if(u===F){o.cancel(),r=!0,n.down([[F]]);return}else if(u===O){o.cancel(),r=!0,n.down([l]);return}else if(u===ce){o.cancel(),r=!0,n.down([l]);return}else n.down([l])}});return s(),()=>{r=!0,o.cancel(),i()}},{...Ve(),initial:t.cache})}var Le,It,Pt,tt=ge(()=>{"use strict";Me();he();fe();ke();X();_n();re();Ne();Le=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};It=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Pt=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Ft(t){return{describeKind:"producer",...t}}function $r(t,e){let{signal:n,period:r,...o}=e??{};return pe(s=>{let i=!1,a=0,l,u,d=()=>{i=!0,l!==void 0&&clearTimeout(l),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",m)},c=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",m),s.emit(a++),s.down([[F]])))},m=()=>{i||(d(),s.down([[O,n.reason]]))};if(n?.aborted){m();return}return l=setTimeout(c,t),n?.addEventListener("abort",m,{once:!0}),d},Ft(o))}function Br(t,e){return pe(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[F]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},Ft(e))}function Cs(t){return t!=null&&typeof t.then=="function"}function Ls(t,e){let{signal:n,...r}=e??{};return pe(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[O,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[F]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Ft(r))}function Ds(t,e){let{signal:n,...r}=e??{};return pe(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,l=!1,u=t[Symbol.asyncIterator](),d=()=>{l||a.aborted||Promise.resolve(u.next()).then(c=>{if(!(l||a.aborted)){if(c.done){o.down([[F]]);return}o.emit(c.value),d()}},c=>{!l&&!a.aborted&&o.down([[O,c]])})};return d(),()=>{l=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},Ft(r))}function Is(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function $(t,e){if(Is(t))return t;if(Cs(t))return Ls(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ds(t,e);if(typeof n[Symbol.iterator]=="function")return Br(t,e)}return Ps(t)}function Ps(...t){return Br(t,void 0)}function pt(t,e,n){return ie([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function $t(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===L){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===F){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Gr(t,e){return new Promise((n,r)=>{let o=!1,s=!1,i;i=t.subscribe(a=>{for(let l of a){if(o)return;if(l[0]===L){let u=l[1];if(e(u)){o=!0,n(u),i?(i(),i=void 0):s=!0;return}}if(l[0]===O){o=!0,r(l[1]),i?(i(),i=void 0):s=!0;return}if(l[0]===F){o=!0,r(new Error("completed without matching value")),i?(i(),i=void 0):s=!0;return}}}),s&&(i?.(),i=void 0)})}async function jr(t,e){let n=e?.predicate??(o=>o!=null);if(e?.timeoutMs==null||e.timeoutMs<=0)return await Gr(t,n);if(Mn===void 0){let[o,s]=await Promise.all([Promise.resolve().then(()=>(tt(),Pr)),Promise.resolve().then(()=>(_n(),Dr))]);Mn=o.timeout,Fr=s.NS_PER_MS}let r=Mn(t,e.timeoutMs*Fr);return await Gr(r,n)}function Z(t){return t.subscribe(()=>{})}var Mn,Fr,re=ge(()=>{"use strict";fe();ke();X()});var tl={};un(tl,{AgentLoopGraph:()=>sn,AllTiersExhaustedError:()=>ft,BudgetExhaustedError:()=>Ut,ChatStreamGraph:()=>rn,CircuitOpenError:()=>Le,DEFAULT_DECAY_RATE:()=>rr,FallbackMissError:()=>Fs,LLMTimeoutError:()=>rt,ReplayCacheMissError:()=>Ke,ToolRegistryGraph:()=>on,admissionFilter3D:()=>Ua,agentLoop:()=>Ba,agentMemory:()=>qa,anthropicAdapter:()=>dn,canonicalJson:()=>Bt,cascadingLlmAdapter:()=>Vn,chatStream:()=>Qn,composePricing:()=>ii,computePrice:()=>no,contentGate:()=>Ga,costMeterExtractor:()=>Oa,createAdapter:()=>ei,createCapabilitiesRegistry:()=>rs,createPricingRegistry:()=>oi,dryRunAdapter:()=>Ee,dryRunPreset:()=>vi,fallbackAdapter:()=>En,fromLLM:()=>wi,frozenContext:()=>Mi,gatedStream:()=>Ea,gaugesAsContext:()=>Ja,googleAdapter:()=>An,graphFromSpec:()=>Ya,handoff:()=>ja,keywordFlagExtractor:()=>La,knobsAsTools:()=>Qa,llmConsolidator:()=>nr,llmExtractor:()=>tr,observableAdapter:()=>ni,openAICompatAdapter:()=>On,parseRateLimitFromError:()=>$n,promptNode:()=>Ei,redactor:()=>Fa,registryPricing:()=>si,resilientAdapter:()=>bi,streamExtractor:()=>Da,streamingPromptNode:()=>Na,suggestStrategy:()=>el,systemPromptBuilder:()=>Aa,toolCallExtractor:()=>Pa,toolRegistry:()=>Zn,toolSelector:()=>Va,validateGraphDef:()=>or,withBreaker:()=>Pn,withBudgetGate:()=>Fn,withDryRun:()=>li,withRateLimiter:()=>jn,withReplayCache:()=>Nn,withRetry:()=>Kn,withTimeout:()=>Un,zeroPrice:()=>In});module.exports=ns(tl);function vt(t,e){return`${t}::${e}`}function rs(t){let e=new Map,n=new Map,r=o=>{e.set(vt(o.provider,o.id),o);let s=n.get(o.provider);s||(s=new Set,n.set(o.provider,s)),s.add(o.id)};if(t)for(let o of t)r(o);return{register:r,lookup(o,s){let i=e.get(vt(o,s));if(i)return i;let a=n.get(o);if(!a)return;let l;for(let u of a)if(s.startsWith(u)&&(!l||u.length>l.key.length)){let d=e.get(vt(o,u));d&&(l={key:u,cap:d})}return l?.cap},remove(o,s){let i=e.delete(vt(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){return e.values()}}}he();function dn(t={}){return t.sdk?ls(t):as(t)}function Tt(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=os(t,e?.systemPrompt),a={model:o,messages:i.map(ss),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(is)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function os(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
1
+ "use strict";var yn=Object.defineProperty;var ds=Object.getOwnPropertyDescriptor;var ls=Object.getOwnPropertyNames;var ps=Object.prototype.hasOwnProperty;var ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var bn=(t,e)=>{for(var n in e)yn(t,n,{get:e[n],enumerable:!0})},fs=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ls(e))!ps.call(t,o)&&o!==n&&yn(t,o,{get:()=>e[o],enumerable:!(r=ds(e,o))||r.enumerable});return t};var ms=t=>fs(yn({},"__esModule",{value:!0}),t);function Tr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Tn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function vr(t,e){if(t.length<br)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${br})`);let n=0,r=t[n++];if(r!==Tn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Tn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),c=e.lookupCodec(s);if(c==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:c,codecVersion:i,payload:a}}function wr(t){t.registerCodec(gs)}var gs,Tn,br,vn=ve(()=>{"use strict";gs={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},Tn=1,br=4});function Et(t){if(t==null)return nt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var nt,Ot=ve(()=>{"use strict";nt={type:"system",id:""}});function At(){return rt>0||mt}function kr(){return rt>0}function ht(t){rt>0?gt.push(t):t()}function te(t){rt+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(rt-=1,rt===0)if(e){if(!mt){let n=gt.splice(0);for(let r of n)try{r()}catch{}Ke.length=0,Ue.length=0,ot.length=0}}else hs()}}function hs(){let t=!mt;t&&(mt=!0);let e=[],n=0;try{for(;Ke.length>0||Ue.length>0||ot.length>0||t&&gt.length>0;){if(t&&gt.length>0){let s=gt.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ke.length=0,Ue.length=0,ot.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Ke.length>0?Ke:Ue.length>0?Ue:ot).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(mt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ct(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!At()){t(e);return}(u>=5?ot:u===4?Ue:Ke).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let c=At();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);c?Ke.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);c?Ue.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);c?ot.push(()=>t(u)):t(u)}}var rt,mt,Ke,Ue,ot,gt,xe=ve(()=>{"use strict";rt=0,mt=!1,Ke=[],Ue=[],ot=[],gt=[]});function $(){return Math.trunc(performance.now()*1e6)}function he(){return Date.now()*1e6}var ge=ve(()=>{"use strict"});var Ge,C,J,z,Re,Se,Ce,fe,F,O,ze,Lt,xr,Dt,Rr,Sr,It,wn,kn,xn,Pt,ue=ve(()=>{"use strict";Ge=Symbol.for("graphrefly/START"),C=Symbol.for("graphrefly/DATA"),J=Symbol.for("graphrefly/DIRTY"),z=Symbol.for("graphrefly/RESOLVED"),Re=Symbol.for("graphrefly/INVALIDATE"),Se=Symbol.for("graphrefly/PAUSE"),Ce=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),F=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),ze=Object.freeze([J]),Lt=Object.freeze([z]),xr=Object.freeze([Re]),Dt=Object.freeze([Ge]),Rr=Object.freeze([F]),Sr=Object.freeze([fe]),It=Object.freeze([ze]),wn=Object.freeze([Lt]),kn=Object.freeze([xr]),xn=Object.freeze([Rr]),Pt=Object.freeze([Sr])});function Nr(t){t.registerMessageType(Ge,{tier:0,wireCrossing:!1}),t.registerMessageType(J,{tier:1,wireCrossing:!1}),t.registerMessageType(Re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Se,{tier:2,wireCrossing:!1}),t.registerMessageType(Ce,{tier:2,wireCrossing:!1}),t.registerMessageType(C,{tier:3,wireCrossing:!0}),t.registerMessageType(z,{tier:3,wireCrossing:!0}),t.registerMessageType(F,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Gt,_r=ve(()=>{"use strict";ue();Gt=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=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Rn(t){let e=ys.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Ne,ys,yt=ve(()=>{"use strict";Ne=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},ys=["human","llm","wallet","system"]});function Sn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Sn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Sn(t[n]);return e}return null}function vs(t){let e=Ts.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,c=3144134277,u=1013904242,d=2773480762,l=1359893119,f=2600822924,p=528734635,m=1541459225,g=new Uint32Array(64),h=(b,T)=>b>>>T|b<<32-T;for(let b=0;b<o;b+=64){for(let M=0;M<16;M++)g[M]=i.getUint32(b+M*4,!1);for(let M=16;M<64;M++){let D=g[M-15],S=g[M-2],G=h(D,7)^h(D,18)^D>>>3,H=h(S,17)^h(S,19)^S>>>10;g[M]=g[M-16]+G+g[M-7]+H>>>0}let T=a,k=c,v=u,w=d,x=l,R=f,N=p,V=m;for(let M=0;M<64;M++){let D=h(x,6)^h(x,11)^h(x,25),S=x&R^~x&N,G=V+D+S+bs[M]+g[M]>>>0,H=h(T,2)^h(T,13)^h(T,22),A=T&k^T&v^k&v,E=H+A>>>0;V=N,N=R,R=x,x=w+G>>>0,w=v,v=k,k=T,T=G+E>>>0}a=a+T>>>0,c=c+k>>>0,u=u+v>>>0,d=d+w>>>0,l=l+x>>>0,f=f+R>>>0,p=p+N>>>0,m=m+V>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(c)+y(u)+y(d)+y(l)+y(f)+y(p)+y(m)}function Nn(t){let e=Sn(t??null),n=JSON.stringify(e);return vs(n).slice(0,16)}function ws(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function _n(t,e,n){let r=n?.id??ws();if(t===0)return{id:r,version:0};let s=(n?.hash??Nn)(e);return{id:r,version:0,cid:s,prev:null}}function Mr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var bs,Ts,Er=ve(()=>{"use strict";bs=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]),Ts=new TextEncoder});function Cr(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Mn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Ft(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ne(t,e,n){let r=Lr(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Lr(t)?s=(En(e)?e:n)??{}:En(t)?s=t:s=(En(e)?e:n)??{},new de(r,o,s)}var Or,Ar,ks,xs,st,de,Lr,En,_e=ve(()=>{"use strict";vn();Ot();xe();ge();_r();yt();ue();Er();Or=()=>{},Ar=100;ks=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},xs=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Dt]:[Dt,[C,s]];o._status==="dirty"&&i.push(ze),Ct(e,i,o._config.tierOf)},st=new Gt({onMessage:ks,onSubscribe:xs});Nr(st);wr(st);de=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??st,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Nn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?_n(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Cr);let s={};for(let[a,c]of Object.entries(r.meta??{})){let u={initial:c,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[C,a]])},down(a){i._emit(Ft(a))},up(a){i._emitUp(Ft(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,c=i?.version??0,u=_n(e,s,{id:a,hash:o});u.version=c,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Et(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Et(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Ne({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Ne({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:he()}}down(e,n){let r=Ft(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[C,e]])}up(e,n){if(this._deps.length===0)return;let r=Ft(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let c=Et(n);if(!this._guard(c,"observe"))throw new Ne({actor:c,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let c of this._deps)Mn(c);if(this._partial===!1){for(let c of this._deps)if(c.prevData!==void 0||c.dataBatch.length!==0||c.terminal!==void 0||c.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(c){throw this._sinkCount-=1,c}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(c){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw c}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Or,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,c=!1;for(let u of i)a(u[0])>=3&&(c=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);c&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Mn(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=Cr(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(It),r.unsub=Or;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[O,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[O,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Mn(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==Ge){if(o===J){this._depDirtied(r);return}if(o===Re){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(kn);return}if(o===Se||o===Ce){this._emit([n]);return}if(o===fe){this._emit(Pt);return}if(o===C)this._depSettledAsData(r,n[1]);else if(o===z)this._depSettledAsResolved(r);else if(o===F)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===C||o===z)&&this._emit([n]),(o===F||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(It))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(wn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[O,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(xn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[O,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[O,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[O,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ar?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ar} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[ze,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let c of e){let u=n(c[0]);u<i&&(r=!1),u===3&&(o=!0),c[0]===J&&(s=!0),i=u}let a=e;if(!r){let c=e.map((u,d)=>({m:u,i:d,tier:n(u[0])}));c.sort((u,d)=>u.tier-d.tier||u.i-d.i),a=c.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let c=0;for(;c<a.length&&n(a[c][0])===0;)c++;return c===0?[ze,...a]:[...a.slice(0,c),ze,...a.slice(c)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let c=e[a];if(c[0]===O&&c[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(c=>c[0]===fe||c[0]===Re);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let c=n[a],u=c[0];if(u!==Se&&u!==Ce){o?.push(c);continue}if(c.length<2)throw new Error(`Node "${this.name}": [[${u===Se?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=c[1];if(u===Se)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(c):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===fe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Pt)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,c=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):c.push(u);c.length>0&&this._dispatchOrAccumulate(c)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,c=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===C){c=d;break}}for(let d=0;d<e.length;d++){let l=e[d],f=l[0];if(f===C){if(l.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(p){r==null&&(r=e.slice(0,d)),r.push(Lt),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(c<0||d===c)&&Mr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),f===J)this._status="dirty";else if(f===z)this._status="resolved";else if(f===F)this._status="completed";else if(f===O)this._status="errored";else if(f===Re){this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let m=p.invalidate;if(typeof m=="function")try{m()}catch{}}}else f===fe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(kr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ht(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ct(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Ct(this._deliverToSinks,n,this._config.tierOf)}},Lr=t=>Array.isArray(t),En=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function L(t,e){return ne([],{...e,initial:t})}function ie(t,e){return ne((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function _(t,e,n){return ne(t,(o,s,i)=>{let a=o.map((c,u)=>c!=null&&c.length>0?c.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function Me(t,e,n){return ne(t,(o,s,i)=>{let a=o.map((c,u)=>c!=null&&c.length>0?c.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var Y=ve(()=>{"use strict";_e()});var $r={};bn($r,{NS_PER_MS:()=>We,NS_PER_SEC:()=>at,constant:()=>Dr,decorrelatedJitter:()=>Fr,exponential:()=>Pr,fibonacci:()=>Gr,linear:()=>Ir,resolveBackoffPreset:()=>$t,withMaxAttempts:()=>_s});function He(t){return t<0?0:t}function Ss(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Ns(t,e){return t+Math.random()*(e-t)}function Dr(t){let e=He(t);return()=>e}function Ir(t,e){let n=He(t),r=e===void 0?n:He(e);return o=>n+r*Math.max(0,o)}function Pr(t){let e=He(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=He(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,c=1;for(let u=0;u<Math.max(0,s);u++){if(c>=a){c=a;break}c*=n}i=e*c,i>r&&(i=r)}return Ss(i,o)}}function Gr(t=100*1e6,e=30*1e9){let n=He(t),r=He(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let c=1;c<s;c++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Fr(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Ns(t,i)}}function _s(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function $t(t){if(t==="constant")return Dr(1*1e9);if(t==="linear")return Ir(1*1e9);if(t==="exponential")return Pr();if(t==="fibonacci")return Gr();if(t==="decorrelatedJitter")return Fr();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var We,at,An=ve(()=>{"use strict";We=1e6,at=1e9});var se,De=ve(()=>{"use strict";se=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Br={};bn(Br,{CircuitOpenError:()=>Fe,RateLimiterOverflowError:()=>jt,TimeoutError:()=>Bt,circuitBreaker:()=>Tt,fallback:()=>Ps,rateLimiter:()=>As,retry:()=>Es,retrySource:()=>Cn,timeout:()=>Gs,tokenBucket:()=>vt,withBreaker:()=>Os,withStatus:()=>Cs});function qe(t){return{describeKind:"derived",...t}}function Ms(t){return t<0?0:t}function Vt(t){return t[1]}function jr(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Es(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?$t(r):r;return ie(i=>{let a=0,c=!1,u=null,d,l=new se;function f(){d?.(),d=void 0}function p(g){if(c)return;if(a>=o){f(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,u);if(h==null){f(),i.down([[O,g]]);return}let y;try{y=jr(h)}catch{f(),i.down([[O,g]]);return}u=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),f(),d=t.subscribe(g=>{if(!c)for(let h of g){let y=h[0];if(y===J)i.down([[J]]);else if(y===C)a=0,u=null,i.emit(h[1]);else if(y===z)i.down([[z]]);else if(y===F)f(),i.down([[F]]);else if(y===O){p(Vt(h));return}else i.down([h])}})}return m(),()=>{c=!0,l.cancel(),f()}},{...qe(),initial:t.cache})}function Cn(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?$t(r):r;return ie(i=>{let a=0,c=!1,u=null,d,l=new se;function f(){d?.(),d=void 0}function p(g){if(c)return;if(a>=o){f(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,u);if(h==null){f(),i.down([[O,g]]);return}let y;try{y=jr(h)}catch{f(),i.down([[O,g]]);return}u=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),f();let g;try{g=t()}catch(h){p(h);return}d=g.subscribe(h=>{if(!c)for(let y of h){let b=y[0];if(b===J)i.down([[J]]);else if(b===C)a=0,u=null,i.emit(y[1]);else if(b===z)i.down([[z]]);else if(b===F)f(),i.down([[F]]);else if(b===O){p(Vt(y));return}else i.down([y])}})}return m(),()=>{c=!0,l.cancel(),f()}},{...qe(),initial:e?.initial})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=Ms(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??$,i="closed",a=0,c=0,u=0,d=n,l=0;function f(){if(!r)return n;let g=r(c);return g!==null?g:n}function p(){i="open",d=f(),u=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,c=0):i==="closed"&&(a=0)},recordFailure(g){if(i==="half-open"){c++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,c=0,l=0}}}function Os(t,e){let n=e?.onOpen??"skip";return r=>{let o=ne([],(s,i)=>{function a(){o.meta.breakerState.down([[C,t.state]])}let c=r.subscribe(u=>{for(let d of u){let l=d[0];l===J?i.down([[J]]):l===C?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[O,new Fe]]):i.down([[z]])):l===z?i.down([[z]]):l===F?(t.recordSuccess(),a(),i.down([[F]])):l===O?(t.recordFailure(Vt(d)),a(),i.down([d])):i.down([d])}});return a(),c},{...qe(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function vt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=$();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o($()),n},tryConsume(s=1){if(s<=0)return!0;let i=$();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o($()),n=Math.min(t,n+s))}}}function As(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return ie(a=>{let c=vt(n,i),u=[],d=new se,l=!1,f=1e9/i;function p(){for(;u.length>0;)if(c.tryConsume(1))a.emit(u.shift());else{d.start(Math.max(1,f/1e6),p);return}}let m=t.subscribe(g=>{for(let h of g){if(l)return;let y=h[0];if(y===J)a.down([[J]]);else if(y===C){if(o!==void 0&&u.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")u.shift(),u.push(h[1]);else{l=!0,d.cancel(),u.length=0,a.down([[O,new jt(o)]]);return}}else u.push(h[1]);p()}else if(y===z)a.down([[z]]);else if(y===F)l=!0,d.cancel(),u.length=0,a.down([[F]]);else if(y===O)l=!0,d.cancel(),u.length=0,a.down([h]);else if(y===fe){l=!0,d.cancel(),u.length=0,a.down([h]);return}else a.down([h])}});return()=>{l=!0,d.cancel(),m()}},{...qe(),initial:t.cache})}function Cs(t,e){let n=e?.initialStatus??"pending",r=ne([],(o,s)=>{let i=n;return r.meta.status.down([[C,n]]),r.meta.error.down([[C,null]]),t.subscribe(c=>{for(let u of c){let d=u[0];if(d===J)s.down([[J]]);else if(d===C)i==="errored"?te(()=>{r.meta.error.down([[C,null]]),r.meta.status.down([[C,"active"]])}):r.meta.status.down([[C,"active"]]),i="active",s.emit(u[1]);else if(d===z)s.down([[z]]);else if(d===F)r.meta.status.down([[C,"completed"]]),i="completed",s.down([[F]]);else if(d===O){let l=Vt(u);te(()=>{r.meta.error.down([[C,l]]),r.meta.status.down([[C,"errored"]])}),i="errored",s.down([u])}else s.down([u])}})},{...qe(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Ls(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Ds(t){return t!=null&&typeof t.then=="function"}function Is(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Ps(t,e){return ie(n=>{let r,o;function s(){o?.(),o=void 0,Ls(e)||Ds(e)||Is(e)?r=I(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[F]]))}return o=t.subscribe(i=>{for(let a of i){let c=a[0];if(c===J)n.down([[J]]);else if(c===C)n.emit(a[1]);else if(c===z)n.down([[z]]);else if(c===F)n.down([[F]]);else if(c===O){s();return}else if(c===fe){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...qe(),initial:t.cache})}function Gs(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return ie(n=>{let r=!1,o=new se;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new Bt(e)]]))})}let i=t.subscribe(a=>{for(let c of a){if(r)return;let u=c[0];if(u===J)n.down([[J]]);else if(u===C)s(),n.emit(c[1]);else if(u===z)n.down([[z]]);else if(u===F){o.cancel(),r=!0,n.down([[F]]);return}else if(u===O){o.cancel(),r=!0,n.down([c]);return}else if(u===fe){o.cancel(),r=!0,n.down([c]);return}else n.down([c])}});return s(),()=>{r=!0,o.cancel(),i()}},{...qe(),initial:t.cache})}var Fe,jt,Bt,ct=ve(()=>{"use strict";xe();ge();ue();_e();Y();An();ee();De();Fe=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};jt=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Bt=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Kt(t){return{describeKind:"producer",...t}}function Ur(t,e){let{signal:n,period:r,...o}=e??{};return ie(s=>{let i=!1,a=0,c,u,d=()=>{i=!0,c!==void 0&&clearTimeout(c),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",f)},l=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",f),s.emit(a++),s.down([[F]])))},f=()=>{i||(d(),s.down([[O,n.reason]]))};if(n?.aborted){f();return}return c=setTimeout(l,t),n?.addEventListener("abort",f,{once:!0}),d},Kt(o))}function zr(t,e){return ie(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[F]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},Kt(e))}function Fs(t){return t!=null&&typeof t.then=="function"}function $s(t,e){let{signal:n,...r}=e??{};return ie(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[O,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[F]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Kt(r))}function js(t,e){let{signal:n,...r}=e??{};return ie(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,c=!1,u=t[Symbol.asyncIterator](),d=()=>{c||a.aborted||Promise.resolve(u.next()).then(l=>{if(!(c||a.aborted)){if(l.done){o.down([[F]]);return}o.emit(l.value),d()}},l=>{!c&&!a.aborted&&o.down([[O,l]])})};return d(),()=>{c=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},Kt(r))}function Bs(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function I(t,e){if(Bs(t))return t;if(Fs(t))return $s(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return js(t,e);if(typeof n[Symbol.iterator]=="function")return zr(t,e)}return Vs(t)}function Vs(...t){return zr(t,void 0)}function wt(t,e,n){return ne([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function we(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===C){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===F){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Vr(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,c=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let d of u){if(s)return;if(!(c&&d[0]===C)){if(d[0]===C){let l=d[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(d[0]===O){s=!0,o(d[1]),a?(a(),a=void 0):i=!0;return}if(d[0]===F){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),c=!1,i&&(a?.(),a=void 0)})}async function Hr(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Vr(t,n,{skipCurrent:r});if(Ln===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(ct(),Br)),Promise.resolve().then(()=>(An(),$r))]);Ln=s.timeout,Kr=i.NS_PER_MS}let o=Ln(t,e.timeoutMs*Kr);return await Vr(o,n,{skipCurrent:r})}function X(t){return t.subscribe(()=>{})}var Ln,Kr,ee=ve(()=>{"use strict";ue();_e();Y()});var bc={};bn(bc,{AgentLoopGraph:()=>gn,AllTiersExhaustedError:()=>Rt,BudgetExhaustedError:()=>Zt,ChatStreamGraph:()=>fn,CircuitOpenError:()=>Fe,DEFAULT_DECAY_RATE:()=>mr,FallbackMissError:()=>Ys,LLMTimeoutError:()=>lt,ReplayCacheMissError:()=>Qe,ToolRegistryGraph:()=>mn,admissionFilter3D:()=>Za,agentLoop:()=>Ja,agentMemory:()=>rc,anthropicAdapter:()=>In,canonicalJson:()=>jn,cascadingLlmAdapter:()=>er,chatStream:()=>dr,composePricing:()=>hi,computePrice:()=>Wn,contentGate:()=>Ha,costMeterExtractor:()=>ja,createAdapter:()=>di,createCapabilitiesRegistry:()=>Rs,createPricingRegistry:()=>mi,dryRunAdapter:()=>Je,fallbackAdapter:()=>Bn,fromLLM:()=>Oi,frozenContext:()=>Ii,gatedStream:()=>Ga,gaugesAsContext:()=>oc,googleAdapter:()=>Vn,graphFromSpec:()=>pc,handoff:()=>Ya,keywordFlagExtractor:()=>Va,knobsAsTools:()=>mc,llmConsolidator:()=>fr,llmExtractor:()=>pr,observableAdapter:()=>pi,openAICompatAdapter:()=>Un,parseRateLimitFromError:()=>Qn,pricingFor:()=>yi,promptNode:()=>Gi,redactor:()=>Wa,registryPricing:()=>gi,resilientAdapter:()=>Ei,streamExtractor:()=>Ka,streamingPromptNode:()=>Pa,suggestStrategy:()=>hc,systemPromptBuilder:()=>Fa,tier:()=>_i,toolCallExtractor:()=>za,toolRegistry:()=>lr,toolSelector:()=>Qa,validateGraphDef:()=>yc,withBreaker:()=>qn,withBudgetGate:()=>Yn,withDryRun:()=>Ti,withRateLimiter:()=>Zn,withReplayCache:()=>xt,withRetry:()=>tr,withTimeout:()=>nr,zeroPrice:()=>Xt});module.exports=ms(bc);Y();xe();ge();ue();Y();var On=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=$(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=$(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return $()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??$())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function it(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new On({maxSize:n,defaultTtl:r}),c=L(a.toMap(),{name:e,describeKind:"state",equals:(f,p)=>f===p,...o!=null?{versioning:o}:{}});function u(){let f=a.toMap();te(()=>{c.down([[J]]),c.down([[C,f]])})}function d(){if(!i)return;let f=a.toMap(),p=i.archiveThreshold,m=i.maxSize,g=[];for(let[y,b]of f)g.push({key:y,value:b,score:i.score(y,b)});g.sort((y,b)=>y.score-b.score);let h=new Set;if(p!==void 0)for(let y of g)if(y.score<p)h.add(y.key);else break;if(m!==void 0&&g.length-h.size>m)for(let y of g){if(g.length-h.size<=m)break;h.has(y.key)||h.add(y.key)}if(h.size!==0)for(let y of g)h.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(f,p="mutation"){let m=a.version;try{return f()}finally{a.version!==m&&(p==="mutation"&&d(),u())}}return{entries:c,has(f){return l(()=>a.has(f),"read")},get(f){return l(()=>a.get(f),"read")},set(f,p,m){l(()=>a.set(f,p,m?.ttl))},setMany(f,p){l(()=>a.setMany(f,p?.ttl))},delete(f){l(()=>a.delete(f))},deleteMany(f){l(()=>a.deleteMany(f))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function bt(t,e){return`${t}::${e}`}function Rs(t){let e=it({name:"capabilitiesRegistry"}),n=u=>{e.set(bt(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,d)=>{let l=e.get(bt(u,d));if(l)return l;let f=e.entries.cache;if(!f)return;let p;for(let[,m]of f){if(m.provider!==u)continue;let g=m.id;d.startsWith(g)&&(!p||g.length>p.id.length)&&(p=m)}return p},o=128,s=new Map,i=new Map,a=(u,d,l,f)=>{for(u.has(d)&&u.delete(d),u.set(d,l);u.size>f;){let p=u.keys().next().value;if(p===void 0)break;u.delete(p)}},c=_([e.entries],([u])=>Array.from(u.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,d){let l=e.has(bt(u,d));return l&&e.delete(bt(u,d)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let d of u.values())yield d})()},lookupNode(u,d){let l=bt(u,d),f=s.get(l);if(f)return s.delete(l),s.set(l,f),f;let p=_([e.entries],()=>r(u,d),{name:`capabilitiesRegistry/lookup/${u}::${d}`,initial:void 0});return a(s,l,p,o),p},entriesNode:c,byProvider(u){let d=i.get(u);if(d)return i.delete(u),i.set(u,d),d;let l=_([c],([f])=>f.filter(p=>p.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}ge();ue();_e();Y();ee();function Dn(t){return{describeKind:"derived",...t}}function Wr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return ne([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[z]]);return}for(let c of a)!o&&r(c)&&(o=!0,e(c)),i.emit(c)},Dn(n))}function Ks(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,c=!1;for(let u of i)u[0]!==Ge&&(u[0]===C?e.emit(u[1]):u[0]===F?a=!0:u[0]===O?(c=!0,e.down([u])):(u[0]===J||u[0]===z)&&e.down([u]));c?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ye(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ne([t],(i,a,c)=>{if(c.terminalDeps[0]!=null&&c.terminalDeps[0]!==!0){s();return}if(c.terminalDeps[0]===!0){o=!0,r||a.down([[F]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=Ks(I(e(u[u.length-1])),a,()=>{s(),o&&a.down([[F]])}),{deactivate:()=>{s(),o=!1}}},{...Dn(n),completeWhenDepsComplete:!1})}function qr(t,e,n){return ie(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===C)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===F&&r.down([[F]])});return()=>{o()}},Dn(n))}var kt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};async function*ut(t,e){let n=e?.parse??(v=>v),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],c,u,d=[],l=()=>{if(a.length===0&&i==="message"&&c===void 0){a=[];return}let v=a.join(`
2
+ `);d.push({event:i,data:n(v),id:c,retry:u}),i="message",a=[],c=void 0,u=void 0},f=v=>{if(v===""){l();return}if(v.startsWith(":"))return;let w=v.indexOf(":"),x=w<0?v:v.slice(0,w),R=w<0?"":v.slice(w+1);switch(R.startsWith(" ")&&(R=R.slice(1)),x){case"event":i=R;break;case"data":a.push(R);break;case"id":R.includes("\0")||(c=R);break;case"retry":{let N=Number(R);Number.isFinite(N)&&(u=N);break}}},p=(v,w)=>{s+=o.decode(v,{stream:!w});let x=s.split(/\r?\n/);s=x.pop()??"";for(let R of x)f(R)},m=t,g=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,h,y,b=!1,T=()=>{b||(b=!0,h&&h.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},k=()=>{T()};if(r){if(r.aborted)return;r.addEventListener("abort",k,{once:!0})}try{if(g){for(h=g.getReader();!r?.aborted;){let{value:v,done:w}=await h.read();if(w)break;for(p(v,!1);d.length>0;)yield d.shift()}p(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let w=await y.next();if(w.done)break;for(p(w.value,!1);d.length>0;)yield d.shift()}p(new Uint8Array,!0)}if(s.trim()){for(let v of s.split(/\r?\n/))f(v);l()}for(;d.length>0;)yield d.shift()}finally{r&&r.removeEventListener("abort",k),T()}}async function Ie(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}function In(t={}){return t.sdk?qs(t):Ws(t)}function Ut(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=Us(t,e?.systemPrompt),a={model:o,messages:i.map(zs),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Hs)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Us(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
2
3
 
3
- `):void 0,chat:r}}function ss(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function is(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function wt(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function cn(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function dr(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:cn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function as(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let l=Tt(i,a,t.model,!1),u=G(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(l),signal:a?.signal});if(!d.ok)throw await ur(d);let c=await d.json(),m=Math.max(0,(G()-u)/1e6);return dr(c,m)},async*stream(i,a){let l=Tt(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(l),signal:a?.signal});if(!u.ok)throw await ur(u);if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let d,c,m=new Map;for await(let f of us(u.body)){let p=f.data;if(!p)continue;let g;try{g=JSON.parse(p)}catch{continue}switch(g.type){case"message_start":{d=wt(d,g.message.usage);break}case"content_block_start":{let h=g,y=h.content_block;y.type==="tool_use"&&(m.set(h.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let h=g,y=h.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let v=m.get(h.index);v&&(v.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let h=g;h.delta.stop_reason&&(c=h.delta.stop_reason),h.delta.usage&&(d=wt(d,h.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:cn(d)}),yield{type:"finish",reason:c??"stop"}}}}function ls(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Tt(n,r,t.model,!1),s=G(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(G()-s)/1e6);return dr(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Tt(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=wt(s,a.message.usage);break;case"content_block_delta":{let l=a.delta;l?.type==="text_delta"&&typeof l.text=="string"?yield{type:"token",delta:l.text}:l?.type==="input_json_delta"&&typeof l.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:l.partial_json}}:l?.type==="thinking_delta"&&typeof l.thinking=="string"&&(yield{type:"thinking",delta:l.thinking});break}case"message_delta":{let l=a;l.delta.stop_reason&&(i=l.delta.stop_reason),l.delta.usage&&(s=wt(s,l.delta.usage));break}}s&&(yield{type:"usage",usage:cn(s)}),yield{type:"finish",reason:i??"stop"}}}}async function*us(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield ar(r));return}r+=n.decode(s,{stream:!0});let i=lr(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let l=ar(a);(l.data||l.event)&&(yield l),i=lr(r)}}}finally{e.releaseLock()}}function ar(t){let e={},n=[];for(let r of t.split(`
4
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
5
- `)),e}function lr(t){let e=t.indexOf(`\r
6
- \r
7
- `),n=t.indexOf(`
4
+ `):void 0,chat:r}}function zs(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function Hs(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function zt(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Pn(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function Jr(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Pn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Ws(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let c=Ut(i,a,t.model,!1),u=$(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(c),signal:a?.signal});if(!d.ok)throw await Ie(d,"Anthropic");let l=await d.json(),f=Math.max(0,($()-u)/1e6);return Jr(l,f)},async*stream(i,a){let c=Ut(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(c),signal:a?.signal});if(!u.ok)throw await Ie(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,f=new Map;for await(let p of ut(u.body,{signal:a?.signal})){let m=p.data;if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}switch(g.type){case"message_start":{d=zt(d,g.message.usage);break}case"content_block_start":{let h=g,y=h.content_block;y.type==="tool_use"&&(f.set(h.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let h=g,y=h.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=f.get(h.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let h=g;h.delta.stop_reason&&(l=h.delta.stop_reason),h.delta.usage&&(d=zt(d,h.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:Pn(d)}),yield{type:"finish",reason:l??"stop"}}}}function qs(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Ut(n,r,t.model,!1),s=$(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,($()-s)/1e6);return Jr(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Ut(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=zt(s,a.message.usage);break;case"content_block_delta":{let c=a.delta;c?.type==="text_delta"&&typeof c.text=="string"?yield{type:"token",delta:c.text}:c?.type==="input_json_delta"&&typeof c.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:c.partial_json}}:c?.type==="thinking_delta"&&typeof c.thinking=="string"&&(yield{type:"thinking",delta:c.thinking});break}case"message_delta":{let c=a;c.delta.stop_reason&&(i=c.delta.stop_reason),c.delta.usage&&(s=zt(s,c.delta.usage));break}}s&&(yield{type:"usage",usage:Pn(s)}),yield{type:"finish",reason:i??"stop"}}}}De();function Ht(){let t=new Error("aborted");return t.name="AbortError",t}function Yr(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ht()):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ht())},e.addEventListener("abort",s,{once:!0}))})}function Je(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let c=[...a].reverse().find(u=>u.role==="user");return c?`echo: ${c.content}`:"dry-run: no user message"}),i=t.usage??((a,c)=>{let u=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(c.length/4)}}});return{provider:e,model:n,async invoke(a,c){if(await Yr(r,c?.signal),c?.signal?.aborted)throw Ht();let u=s(a,c),d=i(a,u);return{content:u,usage:d,finishReason:"stop",model:c?.model??n,provider:e,tier:c?.tier,metadata:{dryRun:!0}}},async*stream(a,c){let u=s(a,c),d=i(a,u),l=Math.ceil(u.length/o)||1,f=r>0?r/l:0;for(let p=0;p<u.length;p+=o){if(c?.signal?.aborted)throw Ht();await Yr(f,c?.signal),yield{type:"token",delta:u.slice(p,p+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}ge();async function Wt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=Qr[r[s]];return o}var Qr=new Array(256);for(let t=0;t<256;t++)Qr[t]=t.toString(16).padStart(2,"0");function Gn(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}ge();var Fn=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function $n(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function Xr(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let c=$n(s(a)),u=await Wt(c);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let c=await i(a),u=await e.load(c);if(u==null){if(o==="read-strict")throw new Fn(c,a);return}return u},async store(a,c){if(o==="read")return;let u=await i(a);await e.save(u,c)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let c=await i(a);await e.clear(c)}}}ee();function Zr(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),c;a!=null&&typeof a.then=="function"?c=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?c=we(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?c=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:f,done:p}=await l.next();if(p)throw new Error("singleFromAny: factory returned empty async iterable");return f}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?c=(async()=>{let l=a[Symbol.iterator]();try{let{value:f,done:p}=l.next();if(p)throw new Error("singleFromAny: factory returned empty iterable");return f}finally{l.return?.()}})():c=Promise.resolve(a);let u,d=()=>{r.get(s)===u&&r.delete(s)};return u=c.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,u),u}}ee();De();function eo(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Xr({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:c,opts:u})=>{let{signal:d,keyContext:l,...f}=u??{};return{messages:c,opts:f}}});async function a(c,u){if(r){if(r.length<=1){let l={messages:c,opts:u,context:u?.keyContext},f=await r(l);return`${o}:${f}`}let d=await r(c,u);return`${o}:${d}`}return i.keyFor({messages:c,opts:u})}return{keyFor:a,async lookup(c,u){if(n!=="write"){if(r){let d=await a(c,u),l=await e.load(d);return l??void 0}return i.lookup({messages:c,opts:u})}},async store(c,u,d){if(n!=="read"){if(r){let l=await a(c,u);await e.save(l,d);return}await i.store({messages:c,opts:u},d)}},async forget(c,u){if(!(n==="read"||n==="write")&&e.clear){if(r){let d=await a(c,u);await e.clear(d);return}await i.forget({messages:c,opts:u})}}}}ge();ue();Y();ee();function be(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function qt(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(d=>{throw r(d),d}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=I(t);if(r){let u=!1;s.subscribe(d=>{for(let l of d){if(u)return;l[0]===O&&(u=!0,r(l[1]))}})}let i,a=!1,c=Wr(s,u=>{i=n(u),a=!0});return _([c],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function Ye(t){let e=t.endNs??$();return{timestamp:e,wallClock:t.startWallClockNs??he(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Le(){return{input:{regular:0},output:{regular:0}}}var to=Symbol.for("graphrefly.adapter.middlewareLayers");function me(t,e,n){let o=[...n?Js(n):[],e];return Object.defineProperty(t,to,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function Js(t){let e=t[to];return Array.isArray(e)?e:[]}var Qe=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function xt(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",c=eo({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=f=>f<=0?Promise.resolve():new Promise(p=>{new se().start(f,()=>p())}),d=Zr(async({messages:f,invokeOpts:p})=>await we(I(t.invoke(f,p))),{keyFn:({_precomputedKey:f})=>f}),l=be(t,{async invoke(f,p){let m=await c.keyFor(f,p),g=await c.lookup(f,p);if(g?.response){let y=g.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Qe(m,"invoke");let h=await d({messages:f,invokeOpts:p,_precomputedKey:m});return a||await c.store(f,p,{response:h,storedAtNs:he()}),h},async*stream(f,p){if(!r){for await(let w of t.stream(f,p))yield w;return}let m=await c.keyFor(f,p),g=await c.lookup(f,p);if(g){let w=g.response;if(g.streamChunks&&g.streamCadenceMs)for(let x=0;x<g.streamChunks.length;x++){let R=g.streamCadenceMs[x]??0,N=s>0?R/s:0;N>0&&await u(N),yield{type:"token",delta:g.streamChunks[x]?.delta??""}}else w.content&&(yield{type:"token",delta:w.content});w.usage&&(yield{type:"usage",usage:w.usage}),yield{type:"finish",reason:w.finishReason??"stop"};return}if(n==="read-strict")throw new Qe(m,"stream");let h="",y,b,T=[],k=[],v;for await(let w of t.stream(f,p)){if(w.type==="token"&&(h+=w.delta,o)){let x=$(),R=v===void 0?0:(x-v)/1e6;k.push(R),v=x,T.push({delta:w.delta})}w.type==="usage"&&(y=w.usage),w.type==="finish"&&(b=w.reason),yield w}if((h||y)&&!a){let x={response:{content:h,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??p?.model??"",provider:t.provider},storedAtNs:he(),...o?{streamChunks:T,streamCadenceMs:k}:{}};await c.store(f,p,x)}}});return me(l,"withReplayCache",t),l}var jn=$n;var Ys=Qe;function no(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function ro(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function Qs(t,e){if("key"in t)return t.key;let n=jn({messages:t.messages,opts:t.invokeOpts??{}}),r=await Wt(n);return`${e}:${r}`}function Xs(t){let e={response:t.response,storedAtNs:he()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function Zs(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=Gn(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Qs(i,e);await r.save(a,Xs(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Bn(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?Je({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let f=t.respond?t.respond(d,l):no(e,n);return ro(f,e,n)},async*stream(d,l){let f=t.respond?t.respond(d,l):no(e,n),p=ro(f,e,n);yield{type:"token",delta:p.content},p.usage&&(yield{type:"usage",usage:p.usage}),yield{type:"finish",reason:p.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let d=Zs(t,o);i=d.tier??Gn(),a=d.seedReady}let c=t.record?"read-write":r==="throw"?"read-strict":"read",u=xt(s,{storage:i,mode:c,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(d,l){return await a,u.invoke(d,l)},async*stream(d,l){await a;for await(let f of u.stream(d,l))yield f}}}ge();function Vn(t={}){return t.sdk?ri(t):ni(t)}function Jt(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let c of i.toolCalls)a.push({functionCall:{name:c.name,args:c.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
8
5
 
9
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function ur(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Anthropic API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}Ne();function xt(){let t=new Error("aborted");return t.name="AbortError",t}function cr(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(xt()):new Promise((n,r)=>{let o=new ne,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(xt())},e.addEventListener("abort",s,{once:!0}))})}function Ee(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let l=[...a].reverse().find(u=>u.role==="user");return l?`echo: ${l.content}`:"dry-run: no user message"}),i=t.usage??((a,l)=>{let u=a.reduce((d,c)=>d+c.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(l.length/4)}}});return{provider:e,model:n,async invoke(a,l){if(await cr(r,l?.signal),l?.signal?.aborted)throw xt();let u=s(a,l),d=i(a,u);return{content:u,usage:d,finishReason:"stop",model:l?.model??n,provider:e,tier:l?.tier,metadata:{dryRun:!0}}},async*stream(a,l){let u=s(a,l),d=i(a,u),c=Math.ceil(u.length/o)||1,m=r>0?r/c:0;for(let f=0;f<u.length;f+=o){if(l?.signal?.aborted)throw xt();await cr(m,l?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}he();async function kt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=pr[r[s]];return o}var pr=new Array(256);for(let t=0;t<256;t++)pr[t]=t.toString(16).padStart(2,"0");function pn(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}he();re();function Vr(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),l;a!=null&&typeof a.then=="function"?l=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?l=$t(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?l=(async()=>{let c=a[Symbol.asyncIterator]();try{let{value:m,done:f}=await c.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return m}finally{await c.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?l=(async()=>{let c=a[Symbol.iterator]();try{let{value:m,done:f}=c.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return m}finally{c.return?.()}})():l=Promise.resolve(a);let u,d=()=>{r.get(s)===u&&r.delete(s)};return u=l.then(c=>(d(),c),c=>{throw d(),c}),r.set(s,u),u}}Ne();var Ke=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function Nn(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=e.storage,l=n==="read"||n==="read-strict",u=async(g,h)=>{if(e.keyFn){let x=e.keyFn;if(x.length<=1){let R={messages:g,opts:h,context:h?.keyContext},k=await x(R);return`${i}:${k}`}let _=await x(g,h);return`${i}:${_}`}let{signal:y,keyContext:v,...b}=h??{},T=Bt({messages:g,opts:b}),w=await kt(T);return`${i}:${w}`},d=async g=>{if(n==="write-only")return;let h=await a.load(g);if(h!=null)try{return typeof h=="string"?JSON.parse(h):h}catch{return}},c=async g=>(await d(g))?.response,m=async(g,h,y)=>{if(l)return;let v={response:h,storedAtNs:be(),...y?{streamChunks:y.chunks,streamCadenceMs:y.delaysMs}:{}};await a.save(g,v)},f=g=>g<=0?Promise.resolve():new Promise(h=>{new ne().start(g,()=>h())}),p=Vr(async({messages:g,invokeOpts:h})=>{let y=t.invoke(g,h);return await Gs(y)},{keyFn:({_precomputedKey:g})=>g});return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(g,h){let y=await u(g,h),v=await c(y);if(v)return{...v,metadata:{...v.metadata??{},replayCache:"hit"}};if(n==="read-strict")throw new Ke(y,"invoke");let b=await p({messages:g,invokeOpts:h,_precomputedKey:y});return await m(y,b),b},async*stream(g,h){if(!r){for await(let k of t.stream(g,h))yield k;return}let y=await u(g,h),v=await d(y);if(v){let k=v.response;if(v.streamChunks&&v.streamCadenceMs)for(let P=0;P<v.streamChunks.length;P++){let A=v.streamCadenceMs[P]??0,D=s>0?A/s:0;D>0&&await f(D),yield{type:"token",delta:v.streamChunks[P]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new Ke(y,"stream");let b="",T,w,x=[],_=[],R;for await(let k of t.stream(g,h)){if(k.type==="token"&&(b+=k.delta,o)){let P=G(),A=R===void 0?0:(P-R)/1e6;_.push(A),R=P,x.push({delta:k.delta})}k.type==="usage"&&(T=k.usage),k.type==="finish"&&(w=k.reason),yield k}if(b||T){let k={content:b,usage:T??{input:{regular:0},output:{regular:0}},finishReason:w,model:t.model??h?.model??"",provider:t.provider};await m(y,k,o?{chunks:x,delaysMs:_}:void 0)}}}}function Bt(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}async function Gs(t){if(t!=null&&typeof t.then=="function")return await t;if(t&&typeof t=="object"&&"content"in t)return t;throw new Error("withReplayCache: adapter.invoke must return Promise or LLMResponse (Node input not supported in cache path)")}var Fs=Ke;function Kr(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function Ur(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function $s(t,e){if("key"in t)return t.key;let n=Bt({messages:t.messages,opts:t.invokeOpts??{}}),r=await kt(n);return`${e}:${r}`}function Bs(t){let e={response:t.response,storedAtNs:be()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function js(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=pn(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await $s(i,e);await r.save(a,Bs(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function En(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?Ee({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,c){let m=t.respond?t.respond(d,c):Kr(e,n);return Ur(m,e,n)},async*stream(d,c){let m=t.respond?t.respond(d,c):Kr(e,n),f=Ur(m,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let d=js(t,o);i=d.tier??pn(),a=d.seedReady}let l=t.record?"read-write":r==="throw"?"read-strict":"read",u=Nn(s,{storage:i,mode:l,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(d,c){return await a,u.invoke(d,c)},async*stream(d,c){await a;for await(let m of u.stream(d,c))yield m}}}he();function An(t={}){return t.sdk?Hs(t):Us(t)}function jt(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let l of i.toolCalls)a.push({functionCall:{name:l.name,args:l.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
6
+ `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(ei)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function ei(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Kn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function oo(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Kn(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function ti(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function ni(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=ti(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),c=Jt(s,i),u=$(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!l.ok)throw await Ie(l,"Google");let f=await l.json(),p=Math.max(0,($()-u)/1e6);return oo(f,p)},async*stream(s,i){let a=r(i),c=Jt(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!d.ok)throw await Ie(d,"Google");if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,f;for await(let p of ut(d.body,{signal:i?.signal})){if(!p.data)continue;let m;try{m=JSON.parse(p.data)}catch{continue}let g=m.candidates?.[0];for(let h of g?.content?.parts??[])typeof h.text=="string"&&(h.thought?yield{type:"thinking",delta:h.text}:yield{type:"token",delta:h.text}),h.functionCall&&(yield{type:"tool-call-delta",delta:{name:h.functionCall.name,argumentsDelta:JSON.stringify(h.functionCall.args??{})}});g?.finishReason&&(f=g.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Kn(l)}),yield{type:"finish",reason:f??"stop"}}}}function ri(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=$(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),c=Math.max(0,($()-i)/1e6);return oo(a,c)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let c of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let u=c.candidates?.[0];for(let d of u?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});u?.finishReason&&(a=u.finishReason),c.usageMetadata&&(i=c.usageMetadata)}i&&(yield{type:"usage",usage:Kn(i)}),yield{type:"finish",reason:a??"stop"}}}}ge();var oi={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Un(t={}){return t.sdk?ui(t):ci(t)}function Yt(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(si);e?.systemPrompt&&!t.some(c=>c.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(ii)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function si(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function ii(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function zn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function so(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:ai(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:zn(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function ai(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function io(t){let e=t.preset??"openai",n=oi[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function ci(t){let{provider:e,baseURL:n,apiKey:r}=io(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,c){let u=Yt(a,c,t.model,!1,t.bodyExtras),d=$(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:c?.signal});if(!l.ok)throw await Ie(l,e);let f=await l.json(),p=Math.max(0,($()-d)/1e6);return so(f,p,e)},async*stream(a,c){let u=Yt(a,c,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:c?.signal});if(!d.ok)throw await Ie(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,f;for await(let p of ut(d.body,{signal:c?.signal})){if(!p.data||p.data==="[DONE]")continue;let m;try{m=JSON.parse(p.data)}catch{continue}let g=m.choices;if(g){let h=g[0];if(h?.delta?.content&&(yield{type:"token",delta:h.delta.content}),h?.delta?.reasoning_content&&(yield{type:"thinking",delta:h.delta.reasoning_content}),h?.delta?.tool_calls)for(let y of h.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};h?.finish_reason&&(f=h.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:zn(l)})}yield{type:"finish",reason:f??"stop"}}}}function ui(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=io(t);return{provider:n,model:t.model,async invoke(r,o){let s=Yt(r,o,t.model,!1,t.bodyExtras),i=$(),a=await e.chat.completions.create(s,{signal:o?.signal}),c=Math.max(0,($()-i)/1e6);return so(a,c,n)},async*stream(r,o){let s=Yt(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,c;for await(let u of i){let d=u.choices;if(d){let f=d[0];if(f?.delta?.content&&(yield{type:"token",delta:f.delta.content}),f?.delta?.reasoning_content&&(yield{type:"thinking",delta:f.delta.reasoning_content}),f?.delta?.tool_calls)for(let p of f.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:p.id,name:p.function?.name,argumentsDelta:p.function?.arguments}};f?.finish_reason&&(c=f.finish_reason)}let l=u.usage;l&&(a=l,yield{type:"usage",usage:zn(l)})}yield{type:"finish",reason:c??"stop"}}}}function di(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return In(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Vn(e)}case"dry-run":{let e={model:t.model,...t.extras};return Je(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Bn(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Un(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ge();Y();xe();ue();Y();var Hn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function ao(t){return t.subscribe(()=>{})}var li=64;function $e(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Hn(t,r),a=L(i.toArray(),{name:n,describeKind:"state",equals:(m,g)=>m===g,...o!=null?{versioning:o}:{}});function c(){let m=i.toArray();te(()=>{a.down([[J]]),a.down([[C,m]])})}let u=new Map,d=new Map;function l(m,g){return`${m}:${g===void 0?"END":g}`}function f(m){if(m.size<li)return;let g=m.keys().next();if(g.done)return;let h=m.get(g.value);h!==void 0&&h.dispose(),m.delete(g.value)}function p(m){let g=i.version;try{return m()}finally{i.version!==g&&c()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){p(()=>i.append(m))},appendMany(m){m.length!==0&&p(()=>i.appendMany(m))},clear(){p(()=>i.clear())},trimHead(m){p(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let g=u.get(m);if(g!==void 0)return u.delete(m),u.set(m,g),g.node;f(u);let h=_([a],([b])=>{let T=b;return m===0||T.length===0?[]:T.slice(Math.max(0,T.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=ao(h);return u.set(m,{node:h,dispose:y}),h},slice(m,g){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(g!==void 0&&(!Number.isInteger(g)||g<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${g})`);let h=l(m,g),y=d.get(h);if(y!==void 0)return d.delete(h),d.set(h,y),y.node;f(d);let b=_([a],([k])=>{let v=k;return g===void 0?v.slice(m):v.slice(m,g)},{initial:i.slice(m,g),describeKind:"derived"}),T=ao(b);return d.set(h,{node:b,dispose:T}),b},disposeTail(m){let g=u.get(m);return g===void 0?!1:(g.dispose(),u.delete(m),!0)},disposeSlice(m,g){let h=l(m,g),y=d.get(h);return y===void 0?!1:(y.dispose(),d.delete(h),!0)},disposeAllViews(){for(let m of u.values())m.dispose();u.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of u.values())m.dispose();u.clear();for(let m of d.values())m.dispose();d.clear()}}}ee();function Ee(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Pe(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function co(){return{input:{regular:0},output:{regular:0}}}function pi(t,e){let n=e?.logMax??1e3,r=$e(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=L(null,{name:"adapterStats/lastCall"}),s=_([r.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),i=_([r.entries],([g])=>g.reduce((h,y)=>h+Ee(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=_([r.entries],([g])=>g.reduce((h,y)=>h+Pe(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),c=[X(s),X(i),X(a)],u=g=>{r.append(g),o.emit(g)},d=()=>{r.clear(),o.emit(null)},l=be(t,{invoke(g,h){let y=$(),b=he(),T=t.model??h?.model??"",k=w=>(u(Ye({provider:t.provider,model:t.model??h?.model??w.model??"",tier:h?.tier??w.tier,usage:w.usage??Le(),startNs:y,startWallClockNs:b,method:"invoke"})),w),v=w=>{let x=w;u(Ye({provider:t.provider,model:T,tier:h?.tier,usage:Le(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(w)}}))};return qt(t.invoke(g,h),{onResp:k,onError:v,name:"adapterStats/invokeTap"})},async*stream(g,h){let y=$(),b=he(),T=t.model??h?.model??"",k;try{for await(let v of t.stream(g,h))v.type==="usage"&&(k=v.usage),yield v;u(Ye({provider:t.provider,model:T,tier:h?.tier,usage:k??Le(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(v){let w=v;throw u(Ye({provider:t.provider,model:T,tier:h?.tier,usage:k??Le(),startNs:y,startWallClockNs:b,method:"stream",error:{type:w?.name??"Error",message:w?.message??String(v)}})),v}}});me(l,"observableAdapter",t);let f=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:d,dispose:()=>{if(!f){f=!0;for(let g of c)g();c.length=0}}}}}function fi(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Xt(t="USD"){return{total:0,currency:t}}function Wn(t,e,n){let r=Ee(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,c=(h,y,b)=>{if(!y||b==null)return;let T=fi(b,r),k=y*T/1e6;a+=k,s&&(i[h]=(i[h]??0)+k)},u=t.input,d=e.input;if(d&&(c("input.regular",u.regular,d.regular),c("input.cacheRead",u.cacheRead??0,d.cacheRead),c("input.cacheWrite5m",u.cacheWrite5m??0,d.cacheWrite5m),c("input.cacheWrite1h",u.cacheWrite1h??0,d.cacheWrite1h),c("input.cacheWriteOther",u.cacheWriteOther??0,d.cacheWriteOther),c("input.audio",u.audio??0,d.audio),c("input.image",u.image??0,d.image),c("input.video",u.video??0,d.video),c("input.toolUse",u.toolUse??0,d.toolUse),u.extensions&&d.extensions))for(let[h,y]of Object.entries(u.extensions))c(`input.ext.${h}`,y,d.extensions[h]);let l=t.output,f=e.output;if(f&&(c("output.regular",l.regular,f.regular),c("output.reasoning",l.reasoning??0,f.reasoning),c("output.audio",l.audio??0,f.audio),c("output.predictionAccepted",l.predictionAccepted??0,f.predictionAccepted),c("output.predictionRejected",l.predictionRejected??0,f.predictionRejected),l.extensions&&f.extensions))for(let[h,y]of Object.entries(l.extensions))c(`output.ext.${h}`,y,f.extensions[h]);let p=n?.tier;if(p&&e.tierMultipliers){let h=e.tierMultipliers[p];if(h!=null&&(a*=h,s))for(let y of Object.keys(i))i[y]*=h}let m=t.auxiliary,g=e.auxiliary;if(m&&g)for(let[h,y]of Object.entries(m)){let b=g[h];if(b==null||!y)continue;let T=y*b;a+=T,s&&(i[`auxiliary.${h}`]=T)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Qt(t,e){return`${t}::${e}`}function mi(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Qt(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(Qt(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let c;for(let u of a)if(s.startsWith(u)&&(!c||u.length>c.key.length)){let d=e.get(Qt(o,u));d&&(c={key:u,pricing:d.pricing})}return c?.pricing},remove(o,s){let i=e.delete(Qt(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function gi(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Wn(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Xt(e)}}function hi(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):Xt()}}function yi(t,e,n){return t?.pricing?Wn(e,t.pricing,n):Xt()}ct();ee();function qn(t,e={}){let n=e.breaker??Tt(e),r=be(t,{async invoke(o,s){if(!n.canExecute())throw new Fe;try{let i=await we(I(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Fe;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return me(r,"withBreaker",t),{adapter:r,breaker:n}}ge();ue();Y();ee();var Zt=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Jn=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),uo=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Yn(t,e){let n=$e(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=L(uo(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=_([r],([u])=>{let d=u;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(X(o),e.onExhausted!=null){let u=e.onExhausted,d=!1,l=!0;o.subscribe(f=>{for(let p of f)if(p[0]===C){let m=p[1];if(d&&l&&m===!1){let g=lo(r.cache??Jn,e.caps);g&&u(g)}l=m,d=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Jn,d=lo(u,e.caps);return new Zt(d??"budget",e.caps[d??"calls"]??0,bi(u,d??"calls"))}},i=(u,d)=>{let l=t.provider,f=Ye({provider:l,model:d.model,tier:d.tier,usage:u,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});n.append(f);let p=r.cache??Jn,m=e.pricingFn?p.usd+e.pricingFn(u,{model:d.model,provider:l,tier:d.tier}).total:p.usd;r.emit({calls:p.calls+1,inputTokens:p.inputTokens+Ee(u),outputTokens:p.outputTokens+Pe(u),usd:m})},a=()=>{n.clear(),r.emit(uo())},c=be(t,{invoke(u,d){let l=s();if(l)return Promise.reject(l);let f=$(),p=t.model??d?.model??"",m=h=>(i(h.usage??Le(),{model:t.model??d?.model??h.model??"",tier:d?.tier??h.tier,startNs:f,method:"invoke"}),h),g=h=>{let y=h;i(Le(),{model:p,tier:d?.tier,startNs:f,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(h)}})};return qt(t.invoke(u,d),{onResp:m,onError:g,name:"budgetGate/invokeTap"})},async*stream(u,d){let l=s();if(l)throw l;let f=$(),p;try{for await(let m of t.stream(u,d))m.type==="usage"&&(p=m.usage),yield m;i(p??Le(),{model:t.model??d?.model??"",tier:d?.tier,startNs:f,method:"stream"})}catch(m){let g=m;throw i(p??Le(),{model:t.model??d?.model??"",tier:d?.tier,startNs:f,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(m)}}),m}}});return me(c,"withBudgetGate",t),{adapter:c,budget:{totals:r,isOpen:o,log:n,reset:a}}}function lo(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function bi(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ee();function Ti(t,e){let n=e.mock??Je({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?I(e.enabled):void 0,s;o&&(s=X(o));let i=()=>r!==void 0?r:!!o?.cache,a=be(t,{invoke(u,d){return i()?n.invoke(u,d):t.invoke(u,d)},stream(u,d){return i()?n.stream(u,d):t.stream(u,d)}});return me(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Qn(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=vi(e.headers);if(n!==429&&n!==503&&!Ni(e.message))return;let o={},s=r("retry-after"),i=ki(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let p=po(a);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let c=r("anthropic-ratelimit-tokens-reset");if(c){let p=po(c);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=en(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let d=en(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=en(r,"x-ratelimit-remaining-requests"),f=en(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),f!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-f/d),o.retryAfterMs==null&&e.message){let p=Ri(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:wi(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function vi(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function wi(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function en(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function ki(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function po(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var xi=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Ri(t){let e=xi.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Si=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Ni(t){return!!t&&Si.test(t)}ge();ue();Y();ct();ee();De();function Xn(t){let e=new Error(t);return e.name="AbortError",e}function mo(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?I(t.rpm):L(Number.POSITIVE_INFINITY),o=t.tpm!=null?I(t.tpm):L(Number.POSITIVE_INFINITY),s=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=L({},{name:"adaptiveRateLimiter/lastSignal"}),c=_([r,s],([S,G])=>Math.min(Number(S??1/0),Number(G??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=_([o,i],([S,G])=>Math.min(Number(S??1/0),Number(G??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=dt(Number(r.cache??Number.POSITIVE_INFINITY),e),l=dt(Number(o.cache??Number.POSITIVE_INFINITY),e),f=!1,p=!1,m=c.subscribe(S=>{for(let G of S)if(G[0]===C){let H=Number(G[1]);Number.isFinite(H)&&H>0?(d=dt(H,e),f=!1):H===1/0?(d=dt(1/0,e),f=!1):H<=0&&(f=!0)}}),g=u.subscribe(S=>{for(let G of S)if(G[0]===C){let H=Number(G[1]);Number.isFinite(H)&&H>0?(l=dt(H,e),p=!1):H===1/0?(l=dt(1/0,e),p=!1):H<=0&&(p=!0)}}),h=0,y=new se,b=new se,T;t.adaptation!=null&&(T=I(t.adaptation).subscribe(G=>{for(let H of G)H[0]===C&&k(H[1])}));function k(S){if(a.emit(S),S.rpmCap!=null&&Number.isFinite(S.rpmCap)&&S.rpmCap>=0&&(s.emit(S.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),S.tpmCap!=null&&Number.isFinite(S.tpmCap)&&S.tpmCap>=0&&(i.emit(S.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),S.retryAfterMs!=null&&S.retryAfterMs>0){let G=$()+S.retryAfterMs*1e6;G>h&&(h=G)}}let v=L(0,{name:"adaptiveRateLimiter/pending"}),w=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=S=>{v.emit((v.cache??0)+S)},N=()=>{w.emit(d.available()),x.emit(l.available())};async function V(S={}){let G=S.requestCost??1,H=S.tokenCost??0,A=S.signal;R(1);try{for(;;){if(A?.aborted)throw Xn("AdaptiveRateLimiter.acquire aborted");let E=$();if(h>E){let ke=Math.ceil((h-E)/1e6);await tn(ke,A);continue}if(G>0&&f||H>0&&p){await tn(250,A);continue}let B=d,U=l;if(!B.tryConsume(G)){await tn(fo(B,G),A);continue}if(!(H>0?U.tryConsume(H):!0)){B.putBack(G),await tn(fo(U,H),A);continue}N();return}}finally{R(-1)}}function M(S){S>0?l.tryConsume(S):S<0&&l.putBack(-S),N()}function D(){m(),g(),T?.(),y.cancel(),b.cancel()}return{effectiveRpm:c,effectiveTpm:u,lastSignal:a,pending:v,rpmAvailable:w,tpmAvailable:x,acquire:V,recordUsage:M,recordSignal:k,dispose:D}}function dt(t,e){if(!Number.isFinite(t)||t===1/0)return vt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return vt(n,r)}function fo(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function tn(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xn("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Xn("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ee();function Zn(t,e={}){let n=e.limiter??mo({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=Qn(i);a&&n.recordSignal(a)},s=be(t,{async invoke(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let u=await we(I(t.invoke(i,a))),d=u.usage??co(),f=Ee(d)+Pe(d)-c;return f>0&&n.recordUsage(f),u}catch(u){throw o(u),u}},async*stream(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let u=0;for await(let l of t.stream(i,a))l.type==="usage"&&(u=Ee(l.usage)+Pe(l.usage)),yield l;let d=u-c;d>0&&n.recordUsage(d)}catch(u){throw o(u),u}}});return me(s,"withRateLimiter",t),{adapter:s,limiter:n}}ct();ee();var Rt=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function er(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Tt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],c=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let f=await we(I(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...f,metadata:{...f.metadata??{},tier:l.name}}}catch(f){c.set(l.name,f),l.breaker?.recordFailure(f);let p=n[d+1];p&&e.onFallback?.(l.name,p.name,f)}}let u={skipped:a,failed:c};throw e.onExhausted?.(u),new Rt(u)},async*stream(s,i){let a=[],c=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let f=!1;try{for await(let p of l.adapter.stream(s,i))f=!0,yield p;l.breaker?.recordSuccess();return}catch(p){if(c.set(l.name,p),l.breaker?.recordFailure(p),f||!r)throw p;let m=n[d+1];m&&e.onFallback?.(l.name,m.name,p)}}let u={skipped:a,failed:c};throw e.onExhausted?.(u),new Rt(u)}};return me(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function _i(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ee();De();function nn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function go(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(nn()):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(nn())},e.addEventListener("abort",s,{once:!0}))})}function tr(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Mi,c=e.retryStreaming??!0,u=(l,f)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,f*3));return r+Math.random()*(h-r)}let p=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,p);if(!i)return m;let g=m*(.5+Math.random());return Math.min(o,g)},d=be(t,{async invoke(l,f){if(f?.signal?.aborted)throw nn();let p,m=r;for(let g=1;g<=n;g++)try{return await we(I(t.invoke(l,f)))}catch(h){if(p=h,g>=n||!a(h,g))throw h;let y=u(g,m);m=y,await go(y,f?.signal)}throw p},async*stream(l,f){if(f?.signal?.aborted)throw nn();if(!c){for await(let g of t.stream(l,f))yield g;return}let p,m=r;for(let g=1;g<=n;g++){let h=!1;try{for await(let y of t.stream(l,f))h=!0,yield y;return}catch(y){if(p=y,h||g>=n||!a(y,g))throw y;let b=u(g,m);m=b,await go(b,f?.signal)}}throw p}});return me(d,"withRetry",t),d}function Mi(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}ee();De();var lt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function nr(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,c,u=new se;return s&&(s.aborted?i.abort(s.reason):(c=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",c,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new lt(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&c&&s.removeEventListener("abort",c)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof lt)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new lt(e);throw u.cause=s,u}throw s},o=be(t,{async invoke(s,i){let{signal:a,cancel:c,timedOut:u}=n(i?.signal);try{return await we(I(t.invoke(s,{...i,signal:a})))}catch(d){return r(d,u())}finally{c()}},async*stream(s,i){let{signal:a,cancel:c,timedOut:u}=n(i?.signal);try{for await(let d of t.stream(s,{...i,signal:a}))yield d}catch(d){r(d,u())}finally{c()}}});return me(o,"withTimeout",t),o}function Ei(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Zn(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Yn(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=qn(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=nr(r,e.timeoutMs)),e.retry&&(r=tr(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=er([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=xt(r,e.cache)),n.adapter=r,n}Y();ee();function Oi(t,e,n){let r=I(e);return ye(r,s=>{if(!s||s.length===0)return L(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}_e();ee();ue();ee();De();ue();ee();function ho(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[J],[C,n+1]]),!0)}function je(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function W(t,e){return je("ai",t,e)}function Ai(t){return t!=null&&typeof t.then=="function"}function Ci(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Li(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Di=3e4;function yo(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Di;return new Promise((r,o)=>{let s=new se,i=t.subscribe(a=>{for(let c of a){if(c[0]===C){s.cancel(),i(),r(c[1]);return}if(c[0]===O){s.cancel(),i(),o(c[1]);return}if(c[0]===F){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function Xe(t){return Ai(t)?Xe(await t):Ci(t)?yo(t):Li(t)?yo(I(t)):t}function pt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Ii(t,e){let n=I(t),r=e?.refreshTrigger!=null?I(e.refreshTrigger):null;return r==null?ne([n],(o,s,i)=>{if(i.store.emitted===!0)return;let c=o[0],u=c!=null&&c.length>0?c.at(-1):i.prevData[0];if(u!==void 0)return i.store.emitted=!0,s.emit(u),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context")}):ne([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let u=o[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context")})}Y();function Pi(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Gi(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,c=_(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:W("prompt_node"),initial:[]});return ye(c,d=>{if(!d||d.length===0)return L(null);let l=i?JSON.stringify(d.map(p=>[p.role,p.content])):"";if(a?.has(l))return L(a.get(l));async function f(p){try{let m=await new Promise((y,b)=>{let T=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});T&&typeof T.then=="function"?T.then(y,b):T&&typeof T.subscribe=="function"?y(T.cache):y(T)}),g=Pi(m),h;return o==="json"?h=JSON.parse(pt(g)):h=g,a?.set(l,h),h}catch(m){if(p>0)return f(p-1);throw m}}return f(s)})}xe();ge();Y();ee();Ot();yt();ue();yt();_e();function rn(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function Fi(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function $i(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function rr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof de&&(s=Fi(t),i=t._deps.map(u=>u.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let c=t instanceof de?t._guard:void 0;if(o){let u={...$i(t)};if(c!=null&&u.access===void 0&&(u.access=Rn(c)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in u&&(d[l]=u[l]);a.meta=d}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&c!=null&&(a.guard=Rn(c)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Y();var le={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},ji=Symbol.for("sizeof");function bo(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Bi(s,e,n,r)}return o}function Bi(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return le.number;case"boolean":return le.boolean;case"string":return le.string+t.length*2;case"bigint":return le.bigint+Vi(t);case"symbol":return le.symbol;case"function":return e.has(t)?0:(e.add(t),le.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[ji];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return le.date;if(s instanceof RegExp)return le.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return le.error+u+d}if(typeof URL<"u"&&s instanceof URL)return le.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return le.promise;if(s instanceof WeakMap)return le.weakmap;if(s instanceof WeakSet)return le.weakset;if(s instanceof Map){let u=le.map;for(let[d,l]of s)u+=le.mapEntry,r.push(d),r.push(l);return u}if(s instanceof Set){let u=le.set;for(let d of s)u+=le.setEntry,r.push(d);return u}if(Array.isArray(s)){let u=le.array+s.length*8;for(let d of s)r.push(d);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=le.object,c=Object.keys(s);for(let u of c){a+=le.string+u.length*2;try{r.push(s[u])}catch{}}return a}function Vi(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function To(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return on(e,n,"no-such-from");if(!s)return on(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Ki(t,e,r);if(u!=null)return u}let c=sn(e,t.nodes[e],0,r);return an(e,n,[c])}if(i===0)return on(e,n,"no-path");let a=vo(t,e,n,i);return a.found?an(e,n,wo(t,a.pathOrder,r)):on(e,n,a.truncated?"max-depth-exceeded":"no-path")}function vo(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,c=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let g=t.nodes[l.path];g?.deps&&g.deps.length>0&&(c=!0);continue}let f=t.nodes[l.path];if(f==null)continue;let p=f.deps??[],m=new Map;for(let g=0;g<p.length;g++){let h=p[g];if(!h)continue;let y=m.get(h);y==null&&(y=[],m.set(h,y)),y.push(g)}for(let[g,h]of m)i.has(g)||(i.add(g),o.set(g,{from:l.path,depIndices:h}),s.push({path:g,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:c};let u=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),d=l.from}return{found:!0,pathOrder:u,truncated:!1}}function Ki(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=sn(e,r,0,n);a.dep_index=s[0];let c=sn(e,r,1,n);return an(e,e,[a,c])}let i=null;for(let a=0;a<o.length;a++){let c=o[a];if(!c||c===e)continue;let u=vo(t,c,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:an(e,e,wo(t,i.pathOrder,n))}function wo(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=sn(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function sn(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function an(t,e,n){return ko(t,e,!0,"ok",n)}function on(t,e,n){return ko(t,e,!1,n,[])}function ko(t,e,n,r,o){let s=Ui(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Ui(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let c=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(c),"value"in i&&s.push(` value: ${zi(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
7
+ `)}function zi(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Ot();xe();ge();yt();ue();_e();Y();ee();De();vn();function or(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function cn(t){let e=0;for(let n of t)e+=or(n.codePointAt(0));return e}function xo(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=or(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=or(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Hi={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},Wi={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function _o(t,e){let n=e.charset==="ascii"?Wi:Hi,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Ji(s,i,n,a);for(let a of t.boxes)qi(s,i,n,a,e.labelOf(a.id));return s.map(a=>Zi(a.join(""))).join(`
8
+ `)}function qi(t,e,n,r,o){let{x:s,y:i,w:a,h:c}=r;if(a<2||c<2){c>0&&Ro(t,e,s,i,a,o);return}Be(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Be(t,e,d,i,n.boxH);Be(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+c-1;d+=1){Be(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Mo(t,e,l,d," ","empty");Be(t,e,s+a-1,d,n.boxV)}Be(t,e,s,i+c-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Be(t,e,d,i+c-1,n.boxH);Be(t,e,s+a-1,i+c-1,n.boxBR);let u=i+Math.floor(c/2);Ro(t,e,s+1,u,a-2,o)}function Be(t,e,n,r,o){Mo(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Mo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function Ro(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let c of s){let u=cn(c);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=c,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Ji(t,e,n,r){let o=r.points;if(o.length<2)return;for(let c=0;c+1<o.length;c+=1)Yi(t,e,n,o[c],o[c+1]);for(let c=1;c+1<o.length;c+=1){let u=o[c-1],d=o[c],l=o[c+1],f=Qi(u,d,l,n);f&&No(t,e,d.x,d.y,f,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Xi(i,s,n);a&&No(t,e,s.x,s.y,a,"arrow")}function Yi(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let c=i;c<=a;c+=1)So(t,e,c,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let c=i;c<=a;c+=1)So(t,e,s,c,n,"v")}}}function So(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function No(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Qi(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let c=t.x<e.x,u=n.y>e.y;return c&&u?r.cornerTR:c&&!u?r.cornerBR:!c&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Xi(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Zi(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Ao(t){let e=ea(t);ta(e),na(e),ra(e),oa(e,t);let n=aa(e,t),{width:r,height:o}=ua(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function ea(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function ta(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let c=(e.get(a.id)??0)-1;e.set(a.id,c),c<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function na(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),c=a.layer-i.layer;if(c<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(c===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let u=i;for(let l=1;l<c;l+=1){let f=`__virt_${o++}__`,p={id:f,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,p),n[p.layer].push(p);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:f,hopIndex:l-1,chainLen:c};u.out.push(m),p.in.push(m),r.push(m),u=p}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:c-1,chainLen:c};u.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function ra(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Eo(t,t.layers[r],"in"),un(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Eo(t,t.layers[r],"out"),un(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Oo(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],un(s),Oo(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],un(s))}}if(!r)break}}function Eo(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let c of s){let u=t.nodes.get(n==="in"?c.fromId:c.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function un(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Oo(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let c of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?c.fromId:c.toId)?.order??0;(e.order<n.order&&u>d||e.order>n.order&&u<d)&&(i+=1)}return i}function oa(t,e){e.direction==="LR"?sa(t,e):ia(t,e)}function sa(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}Co(t,e,"y")}function ia(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}Co(t,e,"x")}function Co(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let c=new Map;for(let d of a){let l=s===0?d.in:d.out;if(l.length===0)continue;let f=[];for(let m of l){let g=t.nodes.get(s===0?m.fromId:m.toId);if(!g)continue;let h=n==="y"?g.y:g.x;f.push(h+Math.floor(r(g)/2))}if(f.length===0)continue;f.sort((m,g)=>m-g);let p=f[Math.floor(f.length/2)];c.set(d.id,p-Math.floor(r(d)/2))}let u=0;for(let d of a){let l=c.get(d.id),f=n==="y"?d.y:d.x,m=Math.max(l??f,u);n==="y"?d.y=m:d.x=m,u=m+r(d)+o}}}}function aa(t,e){let n=new Map;for(let u of t.hops){let d=n.get(u.chainId);d?d.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((d,l)=>d.hopIndex-l.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let d=t.layers[u],l=t.layers[u+1],f=0;for(let R of d)f=Math.max(f,o(R)+s(R));let p=Number.POSITIVE_INFINITY;for(let R of l)p=Math.min(p,o(R));let m=Number.isFinite(p)?p-1:f,g=Math.max(1,m-f+1),h=[];for(let R of d)for(let N of R.out)h.push(N);h.sort((R,N)=>{let V=i(t.nodes.get(R.fromId)),M=i(t.nodes.get(N.fromId));if(V!==M)return V-M;let D=i(t.nodes.get(R.toId)),S=i(t.nodes.get(N.toId));return D-S});let y=[],b=new Map;for(let R of h){let N=i(t.nodes.get(R.fromId)),V=i(t.nodes.get(R.toId)),M=Math.min(N,V),D=Math.max(N,V),S=-1;for(let G=0;G<y.length;G+=1){let H=y[G],A=!0;for(let E of H)if(E.lo<=D&&M<=E.hi){A=!1;break}if(A){H.push({lo:M,hi:D}),S=G;break}}S<0&&(y.push([{lo:M,hi:D}]),S=y.length-1),b.set(R,S)}let T=y.length,k=g>=Math.max(3,T+2),v=k?f+1:f,w=k?m-1:m,x=Math.max(1,w-v+1);for(let R of h){let N=b.get(R),V;if(T<=1)V=v+Math.floor(x/2);else{let M=(x-1)/(T-1);V=v+Math.floor(N*M)}a.set(R,Math.max(f,Math.min(m,V)))}}let c=[];for(let[,u]of n){let d=[];for(let f=0;f<u.length;f+=1){let p=u[f],m=t.nodes.get(p.fromId),g=t.nodes.get(p.toId),h=a.get(p),y=m.isVirtual?o(m):o(m)+s(m),b=g.isVirtual?o(g):o(g)-1,T=i(m),k=i(g);f===0&&dn(d,r,y,T),T!==k&&(dn(d,r,h,T),dn(d,r,h,k)),dn(d,r,b,k)}let l=u[0];c.push({from:l.chainFrom,to:l.chainTo,points:ca(d)})}return c}function dn(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ca(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function ua(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var da=24,la=4,pa=1,fa=3;function Lo(t,e){let n=ma(e.direction),r=Math.max(3,e.maxLabelWidth??da),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),c=new Map,u=new Map;for(let p of s){let m=xo(p,r);c.set(p,m),u.set(p,cn(m)+4)}let d=Ao({nodes:s,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>fa,layerGap:la,nodeGap:pa,direction:n}),l=_o(d,{charset:o,labelOf:p=>c.get(p)??p}),f=e.logger;return f&&f(l),l}function ma(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}_e();function Do(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[f,p]of o)i.set(f,p);let a=[];for(let[f,p]of Object.entries(r.nodes)){let m=i.get(f),g=m instanceof de?m:null,h=g?bo(g.cache):0,y=g?g._sinkCount:0,b=p.deps?.length??0,T=p.type==="effect"&&y===0,k=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:f,type:p.type,status:p.status??"unknown",valueSizeBytes:h,subscriberCount:y,depCount:b,isOrphanEffect:T,orphanKind:k})}let c=a.reduce((f,p)=>f+p.valueSizeBytes,0),u=(f,p)=>[...a].sort(p??((m,g)=>g[f]-m[f])).slice(0,n),d=a.filter(f=>f.orphanKind!=null),l=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:c,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:d,orphanEffects:l}}var re="::",Te="__meta__",Ze=1;function Io(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function ga(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
9
+ `)}function Po(t){if(t.version!==Ze)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${Ze})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function ha(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,c=s.constructor;if(a!==c)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let f=s;if(o.length!==f.length)return!1;for(let p=0;p<o.length;p++)if(!r(o[p],f[p]))return!1;return!0}if(o instanceof Map){let f=s;if(o.size!==f.size)return!1;for(let[p,m]of o)if(!f.has(p)||!r(m,f.get(p)))return!1;return!0}if(o instanceof Set){let f=s;if(o.size!==f.size)return!1;for(let p of o){let m=!1;for(let g of f)if(r(p,g)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let f=o,p=s;if(f.length!==p.length)return!1;for(let m=0;m<f.length;m++)if(f[m]!==p[m])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let l=new Set(d);for(let f of u)if(!l.has(f)||!r(o[f],s[f]))return!1;return!0};return r(t,e)}function ir(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ir);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ir(e[o]);return r}function ya(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ba(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ta(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Fo(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function $o(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function va(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(ir(i),null,e.indent??2);return e.logger?.(a),a}function wa(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${pn(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
10
+ `);return e.logger?.(s),s}function jo(t,e){let n=$o(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${ya(i)}"]`)}for(let[i,a]of Fo(t)){let c=o.get(i),u=o.get(a);!c||!u||s.push(` ${c} --> ${u}`)}return s.join(`
11
+ `)}function ka(t,e){let n=jo(t,e);return Bo(n)}function Bo(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function xa(t,e){let n=$o(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Ta(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${ba(i)}"`)}for(let[i,a]of Fo(t)){let c=o.get(i),u=o.get(a);!c||!u||s.push(`${c} -> ${u}`)}return s.join(`
12
+ `)}function Ra(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ln(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Ra(r)}return e+="$",new RegExp(e)}var Sa={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Na={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function pn(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function _a(t){return t==="none"?Na:t==="ansi"||t==null?Sa:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Go(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Ma(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function sr(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(re))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${re}' (path separator)`);if(t===Te)throw new Error(`Graph "${e}": ${n} name "${Te}" is reserved for meta companion paths`);Ma(t,e,n)}function Ea(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(re);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Oa(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Vo(t){for(let e of t._mounts.values())Vo(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}var ce=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(re))throw new Error(`Graph name must not contain '${re}' (got "${e}")`);if(e===Te)throw new Error(`Graph name "${Te}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??st,this._traceRing=new kt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=ie(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(sr(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:$()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof de&&n._applyVersioning(e)}remove(e){sr(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,c]of i)a.includes(`${re}${Te}${re}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${re}`)),this._mounts.delete(e),n._parent=void 0,Vo(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[fe]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=ln(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(re))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[C,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Re]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[O,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[F]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[c,u]of this._nodes)r.set(u,c);let a=[];for(let[c,u]of this._nodes)if(u instanceof de)for(let d of u._deps){let l=r.get(d.node);l!=null&&a.push([l,c])}return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:c[1]<u[1]?-1:c[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,c]of o)s.set(c,a);let i=[];for(let[a,c]of o)if(c instanceof de)for(let u of c._deps){let d=s.get(u.node);d!=null&&i.push([d,a])}return i.sort((a,c)=>a[0]<c[0]?-1:a[0]>c[0]?1:a[1]<c[1]?-1:a[1]>c[1]?1:0),i}mount(e,n){if(sr(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=Ea(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===Te)return this._resolveMetaChainFromNode(s,o,n.join(re));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(re)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(re))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Te)throw new Error(`Graph "${this.name}": expected ${Te} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Te} in "${r}"`);let a=i[s+1],c=o.meta[a];if(!c)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=c,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let c of this._mounts.values())c._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Oa(e,this.config);for(let c of[...this._nodes.keys()].sort()){let u=this._nodes.get(c);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(d){if(d instanceof Ne)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(c){if(c instanceof Ne)throw c;s.push(c)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=rn(e?.detail,e?.fields),s=e?.format==="spec",i=s?rn("minimal"):o,a=[];this._collectObserveTargets("",a);let c=new Map;for(let[w,x]of a)c.set(x,w);let u=[];{let w=a.map(([,N])=>N),x=new Set(c.values()),R=0;for(;w.length>0;){let N=w.shift();if(N instanceof de)for(let V of N._deps){let M=V.node;if(c.has(M))continue;let D=M.name??"",S=D;if(!S||x.has(S))if(D){let G=2;for(;x.has(`${D}#${G}`);)G++;S=`${D}#${G}`}else for(S=`__internal__/${R++}`;x.has(S);)S=`__internal__/${R++}`;c.set(M,S),x.add(S),u.push([S,M]),w.push(M)}}}let d=[...a,...u],l={};for(let[w,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=rr(x,i),N=x instanceof de?x._deps.map(S=>c.get(S.node)??S.node.name??""):[],{name:V,...M}=R,D={...M,deps:N};if(!s){let S=this._annotations.get(w);S!=null&&(D.annotation=S)}if(r!=null)if(typeof r=="function"){let S=r;if(!(S.length>=2?S(w,D):S(D)))continue}else{let S=!0;for(let[G,H]of Object.entries(r)){let A=G==="deps_includes"?"depsIncludes":G==="meta_has"?"metaHas":G;if(A==="depsIncludes"){if(!D.deps.includes(String(H))){S=!1;break}continue}if(A==="metaHas"){if(!Object.hasOwn(D.meta??{},String(H))){S=!1;break}continue}if(D[A]!==H){S=!1;break}}if(!S)continue}l[w]=D}let f=new Set(Object.keys(l)),p=[];for(let[w,x]of d)if(x instanceof de)for(let R of x._deps){let N=c.get(R.node);N!=null&&p.push([N,w])}p.sort((w,x)=>w[0]<x[0]?-1:w[0]>x[0]?1:w[1]<x[1]?-1:w[1]>x[1]?1:0);let m=p.map(([w,x])=>({from:w,to:x}));(n!=null||r!=null)&&(m=m.filter(w=>f.has(w.from)&&f.has(w.to)));let g=this._collectSubgraphs(""),h=n!=null||r!=null?g.filter(w=>{let x=`${w}${re}`;return[...f].some(R=>R===w||R.startsWith(x))}):g,y=this,b=e,T={name:this.name,nodes:l,edges:m,subgraphs:h,expand(w){let x={...b,format:void 0};return Array.isArray(w)?(x.fields=w,x.detail=void 0):(x.detail=w,x.fields=void 0),y.describe(x)}},k=e??{},v=k.format;return v==="json"?va(T,k):v==="pretty"?wa(T,k):v==="mermaid"?jo(T,k):v==="mermaid-url"?ka(T,k):v==="d2"?xa(T,k):v==="ascii"?Lo(T,k):T}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${re}`))}return n}resourceProfile(e){return Do(this,e)}reachable(e,n,r={}){return r.withDetail===!0?ar(this.describe(),e,n,{...r,withDetail:!0}):ar(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,c]of Object.entries(o.nodes))c.lastMutation!=null&&i.set(a,c.lastMutation);return To(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=L(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,u=()=>{a||c||(a=!0,ht(()=>{a=!1,!c&&(o+=1,s.emit(o))}))},d=i.onEvent(h=>{let y=h.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),l=[],f=new WeakSet,p=h=>{if(f.has(h)||c)return;f.add(h);let y=h.topology.subscribe(b=>{for(let T of b){if(T[0]!==C)continue;let k=T[1];if(u(),k.kind==="added"&&k.nodeKind==="mount"){let v=h._mounts.get(k.name);v!=null&&p(v)}}});l.push(y);for(let b of h._mounts.keys()){let T=h._mounts.get(b);T!=null&&p(T)}};p(this);let m;try{m=_([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(h,y)=>h===y})}catch(h){d();for(let y of l)y();throw i.dispose(),h}let g=X(m);return{node:m,dispose(){c=!0,d();for(let h of l)h();l.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let o=0,s=L(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,u=i.onEvent(p=>{let m=p.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||c||(a=!0,ht(()=>{a=!1,!c&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=_([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,m)=>p.found===m.found&&p.reason===m.reason&&p.steps.length===m.steps.length&&Aa(p.steps,m.steps)})}catch(p){throw u(),i.dispose(),p}let f=X(l);return{node:l,dispose(){c=!0,u(),i.dispose(),f()}}}_pathsMatching(e){let n=ln(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${re}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${re}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${re}${Te}${re}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Go(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new Ne({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(f){return l.subscribe(f)},up(f){try{l.up?.(f)}catch(p){if(p instanceof Ne)return;throw p}}}}let c=[];this._collectObserveTargets("",c),c.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=a==null?c:c.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let l=u.map(([f,p])=>p.subscribe(m=>{d(f,m)}));return()=>{for(let f of l)f()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(f){if(f instanceof Ne)return;throw f}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=i.actor,u=c==null?a:a.filter(([,d])=>d.allowsObserve(c));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",c=this.config.inspectorEnabled,u=(s||i)&&c,d=n.maxEvents,l=d!=null&&d>0?new kt(d):null,f=[],p=new Set,m={},g=new Set,h=0,y=0,b=0,T=0,k=0,v=0,w=!1,x=!1,R=0,N=new Map,V=new Map,M=new Map,D=P=>{l?l.push(P):f.push(P);for(let K of p)K(P)},S=()=>o?{timestamp_ns:$(),in_batch:At(),batch_id:R}:{},G=(P,K)=>{if(!(!u||!(P instanceof de)))return P._setInspectorHook(oe=>{if(oe.kind==="dep_message")N.set(P,oe.depIndex);else if(oe.kind==="run"){let pe=oe.batchData.map((j,ae)=>j!=null&&j.length>0?j.at(-1):oe.prevData[ae]);V.set(P,pe);let q=oe.batchData.map(j=>j!=null?[...j]:void 0);M.set(P,q),i&&D({type:"derived",path:K,dep_values:pe,dep_batches:q,...S()})}})},H=P=>{let K=N.get(P),oe=V.get(P);if(!s||oe==null)return{};let q=(K!=null&&K>=0&&P instanceof de?P._deps[K]:void 0)?.node,j=q?.v,ae=M.get(P);return{trigger_dep_index:K,trigger_dep_name:q?.name,...j!=null?{trigger_version:{id:j.id,version:j.version}}:{},dep_values:[...oe],...ae!=null?{dep_batches:ae}:{}}},A=[],E=[];for(let[P,K]of e){let oe=G(K,P);oe&&A.push(oe),E.push(K.subscribe(pe=>{R++;for(let q of pe){let j=q[0],ae=S();if(j===C){m[P]=q[1];let Ae=K instanceof de?K.lastMutation?.actor??nt:nt;D({type:"data",path:P,data:q[1],actor:Ae,...ae,...H(K)})}else if(a)j===J?h++:j===z?y++:j===Re?b++:j===Se?T++:j===Ce?k++:j===fe?v++:j===F&&!g.has(P)?w=!0:j===O&&(x=!0,g.add(P));else if(j===J)h++,D({type:"dirty",path:P,...ae});else if(j===z)y++,D({type:"resolved",path:P,...ae,...H(K)});else if(j===Re)b++,D({type:"invalidate",path:P,...ae});else if(j===Se)T++,D({type:"pause",path:P,lockId:q[1],...ae});else if(j===Ce)k++,D({type:"resume",path:P,lockId:q[1],...ae});else if(j===F)g.has(P)||(w=!0),D({type:"complete",path:P,...ae});else if(j===O){x=!0,g.add(P);let Ae=K instanceof de?K.lastMutation?.actor??nt:nt;D({type:"error",path:P,data:q[1],actor:Ae,...ae})}else j===fe&&(v++,D({type:"teardown",path:P,...ae}))}}))}let B=!1,U=()=>{if(!B){B=!0;for(let P of E)P();for(let P of A)P();for(let P of Q)P({value:void 0,done:!0});Q.length=0}},Z=[],Q=[];p.add(P=>{let K=Q.shift();K?K({value:P,done:!1}):Z.push(P)});let ke={get values(){return m},get dirtyCount(){return h},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return T},get resumeCount(){return k},get teardownCount(){return v},get events(){return l?l.toArray():[...f]},get anyCompletedCleanly(){return w},get anyErrored(){return x},get completedWithoutErrors(){return w&&!x},onEvent(P){return p.add(P),()=>p.delete(P)},dispose:U,expand(P){U();let K={...n};return typeof P=="string"?K.detail=P:Object.assign(K,P),r(Go(K))},[Symbol.asyncIterator](){return{next(){return Z.length>0?Promise.resolve({value:Z.shift(),done:!1}):B?Promise.resolve({value:void 0,done:!0}):new Promise(P=>Q.push(P))},return(){return U(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ke,n),ke}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),c=_a(n.theme),u=r==="stage-log"?$():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,g)=>m.length>g?`${m.slice(0,g-1)}\u2026`:m,f=m=>m.type==="data"||m.type==="error"?l(pn(m.data),120):"",p=m=>{if(r==="stage-log"){let x=($()-u)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let N=f(m);return`[${x.toFixed(3)}s] ${R} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=f(m);return`[${x.toFixed(3)}s] ${R} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let g=c[m.type]??"",h=m.path?`${c.path}${m.path}${c.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",T=y?` ${pn(m.data)}`:b?` ${pn(m.lockId)}`:"",k=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,v=k?.trigger_dep_name!=null?` <- ${k.trigger_dep_name}`:k?.trigger_dep_index!=null?` <- #${k.trigger_dep_index}`:"",w=m.in_batch?" [batch]":"";return`${h}${g}${m.type.toUpperCase()}${c.reset}${T}${v}${w}`};e.onEvent(m=>{a(m.type)&&o(p(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Io(this._disposers,this.name),this.signal([[fe]],{internal:!0}),Io(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:c,guard:u,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Tr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??st,{codec:o,codecVersion:s,payload:i}=vr(e,r);return o.decode(i,s)}restore(e,n){if(Po(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>ln(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let c=this.tryResolve(s)?.v;if(c!=null&&c.id===i.v.id&&c.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Po(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let p of[...e.subgraphs].sort((m,g)=>{let h=m.split(re).length,y=g.split(re).length;return h!==y?h-y:m<g?-1:m>g?1:0})){let m=p.split(re),g=s;for(let h of m)g._mounts.has(h)||g.mount(h,new t(h)),g=g._mounts.get(h)}let i=o?Object.entries(o).map(([p,m])=>({re:ln(p),factory:m})):[],a=p=>{for(let m of i)if(m.re.test(p))return m.factory},c=p=>{let m=p.split(re),g=m.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${p}"`);let h=s;for(let y of m){let b=h._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${p}"`);h=b}return[h,g]},u=Object.entries(e.nodes).filter(([p])=>!p.includes(`${re}${Te}${re}`)).sort((p,m)=>p[0]<m[0]?-1:p[0]>m[0]?1:0),d=new Map(u),l=new Map,f=!0;for(;d.size>0&&f;){f=!1;for(let[p,m]of[...d.entries()]){let g=m?.deps??[];if(!g.every(v=>l.has(v)))continue;let[h,y]=c(p),b={...m?.meta??{}},T=a(p),k;if(m?.type==="state")k=L(m.value,{meta:b});else{if(T==null)continue;k=T(y,{path:p,type:m.type,value:m.value,meta:b,deps:g,resolvedDeps:g.map(v=>l.get(v))})}h.add(k,{name:y}),l.set(p,k),d.delete(p),f=!0}}if(d.size>0){let p=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,d)=>{if(u.disposed)return;let l=ga(d.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let f=u.seq+1,p=he(),h=u.lastSnapshot==null||f%u.compactEvery===0?{mode:"full",snapshot:d,seq:f,timestamp_ns:p,format_version:Ze}:{mode:"diff",diff:Ko(u.lastSnapshot,d),seq:f,timestamp_ns:p,format_version:Ze};if(u.tier.filter&&!u.tier.filter(this.name,h))return;let y;try{y=u.tier.save(this.name,h)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let k=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=f,u.lastSnapshot=d,u.lastFingerprint=l)},v=>{n.onError?.(v,u.tier)});u.savePending=k.finally(()=>{u.savePending===k&&(u.savePending=void 0)})}else u.seq=f,u.lastSnapshot=d,u.lastFingerprint=l},s=(u,d)=>{try{o(u,d)}catch(l){n.onError?.(l,u.tier)}},i=(u,d)=>{if(!d.some(m=>{let g=this.config.messageTier(m[0]);return g>=3&&g<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let g=rr(m,rn("standard"));if(!n.filter(u,g))return}let f,p=()=>(f==null&&(f=this.snapshot()),f);for(let m of r)m.disposed||(m.debounceMs===0?s(m,p()):(m.timer==null&&(m.timer=new se),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let f=this.tryResolve(l);return f==null?()=>{}:f.subscribe(p=>i(l,p))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((u,d)=>i(u,d));let c=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(c)};return this._storageDisposers.add(c),{dispose:c}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===Ze&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(c){r?.onError?.(c,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Ze&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(c){r?.onError?.(c,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:$(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],c=[];for(let b of r){if(!o.has(b))continue;let T=e.nodes[b],k=n.nodes[b],v=T.v,w=k.v;v!=null&&w!=null&&v.id===w.id&&v.version!==w.version&&c.push({path:b,id:v.id,from:v.version,to:w.version});let x=v!=null&&w!=null&&v.id===w.id&&v.version===w.version;for(let R of["type","status","sentinel"]){let N=T[R],V=k[R];N!==V&&a.push({path:b,field:R,from:N,to:V})}if(!x)for(let R of["value","meta"]){let N=T[R],V=k[R];ha(N,V)||a.push({path:b,field:R,from:N,to:V})}}let u=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),f=n.edges.filter(b=>!d.has(u(b))),p=e.edges.filter(b=>!l.has(u(b))),m=new Set(e.subgraphs),g=new Set(n.subgraphs),h=[...g].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!g.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:c,edgesAdded:f,edgesRemoved:p,subgraphsAdded:h,subgraphsRemoved:y}}};function Ko(t,e){let n=ce.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function ar(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,c=new Map,u=new Map,d=new Set;for(let[T,k]of Object.entries(t.nodes)){if(!T)continue;d.add(T);let v=k.deps??[];i.set(T,v);for(let w of v)w&&(d.add(w),a.has(w)||a.set(w,new Set),a.get(w).add(T))}for(let T of t.edges){if(T==null||typeof T!="object")continue;let k=typeof T.from=="string"?T.from:"",v=typeof T.to=="string"?T.to:"";!k||!v||(d.add(k),d.add(v),u.has(k)||u.set(k,new Set),u.get(k).add(v),c.has(v)||c.set(v,new Set),c.get(v).add(k))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,f=T=>{if(l){let x=i.get(T)??[],R=c.get(T),N=a.get(T),V=u.get(T),M=[...x];return R&&M.push(...R),N&&M.push(...N),V&&M.push(...V),M}if(n==="upstream"){let x=i.get(T)??[],R=c.get(T);return R?[...x,...R]:x}let k=a.get(T),v=u.get(T),w=k?[...k]:[];return v&&w.push(...v),w},p=new Set([e]),m=new Map,g=[{path:e,depth:0}],h=0,y=!1;for(;h<g.length;){let T=g[h++];if(s!=null&&T.depth>=s){f(T.path).length>0&&(y=!0);continue}for(let k of f(T.path))!k||p.has(k)||(p.add(k),m.set(k,T.depth+1),g.push({path:k,depth:T.depth+1}))}let b=[...m.keys()].sort((T,k)=>T<k?-1:T>k?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Aa(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}function Uo(t,e){return je("messaging",t,e)}var cr=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=$e([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=_([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Uo("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(X(this.latest)),this.hasLatest=_([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Uo("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(X(this.hasLatest)),this.addDisposer(()=>{this.events.down([[F]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}};function ur(t,e){return new cr(t,e)}xe();ue();_e();Y();function Ca(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=La(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function La(t,e){let n=t.describe(),r=`::${Te}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Da(t,e,n,r){t.add(n,{name:e})}function Ia(t,e){return je("orchestration",t,e)}function zo(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=Ca(t,n),a=L([],{name:"pending",equals:()=>!1}),c=L(s,{name:"isOpen"}),u=_([a],([v])=>v.length,{name:"count"}),d=[],l=!1,f=s,p=c.subscribe(v=>{for(let w of v)w[0]===C&&(f=w[1])});function m(){a.emit([...d])}function g(v){d.push(v),d.length>o&&d.shift(),m()}function h(v){let w=d.splice(0,v);return m(),w}function y(v){if(l)throw new Error(`gate: ${v}() called after gate was torn down`)}let b=ne([i.node],(v,w,x)=>{let R=x.terminalDeps[0];if(R!==void 0){l=!0,d=[],m(),w.down(R===!0?[[F]]:[[O,R]]);return}let N=v[0];if(N==null||N.length===0){w.down([[z]]);return}for(let V of N)f?w.emit(V):(g(V),w.down([[z]]))},{name:e,describeKind:"derived",meta:Ia("gate",r?.meta)}),T={node:b,pending:a,count:u,isOpen:c,approve(v=1){y("approve");let w=h(v);for(let x of w){if(l)break;b.emit(x)}},reject(v=1){y("reject"),h(v)},modify(v,w=1){y("modify");let x=[...d],R=h(w);for(let N=0;N<R.length&&!l;N++)b.emit(v(R[N],N,x))},open(){y("open"),te(()=>{c.emit(!0);let v=h(d.length);for(let w of v){if(l)break;b.emit(w)}})},close(){y("close"),c.emit(!1)}};t.addDisposer(u.subscribe(()=>{})),t.addDisposer(p),Da(t,e,b,i.path?[i.path]:[]);let k=new ce(`${e}_state`);return k.add(a,{name:"pending"}),k.add(c,{name:"isOpen"}),k.add(u,{name:"count"}),t.mount(`${e}_state`,k),T}async function Ho(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:he()}),i.type==="token"&&(o+=i.delta);return o}function Wo(t,e){if(e==="json")try{return JSON.parse(pt(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function qo(t,e){return _([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:W("accumulated_text"),initial:""})}function Pa(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ur(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=_(e,l=>{if(l.some(p=>p==null))return[];let f=typeof n=="string"?n:n(...l);return f?[{role:"user",content:f}]:[]},{name:`${o}::messages`,meta:W("prompt_node::messages"),initial:[]}),c=ye(a,l=>{let f=l;if(!f||f.length===0)return L(null);let p=new AbortController;async function*m(){try{let g=await Ho(t,f,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:p.signal},i);yield Wo(g,s)}finally{p.abort()}}return I(m())}),u=qo(i,`${o}::accumulatedText`),d=X(c);return{output:c,deltaTopic:i,accumulatedText:u,dispose:()=>{d(),i.destroy()}}}function Ga(t,e,n,r,o,s){let i=L(0,{name:`${e}/cancel`}),a=0,c=[...r,i],u=s?.name??e,d=s?.format??"text",l=ur(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),f=_(c,k=>{let v=k.slice(0,-1);if(v.some(x=>x==null))return[];let w=typeof o=="string"?o:o(...v);return w?[{role:"user",content:w}]:[]},{name:`${u}::messages`,meta:W("prompt_node::messages"),initial:[]}),p=ye(f,k=>{let v=k;if(!v||v.length===0)return L(null);let w=new AbortController;async function*x(){try{let R=await Ho(n,v,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:w.signal},l);yield Wo(R,d)}finally{w.abort()}}return I(x())}),m=qo(l,`${u}::accumulatedText`),g=_([p],([k])=>{if(k!=null)return k},{name:`${e}/filter`});t.add(g,{name:`${e}/raw`});let h=zo(t,`${e}/gate`,`${e}/raw`,s?.gate),y=X(p),b=h.reject.bind(h),T={...h,reject(k=1){te(()=>{b(k),i.emit(++a)})}};return{output:h.node,deltaTopic:l,accumulatedText:m,gate:T,dispose:()=>{y(),l.destroy()}}}Y();ee();function Fa(t,e){let n=e?.separator??`
10
13
 
11
- `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(Vs)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Vs(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Sn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function qr(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Sn(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Ks(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Us(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=Ks(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),l=jt(s,i),u=G(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,c=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(l),signal:i?.signal});if(!c.ok)throw await Wr(c);let m=await c.json(),f=Math.max(0,(G()-u)/1e6);return qr(m,f)},async*stream(s,i){let a=r(i),l=jt(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(l),signal:i?.signal});if(!d.ok)throw await Wr(d);if(!d.body)throw new Error("googleAdapter: streaming response has no body");let c,m;for await(let f of zs(d.body)){if(!f.data)continue;let p;try{p=JSON.parse(f.data)}catch{continue}let g=p.candidates?.[0];for(let h of g?.content?.parts??[])typeof h.text=="string"&&(h.thought?yield{type:"thinking",delta:h.text}:yield{type:"token",delta:h.text}),h.functionCall&&(yield{type:"tool-call-delta",delta:{name:h.functionCall.name,argumentsDelta:JSON.stringify(h.functionCall.args??{})}});g?.finishReason&&(m=g.finishReason),p.usageMetadata&&(c=p.usageMetadata)}c&&(yield{type:"usage",usage:Sn(c)}),yield{type:"finish",reason:m??"stop"}}}}function Hs(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=G(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),l=Math.max(0,(G()-i)/1e6);return qr(a,l)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let l of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let u=l.candidates?.[0];for(let d of u?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});u?.finishReason&&(a=u.finishReason),l.usageMetadata&&(i=l.usageMetadata)}i&&(yield{type:"usage",usage:Sn(i)}),yield{type:"finish",reason:a??"stop"}}}}async function*zs(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Hr(r));return}r+=n.decode(s,{stream:!0});let i=zr(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let l=Hr(a);(l.data||l.event)&&(yield l),i=zr(r)}}}finally{e.releaseLock()}}function Hr(t){let e={},n=[];for(let r of t.split(`
12
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
13
- `)),e}function zr(t){let e=t.indexOf(`\r
14
- \r
15
- `),n=t.indexOf(`
14
+ `,r=t.map(i=>typeof i=="string"?L(i):I(i)),o=_(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:W("system_prompt"),initial:""}),s=X(o);return Object.assign(o,{dispose:s})}Y();var $a=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function ja(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return _([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=Ee(i.usage)+Pe(i.usage));let c=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:c,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:W("cost_meter_extractor"),equals:$a})}Y();var Ba=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function Va(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return _([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,c=s.store.scannedTo,u=Math.max(0,c-n),d=i.slice(u),l=!1;for(let{pattern:f,label:p,compiled:m}of r){m.lastIndex=0;for(let g of d.matchAll(m)){let h=u+(g.index??0);h+g[0].length<=c||(a.push({label:p,pattern:f,match:g[0],position:h}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:W("keyword_flag_extractor"),equals:Ba})}Y();function Ka(t,e,n){return _([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:W("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}Y();var Ua=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function za(t,e){return _([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let c=o.indexOf("{",i);if(c===-1){r.store.scanFrom=o.length;break}let u=0,d=-1,l=!1;for(let p=c;p<o.length;p++){let m=o[p];if(l)m==="\\"&&p+1<o.length?p++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){d=p;break}}if(d===-1){r.store.scanFrom=c;break}let f=o.slice(c,d+1);try{let p=JSON.parse(f);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(s.push({name:p.name,arguments:p.arguments,raw:f,startIndex:c}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:W("tool_call_extractor"),equals:Ua})}Y();function Ha(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),_(i,a=>{let c=a[0]??"";if(c.length===0)return"allow";let u=s?a[1]??0:e(c);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}Y();function Wa(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let c of e){let u=c.global?c:new RegExp(c.source,`${c.flags}g`);a=a.replace(u,d=>o(d,c))}return a}return _([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}xe();ue();_e();Y();ct();ee();Y();var fn=class extends ce{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=$e([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=_([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:W("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(X(this.latest)),this.messageCount=_([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:W("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(X(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function dr(t,e){return new fn(t,e)}Y();ee();var mn=class extends ce{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=it({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=_([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:W("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(X(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=r.handler(n);return Xe(o)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return I(r.handler(n))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function lr(t,e){return new mn(t,e)}var gn=class extends ce{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=dr(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=lr(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let A of n.tools)this.tools.register(A);this.status=L("idle",{name:"status",describeKind:"state",meta:W("agent_status")}),this.add(this.status,{name:"status"}),this.turn=L(0,{name:"turn",describeKind:"state",meta:W("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=L(!1,{name:"aborted",describeKind:"state",meta:W("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(A=>{for(let E of A)E[0]===C&&(r=E[1])}),s=!1,i=this.aborted.subscribe(A=>{for(let E of A)E[0]===C&&(s=E[1])}),a=n.adapter,c=n.systemPrompt,u=n.model,d=n.temperature,l=n.maxTokens,f=n.maxTurns??10,p=n.stopWhen,m=this.chat,g=this.tools,h=this.status,y=this.turn,b=this.aborted,T=ne([h],(A,E,B)=>{if(St(A,B.prevData,0,"idle")!=="thinking"||s||r>=f){E.down([[z]]);return}let Z=m.allMessages();if(Z.length===0){E.down([[z]]);return}let Q=g.schemas.cache??[];E.emit({messages:Z,tools:Q})},{name:"promptInput",describeKind:"derived",meta:W("agent_prompt_input")}),k=ye(T,A=>{let E=new AbortController;return this._currentAbortController=E,s&&E.abort(new Error("agentLoop: aborted")),I(Promise.resolve(a.invoke(A.messages,{tools:A.tools.length>0?A.tools:void 0,systemPrompt:c,model:u,temperature:d,maxTokens:l,signal:E.signal})),{signal:E.signal})},{equals:()=>!1}),v=L(null,{name:"lastResponse",describeKind:"state",meta:W("agent_last_response")});this.lastResponse=v;let w=ne([v,h],(A,E,B)=>{let U=St(A,B.prevData,0,null);if(St(A,B.prevData,1,"idle")!=="acting"){E.down([[z]]);return}let Q=U?.toolCalls;if(Q==null||Q.length===0){E.down([[z]]);return}E.emit(Q)},{name:"toolCalls",describeKind:"derived",meta:W("agent_tool_calls")}),x=n.interceptToolCalls?n.interceptToolCalls(w):w;this.toolCalls=x;let R=(A,E)=>{if(A===E)return!0;if(A.length!==E.length)return!1;for(let B=0;B<A.length;B++){let U=A[B],Z=E[B];if(U?.id!==Z?.id||U?.content!==Z?.content)return!1}return!0},N=ye(x,A=>{if(A==null||A.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let E=A.map(B=>qa(B,g));return _(E,B=>B.map((U,Z)=>{let Q=U;return Q!=null&&typeof Q=="object"&&"id"in Q&&"content"in Q?Q:{id:A[Z].id,content:JSON.stringify(U??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=N;let V=Me([k],([A])=>{if(s)return;let E=A,B=r+1,U=E.toolCalls!=null&&E.toolCalls.length>0,Z=E.finishReason==="end_turn"&&(!E.toolCalls||E.toolCalls.length===0),Q=p?.(E)===!0,ke=B>=f,P=Q||Z||!U||ke?"done":"acting";te(()=>{v.emit(E),h.emit(P),y.emit(B),m.append("assistant",E.content,{toolCalls:E.toolCalls})})}),M=Me([N],([A])=>{if(s)return;let E=A;if(E.length===0)return;let B=r>=f?"done":"thinking";te(()=>{h.emit(B);for(let U of E)m.appendToolResult(U.id,U.content)})}),D=Me([b],([A])=>{A===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),h.emit("done"))}),S=X(V),G=X(M),H=X(D);this._terminalResult=ne([h,v],(A,E,B)=>{let U=St(A,B.prevData,0,"idle"),Z=St(A,B.prevData,1,null);if(U==="done"){if(Z!=null){E.emit({response:Z,runVersion:this._runVersion});return}let Q=new Error("agentLoop: aborted");Q.name="AbortError",E.down([[O,Q]]);return}if(U==="error"){E.down([[O,new Error("agentLoop: errored")]]);return}E.down([[z]])},{name:"terminalResult",describeKind:"derived",meta:W("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(S),this.addDisposer(G),this.addDisposer(H),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r=++this._runVersion;te(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await Hr(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function qa(t,e){let n=Cn(()=>I(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=_([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return qr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function St(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Ja(t,e){return new gn(t,e)}Y();ee();function Ya(t,e,n){let r=I(t),o=n?.condition!=null?I(n.condition):null,s=L(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ye(r,a=>{if(a==null)return s;let c=L(a);return e(c)});let i=_([r,o],([a,c])=>({v:a,open:c===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ye(i,({v:a,open:c})=>{if(a==null)return s;if(!c)return L(a);let u=L(a);return e(u)})}Y();ee();function Qa(t,e,n){let r=I(t),o=e.map(i=>I(i)),s=[r,...o];return _(s,i=>{let a=i[0]??[],c=i.slice(1);return a.filter(u=>{for(let d of c)if(d!=null&&!d(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:W("tool_selector"),equals:(i,a)=>{let c=i,u=a;if(c.length!==u.length)return!1;for(let d=0;d<c.length;d++)if(c[d]!==u[d])return!1;return!0}})}function Xa(t){return{persistence:.5,structure:.5,personalValue:.5}}function Za(t={}){let e=t.scoreFn??Xa,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}xe();ge();Y();xe();ue();Y();ee();function ec(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Jo(t){t.subscribe(()=>{})}function Nt(t){return t instanceof Map?t:new Map}function Yo(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");te(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Qo(t,e,n){let r=I(t),o=it(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?I(n.context):L(null),c=Nt(o.entries.cache);o.entries.subscribe(p=>{for(let m of p)m[0]===C&&(c=Nt(m[1]))});let u=ye(r,p=>e(p,c));if(wt(u,p=>{Yo(o,p)}),n.evict){let p=new Map,m=_([o.entries],([g])=>{let h=[],y=Nt(g);for(let b of p.keys())y.has(b)||(p.get(b)(),p.delete(b));for(let[b,T]of y){let k=n.evict(b,T);if(ec(k)){if(!p.has(b)){let v=wt(k,w=>{w===!0&&o.has(b)&&o.delete(b)});p.set(b,v)}continue}if(typeof k=="boolean"){k&&h.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return h});wt(m,g=>{for(let h of g)o.delete(h)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let p=I(n.consolidateTrigger),m=ye(p,()=>n.consolidate(c));wt(m,g=>{Yo(o,g)})}let l=_([o.entries,a],([p,m])=>{let g=[...Nt(p).entries()].map(([b,T])=>({key:b,value:T,score:n.score(T,m),cost:n.cost(T)}));g.sort((b,T)=>T.score-b.score);let h=[],y=s;for(let b of g)b.cost<=y&&(h.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return h}),f=_([o.entries],([p])=>Nt(p).size);return Jo(l),Jo(f),{store:o,compact:l,size:f}}ee();ge();Y();function Xo(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function tc(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function et(t){return new Map(t)}function Oe(t){return t.cache??new Map}function hn(t){return t.cache??[]}function nc(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,c=e[i]??0;r+=a*c,o+=a*a,s+=c*c}return o===0||s===0?0:r/Math.sqrt(o*s)}function Zo(t={}){let e=t.maxSize,n=t.policy??"fifo";tc(e);let r=L(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let c of i.values()){if(!a){a=c;continue}let u=n==="lru"?c.lastAccessNs:c.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;u<d&&(a=c)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let c=$(),u=Oe(r),d=u.get(i),l=et(u);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??c,lastAccessNs:c}),o(l),s(l)},remove(i){let a=et(Oe(r));a.delete(i)&&s(a)},clear(){Oe(r).size!==0&&s(new Map)},get(i){let a=Oe(r),c=a.get(i);if(c){if(n==="lru"){let u=$(),d=et(a);d.set(i,{...c,lastAccessNs:u}),s(d)}return c.value}},has(i){return Oe(r).has(i)}}}function es(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=L(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,c,u){s(c);let d=et(Oe(o));d.set(a,{id:a,vector:[...c],meta:u}),e==="hnsw"&&r.upsert(a,c,u),i(d)},remove(a){let c=et(Oe(o));c.delete(a)&&(e==="hnsw"&&r.remove(a),i(c))},clear(){Oe(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,c=5){return s(a),c<=0?[]:e==="hnsw"?r.search(a,c):[...Oe(o).values()].map(d=>({id:d.id,score:nc(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,c)}}}function ts(t){let e=new ce(t),n=L(new Map,{name:"entities",describeKind:"state"}),r=L([],{name:"edges",describeKind:"state"}),o=_([r],([c])=>{let u=c??[],d=new Map;for(let l of u){let f=d.get(l.from)??[];d.set(l.from,Object.freeze([...f,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(c){n.emit(c)}function i(c){r.emit(c)}return Object.assign(e,{upsertEntity(c,u){let d=et(Oe(n));d.set(c,u),s(d)},removeEntity(c){let u=et(Oe(n)),d=u.delete(c),l=hn(r),f=l.filter(p=>p.from!==c&&p.to!==c);!d&&f.length===l.length||(s(u),i(f))},link(c,u,d,l=1){let f=`${c}\0${u}\0${d}`,p=hn(r),m=new Set(p.map(h=>`${h.from}\0${h.to}\0${h.relation}`)),g=[...p];if(m.has(f))for(let h=0;h<g.length;h+=1){let y=g[h];if(y.from===c&&y.to===u&&y.relation===d){g[h]={...y,weight:l};break}}else g.push({from:c,to:u,relation:d,weight:l});i(g)},unlink(c,u,d){let l=hn(r),f=l.filter(p=>d===void 0?!(p.from===c&&p.to===u):!(p.from===c&&p.to===u&&p.relation===d));f.length!==l.length&&i(f)},related(c,u){return hn(r).filter(d=>(d.from===c||d.to===c)&&(u===void 0||d.relation===u))}})}ue();Y();ee();function pr(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return ie(i=>{let a=!0,c=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=I(c).subscribe(l=>{if(!a)return;let f=!1;for(let p of l){if(f)break;if(p[0]===C){let m=p[1];try{let g=JSON.parse(m.content);i.emit(g),i.down([[F]])}catch{i.down([[O,new Error("llmExtractor: failed to parse LLM response as JSON")]])}f=!0}else p[0]===O?(i.down([[O,p[1]]]),f=!0):p[0]===F?(i.down([[F]]),f=!0):i.down([[p[0],p[1]]])}});return()=>{d(),a=!1}})}}function fr(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return ie(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),u=I(a).subscribe(d=>{if(!i)return;let l=!1;for(let f of d){if(l)break;if(f[0]===C){let p=f[1];try{let m=JSON.parse(p.content);s.emit(m),s.down([[F]])}catch{s.down([[O,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}l=!0}else f[0]===O?(s.down([[O,f[1]]]),l=!0):f[0]===F?(s.down([[F]]),l=!0):s.down([[f[0],f[1]]])}});return()=>{u(),i=!1}})}}var mr=Math.LN2/604800;function _t(t){return t instanceof Map?t:new Map}function rc(t,e,n){let r=new ce(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=pr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(T,k)=>T==null?{upsert:[]}:s(T,k),a=e;if(n.admissionFilter){let T=I(e),k=n.admissionFilter;a=_([T],([v])=>{if(k(v))return v},{name:"admissionFilter",describeKind:"derived"})}let c;n.consolidateFn?c=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(c=fr(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&c&&n.reflection?.enabled!==!1){let T=n.reflection?.interval??3e5;u=Ur(T,{period:T})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:c,consolidateTrigger:u},l=Qo(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let f=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(f=es({dimension:n.vectorDimensions}),r.add(f.entries,{name:"vectorIndex"}));let p=null;n.enableKnowledgeGraph&&(p=ts(`${t}-kg`),r.mount("kg",p));let m=null;if(n.tiers){let T=n.tiers,k=T.decayRate??mr,v=T.maxActive??1e3,w=T.archiveThreshold??.1,x=T.permanentFilter??(()=>!1),R=Zo({name:"permanent"});r.add(R.entries,{name:"permanent"});let N=new Set,V=E=>N.has(E)?"permanent":_t(l.store.entries.cache).has(E)?"active":"archived",M=(E,B)=>{N.add(E),R.upsert(E,B)},D=new Map,S=l.store.entries,G=n.context?I(n.context):L(null),H=Me([S,G],([E,B])=>{let U=_t(E),Z=$(),Q=[],ke=[];for(let[K,oe]of U){if(D.has(K)||D.set(K,Z),x(K,oe)){ke.push({key:K,value:oe});continue}let pe=n.score(oe,B),q=D.get(K)??Z,j=Number(Z-q)/1e9;Xo(pe,j,k)<w&&Q.push(K)}for(let K of D.keys())U.has(K)||D.delete(K);for(let{key:K,value:oe}of ke)N.has(K)||M(K,oe);let P=U.size-N.size;if(P>v){let K=[...U.entries()].filter(([pe])=>!N.has(pe)).map(([pe,q])=>({key:pe,score:n.score(q,B)})).sort((pe,q)=>pe.score-q.score),oe=P-v;for(let pe=0;pe<oe&&pe<K.length;pe++){let q=K[pe].key;Q.includes(q)||Q.push(q)}}Q.length>0&&te(()=>{for(let K of Q)l.store.delete(K)})});o.push(H.subscribe(()=>{}));let A=null;T.archiveTier&&(A=r.attachStorage([T.archiveTier],T.archiveStorageOptions??{})),m={permanent:R,activeEntries:S,archiveHandle:A,tierOf:V,markPermanent:M}}if(f||p){let T=n.embedFn,k=n.entityFn,v=l.store.entries,w=Me([v],([x])=>{let R=_t(x);for(let[N,V]of R){if(f&&T){let M=T(V);M&&f.upsert(N,M,V)}if(p&&k){let M=k(N,V);if(M){for(let D of M.entities??[])p.upsertEntity(D.id,D.value);for(let D of M.relations??[])p.link(D.from,D.to,D.relation,D.weight)}}}});o.push(w.subscribe(()=>{}))}let g=null,h=null,y=null,b=null;if(f||p){let T=n.retrieval?.topK??20,k=n.retrieval?.graphDepth??1,v=n.budget??2e3,w=n.cost,x=n.score,R=n.contextOf,N=n.contextWeight??0,V=n.context?I(n.context):L(null),M=(A,E)=>{if(!A||!E)return 0;let B=Math.min(A.length,E.length),U=0;for(;U<B&&A[U]===E[U];)U++;return U},D=(A,E,B)=>{let U=new Map,Z=[];if(f&&B.vector){Z=f.search(B.vector,T);for(let q of Z){let j=A.get(q.id);j&&U.set(q.id,{value:j,sources:new Set(["vector"])})}}let Q=[];if(p){let q=[...B.entityIds??[],...U.keys()],j=new Set,ae=q;for(let Ae=0;Ae<k;Ae++){let Ve=[];for(let ft of ae){if(j.has(ft))continue;j.add(ft);let Mt=p.related(ft);for(let us of Mt){let tt=us.to;if(!j.has(tt)){Ve.push(tt);let hr=A.get(tt);if(hr){let yr=U.get(tt);yr?yr.sources.add("graph"):U.set(tt,{value:hr,sources:new Set(["graph"])}),Q.push(tt)}}}}ae=Ve}}for(let[q,j]of A)U.has(q)||U.set(q,{value:j,sources:new Set(["store"])});let ke=B.context?.length??0,P=[];for(let[q,{value:j,sources:ae}]of U){let Ae=R?R(j):void 0,Ve=x(j,E);if(N>0&&ke>0){let Mt=M(B.context,Ae);Mt>0&&(Ve=Ve*(1+N*Mt/ke))}let ft=Ae?{key:q,value:j,score:Ve,sources:[...ae],context:Ae}:{key:q,value:j,score:Ve,sources:[...ae]};P.push(ft)}P.sort((q,j)=>j.score-q.score);let K=[],oe=0;for(let q of P){let j=w(q.value);if(oe+j>v&&K.length>0)break;K.push(q),oe+=j}return{packed:K,trace:{vectorCandidates:Z,graphExpanded:Q,ranked:P,packed:K}}},S=L([],{name:"retrieval",describeKind:"state",meta:W("retrieval_pipeline")});r.add(S,{name:"retrieval"}),g=S;let G=L(null,{name:"retrievalTrace",describeKind:"state",meta:W("retrieval_trace")});r.add(G,{name:"retrievalTrace"}),h=G,y=A=>{let E=_t(l.store.entries.cache),{packed:B,trace:U}=D(E,V.cache,A);return te(()=>{S.emit(B),G.emit(U)}),B},b=A=>{let E=I(A);return _([l.store.entries,V,E],([B,U,Z])=>{if(Z==null)return[];let Q=_t(B);return D(Q,U,Z).packed},{name:"retrievalReactive",describeKind:"derived",meta:W("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let T of o)T();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:f,kg:p,memoryTiers:m,retrieval:g,retrievalTrace:h,retrieve:y,retrieveReactive:b})}function oc(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
15
+ `,i=[],a=n?.sinceVersion;for(let[c,u]of Object.entries(r.nodes)){let d=u.meta??{},l=d.description,f=d.format;if(!l&&!f)continue;if(a!=null&&u.v!=null){let y=a.get(c);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let p=l??c,m=u.value,g=d.unit,h;f==="currency"&&typeof m=="number"?h=`$${m.toFixed(2)}`:f==="percentage"&&typeof m=="number"?h=`${(m*100).toFixed(1)}%`:m==null?h="(no value)":h=String(m),g&&f!=="currency"&&f!=="percentage"&&(h=`${h} ${g}`),i.push({path:c,description:p,formatted:h})}if(i.length===0)return"";if(o){let c=new Map,u=[];for(let l of i){let p=r.nodes[l.path].meta?.tags;if(p&&p.length>0){let m=p[0],g=c.get(m);g||(g=[],c.set(m,g)),g.push(l)}else u.push(l)}if(c.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,f]of[...c.entries()].sort((p,m)=>p[0].localeCompare(m[0])))d.push(`[${l}]${s}${f.map(p=>`- ${p.description}: ${p.formatted}`).join(s)}`);return u.length>0&&d.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(c=>`- ${c.description}: ${c.formatted}`).join(s)}Y();xe();ue();_e();Y();function ns(t,e){return je("reduction",t,e)}function rs(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=L(0,{meta:ns("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),c=t.resolve(n),u=`__feedback_effect_${e}`,d=ne([],(l,f)=>{let p=a.subscribe(m=>{for(let g of m){let h=g[0];if(h===C){let y=g[1];if(y==null)return;te(()=>{ho(i,o)&&c.emit(y)})}else if(h===F||h===O){let y=h===O&&g.length>1?[O,g[1]]:[h];i.down([y])}}});return()=>p()},{name:u,describeKind:"effect",meta:{...ns("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:u}),t.addDisposer(X(d)),t}function ss(t){return typeof t=="object"&&t!==null&&"factory"in t}function sc(t){return typeof t=="object"&&t!==null&&"factory"in t}function ic(t){return ss(t)?t.factory:t}function ac(t){return sc(t)?t.factory:t}function cc(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let c=gr(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let c=gr(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let c=e.fns[a.fn];if(ss(c)&&c.configSchema){for(let[u,d]of Object.entries(c.configSchema))if(d.required!==!1&&!(u in a.config)&&n.push(`Node "${s}": config missing required field "${u}"`),u in a.config&&d.enum){let l=a.config[u];d.enum.includes(l)||n.push(`Node "${s}": config.${u} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,c]of Object.entries(i.nodes))if(c.fn&&r.size>0&&!r.has(c.fn)){let u=gr(c.fn,r);n.push(`Template "${s}" node "${a}": fn "${c.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}}return{valid:n.length===0,errors:n}}function gr(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=uc(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function uc(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,c)=>i===0?c:c===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var os=new Set(["state","producer","derived","effect","operator","template"]),dc=new Set(["state","producer","derived","effect","operator"]);function lc(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes)),o=new Map,s=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[i,a]of Object.entries(n.templates))if(a!=null&&typeof a=="object"){let c=a;s.set(i,{params:Array.isArray(c.params)?c.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))e.push("'templates' must be an object");else for(let[i,a]of Object.entries(n.templates)){if(a==null||typeof a!="object"){e.push(`Template "${i}": must be an object`);continue}let c=a;if(Array.isArray(c.params)||e.push(`Template "${i}": missing 'params' array`),c.nodes==null||typeof c.nodes!="object"||Array.isArray(c.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let u=new Set(Array.isArray(c.params)?c.params:[]),d=new Set(Object.keys(c.nodes));for(let[l,f]of Object.entries(c.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let p=f;if((typeof p.type!="string"||!dc.has(p.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(p.deps))for(let m of p.deps)!d.has(m)&&!u.has(m)&&e.push(`Template "${i}" node "${l}": dep "${m}" is not an inner node or param`)}typeof c.output!="string"?e.push(`Template "${i}": missing 'output' string`):c.nodes[c.output]||e.push(`Template "${i}": output "${c.output}" is not a declared node`)}}for(let[i,a]of Object.entries(n.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${i}": must be an object`);continue}let c=a;if(typeof c.type!="string"||!os.has(c.type)){e.push(`Node "${i}": invalid type "${String(c.type)}" (expected: ${[...os].join(", ")})`);continue}if(o.set(i,c.type),c.type==="template")if(typeof c.template!="string"||!s.has(c.template))e.push(`Node "${i}": template "${String(c.template)}" not found in templates`);else if(c.bind==null||typeof c.bind!="object"||Array.isArray(c.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let u=s.get(c.template),d=c.bind;for(let l of u.params)l in d||e.push(`Node "${i}": template param "${l}" is not bound (template "${c.template}")`);for(let[,l]of Object.entries(d))typeof l=="string"&&!r.has(l)&&e.push(`Node "${i}": bind target "${l}" does not reference an existing node`)}else{if(Array.isArray(c.deps))for(let u of c.deps)u===i?e.push(`Node "${i}": self-referencing dep`):r.has(u)||e.push(`Node "${i}": dep "${u}" does not reference an existing node`);(c.type==="derived"||c.type==="effect"||c.type==="operator")&&!Array.isArray(c.deps)&&e.push(`Node "${i}": ${c.type} node should have a 'deps' array`)}}if(n.feedback!=null)if(!Array.isArray(n.feedback))e.push("'feedback' must be an array");else for(let i=0;i<n.feedback.length;i++){let a=n.feedback[i];if(a==null||typeof a!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let c=a;(typeof c.from!="string"||!r.has(c.from))&&e.push(`Feedback [${i}]: 'from' "${String(c.from)}" does not reference an existing node`),typeof c.from=="string"&&c.from===c.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof c.to!="string"||!r.has(c.to)?e.push(`Feedback [${i}]: 'to' "${String(c.to)}" does not reference an existing node`):typeof c.to=="string"&&o.get(c.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${c.to}" must be a state node (got "${o.get(c.to)??"unknown"}")`)}return{valid:e.length===0,errors:e}}function is(t,e){let n=lc(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
16
+ ${n.errors.join(`
17
+ `)}`);let r=e?.catalog??{},o=new ce(t.name),s=t.templates??{},i=cc(t,r);if(!i.valid)throw new Error(`compileSpec: catalog validation errors:
18
+ ${i.errors.join(`
19
+ `)}`);let a=p=>{let m=r.fns?.[p];return m?ic(m):void 0},c=p=>{let m=r.sources?.[p];return m?ac(m):void 0},u=new Map,d=[];for(let[p,m]of Object.entries(t.nodes)){if(m.type==="template")continue;let g=m;if(g.type==="state"){let h=L(g.initial,{name:p,meta:g.meta?{...g.meta}:void 0});o.add(h,{name:p}),u.set(p,h)}else if(g.type==="producer"){let h=g.source?c(g.source):void 0,y=g.fn?a(g.fn):void 0;if(h){let b=h(g.config??{});o.add(b,{name:p}),u.set(p,b)}else if(y){let b=y([],g.config??{});o.add(b,{name:p}),u.set(p,b)}else{let b=ie(()=>{},{name:p,meta:{...g.meta,_specFn:g.fn,_specSource:g.source}});o.add(b,{name:p}),u.set(p,b)}}else d.push([p,g])}let l=!0,f=new Map(d);for(;f.size>0&&l;){l=!1;for(let[p,m]of[...f.entries()]){let g=m.deps??[];if(!g.every(T=>u.has(T)))continue;let h=g.map(T=>u.get(T)),y=m.fn?a(m.fn):void 0,b;y?b=y(h,m.config??{}):m.type==="effect"?b=Me(h,()=>{}):b=_(h,T=>T[0]),o.add(b,{name:p}),u.set(p,b),f.delete(p),l=!0}}if(f.size>0){let p=[...f.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${p}`)}for(let[p,m]of Object.entries(t.nodes)){if(m.type!=="template")continue;let g=m,h=s[g.template],y=new ce(p),b=new Map,T=[];for(let[x,R]of Object.entries(h.nodes)){let N=(R.deps??[]).map(M=>M.startsWith("$")&&g.bind[M]?g.bind[M]:M),V={...R,deps:N};if(R.type==="state"){let M=L(R.initial,{name:x,meta:R.meta?{...R.meta}:void 0});y.add(M,{name:x}),b.set(x,M)}else if(R.type==="producer"){let M=R.source?c(R.source):void 0,D=R.fn?a(R.fn):void 0;if(M){let S=M(R.config??{});y.add(S,{name:x}),b.set(x,S)}else if(D){let S=D([],R.config??{});y.add(S,{name:x}),b.set(x,S)}else{let S=ie(()=>{},{name:x,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});y.add(S,{name:x}),b.set(x,S)}}else T.push([x,V])}let k=!0,v=new Map(T);for(;v.size>0&&k;){k=!1;for(let[x,R]of[...v.entries()]){let N=R.deps??[];if(!N.every(G=>b.has(G)||u.has(G)))continue;let M=N.map(G=>b.get(G)??u.get(G)),D=R.fn?a(R.fn):void 0,S;D?S=D(M,R.config??{}):R.type==="effect"?S=Me(M,()=>{}):S=_(M,G=>G[0]),y.add(S,{name:x}),b.set(x,S),v.delete(x),k=!0}}if(v.size>0){let x=[...v.keys()].sort().join(", ");throw new Error(`compileSpec: template "${g.template}" has unresolvable deps: ${x}`)}o.mount(p,y);let w=`${p}::${h.output}`;u.set(p,o.resolve(w));try{let x=o.resolve(w);x.meta._templateName?.emit(g.template),x.meta._templateBind?.emit(g.bind)}catch{}}for(let p of t.feedback??[])rs(o,p.from,p.to,{maxIterations:p.maxIterations});return o}var as=`You are a graph architect for GraphReFly, a reactive graph protocol.
16
20
 
17
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Wr(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Google API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}he();var Ws={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function On(t={}){return t.sdk?Qs(t):Xs(t)}function Vt(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(qs);e?.systemPrompt&&!t.some(l=>l.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Js)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function qs(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function Js(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Cn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function Qr(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Ys(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Cn(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Ys(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Zr(t){let e=t.preset??"openai",n=Ws[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Xs(t){let{provider:e,baseURL:n,apiKey:r}=Zr(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,l){let u=Vt(a,l,t.model,!1,t.bodyExtras),d=G(),c=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:l?.signal});if(!c.ok)throw await Xr(c,e);let m=await c.json(),f=Math.max(0,(G()-d)/1e6);return Qr(m,f,e)},async*stream(a,l){let u=Vt(a,l,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:l?.signal});if(!d.ok)throw await Xr(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let c,m;for await(let f of Zs(d.body)){if(!f.data||f.data==="[DONE]")continue;let p;try{p=JSON.parse(f.data)}catch{continue}let g=p.choices;if(g){let h=g[0];if(h?.delta?.content&&(yield{type:"token",delta:h.delta.content}),h?.delta?.reasoning_content&&(yield{type:"thinking",delta:h.delta.reasoning_content}),h?.delta?.tool_calls)for(let y of h.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};h?.finish_reason&&(m=h.finish_reason)}p.usage&&(c=p.usage,yield{type:"usage",usage:Cn(c)})}yield{type:"finish",reason:m??"stop"}}}}function Qs(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Zr(t);return{provider:n,model:t.model,async invoke(r,o){let s=Vt(r,o,t.model,!1,t.bodyExtras),i=G(),a=await e.chat.completions.create(s,{signal:o?.signal}),l=Math.max(0,(G()-i)/1e6);return Qr(a,l,n)},async*stream(r,o){let s=Vt(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,l;for await(let u of i){let d=u.choices;if(d){let m=d[0];if(m?.delta?.content&&(yield{type:"token",delta:m.delta.content}),m?.delta?.reasoning_content&&(yield{type:"thinking",delta:m.delta.reasoning_content}),m?.delta?.tool_calls)for(let f of m.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};m?.finish_reason&&(l=m.finish_reason)}let c=u.usage;c&&(a=c,yield{type:"usage",usage:Cn(c)})}yield{type:"finish",reason:l??"stop"}}}}async function*Zs(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Jr(r));return}r+=n.decode(s,{stream:!0});let i=Yr(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let l=Jr(a);(l.data||l.event)&&(yield l),i=Yr(r)}}}finally{e.releaseLock()}}function Jr(t){let e={},n=[];for(let r of t.split(`
18
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
19
- `)),e}function Yr(t){let e=t.indexOf(`\r
20
- \r
21
- `),n=t.indexOf(`
22
-
23
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Xr(t,e){let n;try{n=await t.text()}catch{n=""}let r=new Error(`${e} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return r.status=t.status,r.headers=t.headers,r}function ei(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return dn(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return An(e)}case"dry-run":{let e={model:t.model,...t.extras};return Ee(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return En(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return On(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}he();X();Me();fe();X();var Ln=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function eo(t){return t.subscribe(()=>{})}var ti=64;function De(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Ln(t,r),a=S(i.toArray(),{name:n,describeKind:"state",equals:(p,g)=>p===g,...o!=null?{versioning:o}:{}});function l(){let p=i.toArray();se(()=>{a.down([[Y]]),a.down([[L,p]])})}let u=new Map,d=new Map;function c(p,g){return`${p}:${g===void 0?"END":g}`}function m(p){if(p.size<ti)return;let g=p.keys().next();if(g.done)return;let h=p.get(g.value);h!==void 0&&h.dispose(),p.delete(g.value)}function f(p){let g=i.version;try{return p()}finally{i.version!==g&&l()}}return{entries:a,get size(){return i.size},at(p){return i.at(p)},append(p){f(()=>i.append(p))},appendMany(p){p.length!==0&&f(()=>i.appendMany(p))},clear(){f(()=>i.clear())},trimHead(p){f(()=>i.trimHead(p))},tail(p){if(!Number.isInteger(p)||p<0)throw new RangeError(`tail: n must be a non-negative integer (got ${p})`);let g=u.get(p);if(g!==void 0)return u.delete(p),u.set(p,g),g.node;m(u);let h=C([a],([v])=>{let b=v;return p===0||b.length===0?[]:b.slice(Math.max(0,b.length-p))},{initial:i.tail(p),describeKind:"derived"}),y=eo(h);return u.set(p,{node:h,dispose:y}),h},slice(p,g){if(!Number.isInteger(p)||p<0)throw new RangeError(`slice: start must be a non-negative integer (got ${p})`);if(g!==void 0&&(!Number.isInteger(g)||g<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${g})`);let h=c(p,g),y=d.get(h);if(y!==void 0)return d.delete(h),d.set(h,y),y.node;m(d);let v=C([a],([T])=>{let w=T;return g===void 0?w.slice(p):w.slice(p,g)},{initial:i.slice(p,g),describeKind:"derived"}),b=eo(v);return d.set(h,{node:v,dispose:b}),v},disposeTail(p){let g=u.get(p);return g===void 0?!1:(g.dispose(),u.delete(p),!0)},disposeSlice(p,g){let h=c(p,g),y=d.get(h);return y===void 0?!1:(y.dispose(),d.delete(h),!0)},disposeAllViews(){for(let p of u.values())p.dispose();u.clear();for(let p of d.values())p.dispose();d.clear()},dispose(){for(let p of u.values())p.dispose();u.clear();for(let p of d.values())p.dispose();d.clear()}}}re();function Se(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Ue(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function to(){return{input:{regular:0},output:{regular:0}}}function ni(t,e){let n=e?.logMax??1e3,r=De(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=S(null,{name:"adapterStats/lastCall"}),s=S(0,{name:"adapterStats/totalCalls"}),i=S(0,{name:"adapterStats/totalInputTokens"}),a=S(0,{name:"adapterStats/totalOutputTokens"}),l=m=>{r.append(m),o.emit(m),s.emit((s.cache??0)+1),i.emit((i.cache??0)+Se(m.usage)),a.emit((a.cache??0)+Ue(m.usage))},u=()=>{r.clear(),o.emit(null),s.emit(0),i.emit(0),a.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(m,f){let p=G(),g=be(),h=t.invoke(m,f),y=b=>{let T=G();return l({timestamp:T,wallClock:g,provider:t.provider,model:t.model??f?.model??b.model??"",tier:f?.tier??b.tier,usage:b.usage??Dn(),latencyMs:Math.max(0,(T-p)/1e6),method:"invoke"}),b};if(h!=null&&typeof h.then=="function")return h.then(y);if(h!=null&&typeof h=="object"&&"content"in h)return y(h);let v=!1;return C([$(h)],([b])=>b==null||v?b:(v=!0,y(b)),{name:"adapterStats/invokeTap"})},async*stream(m,f){let p=G(),g=be(),h;try{for await(let v of t.stream(m,f))v.type==="usage"&&(h=v.usage),yield v;let y=G();l({timestamp:y,wallClock:g,provider:t.provider,model:t.model??f?.model??"",tier:f?.tier,usage:h??Dn(),latencyMs:Math.max(0,(y-p)/1e6),method:"stream"})}catch(y){let v=G(),b=y;throw l({timestamp:v,wallClock:g,provider:t.provider,model:t.model??f?.model??"",tier:f?.tier,usage:h??Dn(),latencyMs:Math.max(0,(v-p)/1e6),method:"stream",error:{type:b?.name??"Error",message:b?.message??String(y)}}),y}}},stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:u}}}function Dn(){return{input:{regular:0},output:{regular:0}}}function ri(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function In(t="USD"){return{total:0,currency:t}}function no(t,e,n){let r=Se(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,l=(h,y,v)=>{if(!y||v==null)return;let b=ri(v,r),T=y*b/1e6;a+=T,s&&(i[h]=(i[h]??0)+T)},u=t.input,d=e.input;if(d&&(l("input.regular",u.regular,d.regular),l("input.cacheRead",u.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",u.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",u.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",u.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",u.audio??0,d.audio),l("input.image",u.image??0,d.image),l("input.video",u.video??0,d.video),l("input.toolUse",u.toolUse??0,d.toolUse),u.extensions&&d.extensions))for(let[h,y]of Object.entries(u.extensions))l(`input.ext.${h}`,y,d.extensions[h]);let c=t.output,m=e.output;if(m&&(l("output.regular",c.regular,m.regular),l("output.reasoning",c.reasoning??0,m.reasoning),l("output.audio",c.audio??0,m.audio),l("output.predictionAccepted",c.predictionAccepted??0,m.predictionAccepted),l("output.predictionRejected",c.predictionRejected??0,m.predictionRejected),c.extensions&&m.extensions))for(let[h,y]of Object.entries(c.extensions))l(`output.ext.${h}`,y,m.extensions[h]);let f=n?.tier;if(f&&e.tierMultipliers){let h=e.tierMultipliers[f];if(h!=null&&(a*=h,s))for(let y of Object.keys(i))i[y]*=h}let p=t.auxiliary,g=e.auxiliary;if(p&&g)for(let[h,y]of Object.entries(p)){let v=g[h];if(v==null||!y)continue;let b=y*v;a+=b,s&&(i[`auxiliary.${h}`]=b)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Kt(t,e){return`${t}::${e}`}function oi(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Kt(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(Kt(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let l;for(let u of a)if(s.startsWith(u)&&(!l||u.length>l.key.length)){let d=e.get(Kt(o,u));d&&(l={key:u,pricing:d.pricing})}return l?.pricing},remove(o,s){let i=e.delete(Kt(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function si(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?no(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):In(e)}}function ii(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):In()}}tt();function Pn(t,e={}){let n=e.breaker??dt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){if(!n.canExecute())throw new Le;try{let i=await Promise.resolve(t.invoke(o,s));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Le;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}},breaker:n}}he();fe();X();re();var Ut=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Gn=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ro=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Fn(t,e){let n=De(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=S(ro(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([d])=>{let c=d;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(Z(o),e.onExhausted!=null){let d=e.onExhausted,c=!1,m=!0;o.subscribe(f=>{for(let p of f)if(p[0]===L){let g=p[1];if(c&&m&&g===!1){let h=oo(r.cache??Gn,e.caps);h&&d(h)}m=g,c=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??Gn,c=oo(d,e.caps);return new Ut(c??"budget",e.caps[c??"calls"]??0,ai(d,c??"calls"))}},i=(d,c)=>{let m=t.provider,f={timestamp:G(),wallClock:be(),provider:m,model:c.model,tier:c.tier,usage:d,latencyMs:c.latencyMs,method:c.method,...c.error?{error:c.error}:{}};n.append(f);let p=r.cache??Gn,g=e.pricingFn?p.usd+e.pricingFn(d,{model:c.model,provider:m,tier:c.tier}).total:p.usd;r.emit({calls:p.calls+1,inputTokens:p.inputTokens+Se(d),outputTokens:p.outputTokens+Ue(d),usd:g})},a=()=>{n.clear(),r.emit(ro())},l=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,c){let m=s();if(m)return Promise.reject(m);let f=G(),p=t.invoke(d,c),g=y=>{let v=Math.max(0,(G()-f)/1e6);return i(y.usage??l(),{model:t.model??c?.model??y.model??"",tier:c?.tier??y.tier,latencyMs:v,method:"invoke"}),y};if(p!=null&&typeof p.then=="function")return p.then(g);if(p!=null&&typeof p=="object"&&"content"in p)return g(p);let h=!1;return C([$(p)],([y])=>y==null||h?y:(h=!0,g(y)),{name:"budgetGate/invokeTap"})},async*stream(d,c){let m=s();if(m)throw m;let f=G(),p;try{for await(let g of t.stream(d,c))g.type==="usage"&&(p=g.usage),yield g;i(p??l(),{model:t.model??c?.model??"",tier:c?.tier,latencyMs:Math.max(0,(G()-f)/1e6),method:"stream"})}catch(g){let h=g;throw i(p??l(),{model:t.model??c?.model??"",tier:c?.tier,latencyMs:Math.max(0,(G()-f)/1e6),method:"stream",error:{type:h?.name??"Error",message:h?.message??String(g)}}),g}}},budget:{totals:r,isOpen:o,log:n,reset:a}}}function oo(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function ai(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}re();function li(t,e){let n=e.mock??Ee({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?$(e.enabled):void 0,s;o&&(s=Z(o));let i=()=>r!==void 0?r:!!o?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(u,d){return i()?n.invoke(u,d):t.invoke(u,d)},stream(u,d){return i()?n.stream(u,d):t.stream(u,d)}},dispose:()=>{s&&(s(),s=void 0)}}}function $n(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=ui(e.headers);if(n!==429&&n!==503&&!hi(e.message))return;let o={},s=r("retry-after"),i=ci(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=so(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let l=r("anthropic-ratelimit-tokens-reset");if(l){let f=so(l);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=Ht(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let d=Ht(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let c=Ht(r,"x-ratelimit-remaining-requests"),m=Ht(r,"x-ratelimit-remaining-tokens");if(c!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-c/u),m!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-m/d),o.retryAfterMs==null&&e.message){let f=fi(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:di(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function ui(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function di(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function Ht(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function ci(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function so(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var pi=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function fi(t){let e=pi.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var mi=/rate\s*limit|too\s*many\s*requests|quota|429/i;function hi(t){return!!t&&mi.test(t)}he();fe();X();tt();re();Ne();function Bn(t){let e=new Error(t);return e.name="AbortError",e}function ao(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?$(t.rpm):S(Number.POSITIVE_INFINITY),o=t.tpm!=null?$(t.tpm):S(Number.POSITIVE_INFINITY),s=S(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=S(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=S({},{name:"adaptiveRateLimiter/lastSignal"}),l=C([r,s],([M,j])=>Math.min(Number(M??1/0),Number(j??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=C([o,i],([M,j])=>Math.min(Number(M??1/0),Number(j??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=nt(Number(r.cache??Number.POSITIVE_INFINITY),e),c=nt(Number(o.cache??Number.POSITIVE_INFINITY),e),m=!1,f=!1,p=l.subscribe(M=>{for(let j of M)if(j[0]===L){let z=Number(j[1]);Number.isFinite(z)&&z>0?(d=nt(z,e),m=!1):z===1/0?(d=nt(1/0,e),m=!1):z<=0&&(m=!0)}}),g=u.subscribe(M=>{for(let j of M)if(j[0]===L){let z=Number(j[1]);Number.isFinite(z)&&z>0?(c=nt(z,e),f=!1):z===1/0?(c=nt(1/0,e),f=!1):z<=0&&(f=!0)}}),h=0,y=new ne,v=new ne,b;t.adaptation!=null&&(b=$(t.adaptation).subscribe(j=>{for(let z of j)z[0]===L&&T(z[1])}));function T(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&v.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let j=G()+M.retryAfterMs*1e6;j>h&&(h=j)}}let w=S(0,{name:"adaptiveRateLimiter/pending"}),x=S(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),_=S(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=M=>{w.emit((w.cache??0)+M)},k=()=>{x.emit(d.available()),_.emit(c.available())};async function P(M={}){let j=M.requestCost??1,z=M.tokenCost??0,E=M.signal;R(1);try{for(;;){if(E?.aborted)throw Bn("AdaptiveRateLimiter.acquire aborted");let N=G();if(h>N){let ve=Math.ceil((h-N)/1e6);await zt(ve,E);continue}if(j>0&&m||z>0&&f){await zt(250,E);continue}let V=d,U=c;if(!V.tryConsume(j)){await zt(io(V,j),E);continue}if(!(z>0?U.tryConsume(z):!0)){V.putBack(j),await zt(io(U,z),E);continue}k();return}}finally{R(-1)}}function A(M){M>0?c.tryConsume(M):M<0&&c.putBack(-M),k()}function D(){p(),g(),b?.(),y.cancel(),v.cancel()}return{effectiveRpm:l,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:x,tpmAvailable:_,acquire:P,recordUsage:A,recordSignal:T,dispose:D}}function nt(t,e){if(!Number.isFinite(t)||t===1/0)return ct(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return ct(n,r)}function io(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function zt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Bn("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new ne,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Bn("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}re();function jn(t,e={}){let n=e.limiter??ao({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=$n(i);a&&n.recordSignal(a)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(i,a){let l=r(i,a);await n.acquire({requestCost:1,tokenCost:l,signal:a?.signal});try{let u=t.invoke(i,a),d=await gi(u),c=d.usage??to(),f=Se(c)+Ue(c)-l;return f>0&&n.recordUsage(f),d}catch(u){throw o(u),u}},async*stream(i,a){let l=r(i,a);await n.acquire({requestCost:1,tokenCost:l,signal:a?.signal});try{let u=0;for await(let c of t.stream(i,a))c.type==="usage"&&(u=Se(c.usage)+Ue(c.usage)),yield c;let d=u-l;d>0&&n.recordUsage(d)}catch(u){throw o(u),u}}},limiter:n}}async function gi(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await $t($(t))}tt();var ft=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Vn(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(o=>({name:o.name,adapter:o.adapter,filter:o.filter,breaker:o.breaker?"canExecute"in o.breaker?o.breaker:dt(o.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0;return{provider:"cascading",model:void 0,async invoke(o,s){let i=[],a=new Map;for(let u=0;u<n.length;u++){let d=n[u];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}try{let c=await Promise.resolve(d.adapter.invoke(o,s));return d.breaker?.recordSuccess(),{...c,metadata:{...c.metadata??{},tier:d.name}}}catch(c){a.set(d.name,c),d.breaker?.recordFailure(c);let m=n[u+1];m&&e.onFallback?.(d.name,m.name,c)}}let l={skipped:i,failed:a};throw e.onExhausted?.(l),new ft(l)},async*stream(o,s){let i=[],a=new Map;for(let u=0;u<n.length;u++){let d=n[u];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}let c=!1;try{for await(let m of d.adapter.stream(o,s))c=!0,yield m;d.breaker?.recordSuccess();return}catch(m){if(a.set(d.name,m),d.breaker?.recordFailure(m),c||!r)throw m;let f=n[u+1];f&&e.onFallback?.(d.name,f.name,m)}}let l={skipped:i,failed:a};throw e.onExhausted?.(l),new ft(l)}}}Ne();function Wt(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function lo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Wt()):new Promise((n,r)=>{let o=new ne,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Wt())},e.addEventListener("abort",s,{once:!0}))})}function Kn(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??yi,l=e.retryStreaming??!0,u=(d,c)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,c*3));return r+Math.random()*(g-r)}let m=s==="exp"?r*2**(d-1):r*d,f=Math.min(o,m);if(!i)return f;let p=f*(.5+Math.random());return Math.min(o,p)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,c){if(c?.signal?.aborted)throw Wt();let m,f=r;for(let p=1;p<=n;p++)try{return await Promise.resolve(t.invoke(d,c))}catch(g){if(m=g,p>=n||!a(g,p))throw g;let h=u(p,f);f=h,await lo(h,c?.signal)}throw m},async*stream(d,c){if(c?.signal?.aborted)throw Wt();if(!l){for await(let p of t.stream(d,c))yield p;return}let m,f=r;for(let p=1;p<=n;p++){let g=!1;try{for await(let h of t.stream(d,c))g=!0,yield h;return}catch(h){if(m=h,g||p>=n||!a(h,p))throw h;let y=u(p,f);f=y,await lo(y,c?.signal)}}throw m}}}function yi(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}Ne();var rt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function Un(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=o=>{let s=new AbortController,i=!1,a;o&&(o.aborted?s.abort(o.reason):(a=()=>s.abort(o.reason),o.addEventListener("abort",a,{once:!0})));let l=new ne;return l.start(e,()=>{i=!0,s.abort(new rt(e))}),{signal:s.signal,cancel:()=>{l.cancel(),o&&a&&o.removeEventListener("abort",a)},timedOut:()=>i}},r=(o,s)=>{if(!s||o instanceof rt)throw o;let i=o;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||o?.message==="aborted"){let l=new rt(e);throw l.cause=o,l}throw o};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){let{signal:i,cancel:a,timedOut:l}=n(s?.signal);try{return await Promise.resolve(t.invoke(o,{...s,signal:i}))}catch(u){return r(u,l())}finally{a()}},async*stream(o,s){let{signal:i,cancel:a,timedOut:l}=n(s?.signal);try{for await(let u of t.stream(o,{...s,signal:i}))yield u}catch(u){r(u,l())}finally{a()}}}}function bi(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=jn(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Fn(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Pn(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Un(r,e.timeoutMs)),e.retry&&(r=Kn(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=Vn([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return n.adapter=r,n}function vi(){return Ee()}X();fe();ke();X();re();function uo(t){return{describeKind:"derived",...t}}function Ti(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,l=!1;for(let u of i)u[0]!==Oe&&(u[0]===L?e.emit(u[1]):u[0]===F?a=!0:u[0]===O?(l=!0,e.down([u])):(u[0]===Y||u[0]===H)&&e.down([u]));l?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function me(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ie([t],(i,a,l)=>{if(l.terminalDeps[0]!=null&&l.terminalDeps[0]!==!0){s();return}if(l.terminalDeps[0]===!0){o=!0,r||a.down([[F]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=Ti($(e(u[u.length-1])),a,()=>{s(),o&&a.down([[F]])}),{deactivate:()=>{s(),o=!1}}},{...uo(n),completeWhenDepsComplete:!1})}function co(t,e,n){return pe(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===L)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===F&&r.down([[F]])});return()=>{o()}},uo(n))}re();function wi(t,e,n){let r=$(e);return me(r,s=>{if(!s||s.length===0)return S(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}ke();re();fe();re();Ne();re();function ot(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function q(t,e){return ot("ai",t,e)}function xi(t){return t!=null&&typeof t.then=="function"}function ki(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function _i(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ri=3e4;function po(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ri;return new Promise((r,o)=>{let s=new ne,i=t.subscribe(a=>{for(let l of a){if(l[0]===L){s.cancel(),i(),r(l[1]);return}if(l[0]===O){s.cancel(),i(),o(l[1]);return}if(l[0]===F){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function He(t){return xi(t)?He(await t):ki(t)?po(t):_i(t)?po($(t)):t}function ze(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Mi(t,e){let n=$(t),r=e?.refreshTrigger!=null?$(e.refreshTrigger):null;return r==null?ie([n],(o,s,i)=>{if(i.store.emitted===!0)return;let l=o[0],u=l!=null&&l.length>0?l.at(-1):i.prevData[0];if(u!==void 0)return i.store.emitted=!0,s.emit(u),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:q("frozen_context")}):ie([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let u=o[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:q("frozen_context")})}X();function Ni(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Ei(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,l=C(e,d=>{if(d.some(f=>f==null))return[];let c=typeof n=="string"?n:n(...d);if(!c)return[];let m=[];return r?.systemPrompt&&m.push({role:"system",content:r.systemPrompt}),m.push({role:"user",content:c}),m},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:q("prompt_node"),initial:[]});return me(l,d=>{if(!d||d.length===0)return S(null);let c=i?JSON.stringify(d.map(f=>[f.role,f.content])):"";if(a?.has(c))return S(a.get(c));async function m(f){try{let p=await new Promise((y,v)=>{let b=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});b&&typeof b.then=="function"?b.then(y,v):b&&typeof b.subscribe=="function"?y(b.cache):y(b)}),g=Ni(p),h;return o==="json"?h=JSON.parse(ze(g)):h=g,a?.set(c,h),h}catch(p){if(f>0)return m(f-1);throw p}}return m(s)})}X();re();At();ut();fe();ut();ke();function qt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function Ai(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Si(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Hn(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof ae&&(s=Ai(t),i=t._deps.map(u=>u.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let l=t instanceof ae?t._guard:void 0;if(o){let u={...Si(t)};if(l!=null&&u.access===void 0&&(u.access=bn(l)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let c of r)c in u&&(d[c]=u[c]);a.meta=d}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&l!=null&&(a.guard=bn(l)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}X();var le={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Oi=Symbol.for("sizeof");function fo(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Ci(s,e,n,r)}return o}function Ci(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return le.number;case"boolean":return le.boolean;case"string":return le.string+t.length*2;case"bigint":return le.bigint+Li(t);case"symbol":return le.symbol;case"function":return e.has(t)?0:(e.add(t),le.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Oi];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return le.date;if(s instanceof RegExp)return le.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return le.error+u+d}if(typeof URL<"u"&&s instanceof URL)return le.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return le.promise;if(s instanceof WeakMap)return le.weakmap;if(s instanceof WeakSet)return le.weakset;if(s instanceof Map){let u=le.map;for(let[d,c]of s)u+=le.mapEntry,r.push(d),r.push(c);return u}if(s instanceof Set){let u=le.set;for(let d of s)u+=le.setEntry,r.push(d);return u}if(Array.isArray(s)){let u=le.array+s.length*8;for(let d of s)r.push(d);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=le.object,l=Object.keys(s);for(let u of l){a+=le.string+u.length*2;try{r.push(s[u])}catch{}}return a}function Li(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function mo(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Jt(e,n,"no-such-from");if(!s)return Jt(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Di(t,e,r);if(u!=null)return u}let l=Yt(e,t.nodes[e],0,r);return Xt(e,n,[l])}if(i===0)return Jt(e,n,"no-path");let a=ho(t,e,n,i);return a.found?Xt(e,n,go(t,a.pathOrder,r)):Jt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function ho(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,l=!1;for(;a<s.length;){let c=s[a++];if(c.path===e)break;if(r!=null&&c.depth>=r){let g=t.nodes[c.path];g?.deps&&g.deps.length>0&&(l=!0);continue}let m=t.nodes[c.path];if(m==null)continue;let f=m.deps??[],p=new Map;for(let g=0;g<f.length;g++){let h=f[g];if(!h)continue;let y=p.get(h);y==null&&(y=[],p.set(h,y)),y.push(g)}for(let[g,h]of p)i.has(g)||(i.add(g),o.set(g,{from:c.path,depIndices:h}),s.push({path:g,depth:c.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:l};let u=[{path:e}],d=e;for(;d!==n;){let c=o.get(d);if(c==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=c.depIndices,u.push({path:c.from}),d=c.from}return{found:!0,pathOrder:u,truncated:!1}}function Di(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=Yt(e,r,0,n);a.dep_index=s[0];let l=Yt(e,r,1,n);return Xt(e,e,[a,l])}let i=null;for(let a=0;a<o.length;a++){let l=o[a];if(!l||l===e)continue;let u=ho(t,l,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:Xt(e,e,go(t,i.pathOrder,n))}function go(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=Yt(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Yt(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function Xt(t,e,n){return yo(t,e,!0,"ok",n)}function Jt(t,e,n){return yo(t,e,!1,n,[])}function yo(t,e,n,r,o){let s=Ii(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Ii(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let l=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(l),"value"in i&&s.push(` value: ${Pi(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
24
- `)}function Pi(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}At();Me();he();ut();fe();ke();X();re();Ne();var mt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};yn();function zn(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function Qt(t){let e=0;for(let n of t)e+=zn(n.codePointAt(0));return e}function bo(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=zn(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=zn(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Gi={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},Fi={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function xo(t,e){let n=e.charset==="ascii"?Fi:Gi,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Bi(s,i,n,a);for(let a of t.boxes)$i(s,i,n,a,e.labelOf(a.id));return s.map(a=>Ui(a.join(""))).join(`
25
- `)}function $i(t,e,n,r,o){let{x:s,y:i,w:a,h:l}=r;if(a<2||l<2){l>0&&vo(t,e,s,i,a,o);return}Ie(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Ie(t,e,d,i,n.boxH);Ie(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+l-1;d+=1){Ie(t,e,s,d,n.boxV);for(let c=s+1;c<s+a-1;c+=1)ko(t,e,c,d," ","empty");Ie(t,e,s+a-1,d,n.boxV)}Ie(t,e,s,i+l-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Ie(t,e,d,i+l-1,n.boxH);Ie(t,e,s+a-1,i+l-1,n.boxBR);let u=i+Math.floor(l/2);vo(t,e,s+1,u,a-2,o)}function Ie(t,e,n,r,o){ko(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function ko(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function vo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let l of s){let u=Qt(l);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=l,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Bi(t,e,n,r){let o=r.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)ji(t,e,n,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let u=o[l-1],d=o[l],c=o[l+1],m=Vi(u,d,c,n);m&&wo(t,e,d.x,d.y,m,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Ki(i,s,n);a&&wo(t,e,s.x,s.y,a,"arrow")}function ji(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let l=i;l<=a;l+=1)To(t,e,l,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let l=i;l<=a;l+=1)To(t,e,s,l,n,"v")}}}function To(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function wo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Vi(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let l=t.x<e.x,u=n.y>e.y;return l&&u?r.cornerTR:l&&!u?r.cornerBR:!l&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Ki(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Ui(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Mo(t){let e=Hi(t);zi(e),Wi(e),qi(e),Ji(e,t);let n=Qi(e,t),{width:r,height:o}=ea(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function Hi(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function zi(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(e.get(a.id)??0)-1;e.set(a.id,l),l<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Wi(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(c=>c!==s),a.in=a.in.filter(c=>c!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(c=>c!==s),a.in=a.in.filter(c=>c!==s);let u=i;for(let c=1;c<l;c+=1){let m=`__virt_${o++}__`,f={id:m,isVirtual:!0,layer:i.layer+c,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(m,f),n[f.layer].push(f);let p={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:m,hopIndex:c-1,chainLen:l};u.out.push(p),f.in.push(p),r.push(p),u=f}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:l-1,chainLen:l};u.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function qi(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)_o(t,t.layers[r],"in"),Zt(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)_o(t,t.layers[r],"out"),Zt(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Ro(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],Zt(s),Ro(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],Zt(s))}}if(!r)break}}function _o(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let l of s){let u=t.nodes.get(n==="in"?l.fromId:l.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function Zt(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Ro(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let l of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?l.fromId:l.toId)?.order??0;(e.order<n.order&&u>d||e.order>n.order&&u<d)&&(i+=1)}return i}function Ji(t,e){e.direction==="LR"?Yi(t,e):Xi(t,e)}function Yi(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}No(t,e,"y")}function Xi(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}No(t,e,"x")}function No(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let c=s===0?d.in:d.out;if(c.length===0)continue;let m=[];for(let p of c){let g=t.nodes.get(s===0?p.fromId:p.toId);if(!g)continue;let h=n==="y"?g.y:g.x;m.push(h+Math.floor(r(g)/2))}if(m.length===0)continue;m.sort((p,g)=>p-g);let f=m[Math.floor(m.length/2)];l.set(d.id,f-Math.floor(r(d)/2))}let u=0;for(let d of a){let c=l.get(d.id),m=n==="y"?d.y:d.x,p=Math.max(c??m,u);n==="y"?d.y=p:d.x=p,u=p+r(d)+o}}}}function Qi(t,e){let n=new Map;for(let u of t.hops){let d=n.get(u.chainId);d?d.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((d,c)=>d.hopIndex-c.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let d=t.layers[u],c=t.layers[u+1],m=0;for(let R of d)m=Math.max(m,o(R)+s(R));let f=Number.POSITIVE_INFINITY;for(let R of c)f=Math.min(f,o(R));let p=Number.isFinite(f)?f-1:m,g=Math.max(1,p-m+1),h=[];for(let R of d)for(let k of R.out)h.push(k);h.sort((R,k)=>{let P=i(t.nodes.get(R.fromId)),A=i(t.nodes.get(k.fromId));if(P!==A)return P-A;let D=i(t.nodes.get(R.toId)),M=i(t.nodes.get(k.toId));return D-M});let y=[],v=new Map;for(let R of h){let k=i(t.nodes.get(R.fromId)),P=i(t.nodes.get(R.toId)),A=Math.min(k,P),D=Math.max(k,P),M=-1;for(let j=0;j<y.length;j+=1){let z=y[j],E=!0;for(let N of z)if(N.lo<=D&&A<=N.hi){E=!1;break}if(E){z.push({lo:A,hi:D}),M=j;break}}M<0&&(y.push([{lo:A,hi:D}]),M=y.length-1),v.set(R,M)}let b=y.length,T=g>=Math.max(3,b+2),w=T?m+1:m,x=T?p-1:p,_=Math.max(1,x-w+1);for(let R of h){let k=v.get(R),P;if(b<=1)P=w+Math.floor(_/2);else{let A=(_-1)/(b-1);P=w+Math.floor(k*A)}a.set(R,Math.max(m,Math.min(p,P)))}}let l=[];for(let[,u]of n){let d=[];for(let m=0;m<u.length;m+=1){let f=u[m],p=t.nodes.get(f.fromId),g=t.nodes.get(f.toId),h=a.get(f),y=p.isVirtual?o(p):o(p)+s(p),v=g.isVirtual?o(g):o(g)-1,b=i(p),T=i(g);m===0&&en(d,r,y,b),b!==T&&(en(d,r,h,b),en(d,r,h,T)),en(d,r,v,T)}let c=u[0];l.push({from:c.chainFrom,to:c.chainTo,points:Zi(d)})}return l}function en(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Zi(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function ea(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var ta=24,na=4,ra=1,oa=3;function Eo(t,e){let n=sa(e.direction),r=Math.max(3,e.maxLabelWidth??ta),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,u=new Map;for(let f of s){let p=bo(f,r);l.set(f,p),u.set(f,Qt(p)+4)}let d=Mo({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>oa,layerGap:na,nodeGap:ra,direction:n}),c=xo(d,{charset:o,labelOf:f=>l.get(f)??f}),m=e.logger;return m&&m(c),c}function sa(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}ke();function Ao(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[m,f]of o)i.set(m,f);let a=[];for(let[m,f]of Object.entries(r.nodes)){let p=i.get(m),g=p instanceof ae?p:null,h=g?fo(g.cache):0,y=g?g._sinkCount:0,v=f.deps?.length??0,b=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:m,type:f.type,status:f.status??"unknown",valueSizeBytes:h,subscriberCount:y,depCount:v,isOrphanEffect:b,orphanKind:T})}let l=a.reduce((m,f)=>m+f.valueSizeBytes,0),u=(m,f)=>[...a].sort(f??((p,g)=>g[m]-p[m])).slice(0,n),d=a.filter(m=>m.orphanKind!=null),c=a.filter(m=>m.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:l,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:d,orphanEffects:c}}var ee="::",ye="__meta__",We=1;function So(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function ia(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
26
- `)}function Oo(t){if(t.version!==We)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${We})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function aa(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,l=s.constructor;if(a!==l)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let m=s;if(o.length!==m.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],m[f]))return!1;return!0}if(o instanceof Map){let m=s;if(o.size!==m.size)return!1;for(let[f,p]of o)if(!m.has(f)||!r(p,m.get(f)))return!1;return!0}if(o instanceof Set){let m=s;if(o.size!==m.size)return!1;for(let f of o){let p=!1;for(let g of m)if(r(f,g)){p=!0;break}if(!p)return!1}return!0}if(ArrayBuffer.isView(o)){let m=o,f=s;if(m.length!==f.length)return!1;for(let p=0;p<m.length;p++)if(m[p]!==f[p])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let c=new Set(d);for(let m of u)if(!c.has(m)||!r(o[m],s[m]))return!1;return!0};return r(t,e)}function qn(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(qn);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=qn(e[o]);return r}function la(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ua(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function da(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Lo(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function Do(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function ca(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(qn(i),null,e.indent??2);return e.logger?.(a),a}function pa(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${nn(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
27
- `);return e.logger?.(s),s}function Io(t,e){let n=Do(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${la(i)}"]`)}for(let[i,a]of Lo(t)){let l=o.get(i),u=o.get(a);!l||!u||s.push(` ${l} --> ${u}`)}return s.join(`
28
- `)}function fa(t,e){let n=Io(t,e);return Po(n)}function Po(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function ma(t,e){let n=Do(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${da(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${ua(i)}"`)}for(let[i,a]of Lo(t)){let l=o.get(i),u=o.get(a);!l||!u||s.push(`${l} -> ${u}`)}return s.join(`
29
- `)}function ha(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tn(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=ha(r)}return e+="$",new RegExp(e)}var ga={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},ya={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function nn(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function ba(t){return t==="none"?ya:t==="ansi"||t==null?ga:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Co(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function va(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function Wn(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(ee))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${ee}' (path separator)`);if(t===ye)throw new Error(`Graph "${e}": ${n} name "${ye}" is reserved for meta companion paths`);va(t,e,n)}function Ta(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(ee);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function wa(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Go(t){for(let e of t._mounts.values())Go(e);for(let e of t._nodes.values())try{e.down([[ce]],{internal:!0})}catch{}}var ue=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(ee))throw new Error(`Graph name must not contain '${ee}' (got "${e}")`);if(e===ye)throw new Error(`Graph name "${ye}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Ze,this._traceRing=new mt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=pe(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(Wn(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:G()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof ae&&n._applyVersioning(e)}remove(e){Wn(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${ee}${ye}${ee}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${ee}`)),this._mounts.delete(e),n._parent=void 0,Go(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[ce]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=tn(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(ee))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);se(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Te]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[O,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[F]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[l,u]of this._nodes)r.set(u,l);let a=[];for(let[l,u]of this._nodes)if(u instanceof ae)for(let d of u._deps){let c=r.get(d.node);c!=null&&a.push([c,l])}return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:l[1]<u[1]?-1:l[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,l]of o)s.set(l,a);let i=[];for(let[a,l]of o)if(l instanceof ae)for(let u of l._deps){let d=s.get(u.node);d!=null&&i.push([d,a])}return i.sort((a,l)=>a[0]<l[0]?-1:a[0]>l[0]?1:a[1]<l[1]?-1:a[1]>l[1]?1:0),i}mount(e,n){if(Wn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=Ta(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===ye)return this._resolveMetaChainFromNode(s,o,n.join(ee));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(ee)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(ee))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==ye)throw new Error(`Graph "${this.name}": expected ${ye} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ye} in "${r}"`);let a=i[s+1],l=o.meta[a];if(!l)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=l,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let l of this._mounts.values())l._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=wa(e,this.config);for(let l of[...this._nodes.keys()].sort()){let u=this._nodes.get(l);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(d){if(d instanceof we)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(l){if(l instanceof we)throw l;s.push(l)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=qt(e?.detail,e?.fields),s=e?.format==="spec",i=s?qt("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[x,_]of a)l.set(_,x);let u=[];{let x=a.map(([,k])=>k),_=new Set(l.values()),R=0;for(;x.length>0;){let k=x.shift();if(k instanceof ae)for(let P of k._deps){let A=P.node;if(l.has(A))continue;let D=A.name??"",M=D;if(!M||_.has(M))if(D){let j=2;for(;_.has(`${D}#${j}`);)j++;M=`${D}#${j}`}else for(M=`__internal__/${R++}`;_.has(M);)M=`__internal__/${R++}`;l.set(A,M),_.add(M),u.push([M,A]),x.push(A)}}}let d=[...a,...u],c={};for(let[x,_]of d){if(n!=null&&!_.allowsObserve(n))continue;let R=Hn(_,i),k=_ instanceof ae?_._deps.map(M=>l.get(M.node)??M.node.name??""):[],{name:P,...A}=R,D={...A,deps:k};if(!s){let M=this._annotations.get(x);M!=null&&(D.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(x,D):M(D)))continue}else{let M=!0;for(let[j,z]of Object.entries(r)){let E=j==="deps_includes"?"depsIncludes":j==="meta_has"?"metaHas":j;if(E==="depsIncludes"){if(!D.deps.includes(String(z))){M=!1;break}continue}if(E==="metaHas"){if(!Object.hasOwn(D.meta??{},String(z))){M=!1;break}continue}if(D[E]!==z){M=!1;break}}if(!M)continue}c[x]=D}let m=new Set(Object.keys(c)),f=[];for(let[x,_]of d)if(_ instanceof ae)for(let R of _._deps){let k=l.get(R.node);k!=null&&f.push([k,x])}f.sort((x,_)=>x[0]<_[0]?-1:x[0]>_[0]?1:x[1]<_[1]?-1:x[1]>_[1]?1:0);let p=f.map(([x,_])=>({from:x,to:_}));(n!=null||r!=null)&&(p=p.filter(x=>m.has(x.from)&&m.has(x.to)));let g=this._collectSubgraphs(""),h=n!=null||r!=null?g.filter(x=>{let _=`${x}${ee}`;return[...m].some(R=>R===x||R.startsWith(_))}):g,y=this,v=e,b={name:this.name,nodes:c,edges:p,subgraphs:h,expand(x){let _={...v,format:void 0};return Array.isArray(x)?(_.fields=x,_.detail=void 0):(_.detail=x,_.fields=void 0),y.describe(_)}},T=e??{},w=T.format;return w==="json"?ca(b,T):w==="pretty"?pa(b,T):w==="mermaid"?Io(b,T):w==="mermaid-url"?fa(b,T):w==="d2"?ma(b,T):w==="ascii"?Eo(b,T):b}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${ee}`))}return n}resourceProfile(e){return Ao(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Jn(this.describe(),e,n,{...r,withDetail:!0}):Jn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,l]of Object.entries(o.nodes))l.lastMutation!=null&&i.set(a,l.lastMutation);return mo(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=S(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=()=>{a||l||(a=!0,lt(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(h=>{let y=h.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),c=[],m=new WeakSet,f=h=>{if(m.has(h)||l)return;m.add(h);let y=h.topology.subscribe(v=>{for(let b of v){if(b[0]!==L)continue;let T=b[1];if(u(),T.kind==="added"&&T.nodeKind==="mount"){let w=h._mounts.get(T.name);w!=null&&f(w)}}});c.push(y);for(let v of h._mounts.keys()){let b=h._mounts.get(v);b!=null&&f(b)}};f(this);let p;try{p=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(h,y)=>h===y})}catch(h){d();for(let y of c)y();throw i.dispose(),h}let g=Z(p);return{node:p,dispose(){l=!0,d();for(let h of c)h();c.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let o=0,s=S(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=i.onEvent(f=>{let p=f.type;p!=="data"&&p!=="error"&&p!=="complete"&&p!=="teardown"||a||l||(a=!0,lt(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},c;try{c=C([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,p)=>f.found===p.found&&f.reason===p.reason&&f.steps.length===p.steps.length&&xa(f.steps,p.steps)})}catch(f){throw u(),i.dispose(),f}let m=Z(c);return{node:c,dispose(){l=!0,u(),i.dispose(),m()}}}_pathsMatching(e){let n=tn(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${ee}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${ee}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${ee}${ye}${ee}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Co(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,c=this.resolve(d);if(a!=null&&!c.allowsObserve(a))throw new we({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,c]],s,"one"):{subscribe(m){return c.subscribe(m)},up(m){try{c.up?.(m)}catch(f){if(f instanceof we)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,c)=>d[0]<c[0]?-1:d[0]>c[0]?1:0);let u=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let c=u.map(([m,f])=>f.subscribe(p=>{d(m,p)}));return()=>{for(let m of c)m()}},up:(d,c)=>{try{this.resolve(d).up?.(c)}catch(m){if(m instanceof we)return;throw m}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,c)=>d[0]<c[0]?-1:d[0]>c[0]?1:0);let l=i.actor,u=l==null?a:a.filter(([,d])=>d.allowsObserve(l));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",l=this.config.inspectorEnabled,u=(s||i)&&l,d=n.maxEvents,c=d!=null&&d>0?new mt(d):null,m=[],f=new Set,p={},g=new Set,h=0,y=0,v=0,b=0,T=0,w=0,x=!1,_=!1,R=0,k=new Map,P=new Map,A=new Map,D=I=>{c?c.push(I):m.push(I);for(let K of f)K(I)},M=()=>o?{timestamp_ns:G(),in_batch:St(),batch_id:R}:{},j=(I,K)=>{if(!(!u||!(I instanceof ae)))return I._setInspectorHook(te=>{if(te.kind==="dep_message")k.set(I,te.depIndex);else if(te.kind==="run"){let de=te.batchData.map((B,oe)=>B!=null&&B.length>0?B.at(-1):te.prevData[oe]);P.set(I,de);let W=te.batchData.map(B=>B!=null?[...B]:void 0);A.set(I,W),i&&D({type:"derived",path:K,dep_values:de,dep_batches:W,...M()})}})},z=I=>{let K=k.get(I),te=P.get(I);if(!s||te==null)return{};let W=(K!=null&&K>=0&&I instanceof ae?I._deps[K]:void 0)?.node,B=W?.v,oe=A.get(I);return{trigger_dep_index:K,trigger_dep_name:W?.name,...B!=null?{trigger_version:{id:B.id,version:B.version}}:{},dep_values:[...te],...oe!=null?{dep_batches:oe}:{}}},E=[],N=[];for(let[I,K]of e){let te=j(K,I);te&&E.push(te),N.push(K.subscribe(de=>{R++;for(let W of de){let B=W[0],oe=M();if(B===L){p[I]=W[1];let Re=K instanceof ae?K.lastMutation?.actor??Ye:Ye;D({type:"data",path:I,data:W[1],actor:Re,...oe,...z(K)})}else if(a)B===Y?h++:B===H?y++:B===Te?v++:B===xe?b++:B===Ae?T++:B===ce?w++:B===F&&!g.has(I)?x=!0:B===O&&(_=!0,g.add(I));else if(B===Y)h++,D({type:"dirty",path:I,...oe});else if(B===H)y++,D({type:"resolved",path:I,...oe,...z(K)});else if(B===Te)v++,D({type:"invalidate",path:I,...oe});else if(B===xe)b++,D({type:"pause",path:I,lockId:W[1],...oe});else if(B===Ae)T++,D({type:"resume",path:I,lockId:W[1],...oe});else if(B===F)g.has(I)||(x=!0),D({type:"complete",path:I,...oe});else if(B===O){_=!0,g.add(I);let Re=K instanceof ae?K.lastMutation?.actor??Ye:Ye;D({type:"error",path:I,data:W[1],actor:Re,...oe})}else B===ce&&(w++,D({type:"teardown",path:I,...oe}))}}))}let V=!1,U=()=>{if(!V){V=!0;for(let I of N)I();for(let I of E)I();for(let I of J)I({value:void 0,done:!0});J.length=0}},Q=[],J=[];f.add(I=>{let K=J.shift();K?K({value:I,done:!1}):Q.push(I)});let ve={get values(){return p},get dirtyCount(){return h},get resolvedCount(){return y},get invalidateCount(){return v},get pauseCount(){return b},get resumeCount(){return T},get teardownCount(){return w},get events(){return c?c.toArray():[...m]},get anyCompletedCleanly(){return x},get anyErrored(){return _},get completedWithoutErrors(){return x&&!_},onEvent(I){return f.add(I),()=>f.delete(I)},dispose:U,expand(I){U();let K={...n};return typeof I=="string"?K.detail=I:Object.assign(K,I),r(Co(K))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):V?Promise.resolve({value:void 0,done:!0}):new Promise(I=>J.push(I))},return(){return U(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ve,n),ve}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(p=>console.log(p)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:p=>(s==null||s.has(p))&&(i==null||!i.has(p)),l=ba(n.theme),u=r==="stage-log"?G():0,d=p=>p==null?"":n.stageLabels?.[p]??p,c=(p,g)=>p.length>g?`${p.slice(0,g-1)}\u2026`:p,m=p=>p.type==="data"||p.type==="error"?c(nn(p.data),120):"",f=p=>{if(r==="stage-log"){let _=(G()-u)/1e9,R=d(p.path).padEnd(9);if(p.type==="data"){let k=m(p);return`[${_.toFixed(3)}s] ${R} \u2190${k?` ${k}`:""}`}if(p.type==="error"){let k=m(p);return`[${_.toFixed(3)}s] ${R} \u2717${k?` ${k}`:""}`}return p.type==="complete"?`[${_.toFixed(3)}s] ${R} \u25A0 complete`:`[${_.toFixed(3)}s] ${R} ${p.type}`}if(r==="json")try{return JSON.stringify(p)}catch{return JSON.stringify({type:p.type,path:p.path,data:"[unserializable]"})}let g=l[p.type]??"",h=p.path?`${l.path}${p.path}${l.reset} `:"",y=p.type==="data"||p.type==="error",v=p.type==="pause"||p.type==="resume",b=y?` ${nn(p.data)}`:v?` ${nn(p.lockId)}`:"",T=p.type==="data"||p.type==="resolved"||p.type==="derived"?p:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",x=p.in_batch?" [batch]":"";return`${h}${g}${p.type.toUpperCase()}${l.reset}${b}${w}${x}`};e.onEvent(p=>{a(p.type)&&o(f(p),p)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){So(this._disposers,this.name),this.signal([[ce]],{internal:!0}),So(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:l,guard:u,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return yr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Ze,{codec:o,codecVersion:s,payload:i}=br(e,r);return o.decode(i,s)}restore(e,n){if(Oo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>tn(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let l=this.tryResolve(s)?.v;if(l!=null&&l.id===i.v.id&&l.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Oo(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((p,g)=>{let h=p.split(ee).length,y=g.split(ee).length;return h!==y?h-y:p<g?-1:p>g?1:0})){let p=f.split(ee),g=s;for(let h of p)g._mounts.has(h)||g.mount(h,new t(h)),g=g._mounts.get(h)}let i=o?Object.entries(o).map(([f,p])=>({re:tn(f),factory:p})):[],a=f=>{for(let p of i)if(p.re.test(f))return p.factory},l=f=>{let p=f.split(ee),g=p.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let h=s;for(let y of p){let v=h._mounts.get(y);if(!v)throw new Error(`unknown mount "${y}" in path "${f}"`);h=v}return[h,g]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${ee}${ye}${ee}`)).sort((f,p)=>f[0]<p[0]?-1:f[0]>p[0]?1:0),d=new Map(u),c=new Map,m=!0;for(;d.size>0&&m;){m=!1;for(let[f,p]of[...d.entries()]){let g=p?.deps??[];if(!g.every(w=>c.has(w)))continue;let[h,y]=l(f),v={...p?.meta??{}},b=a(f),T;if(p?.type==="state")T=S(p.value,{meta:v});else{if(b==null)continue;T=b(y,{path:f,type:p.type,value:p.value,meta:v,deps:g,resolvedDeps:g.map(w=>c.get(w))})}h.add(T,{name:y}),c.set(f,T),d.delete(f),m=!0}}if(d.size>0){let f=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,d)=>{if(u.disposed)return;let c=ia(d.nodes);if(u.lastSnapshot!=null&&c!==""&&c===u.lastFingerprint)return;let m=u.seq+1,f=be(),h=u.lastSnapshot==null||m%u.compactEvery===0?{mode:"full",snapshot:d,seq:m,timestamp_ns:f,format_version:We}:{mode:"diff",diff:Fo(u.lastSnapshot,d),seq:m,timestamp_ns:f,format_version:We};if(u.tier.filter&&!u.tier.filter(this.name,h))return;let y;try{y=u.tier.save(this.name,h)}catch(v){n.onError?.(v,u.tier);return}if(y&&typeof y.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=m,u.lastSnapshot=d,u.lastFingerprint=c)},w=>{n.onError?.(w,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=m,u.lastSnapshot=d,u.lastFingerprint=c},s=(u,d)=>{try{o(u,d)}catch(c){n.onError?.(c,u.tier)}},i=(u,d)=>{if(!d.some(p=>{let g=this.config.messageTier(p[0]);return g>=3&&g<5}))return;if(n.filter){let p=this.tryResolve(u);if(p==null)return;let g=Hn(p,qt("standard"));if(!n.filter(u,g))return}let m,f=()=>(m==null&&(m=this.snapshot()),m);for(let p of r)p.disposed||(p.debounceMs===0?s(p,f()):(p.timer==null&&(p.timer=new ne),p.timer.start(p.debounceMs,()=>{p.disposed||s(p,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(c=>{let m=this.tryResolve(c);return m==null?()=>{}:m.subscribe(f=>i(c,f))});a=()=>{for(let c of d)c()}}else a=this.observe().subscribe((u,d)=>i(u,d));let l=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(l)};return this._storageDisposers.add(l),{dispose:l}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===We&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(l){r?.onError?.(l,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===We&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(l){r?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:G(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(v=>!r.has(v)).sort(),i=[...r].filter(v=>!o.has(v)).sort(),a=[],l=[];for(let v of r){if(!o.has(v))continue;let b=e.nodes[v],T=n.nodes[v],w=b.v,x=T.v;w!=null&&x!=null&&w.id===x.id&&w.version!==x.version&&l.push({path:v,id:w.id,from:w.version,to:x.version});let _=w!=null&&x!=null&&w.id===x.id&&w.version===x.version;for(let R of["type","status","sentinel"]){let k=b[R],P=T[R];k!==P&&a.push({path:v,field:R,from:k,to:P})}if(!_)for(let R of["value","meta"]){let k=b[R],P=T[R];aa(k,P)||a.push({path:v,field:R,from:k,to:P})}}let u=v=>`${v.from} ${v.to}`,d=new Set(e.edges.map(u)),c=new Set(n.edges.map(u)),m=n.edges.filter(v=>!d.has(u(v))),f=e.edges.filter(v=>!c.has(u(v))),p=new Set(e.subgraphs),g=new Set(n.subgraphs),h=[...g].filter(v=>!p.has(v)).sort(),y=[...p].filter(v=>!g.has(v)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:m,edgesRemoved:f,subgraphsAdded:h,subgraphsRemoved:y}}};function Fo(t,e){let n=ue.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function Jn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,l=new Map,u=new Map,d=new Set;for(let[b,T]of Object.entries(t.nodes)){if(!b)continue;d.add(b);let w=T.deps??[];i.set(b,w);for(let x of w)x&&(d.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(b))}for(let b of t.edges){if(b==null||typeof b!="object")continue;let T=typeof b.from=="string"?b.from:"",w=typeof b.to=="string"?b.to:"";!T||!w||(d.add(T),d.add(w),u.has(T)||u.set(T,new Set),u.get(T).add(w),l.has(w)||l.set(w,new Set),l.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let c=r.both===!0,m=b=>{if(c){let _=i.get(b)??[],R=l.get(b),k=a.get(b),P=u.get(b),A=[..._];return R&&A.push(...R),k&&A.push(...k),P&&A.push(...P),A}if(n==="upstream"){let _=i.get(b)??[],R=l.get(b);return R?[..._,...R]:_}let T=a.get(b),w=u.get(b),x=T?[...T]:[];return w&&x.push(...w),x},f=new Set([e]),p=new Map,g=[{path:e,depth:0}],h=0,y=!1;for(;h<g.length;){let b=g[h++];if(s!=null&&b.depth>=s){m(b.path).length>0&&(y=!0);continue}for(let T of m(b.path))!T||f.has(T)||(f.add(T),p.set(T,b.depth+1),g.push({path:T,depth:b.depth+1}))}let v=[...p.keys()].sort((b,T)=>b<T?-1:b>T?1:0);return r.withDetail?{paths:v,depths:p,truncated:y}:v}function xa(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}function $o(t,e){return ot("messaging",t,e)}var Yn=class extends ue{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=De([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=C([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:$o("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Z(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:$o("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Z(this.hasLatest)),this.addDisposer(()=>{this.events.down([[F]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}};function Xn(t,e){return new Yn(t,e)}Me();fe();ke();X();function ka(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=_a(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function _a(t,e){let n=t.describe(),r=`::${ye}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Ra(t,e,n,r){t.add(n,{name:e})}function Ma(t,e){return ot("orchestration",t,e)}function Bo(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=ka(t,n),a=S([],{name:"pending",equals:()=>!1}),l=S(s,{name:"isOpen"}),u=C([a],([w])=>w.length,{name:"count"}),d=[],c=!1,m=s,f=l.subscribe(w=>{for(let x of w)x[0]===L&&(m=x[1])});function p(){a.emit([...d])}function g(w){d.push(w),d.length>o&&d.shift(),p()}function h(w){let x=d.splice(0,w);return p(),x}function y(w){if(c)throw new Error(`gate: ${w}() called after gate was torn down`)}let v=ie([i.node],(w,x,_)=>{let R=_.terminalDeps[0];if(R!==void 0){c=!0,d=[],p(),x.down(R===!0?[[F]]:[[O,R]]);return}let k=w[0];if(k==null||k.length===0){x.down([[H]]);return}for(let P of k)m?x.emit(P):(g(P),x.down([[H]]))},{name:e,describeKind:"derived",meta:Ma("gate",r?.meta)}),b={node:v,pending:a,count:u,isOpen:l,approve(w=1){y("approve");let x=h(w);for(let _ of x){if(c)break;v.emit(_)}},reject(w=1){y("reject"),h(w)},modify(w,x=1){y("modify");let _=[...d],R=h(x);for(let k=0;k<R.length&&!c;k++)v.emit(w(R[k],k,_))},open(){y("open"),se(()=>{l.emit(!0);let w=h(d.length);for(let x of w){if(c)break;v.emit(x)}})},close(){y("close"),l.emit(!1)}};t.addDisposer(u.subscribe(()=>{})),t.addDisposer(f),Ra(t,e,v,i.path?[i.path]:[]);let T=new ue(`${e}_state`);return T.add(a,{name:"pending"}),T.add(l,{name:"isOpen"}),T.add(u,{name:"count"}),t.mount(`${e}_state`,T),b}function Na(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Xn(`${o}/stream`),a=C(e,d=>{if(d.some(f=>f==null))return[];let c=typeof n=="string"?n:n(...d);if(!c)return[];let m=[];return r?.systemPrompt&&m.push({role:"system",content:r.systemPrompt}),m.push({role:"user",content:c}),m}),l=me(a,d=>{let c=d;if(!c||c.length===0)return S(null);let m=new AbortController;async function*f(){let p="",g=0;try{for await(let y of t.stream(c,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:m.signal})){if(y.type!=="token")continue;let v=y.delta;p+=v,i.publish({source:o,token:v,accumulated:p,index:g++})}let h;if(s==="json")try{h=JSON.parse(ze(p))}catch{h=null}else h=p;yield h}finally{m.abort()}}return $(f())}),u=Z(l);return{output:l,stream:i,dispose:()=>{u(),i.destroy()}}}function Ea(t,e,n,r,o,s){let i=S(0,{name:`${e}/cancel`}),a=0,l=[...r,i],u=s?.name??e,d=s?.format??"text",c=Xn(`${u}/stream`),m=C(l,b=>{let T=b.slice(0,-1);if(T.some(_=>_==null))return[];let w=typeof o=="string"?o:o(...T);if(!w)return[];let x=[];return s?.systemPrompt&&x.push({role:"system",content:s.systemPrompt}),x.push({role:"user",content:w}),x}),f=me(m,b=>{let T=b;if(!T||T.length===0)return S(null);let w=new AbortController;async function*x(){let _="",R=0;try{for await(let P of n.stream(T,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:w.signal})){if(P.type!=="token")continue;let A=P.delta;_+=A,c.publish({source:u,token:A,accumulated:_,index:R++})}let k;if(d==="json")try{k=JSON.parse(ze(_))}catch{k=null}else k=_;yield k}finally{w.abort()}}return $(x())}),p=Z(f),g=C([f],([b])=>{if(b!=null)return b},{name:`${e}/filter`});t.add(g,{name:`${e}/raw`});let h=Bo(t,`${e}/gate`,`${e}/raw`,s?.gate),y=h.reject.bind(h),v={...h,reject(b=1){y(b),i.emit(++a)}};return{output:h.node,stream:c,gate:v,dispose:()=>{p(),c.destroy()}}}X();re();function Aa(t,e){let n=e?.separator??`
30
-
31
- `,r=t.map(i=>typeof i=="string"?S(i):$(i)),o=C(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:q("system_prompt"),initial:""}),s=Z(o);return Object.assign(o,{dispose:s})}X();var Sa=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function Oa(t,e){let n=e?.charsPerToken??4;return C([t.latest],([r])=>{if(r==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let o=r,s=o.accumulated.length;return{chunkCount:o.index+1,charCount:s,estimatedTokens:Math.ceil(s/n)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:q("cost_meter_extractor"),equals:Sa})}X();var Ca=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function La(t,e){let n=e.maxPatternLength??128;return C([t.latest],([r],o)=>{if(r==null)return[];let s=r.accumulated;"flags"in o.store||(o.store.flags=[],o.store.scannedTo=0);let i=o.store.flags,a=o.store.scannedTo,l=Math.max(0,a-n),u=s.slice(l),d=!1;for(let{pattern:c,label:m}of e.patterns){let f=new RegExp(c.source,`${c.flags.replace("g","")}g`);for(let p of u.matchAll(f)){let g=l+p.index;g+p[0].length<=a||(i.push({label:m,pattern:c,match:p[0],position:g}),d=!0)}}return o.store.scannedTo=s.length,d?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:q("keyword_flag_extractor"),equals:Ca})}X();function Da(t,e,n){return C([t.latest],([r])=>r==null?null:e(r.accumulated),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:q("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}X();var Ia=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Pa(t,e){return C([t.latest],([n],r)=>{if(n==null)return[];let o=n.accumulated;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let l=o.indexOf("{",i);if(l===-1){r.store.scanFrom=o.length;break}let u=0,d=-1,c=!1;for(let f=l;f<o.length;f++){let p=o[f];if(c)p==="\\"&&f+1<o.length?f++:p==='"'&&(c=!1);else if(p==='"')c=!0;else if(p==="{")u++;else if(p==="}"&&(u--,u===0)){d=f;break}}if(d===-1){r.store.scanFrom=l;break}let m=o.slice(l,d+1);try{let f=JSON.parse(m);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:m,startIndex:l}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:q("tool_call_extractor"),equals:Ia})}X();function Ga(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t.latest];return s&&i.push(e),C(i,a=>{let l=a[0];if(l==null)return"allow";let u=s?a[1]??0:e(l.accumulated);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}X();function Fa(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let l of e){let u=l.global?l:new RegExp(l.source,`${l.flags}g`);a=a.replace(u,d=>o(d,l))}return a}return C([t.latest],([i])=>{if(i==null)return{source:"",token:"",accumulated:"",index:-1};let a=i,l=s(a.accumulated),u=s(a.token);return{source:a.source,token:u,accumulated:l,index:a.index}},{name:r?.name??"redactor"})}Me();fe();ke();X();tt();re();X();var rn=class extends ue{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=De([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=C([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:q("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Z(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:q("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(Z(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function Qn(t,e){return new rn(t,e)}X();var on=class extends ue{definitions;schemas;constructor(e,n={}){super(e,n.graph),this.definitions=S(new Map,{name:"definitions",describeKind:"state",meta:q("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=C([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:q("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(Z(this.schemas))}register(e){let n=this.definitions.cache,r=new Map(n);r.set(e.name,e),this.definitions.emit(r)}unregister(e){let n=this.definitions.cache;if(!n.has(e))return;let r=new Map(n);r.delete(e),this.definitions.emit(r)}async execute(e,n){let o=this.definitions.cache.get(e);if(!o)throw new Error(`toolRegistry: unknown tool "${e}"`);let s=o.handler(n);return He(s)}getDefinition(e){return this.definitions.cache?.get(e)}};function Zn(t,e){return new on(t,e)}var sn=class extends ue{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Qn(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Zn(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let E of n.tools)this.tools.register(E);this.status=S("idle",{name:"status",describeKind:"state",meta:q("agent_status")}),this.add(this.status,{name:"status"}),this.turn=S(0,{name:"turn",describeKind:"state",meta:q("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=S(!1,{name:"aborted",describeKind:"state",meta:q("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(E=>{for(let N of E)N[0]===L&&(r=N[1])}),s=!1,i=this.aborted.subscribe(E=>{for(let N of E)N[0]===L&&(s=N[1])}),a=n.adapter,l=n.systemPrompt,u=n.model,d=n.temperature,c=n.maxTokens,m=n.maxTurns??10,f=n.stopWhen,p=this.chat,g=this.tools,h=this.status,y=this.turn,v=this.aborted,b=ie([h],(E,N,V)=>{if(ht(E,V.prevData,0,"idle")!=="thinking"||s||r>=m){N.down([[H]]);return}let Q=p.allMessages();if(Q.length===0){N.down([[H]]);return}let J=g.schemas.cache??[];N.emit({messages:Q,tools:J})},{name:"promptInput",describeKind:"derived",meta:q("agent_prompt_input")}),T=me(b,E=>{let N=new AbortController;return this._currentAbortController=N,s&&N.abort(new Error("agentLoop: aborted")),$(Promise.resolve(a.invoke(E.messages,{tools:E.tools.length>0?E.tools:void 0,systemPrompt:l,model:u,temperature:d,maxTokens:c,signal:N.signal})),{signal:N.signal})},{equals:()=>!1}),w=S(null,{name:"lastResponse",describeKind:"state",meta:q("agent_last_response")});this.lastResponse=w;let x=ie([w,h],(E,N,V)=>{let U=ht(E,V.prevData,0,null);if(ht(E,V.prevData,1,"idle")!=="acting"){N.down([[H]]);return}let J=U?.toolCalls;if(J==null||J.length===0){N.down([[H]]);return}N.emit(J)},{name:"toolCalls",describeKind:"derived",meta:q("agent_tool_calls")}),_=n.interceptToolCalls?n.interceptToolCalls(x):x;this.toolCalls=_;let R=(E,N)=>{if(E===N)return!0;if(E.length!==N.length)return!1;for(let V=0;V<E.length;V++){let U=E[V],Q=N[V];if(U?.id!==Q?.id||U?.content!==Q?.content)return!1}return!0},k=me(_,E=>{if(E==null||E.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let N=E.map(V=>$a(V,g));return C(N,V=>V.map((U,Q)=>{let J=U;return J!=null&&typeof J=="object"&&"id"in J&&"content"in J?J:{id:E[Q].id,content:JSON.stringify(U??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=k;let P=Ce([T],([E])=>{if(s)return;let N=E,V=r+1,U=N.toolCalls!=null&&N.toolCalls.length>0,Q=N.finishReason==="end_turn"&&(!N.toolCalls||N.toolCalls.length===0),J=f?.(N)===!0,ve=V>=m,I=J||Q||!U||ve?"done":"acting";se(()=>{w.emit(N),h.emit(I),y.emit(V),p.append("assistant",N.content,{toolCalls:N.toolCalls})})}),A=Ce([k],([E])=>{if(s)return;let N=E;if(N.length===0)return;let V=r>=m?"done":"thinking";se(()=>{h.emit(V);for(let U of N)p.appendToolResult(U.id,U.content)})}),D=Ce([v],([E])=>{E===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),h.emit("done"))}),M=Z(P),j=Z(A),z=Z(D);this._terminalResult=ie([h,w],(E,N,V)=>{let U=ht(E,V.prevData,0,"idle"),Q=ht(E,V.prevData,1,null);if(U==="done"){if(Q!=null){N.emit({response:Q,runVersion:this._runVersion});return}let J=new Error("agentLoop: aborted");J.name="AbortError",N.down([[O,J]]);return}if(U==="error"){N.down([[O,new Error("agentLoop: errored")]]);return}N.down([[H]])},{name:"terminalResult",describeKind:"derived",meta:q("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(M),this.addDisposer(j),this.addDisposer(z),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r=++this._runVersion;se(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await jr(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function $a(t,e){let n=Rn(()=>$(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=C([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return co(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function ht(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Ba(t,e){return new sn(t,e)}X();re();function ja(t,e,n){let r=$(t),o=n?.condition!=null?$(n.condition):null,s=S(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return me(r,a=>{if(a==null)return s;let l=S(a);return e(l)});let i=C([r,o],([a,l])=>({v:a,open:l===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return me(i,({v:a,open:l})=>{if(a==null)return s;if(!l)return S(a);let u=S(a);return e(u)})}X();re();function Va(t,e,n){let r=$(t),o=e.map(i=>$(i)),s=[r,...o];return C(s,i=>{let a=i[0]??[],l=i.slice(1);return a.filter(u=>{for(let d of l)if(d!=null&&!d(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:q("tool_selector"),equals:(i,a)=>{let l=i,u=a;if(l.length!==u.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==u[d])return!1;return!0}})}function Ka(t){return{persistence:.5,structure:.5,personalValue:.5}}function Ua(t={}){let e=t.scoreFn??Ka,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}Me();he();X();Me();fe();X();Me();he();fe();X();var er=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=G(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=G(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return G()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??G())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function jo(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s}=t,i=s??new er({maxSize:n,defaultTtl:r}),a=S(i.toMap(),{name:e,describeKind:"state",equals:(d,c)=>d===c,...o!=null?{versioning:o}:{}});function l(){let d=i.toMap();se(()=>{a.down([[Y]]),a.down([[L,d]])})}function u(d){let c=i.version;try{return d()}finally{i.version!==c&&l()}}return{entries:a,has(d){return u(()=>i.has(d))},get(d){return u(()=>i.get(d))},set(d,c,m){u(()=>i.set(d,c,m?.ttl))},setMany(d,c){u(()=>i.setMany(d,c?.ttl))},delete(d){u(()=>i.delete(d))},deleteMany(d){u(()=>i.deleteMany(d))},clear(){u(()=>i.clear())},pruneExpired(){u(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}re();function Ha(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Vo(t){t.subscribe(()=>{})}function gt(t){return t instanceof Map?t:new Map}function Ko(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");se(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Uo(t,e,n){let r=$(t),o=jo(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?$(n.context):S(null),l=gt(o.entries.cache);o.entries.subscribe(f=>{for(let p of f)p[0]===L&&(l=gt(p[1]))});let u=me(r,f=>e(f,l));if(pt(u,f=>{Ko(o,f)}),n.evict){let f=new Map,p=C([o.entries],([g])=>{let h=[],y=gt(g);for(let v of f.keys())y.has(v)||(f.get(v)(),f.delete(v));for(let[v,b]of y){let T=n.evict(v,b);if(Ha(T)){if(!f.has(v)){let w=pt(T,x=>{x===!0&&o.has(v)&&o.delete(v)});f.set(v,w)}continue}if(typeof T=="boolean"){T&&h.push(v);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return h});pt(p,g=>{for(let h of g)o.delete(h)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let f=$(n.consolidateTrigger),p=me(f,()=>n.consolidate(l));pt(p,g=>{Ko(o,g)})}let c=C([o.entries,a],([f,p])=>{let g=[...gt(f).entries()].map(([v,b])=>({key:v,value:b,score:n.score(b,p),cost:n.cost(b)}));g.sort((v,b)=>b.score-v.score);let h=[],y=s;for(let v of g)v.cost<=y&&(h.push({key:v.key,value:v.value,score:v.score}),y-=v.cost);return h}),m=C([o.entries],([f])=>gt(f).size);return Vo(c),Vo(m),{store:o,compact:c,size:m}}re();he();X();function Ho(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function za(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function qe(t){return new Map(t)}function _e(t){return t.cache??new Map}function an(t){return t.cache??[]}function Wa(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,l=e[i]??0;r+=a*l,o+=a*a,s+=l*l}return o===0||s===0?0:r/Math.sqrt(o*s)}function zo(t={}){let e=t.maxSize,n=t.policy??"fifo";za(e);let r=S(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let l of i.values()){if(!a){a=l;continue}let u=n==="lru"?l.lastAccessNs:l.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;u<d&&(a=l)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let l=G(),u=_e(r),d=u.get(i),c=qe(u);c.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??l,lastAccessNs:l}),o(c),s(c)},remove(i){let a=qe(_e(r));a.delete(i)&&s(a)},clear(){_e(r).size!==0&&s(new Map)},get(i){let a=_e(r),l=a.get(i);if(l){if(n==="lru"){let u=G(),d=qe(a);d.set(i,{...l,lastAccessNs:u}),s(d)}return l.value}},has(i){return _e(r).has(i)}}}function Wo(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=S(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,l,u){s(l);let d=qe(_e(o));d.set(a,{id:a,vector:[...l],meta:u}),e==="hnsw"&&r.upsert(a,l,u),i(d)},remove(a){let l=qe(_e(o));l.delete(a)&&(e==="hnsw"&&r.remove(a),i(l))},clear(){_e(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,l=5){return s(a),l<=0?[]:e==="hnsw"?r.search(a,l):[..._e(o).values()].map(d=>({id:d.id,score:Wa(a,d.vector),meta:d.meta})).sort((d,c)=>c.score-d.score).slice(0,l)}}}function qo(t){let e=new ue(t),n=S(new Map,{name:"entities",describeKind:"state"}),r=S([],{name:"edges",describeKind:"state"}),o=C([r],([l])=>{let u=l??[],d=new Map;for(let c of u){let m=d.get(c.from)??[];d.set(c.from,Object.freeze([...m,c]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(l){n.emit(l)}function i(l){r.emit(l)}return Object.assign(e,{upsertEntity(l,u){let d=qe(_e(n));d.set(l,u),s(d)},removeEntity(l){let u=qe(_e(n)),d=u.delete(l),c=an(r),m=c.filter(f=>f.from!==l&&f.to!==l);!d&&m.length===c.length||(s(u),i(m))},link(l,u,d,c=1){let m=`${l}\0${u}\0${d}`,f=an(r),p=new Set(f.map(h=>`${h.from}\0${h.to}\0${h.relation}`)),g=[...f];if(p.has(m))for(let h=0;h<g.length;h+=1){let y=g[h];if(y.from===l&&y.to===u&&y.relation===d){g[h]={...y,weight:c};break}}else g.push({from:l,to:u,relation:d,weight:c});i(g)},unlink(l,u,d){let c=an(r),m=c.filter(f=>d===void 0?!(f.from===l&&f.to===u):!(f.from===l&&f.to===u&&f.relation===d));m.length!==c.length&&i(m)},related(l,u){return an(r).filter(d=>(d.from===l||d.to===l)&&(u===void 0||d.relation===u))}})}fe();X();re();function tr(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return pe(i=>{let a=!0,l=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=$(l).subscribe(c=>{if(!a)return;let m=!1;for(let f of c){if(m)break;if(f[0]===L){let p=f[1];try{let g=JSON.parse(p.content);i.emit(g),i.down([[F]])}catch{i.down([[O,new Error("llmExtractor: failed to parse LLM response as JSON")]])}m=!0}else f[0]===O?(i.down([[O,f[1]]]),m=!0):f[0]===F?(i.down([[F]]),m=!0):i.down([[f[0],f[1]]])}});return()=>{d(),a=!1}})}}function nr(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return pe(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),u=$(a).subscribe(d=>{if(!i)return;let c=!1;for(let m of d){if(c)break;if(m[0]===L){let f=m[1];try{let p=JSON.parse(f.content);s.emit(p),s.down([[F]])}catch{s.down([[O,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}c=!0}else m[0]===O?(s.down([[O,m[1]]]),c=!0):m[0]===F?(s.down([[F]]),c=!0):s.down([[m[0],m[1]]])}});return()=>{u(),i=!1}})}}var rr=Math.LN2/604800;function yt(t){return t instanceof Map?t:new Map}function qa(t,e,n){let r=new ue(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=tr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(b,T)=>b==null?{upsert:[]}:s(b,T),a=e;if(n.admissionFilter){let b=$(e),T=n.admissionFilter;a=C([b],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let l;n.consolidateFn?l=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(l=nr(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&l&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;u=$r(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:l,consolidateTrigger:u},c=Uo(a,i,d);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let m=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(m=Wo({dimension:n.vectorDimensions}),r.add(m.entries,{name:"vectorIndex"}));let f=null;n.enableKnowledgeGraph&&(f=qo(`${t}-kg`),r.mount("kg",f));let p=null;if(n.tiers){let b=n.tiers,T=b.decayRate??rr,w=b.maxActive??1e3,x=b.archiveThreshold??.1,_=b.permanentFilter??(()=>!1),R=zo({name:"permanent"});r.add(R.entries,{name:"permanent"});let k=new Set,P=N=>k.has(N)?"permanent":yt(c.store.entries.cache).has(N)?"active":"archived",A=(N,V)=>{k.add(N),R.upsert(N,V)},D=new Map,M=c.store.entries,j=n.context?$(n.context):S(null),z=Ce([M,j],([N,V])=>{let U=yt(N),Q=G(),J=[],ve=[];for(let[K,te]of U){if(D.has(K)||D.set(K,Q),_(K,te)){ve.push({key:K,value:te});continue}let de=n.score(te,V),W=D.get(K)??Q,B=Number(Q-W)/1e9;Ho(de,B,T)<x&&J.push(K)}for(let K of D.keys())U.has(K)||D.delete(K);for(let{key:K,value:te}of ve)k.has(K)||A(K,te);let I=U.size-k.size;if(I>w){let K=[...U.entries()].filter(([de])=>!k.has(de)).map(([de,W])=>({key:de,score:n.score(W,V)})).sort((de,W)=>de.score-W.score),te=I-w;for(let de=0;de<te&&de<K.length;de++){let W=K[de].key;J.includes(W)||J.push(W)}}J.length>0&&se(()=>{for(let K of J)c.store.delete(K)})});o.push(z.subscribe(()=>{}));let E=null;b.archiveTier&&(E=r.attachStorage([b.archiveTier],b.archiveStorageOptions??{})),p={permanent:R,activeEntries:M,archiveHandle:E,tierOf:P,markPermanent:A}}if(m||f){let b=n.embedFn,T=n.entityFn,w=c.store.entries,x=Ce([w],([_])=>{let R=yt(_);for(let[k,P]of R){if(m&&b){let A=b(P);A&&m.upsert(k,A,P)}if(f&&T){let A=T(k,P);if(A){for(let D of A.entities??[])f.upsertEntity(D.id,D.value);for(let D of A.relations??[])f.link(D.from,D.to,D.relation,D.weight)}}}});o.push(x.subscribe(()=>{}))}let g=null,h=null,y=null,v=null;if(m||f){let b=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,x=n.cost,_=n.score,R=n.contextOf,k=n.contextWeight??0,P=n.context?$(n.context):S(null),A=(E,N)=>{if(!E||!N)return 0;let V=Math.min(E.length,N.length),U=0;for(;U<V&&E[U]===N[U];)U++;return U},D=(E,N,V)=>{let U=new Map,Q=[];if(m&&V.vector){Q=m.search(V.vector,b);for(let W of Q){let B=E.get(W.id);B&&U.set(W.id,{value:B,sources:new Set(["vector"])})}}let J=[];if(f){let W=[...V.entityIds??[],...U.keys()],B=new Set,oe=W;for(let Re=0;Re<T;Re++){let Pe=[];for(let st of oe){if(B.has(st))continue;B.add(st);let bt=f.related(st);for(let Xo of bt){let Je=Xo.to;if(!B.has(Je)){Pe.push(Je);let sr=E.get(Je);if(sr){let ir=U.get(Je);ir?ir.sources.add("graph"):U.set(Je,{value:sr,sources:new Set(["graph"])}),J.push(Je)}}}}oe=Pe}}for(let[W,B]of E)U.has(W)||U.set(W,{value:B,sources:new Set(["store"])});let ve=V.context?.length??0,I=[];for(let[W,{value:B,sources:oe}]of U){let Re=R?R(B):void 0,Pe=_(B,N);if(k>0&&ve>0){let bt=A(V.context,Re);bt>0&&(Pe=Pe*(1+k*bt/ve))}let st=Re?{key:W,value:B,score:Pe,sources:[...oe],context:Re}:{key:W,value:B,score:Pe,sources:[...oe]};I.push(st)}I.sort((W,B)=>B.score-W.score);let K=[],te=0;for(let W of I){let B=x(W.value);if(te+B>w&&K.length>0)break;K.push(W),te+=B}return{packed:K,trace:{vectorCandidates:Q,graphExpanded:J,ranked:I,packed:K}}},M=S([],{name:"retrieval",describeKind:"state",meta:q("retrieval_pipeline")});r.add(M,{name:"retrieval"}),g=M;let j=S(null,{name:"retrievalTrace",describeKind:"state",meta:q("retrieval_trace")});r.add(j,{name:"retrievalTrace"}),h=j,y=E=>{let N=yt(c.store.entries.cache),{packed:V,trace:U}=D(N,P.cache,E);return se(()=>{M.emit(V),j.emit(U)}),V},v=E=>{let N=$(E);return C([c.store.entries,P,N],([V,U,Q])=>{if(Q==null)return[];let J=yt(V);return D(J,U,Q).packed},{name:"retrievalReactive",describeKind:"derived",meta:q("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let b of o)b();o.length=0}),Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:m,kg:f,memoryTiers:p,retrieval:g,retrievalTrace:h,retrieve:y,retrieveReactive:v})}function Ja(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
32
- `,i=[],a=n?.sinceVersion;for(let[l,u]of Object.entries(r.nodes)){let d=u.meta??{},c=d.description,m=d.format;if(!c&&!m)continue;if(a!=null&&u.v!=null){let y=a.get(l);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=c??l,p=u.value,g=d.unit,h;m==="currency"&&typeof p=="number"?h=`$${p.toFixed(2)}`:m==="percentage"&&typeof p=="number"?h=`${(p*100).toFixed(1)}%`:p==null?h="(no value)":h=String(p),g&&m!=="currency"&&m!=="percentage"&&(h=`${h} ${g}`),i.push({path:l,description:f,formatted:h})}if(i.length===0)return"";if(o){let l=new Map,u=[];for(let c of i){let f=r.nodes[c.path].meta?.tags;if(f&&f.length>0){let p=f[0],g=l.get(p);g||(g=[],l.set(p,g)),g.push(c)}else u.push(c)}if(l.size===0)return i.map(c=>`- ${c.description}: ${c.formatted}`).join(s);let d=[];for(let[c,m]of[...l.entries()].sort((f,p)=>f[0].localeCompare(p[0])))d.push(`[${c}]${s}${m.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&d.push(u.map(c=>`- ${c.description}: ${c.formatted}`).join(s)),d.join(s+s)}return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s)}var Jo=new Set(["state","derived","producer","operator","effect"]);function or(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!Jo.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Jo].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let l=`${a.from}->${a.to}`;o.has(l)&&e.push(`Edge [${s}]: duplicate edge ${l}`),o.add(l)}}return{valid:e.length===0,errors:e}}var Yo=`You are a graph architect for GraphReFly, a reactive graph protocol.
33
-
34
- Given a natural-language description, produce a JSON graph definition with this structure:
21
+ Given a natural-language description, produce a JSON graph specification with this structure:
35
22
 
36
23
  {
37
24
  "name": "<graph_name>",
38
25
  "nodes": {
39
26
  "<node_name>": {
40
- "type": "state" | "derived" | "producer" | "operator" | "effect",
41
- "value": <initial_value_or_null>,
27
+ "type": "state" | "derived" | "producer" | "effect" | "operator",
28
+ "initial": <initial_value_for_state_nodes>,
42
29
  "deps": ["<dep_node_name>", ...],
43
30
  "meta": {
44
31
  "description": "<human-readable purpose>",
@@ -51,24 +38,20 @@ Given a natural-language description, produce a JSON graph definition with this
51
38
  "tags": ["<tag>"]
52
39
  }
53
40
  }
54
- },
55
- "edges": [
56
- { "from": "<source_node>", "to": "<target_node>" }
57
- ]
41
+ }
58
42
  }
59
43
 
60
44
  Rules:
61
- - "state" nodes have no deps and hold user/LLM-writable values (knobs).
62
- - "derived" nodes have deps and compute from them.
45
+ - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
46
+ - "derived" nodes have deps and compute from them (pure, no side effects).
63
47
  - "effect" nodes have deps but produce side effects (no return value).
64
48
  - "producer" nodes have no deps but generate values asynchronously.
65
- - Edges wire output of one node as input to another. They must match deps.
49
+ - "operator" nodes are parameterized transformations with deps.
50
+ - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
66
51
  - meta.description is required for every node.
67
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Ya(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Yo}
52
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function pc(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${as}
68
53
 
69
- ${n.systemPromptExtra}`:Yo},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await He(s)).content.trim();a.startsWith("```")&&(a=ze(a));let l;try{l=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}let u=or(l);if(!u.valid)throw new Error(`graphFromSpec: invalid graph definition:
70
- ${u.errors.join(`
71
- `)}`);let d=l;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),ue.fromSnapshot(d,n?.build)}function Xa(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Qa(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let l=a.meta??{},u=l.access;if(u==="human"||u==="system")continue;let d=l.description??`Set the value of ${i}`,c=Xa(l),m={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:d,parameters:m}}),o.push({name:i,description:d,inputSchema:m});let p=t,g=e,h=a.v;s.push({name:i,description:d,parameters:m,handler(y){return p.set(i,y.value,g?{actor:g}:void 0),y.value},...h!=null?{version:{id:h.id,version:h.version}}:{}})}return{openai:r,mcp:o,definitions:s}}var Za=`You are a reactive graph optimizer for GraphReFly.
54
+ ${n.systemPromptExtra}`:as},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await Xe(s)).content.trim();a.startsWith("```")&&(a=pt(a));let c;try{c=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return is(c,{catalog:n?.catalog})}function fc(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function mc(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let c=a.meta??{},u=c.access;if(u==="human"||u==="system")continue;let d=c.description??`Set the value of ${i}`,l=fc(c),f={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},p=i.replace(/::/g,"__");r.push({type:"function",function:{name:p,description:d,parameters:f}}),o.push({name:i,description:d,inputSchema:f});let m=t,g=e,h=a.v;s.push({name:i,description:d,parameters:f,handler(y){return m.set(i,y.value,g?{actor:g}:void 0),y.value},...h!=null?{version:{id:h.id,version:h.version}}:{}})}return{openai:r,mcp:o,definitions:s}}var gc=`You are a reactive graph optimizer for GraphReFly.
72
55
 
73
56
  Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
74
57
 
@@ -89,4 +72,4 @@ Return ONLY valid JSON with this structure:
89
72
  Rules:
90
73
  - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
91
74
  - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
92
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function el(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Za},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),u=(await He(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=d;if(typeof c.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof c.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(c.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:c.summary,reasoning:c.reasoning,operations:c.operations}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,dryRunPreset,fallbackAdapter,fromLLM,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,observableAdapter,openAICompatAdapter,parseRateLimitFromError,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,systemPromptBuilder,toolCallExtractor,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});
75
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function hc(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:gc},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),u=(await Xe(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=d;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}var cs=new Set(["state","derived","producer","operator","effect"]);function yc(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!cs.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...cs].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let c=`${a.from}->${a.to}`;o.has(c)&&e.push(`Edge [${s}]: duplicate edge ${c}`),o.add(c)}}return{valid:e.length===0,errors:e}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,fallbackAdapter,fromLLM,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,observableAdapter,openAICompatAdapter,parseRateLimitFromError,pricingFor,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,systemPromptBuilder,tier,toolCallExtractor,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});