@graphrefly/graphrefly 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
- package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
- package/dist/chunk-2JNT5NDF.js +61 -0
- package/dist/{chunk-DDPYNMGG.js → chunk-2RH4QNDQ.js} +1 -1
- package/dist/chunk-4JBKKUCJ.js +7 -0
- package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
- package/dist/chunk-4VXL3UZK.js +1 -0
- package/dist/{chunk-SHYH5SXV.js → chunk-4YGJ7KZ6.js} +1 -1
- package/dist/{chunk-GJR3P6JG.js → chunk-5PBXUVHI.js} +1 -1
- package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
- package/dist/{chunk-XQAXYVXX.js → chunk-7EMUF2RY.js} +1 -1
- package/dist/chunk-7JZ3YORY.js +80 -0
- package/dist/chunk-7QMVU3IX.js +1 -0
- package/dist/{chunk-WANIEEKV.js → chunk-7QS77X6G.js} +1 -1
- package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
- package/dist/{chunk-Y36UZ5VS.js → chunk-BU4SUZSA.js} +1 -1
- package/dist/{chunk-P7JXGKDO.js → chunk-CNXUW2CU.js} +1 -1
- package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
- package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
- package/dist/chunk-EIFHFDFD.js +1 -0
- package/dist/chunk-FTA5TB2A.js +1 -0
- package/dist/{chunk-T5SHIKJD.js → chunk-JAHAJU4G.js} +1 -1
- package/dist/{chunk-AV3PIDFQ.js → chunk-JYMNVEH6.js} +1 -1
- package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
- package/dist/chunk-KD3IYBTD.js +3 -0
- package/dist/{chunk-3NEPQO2E.js → chunk-LG73TUF4.js} +2 -2
- package/dist/chunk-LJGPOJHS.js +1 -0
- package/dist/chunk-LWGLBCMU.js +1 -0
- package/dist/{chunk-BKPLTBL5.js → chunk-M2VFLRPJ.js} +1 -1
- package/dist/{chunk-GNCBXARM.js → chunk-MFNOZ5E6.js} +1 -1
- package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
- package/dist/chunk-PNTBXOQ6.js +5 -0
- package/dist/{chunk-73Z3W2RN.js → chunk-PWKLZ2XU.js} +1 -1
- package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
- package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
- package/dist/chunk-SGS4OJGS.js +1 -0
- package/dist/{chunk-4OFIQ66T.js → chunk-TOCCHQI6.js} +1 -1
- package/dist/chunk-UMH3HSP7.js +1 -0
- package/dist/{chunk-XHVB6G6M.js → chunk-UXEB35L4.js} +1 -1
- package/dist/{chunk-33FA6V4B.js → chunk-VXJX3ZZP.js} +1 -1
- package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
- package/dist/{chunk-RD52SNH2.js → chunk-WE32AFFA.js} +1 -1
- package/dist/{chunk-KA6MMXIY.js → chunk-WF3V5X2L.js} +1 -1
- package/dist/chunk-WQ7I7JVU.js +1 -0
- package/dist/{chunk-4JJCCD5S.js → chunk-X4OOM6QU.js} +1 -1
- package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
- package/dist/chunk-Y26UN6J5.js +18 -0
- package/dist/{chunk-VWPRPPKR.js → chunk-ZWETYYQG.js} +1 -1
- package/dist/compat/index.cjs +2 -2
- package/dist/compat/index.d.cts +5 -5
- package/dist/compat/index.d.ts +5 -5
- package/dist/compat/index.js +1 -1
- package/dist/compat/jotai/index.cjs +1 -1
- package/dist/compat/jotai/index.js +1 -1
- package/dist/compat/nanostores/index.cjs +1 -1
- package/dist/compat/nanostores/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +5 -5
- package/dist/compat/nestjs/index.d.cts +3 -3
- package/dist/compat/nestjs/index.d.ts +3 -3
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.cjs +2 -2
- package/dist/compat/zustand/index.d.cts +2 -2
- package/dist/compat/zustand/index.d.ts +2 -2
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
- package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
- package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
- package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.js +1 -1
- package/dist/extra/browser.cjs +1 -1
- package/dist/extra/browser.js +1 -1
- package/dist/extra/index.cjs +18 -18
- package/dist/extra/index.d.cts +7 -6
- package/dist/extra/index.d.ts +7 -6
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +41 -1
- package/dist/extra/operators.d.ts +41 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.cjs +1 -1
- package/dist/extra/reactive.d.cts +1 -1
- package/dist/extra/reactive.d.ts +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.d.cts +62 -2
- package/dist/extra/sources.d.ts +62 -2
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.cjs +1 -1
- package/dist/extra/storage-browser.js +1 -1
- package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
- package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
- package/dist/graph/index.cjs +4 -4
- package/dist/graph/index.d.cts +3 -3
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +1 -1
- package/dist/{graph-CWeI0aHd.d.ts → graph-BOhEGJ6E.d.ts} +10 -0
- package/dist/{graph-C4Uxwv0T.d.cts → graph-CdJeX7O7.d.cts} +10 -0
- package/dist/{index-B-z8WaSd.d.cts → index-BDLy6CQ9.d.cts} +1 -1
- package/dist/{index-iBp74eGU.d.cts → index-BJDXj9Wf.d.cts} +2 -2
- package/dist/{index-BBINVimG.d.ts → index-BUZPTPSQ.d.ts} +2 -2
- package/dist/{index-DnrZghBB.d.ts → index-BbcSZCAG.d.ts} +1 -1
- package/dist/{index-lKuLYmHO.d.cts → index-BiGeETJs.d.cts} +1 -1
- package/dist/{index-BHu_Wba0.d.cts → index-BmZb8fNF.d.cts} +3 -3
- package/dist/{index-Docdiu9a.d.ts → index-Bnmttu35.d.ts} +1 -1
- package/dist/{index-D6ajK8Mh.d.cts → index-BuN2wGJs.d.cts} +517 -134
- package/dist/{index-Cy7eFeIX.d.cts → index-BwdPDWI4.d.cts} +1 -1
- package/dist/{index-DylQCKEL.d.cts → index-BzxU4yhV.d.cts} +11 -2
- package/dist/{index-D9Y_u6BG.d.cts → index-C-Gsh-0a.d.cts} +2 -2
- package/dist/{index-ybtSyjWB.d.cts → index-C22aTC1X.d.cts} +5 -5
- package/dist/{index-yIdWFo2b.d.cts → index-C4QTaDli.d.cts} +2 -2
- package/dist/{index-BJHQUCZx.d.ts → index-C7RqYbOZ.d.ts} +82 -7
- package/dist/{index-C5Ghnp5B.d.ts → index-C9qCLIN4.d.ts} +2 -2
- package/dist/{index-DVNLe3pS.d.cts → index-CCdg0JLX.d.cts} +1 -1
- package/dist/{index-B5iVOD7w.d.ts → index-CEoU-r-g.d.ts} +2 -2
- package/dist/{index-CfFYyLR8.d.ts → index-CHfBm51k.d.ts} +11 -2
- package/dist/{index-Dljd76bC.d.ts → index-CNyiYQWF.d.ts} +5 -5
- package/dist/{index-C6NBfXj-.d.ts → index-CVevMZ0n.d.ts} +2 -2
- package/dist/{index-DGb1awva.d.ts → index-CZUzi6Dy.d.ts} +2 -2
- package/dist/{index-FrYrV-Vf.d.ts → index-Ckl03Q0s.d.ts} +1 -1
- package/dist/{index-Bvi5uJxX.d.ts → index-CmSjld-4.d.ts} +1 -1
- package/dist/{index-9iguV3bF.d.cts → index-CnjUhRbs.d.cts} +2 -2
- package/dist/{index-C98oJsEs.d.cts → index-D3HcdZ4d.d.cts} +1 -1
- package/dist/{index-IZ3l_vQ9.d.ts → index-DD1czHj3.d.ts} +1 -1
- package/dist/{index-BS220yqj.d.cts → index-DNhTQReY.d.cts} +82 -7
- package/dist/{index-UZO988ox.d.cts → index-DSawGt8n.d.cts} +2 -2
- package/dist/{index-CcpEvuPl.d.cts → index-DUkuH3jP.d.cts} +1 -1
- package/dist/{index-CRAkoq-y.d.cts → index-DY2QbdoP.d.cts} +1 -1
- package/dist/{index-CvS9IuTG.d.ts → index-Dbmj0iYR.d.ts} +1 -1
- package/dist/{index-ClgKmOHe.d.ts → index-DhlAMlm9.d.ts} +517 -134
- package/dist/{index-ClB7TCfL.d.cts → index-DlGaEBW5.d.cts} +2 -2
- package/dist/{index-CotRMjtJ.d.ts → index-Dp_pS7Bw.d.ts} +1 -1
- package/dist/{index-Cc8VQIgL.d.ts → index-Dxk-pUQI.d.ts} +2 -2
- package/dist/{index-DBQUKh59.d.cts → index-EGjF6iSY.d.cts} +3 -3
- package/dist/{index-D9HrBx2J.d.ts → index-LGzAYqdR.d.ts} +1 -1
- package/dist/{index-DR3gf_DG.d.cts → index-LzCJ0kMT.d.cts} +2 -2
- package/dist/{index-RQg6lTrN.d.ts → index-MV2yGIAq.d.ts} +2 -2
- package/dist/{index-Bs3-LC83.d.cts → index-_BXz9K7b.d.cts} +1 -1
- package/dist/{index-SSGqF8mI.d.cts → index-aBqZUx3B.d.cts} +1 -1
- package/dist/{index-CFW32Dy1.d.ts → index-eYHRkoK-.d.ts} +1 -1
- package/dist/{index-B2HBxvMb.d.ts → index-gXTVbSax.d.ts} +3 -3
- package/dist/{index-B8Aj_z8S.d.cts → index-j33Lfb1G.d.cts} +23 -2
- package/dist/{index-BEpRsvhg.d.ts → index-lpGUhTBn.d.ts} +3 -3
- package/dist/{index-BXbQUn4n.d.ts → index-zMQIQuDu.d.ts} +23 -2
- package/dist/index.cjs +106 -125
- package/dist/index.d.cts +34 -33
- package/dist/index.d.ts +34 -33
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -22
- package/dist/patterns/ai/browser.d.cts +3 -3
- package/dist/patterns/ai/browser.d.ts +3 -3
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +30 -44
- package/dist/patterns/ai/index.d.cts +13 -11
- package/dist/patterns/ai/index.d.ts +13 -11
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.cjs +2 -2
- package/dist/patterns/ai/node.d.cts +5 -4
- package/dist/patterns/ai/node.d.ts +5 -4
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +3 -3
- package/dist/patterns/audit/index.d.cts +3 -3
- package/dist/patterns/audit/index.d.ts +3 -3
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +6 -6
- package/dist/patterns/cqrs/index.d.cts +2 -2
- package/dist/patterns/cqrs/index.d.ts +2 -2
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +2 -2
- package/dist/patterns/demo-shell/index.d.cts +3 -3
- package/dist/patterns/demo-shell/index.d.ts +3 -3
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +6 -6
- package/dist/patterns/domain-templates/index.d.cts +2 -2
- package/dist/patterns/domain-templates/index.d.ts +2 -2
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +27 -25
- package/dist/patterns/graphspec/index.d.cts +3 -3
- package/dist/patterns/graphspec/index.d.ts +3 -3
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.d.cts +4 -4
- package/dist/patterns/guarded-execution/index.d.ts +4 -4
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +12 -11
- package/dist/patterns/harness/index.d.cts +6 -6
- package/dist/patterns/harness/index.d.ts +6 -6
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +5 -5
- package/dist/patterns/job-queue/index.d.cts +2 -2
- package/dist/patterns/job-queue/index.d.ts +2 -2
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +5 -5
- package/dist/patterns/lens/index.d.cts +4 -4
- package/dist/patterns/lens/index.d.ts +4 -4
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +4 -4
- package/dist/patterns/memory/index.d.cts +2 -2
- package/dist/patterns/memory/index.d.ts +2 -2
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +5 -5
- package/dist/patterns/messaging/index.d.cts +2 -2
- package/dist/patterns/messaging/index.d.ts +2 -2
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.d.cts +2 -2
- package/dist/patterns/orchestration/index.d.ts +2 -2
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +2 -2
- package/dist/patterns/reactive-layout/index.d.cts +3 -3
- package/dist/patterns/reactive-layout/index.d.ts +3 -3
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +5 -5
- package/dist/patterns/reduction/index.d.cts +2 -2
- package/dist/patterns/reduction/index.d.ts +2 -2
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.d.cts +3 -3
- package/dist/patterns/refine-loop/index.d.ts +3 -3
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
- package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +15 -13
- package/dist/patterns/surface/index.d.cts +4 -4
- package/dist/patterns/surface/index.d.ts +4 -4
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{reactive-layout-BAr6-_o5.d.ts → reactive-layout-Bq0rA2Wb.d.ts} +1 -1
- package/dist/{reactive-layout-5oEn8lHM.d.cts → reactive-layout-Dhhe54Oj.d.cts} +1 -1
- package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
- package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
- package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
- package/dist/{topology-tree-CVREibAc.d.cts → topology-tree-CpSjvIXp.d.cts} +1 -1
- package/dist/{topology-tree-CkjojcB6.d.ts → topology-tree-DAbCV2Yw.d.ts} +1 -1
- package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
- package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
- package/package.json +1 -1
- package/dist/chunk-2GQREQ6C.js +0 -1
- package/dist/chunk-4C2OR2GH.js +0 -18
- package/dist/chunk-5JDE5JHE.js +0 -1
- package/dist/chunk-7JDLFI6N.js +0 -1
- package/dist/chunk-AMBYCIOH.js +0 -3
- package/dist/chunk-GLSM33ZM.js +0 -78
- package/dist/chunk-ISCENNXS.js +0 -1
- package/dist/chunk-IUK4EFCE.js +0 -1
- package/dist/chunk-KASHOCF5.js +0 -1
- package/dist/chunk-LI3E75VE.js +0 -64
- package/dist/chunk-MGKAO4EK.js +0 -7
- package/dist/chunk-NSG4C6BF.js +0 -23
- package/dist/chunk-VIEUJSTT.js +0 -1
package/dist/chunk-AMBYCIOH.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{e as O}from"./chunk-33FA6V4B.js";import{k as ce}from"./chunk-MGKAO4EK.js";import{v as ue}from"./chunk-5JDE5JHE.js";import{D as le,E as p,G as N,H as G,m as L,o as A}from"./chunk-W4TSQ6RJ.js";import{b as P,j as Q}from"./chunk-CK2E7BTU.js";import{b as pe}from"./chunk-QYADASLV.js";var Se={};pe(Se,{blindVariation:()=>ke,errorCritique:()=>Ie,refineLoop:()=>Ee});function ve(n){if(typeof n!="object"||n===null)return!1;let l=n;return typeof l.subscribe=="function"&&typeof l.down=="function"&&typeof l.emit=="function"}function me(n,l){if(n.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(n.length===1){let e=X(l);return{best:n[0],bestScore:e}}if(l.some(e=>typeof e.candidateIndex=="number")){let e=new Array(n.length);for(let i=0;i<n.length;i++)e[i]={sum:0,count:0};for(let i of l){let d=i.candidateIndex;typeof d=="number"&&d>=0&&d<n.length&&(e[d].sum+=i.score,e[d].count+=1)}let s=n[0],o=e[0].count>0?e[0].sum/e[0].count:Number.NEGATIVE_INFINITY;for(let i=1;i<n.length;i++){let d=e[i].count>0?e[i].sum/e[i].count:Number.NEGATIVE_INFINITY;d>o&&(o=d,s=n[i])}return{best:s,bestScore:o}}let t=n[0],m=l[0]?.score??Number.NEGATIVE_INFINITY;for(let e=1;e<n.length;e++){let s=l[e]?.score??Number.NEGATIVE_INFINITY;s>m&&(m=s,t=n[e])}return{best:t,bestScore:m}}function X(n){if(n.length===0)return Number.NEGATIVE_INFINITY;let l=0;for(let k of n)l+=k.score;return l/n.length}function Ee(n,l,k,t){let m=t.name??"refine-loop",e=new ce(m,t.graph),s=ve(t.dataset)?t.dataset:p(t.dataset,{name:"dataset"});e.add(s,{name:"dataset"});let o=p(0,{name:"iteration"});e.add(o,{name:"iteration"});let i=p(k,{name:"strategy",equals:()=>!1});e.add(i,{name:"strategy"});let d=p(null,{name:"lastFeedback"});e.add(d,{name:"lastFeedback"});let E=p([],{name:"prevCandidates"});e.add(E,{name:"prevCandidates"});let g=p(!1,{name:"paused"});e.add(g,{name:"paused"});let b=p("running",{name:"status"});e.add(b,{name:"status"});let v=p([],{name:"history",equals:()=>!1});e.add(v,{name:"history"});let T=p(null,{name:"best"});e.add(T,{name:"best"});let x=p(Number.NEGATIVE_INFINITY,{name:"score"});e.add(x,{name:"score"});let R=p(0,{name:"budget-used"});e.add(R,{name:"budget-used"});let _=O("GENERATE"),V=O("EVALUATE"),f=O("ANALYZE"),F=O("DECIDE");e.mount("GENERATE",_),e.mount("EVALUATE",V),e.mount("ANALYZE",f),e.mount("DECIDE",F);let Y=k,B=null,ee=[];e.addDisposer(i.subscribe(r=>{for(let a of r)a[0]===P&&(Y=a[1])})),e.addDisposer(d.subscribe(r=>{for(let a of r)a[0]===P&&(B=a[1])})),e.addDisposer(E.subscribe(r=>{for(let a of r)a[0]===P&&(ee=a[1])}));let I=ue(o,r=>{let a=Y,c=r===0||B==null;return le([],(u,y)=>{let S=!1;try{let C=c?a.seed(n):a.generate(B,ee);if(C instanceof Promise)return C.then(q=>{S||y.emit(q)},q=>{S||y.down([[Q,q]])}),()=>{S=!0};y.emit(C)}catch(C){S=!0,y.down([[Q,C]])}},{describeKind:"producer"})},{name:"candidates"});e.add(I,{name:"candidates"});let ne=G([I],(r,a,c)=>{let u=c.terminalDeps[0];u!==void 0&&u!==!0&&b.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});e.add(ne,{name:"error-watcher"}),e.addDisposer(ne.subscribe(()=>{}));let te=G([I,o],([r,a])=>{let c=r,u=a;L(()=>{_.publish({iteration:u,candidates:c,timestamp_ns:A()}),E.emit(c)})},{name:"generate-bridge"});e.add(te,{name:"generate-bridge"}),e.addDisposer(te.subscribe(()=>{}));let $=l(I,s);e.add($,{name:"scores"});let re=G([$,I,o],([r,a,c])=>{V.publish({iteration:c,candidates:a,scores:r,timestamp_ns:A()})},{name:"evaluate-bridge"});e.add(re,{name:"evaluate-bridge"}),e.addDisposer(re.subscribe(()=>{}));let j=N([$,I],([r,a])=>Y.analyze(r,a),{name:"feedback"});e.add(j,{name:"feedback"});let ae=G([j,I,o],([r,a,c])=>{f.publish({iteration:c,candidates:a,feedback:r,timestamp_ns:A()})},{name:"analyze-bridge"});e.add(ae,{name:"analyze-bridge"}),e.addDisposer(ae.subscribe(()=>{}));let M=N([v],([r])=>{let a=r;if(t.patience==null||a.length<=t.patience)return!1;let c=a.slice(-(t.patience+1)),u=c[0].bestScore;return c.slice(1).every(y=>y.bestScore<=u)},{name:"patience-check"});e.add(M,{name:"patience-check"});let U=N([x],([r])=>t.minScore!=null&&r>=t.minScore,{name:"min-score-check"});e.add(U,{name:"min-score-check"});let H=N([v],([r])=>{let a=r;if(t.minDelta==null||a.length<2)return!1;let c=a[a.length-2].bestScore,u=a[a.length-1].bestScore;return Math.abs(u-c)<t.minDelta},{name:"min-delta-check"});e.add(H,{name:"min-delta-check"});let W=N([R],([r])=>t.maxEvaluations!=null&&r>=t.maxEvaluations,{name:"max-evaluations-check"});e.add(W,{name:"max-evaluations-check"});let Z=N([o],([r])=>t.maxIterations!=null&&r>=t.maxIterations,{name:"max-iterations-check"});e.add(Z,{name:"max-iterations-check"});let oe=N([R],([r])=>t.budget!=null&&r>=t.budget,{name:"budget-exhausted-check"});e.add(oe,{name:"budget-exhausted-check"}),e.addDisposer(M.subscribe(()=>{})),e.addDisposer(U.subscribe(()=>{})),e.addDisposer(H.subscribe(()=>{})),e.addDisposer(W.subscribe(()=>{})),e.addDisposer(Z.subscribe(()=>{})),e.addDisposer(oe.subscribe(()=>{}));let ie=N([M,U,H,W,Z],([r,a,c,u,y])=>r?{converged:!0,reason:"patience"}:a?{converged:!0,reason:"min-score"}:c?{converged:!0,reason:"min-delta"}:u?{converged:!0,reason:"max-evaluations"}:y?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});e.add(ie,{name:"converged"}),e.addDisposer(ie.subscribe(()=>{}));let se=-1,de=G([j,$,I],([r,a,c])=>{let u=o.cache,y=r,S=c,C=a;if(u<=se)return;se=u;let{best:q,bestScore:be}=me(S,C),fe=v.cache,ye={n:u,candidates:S,scores:C,feedback:y,best:q,bestScore:be,timestamp_ns:A()},D=[...fe,ye],K=R.cache+S.length,h="continue",w,ge=t.budget!=null&&K>=t.budget,Te=g.cache;if(ge)h="budget",w="budget";else if(t.minScore!=null&&y.score>=t.minScore)h="converged",w="min-score";else if(t.maxIterations!=null&&u>=t.maxIterations)h="converged",w="max-iterations";else if(t.maxEvaluations!=null&&K>=t.maxEvaluations)h="converged",w="max-evaluations";else if(t.minDelta!=null&&D.length>=2){let z=D[D.length-2].bestScore,J=D[D.length-1].bestScore;Math.abs(J-z)<t.minDelta&&(h="converged",w="min-delta")}else if(t.patience!=null&&D.length>t.patience){let z=D.slice(-(t.patience+1)),J=z[0].bestScore;z.slice(1).every(he=>he.bestScore<=J)&&(h="converged",w="patience")}h==="continue"&&Te&&(h="paused"),L(()=>{T.emit(q),x.emit(y.score),v.emit(D),R.emit(K),d.emit(y),F.publish({iteration:u,decision:h,reason:w,timestamp_ns:A()}),h==="continue"?o.emit(u+1):b.emit(h==="converged"?"converged":h==="budget"?"budget":"paused")})},{name:"decide-bridge"});return e.add(de,{name:"decide-bridge"}),e.addDisposer(de.subscribe(()=>{})),Object.assign(e,{best:T,score:x,status:b,history:v,strategy:i,iteration:o,generate:_,evaluate:V,analyze:f,decide:F,setStrategy(r){i.emit(r)},pause(){g.emit(!0)},resume(){b.cache==="paused"&&L(()=>{g.emit(!1),b.emit("running"),o.emit(o.cache+1)})}})}function ke(n){let l=n.width??4;return{name:n.name??"blindVariation",seed(t){return[t]},analyze(t,m){let e=X(t),s=null;for(let o of t)(!s||o.score<s.score)&&(s=o);return{summary:`blindVariation iteration: mean=${e.toFixed(3)}, n=${t.length}`,score:e,weakTasks:s?[s.taskId]:[]}},async generate(t,m){if(m.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let e=m[m.length-1],s=0,i={prior:e,reportCost:d=>{s+=d}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(i)));let d=[];for(let E=0;E<l;E++)d.push(await n.teacher(i));return d}finally{if(n.tokens!=null&&s>0){let d=n.tokens.cache??0;n.tokens.emit(d+s)}}}}}function xe(n){return typeof n=="object"&&n!==null&&n.kind==="errorCritique"}function Ne(n,l){return n.length===0?`No task scored below the batch mean (${l.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
|
|
2
|
-
${n.map(t=>{let m=t.error!=null?` | error: ${t.error}`:"";return`- ${t.taskId} (score=${t.score.toFixed(3)})${m}`}).join(`
|
|
3
|
-
`)}`}function Ie(n){let l=n.width??4,k=n.name??"errorCritique",t=n.maxFailureSamples??5,m=n.formatCritique??Ne;return{name:k,seed(e){return[e]},analyze(e,s){let o=X(e),i=typeof n.failureThreshold=="function"?n.failureThreshold(e):n.failureThreshold,d=i===void 0&&!Number.isFinite(o),E=i??o,g=d?[...e].sort((f,F)=>f.score-F.score):e.filter(f=>f.score<E).slice().sort((f,F)=>f.score-F.score),b=g.slice(0,t),{best:v,bestScore:T}=me(s,e),x={summary:"",score:o,weakTasks:b.map(f=>f.taskId)},R=m(b,x),_={kind:"errorCritique",best:v,failures:b,critiqueText:R},V=g.length>b.length?` (top ${b.length} retained)`:"";return{summary:`errorCritique iteration: mean=${o.toFixed(3)}, failures=${g.length}${V}/${e.length}, bestScore=${T.toFixed(3)}`,critique:_,weakTasks:b.map(f=>f.taskId),score:o}},async generate(e,s){if(s.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=xe(e.critique)?e.critique:void 0,i=o!==void 0?o.best:s[s.length-1],d=o?.critiqueText??e.summary,E=o?.failures??[],g=0,v={prior:i,critique:d,failures:E,reportCost:T=>{g+=T}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(v)));let T=[];for(let x=0;x<l;x++)T.push(await n.teacher(v));return T}finally{if(n.tokens!=null&&g>0){let T=n.tokens.cache??0;n.tokens.emit(T+g)}}}}}export{Ee as a,ke as b,Ie as c,Se as d};
|
package/dist/chunk-GLSM33ZM.js
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import{b as q}from"./chunk-KA6MMXIY.js";import{h as W,k as D}from"./chunk-MGKAO4EK.js";import{E as M,F as A,G as L,H as T}from"./chunk-W4TSQ6RJ.js";import{b as Q}from"./chunk-QYADASLV.js";var ie={};Q(ie,{compileSpec:()=>ne,decompileGraph:()=>se,extractFnFactory:()=>z,extractSourceFactory:()=>U,generateCatalogPrompt:()=>V,isRichFnEntry:()=>_,isRichSourceEntry:()=>J,llmCompose:()=>ae,llmRefine:()=>H,specDiff:()=>re,validateSpec:()=>E,validateSpecAgainstCatalog:()=>I});function _(a){return typeof a=="object"&&a!==null&&"factory"in a}function J(a){return typeof a=="object"&&a!==null&&"factory"in a}function z(a){return _(a)?a.factory:a}function U(a){return J(a)?a.factory:a}function V(a){let o=[];if(a.fns){let n=new Map;for(let[p,i]of Object.entries(a.fns)){let l=_(i)?i.tags?.[0]??"Other":"Other";n.has(l)||n.set(l,[]),n.get(l).push(X(p,i))}for(let[p,i]of n)o.push(`${p}:
|
|
2
|
-
${i.join(`
|
|
3
|
-
`)}`)}if(a.sources){let n=[];for(let[p,i]of Object.entries(a.sources))n.push(Z(p,i));n.length>0&&o.push(`Sources:
|
|
4
|
-
${n.join(`
|
|
5
|
-
`)}`)}return o.join(`
|
|
6
|
-
|
|
7
|
-
`)}function X(a,o){if(!_(o))return`- ${a}`;let n=`- ${a}: ${o.description}`;if(o.configSchema){let p=Object.entries(o.configSchema).map(([i,l])=>{let s=`${i}: ${l.type}`;return l.enum&&(s+=` (${l.enum.join("|")})`),l.required===!1&&(s+="?"),s});n+=`. Config: { ${p.join(", ")} }`}return n}function Z(a,o){if(!J(o))return`- ${a}`;let n=`- ${a}: ${o.description}`;if(o.configSchema){let p=Object.entries(o.configSchema).map(([i,l])=>{let s=`${i}: ${l.type}`;return l.required===!1&&(s+="?"),s});n+=`. Config: { ${p.join(", ")} }`}return n}function I(a,o){let n=[],p=new Set(Object.keys(o.fns??{})),i=new Set(Object.keys(o.sources??{}));for(let[l,s]of Object.entries(a.nodes)){if(s.type==="template")continue;let c=s;if(c.fn&&p.size>0&&!p.has(c.fn))if(i.has(c.fn))n.push(`Node "${l}": fn "${c.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...p].join(", ")}`);else{let e=P(c.fn,p);n.push(`Node "${l}": fn "${c.fn}" not found in catalog`+(e?`. Did you mean "${e}"?`:""))}if(c.source&&i.size>0&&!i.has(c.source))if(p.has(c.source))n.push(`Node "${l}": source "${c.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...i].join(", ")}`);else{let e=P(c.source,i);n.push(`Node "${l}": source "${c.source}" not found in catalog`+(e?`. Did you mean "${e}"?`:""))}if(c.fn&&c.config&&o.fns?.[c.fn]){let e=o.fns[c.fn];if(_(e)&&e.configSchema){for(let[m,$]of Object.entries(e.configSchema))if($.required!==!1&&!(m in c.config)&&n.push(`Node "${l}": config missing required field "${m}"`),m in c.config&&$.enum){let w=c.config[m];$.enum.includes(w)||n.push(`Node "${l}": config.${m} = ${JSON.stringify(w)}, expected one of: ${$.enum.join(", ")}`)}}}}if(a.templates){for(let[l,s]of Object.entries(a.templates))for(let[c,e]of Object.entries(s.nodes))if(e.fn&&p.size>0&&!p.has(e.fn)){let m=P(e.fn,p);n.push(`Template "${l}" node "${c}": fn "${e.fn}" not found in catalog`+(m?`. Did you mean "${m}"?`:""))}}return{valid:n.length===0,errors:n}}function P(a,o){let n=null,p=1/0,i=a.toLowerCase();for(let l of o){let s=ee(i,l.toLowerCase());s<p&&s<=Math.max(3,Math.floor(a.length/2))&&(p=s,n=l)}return n}function ee(a,o){let n=a.length,p=o.length,i=Array.from({length:n+1},(l,s)=>Array.from({length:p+1},(c,e)=>s===0?e:e===0?s:0));for(let l=1;l<=n;l++)for(let s=1;s<=p;s++)i[l][s]=a[l-1]===o[s-1]?i[l-1][s-1]:1+Math.min(i[l-1][s],i[l][s-1],i[l-1][s-1]);return i[n][p]}var Y=new Set(["state","producer","derived","effect","operator","template"]),te=new Set(["state","producer","derived","effect","operator"]);function E(a){let o=[];if(a==null||typeof a!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"]};let n=a;if((typeof n.name!="string"||n.name.length===0)&&o.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return o.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:o};let p=new Set(Object.keys(n.nodes)),i=new Map,l=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[s,c]of Object.entries(n.templates))if(c!=null&&typeof c=="object"){let e=c;l.set(s,{params:Array.isArray(e.params)?e.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))o.push("'templates' must be an object");else for(let[s,c]of Object.entries(n.templates)){if(c==null||typeof c!="object"){o.push(`Template "${s}": must be an object`);continue}let e=c;if(Array.isArray(e.params)||o.push(`Template "${s}": missing 'params' array`),e.nodes==null||typeof e.nodes!="object"||Array.isArray(e.nodes))o.push(`Template "${s}": missing or invalid 'nodes' object`);else{let m=new Set(Array.isArray(e.params)?e.params:[]),$=new Set(Object.keys(e.nodes));for(let[w,R]of Object.entries(e.nodes)){if(R==null||typeof R!="object"){o.push(`Template "${s}" node "${w}": must be an object`);continue}let r=R;if((typeof r.type!="string"||!te.has(r.type))&&o.push(`Template "${s}" node "${w}": invalid type`),Array.isArray(r.deps))for(let f of r.deps)!$.has(f)&&!m.has(f)&&o.push(`Template "${s}" node "${w}": dep "${f}" is not an inner node or param`)}typeof e.output!="string"?o.push(`Template "${s}": missing 'output' string`):e.nodes[e.output]||o.push(`Template "${s}": output "${e.output}" is not a declared node`)}}for(let[s,c]of Object.entries(n.nodes)){if(c==null||typeof c!="object"){o.push(`Node "${s}": must be an object`);continue}let e=c;if(typeof e.type!="string"||!Y.has(e.type)){o.push(`Node "${s}": invalid type "${String(e.type)}" (expected: ${[...Y].join(", ")})`);continue}if(i.set(s,e.type),e.type==="template")if(typeof e.template!="string"||!l.has(e.template))o.push(`Node "${s}": template "${String(e.template)}" not found in templates`);else if(e.bind==null||typeof e.bind!="object"||Array.isArray(e.bind))o.push(`Node "${s}": template ref requires 'bind' object`);else{let m=l.get(e.template),$=e.bind;for(let w of m.params)w in $||o.push(`Node "${s}": template param "${w}" is not bound (template "${e.template}")`);for(let[,w]of Object.entries($))typeof w=="string"&&!p.has(w)&&o.push(`Node "${s}": bind target "${w}" does not reference an existing node`)}else{if(Array.isArray(e.deps))for(let m of e.deps)m===s?o.push(`Node "${s}": self-referencing dep`):p.has(m)||o.push(`Node "${s}": dep "${m}" does not reference an existing node`);(e.type==="derived"||e.type==="effect"||e.type==="operator")&&!Array.isArray(e.deps)&&o.push(`Node "${s}": ${e.type} node should have a 'deps' array`)}}if(n.feedback!=null)if(!Array.isArray(n.feedback))o.push("'feedback' must be an array");else for(let s=0;s<n.feedback.length;s++){let c=n.feedback[s];if(c==null||typeof c!="object"){o.push(`Feedback [${s}]: must be an object`);continue}let e=c;(typeof e.from!="string"||!p.has(e.from))&&o.push(`Feedback [${s}]: 'from' "${String(e.from)}" does not reference an existing node`),typeof e.from=="string"&&e.from===e.to&&o.push(`Feedback [${s}]: 'from' and 'to' must be different nodes`),typeof e.to!="string"||!p.has(e.to)?o.push(`Feedback [${s}]: 'to' "${String(e.to)}" does not reference an existing node`):typeof e.to=="string"&&i.get(e.to)!=="state"&&o.push(`Feedback [${s}]: 'to' node "${e.to}" must be a state node (got "${i.get(e.to)??"unknown"}")`)}return{valid:o.length===0,errors:o}}function ne(a,o){let n=E(a);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
8
|
-
${n.errors.join(`
|
|
9
|
-
`)}`);let p=o?.catalog??{},i=new D(a.name),l=a.templates??{},s=I(a,p);if(!s.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
10
|
-
${s.errors.join(`
|
|
11
|
-
`)}`);let c=r=>{let f=p.fns?.[r];return f?z(f):void 0},e=r=>{let f=p.sources?.[r];return f?U(f):void 0},m=new Map,$=[];for(let[r,f]of Object.entries(a.nodes)){if(f.type==="template")continue;let d=f;if(d.type==="state"){let h=M(d.initial,{name:r,meta:d.meta?{...d.meta}:void 0});i.add(h,{name:r}),m.set(r,h)}else if(d.type==="producer"){let h=d.source?e(d.source):void 0,b=d.fn?c(d.fn):void 0;if(h){let t=h(d.config??{});i.add(t,{name:r}),m.set(r,t)}else if(b){let t=b([],d.config??{});i.add(t,{name:r}),m.set(r,t)}else{let t=A(()=>{},{name:r,meta:{...d.meta,_specFn:d.fn,_specSource:d.source}});i.add(t,{name:r}),m.set(r,t)}}else $.push([r,d])}let w=!0,R=new Map($);for(;R.size>0&&w;){w=!1;for(let[r,f]of[...R.entries()]){let d=f.deps??[];if(!d.every(y=>m.has(y)))continue;let h=d.map(y=>m.get(y)),b=f.fn?c(f.fn):void 0,t;b?t=b(h,f.config??{}):f.type==="effect"?t=T(h,()=>{}):t=L(h,y=>y[0]),i.add(t,{name:r}),m.set(r,t),R.delete(r),w=!0}}if(R.size>0){let r=[...R.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${r}`)}for(let[r,f]of Object.entries(a.nodes)){if(f.type!=="template")continue;let d=f,h=l[d.template],b=new D(r),t=new Map,y=[];for(let[g,u]of Object.entries(h.nodes)){let v=(u.deps??[]).map(j=>j.startsWith("$")&&d.bind[j]?d.bind[j]:j),F={...u,deps:v};if(u.type==="state"){let j=M(u.initial,{name:g,meta:u.meta?{...u.meta}:void 0});b.add(j,{name:g}),t.set(g,j)}else if(u.type==="producer"){let j=u.source?e(u.source):void 0,O=u.fn?c(u.fn):void 0;if(j){let S=j(u.config??{});b.add(S,{name:g}),t.set(g,S)}else if(O){let S=O([],u.config??{});b.add(S,{name:g}),t.set(g,S)}else{let S=A(()=>{},{name:g,meta:{...u.meta,_specFn:u.fn,_specSource:u.source}});b.add(S,{name:g}),t.set(g,S)}}else y.push([g,F])}let N=!0,k=new Map(y);for(;k.size>0&&N;){N=!1;for(let[g,u]of[...k.entries()]){let v=u.deps??[];if(!v.every(G=>t.has(G)||m.has(G)))continue;let j=v.map(G=>t.get(G)??m.get(G)),O=u.fn?c(u.fn):void 0,S;O?S=O(j,u.config??{}):u.type==="effect"?S=T(j,()=>{}):S=L(j,G=>G[0]),b.add(S,{name:g}),t.set(g,S),k.delete(g),N=!0}}if(k.size>0){let g=[...k.keys()].sort().join(", ");throw new Error(`compileSpec: template "${d.template}" has unresolvable deps: ${g}`)}i.mount(r,b);let x=`${r}::${h.output}`;m.set(r,i.resolve(x));try{let g=i.resolve(x);g.meta._templateName?.emit(d.template),g.meta._templateBind?.emit(d.bind)}catch{}}for(let r of a.feedback??[])q(i,r.from,r.to,{maxIterations:r.maxIterations});return i}var oe=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function se(a){let o=a.describe({detail:"standard"}),n={},p=[],i=`::${W}::`,l=/^__feedback_(?!effect_)(.+)$/,s=new Set;for(let r of Object.keys(o.nodes)){if(r.includes(i))continue;let f=l.exec(r);if(f){s.add(f[1]);let d=o.nodes[r]?.meta;d?.feedbackFrom&&d?.feedbackTo&&p.push({from:d.feedbackFrom,to:d.feedbackTo,...d.maxIterations?{maxIterations:d.maxIterations}:{}})}}for(let[r,f]of Object.entries(o.nodes)){if(r.includes(i)||l.test(r)||f.meta?._internal||r.startsWith("__feedback_effect_")||r.startsWith("__bridge_")||r.includes("::"))continue;let d={type:f.type};if(f.deps.length>0&&(d.deps=f.deps.filter(h=>!h.includes("::"))),f.type==="state"&&f.value!==void 0&&(d.initial=f.value),f.meta&&Object.keys(f.meta).length>0){let h={};for(let[b,t]of Object.entries(f.meta))oe.has(b)||(h[b]=t);Object.keys(h).length>0&&(d.meta=h)}n[r]=d}let c={},e={},m=new Set;for(let r of o.subgraphs){let f=`${r}::`;for(let[d,h]of Object.entries(o.nodes)){if(!d.startsWith(f)||d.includes(i))continue;let b=h.meta;if(b?._templateName&&b?._templateBind){let t=b._templateName,y=b._templateBind;if(!c[t]){let N={},k=new Set,x=`${r}::`;for(let[O,S]of Object.entries(o.nodes)){if(!O.startsWith(x)||O.includes(i))continue;let G=O.slice(x.length);G.includes("::")||(k.add(G),N[G]={type:S.type,...S.deps.length>0?{deps:S.deps.map(C=>C.startsWith(x)?C.slice(x.length):C)}:{}})}let g=[],u=new Map;for(let O of Object.values(N))for(let S of O.deps??[])if(!k.has(S)&&!u.has(S)){let G=`$${S}`;g.push(G),u.set(S,G)}for(let O of Object.values(N))O.deps&&(O.deps=O.deps.map(S=>u.get(S)??S));let v=new Set;for(let O of Object.values(N))for(let S of O.deps??[])k.has(S)&&v.add(S);let j=[...k].filter(O=>!v.has(O))[0]??[...k].pop();c[t]={params:g,nodes:N,output:j}}delete n[r],e[r]={type:"template",template:t,bind:y},m.add(r);break}}}let $=new Map;for(let r of o.subgraphs){if(m.has(r))continue;let f={},d=`${r}::`;for(let[b,t]of Object.entries(o.nodes)){if(b.includes(i)||!b.startsWith(d))continue;let y=b.slice(d.length);y.includes("::")||(f[y]={type:t.type,...t.deps.length>0?{deps:t.deps.map(N=>N.startsWith(d)?N.slice(d.length):N)}:{}})}let h=JSON.stringify(Object.fromEntries(Object.entries(f).sort(([b],[t])=>b.localeCompare(t)).map(([b,t])=>[b,{type:t.type,deps:t.deps??[]}])));$.has(h)||$.set(h,[]),$.get(h).push({name:r,nodes:f})}for(let[,r]of $){if(r.length<2)continue;let f=`${r[0].name}_template`,d=r[0].nodes,h=new Set(Object.keys(d)),b=[],t=new Map;for(let g of Object.values(d))for(let u of g.deps??[])if(!h.has(u)&&!t.has(u)){let v=`$${u}`;b.push(v),t.set(u,v)}let y=new Set;for(let g of Object.values(d))for(let u of g.deps??[])h.has(u)&&y.add(u);let k=[...h].filter(g=>!y.has(g))[0]??[...h].pop(),x={};for(let[g,u]of Object.entries(d))x[g]={...u,deps:u.deps?.map(v=>t.get(v)??v)};c[f]={params:b,nodes:x,output:k};for(let g of r){delete n[g.name];let u={},v=new Set(Object.keys(g.nodes));for(let F of Object.values(g.nodes))for(let j of F.deps??[])if(!v.has(j)){let O=t.get(j)??`$${j}`;u[O]=j}e[g.name]={type:"template",template:f,bind:u}}}let w={...n,...e},R={name:o.name,nodes:w};return Object.keys(c).length>0&&(R.templates=c),p.length>0&&(R.feedback=p),R}function re(a,o){let n=[];a.name!==o.name&&n.push({type:"changed",path:"name",detail:`"${a.name}" \u2192 "${o.name}"`});let p=new Set(Object.keys(a.nodes)),i=new Set(Object.keys(o.nodes));for(let t of i)if(!p.has(t)){let y=o.nodes[t];n.push({type:"added",path:`nodes.${t}`,detail:`type: ${y.type}`})}for(let t of p)i.has(t)||n.push({type:"removed",path:`nodes.${t}`});for(let t of p){if(!i.has(t))continue;let y=a.nodes[t],N=o.nodes[t];if(JSON.stringify(y)!==JSON.stringify(N)){let k=[];y.type!==N.type&&k.push(`type: ${y.type} \u2192 ${N.type}`),JSON.stringify(y.deps)!==JSON.stringify(N.deps)&&k.push("deps changed"),y.fn!==N.fn&&k.push(`fn: ${y.fn} \u2192 ${N.fn}`),JSON.stringify(y.config)!==JSON.stringify(N.config)&&k.push("config changed"),n.push({type:"changed",path:`nodes.${t}`,detail:k.join("; ")||"modified"})}}let l=a.templates??{},s=o.templates??{},c=new Set(Object.keys(l)),e=new Set(Object.keys(s));for(let t of e)c.has(t)||n.push({type:"added",path:`templates.${t}`});for(let t of c)e.has(t)||n.push({type:"removed",path:`templates.${t}`});for(let t of c)e.has(t)&&JSON.stringify(l[t])!==JSON.stringify(s[t])&&n.push({type:"changed",path:`templates.${t}`,detail:"template definition changed"});let m=a.feedback??[],$=o.feedback??[],w=new Set(m.map(t=>`${t.from}->${t.to}`)),R=new Set($.map(t=>`${t.from}->${t.to}`));for(let t of $){let y=`${t.from}->${t.to}`;w.has(y)||n.push({type:"added",path:`feedback.${y}`,detail:`maxIterations: ${t.maxIterations??10}`})}for(let t of m){let y=`${t.from}->${t.to}`;R.has(y)||n.push({type:"removed",path:`feedback.${y}`})}for(let t of m){let y=`${t.from}->${t.to}`,N=$.find(k=>k.from===t.from&&k.to===t.to);N&&JSON.stringify(t)!==JSON.stringify(N)&&n.push({type:"changed",path:`feedback.${y}`,detail:`maxIterations: ${t.maxIterations??10} \u2192 ${N.maxIterations??10}`})}let r=n.filter(t=>t.type==="added").length,f=n.filter(t=>t.type==="removed").length,d=n.filter(t=>t.type==="changed").length,h=[];r&&h.push(`${r} added`),f&&h.push(`${f} removed`),d&&h.push(`${d} changed`);let b=h.length>0?h.join(", "):"no changes";return{entries:n,summary:b}}var B=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
12
|
-
|
|
13
|
-
Given a natural-language description, produce a JSON GraphSpec with this structure:
|
|
14
|
-
|
|
15
|
-
{
|
|
16
|
-
"name": "<graph_name>",
|
|
17
|
-
"nodes": {
|
|
18
|
-
"<node_name>": {
|
|
19
|
-
"type": "state" | "derived" | "producer" | "effect" | "operator",
|
|
20
|
-
"deps": ["<dep_node_name>", ...],
|
|
21
|
-
"fn": "<catalog_function_name>",
|
|
22
|
-
"source": "<catalog_source_name>",
|
|
23
|
-
"config": { ... },
|
|
24
|
-
"initial": <value>,
|
|
25
|
-
"meta": { "description": "<purpose>" }
|
|
26
|
-
},
|
|
27
|
-
"<template_instance>": {
|
|
28
|
-
"type": "template",
|
|
29
|
-
"template": "<template_name>",
|
|
30
|
-
"bind": { "$param": "node_name" }
|
|
31
|
-
}
|
|
32
|
-
},
|
|
33
|
-
"templates": {
|
|
34
|
-
"<template_name>": {
|
|
35
|
-
"params": ["$param1", "$param2"],
|
|
36
|
-
"nodes": { ... },
|
|
37
|
-
"output": "<output_node>"
|
|
38
|
-
}
|
|
39
|
-
},
|
|
40
|
-
"feedback": [
|
|
41
|
-
{ "from": "<condition_node>", "to": "<state_node>", "maxIterations": 10 }
|
|
42
|
-
]
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
Rules:
|
|
46
|
-
- "state" nodes hold user/LLM-writable values (knobs). Use "initial" for default values.
|
|
47
|
-
- "derived" nodes compute from deps using a named "fn".
|
|
48
|
-
- "effect" nodes produce side effects from deps.
|
|
49
|
-
- "producer" nodes generate values from a named "source".
|
|
50
|
-
- Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
|
|
51
|
-
- Use "feedback" for bounded cycles where a derived value writes back to a state node.
|
|
52
|
-
- meta.description is required for every node.
|
|
53
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;function K(a){let o=a.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return o?o[1]:a}async function ae(a,o,n){let p=B,i=n?.catalogDescription??(n?.catalog?V(n.catalog):void 0);i&&(p+=`
|
|
54
|
-
|
|
55
|
-
Available catalog (use ONLY these names):
|
|
56
|
-
${i}`),n?.systemPromptExtra&&(p+=`
|
|
57
|
-
|
|
58
|
-
${n.systemPromptExtra}`);let l=[{role:"system",content:p},{role:"user",content:a}],e=(await o.invoke(l,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();e.startsWith("```")&&(e=K(e));let m;try{m=JSON.parse(e)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${e.slice(0,200)}`)}let $=E(m);if(!$.valid)throw new Error(`llmCompose: invalid GraphSpec:
|
|
59
|
-
${$.errors.join(`
|
|
60
|
-
`)}`);let w=m;if(n?.catalog){let R=n.maxAutoRefine??0;for(let r=0;r<=R;r++){let f=I(w,n.catalog);if(f.valid)break;if(r===R)throw new Error(`llmCompose: catalog validation failed after ${R} refine attempts:
|
|
61
|
-
${f.errors.join(`
|
|
62
|
-
`)}`);w=await H(w,`Fix these catalog errors:
|
|
63
|
-
${f.errors.join(`
|
|
64
|
-
`)}
|
|
65
|
-
|
|
66
|
-
Use ONLY functions and sources from the catalog.`,o,{...n,catalogDescription:i})}}return w}async function H(a,o,n,p){let i=B;p?.catalogDescription&&(i+=`
|
|
67
|
-
|
|
68
|
-
Available catalog:
|
|
69
|
-
${p.catalogDescription}`),p?.systemPromptExtra&&(i+=`
|
|
70
|
-
|
|
71
|
-
${p.systemPromptExtra}`);let l=[{role:"system",content:i},{role:"user",content:`Current GraphSpec:
|
|
72
|
-
${JSON.stringify(a,null,2)}
|
|
73
|
-
|
|
74
|
-
Modification request: ${o}
|
|
75
|
-
|
|
76
|
-
Return the complete modified GraphSpec as JSON.`}],e=(await n.invoke(l,{model:p?.model,temperature:p?.temperature??0,maxTokens:p?.maxTokens})).content.trim();e.startsWith("```")&&(e=K(e));let m;try{m=JSON.parse(e)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${e.slice(0,200)}`)}let $=E(m);if(!$.valid)throw new Error(`llmRefine: invalid GraphSpec:
|
|
77
|
-
${$.errors.join(`
|
|
78
|
-
`)}`);return m}export{_ as a,J as b,z as c,U as d,V as e,I as f,E as g,ne as h,se as i,re as j,ae as k,H as l,ie as m};
|
package/dist/chunk-ISCENNXS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{m as b,w as g}from"./chunk-KASHOCF5.js";import{i as p,j as T}from"./chunk-CK2E7BTU.js";function K(l,y={}){let u=y.keyFn??(n=>String(n)),t=new Map;return n=>{let r=u(n),a=t.get(r);if(a)return a;let e=l(n),i;e!=null&&typeof e.then=="function"?i=Promise.resolve(e):e!=null&&typeof e=="object"&&"subscribe"in e&&"cache"in e?i=g(e):e!=null&&typeof e=="object"&&Symbol.asyncIterator in e?i=(async()=>{let o=e[Symbol.asyncIterator]();try{let{value:m,done:f}=await o.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return m}finally{await o.return?.()}})():e!=null&&typeof e=="object"&&Symbol.iterator in e?i=(async()=>{let o=e[Symbol.iterator]();try{let{value:m,done:f}=o.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return m}finally{o.return?.()}})():i=Promise.resolve(e);let s,c=()=>{t.get(r)===s&&t.delete(r)};return s=i.then(o=>(c(),o),o=>{throw c(),o}),t.set(r,s),s}}function k(l,y={}){let u=y.keyFn??(n=>String(n)),t=new Map;return n=>{let r=u(n),a=t.get(r);if(a)return a;let e=b(l(n));t.set(r,e);let i=e.subscribe(s=>{for(let c of s)if(c[0]===T||c[0]===p){t.get(r)===e&&t.delete(r),i();return}});return e}}export{K as a,k as b};
|
package/dist/chunk-IUK4EFCE.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as A,v}from"./chunk-5JDE5JHE.js";import{b as I}from"./chunk-2GQREQ6C.js";import{m as p,r as y}from"./chunk-KASHOCF5.js";import{E as R,G as w,m as h}from"./chunk-W4TSQ6RJ.js";import{b}from"./chunk-CK2E7BTU.js";function z(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function F(t,a,e){let r=p(t),i=r.v!=null,g=R(e?.initialVerified??null,{...i?{meta:{sourceVersion:null}}:{}}),x=e?.trigger!==void 0&&e.trigger!==null,s=null;if(x&&e?.autoVerify?s=A(p(e.trigger),r):x?s=p(e.trigger):e?.autoVerify&&(s=r),s!==null){let d;if(s===r)d=v(r,c=>a(c));else{let c=r.cache;r.subscribe(f=>{for(let M of f)M[0]===b&&(c=M[1])}),d=v(s,()=>a(c))}y(d,c=>{h(()=>{if(g.down([[b,c]]),i){let f=r.v;f!=null&&g.meta.sourceVersion.down([[b,{id:f.id,version:f.version}]])}})})}return{node:r,verified:g,trigger:s}}function E(t){t.subscribe(()=>{})}function k(t){return t instanceof Map?t:new Map}function B(t,a){if(!Array.isArray(a.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");h(()=>{for(let{key:e,value:r}of a.upsert)t.set(e,r);for(let e of a.remove??[])t.delete(e)})}function G(t,a,e){let r=p(t),i=I(e.mapOptions??{}),g=e.budget??2e3,s=e.context!==void 0&&e.context!==null?p(e.context):R(null),d=k(i.entries.cache);i.entries.subscribe(o=>{for(let u of o)u[0]===b&&(d=k(u[1]))});let c=v(r,o=>a(o,d));if(y(c,o=>{B(i,o)}),e.evict){let o=new Map,u=w([i.entries],([l])=>{let m=[],N=k(l);for(let n of o.keys())N.has(n)||(o.get(n)(),o.delete(n));for(let[n,T]of N){let V=e.evict(n,T);if(z(V)){if(!o.has(n)){let S=y(V,D=>{D===!0&&i.has(n)&&i.delete(n)});o.set(n,S)}continue}if(typeof V=="boolean"){V&&m.push(n);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return m});y(u,l=>{for(let m of l)i.delete(m)})}let f=e.consolidateTrigger!==void 0&&e.consolidateTrigger!==null;if(e.consolidate&&f){let o=p(e.consolidateTrigger),u=v(o,()=>e.consolidate(d));y(u,l=>{B(i,l)})}let M=w([i.entries,s],([o,u])=>{let l=[...k(o).entries()].map(([n,T])=>({key:n,value:T,score:e.score(T,u),cost:e.cost(T)}));l.sort((n,T)=>T.score-n.score);let m=[],N=g;for(let n of l)n.cost<=N&&(m.push({key:n.key,value:n.value,score:n.score}),N-=n.cost);return m}),O=w([i.entries],([o])=>k(o).size);return E(M),E(O),{store:i,compact:M,size:O}}export{F as a,G as b};
|
package/dist/chunk-KASHOCF5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{D as N,E as C,F as p,p as A}from"./chunk-W4TSQ6RJ.js";import{b as h,c as S,d as x,i as T,j as b}from"./chunk-CK2E7BTU.js";function y(e,n,t){let s=new Set;for(let i of e.split(",")){let[r,o]=i.split("/"),u=o?Number.parseInt(o,10):1;if(Number.isNaN(u)||u<1)throw new Error(`Invalid cron step: ${i}`);let a,d;if(r==="*")a=n,d=t;else if(r.includes("-")){let[f,c]=r.split("-");a=Number.parseInt(f,10),d=Number.parseInt(c,10)}else a=Number.parseInt(r,10),d=a;if(Number.isNaN(a)||Number.isNaN(d))throw new Error(`Invalid cron field: ${e}`);if(a<n||d>t)throw new Error(`Cron field out of range: ${e} (${n}-${t})`);if(a>d)throw new Error(`Invalid cron range: ${a}-${d} in ${e}`);for(let f=a;f<=d;f+=u)s.add(f)}return s}function I(e){let n=e.trim().split(/\s+/);if(n.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${n.length}`);return{minutes:y(n[0],0,59),hours:y(n[1],0,23),daysOfMonth:y(n[2],1,31),months:y(n[3],1,12),daysOfWeek:y(n[4],0,6)}}function L(e,n){return e.minutes.has(n.getMinutes())&&e.hours.has(n.getHours())&&e.daysOfMonth.has(n.getDate())&&e.months.has(n.getMonth()+1)&&e.daysOfWeek.has(n.getDay())}function m(e){return{describeKind:"producer",...e}}function $(e){return/[\\^$+?.()|[\]{}]/.test(e)?`\\${e}`:e}function J(e){let n="^";for(let t=0;t<e.length;t+=1){let s=e[t];if(s==="*"){e[t+1]==="*"?(n+=".*",t+=1):n+="[^/]*";continue}n+=$(s)}return n+="$",new RegExp(n)}function Q(e,n){for(let t of n)if(t.test(e))return!0;return!1}function _(e,n){let t=N([e],(i,r)=>{let o=i[0];if(o==null||o.length===0){r.down([[x]]);return}for(let u of o)r.emit(u)},{describeKind:"derived",initial:e.cache}),s=t.subscribe.bind(t);return t.subscribe=(i,r)=>(n(i),s(i,r)),t}function X(e,n){let{signal:t,period:s,...i}=n??{};return p(r=>{let o=!1,u=0,a,d,f=()=>{o=!0,a!==void 0&&clearTimeout(a),d!==void 0&&clearInterval(d),t?.removeEventListener("abort",l)},c=()=>{o||(s!=null?(r.emit(u++),d=setInterval(()=>{o||r.emit(u++)},s)):(o=!0,t?.removeEventListener("abort",l),r.emit(u++),r.down([[T]])))},l=()=>{o||(f(),r.down([[b,t.reason]]))};if(t?.aborted){l();return}return a=setTimeout(c,e),t?.addEventListener("abort",l,{once:!0}),f},m(i))}function Z(e){let{signal:n,...t}=e??{};return p(s=>{let i=!1,r,o,u=!1,a=!1,d=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,f=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,c=typeof document<"u"?document:void 0,l=()=>{r!==void 0&&f&&f(r),o!==void 0&&clearTimeout(o),r=void 0,o=void 0},v=()=>{i=!0,l(),u&&(n?.removeEventListener("abort",w),u=!1),a&&c&&(c.removeEventListener("visibilitychange",k),a=!1)},w=()=>{i||(v(),s.down([[b,n.reason]]))},O=F=>{i||(s.emit(F),g())},g=()=>{i||(d&&(!c||c.visibilityState!=="hidden")?r=d(O):o=setTimeout(()=>O(performance.now()),16))},k=()=>{i||(l(),g())};return n?.aborted?(w(),v):(n?.addEventListener("abort",w,{once:!0}),u=n!==void 0,c&&d&&(c.addEventListener("visibilitychange",k),a=!0),g(),v)},m(t))}function ee(e,n){let t=I(e),{tickMs:s,output:i,...r}=n??{},o=s??6e4,u=i==="date";return p(a=>{let d=-1,f=()=>{let l=new Date,v=l.getFullYear()*1e8+(l.getMonth()+1)*1e6+l.getDate()*1e4+l.getHours()*100+l.getMinutes();v!==d&&L(t,l)&&(d=v,a.emit(u?l:A()))};f();let c=setInterval(f,o);return()=>clearInterval(c)},{...m(r),name:r.name??`cron:${e}`})}function ne(e,n,t){let{capture:s,passive:i,once:r,...o}=t??{};return p(u=>{let a=f=>{u.emit(f)},d={capture:s,passive:i,once:r};return e.addEventListener(n,a,d),()=>e.removeEventListener(n,a,d)},m(o))}function M(e,n){return p(t=>{let s=!1;try{for(let i of e){if(s)return;t.emit(i)}s||t.down([[T]])}catch(i){s||t.down([[b,i]])}return()=>{s=!0}},m(n))}function K(e){return e!=null&&typeof e.then=="function"}function W(e,n){let{signal:t,...s}=n??{};return p(i=>{let r=!1,o=()=>{r||(r=!0,i.down([[b,t.reason]]))};if(t?.aborted){o();return}return t?.addEventListener("abort",o,{once:!0}),Promise.resolve(e).then(u=>{r||(r=!0,t?.removeEventListener("abort",o),i.emit(u),i.down([[T]]))},u=>{r||(r=!0,t?.removeEventListener("abort",o),i.down([[b,u]]))}),()=>{r=!0,t?.removeEventListener("abort",o)}},m(s))}function q(e,n){let{signal:t,...s}=n??{};return p(i=>{let r=new AbortController,o=()=>r.abort(t?.reason);t?.aborted?r.abort(t.reason):t?.addEventListener("abort",o,{once:!0});let u=t??r.signal,a=!1,d=e[Symbol.asyncIterator](),f=()=>{a||u.aborted||Promise.resolve(d.next()).then(c=>{if(!(a||u.aborted)){if(c.done){i.down([[T]]);return}i.emit(c.value),f()}},c=>{!a&&!u.aborted&&i.down([[b,c]])})};return f(),()=>{a=!0,t?.removeEventListener("abort",o),r.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},m(s))}function H(e){return e!=null&&typeof e=="object"&&"cache"in e&&typeof e.subscribe=="function"}function te(e,n){if(H(e))return e;if(K(e))return W(e,n);if(e!=null){let t=e;if(typeof t[Symbol.asyncIterator]=="function")return q(e,n);if(typeof t[Symbol.iterator]=="function")return M(e,n)}return V(e)}function V(...e){return M(e,void 0)}function re(e){return p(n=>{n.down([[T]])},m(e))}function oe(e){return p(()=>{},m(e))}function ie(e,n){return p(t=>{t.down([[b,e]])},m(n))}function se(e,n,t){return N([e],(i,r)=>{let o=i[0];if(o!=null&&o.length>0)for(let u of o)n(u)},{describeKind:"effect",...t}).subscribe(()=>{})}function ue(e,n){return N([e],(t,s,i)=>{i.store.buf||(i.store.buf=[]);let r=i.store.buf,o=t[0];if(o!=null&&o.length>0)for(let u of o)r.push(u);if(i.terminalDeps[0]===!0){s.emit([...r]),s.down([[T]]);return}(o==null||o.length===0)&&s.down([[x]])},{describeKind:"derived",completeWhenDepsComplete:!1,...n})}function ae(e,n){return p(t=>e.subscribe(s=>{t.down(s)}),{...m(n),initial:e.cache})}function D(e,n,t){if(n<1)throw new RangeError("replay expects bufferSize >= 1");let s=[],i=p(r=>e.subscribe(o=>{for(let u of o)u[0]===h&&(s.push(u[1]),s.length>n&&s.shift());r.down(o)}),{...m(t),initial:e.cache});return _(i,r=>{for(let o of s)r([[h,o]])})}function de(e,n){return D(e,1,n)}function fe(e){return new Promise((n,t)=>{let s=!1,i=!1,r;r=e.subscribe(o=>{for(let u of o){if(s)return;if(u[0]===h){s=!0,n(u[1]),r?(r(),r=void 0):i=!0;return}if(u[0]===b){s=!0,t(u[1]),r?(r(),r=void 0):i=!0;return}if(u[0]===T){s=!0,t(new Error("completed without DATA")),r?(r(),r=void 0):i=!0;return}}}),i&&(r?.(),r=void 0)})}function P(e,n){return new Promise((t,s)=>{let i=!1,r=!1,o;o=e.subscribe(u=>{for(let a of u){if(i)return;if(a[0]===h){let d=a[1];if(n(d)){i=!0,t(d),o?(o(),o=void 0):r=!0;return}}if(a[0]===b){i=!0,s(a[1]),o?(o(),o=void 0):r=!0;return}if(a[0]===T){i=!0,s(new Error("completed without matching value")),o?(o(),o=void 0):r=!0;return}}}),r&&(o?.(),o=void 0)})}var E,R;async function ce(e,n){let t=n?.predicate??(i=>i!=null);if(n?.timeoutMs==null||n.timeoutMs<=0)return await P(e,t);if(E===void 0){let[i,r]=await Promise.all([import("./resilience-XRUF267O.js"),import("./backoff-HPZMEZNF.js")]);E=i.timeout,R=r.NS_PER_MS}let s=E(e,n.timeoutMs*R);return await P(s,t)}var le=D;function pe(e){return e.subscribe(()=>{})}function me(e){let n=C(0);return{node:n,increment(){let t=n.cache??0;return t>=e?!1:(n.down([[S],[h,t+1]]),!0)},get(){return n.cache??0},atCap(){return(n.cache??0)>=e}}}export{I as a,L as b,$ as c,J as d,Q as e,X as f,Z as g,ee as h,ne as i,M as j,W as k,q as l,te as m,V as n,re as o,oe as p,ie as q,se as r,ue as s,ae as t,D as u,de as v,fe as w,P as x,ce as y,le as z,pe as A,me as B};
|
package/dist/chunk-LI3E75VE.js
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import{a as mt,b as ct,d as pt,e as ft}from"./chunk-4OFIQ66T.js";import{e as dt}from"./chunk-VWPRPPKR.js";import{e as De}from"./chunk-33FA6V4B.js";import{a as Ct,b as Pt,c as jt,d as _t,e as Dt,f as _e}from"./chunk-NSG4C6BF.js";import{a as Me,b as At,c as St,d as Et,e as It,f as Ot}from"./chunk-7JDLFI6N.js";import{c as it}from"./chunk-5Z4HDCO6.js";import{b as ut}from"./chunk-IUK4EFCE.js";import{b as rt,c as Re,d as nt,f as je}from"./chunk-OL33ZI6R.js";import{k as Z}from"./chunk-MGKAO4EK.js";import{a as X}from"./chunk-ESMPEKEV.js";import{P as lt,v as J}from"./chunk-5JDE5JHE.js";import{b as ge}from"./chunk-AUY2YKCO.js";import{A as K,f as ot,m as w,w as at,y as st}from"./chunk-KASHOCF5.js";import{D as se,E as v,F as Pe,G as x,H as ie,m as ae,o as W,p as Te}from"./chunk-W4TSQ6RJ.js";import{b as q,d as fe,i as re,j as Y}from"./chunk-CK2E7BTU.js";import{b as Nt}from"./chunk-QYADASLV.js";var _r={};Nt(_r,{AgentLoopGraph:()=>Oe,AllTiersExhaustedError:()=>Dt,BudgetExhaustedError:()=>Ne,ChatStreamGraph:()=>Ee,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>Xe,FallbackMissError:()=>It,LLMTimeoutError:()=>he,ReplayCacheMissError:()=>At,ToolRegistryGraph:()=>Ie,admissionFilter3D:()=>Cr,agentLoop:()=>Rr,agentMemory:()=>Ar,anthropicAdapter:()=>Ct,canonicalJson:()=>Et,cascadingLlmAdapter:()=>_e,chatStream:()=>ze,composePricing:()=>Kt,computePrice:()=>yt,contentGate:()=>kr,costMeterExtractor:()=>gr,createAdapter:()=>_t,createCapabilitiesRegistry:()=>Ft,createPricingRegistry:()=>$t,dryRunAdapter:()=>Me,dryRunPreset:()=>rr,fallbackAdapter:()=>Ot,fromLLM:()=>nr,frozenContext:()=>lr,gatedStream:()=>cr,gaugesAsContext:()=>Sr,googleAdapter:()=>Pt,graphFromSpec:()=>Er,handoff:()=>Lr,keywordFlagExtractor:()=>hr,knobsAsTools:()=>Or,llmConsolidator:()=>Qe,llmExtractor:()=>Ye,observableAdapter:()=>Gt,openAICompatAdapter:()=>jt,parseRateLimitFromError:()=>Ke,promptNode:()=>dr,redactor:()=>vr,registryPricing:()=>Wt,resilientAdapter:()=>tr,streamExtractor:()=>br,streamingPromptNode:()=>mr,suggestStrategy:()=>jr,systemPromptBuilder:()=>pr,toolCallExtractor:()=>Mr,toolRegistry:()=>Je,toolSelector:()=>wr,validateGraphDef:()=>Ze,withBreaker:()=>Be,withBudgetGate:()=>We,withDryRun:()=>Vt,withRateLimiter:()=>Ve,withReplayCache:()=>St,withRetry:()=>He,withTimeout:()=>qe,zeroPrice:()=>Ge});function Le(t,e){return`${t}::${e}`}function Ft(t){let e=new Map,r=new Map,o=n=>{e.set(Le(n.provider,n.id),n);let a=r.get(n.provider);a||(a=new Set,r.set(n.provider,a)),a.add(n.id)};if(t)for(let n of t)o(n);return{register:o,lookup(n,a){let s=e.get(Le(n,a));if(s)return s;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(Le(n,m));d&&(l={key:m,cap:d})}return l?.cap},remove(n,a){let s=e.delete(Le(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){return e.values()}}}function ne(t){let e=t.input,r=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 r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function le(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function gt(){return{input:{regular:0},output:{regular:0}}}function Gt(t,e){let r=e?.logMax??1e3,o=ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),n=v(null,{name:"adapterStats/lastCall"}),a=v(0,{name:"adapterStats/totalCalls"}),s=v(0,{name:"adapterStats/totalInputTokens"}),i=v(0,{name:"adapterStats/totalOutputTokens"}),l=p=>{o.append(p),n.emit(p),a.emit((a.cache??0)+1),s.emit((s.cache??0)+ne(p.usage)),i.emit((i.cache??0)+le(p.usage))},m=()=>{o.clear(),n.emit(null),a.emit(0),s.emit(0),i.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(p,c){let f=W(),y=Te(),g=t.invoke(p,c),T=b=>{let A=W();return l({timestamp:A,wallClock:y,provider:t.provider,model:t.model??c?.model??b.model??"",tier:c?.tier??b.tier,usage:b.usage??Fe(),latencyMs:Math.max(0,(A-f)/1e6),method:"invoke"}),b};if(g!=null&&typeof g.then=="function")return g.then(T);if(g!=null&&typeof g=="object"&&"content"in g)return T(g);let C=!1;return x([w(g)],([b])=>b==null||C?b:(C=!0,T(b)),{name:"adapterStats/invokeTap"})},async*stream(p,c){let f=W(),y=Te(),g;try{for await(let C of t.stream(p,c))C.type==="usage"&&(g=C.usage),yield C;let T=W();l({timestamp:T,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(T-f)/1e6),method:"stream"})}catch(T){let C=W(),b=T;throw l({timestamp:C,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(C-f)/1e6),method:"stream",error:{type:b?.name??"Error",message:b?.message??String(T)}}),T}}},stats:{lastCall:n,allCalls:o,totalCalls:a,totalInputTokens:s,totalOutputTokens:i,reset:m}}}function Fe(){return{input:{regular:0},output:{regular:0}}}function Bt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ge(t="USD"){return{total:0,currency:t}}function yt(t,e,r){let o=ne(t),n=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,i=0,l=(g,T,C)=>{if(!T||C==null)return;let b=Bt(C,o),A=T*b/1e6;i+=A,a&&(s[g]=(s[g]??0)+A)},m=t.input,d=e.input;if(d&&(l("input.regular",m.regular,d.regular),l("input.cacheRead",m.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",m.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",m.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",m.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",m.audio??0,d.audio),l("input.image",m.image??0,d.image),l("input.video",m.video??0,d.video),l("input.toolUse",m.toolUse??0,d.toolUse),m.extensions&&d.extensions))for(let[g,T]of Object.entries(m.extensions))l(`input.ext.${g}`,T,d.extensions[g]);let u=t.output,p=e.output;if(p&&(l("output.regular",u.regular,p.regular),l("output.reasoning",u.reasoning??0,p.reasoning),l("output.audio",u.audio??0,p.audio),l("output.predictionAccepted",u.predictionAccepted??0,p.predictionAccepted),l("output.predictionRejected",u.predictionRejected??0,p.predictionRejected),u.extensions&&p.extensions))for(let[g,T]of Object.entries(u.extensions))l(`output.ext.${g}`,T,p.extensions[g]);let c=r?.tier;if(c&&e.tierMultipliers){let g=e.tierMultipliers[c];if(g!=null&&(i*=g,a))for(let T of Object.keys(s))s[T]*=g}let f=t.auxiliary,y=e.auxiliary;if(f&&y)for(let[g,T]of Object.entries(f)){let C=y[g];if(C==null||!T)continue;let b=T*C;i+=b,a&&(s[`auxiliary.${g}`]=b)}return a?{total:i,currency:n,breakdown:s}:{total:i,currency:n}}function we(t,e){return`${t}::${e}`}function $t(t){let e=new Map,r=new Map,o=(n,a,s)=>{e.set(we(n,a),{provider:n,model:a,pricing:s});let i=r.get(n);i||(i=new Set,r.set(n,i)),i.add(a)};if(t)for(let[n,a,s]of t)o(n,a,s);return{register:o,lookup(n,a){let s=e.get(we(n,a));if(s)return s.pricing;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(we(n,m));d&&(l={key:m,pricing:d.pricing})}return l?.pricing},remove(n,a){let s=e.delete(we(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){let n=e.values();return(function*(){for(let{provider:a,model:s,pricing:i}of n)yield[a,s,i]})()}}}function Wt(t,e="USD"){return(r,o)=>{let n=t.lookup(o.provider,o.model);return n?yt(r,n,{tier:o.tier,withBreakdown:o.withBreakdown}):Ge(e)}}function Kt(...t){return(e,r)=>{for(let o of t){let n=o(e,r);if(n.total!==0)return n}return t.length>0?t[0](e,r):Ge()}}function Be(t,e={}){let r=e.breaker??nt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){if(!r.canExecute())throw new Re;try{let s=await Promise.resolve(t.invoke(n,a));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(n,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(n,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}},breaker:r}}var Ne=class extends Error{constructor(r,o,n){super(`Budget exhausted: ${r} (limit=${o}, observed=${n})`);this.which=r;this.limit=o;this.observed=n}name="BudgetExhaustedError"},$e=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ht=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function We(t,e){let r=ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),o=v(ht(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),n=x([o],([d])=>{let u=d;return!(e.caps.calls!=null&&u.calls>=e.caps.calls||e.caps.inputTokens!=null&&u.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&u.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&u.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(K(n),e.onExhausted!=null){let d=e.onExhausted,u=!1,p=!0;n.subscribe(c=>{for(let f of c)if(f[0]===q){let y=f[1];if(u&&p&&y===!1){let g=bt(o.cache??$e,e.caps);g&&d(g)}p=y,u=!0}})}let a=()=>{if(n.cache===!1){let d=o.cache??$e,u=bt(d,e.caps);return new Ne(u??"budget",e.caps[u??"calls"]??0,Ut(d,u??"calls"))}},s=(d,u)=>{let p=t.provider,c={timestamp:W(),wallClock:Te(),provider:p,model:u.model,tier:u.tier,usage:d,latencyMs:u.latencyMs,method:u.method,...u.error?{error:u.error}:{}};r.append(c);let f=o.cache??$e,y=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:p,tier:u.tier}).total:f.usd;o.emit({calls:f.calls+1,inputTokens:f.inputTokens+ne(d),outputTokens:f.outputTokens+le(d),usd:y})},i=()=>{r.clear(),o.emit(ht())},l=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,u){let p=a();if(p)return Promise.reject(p);let c=W(),f=t.invoke(d,u),y=T=>{let C=Math.max(0,(W()-c)/1e6);return s(T.usage??l(),{model:t.model??u?.model??T.model??"",tier:u?.tier??T.tier,latencyMs:C,method:"invoke"}),T};if(f!=null&&typeof f.then=="function")return f.then(y);if(f!=null&&typeof f=="object"&&"content"in f)return y(f);let g=!1;return x([w(f)],([T])=>T==null||g?T:(g=!0,y(T)),{name:"budgetGate/invokeTap"})},async*stream(d,u){let p=a();if(p)throw p;let c=W(),f;try{for await(let y of t.stream(d,u))y.type==="usage"&&(f=y.usage),yield y;s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream"})}catch(y){let g=y;throw s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(y)}}),y}}},budget:{totals:o,isOpen:n,log:r,reset:i}}}function bt(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 Ut(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function Vt(t,e){let r=e.mock??Me({provider:t.provider,model:t.model}),o=typeof e.enabled=="boolean"?e.enabled:void 0,n=o===void 0?w(e.enabled):void 0,a;n&&(a=K(n));let s=()=>o!==void 0?o:!!n?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(m,d){return s()?r.invoke(m,d):t.invoke(m,d)},stream(m,d){return s()?r.stream(m,d):t.stream(m,d)}},dispose:()=>{a&&(a(),a=void 0)}}}function Ke(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,o=Ht(e.headers);if(r!==429&&r!==503&&!Xt(e.message))return;let n={},a=o("retry-after"),s=zt(a);s!=null&&(n.retryAfterMs=s);let i=o("anthropic-ratelimit-requests-reset");if(i){let c=Tt(i);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let l=o("anthropic-ratelimit-tokens-reset");if(l){let c=Tt(l);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let m=Ce(o,"x-ratelimit-limit-requests");m!=null&&(n.rpmCap=m);let d=Ce(o,"x-ratelimit-limit-tokens");d!=null&&(n.tpmCap=d);let u=Ce(o,"x-ratelimit-remaining-requests"),p=Ce(o,"x-ratelimit-remaining-tokens");if(u!=null&&m!=null&&m>0&&(n.usageHint??={},n.usageHint.rpm=1-u/m),p!=null&&d!=null&&d>0&&(n.usageHint??={},n.usageHint.tpm=1-p/d),n.retryAfterMs==null&&e.message){let c=Yt(e.message);c!=null&&(n.retryAfterMs=c)}return e.headers&&(n.metadata={headers:qt(e.headers)}),n.retryAfterMs==null&&n.rpmCap==null&&n.tpmCap==null&&n.usageHint==null?n.metadata?n:void 0:n}function Ht(t){if(!t)return()=>{};if(typeof t.get=="function"){let o=t;return n=>o.get(n)??o.get(n.toLowerCase())??void 0}let e=t,r={};for(let[o,n]of Object.entries(e)){let a=Array.isArray(n)?n.join(", "):n;a!=null&&(r[o.toLowerCase()]=a)}return o=>r[o.toLowerCase()]}function qt(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,o)=>{e[o]=r}),e;for(let[r,o]of Object.entries(t))o!=null&&(e[r]=Array.isArray(o)?o.join(", "):o);return e}function Ce(t,e){let r=t(e);if(r==null)return;let o=Number(r);return Number.isFinite(o)?o:void 0}function zt(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let o=Date.parse(e);if(Number.isFinite(o)){let n=o-Date.now();if(n>0)return n}}function Tt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Jt=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Yt(t){let e=Jt.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let o=(e[2]??"s").toLowerCase();if(o==="ms")return r;if(o.startsWith("s"))return r*1e3;if(o.startsWith("m"))return r*6e4}var Qt=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Xt(t){return!!t&&Qt.test(t)}function Ue(t){let e=new Error(t);return e.name="AbortError",e}function kt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,o=t.rpm!=null?w(t.rpm):v(Number.POSITIVE_INFINITY),n=t.tpm!=null?w(t.tpm):v(Number.POSITIVE_INFINITY),a=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=v({},{name:"adaptiveRateLimiter/lastSignal"}),l=x([o,a],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),m=x([n,s],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=ye(Number(o.cache??Number.POSITIVE_INFINITY),e),u=ye(Number(n.cache??Number.POSITIVE_INFINITY),e),p=!1,c=!1,f=l.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(d=ye(P,e),p=!1):P===1/0?(d=ye(1/0,e),p=!1):P<=0&&(p=!0)}}),y=m.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(u=ye(P,e),c=!1):P===1/0?(u=ye(1/0,e),c=!1):P<=0&&(c=!0)}}),g=0,T=new X,C=new X,b;t.adaptation!=null&&(b=w(t.adaptation).subscribe(E=>{for(let P of E)P[0]===q&&A(P[1])}));function A(L){if(i.emit(L),L.rpmCap!=null&&Number.isFinite(L.rpmCap)&&L.rpmCap>=0&&(a.emit(L.rpmCap),Number.isFinite(r)&&r>0&&T.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),L.tpmCap!=null&&Number.isFinite(L.tpmCap)&&L.tpmCap>=0&&(s.emit(L.tpmCap),Number.isFinite(r)&&r>0&&C.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),L.retryAfterMs!=null&&L.retryAfterMs>0){let E=W()+L.retryAfterMs*1e6;E>g&&(g=E)}}let O=v(0,{name:"adaptiveRateLimiter/pending"}),U=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),B=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),V=L=>{O.emit((O.cache??0)+L)},_=()=>{U.emit(d.available()),B.emit(u.available())};async function H(L={}){let E=L.requestCost??1,P=L.tokenCost??0,M=L.signal;V(1);try{for(;;){if(M?.aborted)throw Ue("AdaptiveRateLimiter.acquire aborted");let h=W();if(g>h){let ee=Math.ceil((g-h)/1e6);await Ae(ee,M);continue}if(E>0&&p||P>0&&c){await Ae(250,M);continue}let k=d,R=u;if(!k.tryConsume(E)){await Ae(Mt(k,E),M);continue}if(!(P>0?R.tryConsume(P):!0)){k.putBack(E),await Ae(Mt(R,P),M);continue}_();return}}finally{V(-1)}}function $(L){L>0?u.tryConsume(L):L<0&&u.putBack(-L),_()}function F(){f(),y(),b?.(),T.cancel(),C.cancel()}return{effectiveRpm:l,effectiveTpm:m,lastSignal:i,pending:O,rpmAvailable:U,tpmAvailable:B,acquire:H,recordUsage:$,recordSignal:A,dispose:F}}function ye(t,e){if(!Number.isFinite(t)||t===1/0)return je(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),o=t/60;return je(r,o)}function Mt(t,e){let r=t.available(),o=Math.max(0,e-r);return o<=0?25:Math.min(5e3,Math.max(50,o*100))}function Ae(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ue("AdaptiveRateLimiter.acquire aborted")):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Ue("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ve(t,e={}){let r=e.limiter??kt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),o=(s,i)=>e.costFn?e.costFn(s,i):0,n=s=>{let i=Ke(s);i&&r.recordSignal(i)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=t.invoke(s,i),d=await Zt(m),u=d.usage??gt(),c=ne(u)+le(u)-l;return c>0&&r.recordUsage(c),d}catch(m){throw n(m),m}},async*stream(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=0;for await(let u of t.stream(s,i))u.type==="usage"&&(m=ne(u.usage)+le(u.usage)),yield u;let d=m-l;d>0&&r.recordUsage(d)}catch(m){throw n(m),m}}},limiter:r}}async function Zt(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await at(w(t))}function Se(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function vt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Se()):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Se())},e.addEventListener("abort",a,{once:!0}))})}function He(t,e={}){let r=e.attempts??3,o=e.baseDelayMs??500,n=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,i=e.shouldRetry??er,l=e.retryStreaming??!0,m=(d,u)=>{if(a==="decorrelated"){let y=Math.min(n,Math.max(o,u*3));return o+Math.random()*(y-o)}let p=a==="exp"?o*2**(d-1):o*d,c=Math.min(n,p);if(!s)return c;let f=c*(.5+Math.random());return Math.min(n,f)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,u){if(u?.signal?.aborted)throw Se();let p,c=o;for(let f=1;f<=r;f++)try{return await Promise.resolve(t.invoke(d,u))}catch(y){if(p=y,f>=r||!i(y,f))throw y;let g=m(f,c);c=g,await vt(g,u?.signal)}throw p},async*stream(d,u){if(u?.signal?.aborted)throw Se();if(!l){for await(let f of t.stream(d,u))yield f;return}let p,c=o;for(let f=1;f<=r;f++){let y=!1;try{for await(let g of t.stream(d,u))y=!0,yield g;return}catch(g){if(p=g,y||f>=r||!i(g,f))throw g;let T=m(f,c);c=T,await vt(T,u?.signal)}}throw p}}}function er(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var he=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function qe(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=n=>{let a=new AbortController,s=!1,i;n&&(n.aborted?a.abort(n.reason):(i=()=>a.abort(n.reason),n.addEventListener("abort",i,{once:!0})));let l=new X;return l.start(e,()=>{s=!0,a.abort(new he(e))}),{signal:a.signal,cancel:()=>{l.cancel(),n&&i&&n.removeEventListener("abort",i)},timedOut:()=>s}},o=(n,a)=>{if(!a||n instanceof he)throw n;let s=n;if(s?.name==="AbortError"||s?.name==="DOMException"&&Number(s.code)===20||n?.message==="aborted"){let l=new he(e);throw l.cause=n,l}throw n};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{return await Promise.resolve(t.invoke(n,{...a,signal:s}))}catch(m){return o(m,l())}finally{i()}},async*stream(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{for await(let m of t.stream(n,{...a,signal:s}))yield m}catch(m){o(m,l())}finally{i()}}}}function tr(t,e={}){let r={adapter:t},o=t;if(e.rateLimit){let n=Ve(o,e.rateLimit);o=n.adapter,r.rateLimiter=n.limiter}if(e.budget){let n=We(o,e.budget);o=n.adapter,r.budget=n.budget}if(e.breaker){let n=Be(o,e.breaker);o=n.adapter,r.breaker=n.breaker}if(e.timeoutMs!=null&&(o=qe(o,e.timeoutMs)),e.retry&&(o=He(o,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let n={};e.onFallback&&(n.onFallback=e.onFallback),e.onExhausted&&(n.onExhausted=e.onExhausted),o=_e([{name:e.name??"primary",adapter:o},{name:"fallback",adapter:e.fallback}],n)}return r.adapter=o,r}function rr(){return Me()}function nr(t,e,r){let o=w(e);return J(o,a=>{if(!a||a.length===0)return v(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return it("ai",t,e)}function or(t){return t!=null&&typeof t.then=="function"}function ar(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function sr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ir=3e4;function xt(t,e){if(t.status==="settled"){let o=t.cache;if(o!==void 0)return Promise.resolve(o)}let r=e?.timeoutMs??ir;return new Promise((o,n)=>{let a=new X,s=t.subscribe(i=>{for(let l of i){if(l[0]===q){a.cancel(),s(),o(l[1]);return}if(l[0]===Y){a.cancel(),s(),n(l[1]);return}if(l[0]===re){a.cancel(),s(),n(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),n(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function ue(t){return or(t)?ue(await t):ar(t)?xt(t):sr(t)?xt(w(t)):t}function de(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function lr(t,e){let r=w(t),o=e?.refreshTrigger!=null?w(e.refreshTrigger):null;return o==null?se([r],(n,a,s)=>{if(s.store.emitted===!0)return;let l=n[0],m=l!=null&&l.length>0?l.at(-1):s.prevData[0];if(m!==void 0)return s.store.emitted=!0,a.emit(m),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")}):se([r,o],(n,a,s)=>{let i=n[1];if(!(i!=null&&i.length>0))return;let m=n[0],d=m!=null&&m.length>0?m.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")})}function ur(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function dr(t,e,r,o){let n=o?.format??"text",a=o?.retries??0,s=o?.cache??!1,i=s?new Map:null,l=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p},{name:o?.name?`${o.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(l,d=>{if(!d||d.length===0)return v(null);let u=s?JSON.stringify(d.map(c=>[c.role,c.content])):"";if(i?.has(u))return v(i.get(u));async function p(c){try{let f=await new Promise((T,C)=>{let b=t.invoke(d,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt});b&&typeof b.then=="function"?b.then(T,C):b&&typeof b.subscribe=="function"?T(b.cache):T(b)}),y=ur(f),g;return n==="json"?g=JSON.parse(de(y)):g=y,i?.set(u,g),g}catch(f){if(c>0)return p(c-1);throw f}}return p(a)})}function mr(t,e,r,o){let n=o?.name??"llm",a=o?.format??"text",s=De(`${n}/stream`),i=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p}),l=J(i,d=>{let u=d;if(!u||u.length===0)return v(null);let p=new AbortController;async function*c(){let f="",y=0;try{for await(let T of t.stream(u,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt,signal:p.signal})){if(T.type!=="token")continue;let C=T.delta;f+=C,s.publish({source:n,token:C,accumulated:f,index:y++})}let g;if(a==="json")try{g=JSON.parse(de(f))}catch{g=null}else g=f;yield g}finally{p.abort()}}return w(c())}),m=K(l);return{output:l,stream:s,dispose:()=>{m(),s.destroy()}}}function cr(t,e,r,o,n,a){let s=v(0,{name:`${e}/cancel`}),i=0,l=[...o,s],m=a?.name??e,d=a?.format??"text",u=De(`${m}/stream`),p=x(l,b=>{let A=b.slice(0,-1);if(A.some(B=>B==null))return[];let O=typeof n=="string"?n:n(...A);if(!O)return[];let U=[];return a?.systemPrompt&&U.push({role:"system",content:a.systemPrompt}),U.push({role:"user",content:O}),U}),c=J(p,b=>{let A=b;if(!A||A.length===0)return v(null);let O=new AbortController;async function*U(){let B="",V=0;try{for await(let H of r.stream(A,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:O.signal})){if(H.type!=="token")continue;let $=H.delta;B+=$,u.publish({source:m,token:$,accumulated:B,index:V++})}let _;if(d==="json")try{_=JSON.parse(de(B))}catch{_=null}else _=B;yield _}finally{O.abort()}}return w(U())}),f=K(c),y=x([c],([b])=>{if(b!=null)return b},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let g=dt(t,`${e}/gate`,`${e}/raw`,a?.gate),T=g.reject.bind(g),C={...g,reject(b=1){T(b),s.emit(++i)}};return{output:g.node,stream:u,gate:C,dispose:()=>{f(),u.destroy()}}}function pr(t,e){let r=e?.separator??`
|
|
2
|
-
|
|
3
|
-
`,o=t.map(s=>typeof s=="string"?v(s):w(s)),n=x(o,s=>s.filter(i=>i!=null&&i!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=K(n);return Object.assign(n,{dispose:a})}var fr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function gr(t,e){let r=e?.charsPerToken??4;return x([t.latest],([o])=>{if(o==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let n=o,a=n.accumulated.length;return{chunkCount:n.index+1,charCount:a,estimatedTokens:Math.ceil(a/r)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:N("cost_meter_extractor"),equals:fr})}var yr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.label!==n.label||o.pattern!==n.pattern||o.match!==n.match||o.position!==n.position)return!1}return!0};function hr(t,e){let r=e.maxPatternLength??128;return x([t.latest],([o],n)=>{if(o==null)return[];let a=o.accumulated;"flags"in n.store||(n.store.flags=[],n.store.scannedTo=0);let s=n.store.flags,i=n.store.scannedTo,l=Math.max(0,i-r),m=a.slice(l),d=!1;for(let{pattern:u,label:p}of e.patterns){let c=new RegExp(u.source,`${u.flags.replace("g","")}g`);for(let f of m.matchAll(c)){let y=l+f.index;y+f[0].length<=i||(s.push({label:p,pattern:u,match:f[0],position:y}),d=!0)}}return n.store.scannedTo=a.length,d?[...s]:s.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:yr})}function br(t,e,r){return x([t.latest],([o])=>o==null?null:e(o.accumulated),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Tr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.startIndex!==n.startIndex||o.name!==n.name||o.raw!==n.raw)return!1}return!0};function Mr(t,e){return x([t.latest],([r],o)=>{if(r==null)return[];let n=r.accumulated;"calls"in o.store||(o.store.calls=[],o.store.scanFrom=0);let a=o.store.calls,s=o.store.scanFrom,i=!1;for(;s<n.length;){let l=n.indexOf("{",s);if(l===-1){o.store.scanFrom=n.length;break}let m=0,d=-1,u=!1;for(let c=l;c<n.length;c++){let f=n[c];if(u)f==="\\"&&c+1<n.length?c++:f==='"'&&(u=!1);else if(f==='"')u=!0;else if(f==="{")m++;else if(f==="}"&&(m--,m===0)){d=c;break}}if(d===-1){o.store.scanFrom=l;break}let p=n.slice(l,d+1);try{let c=JSON.parse(p);typeof c.name=="string"&&c.arguments!=null&&typeof c.arguments=="object"&&(a.push({name:c.name,arguments:c.arguments,raw:p,startIndex:l}),i=!0)}catch{}s=d+1,o.store.scanFrom=s}return i?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Tr})}function kr(t,e,r,o){let n=r*(o?.hardMultiplier??1.5),a=typeof e!="function",s=[t.latest];return a&&s.push(e),x(s,i=>{let l=i[0];if(l==null)return"allow";let m=a?i[1]??0:e(l.accumulated);return m>=n?"block":m>=r?"review":"allow"},{name:o?.name??"content-gate",initial:"allow"})}function vr(t,e,r,o){let n=r??(()=>"[REDACTED]");function a(s){let i=s;for(let l of e){let m=l.global?l:new RegExp(l.source,`${l.flags}g`);i=i.replace(m,d=>n(d,l))}return i}return x([t.latest],([s])=>{if(s==null)return{source:"",token:"",accumulated:"",index:-1};let i=s,l=a(i.accumulated),m=a(i.token);return{source:i.source,token:m,accumulated:l,index:i.index}},{name:o?.name??"redactor"})}var Ee=class extends Z{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=ge([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=x([this.messages],([o])=>{let n=o;return n.length===0?null:n[n.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(K(this.latest)),this.messageCount=x([this.messages],([o])=>o.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(K(this.messageCount))}append(e,r,o){this._log.append({role:e,content:r,...o})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ze(t,e){return new Ee(t,e)}var Ie=class extends Z{definitions;schemas;constructor(e,r={}){super(e,r.graph),this.definitions=v(new Map,{name:"definitions",describeKind:"state",meta:N("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=x([this.definitions],([o])=>[...(o??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(K(this.schemas))}register(e){let r=this.definitions.cache,o=new Map(r);o.set(e.name,e),this.definitions.emit(o)}unregister(e){let r=this.definitions.cache;if(!r.has(e))return;let o=new Map(r);o.delete(e),this.definitions.emit(o)}async execute(e,r){let n=this.definitions.cache.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let a=n.handler(r);return ue(a)}getDefinition(e){return this.definitions.cache?.get(e)}};function Je(t,e){return new Ie(t,e)}var Oe=class extends Z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=ze(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=Je(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let M of r.tools)this.tools.register(M);this.status=v("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=v(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=v(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let o=0,n=this.turn.subscribe(M=>{for(let h of M)h[0]===q&&(o=h[1])}),a=!1,s=this.aborted.subscribe(M=>{for(let h of M)h[0]===q&&(a=h[1])}),i=r.adapter,l=r.systemPrompt,m=r.model,d=r.temperature,u=r.maxTokens,p=r.maxTurns??10,c=r.stopWhen,f=this.chat,y=this.tools,g=this.status,T=this.turn,C=this.aborted,b=se([g],(M,h,k)=>{if(ke(M,k.prevData,0,"idle")!=="thinking"||a||o>=p){h.down([[fe]]);return}let I=f.allMessages();if(I.length===0){h.down([[fe]]);return}let S=y.schemas.cache??[];h.emit({messages:I,tools:S})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(b,M=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),w(Promise.resolve(i.invoke(M.messages,{tools:M.tools.length>0?M.tools:void 0,systemPrompt:l,model:m,temperature:d,maxTokens:u,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),O=v(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=O;let U=se([O,g],(M,h,k)=>{let R=ke(M,k.prevData,0,null);if(ke(M,k.prevData,1,"idle")!=="acting"){h.down([[fe]]);return}let S=R?.toolCalls;if(S==null||S.length===0){h.down([[fe]]);return}h.emit(S)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),B=r.interceptToolCalls?r.interceptToolCalls(U):U;this.toolCalls=B;let V=(M,h)=>{if(M===h)return!0;if(M.length!==h.length)return!1;for(let k=0;k<M.length;k++){let R=M[k],I=h[k];if(R?.id!==I?.id||R?.content!==I?.content)return!1}return!0},_=J(B,M=>{if(M==null||M.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 h=M.map(k=>xr(k,y));return x(h,k=>k.map((R,I)=>{let S=R;return S!=null&&typeof S=="object"&&"id"in S&&"content"in S?S:{id:M[I].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:V})});this.toolResults=_;let H=ie([A],([M])=>{if(a)return;let h=M,k=o+1,R=h.toolCalls!=null&&h.toolCalls.length>0,I=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),S=c?.(h)===!0,ee=k>=p,te=S||I||!R||ee?"done":"acting";ae(()=>{O.emit(h),g.emit(te),T.emit(k),f.append("assistant",h.content,{toolCalls:h.toolCalls})})}),$=ie([_],([M])=>{if(a)return;let h=M;if(h.length===0)return;let k=o>=p?"done":"thinking";ae(()=>{g.emit(k);for(let R of h)f.appendToolResult(R.id,R.content)})}),F=ie([C],([M])=>{M===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),L=K(H),E=K($),P=K(F);this._terminalResult=se([g,O],(M,h,k)=>{let R=ke(M,k.prevData,0,"idle"),I=ke(M,k.prevData,1,null);if(R==="done"){if(I!=null){h.emit({response:I,runVersion:this._runVersion});return}let S=new Error("agentLoop: aborted");S.name="AbortError",h.down([[Y,S]]);return}if(R==="error"){h.down([[Y,new Error("agentLoop: errored")]]);return}h.down([[fe]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(n),this.addDisposer(s),this.addDisposer(L),this.addDisposer(E),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,r){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 o=++this._runVersion;ae(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let n;if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}try{return(await st(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===o})).response}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function xr(t,e){let r=rt(()=>w(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),o=x([r],([n])=>({id:t.id,content:typeof n=="string"?n:JSON.stringify(n)}));return lt(o,n=>({id:t.id,content:JSON.stringify({error:String(n)})}))}function ke(t,e,r,o){let n=t[r];if(n!=null&&n.length>0)return n[n.length-1];let a=e[r];return a!==void 0?a:o}function Rr(t,e){return new Oe(t,e)}function Lr(t,e,r){let o=w(t),n=r?.condition!=null?w(r.condition):null,a=v(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(n==null)return J(o,i=>{if(i==null)return a;let l=v(i);return e(l)});let s=x([o,n],([i,l])=>({v:i,open:l===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:i,open:l})=>{if(i==null)return a;if(!l)return v(i);let m=v(i);return e(m)})}function wr(t,e,r){let o=w(t),n=e.map(s=>w(s)),a=[o,...n];return x(a,s=>{let i=s[0]??[],l=s.slice(1);return i.filter(m=>{for(let d of l)if(d!=null&&!d(m))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),equals:(s,i)=>{let l=s,m=i;if(l.length!==m.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==m[d])return!1;return!0}})}function Nr(t){return{persistence:.5,structure:.5,personalValue:.5}}function Cr(t={}){let e=t.scoreFn??Nr,r=t.persistenceThreshold??.3,o=t.personalValueThreshold??.3,n=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<o||n&&s.structure<=0)}}function Ye(t,e){return(r,o)=>{let n=[...o.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:n})}];return Pe(s=>{let i=!0,l=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=w(l).subscribe(u=>{if(!i)return;let p=!1;for(let c of u){if(p)break;if(c[0]===q){let f=c[1];try{let y=JSON.parse(f.content);s.emit(y),s.down([[re]])}catch{s.down([[Y,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else c[0]===Y?(s.down([[Y,c[1]]]),p=!0):c[0]===re?(s.down([[re]]),p=!0):s.down([[c[0],c[1]]])}});return()=>{d(),i=!1}})}}function Qe(t,e){return r=>{let o=[...r.entries()].map(([a,s])=>({key:a,value:s})),n=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:o})}];return Pe(a=>{let s=!0,i=e.adapter.invoke(n,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),m=w(i).subscribe(d=>{if(!s)return;let u=!1;for(let p of d){if(u)break;if(p[0]===q){let c=p[1];try{let f=JSON.parse(c.content);a.emit(f),a.down([[re]])}catch{a.down([[Y,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}u=!0}else p[0]===Y?(a.down([[Y,p[1]]]),u=!0):p[0]===re?(a.down([[re]]),u=!0):a.down([[p[0],p[1]]])}});return()=>{m(),s=!1}})}}var Xe=Math.LN2/604800;function ve(t){return t instanceof Map?t:new Map}function Ar(t,e,r){let o=new Z(t,r.graph),n=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=Ye(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,A)=>b==null?{upsert:[]}:a(b,A),i=e;if(r.admissionFilter){let b=w(e),A=r.admissionFilter;i=x([b],([O])=>{if(A(O))return O},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=Qe(r.consolidatePrompt,{adapter:r.adapter}));let m=r.consolidateTrigger;if(!m&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;m=ot(b,{period:b})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:m},u=ut(i,s,d);o.add(u.store.entries,{name:"store"}),o.add(u.compact,{name:"compact"}),o.add(u.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=pt({dimension:r.vectorDimensions}),o.add(p.entries,{name:"vectorIndex"}));let c=null;r.enableKnowledgeGraph&&(c=ft(`${t}-kg`),o.mount("kg",c));let f=null;if(r.tiers){let b=r.tiers,A=b.decayRate??Xe,O=b.maxActive??1e3,U=b.archiveThreshold??.1,B=b.permanentFilter??(()=>!1),V=ct({name:"permanent"});o.add(V.entries,{name:"permanent"});let _=new Set,H=h=>_.has(h)?"permanent":ve(u.store.entries.cache).has(h)?"active":"archived",$=(h,k)=>{_.add(h),V.upsert(h,k)},F=new Map,L=u.store.entries,E=r.context?w(r.context):v(null),P=ie([L,E],([h,k])=>{let R=ve(h),I=W(),S=[],ee=[];for(let[D,Q]of R){if(F.has(D)||F.set(D,I),B(D,Q)){ee.push({key:D,value:Q});continue}let z=r.score(Q,k),j=F.get(D)??I,G=Number(I-j)/1e9;mt(z,G,A)<U&&S.push(D)}for(let D of F.keys())R.has(D)||F.delete(D);for(let{key:D,value:Q}of ee)_.has(D)||$(D,Q);let te=R.size-_.size;if(te>O){let D=[...R.entries()].filter(([z])=>!_.has(z)).map(([z,j])=>({key:z,score:r.score(j,k)})).sort((z,j)=>z.score-j.score),Q=te-O;for(let z=0;z<Q&&z<D.length;z++){let j=D[z].key;S.includes(j)||S.push(j)}}S.length>0&&ae(()=>{for(let D of S)u.store.delete(D)})});n.push(P.subscribe(()=>{}));let M=null;b.archiveTier&&(M=o.attachStorage([b.archiveTier],b.archiveStorageOptions??{})),f={permanent:V,activeEntries:L,archiveHandle:M,tierOf:H,markPermanent:$}}if(p||c){let b=r.embedFn,A=r.entityFn,O=u.store.entries,U=ie([O],([B])=>{let V=ve(B);for(let[_,H]of V){if(p&&b){let $=b(H);$&&p.upsert(_,$,H)}if(c&&A){let $=A(_,H);if($){for(let F of $.entities??[])c.upsertEntity(F.id,F.value);for(let F of $.relations??[])c.link(F.from,F.to,F.relation,F.weight)}}}});n.push(U.subscribe(()=>{}))}let y=null,g=null,T=null,C=null;if(p||c){let b=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,O=r.budget??2e3,U=r.cost,B=r.score,V=r.contextOf,_=r.contextWeight??0,H=r.context?w(r.context):v(null),$=(M,h)=>{if(!M||!h)return 0;let k=Math.min(M.length,h.length),R=0;for(;R<k&&M[R]===h[R];)R++;return R},F=(M,h,k)=>{let R=new Map,I=[];if(p&&k.vector){I=p.search(k.vector,b);for(let j of I){let G=M.get(j.id);G&&R.set(j.id,{value:G,sources:new Set(["vector"])})}}let S=[];if(c){let j=[...k.entityIds??[],...R.keys()],G=new Set,me=j;for(let ce=0;ce<A;ce++){let oe=[];for(let be of me){if(G.has(be))continue;G.add(be);let xe=c.related(be);for(let wt of xe){let pe=wt.to;if(!G.has(pe)){oe.push(pe);let et=M.get(pe);if(et){let tt=R.get(pe);tt?tt.sources.add("graph"):R.set(pe,{value:et,sources:new Set(["graph"])}),S.push(pe)}}}}me=oe}}for(let[j,G]of M)R.has(j)||R.set(j,{value:G,sources:new Set(["store"])});let ee=k.context?.length??0,te=[];for(let[j,{value:G,sources:me}]of R){let ce=V?V(G):void 0,oe=B(G,h);if(_>0&&ee>0){let xe=$(k.context,ce);xe>0&&(oe=oe*(1+_*xe/ee))}let be=ce?{key:j,value:G,score:oe,sources:[...me],context:ce}:{key:j,value:G,score:oe,sources:[...me]};te.push(be)}te.sort((j,G)=>G.score-j.score);let D=[],Q=0;for(let j of te){let G=U(j.value);if(Q+G>O&&D.length>0)break;D.push(j),Q+=G}return{packed:D,trace:{vectorCandidates:I,graphExpanded:S,ranked:te,packed:D}}},L=v([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});o.add(L,{name:"retrieval"}),y=L;let E=v(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});o.add(E,{name:"retrievalTrace"}),g=E,T=M=>{let h=ve(u.store.entries.cache),{packed:k,trace:R}=F(h,H.cache,M);return ae(()=>{L.emit(k),E.emit(R)}),k},C=M=>{let h=w(M);return x([u.store.entries,H,h],([k,R,I])=>{if(I==null)return[];let S=ve(k);return F(S,R,I).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return o.addDisposer(()=>{for(let b of n)b();n.length=0}),Object.assign(o,{distillBundle:u,compact:u.compact,size:u.size,vectors:p,kg:c,memoryTiers:f,retrieval:y,retrievalTrace:g,retrieve:T,retrieveReactive:C})}function Sr(t,e,r){let o=t.describe({actor:e,detail:"full"}),n=r?.groupByTags??!0,a=r?.separator??`
|
|
4
|
-
`,s=[],i=r?.sinceVersion;for(let[l,m]of Object.entries(o.nodes)){let d=m.meta??{},u=d.description,p=d.format;if(!u&&!p)continue;if(i!=null&&m.v!=null){let T=i.get(l);if(T!=null&&T.id===m.v.id&&m.v.version<=T.version)continue}let c=u??l,f=m.value,y=d.unit,g;p==="currency"&&typeof f=="number"?g=`$${f.toFixed(2)}`:p==="percentage"&&typeof f=="number"?g=`${(f*100).toFixed(1)}%`:f==null?g="(no value)":g=String(f),y&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${y}`),s.push({path:l,description:c,formatted:g})}if(s.length===0)return"";if(n){let l=new Map,m=[];for(let u of s){let c=o.nodes[u.path].meta?.tags;if(c&&c.length>0){let f=c[0],y=l.get(f);y||(y=[],l.set(f,y)),y.push(u)}else m.push(u)}if(l.size===0)return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a);let d=[];for(let[u,p]of[...l.entries()].sort((c,f)=>c[0].localeCompare(f[0])))d.push(`[${u}]${a}${p.map(c=>`- ${c.description}: ${c.formatted}`).join(a)}`);return m.length>0&&d.push(m.map(u=>`- ${u.description}: ${u.formatted}`).join(a)),d.join(a+a)}return s.map(l=>`- ${l.description}: ${l.formatted}`).join(a)}var Rt=new Set(["state","derived","producer","operator","effect"]);function Ze(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let o=new Set(Object.keys(r.nodes));for(let[n,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${n}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Rt.has(s.type))&&e.push(`Node "${n}": invalid type "${String(s.type)}" (expected: ${[...Rt].join(", ")})`),Array.isArray(s.deps))for(let i of s.deps)typeof i=="string"&&!o.has(i)&&e.push(`Node "${n}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let n=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let i=s;(typeof i.from!="string"||!o.has(i.from))&&e.push(`Edge [${a}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!o.has(i.to))&&e.push(`Edge [${a}]: 'to' "${String(i.to)}" does not reference an existing node`);let l=`${i.from}->${i.to}`;n.has(l)&&e.push(`Edge [${a}]: duplicate edge ${l}`),n.add(l)}}return{valid:e.length===0,errors:e}}var Lt=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
5
|
-
|
|
6
|
-
Given a natural-language description, produce a JSON graph definition with this structure:
|
|
7
|
-
|
|
8
|
-
{
|
|
9
|
-
"name": "<graph_name>",
|
|
10
|
-
"nodes": {
|
|
11
|
-
"<node_name>": {
|
|
12
|
-
"type": "state" | "derived" | "producer" | "operator" | "effect",
|
|
13
|
-
"value": <initial_value_or_null>,
|
|
14
|
-
"deps": ["<dep_node_name>", ...],
|
|
15
|
-
"meta": {
|
|
16
|
-
"description": "<human-readable purpose>",
|
|
17
|
-
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
18
|
-
"range": [min, max],
|
|
19
|
-
"values": ["a", "b"],
|
|
20
|
-
"format": "currency" | "percentage" | "status",
|
|
21
|
-
"access": "human" | "llm" | "both" | "system",
|
|
22
|
-
"unit": "<unit>",
|
|
23
|
-
"tags": ["<tag>"]
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
"edges": [
|
|
28
|
-
{ "from": "<source_node>", "to": "<target_node>" }
|
|
29
|
-
]
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
Rules:
|
|
33
|
-
- "state" nodes have no deps and hold user/LLM-writable values (knobs).
|
|
34
|
-
- "derived" nodes have deps and compute from them.
|
|
35
|
-
- "effect" nodes have deps but produce side effects (no return value).
|
|
36
|
-
- "producer" nodes have no deps but generate values asynchronously.
|
|
37
|
-
- Edges wire output of one node as input to another. They must match deps.
|
|
38
|
-
- meta.description is required for every node.
|
|
39
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Er(t,e,r){let n=[{role:"system",content:r?.systemPromptExtra?`${Lt}
|
|
40
|
-
|
|
41
|
-
${r.systemPromptExtra}`:Lt},{role:"user",content:t}],a=e.invoke(n,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),i=(await ue(a)).content.trim();i.startsWith("```")&&(i=de(i));let l;try{l=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}let m=Ze(l);if(!m.valid)throw new Error(`graphFromSpec: invalid graph definition:
|
|
42
|
-
${m.errors.join(`
|
|
43
|
-
`)}`);let d=l;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),Z.fromSnapshot(d,r?.build)}function Ir(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="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 Or(t,e){let r=t.describe({actor:e,detail:"full"}),o=[],n=[],a=[];for(let[s,i]of Object.entries(r.nodes)){if(i.type!=="state"||s.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let l=i.meta??{},m=l.access;if(m==="human"||m==="system")continue;let d=l.description??`Set the value of ${s}`,u=Ir(l),p={type:"object",required:["value"],properties:{value:u},additionalProperties:!1},c=s.replace(/::/g,"__");o.push({type:"function",function:{name:c,description:d,parameters:p}}),n.push({name:s,description:d,inputSchema:p});let f=t,y=e,g=i.v;a.push({name:s,description:d,parameters:p,handler(T){return f.set(s,T.value,y?{actor:y}:void 0),T.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:o,mcp:n,definitions:a}}var Pr=`You are a reactive graph optimizer for GraphReFly.
|
|
44
|
-
|
|
45
|
-
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
46
|
-
|
|
47
|
-
Return ONLY valid JSON with this structure:
|
|
48
|
-
{
|
|
49
|
-
"summary": "<one-line summary of the strategy>",
|
|
50
|
-
"reasoning": "<explanation of why these changes help>",
|
|
51
|
-
"operations": [
|
|
52
|
-
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
53
|
-
{ "type": "remove_node", "name": "<name>" },
|
|
54
|
-
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
55
|
-
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
56
|
-
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
57
|
-
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
58
|
-
]
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
Rules:
|
|
62
|
-
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
63
|
-
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
64
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function jr(t,e,r,o){let{expand:n,...a}=t.describe({actor:o?.actor,detail:"standard"}),s=[{role:"system",content:Pr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],i=r.invoke(s,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens}),m=(await ue(i)).content.trim();m.startsWith("```")&&(m=m.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(m)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${m.slice(0,200)}`)}let u=d;if(typeof u.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof u.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(u.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:u.summary,reasoning:u.reasoning,operations:u.operations}}export{Ft as a,Gt as b,Ge as c,yt as d,$t as e,Wt as f,Kt as g,Be as h,Ne as i,We as j,Vt as k,Ke as l,Ve as m,He as n,he as o,qe as p,tr as q,rr as r,nr as s,lr as t,dr as u,mr as v,cr as w,pr as x,gr as y,hr as z,br as A,Mr as B,kr as C,vr as D,Ee as E,ze as F,Ie as G,Je as H,Oe as I,Rr as J,Lr as K,wr as L,Cr as M,Ye as N,Qe as O,Xe as P,Ar as Q,Sr as R,Ze as S,Er as T,Or as U,jr as V,_r as W};
|
package/dist/chunk-MGKAO4EK.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{a as Le}from"./chunk-ESMPEKEV.js";import{a as se,b as Se}from"./chunk-TWMEGG45.js";import{A as Ee}from"./chunk-KASHOCF5.js";import{A as Oe,C as L,E as re,F as Me,G as _e,e as $e,f as Te,i as Y,k as Ne,l as we,m as Ae,o as K,p as Pe,s as W}from"./chunk-W4TSQ6RJ.js";import{b as Z,c as be,d as ye,e as ee,f as ve,g as xe,h as V,i as te,j as ne}from"./chunk-CK2E7BTU.js";function Ie(e,t,n,r={}){let o=t in e.nodes,s=n in e.nodes;if(!o)return oe(t,n,"no-such-from");if(!s)return oe(t,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(t===n){if(r.findCycle===!0){let u=lt(e,t,r);if(u!=null)return u}let l=ie(t,e.nodes[t],0,r);return ae(t,n,[l])}if(i===0)return oe(t,n,"no-path");let a=je(e,t,n,i);return a.found?ae(t,n,Be(e,a.pathOrder,r)):oe(t,n,a.truncated?"max-depth-exceeded":"no-path")}function je(e,t,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,l=!1;for(;a<s.length;){let h=s[a++];if(h.path===t)break;if(r!=null&&h.depth>=r){let g=e.nodes[h.path];g?.deps&&g.deps.length>0&&(l=!0);continue}let p=e.nodes[h.path];if(p==null)continue;let f=p.deps??[],c=new Map;for(let g=0;g<f.length;g++){let b=f[g];if(!b)continue;let v=c.get(b);v==null&&(v=[],c.set(b,v)),v.push(g)}for(let[g,b]of c)i.has(g)||(i.add(g),o.set(g,{from:h.path,depIndices:b}),s.push({path:g,depth:h.depth+1}))}if(!o.has(t))return{found:!1,pathOrder:[],truncated:l};let u=[{path:t}],d=t;for(;d!==n;){let h=o.get(d);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),d=h.from}return{found:!0,pathOrder:u,truncated:!1}}function lt(e,t,n){let r=e.nodes[t];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===t&&s.push(a);if(s.length>0){let a=ie(t,r,0,n);a.dep_index=s[0];let l=ie(t,r,1,n);return ae(t,t,[a,l])}let i=null;for(let a=0;a<o.length;a++){let l=o[a];if(!l||l===t)continue;let u=je(e,l,t,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:t,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:ae(t,t,Be(e,i.pathOrder,n))}function Be(e,t,n){return t.map((r,o)=>{let s=e.nodes[r.path],i=ie(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 ie(e,t,n,r){let o={path:e,type:t.type,hop:n};t.status!==void 0&&(o.status=t.status),"value"in t&&(o.value=t.value),t.v!=null&&(o.v=t.v);let s=r.annotations?.get(e)??t.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(e)??t.lastMutation;return i!=null&&(o.lastMutation=i),o}function ae(e,t,n){return Fe(e,t,!0,"ok",n)}function oe(e,t,n){return Fe(e,t,!1,n,[])}function Fe(e,t,n,r,o){let s=ct(e,t,n,r,o);return{from:e,to:t,found:n,reason:r,steps:o,text:s,toJSON(){return{from:e,to:t,found:n,reason:r,steps:o}}}}function ct(e,t,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${e}"`;case"no-such-to":return`explainPath: no node named "${t}"`;case"max-depth-exceeded":return`explainPath: no path from "${e}" to "${t}" within maxDepth`;default:return`explainPath: no path from "${e}" to "${t}"`}let s=[`Causal path: ${e} \u2192 ${t} (${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: ${dt(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
|
|
2
|
-
`)}function dt(e){if(e===void 0)return"<sentinel>";if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return t.length>80?`${t.slice(0,77)}...`:t}catch{return String(e)}}var A={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},ft=Symbol.for("sizeof");function ze(e){let t=new WeakSet,n=new WeakSet,r=[e],o=0;for(;r.length>0;){let s=r.pop();o+=pt(s,t,n,r)}return o}function pt(e,t,n,r){if(e==null)return 0;switch(typeof e){case"number":return A.number;case"boolean":return A.boolean;case"string":return A.string+e.length*2;case"bigint":return A.bigint+ht(e);case"symbol":return A.symbol;case"function":return t.has(e)?0:(t.add(e),A.function);case"undefined":return 0}let s=e;if(t.has(s))return 0;t.add(s);let i=s[ft];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 A.date;if(s instanceof RegExp)return A.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 A.error+u+d}if(typeof URL<"u"&&s instanceof URL)return A.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return A.promise;if(s instanceof WeakMap)return A.weakmap;if(s instanceof WeakSet)return A.weakset;if(s instanceof Map){let u=A.map;for(let[d,h]of s)u+=A.mapEntry,r.push(d),r.push(h);return u}if(s instanceof Set){let u=A.set;for(let d of s)u+=A.setEntry,r.push(d);return u}if(Array.isArray(s)){let u=A.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=A.object,l=Object.keys(s);for(let u of l){a+=A.string+u.length*2;try{r.push(s[u])}catch{}}return a}function ht(e){let t=e<0n?-e:e;if(t===0n)return 0;let n=t.toString(2).length;return Math.ceil(n/32)*8}function He(e,t){let n=t?.topN??10,r=e.describe({detail:"standard"}),o=[],s=e._collectObserveTargets;typeof s=="function"&&s.call(e,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let c=i.get(p),g=c instanceof L?c:null,b=g?ze(g.cache):0,v=g?g._sinkCount:0,w=f.deps?.length??0,m=f.type==="effect"&&v===0,y=v===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:b,subscriberCount:v,depCount:w,isOrphanEffect:m,orphanKind:y})}let l=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((c,g)=>g[p]-c[p])).slice(0,n),d=a.filter(p=>p.orphanKind!=null),h=a.filter(p=>p.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:h}}var X=class{constructor(t){this.capacity=t;if(!Number.isInteger(t)||t<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${t})`);this.buf=new Array(t)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(t){let n=(this.head+this._size)%this.capacity;this.buf[n]=t,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let t=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,t}at(t){if(this._size===0)return;let n=t<0?this._size+t:t;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let t=new Array(this._size);for(let n=0;n<this._size;n++)t[n]=this.buf[(this.head+n)%this.capacity];return t}clear(){for(let t=0;t<this._size;t++)this.buf[(this.head+t)%this.capacity]=void 0;this.head=0,this._size=0}};function Re(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e>=1552&&e<=1562||e>=1611&&e<=1631||e>=1648&&e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2304&&e<=2307||e>=2362&&e<=2383||e>=2385&&e<=2391||e>=2402&&e<=2403||e>=2433&&e<=2435||e>=2492&&e<=2509||e>=2561&&e<=2563||e>=2620&&e<=2641||e>=2672&&e<=2673||e>=2677&&e===2677||e>=3633&&e===3633||e>=3636&&e<=3642||e>=3655&&e<=3662||e>=3761&&e===3761||e>=3764&&e<=3772||e>=3784&&e<=3790||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65024&&e<=65039||e>=65056&&e<=65071||e===8205?0:e>=4352&&e<=4447||e>=8986&&e<=8987||e>=9001&&e<=9002||e>=9193&&e<=9203||e>=9208&&e<=9210||e>=9725&&e<=9726||e>=9748&&e<=9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e>=9898&&e<=9899||e>=9917&&e<=9918||e>=9924&&e<=9925||e===9934||e===9940||e===9962||e>=9970&&e<=9971||e===9973||e===9978||e===9981||e===9986||e===9989||e>=9992&&e<=9997||e===9999||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e>=10548&&e<=10549||e>=11013&&e<=11015||e>=11035&&e<=11036||e===11088||e===11093||e>=11904&&e<=12350||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=40959||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=126980&&e===126980||e===127183||e>=127344&&e<=127345||e===127358||e===127359||e===127374||e>=127377&&e<=127386||e>=127456&&e<=127487||e>=127488&&e<=127490||e===127514||e===127535||e>=127538&&e<=127546||e>=127568&&e<=127569||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=129792&&e<=130047||e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}function ue(e){let t=0;for(let n of e)t+=Re(n.codePointAt(0));return t}function Ve(e,t){if(t<=0)return"";let n=0,r="";for(let o of e){let s=Re(o.codePointAt(0));if(n+s>t){if(t<=1)return"\u2026";for(;n+1>t&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=Re(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var gt={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"},mt={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Ue(e,t){let n=t.charset==="ascii"?mt:gt,r=e.width,o=e.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of e.edges)yt(s,i,n,a);for(let a of e.boxes)bt(s,i,n,a,t.labelOf(a.id));return s.map(a=>Ot(a.join(""))).join(`
|
|
3
|
-
`)}function bt(e,t,n,r,o){let{x:s,y:i,w:a,h:l}=r;if(a<2||l<2){l>0&&Ke(e,t,s,i,a,o);return}H(e,t,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)H(e,t,d,i,n.boxH);H(e,t,s+a-1,i,n.boxTR);for(let d=i+1;d<i+l-1;d+=1){H(e,t,s,d,n.boxV);for(let h=s+1;h<s+a-1;h+=1)Je(e,t,h,d," ","empty");H(e,t,s+a-1,d,n.boxV)}H(e,t,s,i+l-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)H(e,t,d,i+l-1,n.boxH);H(e,t,s+a-1,i+l-1,n.boxBR);let u=i+Math.floor(l/2);Ke(e,t,s+1,u,a-2,o)}function H(e,t,n,r,o){Je(e,t,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Je(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];n<0||n>=i.length||(i[n]=o,t[r][n]=s)}function Ke(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=n,a=o;for(let l of s){let u=ue(l);if(u!==0){if(a<u)break;i>=0&&i<e[r].length&&(e[r][i]=l,t[r][i]="label",u===2&&i+1<e[r].length&&(e[r][i+1]="",t[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<e[r].length&&(e[r][i]=" ",t[r][i]="empty"),i+=1,a-=1}function yt(e,t,n,r){let o=r.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)vt(e,t,n,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let u=o[l-1],d=o[l],h=o[l+1],p=xt(u,d,h,n);p&&qe(e,t,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=wt(i,s,n);a&&qe(e,t,s.x,s.y,a,"arrow")}function vt(e,t,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)We(e,t,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)We(e,t,s,l,n,"v")}}}function We(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];if(n<0||n>=i.length)return;let a=t[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,t[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,t[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,t[r][n]="edgeCorner";return}}}function qe(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];if(n<0||n>=i.length)return;let a=t[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,t[r][n]=s)}function xt(e,t,n,r){let o=e.y===t.y,s=t.y===n.y;if(o===s)return;if(o){let l=e.x<t.x,u=n.y>t.y;return l&&u?r.cornerTR:l&&!u?r.cornerBR:!l&&u?r.cornerTL:r.cornerBL}let i=e.y<t.y,a=n.x>t.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function wt(e,t,n){if(t.x>e.x)return n.arrowRight;if(t.x<e.x)return n.arrowLeft;if(t.y>e.y)return n.arrowDown;if(t.y<e.y)return n.arrowUp}function Ot(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===32;)t-=1;return e.slice(0,t)}function Qe(e){let t=_t(e);Et(t),St(t),Rt(t),Dt(t,e);let n=kt(t,e),{width:r,height:o}=Tt(t),s=[];for(let i of t.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 _t(e){let t=new Map;for(let o of e.nodes)t.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:e.widthCells(o),h:e.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of e.edges){if(o.from===o.to)continue;let s=t.get(o.from),i=t.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:t,layers:[],hops:n}}function Et(e){let t=new Map;for(let s of e.nodes.values())t.set(s.id,s.in.length);let n=[];for(let s of e.nodes.values())(t.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=e.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(t.get(a.id)??0)-1;t.set(a.id,l),l<=0&&n.push(a)}}}for(let s of e.nodes.values())s.layer<0&&(s.layer=0)}function St(e){let t=Math.max(0,...Array.from(e.nodes.values(),s=>s.layer)),n=Array.from({length:t+1},()=>[]);for(let s of e.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of e.hops){let i=e.nodes.get(s.fromId),a=e.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);let u=i;for(let h=1;h<l;h+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};e.nodes.set(p,f),n[f.layer].push(f);let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:h-1,chainLen:l};u.out.push(c),f.in.push(c),r.push(c),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;e.layers=n,e.hops=r}function Rt(e){for(let n=0;n<4;n+=1){for(let r=1;r<e.layers.length;r+=1)Ye(e,e.layers[r],"in"),le(e.layers[r]);for(let r=e.layers.length-2;r>=0;r-=1)Ye(e,e.layers[r],"out"),le(e.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<e.layers.length;o+=1){let s=e.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Xe(e,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],le(s),Xe(e,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],le(s))}}if(!r)break}}function Ye(e,t,n){let r=new Map;for(let o of t){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=e.nodes.get(n==="in"?l.fromId:l.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}t.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function le(e){for(let t=0;t<e.length;t+=1)e[t].order=t}function Xe(e,t,n,r){let o=r==="in"?t.in:t.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let l of s){let u=e.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=e.nodes.get(r==="in"?l.fromId:l.toId)?.order??0;(t.order<n.order&&u>d||t.order>n.order&&u<d)&&(i+=1)}return i}function Dt(e,t){t.direction==="LR"?Gt(e,t):Ct(e,t)}function Gt(e,t){let n=[],r=0;for(let o=0;o<e.layers.length;o+=1){n.push(r);let s=0;for(let i of e.layers[o])s=Math.max(s,i.w);r+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.x=n[o];for(let o of e.layers){let s=0;for(let i of o)i.y=s,s+=i.h+t.nodeGap}Ze(e,t,"y")}function Ct(e,t){let n=[],r=0;for(let o=0;o<e.layers.length;o+=1){n.push(r);let s=0;for(let i of e.layers[o])s=Math.max(s,i.h);r+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.y=n[o];for(let o of e.layers){let s=0;for(let i of o)i.x=s,s+=i.w+t.nodeGap}Ze(e,t,"x")}function Ze(e,t,n){let r=s=>n==="y"?s.h:s.w,o=t.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?e.layers.slice(1):e.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let h=s===0?d.in:d.out;if(h.length===0)continue;let p=[];for(let c of h){let g=e.nodes.get(s===0?c.fromId:c.toId);if(!g)continue;let b=n==="y"?g.y:g.x;p.push(b+Math.floor(r(g)/2))}if(p.length===0)continue;p.sort((c,g)=>c-g);let f=p[Math.floor(p.length/2)];l.set(d.id,f-Math.floor(r(d)/2))}let u=0;for(let d of a){let h=l.get(d.id),p=n==="y"?d.y:d.x,c=Math.max(h??p,u);n==="y"?d.y=c:d.x=c,u=c+r(d)+o}}}}function kt(e,t){let n=new Map;for(let u of e.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,h)=>d.hopIndex-h.hopIndex);let r=t.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<e.layers.length;u+=1){let d=e.layers[u],h=e.layers[u+1],p=0;for(let E of d)p=Math.max(p,o(E)+s(E));let f=Number.POSITIVE_INFINITY;for(let E of h)f=Math.min(f,o(E));let c=Number.isFinite(f)?f-1:p,g=Math.max(1,c-p+1),b=[];for(let E of d)for(let R of E.out)b.push(R);b.sort((E,R)=>{let k=i(e.nodes.get(E.fromId)),$=i(e.nodes.get(R.fromId));if(k!==$)return k-$;let G=i(e.nodes.get(E.toId)),D=i(e.nodes.get(R.toId));return G-D});let v=[],w=new Map;for(let E of b){let R=i(e.nodes.get(E.fromId)),k=i(e.nodes.get(E.toId)),$=Math.min(R,k),G=Math.max(R,k),D=-1;for(let P=0;P<v.length;P+=1){let F=v[P],z=!0;for(let U of F)if(U.lo<=G&&$<=U.hi){z=!1;break}if(z){F.push({lo:$,hi:G}),D=P;break}}D<0&&(v.push([{lo:$,hi:G}]),D=v.length-1),w.set(E,D)}let m=v.length,y=g>=Math.max(3,m+2),S=y?p+1:p,x=y?c-1:c,O=Math.max(1,x-S+1);for(let E of b){let R=w.get(E),k;if(m<=1)k=S+Math.floor(O/2);else{let $=(O-1)/(m-1);k=S+Math.floor(R*$)}a.set(E,Math.max(p,Math.min(c,k)))}}let l=[];for(let[,u]of n){let d=[];for(let p=0;p<u.length;p+=1){let f=u[p],c=e.nodes.get(f.fromId),g=e.nodes.get(f.toId),b=a.get(f),v=c.isVirtual?o(c):o(c)+s(c),w=g.isVirtual?o(g):o(g)-1,m=i(c),y=i(g);p===0&&ce(d,r,v,m),m!==y&&(ce(d,r,b,m),ce(d,r,b,y)),ce(d,r,w,y)}let h=u[0];l.push({from:h.chainFrom,to:h.chainTo,points:$t(d)})}return l}function ce(e,t,n,r){e.push(t?{x:n,y:r}:{x:r,y:n})}function $t(e){let t=[];for(let n of e){let r=t[t.length-1];(!r||r.x!==n.x||r.y!==n.y)&&t.push(n)}return t}function Tt(e){let t=0,n=0;for(let r of e.layers)for(let o of r)t=Math.max(t,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:t,height:n}}var Nt=24,At=4,Pt=1,Mt=3;function et(e,t){let n=Lt(t.direction),r=Math.max(3,t.maxLabelWidth??Nt),o=t.asciiCharset??"unicode",s=Object.keys(e.nodes).sort(),i=new Set(s),a=e.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,u=new Map;for(let f of s){let c=Ve(f,r);l.set(f,c),u.set(f,ue(c)+4)}let d=Qe({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>Mt,layerGap:At,nodeGap:Pt,direction:n}),h=Ue(d,{charset:o,labelOf:f=>l.get(f)??f}),p=t.logger;return p&&p(h),h}function Lt(e){if(e===void 0||e==="LR")return"LR";if(e==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(e)}`)}var N="::",B="__meta__",q=1;function tt(e,t){let n=Math.max(16,e.size*4),r=0;for(;e.size>0;){if(r++>=n){console.error(`[Graph "${t}".destroy] disposer drain exceeded cap (${n}); ${e.size} disposer(s) discarded`),e.clear();return}let o=e.values().next();if(o.done)return;let s=o.value;e.delete(s);try{s()}catch(i){console.error(`[Graph "${t}".destroy] disposer threw:`,i)}}}function It(e){let t=[];for(let n of Object.keys(e).sort()){let r=e[n].v;r!=null&&t.push(`${n} ${r.id} ${r.version}`)}return t.join(`
|
|
4
|
-
`)}function nt(e){if(e.version!==q)throw new Error(`unsupported snapshot version ${String(e.version)} (expected ${q})`);for(let t of["name","nodes","edges","subgraphs"])if(!(t in e))throw new Error(`snapshot missing required key "${t}"`);if(typeof e.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof e.nodes!="object"||e.nodes===null||Array.isArray(e.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(e.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(e.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function jt(e,t){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 p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,c]of o)if(!p.has(f)||!r(c,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let c=!1;for(let g of p)if(r(f,g)){c=!0;break}if(!c)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let c=0;c<p.length;c++)if(p[c]!==f[c])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let h=new Set(d);for(let p of u)if(!h.has(p)||!r(o[p],s[p]))return!1;return!0};return r(e,t)}function Ge(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ge);let t=e,n=Object.keys(t).sort(),r={};for(let o of n)r[o]=Ge(t[o]);return r}function Bt(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ft(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function zt(e){return e==="TD"?"down":e==="BT"?"up":e==="RL"?"left":"right"}function ot(e){let t=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;t.has(i)||(t.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(e.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of e.edges)r(o.from,o.to);return n}function it(e){if(e===void 0)return"LR";if(e==="TD"||e==="LR"||e==="BT"||e==="RL")return e;throw new Error(`invalid diagram direction ${String(e)}; expected one of: TD, LR, BT, RL`)}function Ht(e,t){let n=t.includeEdges??!0,r=t.includeSubgraphs??!0,{expand:o,...s}=e,i={...s,edges:n?e.edges:[],subgraphs:r?e.subgraphs:[]},a=JSON.stringify(Ge(i),null,t.indent??2);return t.logger?.(a),a}function Vt(e,t){let n=t.includeEdges??!0,r=t.includeSubgraphs??!0,o=[];o.push(`Graph ${e.name}`),o.push("Nodes:");for(let i of Object.keys(e.nodes).sort()){let a=e.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${fe(a.value)}`)}if(n){o.push("Edges:");for(let i of e.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of e.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
5
|
-
`);return t.logger?.(s),s}function at(e,t){let n=it(t.direction),r=Object.keys(e.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}["${Bt(i)}"]`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(` ${l} --> ${u}`)}return s.join(`
|
|
6
|
-
`)}function Kt(e,t){let n=at(e,t);return Wt(n)}function Wt(e,t){let n=t?.theme??"default",r=t?.autoSync??!0,s=JSON.stringify({code:e,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 qt(e,t){let n=it(t.direction),r=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${zt(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Ft(i)}"`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(`${l} -> ${u}`)}return s.join(`
|
|
7
|
-
`)}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function de(e){let t="^";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="*"){t+=".*";continue}if(r==="?"){t+=".";continue}if(r==="["){let o=e.indexOf("]",n+1);if(o<=n+1){t+="\\[";continue}let s=e.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),t+=`[${s}]`,n=o;continue}t+=Ut(r)}return t+="$",new RegExp(t)}var Jt={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"},Yt={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function fe(e){if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Xt(e){return e==="none"?Yt:e==="ansi"||e==null?Jt:{data:e.data??"",dirty:e.dirty??"",resolved:e.resolved??"",invalidate:e.invalidate??"",pause:e.pause??"",resume:e.resume??"",complete:e.complete??"",error:e.error??"",teardown:e.teardown??"",derived:e.derived??"",path:e.path??"",reset:e.reset??""}}function rt(e){if(e==null)return{};let t=e.detail;return t==="full"?{...e,structured:e.structured??!0,timeline:e.timeline??!0,causal:e.causal??!0,derived:e.derived??!0}:t==="minimal"?{...e,structured:e.structured??!0}:e.format==="stage-log"?{...e,structured:e.structured??!0,timeline:e.timeline??!0}:e}function Qt(e,t,n){for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${t}": ${n} "${e}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function De(e,t,n){if(e==="")throw new Error(`Graph "${t}": ${n} name must be non-empty`);if(e.includes(N))throw new Error(`Graph "${t}": ${n} "${e}" must not contain '${N}' (path separator)`);if(e===B)throw new Error(`Graph "${t}": ${n} name "${B}" is reserved for meta companion paths`);Qt(e,t,n)}function Zt(e,t){if(e==="")throw new Error(`Graph "${t}": resolve path must be non-empty`);let n=e.split(N);for(let r of n)if(r==="")throw new Error(`Graph "${t}": resolve path has empty segment`);return n}function en(e,t){let n=!1;for(let o of e)if(!t.isMetaPassthrough(o[0])){n=!0;break}return n?e.filter(o=>t.isMetaPassthrough(o[0])):e}function ut(e){for(let t of e._mounts.values())ut(t);for(let t of e._nodes.values())try{t.down([[V]],{internal:!0})}catch{}}var Ce=class e{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(t,n){if(t==="")throw new Error("Graph name must be non-empty");if(t.includes(N))throw new Error(`Graph name must not contain '${N}' (got "${t}")`);if(t===B)throw new Error(`Graph name "${B}" is reserved for meta companion paths`);this.name=t,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Oe,this._traceRing=new X(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(t=!0){let n=[],r=t?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=Me(t=>{let n=r=>{t.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(t){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(t)}add(t,n){let r=t.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(De(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(t);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,t),this._nodeToName.set(t,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:K()})),t}setVersioning(t){if(t!=null)for(let n of this._nodes.values())n instanceof L&&n._applyVersioning(t)}remove(t){De(t,this.name,"remove");let n=this._mounts.get(t);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${N}${B}${N}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(t),s.mounts.push(...n._collectSubgraphs(`${t}${N}`)),this._mounts.delete(t),n._parent=void 0,ut(n),this._emitTopology({kind:"removed",name:t,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(t);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${t}"`);this._nodes.delete(t),this._nodeToName.delete(r),r.down([[V]],{internal:!0});let o={kind:"node",nodes:[t],mounts:[]};return this._emitTopology({kind:"removed",name:t,nodeKind:"node",audit:o}),o}removeAll(t){let n=typeof t=="function"?t:(()=>{let s=de(t);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 t=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=t.length)return{value:void 0,done:!0};let o=t[r++];return{value:[o,n.get(o)],done:!1}}}}node(t){if(t==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(t.includes(N))return this.resolve(t);let n=this._nodes.get(t);if(!n)throw new Error(`Graph "${this.name}": unknown node "${t}"`);return n}get(t){return this.node(t).cache}set(t,n,r){let o=r?.internal===!0;this.node(t).down([[Z,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(t,n){let r=Symbol.iterator in t?t:Object.entries(t);Ae(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(t,n){let r=n?.internal===!0;this.node(t).down([[ee]],{actor:n?.actor,internal:r,delivery:"write"})}error(t,n,r){let o=r?.internal===!0;this.node(t).down([[ne,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(t,n){let r=n?.internal===!0;this.node(t).down([[te]],{actor:n?.actor,internal:r,delivery:"write"})}edges(t){let n=t?.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 L)for(let d of u._deps){let h=r.get(d.node);h!=null&&a.push([h,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 L)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(t,n){if(De(t,this.name,"mount"),this._nodes.has(t))throw new Error(`Graph "${this.name}": cannot mount at "${t}" \u2014 node with that name exists`);if(this._mounts.has(t))throw new Error(`Graph "${this.name}": mount "${t}" 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("${t}", \u2026) would create a mount cycle`);return this._mounts.set(t,n),n._parent=this,this._emitTopology({kind:"added",name:t,nodeKind:"mount"}),n}resolve(t){let n=Zt(t,this.name);return this._resolveFromSegments(n)}tryResolve(t){try{return this.resolve(t)}catch{return}}_resolveFromSegments(t){let n=t;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]===B)return this._resolveMetaChainFromNode(s,o,n.join(N));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(N)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(N))}_resolveMetaChainFromNode(t,n,r){let o=t,s=0,i=[...n];for(;s<i.length;){if(i[s]!==B)throw new Error(`Graph "${this.name}": expected ${B} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${B} 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(t,n){if(n?.internal!==!0){for(let o of t)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(t,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(t,n,r,o){for(let l of this._mounts.values())l._signalDeliver(t,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=en(t,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(t,i)}catch(d){if(d instanceof W)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(t,n,r,o,s){for(let i of Object.keys(t.meta).sort()){let a=t.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(l){if(l instanceof W)throw l;s.push(l)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(t){if(t?.reactive===!0)return this._describeReactive(t);let n=t?.actor,r=t?.filter,o=se(t?.detail,t?.fields),s=t?.format==="spec",i=s?se("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[x,O]of a)l.set(O,x);let u=[];{let x=a.map(([,R])=>R),O=new Set(l.values()),E=0;for(;x.length>0;){let R=x.shift();if(R instanceof L)for(let k of R._deps){let $=k.node;if(l.has($))continue;let G=$.name??"",D=G;if(!D||O.has(D))if(G){let P=2;for(;O.has(`${G}#${P}`);)P++;D=`${G}#${P}`}else for(D=`__internal__/${E++}`;O.has(D);)D=`__internal__/${E++}`;l.set($,D),O.add(D),u.push([D,$]),x.push($)}}}let d=[...a,...u],h={};for(let[x,O]of d){if(n!=null&&!O.allowsObserve(n))continue;let E=Se(O,i),R=O instanceof L?O._deps.map(D=>l.get(D.node)??D.node.name??""):[],{name:k,...$}=E,G={...$,deps:R};if(!s){let D=this._annotations.get(x);D!=null&&(G.annotation=D)}if(r!=null)if(typeof r=="function"){let D=r;if(!(D.length>=2?D(x,G):D(G)))continue}else{let D=!0;for(let[P,F]of Object.entries(r)){let z=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(z==="depsIncludes"){if(!G.deps.includes(String(F))){D=!1;break}continue}if(z==="metaHas"){if(!Object.hasOwn(G.meta??{},String(F))){D=!1;break}continue}if(G[z]!==F){D=!1;break}}if(!D)continue}h[x]=G}let p=new Set(Object.keys(h)),f=[];for(let[x,O]of d)if(O instanceof L)for(let E of O._deps){let R=l.get(E.node);R!=null&&f.push([R,x])}f.sort((x,O)=>x[0]<O[0]?-1:x[0]>O[0]?1:x[1]<O[1]?-1:x[1]>O[1]?1:0);let c=f.map(([x,O])=>({from:x,to:O}));(n!=null||r!=null)&&(c=c.filter(x=>p.has(x.from)&&p.has(x.to)));let g=this._collectSubgraphs(""),b=n!=null||r!=null?g.filter(x=>{let O=`${x}${N}`;return[...p].some(E=>E===x||E.startsWith(O))}):g,v=this,w=t,m={name:this.name,nodes:h,edges:c,subgraphs:b,expand(x){let O={...w,format:void 0};return Array.isArray(x)?(O.fields=x,O.detail=void 0):(O.detail=x,O.fields=void 0),v.describe(O)}},y=t??{},S=y.format;return S==="json"?Ht(m,y):S==="pretty"?Vt(m,y):S==="mermaid"?at(m,y):S==="mermaid-url"?Kt(m,y):S==="d2"?qt(m,y):S==="ascii"?et(m,y):m}_collectSubgraphs(t){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=t===""?r:`${t}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${N}`))}return n}resourceProfile(t){return He(this,t)}reachable(t,n,r={}){return r.withDetail===!0?st(this.describe(),t,n,{...r,withDetail:!0}):st(this.describe(),t,n,r)}explain(t,n,r){return r?.reactive===!0?this._explainReactive(t,n,r):this._explainStatic(t,n,r)}_explainStatic(t,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 Ie(o,t,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(t){let n={...t,reactive:!1},r=t.reactiveName??"describe",o=0,s=re(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=()=>{a||l||(a=!0,we(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),h=[],p=new WeakSet,f=b=>{if(p.has(b)||l)return;p.add(b);let v=b.topology.subscribe(w=>{for(let m of w){if(m[0]!==Z)continue;let y=m[1];if(u(),y.kind==="added"&&y.nodeKind==="mount"){let S=b._mounts.get(y.name);S!=null&&f(S)}}});h.push(v);for(let w of b._mounts.keys()){let m=b._mounts.get(w);m!=null&&f(m)}};f(this);let c;try{c=_e([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){d();for(let v of h)v();throw i.dispose(),b}let g=Ee(c);return{node:c,dispose(){l=!0,d();for(let b of h)b();h.length=0,i.dispose(),g()}}}_explainReactive(t,n,r){let o=0,s=re(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=i.onEvent(f=>{let c=f.type;c!=="data"&&c!=="error"&&c!=="complete"&&c!=="teardown"||a||l||(a=!0,we(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},h;try{h=_e([s],()=>this._explainStatic(t,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:t,to:n},equals:(f,c)=>f.found===c.found&&f.reason===c.reason&&f.steps.length===c.steps.length&&nn(f.steps,c.steps)})}catch(f){throw u(),i.dispose(),f}let p=Ee(h);return{node:h,dispose(){l=!0,u(),i.dispose(),p()}}}_pathsMatching(t){let n=de(t),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(t,n){for(let r of[...this._mounts.keys()].sort()){let o=t===""?r:`${t}${N}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=t===""?r:`${t}${N}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(t,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${t}${N}${B}${N}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(t,n){let r=typeof t=="string",s=rt(r?n:t),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=t,h=this.resolve(d);if(a!=null&&!h.allowsObserve(a))throw new W({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,h]],s,"one"):{subscribe(p){return h.subscribe(p)},up(p){try{h.up?.(p)}catch(f){if(f instanceof W)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let u=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let h=u.map(([p,f])=>f.subscribe(c=>{d(p,c)}));return()=>{for(let p of h)p()}},up:(d,h)=>{try{this.resolve(d).up?.(h)}catch(p){if(p instanceof W)return;throw p}}}}_buildStructuredObserver(t,n,r){let o=r==="one"?t[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,h)=>d[0]<h[0]?-1:d[0]>h[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(t,n,s)}_createObserveResult(t,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,h=d!=null&&d>0?new X(d):null,p=[],f=new Set,c={},g=new Set,b=0,v=0,w=0,m=0,y=0,S=0,x=!1,O=!1,E=0,R=new Map,k=new Map,$=new Map,G=_=>{h?h.push(_):p.push(_);for(let T of f)T(_)},D=()=>o?{timestamp_ns:K(),in_batch:Ne(),batch_id:E}:{},P=(_,T)=>{if(!(!u||!(_ instanceof L)))return _._setInspectorHook(I=>{if(I.kind==="dep_message")R.set(_,I.depIndex);else if(I.kind==="run"){let J=I.batchData.map((C,M)=>C!=null&&C.length>0?C.at(-1):I.prevData[M]);k.set(_,J);let j=I.batchData.map(C=>C!=null?[...C]:void 0);$.set(_,j),i&&G({type:"derived",path:T,dep_values:J,dep_batches:j,...D()})}})},F=_=>{let T=R.get(_),I=k.get(_);if(!s||I==null)return{};let j=(T!=null&&T>=0&&_ instanceof L?_._deps[T]:void 0)?.node,C=j?.v,M=$.get(_);return{trigger_dep_index:T,trigger_dep_name:j?.name,...C!=null?{trigger_version:{id:C.id,version:C.version}}:{},dep_values:[...I],...M!=null?{dep_batches:M}:{}}},z=[],U=[];for(let[_,T]of t){let I=P(T,_);I&&z.push(I),U.push(T.subscribe(J=>{E++;for(let j of J){let C=j[0],M=D();if(C===Z){c[_]=j[1];let me=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"data",path:_,data:j[1],actor:me,...M,...F(T)})}else if(a)C===be?b++:C===ye?v++:C===ee?w++:C===ve?m++:C===xe?y++:C===V?S++:C===te&&!g.has(_)?x=!0:C===ne&&(O=!0,g.add(_));else if(C===be)b++,G({type:"dirty",path:_,...M});else if(C===ye)v++,G({type:"resolved",path:_,...M,...F(T)});else if(C===ee)w++,G({type:"invalidate",path:_,...M});else if(C===ve)m++,G({type:"pause",path:_,lockId:j[1],...M});else if(C===xe)y++,G({type:"resume",path:_,lockId:j[1],...M});else if(C===te)g.has(_)||(x=!0),G({type:"complete",path:_,...M});else if(C===ne){O=!0,g.add(_);let me=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"error",path:_,data:j[1],actor:me,...M})}else C===V&&(S++,G({type:"teardown",path:_,...M}))}}))}let pe=!1,he=()=>{if(!pe){pe=!0;for(let _ of U)_();for(let _ of z)_();for(let _ of Q)_({value:void 0,done:!0});Q.length=0}},ge=[],Q=[];f.add(_=>{let T=Q.shift();T?T({value:_,done:!1}):ge.push(_)});let ke={get values(){return c},get dirtyCount(){return b},get resolvedCount(){return v},get invalidateCount(){return w},get pauseCount(){return m},get resumeCount(){return y},get teardownCount(){return S},get events(){return h?h.toArray():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return O},get completedWithoutErrors(){return x&&!O},onEvent(_){return f.add(_),()=>f.delete(_)},dispose:he,expand(_){he();let T={...n};return typeof _=="string"?T.detail=_:Object.assign(T,_),r(rt(T))},[Symbol.asyncIterator](){return{next(){return ge.length>0?Promise.resolve({value:ge.shift(),done:!1}):pe?Promise.resolve({value:void 0,done:!0}):new Promise(_=>Q.push(_))},return(){return he(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ke,n),ke}_attachFormatLogger(t,n){let r=n.format;if(r==null)return;let o=n.logger??(c=>console.log(c)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:c=>(s==null||s.has(c))&&(i==null||!i.has(c)),l=Xt(n.theme),u=r==="stage-log"?K():0,d=c=>c==null?"":n.stageLabels?.[c]??c,h=(c,g)=>c.length>g?`${c.slice(0,g-1)}\u2026`:c,p=c=>c.type==="data"||c.type==="error"?h(fe(c.data),120):"",f=c=>{if(r==="stage-log"){let O=(K()-u)/1e9,E=d(c.path).padEnd(9);if(c.type==="data"){let R=p(c);return`[${O.toFixed(3)}s] ${E} \u2190${R?` ${R}`:""}`}if(c.type==="error"){let R=p(c);return`[${O.toFixed(3)}s] ${E} \u2717${R?` ${R}`:""}`}return c.type==="complete"?`[${O.toFixed(3)}s] ${E} \u25A0 complete`:`[${O.toFixed(3)}s] ${E} ${c.type}`}if(r==="json")try{return JSON.stringify(c)}catch{return JSON.stringify({type:c.type,path:c.path,data:"[unserializable]"})}let g=l[c.type]??"",b=c.path?`${l.path}${c.path}${l.reset} `:"",v=c.type==="data"||c.type==="error",w=c.type==="pause"||c.type==="resume",m=v?` ${fe(c.data)}`:w?` ${fe(c.lockId)}`:"",y=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,S=y?.trigger_dep_name!=null?` <- ${y.trigger_dep_name}`:y?.trigger_dep_index!=null?` <- #${y.trigger_dep_index}`:"",x=c.in_batch?" [batch]":"";return`${b}${g}${c.type.toUpperCase()}${l.reset}${m}${S}${x}`};t.onEvent(c=>{a(c.type)&&o(f(c),c)})}addDisposer(t){return this._disposers.add(t),()=>{this._disposers.delete(t)}}destroy(){tt(this._disposers,this.name),this.signal([[V]],{internal:!0}),tt(this._storageDisposers,this.name);for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(t){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(t?.format==null)return i;if(t.format==="json-string")return JSON.stringify(i);if(t.format==="bytes"){if(t.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(t.codec);if(a==null)throw new Error(`snapshot: codec "${t.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return $e(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(t.format)}"`)}static decode(t,n){let r=n?.config??Oe,{codec:o,codecVersion:s,payload:i}=Te(t,r);return o.decode(i,s)}restore(t,n){if(nt(t),t.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${t.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>de(s)),o=n?.includeProducers===!0;for(let s of Object.keys(t.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=t.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(t,n){nt(t);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new e(t.name);if(r)return r(s),s.restore(t),s;for(let f of[...t.subgraphs].sort((c,g)=>{let b=c.split(N).length,v=g.split(N).length;return b!==v?b-v:c<g?-1:c>g?1:0})){let c=f.split(N),g=s;for(let b of c)g._mounts.has(b)||g.mount(b,new e(b)),g=g._mounts.get(b)}let i=o?Object.entries(o).map(([f,c])=>({re:de(f),factory:c})):[],a=f=>{for(let c of i)if(c.re.test(f))return c.factory},l=f=>{let c=f.split(N),g=c.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let b=s;for(let v of c){let w=b._mounts.get(v);if(!w)throw new Error(`unknown mount "${v}" in path "${f}"`);b=w}return[b,g]},u=Object.entries(t.nodes).filter(([f])=>!f.includes(`${N}${B}${N}`)).sort((f,c)=>f[0]<c[0]?-1:f[0]>c[0]?1:0),d=new Map(u),h=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,c]of[...d.entries()]){let g=c?.deps??[];if(!g.every(S=>h.has(S)))continue;let[b,v]=l(f),w={...c?.meta??{}},m=a(f),y;if(c?.type==="state")y=re(c.value,{meta:w});else{if(m==null)continue;y=m(v,{path:f,type:c.type,value:c.value,meta:w,deps:g,resolvedDeps:g.map(S=>h.get(S))})}b.add(y,{name:v}),h.set(f,y),d.delete(f),p=!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(t),s}toJSON(){return this.snapshot()}attachStorage(t,n={}){let r=t.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(t,n.onError);let o=(u,d)=>{if(u.disposed)return;let h=It(d.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let p=u.seq+1,f=Pe(),b=u.lastSnapshot==null||p%u.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:q}:{mode:"diff",diff:tn(u.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:q};if(u.tier.filter&&!u.tier.filter(this.name,b))return;let v;try{v=u.tier.save(this.name,b)}catch(w){n.onError?.(w,u.tier);return}if(v&&typeof v.then=="function"){let y=(u.savePending??Promise.resolve()).then(()=>v,()=>v).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h)},S=>{n.onError?.(S,u.tier)});u.savePending=y.finally(()=>{u.savePending===y&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h},s=(u,d)=>{try{o(u,d)}catch(h){n.onError?.(h,u.tier)}},i=(u,d)=>{if(!d.some(c=>{let g=this.config.messageTier(c[0]);return g>=3&&g<5}))return;if(n.filter){let c=this.tryResolve(u);if(c==null)return;let g=Se(c,se("standard"));if(!n.filter(u,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let c of r)c.disposed||(c.debounceMs===0?s(c,f()):(c.timer==null&&(c.timer=new Le),c.timer.start(c.debounceMs,()=>{c.disposed||s(c,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(h=>{let p=this.tryResolve(h);return p==null?()=>{}:p.subscribe(f=>i(h,f))});a=()=>{for(let h of d)h()}}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(t,n){for(let r of t){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===q&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(t,n,r){for(let o of n){let s;try{s=await o.load(t)}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===q&&i.nodes!=null?i:void 0;if(a!=null)try{return e.fromSnapshot(a,r)}catch(l){r?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${t}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(t,n,r){if(t!=null&&n!=null){if(this.tryResolve(t)==null)return;if(this._annotations.set(t,n),this.config.inspectorEnabled){let o={path:t,annotation:n,timestamp_ns:K(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return t!=null?this.config.inspectorEnabled?this._annotations.get(t):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(t){return this._annotations.get(t)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(t){let n=this._traceRing.toArray().filter(o=>!t(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(t,n){let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(w=>!r.has(w)).sort(),i=[...r].filter(w=>!o.has(w)).sort(),a=[],l=[];for(let w of r){if(!o.has(w))continue;let m=t.nodes[w],y=n.nodes[w],S=m.v,x=y.v;S!=null&&x!=null&&S.id===x.id&&S.version!==x.version&&l.push({path:w,id:S.id,from:S.version,to:x.version});let O=S!=null&&x!=null&&S.id===x.id&&S.version===x.version;for(let E of["type","status","sentinel"]){let R=m[E],k=y[E];R!==k&&a.push({path:w,field:E,from:R,to:k})}if(!O)for(let E of["value","meta"]){let R=m[E],k=y[E];jt(R,k)||a.push({path:w,field:E,from:R,to:k})}}let u=w=>`${w.from} ${w.to}`,d=new Set(t.edges.map(u)),h=new Set(n.edges.map(u)),p=n.edges.filter(w=>!d.has(u(w))),f=t.edges.filter(w=>!h.has(u(w))),c=new Set(t.subgraphs),g=new Set(n.subgraphs),b=[...g].filter(w=>!c.has(w)).sort(),v=[...c].filter(w=>!g.has(w)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:p,edgesRemoved:f,subgraphsAdded:b,subgraphsRemoved:v}}};function tn(e,t){let n=Ce.diff(e,t),r={};for(let o of n.nodesAdded){let s=t.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function st(e,t,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!t)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[m,y]of Object.entries(e.nodes)){if(!m)continue;d.add(m);let S=y.deps??[];i.set(m,S);for(let x of S)x&&(d.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(m))}for(let m of e.edges){if(m==null||typeof m!="object")continue;let y=typeof m.from=="string"?m.from:"",S=typeof m.to=="string"?m.to:"";!y||!S||(d.add(y),d.add(S),u.has(y)||u.set(y,new Set),u.get(y).add(S),l.has(S)||l.set(S,new Set),l.get(S).add(y))}if(!d.has(t))return r.withDetail?o:[];let h=r.both===!0,p=m=>{if(h){let O=i.get(m)??[],E=l.get(m),R=a.get(m),k=u.get(m),$=[...O];return E&&$.push(...E),R&&$.push(...R),k&&$.push(...k),$}if(n==="upstream"){let O=i.get(m)??[],E=l.get(m);return E?[...O,...E]:O}let y=a.get(m),S=u.get(m),x=y?[...y]:[];return S&&x.push(...S),x},f=new Set([t]),c=new Map,g=[{path:t,depth:0}],b=0,v=!1;for(;b<g.length;){let m=g[b++];if(s!=null&&m.depth>=s){p(m.path).length>0&&(v=!0);continue}for(let y of p(m.path))!y||f.has(y)||(f.add(y),c.set(y,m.depth+1),g.push({path:y,depth:m.depth+1}))}let w=[...c.keys()].sort((m,y)=>m<y?-1:m>y?1:0);return r.withDetail?{paths:w,depths:c,truncated:v}:w}function nn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],o=t[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}export{X as a,ue as b,Ie as c,A as d,ft as e,ze as f,He as g,B as h,q as i,Wt as j,Ce as k,tn as l,st as m};
|